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.Collections;
32  import java.util.List;
33  import java.util.Locale;
34  
35  import org.apache.http.FormattedHeader;
36  import org.apache.http.Header;
37  import org.apache.http.HeaderElement;
38  import org.apache.http.NameValuePair;
39  import org.apache.http.annotation.ThreadSafe;
40  import org.apache.http.client.utils.DateUtils;
41  import org.apache.http.cookie.Cookie;
42  import org.apache.http.cookie.CookieAttributeHandler;
43  import org.apache.http.cookie.CookieOrigin;
44  import org.apache.http.cookie.MalformedCookieException;
45  import org.apache.http.cookie.SM;
46  import org.apache.http.message.BasicHeaderElement;
47  import org.apache.http.message.BasicHeaderValueFormatter;
48  import org.apache.http.message.BufferedHeader;
49  import org.apache.http.message.ParserCursor;
50  import org.apache.http.util.Args;
51  import org.apache.http.util.CharArrayBuffer;
52  
53  
54  /**
55   * Cookie specification that strives to closely mimic (mis)behavior of
56   * common web browser applications such as Microsoft Internet Explorer
57   * and Mozilla FireFox.
58   *
59   * @deprecated (4.4) use {@link org.apache.http.impl.cookie.DefaultCookieSpec}.
60   *
61   * @since 4.0
62   */
63  @Deprecated
64  @ThreadSafe
65  public class BrowserCompatSpec extends CookieSpecBase {
66  
67  
68      private static final String[] DEFAULT_DATE_PATTERNS = new String[] {
69          DateUtils.PATTERN_RFC1123,
70          DateUtils.PATTERN_RFC1036,
71          DateUtils.PATTERN_ASCTIME,
72          "EEE, dd-MMM-yyyy HH:mm:ss z",
73          "EEE, dd-MMM-yyyy 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 MMM yyyy HH:mm:ss z",
77          "EEE dd-MMM-yyyy HH-mm-ss z",
78          "EEE dd-MMM-yy HH:mm:ss z",
79          "EEE dd MMM yy HH:mm:ss z",
80          "EEE,dd-MMM-yy HH:mm:ss z",
81          "EEE,dd-MMM-yyyy HH:mm:ss z",
82          "EEE, dd-MM-yyyy HH:mm:ss z",
83      };
84  
85      /** Default constructor */
86      public BrowserCompatSpec(final String[] datepatterns, final BrowserCompatSpecFactory.SecurityLevel securityLevel) {
87          super(new BrowserCompatVersionAttributeHandler(),
88                  new BasicDomainHandler(),
89                  securityLevel == BrowserCompatSpecFactory.SecurityLevel.SECURITYLEVEL_IE_MEDIUM ?
90                          new BasicPathHandler() {
91                              @Override
92                              public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException {
93                                  // No validation
94                              }
95                          } : new BasicPathHandler(),
96                  new BasicMaxAgeHandler(),
97                  new BasicSecureHandler(),
98                  new BasicCommentHandler(),
99                  new BasicExpiresHandler(datepatterns != null ? datepatterns.clone() : DEFAULT_DATE_PATTERNS));
100     }
101 
102     /** Default constructor */
103     public BrowserCompatSpec(final String[] datepatterns) {
104         this(datepatterns, BrowserCompatSpecFactory.SecurityLevel.SECURITYLEVEL_DEFAULT);
105     }
106 
107     /** Default constructor */
108     public BrowserCompatSpec() {
109         this(null, BrowserCompatSpecFactory.SecurityLevel.SECURITYLEVEL_DEFAULT);
110     }
111 
112     @Override
113     public List<Cookie> parse(final Header header, final CookieOrigin origin)
114             throws MalformedCookieException {
115         Args.notNull(header, "Header");
116         Args.notNull(origin, "Cookie origin");
117         final String headername = header.getName();
118         if (!headername.equalsIgnoreCase(SM.SET_COOKIE)) {
119             throw new MalformedCookieException("Unrecognized cookie header '"
120                     + header.toString() + "'");
121         }
122         final HeaderElement[] helems = header.getElements();
123         boolean versioned = false;
124         boolean netscape = false;
125         for (final HeaderElement helem: helems) {
126             if (helem.getParameterByName("version") != null) {
127                 versioned = true;
128             }
129             if (helem.getParameterByName("expires") != null) {
130                netscape = true;
131             }
132         }
133         if (netscape || !versioned) {
134             // Need to parse the header again, because Netscape style cookies do not correctly
135             // support multiple header elements (comma cannot be treated as an element separator)
136             final NetscapeDraftHeaderParser parser = NetscapeDraftHeaderParser.DEFAULT;
137             final CharArrayBuffer buffer;
138             final ParserCursor cursor;
139             if (header instanceof FormattedHeader) {
140                 buffer = ((FormattedHeader) header).getBuffer();
141                 cursor = new ParserCursor(
142                         ((FormattedHeader) header).getValuePos(),
143                         buffer.length());
144             } else {
145                 final String s = header.getValue();
146                 if (s == null) {
147                     throw new MalformedCookieException("Header value is null");
148                 }
149                 buffer = new CharArrayBuffer(s.length());
150                 buffer.append(s);
151                 cursor = new ParserCursor(0, buffer.length());
152             }
153             final HeaderElement elem = parser.parseHeader(buffer, cursor);
154             final String name = elem.getName();
155             final String value = elem.getValue();
156             if (name == null || name.isEmpty()) {
157                 throw new MalformedCookieException("Cookie name may not be empty");
158             }
159             final BasicClientCookie cookie = new BasicClientCookie(name, value);
160             cookie.setPath(getDefaultPath(origin));
161             cookie.setDomain(getDefaultDomain(origin));
162 
163             // cycle through the parameters
164             final NameValuePair[] attribs = elem.getParameters();
165             for (int j = attribs.length - 1; j >= 0; j--) {
166                 final NameValuePair attrib = attribs[j];
167                 final String s = attrib.getName().toLowerCase(Locale.ROOT);
168                 cookie.setAttribute(s, attrib.getValue());
169                 final CookieAttributeHandler handler = findAttribHandler(s);
170                 if (handler != null) {
171                     handler.parse(cookie, attrib.getValue());
172                 }
173             }
174             // Override version for Netscape style cookies
175             if (netscape) {
176                 cookie.setVersion(0);
177             }
178             return Collections.<Cookie>singletonList(cookie);
179         } else {
180             return parse(helems, origin);
181         }
182     }
183 
184     private static boolean isQuoteEnclosed(final String s) {
185         return s != null && s.startsWith("\"") && s.endsWith("\"");
186     }
187 
188     @Override
189     public List<Header> formatCookies(final List<Cookie> cookies) {
190         Args.notEmpty(cookies, "List of cookies");
191         final CharArrayBuffer buffer = new CharArrayBuffer(20 * cookies.size());
192         buffer.append(SM.COOKIE);
193         buffer.append(": ");
194         for (int i = 0; i < cookies.size(); i++) {
195             final Cookie cookie = cookies.get(i);
196             if (i > 0) {
197                 buffer.append("; ");
198             }
199             final String cookieName = cookie.getName();
200             final String cookieValue = cookie.getValue();
201             if (cookie.getVersion() > 0 && !isQuoteEnclosed(cookieValue)) {
202                 BasicHeaderValueFormatter.INSTANCE.formatHeaderElement(
203                         buffer,
204                         new BasicHeaderElement(cookieName, cookieValue),
205                         false);
206             } else {
207                 // Netscape style cookies do not support quoted values
208                 buffer.append(cookieName);
209                 buffer.append("=");
210                 if (cookieValue != null) {
211                     buffer.append(cookieValue);
212                 }
213             }
214         }
215         final List<Header> headers = new ArrayList<Header>(1);
216         headers.add(new BufferedHeader(buffer));
217         return headers;
218     }
219 
220     @Override
221     public int getVersion() {
222         return 0;
223     }
224 
225     @Override
226     public Header getVersionHeader() {
227         return null;
228     }
229 
230     @Override
231     public String toString() {
232         return "compatibility";
233     }
234 
235 }