Path: blob/master/src/java.base/share/classes/java/net/HttpCookie.java
41152 views
/*1* Copyright (c) 2005, 2021, 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.List;28import java.util.StringTokenizer;29import java.util.NoSuchElementException;30import java.text.SimpleDateFormat;31import java.util.TimeZone;32import java.util.Calendar;33import java.util.GregorianCalendar;34import java.util.Locale;35import java.util.Objects;36import jdk.internal.access.JavaNetHttpCookieAccess;37import jdk.internal.access.SharedSecrets;3839/**40* An HttpCookie object represents an HTTP cookie, which carries state41* information between server and user agent. Cookie is widely adopted42* to create stateful sessions.43*44* <p> There are 3 HTTP cookie specifications:45* <blockquote>46* Netscape draft<br>47* RFC 2109 - <a href="http://www.ietf.org/rfc/rfc2109.txt">48* <i>http://www.ietf.org/rfc/rfc2109.txt</i></a><br>49* RFC 2965 - <a href="http://www.ietf.org/rfc/rfc2965.txt">50* <i>http://www.ietf.org/rfc/rfc2965.txt</i></a>51* </blockquote>52*53* <p> HttpCookie class can accept all these 3 forms of syntax.54*55* @author Edward Wang56* @since 1.657*/58public final class HttpCookie implements Cloneable {59// ---------------- Fields --------------6061// The value of the cookie itself.62private final String name; // NAME= ... "$Name" style is reserved63private String value; // value of NAME6465// Attributes encoded in the header's cookie fields.66private String comment; // Comment=VALUE ... describes cookie's use67private String commentURL; // CommentURL="http URL" ... describes cookie's use68private boolean toDiscard; // Discard ... discard cookie unconditionally69private String domain; // Domain=VALUE ... domain that sees cookie70private long maxAge = MAX_AGE_UNSPECIFIED; // Max-Age=VALUE ... cookies auto-expire71private String path; // Path=VALUE ... URLs that see the cookie72private String portlist; // Port[="portlist"] ... the port cookie may be returned to73private boolean secure; // Secure ... e.g. use SSL74private boolean httpOnly; // HttpOnly ... i.e. not accessible to scripts75private int version = 1; // Version=1 ... RFC 2965 style7677// The original header this cookie was constructed from, if it was78// constructed by parsing a header, otherwise null.79private final String header;8081// Hold the creation time (in seconds) of the http cookie for later82// expiration calculation83private final long whenCreated;8485// Since the positive and zero max-age have their meanings,86// this value serves as a hint as 'not specify max-age'87private static final long MAX_AGE_UNSPECIFIED = -1;8889// date formats used by Netscape's cookie draft90// as well as formats seen on various sites91private static final String[] COOKIE_DATE_FORMATS = {92"EEE',' dd-MMM-yyyy HH:mm:ss 'GMT'",93"EEE',' dd MMM yyyy HH:mm:ss 'GMT'",94"EEE MMM dd yyyy HH:mm:ss 'GMT'Z",95"EEE',' dd-MMM-yy HH:mm:ss 'GMT'",96"EEE',' dd MMM yy HH:mm:ss 'GMT'",97"EEE MMM dd yy HH:mm:ss 'GMT'Z"98};99100// constant strings represent set-cookie header token101private static final String SET_COOKIE = "set-cookie:";102private static final String SET_COOKIE2 = "set-cookie2:";103104// ---------------- Ctors --------------105106/**107* Constructs a cookie with a specified name and value.108*109* <p> The name must conform to RFC 2965. That means it can contain110* only ASCII alphanumeric characters and cannot contain commas,111* semicolons, or white space or begin with a $ character. The cookie's112* name cannot be changed after creation.113*114* <p> The value can be anything the server chooses to send. Its115* value is probably of interest only to the server. The cookie's116* value can be changed after creation with the117* {@code setValue} method.118*119* <p> By default, cookies are created according to the RFC 2965120* cookie specification. The version can be changed with the121* {@code setVersion} method.122*123*124* @param name125* a {@code String} specifying the name of the cookie126*127* @param value128* a {@code String} specifying the value of the cookie129*130* @throws IllegalArgumentException131* if the cookie name contains illegal characters132* @throws NullPointerException133* if {@code name} is {@code null}134*135* @see #setValue136* @see #setVersion137*/138public HttpCookie(String name, String value) {139this(name, value, null /*header*/);140}141142private HttpCookie(String name, String value, String header) {143this(name, value, header, System.currentTimeMillis());144}145146/**147* Package private for testing purposes.148*/149HttpCookie(String name, String value, String header, long creationTime) {150name = name.trim();151if (name.isEmpty() || !isToken(name) || name.charAt(0) == '$') {152throw new IllegalArgumentException("Illegal cookie name");153}154155this.name = name;156this.value = value;157toDiscard = false;158secure = false;159160whenCreated = creationTime;161portlist = null;162this.header = header;163}164165/**166* Constructs cookies from set-cookie or set-cookie2 header string.167* RFC 2965 section 3.2.2 set-cookie2 syntax indicates that one header line168* may contain more than one cookie definitions, so this is a static169* utility method instead of another constructor.170*171* @param header172* a {@code String} specifying the set-cookie header. The header173* should start with "set-cookie", or "set-cookie2" token; or it174* should have no leading token at all.175*176* @return a List of cookie parsed from header line string177*178* @throws IllegalArgumentException179* if header string violates the cookie specification's syntax or180* the cookie name contains illegal characters.181* @throws NullPointerException182* if the header string is {@code null}183*/184public static List<HttpCookie> parse(String header) {185return parse(header, false);186}187188// Private version of parse() that will store the original header used to189// create the cookie, in the cookie itself. This can be useful for filtering190// Set-Cookie[2] headers, using the internal parsing logic defined in this191// class.192private static List<HttpCookie> parse(String header, boolean retainHeader) {193194int version = guessCookieVersion(header);195196// if header start with set-cookie or set-cookie2, strip it off197if (startsWithIgnoreCase(header, SET_COOKIE2)) {198header = header.substring(SET_COOKIE2.length());199} else if (startsWithIgnoreCase(header, SET_COOKIE)) {200header = header.substring(SET_COOKIE.length());201}202203List<HttpCookie> cookies = new java.util.ArrayList<>();204// The Netscape cookie may have a comma in its expires attribute, while205// the comma is the delimiter in rfc 2965/2109 cookie header string.206// so the parse logic is slightly different207if (version == 0) {208// Netscape draft cookie209HttpCookie cookie = parseInternal(header, retainHeader);210cookie.setVersion(0);211cookies.add(cookie);212} else {213// rfc2965/2109 cookie214// if header string contains more than one cookie,215// it'll separate them with comma216List<String> cookieStrings = splitMultiCookies(header);217for (String cookieStr : cookieStrings) {218HttpCookie cookie = parseInternal(cookieStr, retainHeader);219cookie.setVersion(1);220cookies.add(cookie);221}222}223224return cookies;225}226227// ---------------- Public operations --------------228229/**230* Reports whether this HTTP cookie has expired or not.231*232* @return {@code true} to indicate this HTTP cookie has expired;233* otherwise, {@code false}234*/235public boolean hasExpired() {236if (maxAge == 0) return true;237238// if not specify max-age, this cookie should be239// discarded when user agent is to be closed, but240// it is not expired.241if (maxAge < 0) return false;242243long deltaSecond = (System.currentTimeMillis() - whenCreated) / 1000;244if (deltaSecond > maxAge)245return true;246else247return false;248}249250/**251* Specifies a comment that describes a cookie's purpose.252* The comment is useful if the browser presents the cookie253* to the user. Comments are not supported by Netscape Version 0 cookies.254*255* @param purpose256* a {@code String} specifying the comment to display to the user257*258* @see #getComment259*/260public void setComment(String purpose) {261comment = purpose;262}263264/**265* Returns the comment describing the purpose of this cookie, or266* {@code null} if the cookie has no comment.267*268* @return a {@code String} containing the comment, or {@code null} if none269*270* @see #setComment271*/272public String getComment() {273return comment;274}275276/**277* Specifies a comment URL that describes a cookie's purpose.278* The comment URL is useful if the browser presents the cookie279* to the user. Comment URL is RFC 2965 only.280*281* @param purpose282* a {@code String} specifying the comment URL to display to the user283*284* @see #getCommentURL285*/286public void setCommentURL(String purpose) {287commentURL = purpose;288}289290/**291* Returns the comment URL describing the purpose of this cookie, or292* {@code null} if the cookie has no comment URL.293*294* @return a {@code String} containing the comment URL, or {@code null}295* if none296*297* @see #setCommentURL298*/299public String getCommentURL() {300return commentURL;301}302303/**304* Specify whether user agent should discard the cookie unconditionally.305* This is RFC 2965 only attribute.306*307* @param discard308* {@code true} indicates to discard cookie unconditionally309*310* @see #getDiscard311*/312public void setDiscard(boolean discard) {313toDiscard = discard;314}315316/**317* Returns the discard attribute of the cookie318*319* @return a {@code boolean} to represent this cookie's discard attribute320*321* @see #setDiscard322*/323public boolean getDiscard() {324return toDiscard;325}326327/**328* Specify the portlist of the cookie, which restricts the port(s)329* to which a cookie may be sent back in a Cookie header.330*331* @param ports332* a {@code String} specify the port list, which is comma separated333* series of digits334*335* @see #getPortlist336*/337public void setPortlist(String ports) {338portlist = ports;339}340341/**342* Returns the port list attribute of the cookie343*344* @return a {@code String} contains the port list or {@code null} if none345*346* @see #setPortlist347*/348public String getPortlist() {349return portlist;350}351352/**353* Specifies the domain within which this cookie should be presented.354*355* <p> The form of the domain name is specified by RFC 2965. A domain356* name begins with a dot ({@code .foo.com}) and means that357* the cookie is visible to servers in a specified Domain Name System358* (DNS) zone (for example, {@code www.foo.com}, but not359* {@code a.b.foo.com}). By default, cookies are only returned360* to the server that sent them.361*362* @param pattern363* a {@code String} containing the domain name within which this364* cookie is visible; form is according to RFC 2965365*366* @see #getDomain367*/368public void setDomain(String pattern) {369if (pattern != null)370domain = pattern.toLowerCase();371else372domain = pattern;373}374375/**376* Returns the domain name set for this cookie. The form of the domain name377* is set by RFC 2965.378*379* @return a {@code String} containing the domain name380*381* @see #setDomain382*/383public String getDomain() {384return domain;385}386387/**388* Sets the maximum age of the cookie in seconds.389*390* <p> A positive value indicates that the cookie will expire391* after that many seconds have passed. Note that the value is392* the <i>maximum</i> age when the cookie will expire, not the cookie's393* current age.394*395* <p> A negative value means that the cookie is not stored persistently396* and will be deleted when the Web browser exits. A zero value causes the397* cookie to be deleted.398*399* @param expiry400* an integer specifying the maximum age of the cookie in seconds;401* if zero, the cookie should be discarded immediately; otherwise,402* the cookie's max age is unspecified.403*404* @see #getMaxAge405*/406public void setMaxAge(long expiry) {407maxAge = expiry;408}409410/**411* Returns the maximum age of the cookie, specified in seconds. By default,412* {@code -1} indicating the cookie will persist until browser shutdown.413*414* @return an integer specifying the maximum age of the cookie in seconds415*416* @see #setMaxAge417*/418public long getMaxAge() {419return maxAge;420}421422/**423* Specifies a path for the cookie to which the client should return424* the cookie.425*426* <p> The cookie is visible to all the pages in the directory427* you specify, and all the pages in that directory's subdirectories.428* A cookie's path must include the servlet that set the cookie,429* for example, <i>/catalog</i>, which makes the cookie430* visible to all directories on the server under <i>/catalog</i>.431*432* <p> Consult RFC 2965 (available on the Internet) for more433* information on setting path names for cookies.434*435* @param uri436* a {@code String} specifying a path437*438* @see #getPath439*/440public void setPath(String uri) {441path = uri;442}443444/**445* Returns the path on the server to which the browser returns this cookie.446* The cookie is visible to all subpaths on the server.447*448* @return a {@code String} specifying a path that contains a servlet name,449* for example, <i>/catalog</i>450*451* @see #setPath452*/453public String getPath() {454return path;455}456457/**458* Indicates whether the cookie should only be sent using a secure protocol,459* such as HTTPS or SSL.460*461* <p> The default value is {@code false}.462*463* @param flag464* If {@code true}, the cookie can only be sent over a secure465* protocol like HTTPS. If {@code false}, it can be sent over466* any protocol.467*468* @see #getSecure469*/470public void setSecure(boolean flag) {471secure = flag;472}473474/**475* Returns {@code true} if sending this cookie should be restricted to a476* secure protocol, or {@code false} if the it can be sent using any477* protocol.478*479* @return {@code false} if the cookie can be sent over any standard480* protocol; otherwise, {@code true}481*482* @see #setSecure483*/484public boolean getSecure() {485return secure;486}487488/**489* Returns the name of the cookie. The name cannot be changed after490* creation.491*492* @return a {@code String} specifying the cookie's name493*/494public String getName() {495return name;496}497498/**499* Assigns a new value to a cookie after the cookie is created.500* If you use a binary value, you may want to use BASE64 encoding.501*502* <p> With Version 0 cookies, values should not contain white space,503* brackets, parentheses, equals signs, commas, double quotes, slashes,504* question marks, at signs, colons, and semicolons. Empty values may not505* behave the same way on all browsers.506*507* @param newValue508* a {@code String} specifying the new value509*510* @see #getValue511*/512public void setValue(String newValue) {513value = newValue;514}515516/**517* Returns the value of the cookie.518*519* @return a {@code String} containing the cookie's present value520*521* @see #setValue522*/523public String getValue() {524return value;525}526527/**528* Returns the version of the protocol this cookie complies with. Version 1529* complies with RFC 2965/2109, and version 0 complies with the original530* cookie specification drafted by Netscape. Cookies provided by a browser531* use and identify the browser's cookie version.532*533* @return 0 if the cookie complies with the original Netscape534* specification; 1 if the cookie complies with RFC 2965/2109535*536* @see #setVersion537*/538public int getVersion() {539return version;540}541542/**543* Sets the version of the cookie protocol this cookie complies544* with. Version 0 complies with the original Netscape cookie545* specification. Version 1 complies with RFC 2965/2109.546*547* @param v548* 0 if the cookie should comply with the original Netscape549* specification; 1 if the cookie should comply with RFC 2965/2109550*551* @throws IllegalArgumentException552* if {@code v} is neither 0 nor 1553*554* @see #getVersion555*/556public void setVersion(int v) {557if (v != 0 && v != 1) {558throw new IllegalArgumentException("cookie version should be 0 or 1");559}560561version = v;562}563564/**565* Returns {@code true} if this cookie contains the <i>HttpOnly</i>566* attribute. This means that the cookie should not be accessible to567* scripting engines, like javascript.568*569* @return {@code true} if this cookie should be considered HTTPOnly570*571* @see #setHttpOnly(boolean)572*/573public boolean isHttpOnly() {574return httpOnly;575}576577/**578* Indicates whether the cookie should be considered HTTP Only. If set to579* {@code true} it means the cookie should not be accessible to scripting580* engines like javascript.581*582* @param httpOnly583* if {@code true} make the cookie HTTP only, i.e. only visible as584* part of an HTTP request.585*586* @see #isHttpOnly()587*/588public void setHttpOnly(boolean httpOnly) {589this.httpOnly = httpOnly;590}591592/**593* The utility method to check whether a host name is in a domain or not.594*595* <p> This concept is described in the cookie specification.596* To understand the concept, some terminologies need to be defined first:597* <blockquote>598* effective host name = hostname if host name contains dot<br>599* 600* or = hostname.local if not601* </blockquote>602* <p>Host A's name domain-matches host B's if:603* <blockquote><ul>604* <li>their host name strings string-compare equal; or</li>605* <li>A is a HDN string and has the form NB, where N is a non-empty606* name string, B has the form .B', and B' is a HDN string. (So,607* x.y.com domain-matches .Y.com but not Y.com.)</li>608* </ul></blockquote>609*610* <p>A host isn't in a domain (RFC 2965 sec. 3.3.2) if:611* <blockquote><ul>612* <li>The value for the Domain attribute contains no embedded dots,613* and the value is not .local.</li>614* <li>The effective host name that derives from the request-host does615* not domain-match the Domain attribute.</li>616* <li>The request-host is a HDN (not IP address) and has the form HD,617* where D is the value of the Domain attribute, and H is a string618* that contains one or more dots.</li>619* </ul></blockquote>620*621* <p>Examples:622* <blockquote><ul>623* <li>A Set-Cookie2 from request-host y.x.foo.com for Domain=.foo.com624* would be rejected, because H is y.x and contains a dot.</li>625* <li>A Set-Cookie2 from request-host x.foo.com for Domain=.foo.com626* would be accepted.</li>627* <li>A Set-Cookie2 with Domain=.com or Domain=.com., will always be628* rejected, because there is no embedded dot.</li>629* <li>A Set-Cookie2 from request-host example for Domain=.local will630* be accepted, because the effective host name for the request-631* host is example.local, and example.local domain-matches .local.</li>632* </ul></blockquote>633*634* @param domain635* the domain name to check host name with636*637* @param host638* the host name in question639*640* @return {@code true} if they domain-matches; {@code false} if not641*/642public static boolean domainMatches(String domain, String host) {643if (domain == null || host == null)644return false;645646// if there's no embedded dot in domain and domain is not .local647boolean isLocalDomain = ".local".equalsIgnoreCase(domain);648int embeddedDotInDomain = domain.indexOf('.');649if (embeddedDotInDomain == 0)650embeddedDotInDomain = domain.indexOf('.', 1);651if (!isLocalDomain652&& (embeddedDotInDomain == -1 ||653embeddedDotInDomain == domain.length() - 1))654return false;655656// if the host name contains no dot and the domain name657// is .local or host.local658int firstDotInHost = host.indexOf('.');659if (firstDotInHost == -1 &&660(isLocalDomain ||661domain.equalsIgnoreCase(host + ".local"))) {662return true;663}664665int domainLength = domain.length();666int lengthDiff = host.length() - domainLength;667if (lengthDiff == 0) {668// if the host name and the domain name are just string-compare equal669return host.equalsIgnoreCase(domain);670}671else if (lengthDiff > 0) {672// need to check H & D component673String H = host.substring(0, lengthDiff);674String D = host.substring(lengthDiff);675676return (H.indexOf('.') == -1 && D.equalsIgnoreCase(domain));677}678else if (lengthDiff == -1) {679// if domain is actually .host680return (domain.charAt(0) == '.' &&681host.equalsIgnoreCase(domain.substring(1)));682}683684return false;685}686687/**688* Constructs a cookie header string representation of this cookie,689* which is in the format defined by corresponding cookie specification,690* but without the leading "Cookie:" token.691*692* @return a string form of the cookie. The string has the defined format693*/694@Override695public String toString() {696if (getVersion() > 0) {697return toRFC2965HeaderString();698} else {699return toNetscapeHeaderString();700}701}702703/**704* Test the equality of two HTTP cookies.705*706* <p> The result is {@code true} only if two cookies come from same domain707* (case-insensitive), have same name (case-insensitive), and have same path708* (case-sensitive).709*710* @return {@code true} if two HTTP cookies equal to each other;711* otherwise, {@code false}712*/713@Override714public boolean equals(Object obj) {715if (obj == this)716return true;717if (!(obj instanceof HttpCookie other))718return false;719720// One http cookie is equal to another cookie (RFC 2965 sec. 3.3.3) if:721// 1. they come from same domain (case-insensitive),722// 2. have same name (case-insensitive),723// 3. and have same path (case-sensitive).724return equalsIgnoreCase(getName(), other.getName()) &&725equalsIgnoreCase(getDomain(), other.getDomain()) &&726Objects.equals(getPath(), other.getPath());727}728729/**730* Returns the hash code of this HTTP cookie. The result is the sum of731* hash code value of three significant components of this cookie: name,732* domain, and path. That is, the hash code is the value of the expression:733* <blockquote>734* getName().toLowerCase().hashCode()<br>735* + getDomain().toLowerCase().hashCode()<br>736* + getPath().hashCode()737* </blockquote>738*739* @return this HTTP cookie's hash code740*/741@Override742public int hashCode() {743int h1 = name.toLowerCase().hashCode();744int h2 = (domain!=null) ? domain.toLowerCase().hashCode() : 0;745int h3 = (path!=null) ? path.hashCode() : 0;746747return h1 + h2 + h3;748}749750/**751* Create and return a copy of this object.752*753* @return a clone of this HTTP cookie754*/755@Override756public Object clone() {757try {758return super.clone();759} catch (CloneNotSupportedException e) {760throw new RuntimeException(e.getMessage());761}762}763// ---------------- Package private operations --------------764765long getCreationTime() {766return whenCreated;767}768769// ---------------- Private operations --------------770771// Note -- disabled for now to allow full Netscape compatibility772// from RFC 2068, token special case characters773//774// private static final String tspecials = "()<>@,;:\\\"/[]?={} \t";775private static final String tspecials = ",; "; // deliberately includes space776777/*778* Tests a string and returns true if the string counts as a token.779*780* @param value781* the {@code String} to be tested782*783* @return {@code true} if the {@code String} is a token;784* {@code false} if it is not785*/786private static boolean isToken(String value) {787int len = value.length();788789for (int i = 0; i < len; i++) {790char c = value.charAt(i);791792if (c < 0x20 || c >= 0x7f || tspecials.indexOf(c) != -1)793return false;794}795return true;796}797798/*799* Parse header string to cookie object.800*801* @param header802* header string; should contain only one NAME=VALUE pair803*804* @return an HttpCookie being extracted805*806* @throws IllegalArgumentException807* if header string violates the cookie specification808*/809private static HttpCookie parseInternal(String header,810boolean retainHeader)811{812HttpCookie cookie = null;813String namevaluePair = null;814815StringTokenizer tokenizer = new StringTokenizer(header, ";");816817// there should always have at least on name-value pair;818// it's cookie's name819try {820namevaluePair = tokenizer.nextToken();821int index = namevaluePair.indexOf('=');822if (index != -1) {823String name = namevaluePair.substring(0, index).trim();824String value = namevaluePair.substring(index + 1).trim();825if (retainHeader)826cookie = new HttpCookie(name,827stripOffSurroundingQuote(value),828header);829else830cookie = new HttpCookie(name,831stripOffSurroundingQuote(value));832} else {833// no "=" in name-value pair; it's an error834throw new IllegalArgumentException("Invalid cookie name-value pair");835}836} catch (NoSuchElementException ignored) {837throw new IllegalArgumentException("Empty cookie header string");838}839840// remaining name-value pairs are cookie's attributes841while (tokenizer.hasMoreTokens()) {842namevaluePair = tokenizer.nextToken();843int index = namevaluePair.indexOf('=');844String name, value;845if (index != -1) {846name = namevaluePair.substring(0, index).trim();847value = namevaluePair.substring(index + 1).trim();848} else {849name = namevaluePair.trim();850value = null;851}852853// assign attribute to cookie854assignAttribute(cookie, name, value);855}856857return cookie;858}859860/*861* assign cookie attribute value to attribute name;862* use a map to simulate method dispatch863*/864static interface CookieAttributeAssignor {865public void assign(HttpCookie cookie,866String attrName,867String attrValue);868}869static final java.util.Map<String, CookieAttributeAssignor> assignors =870new java.util.HashMap<>();871static {872assignors.put("comment", new CookieAttributeAssignor() {873public void assign(HttpCookie cookie,874String attrName,875String attrValue) {876if (cookie.getComment() == null)877cookie.setComment(attrValue);878}879});880assignors.put("commenturl", new CookieAttributeAssignor() {881public void assign(HttpCookie cookie,882String attrName,883String attrValue) {884if (cookie.getCommentURL() == null)885cookie.setCommentURL(attrValue);886}887});888assignors.put("discard", new CookieAttributeAssignor() {889public void assign(HttpCookie cookie,890String attrName,891String attrValue) {892cookie.setDiscard(true);893}894});895assignors.put("domain", new CookieAttributeAssignor(){896public void assign(HttpCookie cookie,897String attrName,898String attrValue) {899if (cookie.getDomain() == null)900cookie.setDomain(attrValue);901}902});903assignors.put("max-age", new CookieAttributeAssignor(){904public void assign(HttpCookie cookie,905String attrName,906String attrValue) {907try {908long maxage = Long.parseLong(attrValue);909if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED)910cookie.setMaxAge(maxage);911} catch (NumberFormatException ignored) {912throw new IllegalArgumentException(913"Illegal cookie max-age attribute");914}915}916});917assignors.put("path", new CookieAttributeAssignor(){918public void assign(HttpCookie cookie,919String attrName,920String attrValue) {921if (cookie.getPath() == null)922cookie.setPath(attrValue);923}924});925assignors.put("port", new CookieAttributeAssignor(){926public void assign(HttpCookie cookie,927String attrName,928String attrValue) {929if (cookie.getPortlist() == null)930cookie.setPortlist(attrValue == null ? "" : attrValue);931}932});933assignors.put("secure", new CookieAttributeAssignor(){934public void assign(HttpCookie cookie,935String attrName,936String attrValue) {937cookie.setSecure(true);938}939});940assignors.put("httponly", new CookieAttributeAssignor(){941public void assign(HttpCookie cookie,942String attrName,943String attrValue) {944cookie.setHttpOnly(true);945}946});947assignors.put("version", new CookieAttributeAssignor(){948public void assign(HttpCookie cookie,949String attrName,950String attrValue) {951try {952int version = Integer.parseInt(attrValue);953cookie.setVersion(version);954} catch (NumberFormatException ignored) {955// Just ignore bogus version, it will default to 0 or 1956}957}958});959assignors.put("expires", new CookieAttributeAssignor(){ // Netscape only960public void assign(HttpCookie cookie,961String attrName,962String attrValue) {963if (cookie.getMaxAge() == MAX_AGE_UNSPECIFIED) {964long delta = cookie.expiryDate2DeltaSeconds(attrValue);965cookie.setMaxAge(delta > 0 ? delta : 0);966}967}968});969}970private static void assignAttribute(HttpCookie cookie,971String attrName,972String attrValue)973{974// strip off the surrounding "-sign if there's any975attrValue = stripOffSurroundingQuote(attrValue);976977CookieAttributeAssignor assignor = assignors.get(attrName.toLowerCase());978if (assignor != null) {979assignor.assign(cookie, attrName, attrValue);980} else {981// Ignore the attribute as per RFC 2965982}983}984985static {986SharedSecrets.setJavaNetHttpCookieAccess(987new JavaNetHttpCookieAccess() {988public List<HttpCookie> parse(String header) {989return HttpCookie.parse(header, true);990}991992public String header(HttpCookie cookie) {993return cookie.header;994}995}996);997}998999/*1000* Returns the original header this cookie was constructed from, if it was1001* constructed by parsing a header, otherwise null.1002*/1003private String header() {1004return header;1005}10061007/*1008* Constructs a string representation of this cookie. The string format is1009* as Netscape spec, but without leading "Cookie:" token.1010*/1011private String toNetscapeHeaderString() {1012return getName() + "=" + getValue();1013}10141015/*1016* Constructs a string representation of this cookie. The string format is1017* as RFC 2965/2109, but without leading "Cookie:" token.1018*/1019private String toRFC2965HeaderString() {1020StringBuilder sb = new StringBuilder();10211022sb.append(getName()).append("=\"").append(getValue()).append('"');1023if (getPath() != null)1024sb.append(";$Path=\"").append(getPath()).append('"');1025if (getDomain() != null)1026sb.append(";$Domain=\"").append(getDomain()).append('"');1027if (getPortlist() != null)1028sb.append(";$Port=\"").append(getPortlist()).append('"');10291030return sb.toString();1031}10321033static final TimeZone GMT = TimeZone.getTimeZone("GMT");10341035/*1036* @param dateString1037* a date string in one of the formats defined in Netscape cookie spec1038*1039* @return delta seconds between this cookie's creation time and the time1040* specified by dateString1041*/1042private long expiryDate2DeltaSeconds(String dateString) {1043Calendar cal = new GregorianCalendar(GMT);1044for (int i = 0; i < COOKIE_DATE_FORMATS.length; i++) {1045SimpleDateFormat df = new SimpleDateFormat(COOKIE_DATE_FORMATS[i],1046Locale.US);1047cal.set(1970, 0, 1, 0, 0, 0);1048df.setTimeZone(GMT);1049df.setLenient(false);1050df.set2DigitYearStart(cal.getTime());1051try {1052cal.setTime(df.parse(dateString));1053if (!COOKIE_DATE_FORMATS[i].contains("yyyy")) {1054// 2-digit years following the standard set1055// out it rfc 62651056int year = cal.get(Calendar.YEAR);1057year %= 100;1058if (year < 70) {1059year += 2000;1060} else {1061year += 1900;1062}1063cal.set(Calendar.YEAR, year);1064}1065return (cal.getTimeInMillis() - whenCreated) / 1000;1066} catch (Exception e) {1067// Ignore, try the next date format1068}1069}1070return 0;1071}10721073/*1074* try to guess the cookie version through set-cookie header string1075*/1076private static int guessCookieVersion(String header) {1077int version = 0;10781079header = header.toLowerCase();1080if (header.indexOf("expires=") != -1) {1081// only netscape cookie using 'expires'1082version = 0;1083} else if (header.indexOf("version=") != -1) {1084// version is mandatory for rfc 2965/2109 cookie1085version = 1;1086} else if (header.indexOf("max-age") != -1) {1087// rfc 2965/2109 use 'max-age'1088version = 1;1089} else if (startsWithIgnoreCase(header, SET_COOKIE2)) {1090// only rfc 2965 cookie starts with 'set-cookie2'1091version = 1;1092}10931094return version;1095}10961097private static String stripOffSurroundingQuote(String str) {1098if (str != null && str.length() > 2 &&1099str.charAt(0) == '"' && str.charAt(str.length() - 1) == '"') {1100return str.substring(1, str.length() - 1);1101}1102if (str != null && str.length() > 2 &&1103str.charAt(0) == '\'' && str.charAt(str.length() - 1) == '\'') {1104return str.substring(1, str.length() - 1);1105}1106return str;1107}11081109private static boolean equalsIgnoreCase(String s, String t) {1110if (s == t) return true;1111if ((s != null) && (t != null)) {1112return s.equalsIgnoreCase(t);1113}1114return false;1115}11161117private static boolean startsWithIgnoreCase(String s, String start) {1118if (s == null || start == null) return false;11191120if (s.length() >= start.length() &&1121start.equalsIgnoreCase(s.substring(0, start.length()))) {1122return true;1123}11241125return false;1126}11271128/*1129* Split cookie header string according to rfc 2965:1130* 1) split where it is a comma;1131* 2) but not the comma surrounding by double-quotes, which is the comma1132* inside port list or embedded URIs.1133*1134* @param header1135* the cookie header string to split1136*1137* @return list of strings; never null1138*/1139private static List<String> splitMultiCookies(String header) {1140List<String> cookies = new java.util.ArrayList<>();1141int quoteCount = 0;1142int p, q;11431144for (p = 0, q = 0; p < header.length(); p++) {1145char c = header.charAt(p);1146if (c == '"') quoteCount++;1147if (c == ',' && (quoteCount % 2 == 0)) {1148// it is comma and not surrounding by double-quotes1149cookies.add(header.substring(q, p));1150q = p + 1;1151}1152}11531154cookies.add(header.substring(q));11551156return cookies;1157}1158}115911601161