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  package org.apache.http.impl.cookie;
28  
29  import java.util.ArrayList;
30  import java.util.HashMap;
31  import java.util.List;
32  import java.util.Locale;
33  import java.util.Map;
34  
35  import org.apache.http.Header;
36  import org.apache.http.HeaderElement;
37  import org.apache.http.NameValuePair;
38  import org.apache.http.annotation.NotThreadSafe;
39  import org.apache.http.cookie.ClientCookie;
40  import org.apache.http.cookie.Cookie;
41  import org.apache.http.cookie.CookieAttributeHandler;
42  import org.apache.http.cookie.CookieOrigin;
43  import org.apache.http.cookie.MalformedCookieException;
44  import org.apache.http.cookie.SM;
45  import org.apache.http.message.BufferedHeader;
46  import org.apache.http.util.Args;
47  import org.apache.http.util.CharArrayBuffer;
48  
49  /**
50   * RFC 2965 compliant {@link org.apache.http.cookie.CookieSpec} implementation.
51   *
52   * @since 4.0
53   */
54  @NotThreadSafe // superclass is @NotThreadSafe
55  public class RFC2965Spec extends RFC2109Spec {
56  
57      /**
58       * Default constructor
59       *
60       */
61      public RFC2965Spec() {
62          this(null, false);
63      }
64  
65      public RFC2965Spec(final String[] datepatterns, final boolean oneHeader) {
66          super(datepatterns, oneHeader);
67          registerAttribHandler(ClientCookie.DOMAIN_ATTR, new RFC2965DomainAttributeHandler());
68          registerAttribHandler(ClientCookie.PORT_ATTR, new RFC2965PortAttributeHandler());
69          registerAttribHandler(ClientCookie.COMMENTURL_ATTR, new RFC2965CommentUrlAttributeHandler());
70          registerAttribHandler(ClientCookie.DISCARD_ATTR, new RFC2965DiscardAttributeHandler());
71          registerAttribHandler(ClientCookie.VERSION_ATTR, new RFC2965VersionAttributeHandler());
72      }
73  
74      @Override
75      public List<Cookie> parse(
76              final Header header,
77              final CookieOrigin origin) throws MalformedCookieException {
78          Args.notNull(header, "Header");
79          Args.notNull(origin, "Cookie origin");
80          if (!header.getName().equalsIgnoreCase(SM.SET_COOKIE2)) {
81              throw new MalformedCookieException("Unrecognized cookie header '"
82                      + header.toString() + "'");
83          }
84          final HeaderElement[] elems = header.getElements();
85          return createCookies(elems, adjustEffectiveHost(origin));
86      }
87  
88      @Override
89      protected List<Cookie> parse(
90              final HeaderElement[] elems,
91              final CookieOrigin origin) throws MalformedCookieException {
92          return createCookies(elems, adjustEffectiveHost(origin));
93      }
94  
95      private List<Cookie> createCookies(
96              final HeaderElement[] elems,
97              final CookieOrigin origin) throws MalformedCookieException {
98          final List<Cookie> cookies = new ArrayList<Cookie>(elems.length);
99          for (final HeaderElement headerelement : elems) {
100             final String name = headerelement.getName();
101             final String value = headerelement.getValue();
102             if (name == null || name.length() == 0) {
103                 throw new MalformedCookieException("Cookie name may not be empty");
104             }
105 
106             final BasicClientCookie2 cookie = new BasicClientCookie2(name, value);
107             cookie.setPath(getDefaultPath(origin));
108             cookie.setDomain(getDefaultDomain(origin));
109             cookie.setPorts(new int [] { origin.getPort() });
110             // cycle through the parameters
111             final NameValuePair[] attribs = headerelement.getParameters();
112 
113             // Eliminate duplicate attributes. The first occurrence takes precedence
114             // See RFC2965: 3.2  Origin Server Role
115             final Map<String, NameValuePair> attribmap =
116                     new HashMap<String, NameValuePair>(attribs.length);
117             for (int j = attribs.length - 1; j >= 0; j--) {
118                 final NameValuePair param = attribs[j];
119                 attribmap.put(param.getName().toLowerCase(Locale.ENGLISH), param);
120             }
121             for (final Map.Entry<String, NameValuePair> entry : attribmap.entrySet()) {
122                 final NameValuePair attrib = entry.getValue();
123                 final String s = attrib.getName().toLowerCase(Locale.ENGLISH);
124 
125                 cookie.setAttribute(s, attrib.getValue());
126 
127                 final CookieAttributeHandler handler = findAttribHandler(s);
128                 if (handler != null) {
129                     handler.parse(cookie, attrib.getValue());
130                 }
131             }
132             cookies.add(cookie);
133         }
134         return cookies;
135     }
136 
137     @Override
138     public void validate(
139             final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
140         Args.notNull(cookie, "Cookie");
141         Args.notNull(origin, "Cookie origin");
142         super.validate(cookie, adjustEffectiveHost(origin));
143     }
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         return super.match(cookie, adjustEffectiveHost(origin));
150     }
151 
152     /**
153      * Adds valid Port attribute value, e.g. "8000,8001,8002"
154      */
155     @Override
156     protected void formatCookieAsVer(final CharArrayBuffer buffer,
157             final Cookie cookie, final int version) {
158         super.formatCookieAsVer(buffer, cookie, version);
159         // format port attribute
160         if (cookie instanceof ClientCookie) {
161             // Test if the port attribute as set by the origin server is not blank
162             final String s = ((ClientCookie) cookie).getAttribute(ClientCookie.PORT_ATTR);
163             if (s != null) {
164                 buffer.append("; $Port");
165                 buffer.append("=\"");
166                 if (s.trim().length() > 0) {
167                     final int[] ports = cookie.getPorts();
168                     if (ports != null) {
169                         final int len = ports.length;
170                         for (int i = 0; i < len; i++) {
171                             if (i > 0) {
172                                 buffer.append(",");
173                             }
174                             buffer.append(Integer.toString(ports[i]));
175                         }
176                     }
177                 }
178                 buffer.append("\"");
179             }
180         }
181     }
182 
183     /**
184      * Set 'effective host name' as defined in RFC 2965.
185      * <p>
186      * If a host name contains no dots, the effective host name is
187      * that name with the string .local appended to it.  Otherwise
188      * the effective host name is the same as the host name.  Note
189      * that all effective host names contain at least one dot.
190      *
191      * @param origin origin where cookie is received from or being sent to.
192      */
193     private static CookieOrigin adjustEffectiveHost(final CookieOrigin origin) {
194         String host = origin.getHost();
195 
196         // Test if the host name appears to be a fully qualified DNS name,
197         // IPv4 address or IPv6 address
198         boolean isLocalHost = true;
199         for (int i = 0; i < host.length(); i++) {
200             final char ch = host.charAt(i);
201             if (ch == '.' || ch == ':') {
202                 isLocalHost = false;
203                 break;
204             }
205         }
206         if (isLocalHost) {
207             host += ".local";
208             return new CookieOrigin(
209                     host,
210                     origin.getPort(),
211                     origin.getPath(),
212                     origin.isSecure());
213         } else {
214             return origin;
215         }
216     }
217 
218     @Override
219     public int getVersion() {
220         return 1;
221     }
222 
223     @Override
224     public Header getVersionHeader() {
225         final CharArrayBuffer buffer = new CharArrayBuffer(40);
226         buffer.append(SM.COOKIE2);
227         buffer.append(": ");
228         buffer.append("$Version=");
229         buffer.append(Integer.toString(getVersion()));
230         return new BufferedHeader(buffer);
231     }
232 
233     @Override
234     public String toString() {
235         return "rfc2965";
236     }
237 
238 }
239