0N/A/*
2362N/A * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.net;
0N/A
0N/Aimport java.util.Map;
0N/Aimport java.util.List;
0N/Aimport java.util.Collections;
0N/Aimport java.util.Comparator;
0N/Aimport java.io.IOException;
1929N/Aimport sun.util.logging.PlatformLogger;
0N/A
0N/A/**
0N/A * CookieManager provides a concrete implementation of {@link CookieHandler},
0N/A * which separates the storage of cookies from the policy surrounding accepting
0N/A * and rejecting cookies. A CookieManager is initialized with a {@link CookieStore}
0N/A * which manages storage, and a {@link CookiePolicy} object, which makes
0N/A * policy decisions on cookie acceptance/rejection.
0N/A *
0N/A * <p> The HTTP cookie management in java.net package looks like:
0N/A * <blockquote>
0N/A * <pre>
0N/A * use
0N/A * CookieHandler <------- HttpURLConnection
0N/A * ^
0N/A * | impl
0N/A * | use
0N/A * CookieManager -------> CookiePolicy
0N/A * | use
0N/A * |--------> HttpCookie
0N/A * | ^
0N/A * | | use
0N/A * | use |
0N/A * |--------> CookieStore
0N/A * ^
0N/A * | impl
0N/A * |
0N/A * Internal in-memory implementation
0N/A * </pre>
0N/A * <ul>
0N/A * <li>
0N/A * CookieHandler is at the core of cookie management. User can call
0N/A * CookieHandler.setDefault to set a concrete CookieHanlder implementation
0N/A * to be used.
0N/A * </li>
0N/A * <li>
0N/A * CookiePolicy.shouldAccept will be called by CookieManager.put to see whether
0N/A * or not one cookie should be accepted and put into cookie store. User can use
0N/A * any of three pre-defined CookiePolicy, namely ACCEPT_ALL, ACCEPT_NONE and
0N/A * ACCEPT_ORIGINAL_SERVER, or user can define his own CookiePolicy implementation
0N/A * and tell CookieManager to use it.
0N/A * </li>
0N/A * <li>
0N/A * CookieStore is the place where any accepted HTTP cookie is stored in.
0N/A * If not specified when created, a CookieManager instance will use an internal
0N/A * in-memory implementation. Or user can implements one and tell CookieManager
0N/A * to use it.
0N/A * </li>
0N/A * <li>
0N/A * Currently, only CookieStore.add(URI, HttpCookie) and CookieStore.get(URI)
0N/A * are used by CookieManager. Others are for completeness and might be needed
0N/A * by a more sophisticated CookieStore implementation, e.g. a NetscapeCookieSotre.
0N/A * </li>
0N/A * </ul>
0N/A * </blockquote>
0N/A *
0N/A * <p>There're various ways user can hook up his own HTTP cookie management behavior, e.g.
0N/A * <blockquote>
0N/A * <ul>
0N/A * <li>Use CookieHandler.setDefault to set a brand new {@link CookieHandler} implementation
0N/A * <li>Let CookieManager be the default {@link CookieHandler} implementation,
0N/A * but implement user's own {@link CookieStore} and {@link CookiePolicy}
0N/A * and tell default CookieManager to use them:
0N/A * <blockquote><pre>
0N/A * // this should be done at the beginning of an HTTP session
0N/A * CookieHandler.setDefault(new CookieManager(new MyCookieStore(), new MyCookiePolicy()));
0N/A * </pre></blockquote>
0N/A * <li>Let CookieManager be the default {@link CookieHandler} implementation, but
0N/A * use customized {@link CookiePolicy}:
0N/A * <blockquote><pre>
0N/A * // this should be done at the beginning of an HTTP session
0N/A * CookieHandler.setDefault(new CookieManager());
0N/A * // this can be done at any point of an HTTP session
0N/A * ((CookieManager)CookieHandler.getDefault()).setCookiePolicy(new MyCookiePolicy());
0N/A * </pre></blockquote>
0N/A * </ul>
0N/A * </blockquote>
0N/A *
858N/A * <p>The implementation conforms to <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>, section 3.3.
0N/A *
858N/A * @see CookiePolicy
0N/A * @author Edward Wang
0N/A * @since 1.6
0N/A */
0N/Apublic class CookieManager extends CookieHandler
0N/A{
0N/A /* ---------------- Fields -------------- */
0N/A
0N/A private CookiePolicy policyCallback;
0N/A
0N/A
0N/A private CookieStore cookieJar = null;
0N/A
0N/A
0N/A /* ---------------- Ctors -------------- */
0N/A
0N/A /**
0N/A * Create a new cookie manager.
0N/A *
0N/A * <p>This constructor will create new cookie manager with default
0N/A * cookie store and accept policy. The effect is same as
0N/A * <tt>CookieManager(null, null)</tt>.
0N/A */
0N/A public CookieManager() {
0N/A this(null, null);
0N/A }
0N/A
0N/A
0N/A /**
0N/A * Create a new cookie manager with specified cookie store and cookie policy.
0N/A *
0N/A * @param store a <tt>CookieStore</tt> to be used by cookie manager.
0N/A * if <tt>null</tt>, cookie manager will use a default one,
0N/A * which is an in-memory CookieStore implmentation.
0N/A * @param cookiePolicy a <tt>CookiePolicy</tt> instance
0N/A * to be used by cookie manager as policy callback.
0N/A * if <tt>null</tt>, ACCEPT_ORIGINAL_SERVER will
0N/A * be used.
0N/A */
0N/A public CookieManager(CookieStore store,
0N/A CookiePolicy cookiePolicy)
0N/A {
0N/A // use default cookie policy if not specify one
0N/A policyCallback = (cookiePolicy == null) ? CookiePolicy.ACCEPT_ORIGINAL_SERVER
0N/A : cookiePolicy;
0N/A
0N/A // if not specify CookieStore to use, use default one
0N/A if (store == null) {
1669N/A cookieJar = new InMemoryCookieStore();
0N/A } else {
0N/A cookieJar = store;
0N/A }
0N/A }
0N/A
0N/A
0N/A /* ---------------- Public operations -------------- */
0N/A
0N/A /**
0N/A * To set the cookie policy of this cookie manager.
0N/A *
0N/A * <p> A instance of <tt>CookieManager</tt> will have
0N/A * cookie policy ACCEPT_ORIGINAL_SERVER by default. Users always
0N/A * can call this method to set another cookie policy.
0N/A *
0N/A * @param cookiePolicy the cookie policy. Can be <tt>null</tt>, which
0N/A * has no effects on current cookie policy.
0N/A */
0N/A public void setCookiePolicy(CookiePolicy cookiePolicy) {
0N/A if (cookiePolicy != null) policyCallback = cookiePolicy;
0N/A }
0N/A
0N/A
0N/A /**
0N/A * To retrieve current cookie store.
0N/A *
0N/A * @return the cookie store currently used by cookie manager.
0N/A */
0N/A public CookieStore getCookieStore() {
0N/A return cookieJar;
0N/A }
0N/A
0N/A
0N/A public Map<String, List<String>>
0N/A get(URI uri, Map<String, List<String>> requestHeaders)
0N/A throws IOException
0N/A {
0N/A // pre-condition check
0N/A if (uri == null || requestHeaders == null) {
0N/A throw new IllegalArgumentException("Argument is null");
0N/A }
0N/A
0N/A Map<String, List<String>> cookieMap =
0N/A new java.util.HashMap<String, List<String>>();
0N/A // if there's no default CookieStore, no way for us to get any cookie
0N/A if (cookieJar == null)
0N/A return Collections.unmodifiableMap(cookieMap);
0N/A
257N/A boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());
0N/A List<HttpCookie> cookies = new java.util.ArrayList<HttpCookie>();
257N/A String path = uri.getPath();
257N/A if (path == null || path.isEmpty()) {
257N/A path = "/";
257N/A }
0N/A for (HttpCookie cookie : cookieJar.get(uri)) {
0N/A // apply path-matches rule (RFC 2965 sec. 3.3.4)
257N/A // and check for the possible "secure" tag (i.e. don't send
257N/A // 'secure' cookies over unsecure links)
257N/A if (pathMatches(path, cookie.getPath()) &&
257N/A (secureLink || !cookie.getSecure())) {
1788N/A // Enforce httponly attribute
1788N/A if (cookie.isHttpOnly()) {
1788N/A String s = uri.getScheme();
1788N/A if (!"http".equalsIgnoreCase(s) && !"https".equalsIgnoreCase(s)) {
1788N/A continue;
1788N/A }
1788N/A }
257N/A // Let's check the authorize port list if it exists
257N/A String ports = cookie.getPortlist();
257N/A if (ports != null && !ports.isEmpty()) {
257N/A int port = uri.getPort();
257N/A if (port == -1) {
257N/A port = "https".equals(uri.getScheme()) ? 443 : 80;
257N/A }
257N/A if (isInPortList(ports, port)) {
257N/A cookies.add(cookie);
257N/A }
257N/A } else {
257N/A cookies.add(cookie);
257N/A }
0N/A }
0N/A }
0N/A
0N/A // apply sort rule (RFC 2965 sec. 3.3.4)
0N/A List<String> cookieHeader = sortByPath(cookies);
0N/A
0N/A cookieMap.put("Cookie", cookieHeader);
0N/A return Collections.unmodifiableMap(cookieMap);
0N/A }
0N/A
0N/A
0N/A public void
0N/A put(URI uri, Map<String, List<String>> responseHeaders)
0N/A throws IOException
0N/A {
0N/A // pre-condition check
0N/A if (uri == null || responseHeaders == null) {
0N/A throw new IllegalArgumentException("Argument is null");
0N/A }
0N/A
0N/A
0N/A // if there's no default CookieStore, no need to remember any cookie
0N/A if (cookieJar == null)
0N/A return;
0N/A
1929N/A PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");
0N/A for (String headerKey : responseHeaders.keySet()) {
0N/A // RFC 2965 3.2.2, key must be 'Set-Cookie2'
0N/A // we also accept 'Set-Cookie' here for backward compatibility
0N/A if (headerKey == null
0N/A || !(headerKey.equalsIgnoreCase("Set-Cookie2")
0N/A || headerKey.equalsIgnoreCase("Set-Cookie")
0N/A )
0N/A )
0N/A {
0N/A continue;
0N/A }
0N/A
0N/A for (String headerValue : responseHeaders.get(headerKey)) {
0N/A try {
1929N/A List<HttpCookie> cookies;
1929N/A try {
1929N/A cookies = HttpCookie.parse(headerValue);
1929N/A } catch (IllegalArgumentException e) {
1929N/A // Bogus header, make an empty list and log the error
1929N/A cookies = java.util.Collections.EMPTY_LIST;
1929N/A if (logger.isLoggable(PlatformLogger.SEVERE)) {
1929N/A logger.severe("Invalid cookie for " + uri + ": " + headerValue);
1929N/A }
1929N/A }
0N/A for (HttpCookie cookie : cookies) {
257N/A if (cookie.getPath() == null) {
257N/A // If no path is specified, then by default
257N/A // the path is the directory of the page/doc
257N/A String path = uri.getPath();
257N/A if (!path.endsWith("/")) {
257N/A int i = path.lastIndexOf("/");
257N/A if (i > 0) {
257N/A path = path.substring(0, i + 1);
257N/A } else {
257N/A path = "/";
257N/A }
257N/A }
257N/A cookie.setPath(path);
257N/A }
1248N/A
1248N/A // As per RFC 2965, section 3.3.1:
1248N/A // Domain Defaults to the effective request-host. (Note that because
1248N/A // there is no dot at the beginning of effective request-host,
1248N/A // the default Domain can only domain-match itself.)
1248N/A if (cookie.getDomain() == null) {
1248N/A cookie.setDomain(uri.getHost());
1248N/A }
257N/A String ports = cookie.getPortlist();
257N/A if (ports != null) {
257N/A int port = uri.getPort();
257N/A if (port == -1) {
257N/A port = "https".equals(uri.getScheme()) ? 443 : 80;
257N/A }
257N/A if (ports.isEmpty()) {
257N/A // Empty port list means this should be restricted
257N/A // to the incoming URI port
257N/A cookie.setPortlist("" + port );
257N/A if (shouldAcceptInternal(uri, cookie)) {
257N/A cookieJar.add(uri, cookie);
257N/A }
257N/A } else {
257N/A // Only store cookies with a port list
257N/A // IF the URI port is in that list, as per
257N/A // RFC 2965 section 3.3.2
257N/A if (isInPortList(ports, port) &&
257N/A shouldAcceptInternal(uri, cookie)) {
257N/A cookieJar.add(uri, cookie);
257N/A }
257N/A }
257N/A } else {
257N/A if (shouldAcceptInternal(uri, cookie)) {
257N/A cookieJar.add(uri, cookie);
257N/A }
0N/A }
0N/A }
0N/A } catch (IllegalArgumentException e) {
0N/A // invalid set-cookie header string
0N/A // no-op
0N/A }
0N/A }
0N/A }
0N/A }
0N/A
0N/A
0N/A /* ---------------- Private operations -------------- */
0N/A
0N/A // to determine whether or not accept this cookie
0N/A private boolean shouldAcceptInternal(URI uri, HttpCookie cookie) {
0N/A try {
0N/A return policyCallback.shouldAccept(uri, cookie);
0N/A } catch (Exception ignored) { // pretect against malicious callback
0N/A return false;
0N/A }
0N/A }
0N/A
0N/A
257N/A static private boolean isInPortList(String lst, int port) {
257N/A int i = lst.indexOf(",");
257N/A int val = -1;
257N/A while (i > 0) {
257N/A try {
257N/A val = Integer.parseInt(lst.substring(0, i));
257N/A if (val == port) {
257N/A return true;
257N/A }
257N/A } catch (NumberFormatException numberFormatException) {
257N/A }
257N/A lst = lst.substring(i+1);
257N/A i = lst.indexOf(",");
257N/A }
257N/A if (!lst.isEmpty()) {
257N/A try {
257N/A val = Integer.parseInt(lst);
257N/A if (val == port) {
257N/A return true;
257N/A }
257N/A } catch (NumberFormatException numberFormatException) {
257N/A }
257N/A }
257N/A return false;
257N/A }
257N/A
0N/A /*
0N/A * path-matches algorithm, as defined by RFC 2965
0N/A */
0N/A private boolean pathMatches(String path, String pathToMatchWith) {
0N/A if (path == pathToMatchWith)
0N/A return true;
0N/A if (path == null || pathToMatchWith == null)
0N/A return false;
0N/A if (path.startsWith(pathToMatchWith))
0N/A return true;
0N/A
0N/A return false;
0N/A }
0N/A
0N/A
0N/A /*
0N/A * sort cookies with respect to their path: those with more specific Path attributes
0N/A * precede those with less specific, as defined in RFC 2965 sec. 3.3.4
0N/A */
0N/A private List<String> sortByPath(List<HttpCookie> cookies) {
0N/A Collections.sort(cookies, new CookiePathComparator());
0N/A
0N/A List<String> cookieHeader = new java.util.ArrayList<String>();
0N/A for (HttpCookie cookie : cookies) {
0N/A // Netscape cookie spec and RFC 2965 have different format of Cookie
0N/A // header; RFC 2965 requires a leading $Version="1" string while Netscape
0N/A // does not.
0N/A // The workaround here is to add a $Version="1" string in advance
0N/A if (cookies.indexOf(cookie) == 0 && cookie.getVersion() > 0) {
0N/A cookieHeader.add("$Version=\"1\"");
0N/A }
0N/A
0N/A cookieHeader.add(cookie.toString());
0N/A }
0N/A return cookieHeader;
0N/A }
0N/A
0N/A
0N/A static class CookiePathComparator implements Comparator<HttpCookie> {
0N/A public int compare(HttpCookie c1, HttpCookie c2) {
0N/A if (c1 == c2) return 0;
0N/A if (c1 == null) return -1;
0N/A if (c2 == null) return 1;
0N/A
0N/A // path rule only applies to the cookies with same name
0N/A if (!c1.getName().equals(c2.getName())) return 0;
0N/A
0N/A // those with more specific Path attributes precede those with less specific
0N/A if (c1.getPath().startsWith(c2.getPath()))
0N/A return -1;
0N/A else if (c2.getPath().startsWith(c1.getPath()))
0N/A return 1;
0N/A else
0N/A return 0;
0N/A }
0N/A }
0N/A}