View Javadoc

1   /*
2    * ====================================================================
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *   http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing,
14   * software distributed under the License is distributed on an
15   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16   * KIND, either express or implied.  See the License for the
17   * specific language governing permissions and limitations
18   * under the License.
19   * ====================================================================
20   *
21   * This software consists of voluntary contributions made by many
22   * individuals on behalf of the Apache Software Foundation.  For more
23   * information on the Apache Software Foundation, please see
24   * <http://www.apache.org/>.
25   *
26   */
27  
28  package org.apache.http.impl.cookie;
29  
30  import java.util.StringTokenizer;
31  
32  import org.apache.http.annotation.Immutable;
33  import org.apache.http.cookie.ClientCookie;
34  import org.apache.http.cookie.Cookie;
35  import org.apache.http.cookie.CookieAttributeHandler;
36  import org.apache.http.cookie.CookieOrigin;
37  import org.apache.http.cookie.CookieRestrictionViolationException;
38  import org.apache.http.cookie.MalformedCookieException;
39  import org.apache.http.cookie.SetCookie;
40  import org.apache.http.cookie.SetCookie2;
41  import org.apache.http.util.Args;
42  
43  /**
44   * <tt>"Port"</tt> cookie attribute handler for RFC 2965 cookie spec.
45   *
46   * @since 4.0
47   */
48  @Immutable
49  public class RFC2965PortAttributeHandler implements CookieAttributeHandler {
50  
51      public RFC2965PortAttributeHandler() {
52          super();
53      }
54  
55      /**
56       * Parses the given Port attribute value (e.g. "8000,8001,8002")
57       * into an array of ports.
58       *
59       * @param portValue port attribute value
60       * @return parsed array of ports
61       * @throws MalformedCookieException if there is a problem in
62       *          parsing due to invalid portValue.
63       */
64      private static int[] parsePortAttribute(final String portValue)
65              throws MalformedCookieException {
66          final StringTokenizer st = new StringTokenizer(portValue, ",");
67          final int[] ports = new int[st.countTokens()];
68          try {
69              int i = 0;
70              while(st.hasMoreTokens()) {
71                  ports[i] = Integer.parseInt(st.nextToken().trim());
72                  if (ports[i] < 0) {
73                    throw new MalformedCookieException ("Invalid Port attribute.");
74                  }
75                  ++i;
76              }
77          } catch (final NumberFormatException e) {
78              throw new MalformedCookieException ("Invalid Port "
79                                                  + "attribute: " + e.getMessage());
80          }
81          return ports;
82      }
83  
84      /**
85       * Returns <tt>true</tt> if the given port exists in the given
86       * ports list.
87       *
88       * @param port port of host where cookie was received from or being sent to.
89       * @param ports port list
90       * @return true returns <tt>true</tt> if the given port exists in
91       *         the given ports list; <tt>false</tt> otherwise.
92       */
93      private static boolean portMatch(final int port, final int[] ports) {
94          boolean portInList = false;
95          for (final int port2 : ports) {
96              if (port == port2) {
97                  portInList = true;
98                  break;
99              }
100         }
101         return portInList;
102     }
103 
104     /**
105      * Parse cookie port attribute.
106      */
107     public void parse(final SetCookie cookie, final String portValue)
108             throws MalformedCookieException {
109         Args.notNull(cookie, "Cookie");
110         if (cookie instanceof SetCookie2) {
111             final SetCookie2 cookie2 = (SetCookie2) cookie;
112             if (portValue != null && portValue.trim().length() > 0) {
113                 final int[] ports = parsePortAttribute(portValue);
114                 cookie2.setPorts(ports);
115             }
116         }
117     }
118 
119     /**
120      * Validate cookie port attribute. If the Port attribute was specified
121      * in header, the request port must be in cookie's port list.
122      */
123     public void validate(final Cookie cookie, final CookieOrigin origin)
124             throws MalformedCookieException {
125         Args.notNull(cookie, "Cookie");
126         Args.notNull(origin, "Cookie origin");
127         final int port = origin.getPort();
128         if (cookie instanceof ClientCookie
129                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
130             if (!portMatch(port, cookie.getPorts())) {
131                 throw new CookieRestrictionViolationException(
132                         "Port attribute violates RFC 2965: "
133                         + "Request port not found in cookie's port list.");
134             }
135         }
136     }
137 
138     /**
139      * Match cookie port attribute. If the Port attribute is not specified
140      * in header, the cookie can be sent to any port. Otherwise, the request port
141      * must be in the cookie's port list.
142      */
143     public boolean match(final Cookie cookie, final CookieOrigin origin) {
144         Args.notNull(cookie, "Cookie");
145         Args.notNull(origin, "Cookie origin");
146         final int port = origin.getPort();
147         if (cookie instanceof ClientCookie
148                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
149             if (cookie.getPorts() == null) {
150                 // Invalid cookie state: port not specified
151                 return false;
152             }
153             if (!portMatch(port, cookie.getPorts())) {
154                 return false;
155             }
156         }
157         return true;
158     }
159 
160 }