1 /*
2  * Copyright (C) 2014 The Android Open Source Project
3  * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
4  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5  *
6  * This code is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License version 2 only, as
8  * published by the Free Software Foundation.  Oracle designates this
9  * particular file as subject to the "Classpath" exception as provided
10  * by Oracle in the LICENSE file that accompanied this code.
11  *
12  * This code is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15  * version 2 for more details (a copy is included in the LICENSE file that
16  * accompanied this code).
17  *
18  * You should have received a copy of the GNU General Public License version
19  * 2 along with this work; if not, write to the Free Software Foundation,
20  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
21  *
22  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
23  * or visit www.oracle.com if you need additional information or have any
24  * questions.
25  */
26 
27 package java.net;
28 
29 import java.util.Map;
30 import java.util.List;
31 import java.util.Collections;
32 import java.util.Comparator;
33 import java.io.IOException;
34 import sun.util.logging.PlatformLogger;
35 
36 /**
37  * CookieManager provides a concrete implementation of {@link CookieHandler},
38  * which separates the storage of cookies from the policy surrounding accepting
39  * and rejecting cookies. A CookieManager is initialized with a {@link CookieStore}
40  * which manages storage, and a {@link CookiePolicy} object, which makes
41  * policy decisions on cookie acceptance/rejection.
42  *
43  * <p> The HTTP cookie management in java.net package looks like:
44  * <blockquote>
45  * <pre>{@code
46  *                  use
47  * CookieHandler <------- HttpURLConnection
48  *       ^
49  *       | impl
50  *       |         use
51  * CookieManager -------> CookiePolicy
52  *             |   use
53  *             |--------> HttpCookie
54  *             |              ^
55  *             |              | use
56  *             |   use        |
57  *             |--------> CookieStore
58  *                            ^
59  *                            | impl
60  *                            |
61  *                  Internal in-memory implementation
62  * }</pre>
63  * <ul>
64  *   <li>
65  *     CookieHandler is at the core of cookie management. User can call
66  *     CookieHandler.setDefault to set a concrete CookieHanlder implementation
67  *     to be used.
68  *   </li>
69  *   <li>
70  *     CookiePolicy.shouldAccept will be called by CookieManager.put to see whether
71  *     or not one cookie should be accepted and put into cookie store. User can use
72  *     any of three pre-defined CookiePolicy, namely ACCEPT_ALL, ACCEPT_NONE and
73  *     ACCEPT_ORIGINAL_SERVER, or user can define his own CookiePolicy implementation
74  *     and tell CookieManager to use it.
75  *   </li>
76  *   <li>
77  *     CookieStore is the place where any accepted HTTP cookie is stored in.
78  *     If not specified when created, a CookieManager instance will use an internal
79  *     in-memory implementation. Or user can implements one and tell CookieManager
80  *     to use it.
81  *   </li>
82  *   <li>
83  *     Currently, only CookieStore.add(URI, HttpCookie) and CookieStore.get(URI)
84  *     are used by CookieManager. Others are for completeness and might be needed
85  *     by a more sophisticated CookieStore implementation, e.g. a NetscapeCookieStore.
86  *   </li>
87  * </ul>
88  * </blockquote>
89  *
90  * <p>There're various ways user can hook up his own HTTP cookie management behavior, e.g.
91  * <blockquote>
92  * <ul>
93  *   <li>Use CookieHandler.setDefault to set a brand new {@link CookieHandler} implementation
94  *   <li>Let CookieManager be the default {@link CookieHandler} implementation,
95  *       but implement user's own {@link CookieStore} and {@link CookiePolicy}
96  *       and tell default CookieManager to use them:
97  *     <blockquote><pre>
98  *       // this should be done at the beginning of an HTTP session
99  *       CookieHandler.setDefault(new CookieManager(new MyCookieStore(), new MyCookiePolicy()));
100  *     </pre></blockquote>
101  *   <li>Let CookieManager be the default {@link CookieHandler} implementation, but
102  *       use customized {@link CookiePolicy}:
103  *     <blockquote><pre>
104  *       // this should be done at the beginning of an HTTP session
105  *       CookieHandler.setDefault(new CookieManager());
106  *       // this can be done at any point of an HTTP session
107  *       ((CookieManager)CookieHandler.getDefault()).setCookiePolicy(new MyCookiePolicy());
108  *     </pre></blockquote>
109  * </ul>
110  * </blockquote>
111  *
112  * <p>The implementation conforms to <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>, section 3.3.
113  *
114  * @see CookiePolicy
115  * @author Edward Wang
116  * @since 1.6
117  */
118 public class CookieManager extends CookieHandler
119 {
120     /* ---------------- Fields -------------- */
121 
122     private CookiePolicy policyCallback;
123 
124 
125     private CookieStore cookieJar = null;
126 
127 
128     /* ---------------- Ctors -------------- */
129 
130     /**
131      * Create a new cookie manager.
132      *
133      * <p>This constructor will create new cookie manager with default
134      * cookie store and accept policy. The effect is same as
135      * {@code CookieManager(null, null)}.
136      */
CookieManager()137     public CookieManager() {
138         this(null, null);
139     }
140 
141 
142     /**
143      * Create a new cookie manager with specified cookie store and cookie policy.
144      *
145      * @param store     a {@code CookieStore} to be used by cookie manager.
146      *                  if {@code null}, cookie manager will use a default one,
147      *                  which is an in-memory CookieStore implementation.
148      * @param cookiePolicy      a {@code CookiePolicy} instance
149      *                          to be used by cookie manager as policy callback.
150      *                          if {@code null}, ACCEPT_ORIGINAL_SERVER will
151      *                          be used.
152      */
CookieManager(CookieStore store, CookiePolicy cookiePolicy)153     public CookieManager(CookieStore store,
154                          CookiePolicy cookiePolicy)
155     {
156         // use default cookie policy if not specify one
157         policyCallback = (cookiePolicy == null) ? CookiePolicy.ACCEPT_ORIGINAL_SERVER
158                                                 : cookiePolicy;
159 
160         // if not specify CookieStore to use, use default one
161         if (store == null) {
162             cookieJar = new InMemoryCookieStore();
163         } else {
164             cookieJar = store;
165         }
166     }
167 
168 
169     /* ---------------- Public operations -------------- */
170 
171     /**
172      * To set the cookie policy of this cookie manager.
173      *
174      * <p> A instance of {@code CookieManager} will have
175      * cookie policy ACCEPT_ORIGINAL_SERVER by default. Users always
176      * can call this method to set another cookie policy.
177      *
178      * @param cookiePolicy      the cookie policy. Can be {@code null}, which
179      *                          has no effects on current cookie policy.
180      */
setCookiePolicy(CookiePolicy cookiePolicy)181     public void setCookiePolicy(CookiePolicy cookiePolicy) {
182         if (cookiePolicy != null) policyCallback = cookiePolicy;
183     }
184 
185 
186     /**
187      * To retrieve current cookie store.
188      *
189      * @return  the cookie store currently used by cookie manager.
190      */
getCookieStore()191     public CookieStore getCookieStore() {
192         return cookieJar;
193     }
194 
195 
196     public Map<String, List<String>>
get(URI uri, Map<String, List<String>> requestHeaders)197         get(URI uri, Map<String, List<String>> requestHeaders)
198         throws IOException
199     {
200         // pre-condition check
201         if (uri == null || requestHeaders == null) {
202             throw new IllegalArgumentException("Argument is null");
203         }
204 
205         // if there's no default CookieStore, no way for us to get any cookie
206         if (cookieJar == null)
207             return Map.of();
208 
209         boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
210         List<HttpCookie> cookies = new java.util.ArrayList<>();
211         // BEGIN Android-removed: The logic of converting null path is moved into pathMatches.
212         /*
213         String path = uri.getPath();
214         if (path == null || path.isEmpty()) {
215             path = "/";
216         }
217         */
218         // END Android-removed: The logic of converting null path is moved into pathMatches.
219         for (HttpCookie cookie : cookieJar.get(uri)) {
220             // apply path-matches rule (RFC 2965 sec. 3.3.4)
221             // and check for the possible "secure" tag (i.e. don't send
222             // 'secure' cookies over unsecure links)
223             if (pathMatches(uri, cookie) &&
224                     (secureLink || !cookie.getSecure())) {
225                 // BEGIN Android-removed: App compat: b/25897688 InMemoryCookieStore ignores scheme.
226                 /*
227                 if (cookie.isHttpOnly()) {
228                     String s = uri.getScheme();
229                     if (!"http".equalsIgnoreCase(s) && !"https".equalsIgnoreCase(s)) {
230                         continue;
231                     }
232                 }
233                 */
234                 // END Android-removed: App compat: b/25897688 InMemoryCookieStore ignores scheme.
235 
236                 // Let's check the authorize port list if it exists
237                 String ports = cookie.getPortlist();
238                 if (ports != null && !ports.isEmpty()) {
239                     int port = uri.getPort();
240                     if (port == -1) {
241                         port = "https".equals(uri.getScheme()) ? 443 : 80;
242                     }
243                     if (isInPortList(ports, port)) {
244                         cookies.add(cookie);
245                     }
246                 } else {
247                     cookies.add(cookie);
248                 }
249             }
250         }
251         // Android-added: A fix to return empty map if cookies list is empty. b/25897688
252         if (cookies.isEmpty()) {
253             return Collections.emptyMap();
254         }
255 
256         // apply sort rule (RFC 2965 sec. 3.3.4)
257         List<String> cookieHeader = sortByPath(cookies);
258 
259         return Map.of("Cookie", cookieHeader);
260     }
261 
262     public void
put(URI uri, Map<String, List<String>> responseHeaders)263         put(URI uri, Map<String, List<String>> responseHeaders)
264         throws IOException
265     {
266         // pre-condition check
267         if (uri == null || responseHeaders == null) {
268             throw new IllegalArgumentException("Argument is null");
269         }
270 
271 
272         // if there's no default CookieStore, no need to remember any cookie
273         if (cookieJar == null)
274             return;
275 
276     PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");
277         for (String headerKey : responseHeaders.keySet()) {
278             // RFC 2965 3.2.2, key must be 'Set-Cookie2'
279             // we also accept 'Set-Cookie' here for backward compatibility
280             if (headerKey == null
281                 || !(headerKey.equalsIgnoreCase("Set-Cookie2")
282                      || headerKey.equalsIgnoreCase("Set-Cookie")
283                     )
284                 )
285             {
286                 continue;
287             }
288 
289             for (String headerValue : responseHeaders.get(headerKey)) {
290                 try {
291                     List<HttpCookie> cookies;
292                     try {
293                         cookies = HttpCookie.parse(headerValue);
294                     } catch (IllegalArgumentException e) {
295                         // Bogus header, make an empty list and log the error
296                         cookies = java.util.Collections.emptyList();
297                         if (logger.isLoggable(PlatformLogger.Level.SEVERE)) {
298                             logger.severe("Invalid cookie for " + uri + ": " + headerValue);
299                         }
300                     }
301                     for (HttpCookie cookie : cookies) {
302                         if (cookie.getPath() == null) {
303                             // If no path is specified, then by default
304                             // the path is the directory of the page/doc
305                             String path = uri.getPath();
306                             if (!path.endsWith("/")) {
307                                 int i = path.lastIndexOf('/');
308                                 if (i > 0) {
309                                     path = path.substring(0, i + 1);
310                                 } else {
311                                     path = "/";
312                                 }
313                             }
314                             cookie.setPath(path);
315                         // Android-added: A fix to verify cookie URI before removal. b/25763487
316                         } else {
317                             // Validate existing path
318                             if (!pathMatches(uri, cookie)) {
319                                 continue;
320                             }
321                         }
322 
323                         // As per RFC 2965, section 3.3.1:
324                         // Domain  Defaults to the effective request-host.  (Note that because
325                         // there is no dot at the beginning of effective request-host,
326                         // the default Domain can only domain-match itself.)
327                         if (cookie.getDomain() == null) {
328                             String host = uri.getHost();
329                             if (host != null && !host.contains("."))
330                                 host += ".local";
331                             cookie.setDomain(host);
332                         }
333                         String ports = cookie.getPortlist();
334                         if (ports != null) {
335                             int port = uri.getPort();
336                             if (port == -1) {
337                                 port = "https".equals(uri.getScheme()) ? 443 : 80;
338                             }
339                             if (ports.isEmpty()) {
340                                 // Empty port list means this should be restricted
341                                 // to the incoming URI port
342                                 cookie.setPortlist("" + port );
343                                 if (shouldAcceptInternal(uri, cookie)) {
344                                     cookieJar.add(uri, cookie);
345                                 }
346                             } else {
347                                 // Only store cookies with a port list
348                                 // IF the URI port is in that list, as per
349                                 // RFC 2965 section 3.3.2
350                                 if (isInPortList(ports, port) &&
351                                         shouldAcceptInternal(uri, cookie)) {
352                                     cookieJar.add(uri, cookie);
353                                 }
354                             }
355                         } else {
356                             if (shouldAcceptInternal(uri, cookie)) {
357                                 cookieJar.add(uri, cookie);
358                             }
359                         }
360                     }
361                 } catch (IllegalArgumentException e) {
362                     // invalid set-cookie header string
363                     // no-op
364                 }
365             }
366         }
367     }
368 
369 
370     /* ---------------- Private operations -------------- */
371 
372     // to determine whether or not accept this cookie
shouldAcceptInternal(URI uri, HttpCookie cookie)373     private boolean shouldAcceptInternal(URI uri, HttpCookie cookie) {
374         try {
375             return policyCallback.shouldAccept(uri, cookie);
376         } catch (Exception ignored) { // pretect against malicious callback
377             return false;
378         }
379     }
380 
381 
isInPortList(String lst, int port)382     private static boolean isInPortList(String lst, int port) {
383         int i = lst.indexOf(',');
384         int val = -1;
385         while (i > 0) {
386             try {
387                 val = Integer.parseInt(lst.substring(0, i));
388                 if (val == port) {
389                     return true;
390                 }
391             } catch (NumberFormatException numberFormatException) {
392             }
393             lst = lst.substring(i+1);
394             i = lst.indexOf(',');
395         }
396         if (!lst.isEmpty()) {
397             try {
398                 val = Integer.parseInt(lst);
399                 if (val == port) {
400                     return true;
401                 }
402             } catch (NumberFormatException numberFormatException) {
403             }
404         }
405         return false;
406     }
407 
408     // Android-changed: Cookie path matching logic in OpenJDK was wrong. b/25763487
409     /**
410      * Return true iff. the path from {@code cookie} matches the path from {@code uri}.
411      */
pathMatches(URI uri, HttpCookie cookie)412     private static boolean pathMatches(URI uri, HttpCookie cookie) {
413         return normalizePath(uri.getPath()).startsWith(normalizePath(cookie.getPath()));
414     }
415 
normalizePath(String path)416     private static String normalizePath(String path) {
417         if (path == null) {
418             path = "";
419         }
420 
421         if (!path.endsWith("/")) {
422             path = path + "/";
423         }
424 
425         return path;
426     }
427 
428 
429     /*
430      * sort cookies with respect to their path: those with more specific Path attributes
431      * precede those with less specific, as defined in RFC 2965 sec. 3.3.4
432      */
sortByPath(List<HttpCookie> cookies)433     private List<String> sortByPath(List<HttpCookie> cookies) {
434         Collections.sort(cookies, new CookiePathComparator());
435 
436         // BEGIN Android-changed: Cookie header differs in Netscape cookie spec and RFC 2965.
437         // RFC 2965 requires a leading $Version="1" string while Netscape does not.
438         // The workaround here is to add a $Version="1" string in advance.
439         final StringBuilder result = new StringBuilder();
440         int minVersion = 1;
441         for (HttpCookie cookie : cookies) {
442             if (cookie.getVersion() < minVersion) {
443                 minVersion = cookie.getVersion();
444             }
445         }
446 
447         if (minVersion == 1) {
448             result.append("$Version=\"1\"; ");
449         }
450 
451         for (int i = 0; i < cookies.size(); ++i) {
452             if (i != 0) {
453                 result.append("; ");
454             }
455 
456             result.append(cookies.get(i).toString());
457         }
458 
459         List<String> cookieHeader = new java.util.ArrayList<>();
460         cookieHeader.add(result.toString());
461         // END Android-changed: Cookie header differs in Netscape cookie spec and RFC 2965.
462         return cookieHeader;
463     }
464 
465 
466     static class CookiePathComparator implements Comparator<HttpCookie> {
compare(HttpCookie c1, HttpCookie c2)467         public int compare(HttpCookie c1, HttpCookie c2) {
468             if (c1 == c2) return 0;
469             if (c1 == null) return -1;
470             if (c2 == null) return 1;
471 
472             // path rule only applies to the cookies with same name
473             if (!c1.getName().equals(c2.getName())) return 0;
474 
475             // Android-changed: normalize before comparison.
476             final String c1Path = normalizePath(c1.getPath());
477             final String c2Path = normalizePath(c2.getPath());
478 
479             // those with more specific Path attributes precede those with less specific
480             if (c1Path.startsWith(c2Path))
481                 return -1;
482             else if (c2Path.startsWith(c1Path))
483                 return 1;
484             else
485                 return 0;
486         }
487     }
488 }
489