1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 * Copyright (c) 2005, 2008, 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
27package java.net;
28
29import java.util.Map;
30import java.util.List;
31import java.util.Collections;
32import java.util.Comparator;
33import java.io.IOException;
34import 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>
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 NetscapeCookieSotre.
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 */
118public 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     * <tt>CookieManager(null, null)</tt>.
136     */
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 <tt>CookieStore</tt> to be used by cookie manager.
146     *                  if <tt>null</tt>, cookie manager will use a default one,
147     *                  which is an in-memory CookieStore implmentation.
148     * @param cookiePolicy      a <tt>CookiePolicy</tt> instance
149     *                          to be used by cookie manager as policy callback.
150     *                          if <tt>null</tt>, ACCEPT_ORIGINAL_SERVER will
151     *                          be used.
152     */
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 <tt>CookieManager</tt> 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 <tt>null</tt>, which
179     *                          has no effects on current cookie policy.
180     */
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     */
191    public CookieStore getCookieStore() {
192        return cookieJar;
193    }
194
195
196    public Map<String, List<String>>
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        Map<String, List<String>> cookieMap =
206                        new java.util.HashMap<String, List<String>>();
207        // if there's no default CookieStore, no way for us to get any cookie
208        if (cookieJar == null) {
209            return Collections.unmodifiableMap(cookieMap);
210        }
211
212        boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
213        List<HttpCookie> cookies = new java.util.ArrayList<HttpCookie>();
214        for (HttpCookie cookie : cookieJar.get(uri)) {
215            // apply path-matches rule (RFC 2965 sec. 3.3.4)
216            // and check for the possible "secure" tag (i.e. don't send
217            // 'secure' cookies over unsecure links)
218            if (pathMatches(uri, cookie) &&
219                    (secureLink || !cookie.getSecure())) {
220
221                // Let's check the authorize port list if it exists
222                String ports = cookie.getPortlist();
223                if (ports != null && !ports.isEmpty()) {
224                    int port = uri.getPort();
225                    if (port == -1) {
226                        port = "https".equals(uri.getScheme()) ? 443 : 80;
227                    }
228                    if (isInPortList(ports, port)) {
229                        cookies.add(cookie);
230                    }
231                } else {
232                    cookies.add(cookie);
233                }
234            }
235        }
236        if (cookies.isEmpty()) {
237            return Collections.emptyMap();
238        }
239
240        // apply sort rule (RFC 2965 sec. 3.3.4)
241        List<String> cookieHeader = sortByPath(cookies);
242
243        cookieMap.put("Cookie", cookieHeader);
244        return Collections.unmodifiableMap(cookieMap);
245    }
246
247
248    public void
249        put(URI uri, Map<String, List<String>> responseHeaders)
250        throws IOException
251    {
252        // pre-condition check
253        if (uri == null || responseHeaders == null) {
254            throw new IllegalArgumentException("Argument is null");
255        }
256
257
258        // if there's no default CookieStore, no need to remember any cookie
259        if (cookieJar == null)
260            return;
261
262        PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");
263        for (String headerKey : responseHeaders.keySet()) {
264            // RFC 2965 3.2.2, key must be 'Set-Cookie2'
265            // we also accept 'Set-Cookie' here for backward compatibility
266            if (headerKey == null
267                || !(headerKey.equalsIgnoreCase("Set-Cookie2")
268                     || headerKey.equalsIgnoreCase("Set-Cookie")
269                    )
270                )
271            {
272                continue;
273            }
274
275            for (String headerValue : responseHeaders.get(headerKey)) {
276                try {
277                    List<HttpCookie> cookies;
278                    try {
279                        cookies = HttpCookie.parse(headerValue);
280                    } catch (IllegalArgumentException e) {
281                        // Bogus header, make an empty list and log the error
282                        cookies = java.util.Collections.EMPTY_LIST;
283                        if (logger.isLoggable(PlatformLogger.SEVERE)) {
284                            logger.severe("Invalid cookie for " + uri + ": " + headerValue);
285                        }
286                    }
287                    for (HttpCookie cookie : cookies) {
288                        if (cookie.getPath() == null) {
289                            // If no path is specified, then by default
290                            // the path is the directory of the page/doc
291                            String path = uri.getPath();
292                            if (!path.endsWith("/")) {
293                                int i = path.lastIndexOf("/");
294                                if (i > 0) {
295                                    path = path.substring(0, i + 1);
296                                } else {
297                                    path = "/";
298                                }
299                            }
300                            cookie.setPath(path);
301                        } else {
302                            // Validate existing path
303                            if (!pathMatches(uri, cookie)) {
304                                continue;
305                            }
306                        }
307
308                        // As per RFC 2965, section 3.3.1:
309                        // Domain  Defaults to the effective request-host.  (Note that because
310                        // there is no dot at the beginning of effective request-host,
311                        // the default Domain can only domain-match itself.)
312                        if (cookie.getDomain() == null) {
313                            cookie.setDomain(uri.getHost());
314                        }
315                        String ports = cookie.getPortlist();
316                        if (ports != null) {
317                            int port = uri.getPort();
318                            if (port == -1) {
319                                port = "https".equals(uri.getScheme()) ? 443 : 80;
320                            }
321                            if (ports.isEmpty()) {
322                                // Empty port list means this should be restricted
323                                // to the incoming URI port
324                                cookie.setPortlist("" + port );
325                                if (shouldAcceptInternal(uri, cookie)) {
326                                    cookieJar.add(uri, cookie);
327                                }
328                            } else {
329                                // Only store cookies with a port list
330                                // IF the URI port is in that list, as per
331                                // RFC 2965 section 3.3.2
332                                if (isInPortList(ports, port) &&
333                                        shouldAcceptInternal(uri, cookie)) {
334                                    cookieJar.add(uri, cookie);
335                                }
336                            }
337                        } else {
338                            if (shouldAcceptInternal(uri, cookie)) {
339                                cookieJar.add(uri, cookie);
340                            }
341                        }
342                    }
343                } catch (IllegalArgumentException e) {
344                    // invalid set-cookie header string
345                    // no-op
346                }
347            }
348        }
349    }
350
351
352    /* ---------------- Private operations -------------- */
353
354    // to determine whether or not accept this cookie
355    private boolean shouldAcceptInternal(URI uri, HttpCookie cookie) {
356        try {
357            return policyCallback.shouldAccept(uri, cookie);
358        } catch (Exception ignored) { // pretect against malicious callback
359            return false;
360        }
361    }
362
363
364    static private boolean isInPortList(String lst, int port) {
365        int i = lst.indexOf(",");
366        int val = -1;
367        while (i > 0) {
368            try {
369                val = Integer.parseInt(lst.substring(0, i));
370                if (val == port) {
371                    return true;
372                }
373            } catch (NumberFormatException numberFormatException) {
374            }
375            lst = lst.substring(i+1);
376            i = lst.indexOf(",");
377        }
378        if (!lst.isEmpty()) {
379            try {
380                val = Integer.parseInt(lst);
381                if (val == port) {
382                    return true;
383                }
384            } catch (NumberFormatException numberFormatException) {
385            }
386        }
387        return false;
388    }
389
390    /**
391     * Return true iff. the path from {@code cookie} matches the path from {@code uri}.
392     */
393    private static boolean pathMatches(URI uri, HttpCookie cookie) {
394        return normalizePath(uri.getPath()).startsWith(normalizePath(cookie.getPath()));
395    }
396
397    private static String normalizePath(String path) {
398        if (path == null) {
399            path = "";
400        }
401
402        if (!path.endsWith("/")) {
403            path = path + "/";
404        }
405
406        return path;
407    }
408
409
410    /*
411     * sort cookies with respect to their path: those with more specific Path attributes
412     * precede those with less specific, as defined in RFC 2965 sec. 3.3.4.
413     */
414    private List<String> sortByPath(List<HttpCookie> cookies) {
415        Collections.sort(cookies, new CookiePathComparator());
416
417        final StringBuilder result = new StringBuilder();
418
419        // Netscape cookie spec and RFC 2965 have different format of Cookie
420        // header; RFC 2965 requires a leading $Version="1" string while Netscape
421        // does not.
422        // The workaround here is to add a $Version="1" string in advance
423        int minVersion = 1;
424        for (HttpCookie cookie : cookies) {
425            if (cookie.getVersion() < minVersion) {
426                minVersion = cookie.getVersion();
427            }
428        }
429
430        if (minVersion == 1) {
431            result.append("$Version=\"1\"; ");
432        }
433
434        for (int i = 0; i < cookies.size(); ++i) {
435            if (i != 0) {
436                result.append("; ");
437            }
438
439            result.append(cookies.get(i).toString());
440        }
441
442        List<String> cookieHeader = new java.util.ArrayList<String>();
443        cookieHeader.add(result.toString());
444        return cookieHeader;
445    }
446
447
448    static class CookiePathComparator implements Comparator<HttpCookie> {
449        public int compare(HttpCookie c1, HttpCookie c2) {
450            if (c1 == c2) return 0;
451            if (c1 == null) return -1;
452            if (c2 == null) return 1;
453
454            // path rule only applies to the cookies with same name
455            if (!c1.getName().equals(c2.getName())) return 0;
456
457            final String c1Path = normalizePath(c1.getPath());
458            final String c2Path = normalizePath(c2.getPath());
459
460            // those with more specific Path attributes precede those with less specific
461            if (c1Path.startsWith(c2Path))
462                return -1;
463            else if (c2Path.startsWith(c1Path))
464                return 1;
465            else
466                return 0;
467        }
468    }
469}
470