a 97a+@sndZddlmZddlmZddlmZddlmZddlmZmZm Z m Z m Z ddl m Z mZgdZdd lZdd lZdd lZerde_dd lZdd lmZmZmZdd lmZz dd lZWneydd lZYn0dd lm Z d Z!d a"ddZ#e eZ$dZ%ddZ&dZ'ddZ(gdZ)gdZ*gZ+e*D]Z,e+-e,.q.dmddZ/dnddZ0d d d d dZ1e2dejZ3ddZ4d d!Z5e2d"ejZ6e2d#ej7ejBZ8e2d$ej9ejBZ:d%d&Z;e2d'ej9ejBZe2d,Z?e2d-Z@e2d.ZAe2d/ZBd0d1ZCe2d2ZDd3d4ZEd5d6ZFd7d8ZGe2d9ejZHd:d;ZIdd?ZKd@dAZLe2dBejZMdCdDZNdEdFZOdGdHZPdIdJZQdKZRe2dLZSdMdNZTdOdPZUdQdRZVdSdTZWGdUdVdVeXZYGdWdXdXeXZZGdYdZdZeZZ[d[d\Z\d]d^Z]Gd_d`d`eXZ^GdadbdbeXZ_Gdcdddde`ZaGdedfdfe_ZbdgdhZcGdidjdjebZdGdkdldlebZed S)oaHTTP cookie handling for web clients. This is a backport of the Py3.3 ``http.cookiejar`` module for python-future. This module has (now fairly distant) origins in Gisle Aas' Perl module HTTP::Cookies, from the libwww-perl library. Docstrings, comments and debug strings in this code refer to the attributes of the HTTP cookie system as cookie-attributes, to distinguish them clearly from Python attributes. Class diagram (note that BSDDBCookieJar and the MSIE* classes are not distributed with the Python standard library, but are available from http://wwwsearch.sf.net/): CookieJar____ / \ \ FileCookieJar \ \ / | \ \ \ MozillaCookieJar | LWPCookieJar \ \ | | \ | ---MSIEBase | \ | / | | \ | / MSIEDBCookieJar BSDDBCookieJar |/ MSIECookieJar )unicode_literals)print_function)division)absolute_import)filterintmapopenstr) as_native_strPY2)Cookie CookieJar CookiePolicyDefaultCookiePolicy FileCookieJar LWPCookieJar LoadErrorMozillaCookieJarN)urlparseurlsplitquote) HTTP_PORT)timegmFcGs(tsdStsddl}|datj|S)Nrzhttp.cookiejar)debugloggerlogging getLogger)argsrrz/private/var/folders/s6/9n5zrl012gv99k63s4q6ccsd4s6mqz/T/pip-target-f5cq3f2q/lib/python/future/backports/http/cookiejar.py_debug:s  r!zQa filename was not supplied (nor was the CookieJar instance initialised with one)cCsJddl}ddl}ddl}|}|d||}|jd|dddS)Nrzhttp.cookiejar bug! %s) stacklevel)iowarnings tracebackStringIO print_excgetvaluewarn)r$r%r&fmsgrrr _warn_unhandled_exceptionHs  r-icCs|dd\}}}}}}|tkrd|kr4dkrnnhd|krLdkrnnPd|krddkrnn8d|kr|dkrnn d|krdkrnnt|SdSdS) N r;=) EPOCH_YEARr)ttyearmonthmdayhourminsecrrr _timegmWs 8   r=)MonTueWedThuFriSatSun) JanFebMarAprMayJunJulAugSepOctNovDeccCs@|durtj}n tj|}d|j|j|j|j|j|jfS)aHReturn a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ", representing Universal Time (UTC, aka GMT). An example of this format is: 1994-11-24 08:49:37Z Nz%04d-%02d-%02d %02d:%02d:%02dZ) datetimeutcnowutcfromtimestampr7r8dayr:minutesecondtdtrrr time2isozes   rZcCsR|durtj}n tj|}dt||jt|jd|j|j |j |j fS)zReturn a string representing time in seconds since epoch, t. If the function is called without an argument, it will use the current time. The format of the returned string is like this: Wed, DD-Mon-YYYY HH:MM:SS GMT Nz"%s %02d-%s-%04d %02d:%02d:%02d GMTr/) rQrRrSDAYSweekdayrTMONTHSr8r7r:rUrVrWrrr time2netscapexs   r^)GMTUTCUTZz^([-+])?(\d\d?):?(\d\d)?$cCsjd}|tvrd}nTt|}|rfdt|d}|drR|dt|d}|ddkrf| }|S)Nrir"<r/-) UTC_ZONES TIMEZONE_REsearchrgroup)tzoffsetmrrr offset_from_tz_strings  rmc Cs|zt|d}WnZtypz t|}WntyFYYdS0d|kr\dkrfnn|}nYdSYn0|dur~d}|durd}|durd}t|}t|}t|}t|}t|}|dkr$ttd}|d} |} ||| }| | } t| dkr$| dkr|d}n|d}t|||||||f} | durx|durRd}| }t |} | durpdS| | } | S)Nr/r0rid2r`) MONTHS_LOWERindexlower ValueErrorrtime localtimeabsr=upperrm) rTmonyrhrr;r<rjimoncur_yrrltmprXrkrrr _str2timesJ             r~zV^[SMTWF][a-z][a-z], (\d\d) ([JFMASOND][a-z][a-z]) (\d\d\d\d) (\d\d):(\d\d):(\d\d) GMT$z+^(?:Sun|Mon|Tue|Wed|Thu|Fri|Sat)[a-z]*,?\s*a^ (\d\d?) # day (?:\s+|[-\/]) (\w+) # month (?:\s+|[-\/]) (\d+) # year (?: (?:\s+|:) # separator before clock (\d\d?):(\d\d) # hour:min (?::(\d\d))? # optional seconds )? # optional clock \s* ([-+]?\d{2,4}|(?![APap][Mm]\b)[A-Za-z]+)? # timezone \s* (?:\(\w+\))? # ASCII representation of timezone in parens. \s*$c Cst|}|rl|}t|dd}t|d|t|dt|dt|dt|df}t|S| }t d|d}dgd \}}}}}} } t |}|dur|\}}}}}} } ndSt |||||| | S) aReturns time in seconds since epoch of time represented by a string. Return value is an integer. None is returned if the format of str is unrecognized, the time is outside the representable range, or the timezone string is not recognized. If the string contains no timezone, UTC is assumed. The timezone in the string may be numerical (like "-0800" or "+0100") or a string timezone (like "UTC", "GMT", "BST" or "EST"). Currently, only the timezone strings equivalent to UTC (zero offset) are known to the function. The function loosely parses the following formats: Wed, 09 Feb 1994 22:23:32 GMT -- HTTP format Tuesday, 08-Feb-94 14:15:29 GMT -- old rfc850 HTTP format Tuesday, 08-Feb-1994 14:15:29 GMT -- broken rfc850 HTTP format 09 Feb 1994 22:23:32 GMT -- HTTP format (no weekday) 08-Feb-94 14:15:29 GMT -- rfc850 format (no weekday) 08-Feb-1994 14:15:29 GMT -- broken rfc850 format (no weekday) The parser ignores leading and trailing whitespace. The time may be absent. If the year is given with only 2 digits, the function will select the century that makes the year closest to the current date. r/r"rrcN)STRICT_DATE_RErhgroupsrprqrrrfloatr=lstrip WEEKDAY_REsubLOOSE_HTTP_DATE_REr~) textrlgrxr6rTryrzr;r<rjrrr http2times   ra^ (\d{4}) # year [-\/]? (\d\d?) # numerical month [-\/]? (\d\d?) # day (?: (?:\s+|[-:Tt]) # separator before clock (\d\d?):?(\d\d) # hour:min (?::?(\d\d(?:\.\d*)?))? # optional seconds (and fractional) )? # optional clock \s* ([-+]?\d\d?:?(:?\d\d)? |Z|z)? # timezone (Z is "zero meridian", i.e. GMT) \s*$c Csd|}dgd\}}}}}}}t|}|durL|\}}}}}}}} ndSt|||||||S)av As for http2time, but parses the ISO 8601 formats: 1994-02-03 14:15:29 -0100 -- ISO 8601 format 1994-02-03 14:15:29 -- zone is optional 1994-02-03 -- only date 1994-02-03T14:15:29 -- Use T as separator 19940203T141529Z -- ISO 8601 compact format 19940203 -- only date Nr)r ISO_DATE_RErhrr~) rrTrxryrzr;r<rjrl_rrr iso2time0s  rcCs*|d\}}|jd||j|dS)z)Return unmatched part of re.Match object.rN)spanstring)matchstartendrrr unmatchedQsrz^\s*([^=\s;,]+)z&^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"z^\s*=\s*([^\s;,]*)z\\(.)c Cs0t|trJg}|D]}|}g}|rt|}|rt|}|d}t|}|rxt|}|d}td|}n.t |}|rt|}|d}| }nd}| ||fq$| dr| dd}|r| |g}q$tdd|\}} | dksJd|||f|}q$|r| |q|S) amParse header values into a list of lists containing key,value pairs. The function knows how to deal with ",", ";" and "=" as well as quoted values after "=". A list of space separated tokens are parsed as if they were separated by ";". If the header_values passed as argument contains multiple values, then they are treated as if they were a single value separated by comma ",". This means that this function is useful for parsing header fields that follow this syntax (BNF as from the HTTP/1.1 specification, but we relax the requirement for tokens). headers = #header header = (token | parameter) *( [";"] (token | parameter)) token = 1* separators = "(" | ")" | "<" | ">" | "@" | "," | ";" | ":" | "\" | <"> | "/" | "[" | "]" | "?" | "=" | "{" | "}" | SP | HT quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) qdtext = > quoted-pair = "\" CHAR parameter = attribute "=" value attribute = token value = token | quoted-string Each header is represented by a list of key/value pairs. The value for a simple token (not part of a parameter) is None. Syntactically incorrect headers will not necessarily be parsed as you would want. This is easier to describe with some examples: >>> split_header_words(['foo="bar"; port="80,81"; discard, bar=baz']) [[('foo', 'bar'), ('port', '80,81'), ('discard', None)], [('bar', 'baz')]] >>> split_header_words(['text/html; charset="iso-8859-1"']) [[('text/html', None), ('charset', 'iso-8859-1')]] >>> split_header_words([r'Basic realm="\"foo\bar\""']) [[('Basic', None), ('realm', '"foobar"')]] r/z\1N,z^[=\s;]*rrz&split_header_words bug: '%s', '%s', %s) isinstancer HEADER_TOKEN_RErhrriHEADER_QUOTED_VALUE_REHEADER_ESCAPE_RErHEADER_VALUE_RErstripappendr startswithresubn) header_valuesresultr orig_textpairsrlnamevaluenon_junk nr_junk_charsrrr split_header_wordsZsF-         r([\"\\])cCs|g}|D]h}g}|D]F\}}|durPtd|sDtd|}d|}d||f}||q|r|d|qd|S)aDo the inverse (almost) of the conversion done by split_header_words. Takes a list of lists of (key, value) pairs and produces a single header value. Attribute values are quoted if needed. >>> join_header_words([[("text/plain", None), ("charset", "iso-8859/1")]]) 'text/plain; charset="iso-8859/1"' >>> join_header_words([[("text/plain", None)], [("charset", "iso-8859/1")]]) 'text/plain, charset="iso-8859/1"' Nz^\w+$\\\1z"%s"%s=%s; , )rrhHEADER_JOIN_ESCAPE_RErrjoin)listsheadersrattrkvrrr join_header_wordss      rcCs0|dr|dd}|dr,|dd}|S)N"r/)rendswithrrrr strip_quotess     rc Csd}g}|D]}g}d}ttd|D]\}}|}|dkrBq(d|vrV|d}} ntd|d\}} |}|d kr|} | |vr| }|d krt| } d }|d krtt| } ||| fq(|r |s|d ||q |S)a5Ad-hoc parser for Netscape protocol cookie-attributes. The old Netscape cookie format for Set-Cookie can for instance contain an unquoted "," in the expires field, so we have to use this ad-hoc parser instead of split_header_words. XXX This may not make the best possible effort to parse all the crap that Netscape Cookie headers contain. Ronald Tschalar's HTTPClient parser is probably better, so could do worse than following that if this ever gives any trouble. Currently, this is also used for parsing RFC 2109 cookies. )expiresdomainpathsecureversionportmax-ageFz;\s*r=Nz\s*=\s*r/rrTr)r0) enumeratersplitrrrrrrr) ns_headers known_attrsr ns_headerr version_setiiparamrrlcrrr parse_ns_headerss6     rz\.\d+$cCs:t|rdS|dkrdS|ddks2|ddkr6dSdS)z*Return True if text is a host domain name.Frr.rTIPV4_RErhrrrr is_HDNs rcCsl|}|}||krdSt|s(dS||}|dksB|dkrFdS|dsTdSt|ddshdSdS)aReturn True if domain A domain-matches domain B, according to RFC 2965. A and B may be host domain names or IP addresses. RFC 2965, section 1: Host names can be specified either as an IP address or a HDN string. Sometimes we compare one host name with another. (Such comparisons SHALL be case-insensitive.) Host A's name domain-matches host B's if * their host name strings string-compare equal; or * A is a HDN string and has the form NB, where N is a non-empty name string, B has the form .B', and B' is a HDN string. (So, x.y.com domain-matches .Y.com but not Y.com.) Note that domain-match is not a commutative operation: a.b.c.com domain-matches .c.com, but not the reverse. TFrrrr/N)rrrrfindr)ABirrr domain_matchs  rcCst|rdSdS)zdReturn True if text is a sort-of-like a host domain name. For accepting/blocking domains. FTrrrrr liberal_is_HDN;s rcCs`|}|}t|r t|s0||kr,dSdS|d}|rL||rLdS|s\||kr\dSdS)z\For blocking/accepting domains. A and B may be host domain names or IP addresses. TFr)rrrrr)rr initial_dotrrr user_domain_matchEs  rz:\d+$cCs>|}t|d}|dkr(|dd}td|d}|S)zReturn request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. r/rHost) get_full_urlr get_header cut_port_rerrr)requesturlhostrrr request_hostZs   rcCs4t|}}|ddkr,t|s,|d}||fS)zzReturn a tuple (request-host, effective request-host name). As defined by RFC 2965, except both are lowercased. rr.local)rfindrrh)rerhnreq_hostrrr eff_request_hostjs rcCs0|}t|}t|j}|ds,d|}|S)z6Path component of request-URI, as defined by RFC 2965./)rr escape_pathrr)rrpartsrrrr request_pathus   rcCs^|j}|d}|dkrV||dd}z t|WqZtyRtd|YdS0nt}|S)N:rr/znonnumeric port: '%s')rrrrsr!DEFAULT_HTTP_PORT)rrrrrrr request_ports     rz%/;:@&=+$,!~*'()z%([0-9a-fA-F][0-9a-fA-F])cCsd|dS)Nz%%%sr/)rirw)rrrr uppercase_escaped_charsrcCst|t}tt|}|S)zEEscape any invalid characters in HTTP URL, and uppercase all escapes.)rHTTP_PATH_SAFEESCAPED_CHAR_RErr)rrrr rs  rcCsP|d}|dkrL||dd}|d}t|rL|dksD|dkrLd|S|S)aBReturn reach of host h, as defined by RFC 2965, section 1. The reach R of a host name H is defined as follows: * If - H is the host domain name of a host; and, - H has the form A.B; and - A has no embedded (that is, interior) dots; and - B has at least one embedded dot, or B is the string "local". then the reach of H is .B. * Otherwise, the reach of H is H. >>> reach("www.acme.com") '.acme.com' >>> reach("acme.com") 'acme.com' >>> reach("acme.local") '.local' rrr/Nlocal)rr)hrbrrr reachs  rcCs&t|}t|t|sdSdSdS)z RFC 2965, section 3.3.6: An unverifiable transaction is to a third-party host if its request- host U does not domain-match the reach R of the request-host O in the origin transaction. TFN)rrrget_origin_req_host)rrrrr is_third_partys rc@sTeZdZdZdddZddZddd Zd d Zdd d ZddZ e ddZ dS)r aHTTP Cookie. This class represents both Netscape and RFC 2965 cookies. This is deliberately a very simple class. It just holds attributes. It's possible to construct Cookie instances that don't comply with the cookie standards. CookieJar.make_cookies is the factory function for Cookie objects -- it deals with cookie parsing, supplying defaults, and normalising to the representation used in this class. CookiePolicy is responsible for checking them to see whether they should be accepted from and returned to the server. Note that the port may be present in the headers, but unspecified ("Port" rather than"Port=80", for example); if this is the case, port is None. FcCs|durt|}| dur t| } |dur8|dur8td||_||_||_||_||_||_||_ ||_ | |_ | |_ | |_ | |_| |_||_||_||_t||_dS)NTz-if port is None, port_specified must be false)rrsrrrrport_specifiedrrrdomain_specifieddomain_initial_dotrpath_specifiedrrdiscardcomment comment_urlrfc2109copy_rest)selfrrrrrrrrrrrrrrrrestrrrr __init__s*  zCookie.__init__cCs ||jvSNr)rrrrr has_nonstandard_attrszCookie.has_nonstandard_attrNcCs|j||Sr)rget)rrdefaultrrr get_nonstandard_attrszCookie.get_nonstandard_attrcCs||j|<dSrr)rrrrrr set_nonstandard_attrszCookie.set_nonstandard_attrcCs,|durt}|jdur(|j|kr(dSdSNTF)rtr)rnowrrr is_expiredszCookie.is_expiredcCsX|jdurd}n d|j}|j||j}|jdurFd|j|jf}n|j}d||fS)Nrrrz)rrrrr)rplimit namevaluerrr __str__s  zCookie.__str__cCszg}dD]:}t||}t|tr(t|}|td|t|fq|dt|j|dt|jdd|S)N)rrrrrrrrrrrrrrrrzrest=%sz rfc2109=%sz Cookie(%s)r)getattrrr rreprrrr)rrrrrrr __repr__(s  zCookie.__repr__)F)N)N) __name__ __module__ __qualname____doc__rrr r rrr rrrrr r s *   r c@s0eZdZdZddZddZddZdd Zd S) ra Defines which cookies get accepted from and returned to server. May also modify cookies, though this is probably a bad idea. The subclass DefaultCookiePolicy defines the standard rules for Netscape and RFC 2965 cookies -- override that if you want a customised policy. cCs tdS)zReturn true if (and only if) cookie should be accepted from server. Currently, pre-expired cookies never get this far -- the CookieJar class deletes such cookies itself. NNotImplementedErrorrcookierrrr set_okFszCookiePolicy.set_okcCs tdS)zAReturn true if (and only if) cookie should be returned to server.Nrrrrr return_okOszCookiePolicy.return_okcCsdS)zMReturn false if cookies should not be returned, given cookie domain. Tr)rrrrrr domain_return_okSszCookiePolicy.domain_return_okcCsdS)zKReturn false if cookies should not be returned, given cookie path. Tr)rrrrrr path_return_okXszCookiePolicy.path_return_okN)rrrrrrr r!rrrr r=s  rc @seZdZdZdZdZdZdZeeBZdddddddddeddf d d Z d d Z d dZ ddZ ddZ ddZddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd3d4Zd5d6ZdS)7rzBImplements the standard rules for accepting and returning cookies.r/r"rrNTFc Csp||_||_||_||_||_||_| |_| |_| |_| |_ |durPt ||_ nd|_ |durft |}||_ dS)zAConstructor arguments should be passed as keyword arguments only.Nr) netscaperfc2965rfc2109_as_netscape hide_cookie2 strict_domainstrict_rfc2965_unverifiablestrict_ns_unverifiablestrict_ns_domainstrict_ns_set_initial_dollarstrict_ns_set_pathtuple_blocked_domains_allowed_domains) rblocked_domainsallowed_domainsr"r#r$r%r&r'r(r)r*r+rrr rhs  zDefaultCookiePolicy.__init__cCs|jS)z4Return the sequence of blocked domains (as a tuple).)r-rrrr r/sz#DefaultCookiePolicy.blocked_domainscCst||_dS)z$Set the sequence of blocked domains.N)r,r-)rr/rrr set_blocked_domainssz'DefaultCookiePolicy.set_blocked_domainscCs |jD]}t||rdSqdSr )r-r)rrblocked_domainrrr is_blockeds  zDefaultCookiePolicy.is_blockedcCs|jS)z=Return None, or the sequence of allowed domains (as a tuple).)r.r1rrr r0sz#DefaultCookiePolicy.allowed_domainscCs|durt|}||_dS)z-Set the sequence of allowed domains, or None.N)r,r.)rr0rrr set_allowed_domainssz'DefaultCookiePolicy.set_allowed_domainscCs.|jdurdS|jD]}t||rdSqdS)NFT)r.r)rrallowed_domainrrr is_not_alloweds    z"DefaultCookiePolicy.is_not_allowedcCsNtd|j|j|jdusJdD]&}d|}t||}|||s"dSq"dS)z If you override .set_ok(), be sure to call this method. If it returns false, so should your subclass (assuming your subclass wants to be more strict about which cookies to accept).  - checking cookie %s=%sN)r verifiabilityrrrrset_ok_FTr!rrrrrrnfn_namefnrrr rs  zDefaultCookiePolicy.set_okcCsZ|jdurtd|j|jdS|jdkr:|js:tddS|jdkrV|jsVtddSdS)Nz0 Set-Cookie2 without version attribute (%s=%s)Fr$ RFC 2965 cookies are switched off$ Netscape cookies are switched offT)rr!rrr#r"rrrr set_ok_versions z"DefaultCookiePolicy.set_ok_versioncCsJ|jrFt|rF|jdkr*|jr*tddS|jdkrF|jrFtddSdSNrz> third-party RFC 2965 cookie during unverifiable transactionFz> third-party Netscape cookie during unverifiable transactionT unverifiablerrr'r!r(rrrr set_ok_verifiabilitysz(DefaultCookiePolicy.set_ok_verifiabilitycCs0|jdkr,|jr,|jdr,td|jdSdS)Nr$z' illegal name (starts with '$'): '%s'FT)rr*rrr!rrrr set_ok_names   zDefaultCookiePolicy.set_ok_namecCsJ|jrFt|}|jdks(|jdkrF|jrF||jsFtd|j|dSdS)Nrz7 path attribute %s is not a prefix of request path %sFT)rrrr+rrr!)rrrreq_pathrrr set_ok_paths  zDefaultCookiePolicy.set_ok_pathc Cs||jrtd|jdS||jr8td|jdS|jrt|\}}|j}|jr|ddkr|d}|dd|}|dkr||dd}||d|} | dvrt |dkrtd |dS| dr|dd} n|} | ddk} | s|d krtd |dS|j dkrX||sX| dsXd||sXtd ||dS|j dksr|j|j@rt||std ||dS|j dks|j|j@r|dt | } | ddkrt|std| |dSdS)N" domain %s is in user block-listF& domain %s is not in user allow-listrr"rr/)coaccomeduorgnetgovmilraerobizcatcoopinfojobsmobimuseumrprotraveleuz& country-code second level domain %srz/ non-local domain %s contains no embedded dotzO effective request-host %s (even with added initial dot) does not end with %sz5 effective request-host %s does not domain-match %sz. host prefix %s for domain %s contains a dotT)r4rr!r7rrr&countrrrlenrrrrr)DomainRFC2965MatchrDomainStrictNoDotsrrh) rrrrrrrjtldsldundotted_domain embedded_dots host_prefixrrr set_ok_domainsv                  z!DefaultCookiePolicy.set_ok_domainc Cs|jrt|}|durd}nt|}|jdD]>}z t|Wn ty`td|YdS0||kr0qq0td||jdSdS)N80rz bad port %s (not numeric)Fz$ request port (%s) not found in %sT)rrr rrrrsr!rrrreq_portrrrr set_ok_port$s$    zDefaultCookiePolicy.set_ok_portcCs@td|j|jdD]&}d|}t||}|||sdSqdS)z If you override .return_ok(), be sure to call this method. If it returns false, so should your subclass (assuming your subclass wants to be more strict about which cookies to return). r8)rr9rrrr return_ok_FTr;r<rrr r9s   zDefaultCookiePolicy.return_okcCs<|jdkr|jstddS|jdkr8|js8tddSdS)Nrr@FrAT)rr#r!r"rrrr return_ok_versionKsz%DefaultCookiePolicy.return_ok_versioncCsJ|jrFt|rF|jdkr*|jr*tddS|jdkrF|jrFtddSdSrCrDrrrr return_ok_verifiabilityTsz+DefaultCookiePolicy.return_ok_verifiabilitycCs |jr|jdkrtddSdS)Nhttpsz( secure cookie with non-secure requestFT)rtyper!rrrr return_ok_secure`sz$DefaultCookiePolicy.return_ok_securecCs||jrtddSdS)Nz cookie expiredFT)r_nowr!rrrr return_ok_expiresfs z%DefaultCookiePolicy.return_ok_expirescCsN|jrJt|}|durd}|jdD]}||kr&qJq&td||jdSdS)Nrkrz0 request port %s does not match cookie port %sFT)rrrr!rlrrr return_ok_portlsz"DefaultCookiePolicy.return_ok_portcCst|\}}|j}|jdkrB|j|j@rB|jsB||krBtddS|jdkrft||sftd||dS|jdkrd||std||dSdS)NrzQ cookie with unspecified domain does not string-compare equal to request domainFzQ effective request-host name %s does not domain-match RFC 2965 cookie domain %srz; request-host %s does not match Netscape cookie domain %sT) rrrr)DomainStrictNonDomainrr!rr)rrrrrrrrr return_ok_domainzs,   z$DefaultCookiePolicy.return_ok_domaincCs|t|\}}|dsd|}|ds0d|}||sH||sHdS||r`td|dS||rxtd|dSdS)NrFrKrLT)rrrr4r!r7)rrrrrrrr r s       z$DefaultCookiePolicy.domain_return_okcCs0td|t|}||s,td||dSdS)Nz- checking cookie path=%sz %s does not path-match %sFT)r!rr)rrrrIrrr r!s    z"DefaultCookiePolicy.path_return_ok) rrrrrcrxrb DomainLiberal DomainStrictrr/r2r4r0r5r7rrBrFrHrJrjrnrrprqrtrvrwryr r!rrrr r^sN !   ;  rcCst|}t|j|Sr)sortedkeysrr)adictr}rrr vals_sorted_by_keys rc csZt|}|D]H}d}z |jWnty0Yn0d}t|D] }|Vq>|s |Vq dS)zBIterates over nested mapping, depth-first, in sorted order by key.FTN)ritemsAttributeError deepvalues)mappingvaluesobjZsubobjrrr rs   rc@s eZdZdS)AbsentNrrrrrrr rrc@seZdZdZedZedZedZedZ edZ edej Z d3d d Z d d Zd dZddZddZddZddZddZddZddZddZdd Zd!d"Zd#d$Zd4d%d&Zd'd(Zd)d*Zd+d,Zd-d.Ze d/d0Z!d1d2Z"dS)5rzCollection of HTTP cookies. You may not need to know about this class: try urllib.request.build_opener(HTTPCookieProcessor).open(url). z\Wrz\.?[^.]*z[^.]*z^\.+z^\#LWP-Cookies-(\d+\.\d+)NcCs(|durt}||_t|_i|_dSr)r_policy _threadingRLock _cookies_lock_cookiesrpolicyrrr rs  zCookieJar.__init__cCs ||_dSr)rrrrr set_policyszCookieJar.set_policycCsg}|j||sgStd||j|}|D]T}|j||sFq2||}|D].}|j||srtdqVtd||qVq2|S)Nz!Checking %s for cookies to returnz not returning cookiez it's a match) rr r!rr}r!rrr)rrrcookiescookies_by_pathrcookies_by_namerrrr _cookies_for_domains     zCookieJar._cookies_for_domaincCs*g}|jD]}||||q|S)z2Return a list of cookies to be returned to server.)rr}extendr)rrrrrrr _cookies_for_requestszCookieJar._cookies_for_requestc Cs<|jddddd}g}|D]}|j}|sHd}|dkrH|d||jdurz|j|jrz|dkrz|jd |j}n|j}|jdur||jn|d |j|f|dkr|j r|d |j |j d r|j }|j s| d r|d d}|d||jdurd}|jr,|d|j}||q|S)zReturn a list of cookie-attributes to be returned to server. like ['foo="bar"; $Path="/"', ...] The $Version attribute is also added when appropriate (currently only once per request). cSs t|jSr)rar)arrr rz)CookieJar._cookie_attrs..T)keyreverseFrz $Version=%sNrrz $Path="%s"rr/z $Domain="%s"z$Portz="%s")sortrrr non_word_rerhquote_rerrrrrrrrr) rrrattrsrrrrrrrr _cookie_attrssF        zCookieJar._cookie_attrscCstd|jztt|j_|_||}||}|r^| ds^| dd ||jj r|jj s| ds|D]}|jdkr|| ddqq|W|jn |j0|dS)zAdd correct Cookie: header to request (urllib.request.Request object). The Cookie2 header is also added unless policy.hide_cookie2 is true. add_cookie_headerr rCookie2r/z $Version="1"N)r!racquirerrtrrurr has_headeradd_unredirected_headerrr#r%rreleaseclear_expired_cookies)rrrrrrrr r6s(       zCookieJar.add_cookie_headerc Csg}d}d}|D]x}|d\}}d}d} i} i} |ddD].\} } | }||vs`||vrd|} | |vrx| durxd} | | vrq>| dkr| durtd d} qp| } | d kr|rq>| durtd q>| d krd}z t| } Wn(tytd d} YqpYn0d } |j| } | |vs2| |vrf| dur\| dvr\td| d} qp| | | <q>| | | <q>| rxq|||| | fq|S)aReturn list of tuples containing normalised cookie information. attrs_set is the list of lists of key,value pairs extracted from the Set-Cookie or Set-Cookie2 headers. Tuples are name, value, standard, rest, where name and value are the cookie name and value, standard is a dictionary containing the standard cookie-attributes (discard, secure, version, expires or max-age, domain, path and port) and rest is a dictionary containing the rest of the cookie-attributes. )rr)rrrrrrr commenturlrFr/NTrz% missing value for domain attributerzM missing or invalid value for expires attribute: treating as session cookierz? missing or invalid (non-numeric) value for max-age attribute)rrrz! missing value for %s attribute)rrr!rrsrur)r attrs_set cookie_tuples boolean_attrs value_attrs cookie_attrsrr max_age_set bad_cookiestandardrrrrrrr _normalized_cookie_tuplesWsh          z#CookieJar._normalized_cookie_tuplescCs"|\}}}}|dt}|dt}|dt} |dt} |dd} | durrz t| } WntypYdS0|dd} |dd} |d d}|d d}|tur|d krd }t|}nXd}t|}|d }|dkr| dkr|d|}n|d|d}t|dkrd }|tu}d}|r8t| d}|turTt |\}}|}n| dshd|}d}| tur| durt |} nd }t dd | } nd} | turd} d } nF| |jkrz||||WntyYn0td|||dSt| ||| ||||||| | | |||S)NrrrrrrFrrrrTrrrr/rz\s+z2Expiring cookie, domain='%s', path='%s', name='%s')rrrrsrrrraboolrrrrrruclearKeyErrorr!r )rtuprrrrrrrrrrrrrrrrrrrrrrrr _cookie_from_cookie_tuples                       z#CookieJar._cookie_from_cookie_tuplecCs6||}g}|D]}|||}|r||q|Sr)rrr)rrrrrrrrrr _cookies_from_attrs_sets   z!CookieJar._cookies_from_attrs_setcCsHt|jdd}|dur |jj }|D]}|jdkr$d|_|r$d|_q$dS)Nr$r/Tr)rrr#rr)rr rfc2109_as_nsrrrr _process_rfc2109_cookiess  z"CookieJar._process_rfc2109_cookiesc Cs |}|dg}|dg}|jj}|jj}|s8|rP|s@|rP|sH|rP|sT|sTgSz|t||}Wntytg}Yn0|r|rz|t ||} Wntytg} Yn0| | |r i} |D]} d| | j | j | j f<q| fdd} t| | } | r|| |S)zAReturn sequence of Cookie objects extracted from response object.z Set-Cookie2z Set-CookieNcSs|j|j|jf}||vSr)rrr) ns_cookielookuprrrr no_matching_rfc2965Usz3CookieJar.make_cookies..no_matching_rfc2965)rYget_allrr#r"rr Exceptionr-rrrrrrr) rresponserr rfc2965_hdrsns_hdrsr#r"r ns_cookiesrrrrrr make_cookies)sX           zCookieJar.make_cookiescCsX|jz|durX|durJtd|j||=n|durj|j|=ni|_dS)aClear some cookies. Invoking this method without arguments will clear all cookies. If given a single argument, only cookies belonging to that domain will be removed. If given two arguments, cookies belonging to the specified path within that domain are removed. If given three arguments, then the cookie with the specified name, path and domain is removed. Raises KeyError if no matching cookie exists. Nz8domain and path must be given to remove a cookie by namez.domain must be given to remove cookies by path)rsr)rrrrrrr rs  zCookieJar.clearcCsN|jz2|D]}|jr||j|j|jqW|jn |j0dS)zDiscard all session cookies. Note that the .save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument. N)rrrrrrrr)rrrrr clear_session_cookiess  zCookieJar.clear_session_cookiescCsZ|jz>t}|D]"}||r||j|j|jqW|jn |j0dS)aDiscard all expired cookies. You probably don't need to call this method: expired cookies are never sent back to the server (provided you're using DefaultCookiePolicy), this method is called by CookieJar itself every so often, and the .save() method won't save expired cookies anyway (unless you ask otherwise by passing a true ignore_expires argument). N) rrrtrrrrrr)rr rrrr rs  zCookieJar.clear_expired_cookiescCs t|jSr)rrr1rrr __iter__szCookieJar.__iter__cCsd}|D] }|d}q|S)z#Return number of contained cookies.rr/r)rrrrrr __len__szCookieJar.__len__cCs0g}|D]}|t|qd|jd|fSNz<%s[%s]>r)rr __class__rrrrrrr rszCookieJar.__repr__cCs0g}|D]}|t|qd|jd|fSr)rr rrrrrr rszCookieJar.__str__)N)NNN)#rrrrrcompilerrstrict_domain_re domain_redots_reASCIImagic_rerrrrrrrrrrrrrrrrrrrr rrrrrr rs:      ;!a\  6    rc@s eZdZdS)rNrrrrr rrrc@s8eZdZdZd ddZd ddZddd Zdd d ZdS)rz6CookieJar that can be loaded from and saved to a file.NFcCsJt|||dur6z |dWntdYn0||_t||_dS)z} Cookies are NOT loaded from the named file until either the .load() or .revert() method is called. Nrzfilename must be string-like)rrrsfilenamer delayload)rrrrrrr rs  zFileCookieJar.__init__cCs tdS)zSave cookies to a file.Nr)rrignore_discardignore_expiresrrr saveszFileCookieJar.savecCsV|dur"|jdur|j}nttt|}z|||||W|n |0dS)zLoad cookies from a file.N)rrsMISSING_FILENAME_TEXTr _really_loadcloserrrrr+rrr loadszFileCookieJar.loadc Cs|dur"|jdur|j}ntt|jzRt|j}i|_z||||Wnt t fyp||_Yn0W|j n |j 0dS)zClear all cookies and reload cookies from a saved file. Raises LoadError (or IOError) if reversion is not successful; the object's state will not be altered if this happens. N) rrsrrrrdeepcopyrrrIOErrorr)rrrr old_staterrr reverts   zFileCookieJar.revert)NFN)NFF)NFF)NFF)rrrrrrrrrrrr rs   rcCs |j|jfd|jfd|jfg}|jdur8|d|jf|jrH|d|jrX|d|jrh|d|j rx|d|j r|d t t |j f|j r|d |jr|d |jf|jr|d |jft|j}|D]}||t|j|fq|d t|jft|gS)zReturn string representation of Cookie in an the LWP cookie file format. Actually, the format is extended a bit -- see module docstring. rrNr) path_specN) port_specN) domain_dotN)rNr)rNrrr)rrrrrrrrrrrrZrrrrr|rr}r rr)rrr}rrrr lwp_cookie_strs(   rc@s,eZdZdZd ddZd ddZd d ZdS) raZ The LWPCookieJar saves a sequence of "Set-Cookie3" lines. "Set-Cookie3" is the format used by the libwww-perl libary, not known to be compatible with any browser, but which is easy to read and doesn't lose information about RFC 2965 cookies. Additional methods as_lwp_str(ignore_discard=True, ignore_expired=True) TcCsTt}g}|D]2}|s |jr q|s0||r0q|dt|qd|dgS)zReturn cookies as a string of "\n"-separated "Set-Cookie3" headers. ignore_discard and ignore_expires: see docstring for FileCookieJar.save zSet-Cookie3: %s r)rtrrrrr)rrrr rrrrr as_lwp_strBs zLWPCookieJar.as_lwp_strNFcCsd|dur"|jdur|j}nttt|d}z(|d||||W|n |0dS)Nwz#LWP-Cookies-2.0 )rrsrr writerrrrrr rRs  zLWPCookieJar.savecCs,|}|j|s$d|}t|t}d}d} d} z|} | dkrPq| |s\q<| t|d} t| gD]f} | d\} }i}i}| D] }d||<q| ddD]n\}}|dur| }nd}|| vs|| vr|}|| vr|durd }|||<q|| vr|||<q|||<q|j }|d }|d }|durJt |}|durXd }|d }|d }t |d| ||d|d|||d|d|d|d|||d|d|}|s|j rqz|s||rqz||qzqtyYn*ty&ttd|| fYn0dS)Nz5%r does not look like a Set-Cookie3 (LWP) format filez Set-Cookie3:)rrrrr)rrrrrrrrrFr/Trrrrrrrrrrrrrz&invalid Set-Cookie3 format file %r: %r)readlinerrhrrtrrastriprrrrrr rrrrrr-)rr+rrrmagicr,r headerrrlinedatarrrrrrrrrrrrrrrr ras                    zLWPCookieJar._really_load)TT)NFF)rrrrrrrrrrr r5s  rc@s0eZdZdZedZdZddZd dd Z dS) ra WARNING: you may want to backup your browser's cookies file if you use this class to save cookies. I *think* it works, but there have been bugs in the past! This class differs from CookieJar only in the format it uses to save and load cookies to and from a file. This class uses the Mozilla/Netscape `cookies.txt' format. lynx uses this file format, too. Don't expect cookies saved while the browser is running to be noticed by the browser (in fact, Mozilla on unix will overwrite your saved cookies if you change them on disk while it's running; on Windows, you probably can't save at all while the browser is running). Note that the Mozilla/Netscape format will downgrade RFC2965 cookies to Netscape cookies on saving. In particular, the cookie version and port number information is lost, together with information about whether or not Path, Port and Discard were specified by the Set-Cookie2 (or Set-Cookie) header, and whether or not the domain as set in the HTTP header started with a dot (yes, I'm aware some domains in Netscape files start with a dot and some don't -- trust me, you really don't want to know any more about this). Note that though Mozilla and Netscape use the same format, they use slightly different headers. The class saves cookies using the Netscape header by default (Mozilla can cope with that). z#( Netscape)? HTTP Cookie Filez~# Netscape HTTP Cookie File # http://www.netscape.com/newsref/std/cookie_spec.html # This is a generated file! Do not edit. cCsxt}|}|j|s0|td|z|}|dkrHq2|dr^|dd}|ds4|dkrzq4| d\}} } } } } }| dk} | dk} | dkr|} d}|d}| |ksJd }| dkrd} d }t d | |dd || || d | | |ddi}|s|j rq4|s&| |r&q4| |q4Wn>tyJYn*tyrttd ||fYn0dS) Nz4%r does not look like a Netscape format cookies filerrr)#rG TRUErFTrz+invalid Netscape format cookies file %r: %r)rtrrrhrrrrrrr rrrrrr-)rr+rrrr rrrrrrrrrrrrrrr rsj      zMozillaCookieJar._really_loadNFc Cs |dur"|jdur|j}nttt|d}z||jt}|D]}|sV|jrVqF|sf||rfqF|j rrd}nd}|j drd}nd}|j durt |j } nd} |jdurd} |j} n |j} |j} |d|j ||j|| | | gdqFW|n |0dS)NrrFALSErrrr)rrsrr rrrtrrrrrrr rrrrr) rrrrr+r rrrrrrrrr rs@       zMozillaCookieJar.save)NFF) rrrrrrrrrrrrrr rs  Br)N)N)fr __future__rrrrZfuture.builtinsrrrr r Z future.utilsr r __all__rrQrrrtZfuture.backports.urllib.parserrrZfuture.backports.http.clientr threadingr ImportErrorZdummy_threadingcalendarrrrr!rrr-r5r=r[r]rpr8rrrrZr^rfrrgrmr~rIrXrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrobjectr rrrrrrrrrrrrrrrr s           5  8 !    U 4'    #h!S=|