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   * {@code "Port"} 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 {@code true} 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 {@code true} if the given port exists in
91       *         the given ports list; {@code false} 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     @Override
108     public void parse(final SetCookie cookie, final String portValue)
109             throws MalformedCookieException {
110         Args.notNull(cookie, "Cookie");
111         if (cookie instanceof SetCookie2) {
112             final SetCookie2 cookie2 = (SetCookie2) cookie;
113             if (portValue != null && !portValue.trim().isEmpty()) {
114                 final int[] ports = parsePortAttribute(portValue);
115                 cookie2.setPorts(ports);
116             }
117         }
118     }
119 
120     /**
121      * Validate cookie port attribute. If the Port attribute was specified
122      * in header, the request port must be in cookie's port list.
123      */
124     @Override
125     public void validate(final Cookie cookie, final CookieOrigin origin)
126             throws MalformedCookieException {
127         Args.notNull(cookie, "Cookie");
128         Args.notNull(origin, "Cookie origin");
129         final int port = origin.getPort();
130         if (cookie instanceof ClientCookie
131                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
132             if (!portMatch(port, cookie.getPorts())) {
133                 throw new CookieRestrictionViolationException(
134                         "Port attribute violates RFC 2965: "
135                         + "Request port not found in cookie's port list.");
136             }
137         }
138     }
139 
140     /**
141      * Match cookie port attribute. If the Port attribute is not specified
142      * in header, the cookie can be sent to any port. Otherwise, the request port
143      * must be in the cookie's port list.
144      */
145     @Override
146     public boolean match(final Cookie cookie, final CookieOrigin origin) {
147         Args.notNull(cookie, "Cookie");
148         Args.notNull(origin, "Cookie origin");
149         final int port = origin.getPort();
150         if (cookie instanceof ClientCookie
151                 && ((ClientCookie) cookie).containsAttribute(ClientCookie.PORT_ATTR)) {
152             if (cookie.getPorts() == null) {
153                 // Invalid cookie state: port not specified
154                 return false;
155             }
156             if (!portMatch(port, cookie.getPorts())) {
157                 return false;
158             }
159         }
160         return true;
161     }
162 
163 }