Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/src/share/classes/java/net/CookieManager.java
38829 views
/*1* Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation. Oracle designates this7* particular file as subject to the "Classpath" exception as provided8* by Oracle in the LICENSE file that accompanied this code.9*10* This code is distributed in the hope that it will be useful, but WITHOUT11* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or12* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License13* version 2 for more details (a copy is included in the LICENSE file that14* accompanied this code).15*16* You should have received a copy of the GNU General Public License version17* 2 along with this work; if not, write to the Free Software Foundation,18* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.19*20* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA21* or visit www.oracle.com if you need additional information or have any22* questions.23*/2425package java.net;2627import java.util.Map;28import java.util.List;29import java.util.Collections;30import java.util.Comparator;31import java.io.IOException;32import sun.util.logging.PlatformLogger;3334/**35* CookieManager provides a concrete implementation of {@link CookieHandler},36* which separates the storage of cookies from the policy surrounding accepting37* and rejecting cookies. A CookieManager is initialized with a {@link CookieStore}38* which manages storage, and a {@link CookiePolicy} object, which makes39* policy decisions on cookie acceptance/rejection.40*41* <p> The HTTP cookie management in java.net package looks like:42* <blockquote>43* <pre>{@code44* use45* CookieHandler <------- HttpURLConnection46* ^47* | impl48* | use49* CookieManager -------> CookiePolicy50* | use51* |--------> HttpCookie52* | ^53* | | use54* | use |55* |--------> CookieStore56* ^57* | impl58* |59* Internal in-memory implementation60* }</pre>61* <ul>62* <li>63* CookieHandler is at the core of cookie management. User can call64* CookieHandler.setDefault to set a concrete CookieHanlder implementation65* to be used.66* </li>67* <li>68* CookiePolicy.shouldAccept will be called by CookieManager.put to see whether69* or not one cookie should be accepted and put into cookie store. User can use70* any of three pre-defined CookiePolicy, namely ACCEPT_ALL, ACCEPT_NONE and71* ACCEPT_ORIGINAL_SERVER, or user can define his own CookiePolicy implementation72* and tell CookieManager to use it.73* </li>74* <li>75* CookieStore is the place where any accepted HTTP cookie is stored in.76* If not specified when created, a CookieManager instance will use an internal77* in-memory implementation. Or user can implements one and tell CookieManager78* to use it.79* </li>80* <li>81* Currently, only CookieStore.add(URI, HttpCookie) and CookieStore.get(URI)82* are used by CookieManager. Others are for completeness and might be needed83* by a more sophisticated CookieStore implementation, e.g. a NetscapeCookieSotre.84* </li>85* </ul>86* </blockquote>87*88* <p>There're various ways user can hook up his own HTTP cookie management behavior, e.g.89* <blockquote>90* <ul>91* <li>Use CookieHandler.setDefault to set a brand new {@link CookieHandler} implementation92* <li>Let CookieManager be the default {@link CookieHandler} implementation,93* but implement user's own {@link CookieStore} and {@link CookiePolicy}94* and tell default CookieManager to use them:95* <blockquote><pre>96* // this should be done at the beginning of an HTTP session97* CookieHandler.setDefault(new CookieManager(new MyCookieStore(), new MyCookiePolicy()));98* </pre></blockquote>99* <li>Let CookieManager be the default {@link CookieHandler} implementation, but100* use customized {@link CookiePolicy}:101* <blockquote><pre>102* // this should be done at the beginning of an HTTP session103* CookieHandler.setDefault(new CookieManager());104* // this can be done at any point of an HTTP session105* ((CookieManager)CookieHandler.getDefault()).setCookiePolicy(new MyCookiePolicy());106* </pre></blockquote>107* </ul>108* </blockquote>109*110* <p>The implementation conforms to <a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>, section 3.3.111*112* @see CookiePolicy113* @author Edward Wang114* @since 1.6115*/116public class CookieManager extends CookieHandler117{118/* ---------------- Fields -------------- */119120private CookiePolicy policyCallback;121122123private CookieStore cookieJar = null;124125126/* ---------------- Ctors -------------- */127128/**129* Create a new cookie manager.130*131* <p>This constructor will create new cookie manager with default132* cookie store and accept policy. The effect is same as133* {@code CookieManager(null, null)}.134*/135public CookieManager() {136this(null, null);137}138139140/**141* Create a new cookie manager with specified cookie store and cookie policy.142*143* @param store a {@code CookieStore} to be used by cookie manager.144* if {@code null}, cookie manager will use a default one,145* which is an in-memory CookieStore implementation.146* @param cookiePolicy a {@code CookiePolicy} instance147* to be used by cookie manager as policy callback.148* if {@code null}, ACCEPT_ORIGINAL_SERVER will149* be used.150*/151public CookieManager(CookieStore store,152CookiePolicy cookiePolicy)153{154// use default cookie policy if not specify one155policyCallback = (cookiePolicy == null) ? CookiePolicy.ACCEPT_ORIGINAL_SERVER156: cookiePolicy;157158// if not specify CookieStore to use, use default one159if (store == null) {160cookieJar = new InMemoryCookieStore();161} else {162cookieJar = store;163}164}165166167/* ---------------- Public operations -------------- */168169/**170* To set the cookie policy of this cookie manager.171*172* <p> A instance of {@code CookieManager} will have173* cookie policy ACCEPT_ORIGINAL_SERVER by default. Users always174* can call this method to set another cookie policy.175*176* @param cookiePolicy the cookie policy. Can be {@code null}, which177* has no effects on current cookie policy.178*/179public void setCookiePolicy(CookiePolicy cookiePolicy) {180if (cookiePolicy != null) policyCallback = cookiePolicy;181}182183184/**185* To retrieve current cookie store.186*187* @return the cookie store currently used by cookie manager.188*/189public CookieStore getCookieStore() {190return cookieJar;191}192193194public Map<String, List<String>>195get(URI uri, Map<String, List<String>> requestHeaders)196throws IOException197{198// pre-condition check199if (uri == null || requestHeaders == null) {200throw new IllegalArgumentException("Argument is null");201}202203Map<String, List<String>> cookieMap =204new java.util.HashMap<String, List<String>>();205// if there's no default CookieStore, no way for us to get any cookie206if (cookieJar == null)207return Collections.unmodifiableMap(cookieMap);208209boolean secureLink = "https".equalsIgnoreCase(uri.getScheme());210List<HttpCookie> cookies = new java.util.ArrayList<HttpCookie>();211String path = uri.getPath();212if (path == null || path.isEmpty()) {213path = "/";214}215for (HttpCookie cookie : cookieJar.get(uri)) {216// apply path-matches rule (RFC 2965 sec. 3.3.4)217// and check for the possible "secure" tag (i.e. don't send218// 'secure' cookies over unsecure links)219if (pathMatches(path, cookie.getPath()) &&220(secureLink || !cookie.getSecure())) {221// Enforce httponly attribute222if (cookie.isHttpOnly()) {223String s = uri.getScheme();224if (!"http".equalsIgnoreCase(s) && !"https".equalsIgnoreCase(s)) {225continue;226}227}228// Let's check the authorize port list if it exists229String ports = cookie.getPortlist();230if (ports != null && !ports.isEmpty()) {231int port = uri.getPort();232if (port == -1) {233port = "https".equals(uri.getScheme()) ? 443 : 80;234}235if (isInPortList(ports, port)) {236cookies.add(cookie);237}238} else {239cookies.add(cookie);240}241}242}243244// apply sort rule (RFC 2965 sec. 3.3.4)245List<String> cookieHeader = sortByPath(cookies);246247cookieMap.put("Cookie", cookieHeader);248return Collections.unmodifiableMap(cookieMap);249}250251public void252put(URI uri, Map<String, List<String>> responseHeaders)253throws IOException254{255// pre-condition check256if (uri == null || responseHeaders == null) {257throw new IllegalArgumentException("Argument is null");258}259260261// if there's no default CookieStore, no need to remember any cookie262if (cookieJar == null)263return;264265PlatformLogger logger = PlatformLogger.getLogger("java.net.CookieManager");266for (String headerKey : responseHeaders.keySet()) {267// RFC 2965 3.2.2, key must be 'Set-Cookie2'268// we also accept 'Set-Cookie' here for backward compatibility269if (headerKey == null270|| !(headerKey.equalsIgnoreCase("Set-Cookie2")271|| headerKey.equalsIgnoreCase("Set-Cookie")272)273)274{275continue;276}277278for (String headerValue : responseHeaders.get(headerKey)) {279try {280List<HttpCookie> cookies;281try {282cookies = HttpCookie.parse(headerValue);283} catch (IllegalArgumentException e) {284// Bogus header, make an empty list and log the error285cookies = java.util.Collections.emptyList();286if (logger.isLoggable(PlatformLogger.Level.SEVERE)) {287logger.severe("Invalid cookie for " + uri + ": " + headerValue);288}289}290for (HttpCookie cookie : cookies) {291if (cookie.getPath() == null) {292// If no path is specified, then by default293// the path is the directory of the page/doc294String path = uri.getPath();295if (!path.endsWith("/")) {296int i = path.lastIndexOf("/");297if (i > 0) {298path = path.substring(0, i + 1);299} else {300path = "/";301}302}303cookie.setPath(path);304}305306// As per RFC 2965, section 3.3.1:307// Domain Defaults to the effective request-host. (Note that because308// there is no dot at the beginning of effective request-host,309// the default Domain can only domain-match itself.)310if (cookie.getDomain() == null) {311String host = uri.getHost();312if (host != null && !host.contains("."))313host += ".local";314cookie.setDomain(host);315}316String ports = cookie.getPortlist();317if (ports != null) {318int port = uri.getPort();319if (port == -1) {320port = "https".equals(uri.getScheme()) ? 443 : 80;321}322if (ports.isEmpty()) {323// Empty port list means this should be restricted324// to the incoming URI port325cookie.setPortlist("" + port );326if (shouldAcceptInternal(uri, cookie)) {327cookieJar.add(uri, cookie);328}329} else {330// Only store cookies with a port list331// IF the URI port is in that list, as per332// RFC 2965 section 3.3.2333if (isInPortList(ports, port) &&334shouldAcceptInternal(uri, cookie)) {335cookieJar.add(uri, cookie);336}337}338} else {339if (shouldAcceptInternal(uri, cookie)) {340cookieJar.add(uri, cookie);341}342}343}344} catch (IllegalArgumentException e) {345// invalid set-cookie header string346// no-op347}348}349}350}351352353/* ---------------- Private operations -------------- */354355// to determine whether or not accept this cookie356private boolean shouldAcceptInternal(URI uri, HttpCookie cookie) {357try {358return policyCallback.shouldAccept(uri, cookie);359} catch (Exception ignored) { // pretect against malicious callback360return false;361}362}363364365static private boolean isInPortList(String lst, int port) {366int i = lst.indexOf(",");367int val = -1;368while (i > 0) {369try {370val = Integer.parseInt(lst.substring(0, i));371if (val == port) {372return true;373}374} catch (NumberFormatException numberFormatException) {375}376lst = lst.substring(i+1);377i = lst.indexOf(",");378}379if (!lst.isEmpty()) {380try {381val = Integer.parseInt(lst);382if (val == port) {383return true;384}385} catch (NumberFormatException numberFormatException) {386}387}388return false;389}390391/*392* path-matches algorithm, as defined by RFC 2965393*/394private boolean pathMatches(String path, String pathToMatchWith) {395if (path == pathToMatchWith)396return true;397if (path == null || pathToMatchWith == null)398return false;399if (path.startsWith(pathToMatchWith))400return true;401402return false;403}404405406/*407* sort cookies with respect to their path: those with more specific Path attributes408* precede those with less specific, as defined in RFC 2965 sec. 3.3.4409*/410private List<String> sortByPath(List<HttpCookie> cookies) {411Collections.sort(cookies, new CookiePathComparator());412413List<String> cookieHeader = new java.util.ArrayList<String>();414for (HttpCookie cookie : cookies) {415// Netscape cookie spec and RFC 2965 have different format of Cookie416// header; RFC 2965 requires a leading $Version="1" string while Netscape417// does not.418// The workaround here is to add a $Version="1" string in advance419if (cookies.indexOf(cookie) == 0 && cookie.getVersion() > 0) {420cookieHeader.add("$Version=\"1\"");421}422423cookieHeader.add(cookie.toString());424}425return cookieHeader;426}427428429static class CookiePathComparator implements Comparator<HttpCookie> {430public int compare(HttpCookie c1, HttpCookie c2) {431if (c1 == c2) return 0;432if (c1 == null) return -1;433if (c2 == null) return 1;434435// path rule only applies to the cookies with same name436if (!c1.getName().equals(c2.getName())) return 0;437438// those with more specific Path attributes precede those with less specific439if (c1.getPath().startsWith(c2.getPath()))440return -1;441else if (c2.getPath().startsWith(c1.getPath()))442return 1;443else444return 0;445}446}447}448449450