o Pc?+@sldZddlmZddlmZddlmZddlmZddlmZmZm Z m Z m Z ddl m Z mZgdZdd lZdd lZdd lZerEde_dd lZdd lmZmZmZdd lmZzdd lZWn eyldd lZYnwdd lm Z d Z!d a"ddZ#e eZ$dZ%ddZ&dZ'ddZ(gdZ)gdZ*gZ+e*D] Z,e+-e,.qdmddZ/dmddZ0d 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)naHTTP 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)argsrrA/usr/lib/python3/dist-packages/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\}}}}}}|tkrTd|krdkrTndSd|kr'dkrTndSd|kr4dkrTndSd|krAdkrTndSd|krQdkrTt|SdSdS) N r;=) EPOCH_YEARr)ttyearmonthmdayhourminsecrrr _timegmWsr=)MonTueWedThuFriSatSun) JanFebMarAprMayJunJulAugSepOctNovDeccCs@|dur tj}ntj|}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|dur tj}ntj|}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)?$cCsld}|tvr d}|St|}|r4dt|d}|dr*|dt|d}|ddkr4| }|S)Nrir"<r/-) UTC_ZONES TIMEZONE_REsearchrgroup)tzoffsetmrrr offset_from_tz_strings  rmc Cstz t|d}Wn/ty:zt|}Wn ty#YYdSwd|kr.dkr5nYdS|}nYdSYnw|durAd}|durGd}|durMd}t|}t|}t|}t|}t|}|dkrttd}|d} |} ||| }| | } t| dkr| dkr|d}n|d}t|||||||f} | dur|durd}| }t |} | durdS| | } | S)Nr/r0rid2r`) MONTHS_LOWERindexlower ValueErrorrtime localtimeabsr=upperrm) rTmonyrhrr;r<rjimoncur_yrrltmprXrkrrr _str2timesR       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|}|r6|}t|dd}t|d|t|dt|dt|dt|df}t|S| }t d|d}dgd \}}}}}} } t |}|durb|\}}}}}} } 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|}|dur&|\}}}}}}}} 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 iso2time6s  rcCs*|d\}}|jd||j|dS)z)Return unmatched part of re.Match object.rN)spanstring)matchstartendrrr unmatchedWsrz^\s*([^=\s;,]+)z&^\s*=\s*\"([^\"\\]*(?:\\.[^\"\\]*)*)\"z^\s*=\s*([^\s;,]*)z\\(.)c Cs,t|trJg}|D]}|}g}|rt|}|rYt|}|d}t|}|r:t|}|d}td|}nt |}|rOt|}|d}| }nd}| ||fn1| drr| dd}|ro| |g}ntdd|\}} | dksJd|||f|}|s|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_words`sJ-         r([\"\\])cCs|g}|D]4}g}|D]#\}}|dur(td|s"td|}d|}d||f}||q |r8|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]j}g}d}ttd|D]M\}}|}|dkr!qd|vr+|d}} n td|d\}} |}|d krZ|} | |vrF| }|d krPt| } d }|d krZtt| } ||| fq|rp|sk|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_headerss8     rz\.\d+$cCs:t|rdS|dkr dS|ddks|ddkrdSdS)z*Return True if text is a host domain name.Frr.rTIPV4_RErhrrrr is_HDN s rcCsl|}|}||krdSt|sdS||}|dks!|dkr#dS|ds*dSt|dds4dSdS)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_HDNAs rcCs`|}|}t|rt|s||krdSdS|d}|r&||r&dS|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_matchKs  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_host`s   rcCs4t|}}|ddkrt|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_hostps rcCs0|}t|}t|j}|dsd|}|S)z6Path component of request-URI, as defined by RFC 2965./)rr escape_pathrr)rrpartsrrrr request_path{s   rcCs^|j}|d}|dkr+||dd}zt|W|Sty*td|YdSwt}|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}|dkr&||dd}|d}t|r&|dks"|dkr&d|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|sdSdS)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. TF)rrrget_origin_req_host)rrrrr is_third_partys rc@sVeZdZdZ dddZddZddd 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|}| durt| } |dur|durtd||_||_||_||_||_||_||_ ||_ | |_ | |_ | |_ | |_| |_||_||_||_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_attr zCookie.has_nonstandard_attrNcCs|j||Sr)rget)rrdefaultrrr get_nonstandard_attrzCookie.get_nonstandard_attrcCs||j|<dSrr)rrrrrr set_nonstandard_attrr zCookie.set_nonstandard_attrcCs,|durt}|jdur|j|krdSdSNTF)rtr)rnowrrr is_expiredszCookie.is_expiredcCsX|jdurd}nd|j}|j||j}|jdur#d|j|jf}n|j}d||fS)Nrrrz)rrrrr)rplimit namevaluerrr __str__$s   zCookie.__str__cCszg}dD]}t||}t|trt|}|td|t|fq|dt|j|dt|jdd|S)N)rrrrrrrrrrrrrrrrzrest=%sz rfc2109=%sz Cookie(%s)r)getattrrr rreprrrr)rrrrrrr __repr__.s  zCookie.__repr__)Fr) __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. cCt)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. NotImplementedErrorrcookierrrr set_okLszCookiePolicy.set_okcCr)zAReturn true if (and only if) cookie should be returned to server.rrrrr return_okUzCookiePolicy.return_okcCdS)zMReturn false if cookies should not be returned, given cookie domain. Tr)rrrrrr domain_return_okYzCookiePolicy.domain_return_okcCr$)zKReturn false if cookies should not be returned, given cookie path. Tr)rrrrrr path_return_ok^r&zCookiePolicy.path_return_okN)rrrrr!r"r%r'rrrr rCs   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||_||_||_||_||_||_| |_| |_| |_| |_ |dur(t ||_ nd|_ |dur3t |}||_ 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/r0r1rrr rns    zDefaultCookiePolicy.__init__cC|jS)z4Return the sequence of blocked domains (as a tuple).)r3rrrr r5r#z#DefaultCookiePolicy.blocked_domainscCst||_dS)z$Set the sequence of blocked domains.N)r2r3)rr5rrr set_blocked_domainssz'DefaultCookiePolicy.set_blocked_domainscCs |jD] }t||r dSqdSr)r3r)rrblocked_domainrrr is_blockeds  zDefaultCookiePolicy.is_blockedcCr7)z=Return None, or the sequence of allowed domains (as a tuple).)r4r8rrr r6r#z#DefaultCookiePolicy.allowed_domainscCs|durt|}||_dS)z-Set the sequence of allowed domains, or None.N)r2r4)rr6rrr set_allowed_domainss z'DefaultCookiePolicy.set_allowed_domainscCs.|jdurdS|jD] }t||rdSq dS)NFT)r4r)rrallowed_domainrrr is_not_alloweds   z"DefaultCookiePolicy.is_not_allowedcCsNtd|j|j|jdusJdD]}d|}t||}|||s$dSqdS)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!rrrrr rnfn_namefnrrr r!s  zDefaultCookiePolicy.set_okcCsZ|jdurtd|j|jdS|jdkr|jstddS|jdkr+|js+tddSdS)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_versioncCJ|jr#t|r#|jdkr|jrtddS|jdkr#|jr#tddSdSNrz> third-party RFC 2965 cookie during unverifiable transactionFz> third-party Netscape cookie during unverifiable transactionT unverifiablerrr-r!r.rrrr set_ok_verifiabilityz(DefaultCookiePolicy.set_ok_verifiabilitycCs0|jdkr|jr|jdrtd|jdSdS)Nr$z' illegal name (starts with '$'): '%s'FT)rr0rrr!rrrr set_ok_names   zDefaultCookiePolicy.set_ok_namecCsJ|jr#t|}|jdks|jdkr#|jr#||js#td|j|dSdS)Nrz7 path attribute %s is not a prefix of request path %sFT)rrrr1rrr!)rr rreq_pathrrr set_ok_paths  zDefaultCookiePolicy.set_ok_pathc Cs||jrtd|jdS||jrtd|jdS|jrt|\}}|j}|jre|ddkre|d}|dd|}|dkre||dd}||d|} | dvret |dkretd |dS| drq|dd} n|} | ddk} | s|d krtd |dS|j dkr||s| dsd||std ||dS|j dks|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)r;rr!r>rrr,countrrrlenrrrrr/DomainRFC2965MatchrDomainStrictNoDotsrrh) rr rrrrrjtldsldundotted_domain embedded_dots host_prefixrrr set_ok_domainst                   z!DefaultCookiePolicy.set_ok_domainc Cs|jrBt|}|durd}nt|}|jdD] }zt|Wnty0td|YdSw||kr8dSqtd||jdSdS)N80rz bad port %s (not numeric)Fz$ request port (%s) not found in %sT)rrr rrrrsr!rr rreq_portrrrr set_ok_port*s*   zDefaultCookiePolicy.set_ok_portcCs@td|j|jdD]}d|}t||}|||sdSq dS)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). r?)rr@rrrr return_ok_FTrBrCrrr r"?s   zDefaultCookiePolicy.return_okcCs<|jdkr|jstddS|jdkr|jstddSdS)NrrGFrHT)rr)r!r(rrrr return_ok_versionQsz%DefaultCookiePolicy.return_ok_versioncCrJrKrLrrrr return_ok_verifiabilityZrOz+DefaultCookiePolicy.return_ok_verifiabilitycCs |jr|jdkrtddSdS)Nhttpsz( secure cookie with non-secure requestFT)rtyper!rrrr return_ok_securefsz$DefaultCookiePolicy.return_ok_securecCs||jr tddSdS)Nz cookie expiredFT)r_nowr!rrrr return_ok_expiresls z%DefaultCookiePolicy.return_ok_expirescCsP|jr&t|}|dur d}|jdD] }||krdSqtd||jdSdS)Nrtrz0 request port %s does not match cookie port %sFT)rrrr!rurrr return_ok_portrsz"DefaultCookiePolicy.return_ok_portcCst|\}}|j}|jdkr!|j|j@r!|js!||kr!tddS|jdkr3t||s3td||dS|jdkrGd||sGtd||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)rr rrrrrrr return_ok_domains*   z$DefaultCookiePolicy.return_ok_domaincCs|t|\}}|dsd|}|dsd|}||s$||s$dS||r0td|dS||r)rrrrrrrr r%s       z$DefaultCookiePolicy.domain_return_okcCs0td|t|}||std||dSdS)Nz- checking cookie path=%sz %s does not path-match %sFT)r!rr)rrrrRrrr r's   z"DefaultCookiePolicy.path_return_ok) rrrrrlrrk DomainLiberal DomainStrictrr5r9r;r6r<r>r!rIrNrQrSrsrwr"ryrzr}rrrr%r'rrrr rdsP !   ;   rcCst|}t|j|Sr)sortedkeysrr )adictrrrr vals_sorted_by_keys  rc cs\t|}|D]$}d}z|jWn tyYn wd}t|D]}|Vq |s+|VqdS)zBIterates over nested mapping, depth-first, in sorted order by key.FTN)ritemsAttributeError deepvalues)mappingvaluesobjsubobjrrr rs    rc@ eZdZdS)AbsentNrrrrrrr r rc@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_policyrzCookieJar.set_policycCsg}|j||s gStd||j|}|D]*}|j||s#q||}|D]}|j||s9tdq+td||q+q|S)Nz!Checking %s for cookies to returnz not returning cookiez it's a match) rr%r!rrr'rr"r)rrrcookiescookies_by_pathrcookies_by_namer rrr _cookies_for_domains"     zCookieJar._cookies_for_domaincCs*g}|jD] }||||q|S)z2Return a list of cookies to be returned to server.)rrextendr)rrrrrrr _cookies_for_requestszCookieJar._cookies_for_requestc Cs6|jddddd}g}|D]}|j}|s#d}|dkr#|d||jdur<|j|jr<|dkr<|jd |j}n|j}|jdurK||jn |d |j|f|dkr|j rd|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). cS t|jSr)rjr)arrr  s z)CookieJar._cookie_attrs..T)keyreverseFrz $Version=%sNrrz $Path="%s"rr/z $Domain="%s"z$Portz="%s")sortrrr non_word_rerhquote_rerrrrrrrrr) rrrattrsr rrrrrrr _cookie_attrssF        zCookieJar._cookie_attrscCstd|jzKtt|j_|_||}||}|r/| ds/| dd ||jj rN|jj sN| dsN|D]}|jdkrM| ddnq>W|jn|jw|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!racquirerrtrr~rr has_headeradd_unredirected_headerrr)r+rreleaseclear_expired_cookies)rrrrr rrr r<s,        zCookieJar.add_cookie_headerc Cstg}d}d}|D]}|d\}}d}d} i} i} |ddD]\} } | }||vs.||vr0|} | |vr:| dur:d} | | vr?q| dkrS| durOtd d} n\| } | d krc|rZq| durctd q| d krd}zt| } Wntytd d} Yn,wd } |j| } | |vs| |vr| dur| dvrtd| d} n | | | <q| | | <q| rq|||| | 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!rrsr~r)r attrs_set cookie_tuples boolean_attrs value_attrs cookie_attrsrr max_age_set bad_cookiestandardrrrrrrr _normalized_cookie_tuples]sh         z#CookieJar._normalized_cookie_tuplescCs|\}}}}|dt}|dt}|dt} |dt} |dd} | dur9zt| } Wn ty8YdSw|dd} |dd} |d d}|d d}|tur`|d kr`d }t|}n*d}t|}|d }|dkr| dkrz|d|}n|d|d}t|dkrd }|tu}d}|rt| d}|turt |\}}|}n | dsd|}d}| tur| durt |} n d }t dd | } nd} | turd} d } n!| |jkrz ||||Wn tyYnwtd|||dSt| ||| ||||||| | | |||S)NrrrrrrFrrrrTrrrr/rz\s+z2Expiring cookie, domain='%s', path='%s', name='%s')r rrrsrrrrjboolrrrrrr~clearKeyErrorr!r )rtuprrrrrrrrrrrrrrrrrrrrrrrr _cookie_from_cookie_tuples                   z#CookieJar._cookie_from_cookie_tuplecCs6||}g}|D]}|||}|r||q |Sr)rrr)rrrrrrr rrr _cookies_from_attrs_sets  z!CookieJar._cookies_from_attrs_setcCsHt|jdd}|dur|jj }|D]}|jdkr!d|_|r!d|_qdS)Nr*r/Tr)rrr)rr)rr rfc2109_as_nsr rrr _process_rfc2109_cookies#s  z"CookieJar._process_rfc2109_cookiesc Cs|}|dg}|dg}|jj}|jj}|s|r(|s |r(|s$|r(|s*|s*gSz |t||}WntyBtg}Ynw|r|rz |t ||} Wnty_tg} Ynw| | |ri} |D] } d| | j | j | j f<qk| 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_rfc2965[sz3CookieJar.make_cookies..no_matching_rfc2965)rbget_allrr)r(rr Exceptionr-rrrrrrr) rresponserr rfc2965_hdrsns_hdrsr)r(r ns_cookiesrr rrrr make_cookies/s\        zCookieJar.make_cookiescCsf|jz'tt|j_|_|j||r%||W|jdSW|jdS|jw)z-Set a cookie if policy says it's OK to do so.N) rrrrtrr~r! set_cookierrrrr set_cookie_if_okes  zCookieJar.set_cookie_if_okcCst|j}|jz+|j|vri||j<||j}|j|vr"i||j<||j}|||j<W|jdS|jw)z?Set a cookie, without checking whether or not it should be set.N)rrrrrrr)rr cc2c3rrr rrs    zCookieJar.set_cookiecCstd||jz-tt|j_|_|||D]}|j ||r1td|| |qW|j dS|j w)zAExtract cookies from response, where allowable given the request.zextract_cookies: %sz setting cookie: %sN) r!rbrrrrtrr~rr!rr)rrrr rrr extract_cookiess   zCookieJar.extract_cookiescCsz|dur|dus |durtd|j|||=dS|dur.|dur&td|j||=dS|dur8|j|=dSi|_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.clearcCsL|jz|D]}|jr||j|j|jqW|jdS|jw)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)rr rrr clear_session_cookiess zCookieJar.clear_session_cookiescCsX|jz t}|D]}||r||j|j|jq W|jdS|jw)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)rrr rrr rs  zCookieJar.clear_expired_cookiescCrr)rrr8rrr __iter__rzCookieJar.__iter__cCsd}|D]}|d}q|S)z#Return number of contained cookies.rr/r)rrr rrr __len__szCookieJar.__len__cC0g}|D] }|t|qd|jd|fSNz<%s[%s]>r)rr __class__rrrr rrr rszCookieJar.__repr__cCrr)rr rrrrrr rszCookieJar.__str__r)NNN)#rrrrrcompilerrstrict_domain_re domain_redots_reASCIImagic_rerrrrrrrrrrrrrrrrrrrr rrrrrr rs<      ;!a\  6    rc@r)rNrrrrr rrrc@s<eZdZdZd ddZd ddZd dd Z  d d d ZdS)rz6CookieJar that can be loaded from and saved to a file.NFcCsDt|||durz|dWntd||_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__cCr)zSave cookies to a file.r)rrignore_discardignore_expiresrrr saver#zFileCookieJar.savecCsT|dur|jdur |j}nttt|}z|||||W|dS|w)zLoad cookies from a file.N)rrsMISSING_FILENAME_TEXTr _really_loadcloserrrrr+rrr loadszFileCookieJar.loadc Cs|dur|jdur |j}ntt|jz(t|j}i|_z ||||Wn t t fy6||_wW|j dS|j w)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)NFNNFF)rrrrrrrrrrrr rs    rcCs |j|jfd|jfd|jfg}|jdur|d|jf|jr$|d|jr,|d|jr4|d|j r<|d|j rK|d t t |j f|j rS|d |jr^|d |jf|jri|d |jft|j}|D]}||t|j|fqr|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)rrrrrrrrrrrrZrrrrrrrr rr)r rrrrrr 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]}|s|jrq|s||rq|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)rrrrrr rrr as_lwp_strHs zLWPCookieJar.as_lwp_strNFcCsb|dur|jdur |j}nttt|d}z|d||||W|dS|w)Nwz#LWP-Cookies-2.0 )rrsrr writerrrrrr rXs  zLWPCookieJar.savecCs |}|j|sd|}t|t}d}d} d} z |} | dkr)WdS| |s/q| t|d} t| gD]} | d\} }i}i}| D]}d||<qL| ddD]5\}}|durf| }nd}|| vsp|| vrr|}|| vr|dur|d }|||<qY|| vr|||<qY|||<qY|j }|d }|d }|durt |}|durd }|d }|d }t |d| ||d|d|||d|d|d|d|||d|d|}|s|j rq>|s||rq>||q>qtytyttd|| fw)Nz5%r does not look like a Set-Cookie3 (LWP) format filez Set-Cookie3:)rrrrr)rrrrrrrr/rrFTrrrrrrrrrrrrrz&invalid Set-Cookie3 format file %r: %r)readlinerrhrrtrrjstriprrrr rr rrrrrr-)rr+rrrmagicr,rheaderrrlinedatarrrrrrrrrrrrrrrr rgs                 6zLWPCookieJar._really_load)TTr)rrrrrrrrrrr r;s   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. cCs^t}|}|j|s|td|z} |}|dkr%WdS|dr0|dd}|ds=|dkr>q| d\}} } } } } }| dk} | dk} | dkrZ|} d}|d }| |kseJd }| dkrod} d }t d | |dd || || d | | |ddi}|s|j rq|s| |rq| |qtytyttd ||fw)Nz4%r does not look like a Netscape format cookies filer/rrr)#rP TRUErFTrz+invalid Netscape format cookies file %r: %r)rtrrrhrrrrrrr rrrrrr-)rr+rrrrrrrrrrrrrrrrrrr rsn       0 zMozillaCookieJar._really_loadNFc Cs|dur|jdur |j}nttt|d}zh||jt}|D]T}|s+|jr+q#|s3||r3q#|j r9d}nd}|j drDd}nd}|j durQt |j } nd} |jdur^d} |j} n|j} |j} |d|j ||j|| | | gdq#W|dS|w)NrrFALSErrrr)rrsrr rrrtrrrrrrr rrrrr) rrrrr+rr rrrrrrrr r sB       zMozillaCookieJar.saver) rrrrrrrrrrrrrr rs  Brr)fr __future__rrrrfuture.builtinsrrrr r future.utilsr r __all__rrQrrrtfuture.backports.urllib.parserrrfuture.backports.http.clientr threadingr ImportErrordummy_threadingcalendarrrrr!rrr-r5r=r[r]rpr8rrrrZr^rfrrgrmr~rIrXrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrobjectr rrrrrrrrrrrrrrrr s            5  8 !     U4'    #h!S=|