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.ArrayList;
31  import java.util.List;
32  
33  import org.apache.http.FormattedHeader;
34  import org.apache.http.Header;
35  import org.apache.http.HeaderElement;
36  import org.apache.http.annotation.NotThreadSafe;
37  import org.apache.http.client.utils.DateUtils;
38  import org.apache.http.cookie.ClientCookie;
39  import org.apache.http.cookie.Cookie;
40  import org.apache.http.cookie.CookieOrigin;
41  import org.apache.http.cookie.MalformedCookieException;
42  import org.apache.http.cookie.SM;
43  import org.apache.http.message.BasicHeaderElement;
44  import org.apache.http.message.BasicHeaderValueFormatter;
45  import org.apache.http.message.BufferedHeader;
46  import org.apache.http.message.ParserCursor;
47  import org.apache.http.util.Args;
48  import org.apache.http.util.CharArrayBuffer;
49  
50  
51  /**
52   * Cookie specification that strives to closely mimic (mis)behavior of
53   * common web browser applications such as Microsoft Internet Explorer
54   * and Mozilla FireFox.
55   *
56   *
57   * @since 4.0
58   */
59  @NotThreadSafe // superclass is @NotThreadSafe
60  public class BrowserCompatSpec extends CookieSpecBase {
61  
62      private static final String[] DEFAULT_DATE_PATTERNS = new String[] {
63          DateUtils.PATTERN_RFC1123,
64          DateUtils.PATTERN_RFC1036,
65          DateUtils.PATTERN_ASCTIME,
66          "EEE, dd-MMM-yyyy HH:mm:ss z",
67          "EEE, dd-MMM-yyyy HH-mm-ss z",
68          "EEE, dd MMM yy HH:mm:ss z",
69          "EEE dd-MMM-yyyy HH:mm:ss z",
70          "EEE dd MMM yyyy HH:mm:ss z",
71          "EEE dd-MMM-yyyy HH-mm-ss z",
72          "EEE dd-MMM-yy HH:mm:ss z",
73          "EEE dd MMM yy HH:mm:ss z",
74          "EEE,dd-MMM-yy HH:mm:ss z",
75          "EEE,dd-MMM-yyyy HH:mm:ss z",
76          "EEE, dd-MM-yyyy HH:mm:ss z",
77      };
78  
79      private final String[] datepatterns;
80  
81      /** Default constructor */
82      public BrowserCompatSpec(final String[] datepatterns) {
83          super();
84          if (datepatterns != null) {
85              this.datepatterns = datepatterns.clone();
86          } else {
87              this.datepatterns = DEFAULT_DATE_PATTERNS;
88          }
89          registerAttribHandler(ClientCookie.PATH_ATTR, new BasicPathHandler());
90          registerAttribHandler(ClientCookie.DOMAIN_ATTR, new BasicDomainHandler());
91          registerAttribHandler(ClientCookie.MAX_AGE_ATTR, new BasicMaxAgeHandler());
92          registerAttribHandler(ClientCookie.SECURE_ATTR, new BasicSecureHandler());
93          registerAttribHandler(ClientCookie.COMMENT_ATTR, new BasicCommentHandler());
94          registerAttribHandler(ClientCookie.EXPIRES_ATTR, new BasicExpiresHandler(
95                  this.datepatterns));
96          registerAttribHandler(ClientCookie.VERSION_ATTR, new BrowserCompatVersionAttributeHandler());
97      }
98  
99      /** Default constructor */
100     public BrowserCompatSpec() {
101         this(null);
102     }
103 
104     public List<Cookie> parse(final Header header, final CookieOrigin origin)
105             throws MalformedCookieException {
106         Args.notNull(header, "Header");
107         Args.notNull(origin, "Cookie origin");
108         final String headername = header.getName();
109         if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) {
110             throw new MalformedCookieException("Unrecognized cookie header '"
111                     + header.toString() + "'");
112         }
113         HeaderElement[] helems = header.getElements();
114         boolean versioned = false;
115         boolean netscape = false;
116         for (final HeaderElement helem: helems) {
117             if (helem.getParameterByName("version") != null) {
118                 versioned = true;
119             }
120             if (helem.getParameterByName("expires") != null) {
121                netscape = true;
122             }
123         }
124         if (netscape || !versioned) {
125             // Need to parse the header again, because Netscape style cookies do not correctly
126             // support multiple header elements (comma cannot be treated as an element separator)
127             final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
128             CharArrayBuffer buffer;
129             ParserCursor cursor;
130             if (header instanceof FormattedHeader) {
131                 buffer = ((FormattedHeader) header).getBuffer();
132                 cursor = new ParserCursor(
133                         ((FormattedHeader) header).getValuePos(),
134                         buffer.length());
135             } else {
136                 final String s = header.getValue();
137                 if (s == null) {
138                     throw new MalformedCookieException("Header value is null");
139                 }
140                 buffer = new CharArrayBuffer(s.length());
141                 buffer.append(s);
142                 cursor = new ParserCursor(0, buffer.length());
143             }
144             helems = new HeaderElement[] { parser.parseHeader(buffer, cursor) };
145         }
146         return parse(helems, origin);
147     }
148 
149     public List<Header> formatCookies(final List<Cookie> cookies) {
150         Args.notEmpty(cookies, "List of cookies");
151         final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
152         buffer.append(SM.COOKIE);
153         buffer.append(": ");
154         for (int i = 0; i < cookies.size(); i++) {
155             final Cookie cookie = cookies.get(i);
156             if (i > 0) {
157                 buffer.append("; ");
158             }
159             final String cookieName = cookie.getName();
160             final String cookieValue = cookie.getValue();
161             if (cookie.getVersion() > 0 &&
162                     !(cookieValue.startsWith("\"") && cookieValue.endsWith("\""))) {
163                 BasicHeaderValueFormatter.INSTANCE.formatHeaderElement(
164                         buffer,
165                         new BasicHeaderElement(cookieName, cookieValue),
166                         false);
167             } else {
168                 // Netscape style cookies do not support quoted values
169                 buffer.append(cookieName);
170                 buffer.append("=");
171                 if (cookieValue != null) {
172                     buffer.append(cookieValue);
173                 }
174             }
175         }
176         final List<Header> headers = new ArrayList<Header>(1);
177         headers.add(new BufferedHeader(buffer));
178         return headers;
179     }
180 
181     public int getVersion() {
182         return 0;
183     }
184 
185     public Header getVersionHeader() {
186         return null;
187     }
188 
189     @Override
190     public String toString() {
191         return "compatibility";
192     }
193 
194 }