a 97ax@sdZddlmZmZmZmZddlmZmZm Z m Z m Z m Z m Z mZddlmZmZmZddlZddlZddlZddlZddlmZddlmZdd lmZmZmZdd l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1dd l2m3Z3m4Z4ddl5Z5ddl6Z6ddl7Z7ddl8Z8ddl9Z9ddl:Z:ddl;Z;ddlZ>dd lmZerpdd l?m@Z@n dd lAm@Z@zddlBZBddlBmCZCWneDydZEYn0dZEgdZFe:jGddZHdaIde9jJfddZKddZLgZMdddZNddZOere8Pde8jQZRn e8PdZRddZSGdddeTZUGd d!d!eTZVd"d#ZWGd$d%d%eTZXGd&d'd'eXZYGd(d)d)eXZZGd*d+d+eXZ[d,d-Z\Gd.d/d/eXZ]Gd0d1d1eTZ^Gd2d3d3e^Z_Gd4d5d5eTZ`Gd6d7d7e`eXZaGd8d9d9e`eXZbe6jcZdGd:d;d;eTZeGdd?d?eXeeZgGd@dAdAeXZhGdBdCdCehZiejedDrvGdEdFdFehZkeFldFGdGdHdHeXZmGdIdJdJeXZndKdLZodMdNZpGdOdPdPeXZqdQdRZrGdSdTdTeXZsGdUdVdVesZtdWZue6jvdXkrddYlwmxZxmyZyndZd[Zxd\d]ZyiZzGd^d_d_eTZ{Gd`dadae{Z|da}dbdcZ~dadddeZdadfdgZdadhdiZGdjdkdkeTZdldmZdndoZdpdqZe:jdrkrddslmZmZdtduZdvdwZdxdyZdzd{Zn6e6jvdXkrd|d}Zd~d{ZddZddyZneZeZdS)a Ported using Python-Future from the Python 3.3 standard library. An extensible library for opening URLs using a variety of protocols The simplest way to use this module is to call the urlopen function, which accepts a string containing a URL or a Request object (described below). It opens the URL and returns the results as file-like object; the returned object has some extra methods described below. The OpenerDirector manages a collection of Handler objects that do all the actual work. Each Handler implements a particular protocol or option. The OpenerDirector is a composite object that invokes the Handlers needed to open the requested URL. For example, the HTTPHandler performs HTTP GET and POST requests and deals with non-error returns. The HTTPRedirectHandler automatically deals with HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler deals with digest authentication. urlopen(url, data=None) -- Basic usage is the same as original urllib. pass the url and optionally data to post to an HTTP URL, and get a file-like object back. One difference is that you can also pass a Request instance instead of URL. Raises a URLError (subclass of IOError); for HTTP errors, raises an HTTPError, which can also be treated as a valid response. build_opener -- Function that creates a new OpenerDirector instance. Will install the default handlers. Accepts one or more Handlers as arguments, either instances or Handler classes that it will instantiate. If one of the argument is a subclass of the default handler, the argument will be installed instead of the default. install_opener -- Installs a new opener as the default opener. objects of interest: OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages the Handler classes, while dealing with requests and responses. Request -- An object that encapsulates the state of a request. The state can be as simple as the URL. It can also include extra HTTP headers, e.g. a User-Agent. BaseHandler -- internals: BaseHandler and parent _call_chain conventions Example usage: import urllib.request # set up authentication info authinfo = urllib.request.HTTPBasicAuthHandler() authinfo.add_password(realm='PDQ Application', uri='https://mahler:8092/site-updates.py', user='klem', passwd='geheim$parole') proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"}) # build a new opener that adds authentication and caching FTP handlers opener = urllib.request.build_opener(proxy_support, authinfo, urllib.request.CacheFTPHandler) # install it urllib.request.install_opener(opener) f = urllib.request.urlopen('http://www.python.org/') )absolute_importdivisionprint_functionunicode_literals)bytesdictfilterinputintmapopenstr)PY2PY3raise_with_tracebackN)email)client)URLError HTTPErrorContentTooShortError)urlparseurlspliturljoinunwrapquoteunquote splittype splithost splitport splituser splitpasswd splitattr splitquery splitvaluesplittagto_bytes urlunparse) addinfourl addclosehook)r)Iterable) SSLContextFT)RequestOpenerDirector BaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessor ProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandler HTTPHandler FileHandler FTPHandlerCacheFTPHandlerUnknownHandlerHTTPErrorProcessorurlopeninstall_opener build_opener pathname2url url2pathname getproxies urlretrieve urlcleanup URLopenerFancyURLopenerc Ksd|vr|d}|d=nd}d|vr4|d}|d=nd}d|vrP|d}|d=nd}|s`|s`|rtsltdttj}|jtjO_tj|_|s|r| ||n| t |dd}t |} nt durt a } nt } | |||S)N cadefaultFcapathcafilezSSL support not availableTcontextcheck_hostname) _have_ssl ValueErrorsslr+PROTOCOL_SSLv23options OP_NO_SSLv2 CERT_REQUIRED verify_modeload_verify_locationsset_default_verify_paths HTTPSHandlerrC_openerr ) urldatatimeoutZ _3to2kwargsrLrMrNrP https_handleropenerrcz/private/var/folders/s6/9n5zrl012gv99k63s4q6ccsd4s6mqz/T/pip-target-f5cq3f2q/lib/python/future/backports/urllib/request.pyrAs*     rAcCs|adSN)r])rbrcrcrdrBsrBc Cslt|\}}tt||}|}|dkrR|sRtj||fWdS|rbt|d}nt j dd}|j }t ||||f} d} d} d} d} d |vrt|d } |r|| | | || }|sҐq| t|7} ||| d 7} |r|| | | qWdn1s0YWdn1s80Y| dkrh| | krhtd | | f| | S) aW Retrieve a URL into a temporary location on disk. Requires a URL argument. If a filename is passed, it is used as the temporary file location. The reporthook argument should be a callable that accepts a block number, a read size, and the total file size of the URL target. The data argument should be valid URL encoded data. If a filename is passed and the URL points to a local resource, the result is a copy from local file to new file. Returns a tuple containing the path to the newly created data file as well as the resulting HTTPMessage object. fileNwbF)delete rcontent-lengthContent-Lengthr1retrieval incomplete: got only %i out of %i bytes)r contextlibclosingrAinfoospathnormpathr tempfileNamedTemporaryFilename_url_tempfilesappendr readlenwriter)r^filename reporthookr_url_typerrfpheaderstfpresultbssizeryblocknumblockrcrcrdrGsH          NrGc CsBtD]&}zt|Wqty(Yq0qtdd=tr>dadSre)rwrqunlinkEnvironmentErrorr]) temp_filercrcrdrHs  rHz:\d+$cCs<|j}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. rHost)full_urlr get_header _cut_port_resublower)requestr^hostrcrcrd request_hosts   rc@seZdZdidddfddZddZddZd d Zd d Zd dZddZ ddZ ddZ ddZ ddZ ddZddZddZdd Zd!d"Zd#d$Zd)d%d&Zd'd(ZdS)*r,NFc Cst||_t|j\|_|_||_i|_d|_|D]\}}|||q6i|_ |durbt |}||_ ||_ ||_ |dSre)rrr%fragmentr_r _tunnel_hostitems add_headerunredirected_hdrsrorigin_req_host unverifiablemethod_parse) selfr^r_rrrrkeyvaluercrcrd__init__s zRequest.__init__cCsNt|j\|_}|jdur(td|jt|\|_|_|jrJt|j|_dS)Nzunknown url type: %r)rrtyperSrrselectorr)rrestrcrcrdr.s  zRequest._parsecCs&|jdur|jS|jdurdSdSdS)z3Return a string indicating the HTTP request method.NPOSTGET)rr_rrcrcrd get_method6s   zRequest.get_methodcCs |jrd|j|jfS|jSdS)Nz%s#%s)rrrrcrcrd get_full_url?szRequest.get_full_urlcCsd}tj|tdd||_dS)Nz&Request.add_data method is deprecated.r stacklevelwarningswarnDeprecationWarningr_)rr_msgrcrcrdadd_dataGszRequest.add_datacCsd}tj|tdd|jduS)Nz&Request.has_data method is deprecated.rrrrrrcrcrdhas_dataLszRequest.has_datacCsd}tj|tdd|jS)Nz&Request.get_data method is deprecated.rrrrrcrcrdget_dataQszRequest.get_datacCsd}tj|tdd|jS)Nz&Request.get_type method is deprecated.rr)rrrrrrcrcrdget_typeVszRequest.get_typecCsd}tj|tdd|jS)Nz&Request.get_host method is deprecated.rr)rrrrrrcrcrdget_host[szRequest.get_hostcCsd}tj|tdd|jS)Nz*Request.get_selector method is deprecated.rr)rrrrrrcrcrd get_selector`szRequest.get_selectorcCsd}tj|tdd|jS)Nz-Request.is_unverifiable method is deprecated.rr)rrrrrrcrcrdis_unverifiableeszRequest.is_unverifiablecCsd}tj|tdd|jS)Nz1Request.get_origin_req_host method is deprecated.rr)rrrrrrcrcrdget_origin_req_hostjszRequest.get_origin_req_hostcCs2|jdkr|js|j|_n||_|j|_||_dS)Nhttps)rrrrr)rrrrcrcrd set_proxyqs  zRequest.set_proxycCs |j|jkSre)rrrrcrcrd has_proxyyszRequest.has_proxycCs||j|<dSre)r capitalizerrvalrcrcrdr|szRequest.add_headercCs||j|<dSre)rrrrcrcrdadd_unredirected_headerszRequest.add_unredirected_headercCs||jvp||jvSre)rr)r header_namercrcrd has_headers zRequest.has_headercCs|j||j||Sre)rgetr)rrdefaultrcrcrdrs zRequest.get_headercCs"|j}||jt|Sre)rcopyupdaterlistr)rhdrsrcrcrd header_itemss  zRequest.header_items)N)__name__ __module__ __qualname__rrrrrrrrrrrrrrrrrrrrcrcrcrdr,s,   r,c@sNeZdZddZddZddZddZd ejfd d Z dd d Z ddZ d S)r-cCs6dt}d|fg|_g|_i|_i|_i|_i|_dS)NPython-urllib/%sz User-agent) __version__ addheadershandlers handle_open handle_errorprocess_responseprocess_request)rclient_versionrcrcrdrs zOpenerDirector.__init__c CsRt|dstdt|d}t|D]}|dvr6q&|d}|d|}||dd}|dr|d|d}||dd}z t|}WntyYn0|j |i} | |j|<n>|dkr|}|j } n*|d kr|}|j } n|d kr&|}|j } nq&| |g} | r t| |n | |d }q&|rNt|j|||dS) N add_parentz%expected BaseHandler instance, got %rF)redirect_requestdo_open proxy_open_rerrorr responserT)hasattr TypeErrorrdirfind startswithr rSrrrrr setdefaultbisectinsortrxrr) rhandleraddedmethiprotocol conditionjkindlookuprrcrcrd add_handlersL         zOpenerDirector.add_handlercCsdSrercrrcrcrdcloseszOpenerDirector.closec Gs<||d}|D]&}t||}||}|dur|SqdS)Nrc)rgetattr) rchainr meth_nameargsrrfuncrrcrcrd _call_chains   zOpenerDirector._call_chainNc Cst|tr|}t|tr(t||}n|}|dur:||_||_|j}|d}|j |gD]}t ||}||}q\| ||} |d}|j |gD]}t ||}||| } q| S)z Accept a URL or a Request object Python-Future: if the URL is passed as a byte-string, decode it first. N_request _response) isinstancerdecoder r,r_r`rrrr_openr) rfullurlr_r`reqrr processorrrrcrcrdr s&        zOpenerDirector.opencCsP||jdd|}|r|S|j}||j||d|}|r>|S||jdd|S)Nr default_openrunknown unknown_open)rrr)rrr_rrrcrcrdrs    zOpenerDirector._opencGs~|dvr,|jd}|d}d|}d}|}n|j}|d}d}|||f|}|j|}|r^|S|rz|dd f|}|j|SdS) Nhttprrz http_error_%sr_errorrrhttp_error_default)rr)rprotorrrhttp_err orig_argsrrcrcrdr s   zOpenerDirector.error)N) rrrrrrrsocket_GLOBAL_DEFAULT_TIMEOUTr rrrcrcrcrdr-s / " r-cGsdd}t}ttttttttg}t t dr6| t t }|D]@}|D]6}||rjt||r~||qHt||rH||qHq@|D]}||q|D]}||q|D]}||r|}||q|S)a*Create an opener object from a list of handlers. The opener will use several default handlers, including support for HTTP, FTP and when applicable HTTPS. If any of the handlers passed as arguments are subclasses of the default handlers, the default handlers will not be used. cSst|tpt|dS)N __bases__)rrr)objrcrcrdisclass/szbuild_opener..isclassHTTPSConnection)r-r2r?r;r/r0r=r<r@r http_clientrxr\set issubclassaddrremover)rr rbdefault_classesskipklasscheckhrcrcrdrC&s2        rCc@s(eZdZdZddZddZddZdS) r.cCs ||_dSre)parent)rrrcrcrdrOszBaseHandler.add_parentcCsdSrercrrcrcrdrRszBaseHandler.closecCst|dsdS|j|jkS)N handler_orderT)rr)rotherrcrcrd__lt__Vs zBaseHandler.__lt__N)rrrrrrrrcrcrcrdr.Lsr.c@s eZdZdZdZddZeZdS)r@zProcess HTTP error responses.icCsH|j|j|}}}d|kr,dksDn|jd|||||}|S)N,r)coderrprr)rrrrrrrcrcrd http_responsecs  z HTTPErrorProcessor.http_responseN)rrr__doc__rr https_responsercrcrcrdr@_s r@c@seZdZddZdS)r/cCst|j||||dSre)rr)rrrrrrrcrcrdrqsz*HTTPDefaultErrorHandler.http_error_defaultN)rrrrrcrcrcrdr/psr/c@s4eZdZdZdZddZddZeZZZ dZ dS) r0 c sx|}|dvr|dvs:|dvr(|dks:t|j|||||dd}dtfdd |jD}t|||jd d S) aReturn a Request or None in response to a redirect. This is called by the http_error_30x methods when a redirection response is received. If a redirection should take place, return a new Request to allow http_error_30x to perform the redirect. Otherwise, raise HTTPError if no-one else should try to handle this url. Return None if you can't but another Handler might. )-./i3)rHEAD)r%r&r'r z%20)rkz content-typec3s&|]\}}|vr||fVqdSre)r.0kvCONTENT_HEADERSrcrd s  z7HTTPRedirectHandler.redirect_request..T)rrr) rrrreplacerrrr,r) rrrrrrnewurlm newheadersrcr.rdr|s  z$HTTPRedirectHandler.redirect_requestc Cs2d|vr|d}nd|vr$|d}ndSt|}|jdvrRt||d||f|||jsht|}d|d<t|}t|j|}|||||||}|durdSt |dr|j } |_ | |d|j kst | |jkrt|j||j|||ni} |_ |_ | |dd | |<|||jj||jd S) Nlocationurirrftprz+%s - Redirection to url '%s' is not allowed/r redirect_dictrrr`)rschemerrrrr'rrrrr:r max_repeatsrzmax_redirectionsinf_msgryrrr r`) rrrrrrr2urlpartsnewvisitedrcrcrdhttp_error_302sB         z"HTTPRedirectHandler.http_error_302zoThe HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: N) rrrr=r>rrChttp_error_301http_error_303http_error_307r?rcrcrcrdr0ts "7 r0c Cst|\}}|ds d}|}n:|ds6td||dd}|dkrNd}|d|}t|\}}|dur|t|\}}nd}}||||fS)a3Return (scheme, user, password, host/port) given a URL or an authority. If a URL is supplied, it must have an authority (host:port) component. According to RFC 3986, having an authority component means the URL must have two slashes after the scheme: >>> _parse_proxy('file:/ftp.example.com/') Traceback (most recent call last): ValueError: proxy URL with no authority: 'file:/ftp.example.com/' The first three items of the returned tuple may be None. Examples of authority parsing: >>> _parse_proxy('proxy.example.com') (None, None, None, 'proxy.example.com') >>> _parse_proxy('proxy.example.com:3128') (None, None, None, 'proxy.example.com:3128') The authority component may optionally include userinfo (assumed to be username:password): >>> _parse_proxy('joe:password@proxy.example.com') (None, 'joe', 'password', 'proxy.example.com') >>> _parse_proxy('joe:password@proxy.example.com:3128') (None, 'joe', 'password', 'proxy.example.com:3128') Same examples, but with URLs instead: >>> _parse_proxy('http://proxy.example.com/') ('http', None, None, 'proxy.example.com') >>> _parse_proxy('http://proxy.example.com:3128/') ('http', None, None, 'proxy.example.com:3128') >>> _parse_proxy('http://joe:password@proxy.example.com/') ('http', 'joe', 'password', 'proxy.example.com') >>> _parse_proxy('http://joe:password@proxy.example.com:3128') ('http', 'joe', 'password', 'proxy.example.com:3128') Everything after the authority is ignored: >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128') ('ftp', 'joe', 'password', 'proxy.example.com') Test for no trailing '/' case: >>> _parse_proxy('http://joe:password@proxy.example.com') ('http', 'joe', 'password', 'proxy.example.com') r9N//zproxy URL with no authority: %rrrj)rrrSrr r!) proxyr<r_scheme authorityenduserinfohostportuserpasswordrcrcrd _parse_proxys2       rPc@s"eZdZdZdddZddZdS)r2dNcCsZ|durt}t|ds Jd||_|D]&\}}t|d||||jfddq.dS)Nkeysproxies must be a mappingz%s_opencSs ||||Srerc)rrHrrrcrcrd/sz'ProxyHandler.__init__..)rFrproxiesrsetattrr)rrVrr^rcrcrdr(s zProxyHandler.__init__c Cs|j}t|\}}}}|dur"|}|jr6t|jr6dS|rv|rvdt|t|f} t| d} | dd| t|}| ||||ks|dkrdS|j j ||j dSdS)N%s:%sasciiProxy-authorizationBasic rr;)rrPr proxy_bypassrbase64 b64encodeencoderrrrr r`) rrrHr orig_type proxy_typerNrOrM user_passcredsrcrcrdr2s" zProxyHandler.proxy_open)N)rrrrrrrcrcrcrdr2$s r2c@s6eZdZddZddZddZd dd Zd d Zd S)r3cCs i|_dSre)passwdrrcrcrdrPszHTTPPasswordMgr.__init__cs\t|tr|g}|jvr$ij|<dD].tfdd|D}||fj||<q(dS)NTFcsg|]}|qSrc) reduce_uri)r+u default_portrrcrd [z0HTTPPasswordMgr.add_password..)rr rdtuple)rrealmr6rNrd reduced_urircrhrd add_passwordSs   zHTTPPasswordMgr.add_passwordc Cs`|j|i}dD]H}|||}|D].\}}|D] }|||r6|Sq6q*qdS)NreNN)rdrrfr is_suburi) rrmauthuridomainsrireduced_authuriurisauthinfor6rcrcrdfind_user_password^s  z"HTTPPasswordMgr.find_user_passwordTc Cst|}|dr.|d}|d}|dp*d}n d}|}d}t|\}}|r~|dur~|dur~ddd|} | dur~d || f}||fS) z@Accept authority or URI and extract only the authority and path.rrrr9NPirz%s:%d)rrr) rr6ripartsr<rJrrrportdportrcrcrdrfhs$  zHTTPPasswordMgr.reduce_uricCsR||kr dS|d|dkr dSt|d|df}t|t|dkrNdSdS)zcCheck if test is below base in a URI tree Both args must be URIs in reduced form. TrFr) posixpath commonprefixrz)rbasetestcommonrcrcrdrqszHTTPPasswordMgr.is_suburiN)T)rrrrrorwrfrqrcrcrcrdr3Ns   r3c@seZdZddZdS)r4cCs0t|||\}}|dur"||fSt|d|Sre)r3rw)rrmrrrNrOrcrcrdrws z2HTTPPasswordMgrWithDefaultRealm.find_user_passwordN)rrrrwrcrcrcrdr4sr4c@s<eZdZedejZd ddZddZddZ d d Z dS) r5z1(?:.*,)*[ ]*([^ ]+)[ ]+realm=(["']?)([^"']*)\2NcCs(|durt}||_|jj|_d|_dSNr)r3rdroretried)r password_mgrrcrcrdrs  z!AbstractBasicAuthHandler.__init__cCs d|_dSrrrrcrcrdreset_retry_countsz*AbstractBasicAuthHandler.reset_retry_countc Cs||d}|jdkr,t|dd|dn|jd7_|r|d}|dkrdtd|nftj |}|r| \}}}|dvrt d t d |dkr||||} | r| jdkrd|_| SdS) Nzbasic auth failedrrbasiczDAbstractBasicAuthHandler does not support the following scheme: '%s')"'zBasic Auth Realm was unquotedr)rrrrsplitrrSr5rxsearchgroupsrr UserWarningretry_http_basic_authr) rauthreqrrrr<morrmrrcrcrdhttp_error_auth_reqeds0       z.AbstractBasicAuthHandler.http_error_auth_reqedcCs~|j||\}}|durvd||f}dt|d}|j|jd|krVdS| |j||j j ||j dSdSdS)NrXr[rYr;) rdrwr]r^r_rrr auth_headerrrr r`)rrrrmrNpwrawauthrcrcrdrs z.AbstractBasicAuthHandler.retry_http_basic_auth)N) rrrrecompileIrrrrrrcrcrcrdr5s  r5c@seZdZdZddZdS)r6 AuthorizationcCs"|j}|d|||}||S)Nwww-authenticate)rrr)rrrrrrr^rrcrcrdhttp_error_401s z#HTTPBasicAuthHandler.http_error_401N)rrrrrrcrcrcrdr6sr6c@seZdZdZddZdS)r7rZcCs"|j}|d|||}||SNproxy-authenticaterrr)rrrrrrrJrrcrcrdhttp_error_407s z$ProxyBasicAuthHandler.http_error_407N)rrrrrrcrcrcrdr7sr7c@sNeZdZdddZddZddZdd Zd d Zd d ZddZ ddZ dS)r8NcCs4|durt}||_|jj|_d|_d|_d|_dSr)r3rdror nonce_count last_nonce)rrdrcrcrdrs z"AbstractDigestAuthHandler.__init__cCs d|_dSrrrrcrcrdrsz+AbstractDigestAuthHandler.reset_retry_countcCs|||d}|jdkr*t|jdd|dn|jd7_|rx|d}|dkr`|||S|dkrxtd|dS) Nrrzdigest auth failedrrdigestrzEAbstractDigestAuthHandler does not support the following scheme: '%s')rrrrrrretry_http_digest_authrS)rrrrrrr<rcrcrdrs       z/AbstractDigestAuthHandler.http_error_auth_reqedcCsz|dd\}}ttdt|}|||}|rvd|}|j|jd|krRdS||j||j j ||j d}|SdS)Nr)rz Digest %sr;) rparse_keqv_listrparse_http_listget_authorizationrrrrrr r`)rrrtoken challengechalauth_valresprcrcrdr(s z0AbstractDigestAuthHandler.retry_http_digest_authcCs@d|j|tf}|dtd}t|}|ddS)Nz %s:%s:%s:rY)rtimectimer_ _randombyteshashlibsha1 hexdigest)rnoncesbdigrcrcrd get_cnonce4sz$AbstractDigestAuthHandler.get_cnoncecCsz6|d}|d}|d}|dd}|dd}WntyJYdS0||\}} |durfdS|j||j\} } | durdS|jdur||j|} nd} d| || f} d||j f}|d kr.||j kr|j d 7_ n d |_ ||_ d |j }| |}d ||||||f}| || |}n2|durT| || d|||f}n t d |d| |||j |f}|r|d|7}| r|d| 7}|d|7}|r|d||f7}|S)Nrmrqop algorithmMD5opaquez%s:%s:%srXrrz%08xz%s:%s:%s:%s:%szqop '%s' is not supported.z>username="%s", realm="%s", nonce="%s", uri="%s", response="%s"z , opaque="%s"z , digest="%s"z, algorithm="%s"z, qop=auth, nc=%s, cnonce="%s")rKeyErrorget_algorithm_implsrdrwrr_get_entity_digestrrrrrr)rrrrmrrrrHKDrNrentdigA1A2ncvaluecnoncenoncebitrespdigr~rcrcrdr?s\              z+AbstractDigestAuthHandler.get_authorizationcs6|dkrddn|dkr"ddfdd}|fS)NrcSst|dSNrY)rmd5r_rxrcrcrdrU~rkz?AbstractDigestAuthHandler.get_algorithm_impls..SHAcSst|dSr)rrr_rrrcrcrdrUrkcsd||fS)NrXrc)rdrrcrdrUrkrc)rrrrcrrdr{s   z-AbstractDigestAuthHandler.get_algorithm_implscCsdSrerc)rr_rrcrcrdrsz+AbstractDigestAuthHandler.get_entity_digest)N) rrrrrrrrrrrrcrcrcrdr8s   < r8c@s eZdZdZdZdZddZdS)r9zAn authentication protocol defined by RFC 2069 Digest authentication improves on basic authentication because it does not transmit passwords in the clear. rcCs*t|jd}|d|||}||S)Nrr)rrrrrrrrrrrretryrcrcrdrs z$HTTPDigestAuthHandler.http_error_401N)rrrr!rrrrcrcrcrdr9sr9c@seZdZdZdZddZdS)r:Proxy-AuthorizationrcCs"|j}|d|||}||Srrrrcrcrdrs z%ProxyDigestAuthHandler.http_error_407N)rrrrrrrcrcrcrdr:sr:c@s.eZdZd ddZddZddZdd Zd S) AbstractHTTPHandlerrcCs ||_dSre _debuglevel)r debuglevelrcrcrdrszAbstractHTTPHandler.__init__cCs ||_dSrer)rlevelrcrcrdset_http_debuglevelsz'AbstractHTTPHandler.set_http_debuglevelc CsN|j}|std|jdur|j}t|tr8d}t||dsN|dd|dsd}z:tr~t|t j r~t ||j }nt |}t ||j }Wn0tyt|t rtdt||fYn0|dd||}|rt|j\}} t| \}} |ds|d||jjD]*\} } | } || s|| | q|S) N no host givenzLPOST data should be bytes or an iterable of bytes. It cannot be of type str.z Content-type!application/x-www-form-urlencodedzContent-lengthzBContent-Length should be specified for iterable data of type %r %rz%dr)rrr_rr rrrrarrayrzitemsize memoryviewr*rSrrrrrrrr) rrrr_rrmvsel_hostr<selsel_pathrvrrcrcrd do_request_sR           zAbstractHTTPHandler.do_request_c s4|j}|std||fd|ji|}t|jtfdd|jDdd<tddD|jri}d}|vr|||<|=|j |j|d z| | |j |j Wn6tjy}z|t|WYd }~n*d }~00|} |jr|jd |_|| _| j| _| S) zReturn an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client. rr`c3s"|]\}}|vr||fVqdSrercr*rrcrdr0s z.AbstractHTTPHandler.do_open..r Connectioncss|]\}}||fVqdSre)title)r+rvrrcrcrdr0rkrrN)rrr`rrrrrr set_tunnelrrrr_rrr getresponsesockrr^reasonr) r http_classrhttp_conn_argsrrtunnel_headersproxy_auth_hdrerrrTrcrrdrs6 "    zAbstractHTTPHandler.do_openN)r)rrrrrrrrcrcrcrdrs 3rc@seZdZddZejZdS)r;cCs|tj|Sre)rrHTTPConnectionrrrcrcrd http_open$szHTTPHandler.http_openN)rrrrrr http_requestrcrcrcrdr;"sr;r c@s$eZdZdddZddZejZdS)r\rNcCst||||_||_dSre)rr_context_check_hostname)rrrPrQrcrcrdr-s zHTTPSHandler.__init__cCs|jtj||j|jdS)NrO)rrr rrrrcrcrd https_open2s zHTTPSHandler.https_open)rNN)rrrrrrr https_requestrcrcrcrdr\+s r\c@s.eZdZdddZddZddZeZeZdS) r1NcCs2ddlmmm}|dur(|}||_dSr)Zfuture.backports.http.cookiejar backportsr cookiejar CookieJar)rrhttp_cookiejarrcrcrdr;szHTTPCookieProcessor.__init__cCs|j||Sre)radd_cookie_header)rrrcrcrdrAs z HTTPCookieProcessor.http_requestcCs|j|||Sre)rextract_cookies)rrrrcrcrdr Esz!HTTPCookieProcessor.http_response)N)rrrrrr rr"rcrcrcrdr1:s  r1c@seZdZddZdS)r?cCs|j}td|dS)Nzunknown url type: %s)rr)rrrrcrcrdrMszUnknownHandler.unknown_openN)rrrrrcrcrcrdr?Lsr?cCsNi}|D]@}|dd\}}|ddkr@|ddkr@|dd}|||<q|S)z>Parse list of key=value strings where keys are not duplicated.=rrrrj)r)lparsedeltr,r-rcrcrdrQs  rcCsg}d}d}}|D]l}|r*||7}d}q|rT|dkr>d}qn |dkrJd}||7}q|dkrl||d}q|dkrxd}||7}q|r||dd|DS) apParse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Neither commas nor quotes count if they are escaped. Only double-quotes count, not single-quotes. rF\Tr,cSsg|] }|qSrcstrip)r+partrcrcrdrjrkz#parse_http_list..)rx)rresrescapercurrcrcrdr[s4    rc@s(eZdZddZdZddZddZdS)r<cCs\|j}|dddkrN|dddkrN|jrN|jdkrN|j|urXtdn ||SdS)NrrGrKr9 localhost-file:// scheme is supported only on localhost)rr get_namesropen_local_file)rrr^rcrcrd file_opens& zFileHandler.file_openNcCs^tjdurXz*ttddttdt_Wn"tjyVtdft_Yn0tjS)Nr r)r<namesrlrgethostbyname_ex gethostnamegaierror gethostbynamerrcrcrdrs   zFileHandler.get_namesc Csddlmmm}ddl}|j}|j}t|}zt |}|j }|j |j dd} | |d} td| ppd|| f} |rt|\}} |r| st||vr|rd||} nd|} tt|d| | WSWn.ty}zt|WYd}~n d}~00tddS) NrTusegmtz6Content-type: %s Content-length: %d Last-modified: %s text/plainfile://rbzfile not on local host)future.backports.email.utilsrrutils mimetypesrrrErqstatst_size formatdatest_mtime guess_typemessage_from_stringr_safe_gethostbynamerr(r OSErrorr)rr email_utilsrrr| localfilestatsrmodifiedmtyperrzorigurlexprcrcrdrs:   zFileHandler.open_local_file)rrrrrrrrcrcrcrdr<s  r<cCs(z t|WStjy"YdS0dSre)rrrrrcrcrdr$s r$c@seZdZddZddZdS)r=c Cs&ddl}ddl}|j}|s"tdt|\}}|dur>|j}nt|}t|\}}|rdt|\}}nd}t |}|pvd}|p~d}zt |}Wn.t j y}zt|WYd}~n d}~00t |j\} } | d} ttt | } | dd| d} } | r| ds| dd} z|||||| |j} | r:dpcCs"i|_i|_d|_d|_d|_dS)Nr<r)cacher`soonestdelay max_connsrrcrcrdrs zCacheFTPHandler.__init__cCs ||_dSre)rF)rtrcrcrd setTimeoutszCacheFTPHandler.setTimeoutcCs ||_dSre)rG)rr3rcrcrd setMaxConnsszCacheFTPHandler.setMaxConnscCsr|||d||f}||jvr4t|j|j|<n,t|||||||j|<t|j|j|<||j|S)Nr9)joinrDrrFr`rB check_cache)rrNrdrrzr;r`rrcrcrdr6 s   zCacheFTPHandler.connect_ftpcCst}|j|krPt|jD].\}}||kr |j||j|=|j|=q tt|j|_t |j|j krt|jD]&\}}||jkr|j|=|j|=qqtt|j|_dSre) rrErr`rrDrminvaluesrzrG)rrHr,r-rcrcrdrLs   zCacheFTPHandler.check_cachecCs0|jD] }|q |j|jdSre)rDrNrclearr`)rconnrcrcrd clear_cache)s  zCacheFTPHandler.clear_cacheN) rrrrrIrJr6rLrQrcrcrcrdr>s  r>r$nt)rErDcCst|S)zOS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.)rpathnamercrcrdrE8srEcCst|S)zOS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.)rrSrcrcrdrD=srDc@seZdZdZdZdeZd*ddZddZdd Z d d Z d d Z d+ddZ d,ddZ d-ddZd.ddZddZd/ddZd0ddZddZerddZd1d d!Zd"d#Zd$d%Zd&d'Zd2d(d)ZdS)3rIa,Class to open URLs. This is a class rather than just a subroutine because we may need more than one set of global protocol-specific options. Note -- this is a base class for those who don't want the automatic handling of errors type 302 (relocated) and 401 (authorization needed).NrcKsdd|jji}tj|tdd|dur.t}t|ds@Jd||_|d|_ |d|_ d |j fg|_ g|_ tj|_d|_t|_dS) NzW%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methodsclassrKrrRrSkey_file cert_filez User-Agent) __class__rrrrrFrrVrrVrWversionr_URLopener__tempfilesrqr_URLopener__unlink tempcacheftpcache)rrVx509rrcrcrdrWs   zURLopener.__init__cCs |dSre)rrrcrcrd__del__qszURLopener.__del__cCs |dSre)cleanuprrcrcrdrtszURLopener.closec CsT|jr@|jD]&}z||Wq ty0Yq 0q |jdd=|jrP|jdSre)rZr[r%r\rO)rrfrcrcrdr`ws   zURLopener.cleanupcGs|j|dS)zdAdd a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')N)rrx)rrrcrcrd addheaderszURLopener.addheaderc CsZtt|}t|dd}|jrL||jvrL|j|\}}t|d}t|||St|\}}|s`d}||jvr|j|}t|\}} t| \} } | |f}nd}d|} ||_ | dd} t || s|r| |||S| ||Sz.|durt|| |WSt|| ||WSWnJty Yn6tjyT} zttd | WYd} ~ n d} ~ 00dS) z6Use URLopener().open(file) instead of open(file, 'r').z%/:=&?~#+!$,;'@()*[]|saferrfNopen_-rz socket error)rr&rr\r r(rrVrrr1ropen_unknown_proxy open_unknownrrrrrIOError)rrr_r|rrurltyper^rH proxyhostrrrvrrcrcrdr s<             zURLopener.opencCst|\}}tdd|dS)/Overridable interface to open unknown URL type. url errorzunknown url typeNrrh)rrr_rr^rcrcrdrgs zURLopener.open_unknowncCs t|\}}tdd||dS)rkrlzinvalid proxy for %sNrm)rrHrr_rr^rcrcrdrfs zURLopener.open_unknown_proxyc Cs6tt|}|jr&||jvr&|j|St|\}}|dur|rF|dkrz0||}|}|tt|d|fWSt y} z WYd} ~ n d} ~ 00| ||}zV|} |rt |d} n|ddl } t|\} }t|pd\} }t |pd\}} t |pd\}} tj|d}| |\}}|j|t|d} z|| f}|jdur`||j|<d}d}d}d}d | vrt| d }|r||||||}|sq|t|7}| ||d7}|r||||qW| n | 0W|n |0|dkr2||kr2td ||f||S) ztretrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.Nrfrrgrrrirjrkrlrm)rr&r\rrrprrErrhr rtr#r"rqrrsplitextmkstemprZrxfdopenr ryrzr{r)rr^r|r}r_rurl1rrrrrrtgarbagerrsuffixfdrrrryrrrcrcrdretrievesp                 zURLopener.retrievecCs d}d}t|trDefault error handler: close the connection and raise IOError.N)rrrr^rrrrrcrcrdrlszURLopener.http_error_defaultcCstj||j|jdS)N)rVrW)rr rVrW)rrrcrcrd_https_connectionrszURLopener._https_connectioncCs||j||S)zUse HTTPS protocol.)rrrrcrcrd open_httpswszURLopener.open_httpscCs^t|tstd|dddkrP|dddkrP|dddkrPtd n ||SdS) z/Use local file or FTP depending on form of URL.zEfile error: proxy support for file protocol currently not implementedNrrGrKr9 z localhost/r )rr rrrSr)rr^rcrcrd open_file{s  4 zURLopener.open_filec Cslddlmmm}ddl}t|\}}t|}zt|}Wn2t yt}zt |j |j WYd}~n d}~00|j } |j|jdd} ||d} td| pd| | f} |s|} |dddkrd |} tt|d | | St|\}}|s`t|tftvr`|} |dddkr0d |} n|dd d krNtd |tt|d | | St ddS)zUse local file.rNTrz6Content-Type: %s Content-Length: %d Last-modified: %s rrr9rrrz./zAlocal file url may start with / or file:. Unknown url of type: %sz#local file error: not on local host)rrrrrrrErqrr%rstrerrorr|rr r!r"r#r(r rrrr thishostrS)rr^r&rrrf localnamer(err)r*rurlfilerzrcrcrdrs@ $    zURLopener.open_local_filec Cst|tstdddl}t|\}}|s2tdt|\}}t|\}}|r\t|\}}nd}t|}t|ppd}t|p|d}t |}|sddl }|j }nt |}t|\}} t|}|d} | dd| d} } | r| ds| dd} | r | ds d| d<|||d| f} t|jtkrb|jD]*} | | kr6|j| }|j| =|q6z| |jvrt||||| |j| <| sd }nd }| D]2}t|\}}|d kr|d vr|}q|j| | |\}}|d |d}d}|r |d|7}|dur,|dkr,|d|7}t|}t||d |WSty~}zt td|WYd}~n d}~00dS)zUse FTP protocol.zCftp error: proxy support for ftp protocol currently not implementedrNr.rr9rjrr/rrr0zftp:zContent-Type: %s zContent-Length: %d z ftp error %r)!rr rrrrr r!rrrr4r5r r"rrKrzr] MAXFTPCACHErRrrBr$rr7r8r"rr#r( ftperrorsr)rr^rrrrrzrNrdr4r:r;rfrr,r-rr=rrr>r*rr,rcrcrdopen_ftpsj                    zURLopener.open_ftpc Cs:t|tstdz|dd\}}WntyBtddYn0|sLd}|d}|dkrd ||d vr||dd }|d |}nd }g}|d t d t t|d||dkrt | dd}nt|}|dt||d ||d|}t|}t|}t|||S)zUse "data" URL.zEdata error: proxy support for data protocol currently not implementedrrz data errorz bad data URLztext/plain;charset=US-ASCII;rrNrzDate: %sz%a, %d %b %Y %H:%M:%S GMTzContent-type: %sr]rYzlatin-1zContent-Length: %d )rr rrrSrhrfindrxrstrftimegmtimer] decodebytesr_rrrzrKrr#ioStringIOr() rr^r_rsemiencodingrrfrcrcrd open_datas8          zURLopener.open_data)N)N)N)N)NNN)N)N)N)N)rrrr!rZrrYrr_rr`rar rgrfrurrryrrRrrrrrrrcrcrcrdrIJs.  $   B\     :rIc@seZdZdZddZddZd#ddZd d Zd$d d Zd%d dZ d&ddZ d'ddZ d(ddZ d)ddZ d*ddZd+ddZd,ddZd-dd Zd!d"ZdS).rJz?Derived class with handlers for errors we can handle (perhaps).cOs.tj|g|Ri|i|_d|_d|_dS)Nrr$)rIr auth_cachetriesmaxtries)rrkwargsrcrcrdr szFancyURLopener.__init__cCst||d||S)z3Default error handling -- don't raise an exception.rv)r(rrcrcrdrsz!FancyURLopener.http_error_defaultNc Csl|jd7_|jrN|j|jkrNt|dr2|j}n|j}d|_|||dd|S|||||||}d|_|S)z%Error 302 -- relocated (temporarily).rhttp_error_500rrz)Internal Server Error: Redirect Recursion)rrrrrredirect_internal) rr^rrrrr_rrrcrcrdrCs zFancyURLopener.http_error_302c Csxd|vr|d}nd|vr$|d}ndS|t|jd||}t|}|jdvrnt|||d|||||S)Nr5r6:r7z( Redirection to url '%s' is not allowed.)rrrrr<rr ) rr^rrrrr_r2r@rcrcrdr%s    z FancyURLopener.redirect_internalcCs|||||||S)z*Error 301 -- also relocated (permanently).rCrr^rrrrr_rcrcrdrDAszFancyURLopener.http_error_301cCs|||||||S)z;Error 303 -- also relocated (essentially identical to 302).rrrcrcrdrEEszFancyURLopener.http_error_303cCs2|dur|||||||S||||||SdS)z1Error 307 -- relocated, but turn POST into error.N)rCrrrcrcrdrFIszFancyURLopener.http_error_307Fc Csd|vrt|||||||d}td|} | sHt||||||| \} } | dkrtt|||||||st||||||d|jd} |durt|| || St|| || |SdS)z_Error 401 -- authentication required. This function supports Basic authentication only.r![ ]*([^ ]+)[ ]+realm="([^"]*)"rretry_ _basic_authNrIrrmatchrrrr rr^rrrrr_rstuffrr<rmrvrcrcrdrPs.      zFancyURLopener.http_error_401c Csd|vrt|||||||d}td|} | sHt||||||| \} } | dkrtt|||||||st||||||d|jd} |durt|| || St|| || |SdS)zeError 407 -- proxy authentication required. This function supports Basic authentication only.rrr retry_proxy_rNrrrcrcrdris.      zFancyURLopener.http_error_407cCst|\}}d||}|jd}t|\}} t| \} } | dd} | | d} || || \} } | sr| srdSdt| ddt| dd| f} d| | |jd<|dur||S|||SdS)Nhttp://r@r%s:%s@%srrbrrVrrget_user_passwdrr rr^rmr_rrr2rHrirj proxyselectorrrNrdrcrcrdretry_proxy_http_basic_auths           z*FancyURLopener.retry_proxy_http_basic_authcCst|\}}d||}|jd}t|\}} t| \} } | dd} | | d} || || \} } | sr| srdSdt| ddt| dd| f} d| | |jd<|dur||S|||SdS)Nhttps://rrrrrrbrrrcrcrdretry_proxy_https_basic_auths           z+FancyURLopener.retry_proxy_https_basic_authc Cst|\}}|dd}||d}||||\}}|sD|sDdSdt|ddt|dd|f}d||} |dur|| S|| |SdS)Nrrrrrbrrrrrr rr^rmr_rrrrNrdr2rcrcrdrs       z$FancyURLopener.retry_http_basic_authc Cst|\}}|dd}||d}||||\}}|sD|sDdSdt|ddt|dd|f}d||} |dur|| S|| |SdS)Nrrrrrbrrrrcrcrdretry_https_basic_auths       z%FancyURLopener.retry_https_basic_authrcCs`|d|}||jvr2|r(|j|=n |j|S|||\}}|sJ|rX||f|j|<||fS)Nr)rrprompt_user_passwd)rrrmrQrrNrdrcrcrdrs   zFancyURLopener.get_user_passwdcCsVddl}z.td||f}|d|||f}||fWStyPtYdS0dS)z#Override this in a GUI environment!rNzEnter username for %s at %s: z#Enter password for %s in %s at %s: rp)getpassr KeyboardInterruptprint)rrrmrrNrdrcrcrdrs  z!FancyURLopener.prompt_user_passwd)N)N)N)N)NF)NF)N)N)N)N)r)rrrr!rrrCrrDrErFrrrrrrrrrcrcrcrdrJs(           rJcCstdurtdatS)z8Return the IP address of the magic hostname 'localhost'.Nr ) _localhostrrrcrcrcrdr s r cCsNtdurJztttdaWn&tjyHttddaYn0tS)z,Return the IP addresses of the current host.Nrr ) _thishostrlrrrrrcrcrcrdrs rcCstdurddl}|jatS)z1Return the set of errors raised by the FTP class.Nr) _ftperrorsr4r9)r4rcrcrdrsrcCstdurtdatS)z%Return an empty email Message object.Nr) _noheadersrr#rcrcrcrd noheaderss rc@sJeZdZdZdddZddZdd Zd d Zd d ZddZ ddZ dS)rBz;Class used by open_ftp() for cache of open FTP connections.NTcCs<||_||_||_||_||_||_d|_||_|dSr) rNrdrrzr;r`refcount keepaliveinit)rrNrdrrzr;r`rArcrcrdr szftpwrapper.__init__cCs\ddl}d|_||_|j|j|j|j|j|j |j d |j }|j |dS)Nrr9)r4busyFTPr8connectrrzr`loginrNrdrKr;cwd)rr4_targetrcrcrdr s  zftpwrapper.initc Csddl}||dvr"d}d}n d|}d}z|j|Wn(|jyf||j|Yn0d}|r|szd|}|j|\}}WnJ|jy}z0t|dddkrt t d |WYd}~n d}~00|s|jd|rx|j } z`z|j |Wn>|jyN}z"t d |} || _ | WYd}~n d}~00W|j | n|j | 0d |}nd }|j|\}}d|_t|d |j} |jd7_|| |fS) Nr)rr/zTYPE ArzTYPE zRETR rK550r3zLIST LISTr)r4 endtransferr8voidcmdr9r ntransfercmd error_permr rrpwdr __cause__rr)makefile file_closerr) rrfrr4cmdisdirrPr>rrr?ftpobjrcrcrdr8 sJ &    zftpwrapper.retrfilecCs d|_dSr)rrrcrcrdrK szftpwrapper.endtransfercCsd|_|jdkr|dS)NFr)rr real_closerrcrcrdrN s zftpwrapper.closecCs2||jd8_|jdkr.|js.|dS)Nrr)rrrrrrcrcrdrS szftpwrapper.file_closecCs0|z|jWnty*Yn0dSre)rr8rrrrcrcrdrY s zftpwrapper.real_close)NT) rrrr!rrr8rrrrrcrcrcrdrB s  0rBcCsHi}tjD]4\}}|}|r|dddkr|||dd<q|S)aReturn a dictionary of scheme -> proxy server URL mappings. Scan the environment for variables named _proxy; this seems to be the standard convention. If you need a different way, you can pass a proxies dictionary to the [Fancy]URLopener constructor. iN_proxy)rqenvironrr)rVrvrrcrcrdgetproxies_environmenta s rcCsttjddptjdd}|dkr(dSt|\}}dd|dD}|D]"}|rL||sh||rLdSqLd S) zTest if proxies should not be used for a particular host. Checks the environment for a variable named no_proxy, which should be a list of DNS suffixes separated by commas, or '*' for all hosts. no_proxyrZNO_PROXY*rcSsg|] }|qSrcr)r+rHrcrcrdrj~ rkz,proxy_bypass_environment..rr)rqrrrrendswith)rrhostonlyrzZ no_proxy_listrvrcrcrdproxy_bypass_environmentq s rc Csddlm}t|\}}dd}d|vr4|dr4dSd}|d d D]}|sNqDtd |}|dur|durzt|}||}WntjyYqDYn0||d } |d } | durd|d  dd } nt | d d} d| } || ?| | ?krdSqD|||rDdSqDdS)aj Return True iff this host shouldn't be accessed using a proxy This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. proxy_settings come from _scproxy._get_proxy_settings or get mocked ie: { 'exclude_simple': bool, 'exceptions': ['foo.bar', '*.bar.com', '127.0.0.1', '10.1', '10.0/16'] } r)fnmatchcSsd|d}ttt|}t|dkr8|gddd}|dd>|dd>B|dd >B|d BS) N.r#)rrrrrrrrrrK)rrr r rz)ipAddrryrcrcrdip2num s   z,_proxy_bypass_macosx_sysconf..ip2numrexclude_simpleTN exceptionsrcz(\d+(?:\.\d+)*)(/\d+)?rrr F) rrrrrrrrgroupcountr ) rproxy_settingsrrrzrhostIPrr3r~maskrcrcrd_proxy_bypass_macosx_sysconf s8         rdarwin)_get_proxy_settings _get_proxiescCst}t||Sre)rr)rrrcrcrdproxy_bypass_macosx_sysconf srcCstS)zReturn a dictionary of scheme -> proxy server URL mappings. This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. )rrcrcrcrdgetproxies_macosx_sysconf srcCstrt|St|SdSre)rrrr-rcrcrdr\ sr\cCs tp tSre)rrrcrcrcrdrF srFc Csi}z ddl}Wnty&|YS0z||jd}||dd}|rt||dd}d|vr|dD]4}|dd\}}td |sd ||f}|||<qrn>|dd d kr||d <n$d||d <d||d<d||d<| Wnt t t fy Yn0|S)zxReturn a dictionary of scheme -> proxy server URL mappings. Win32 uses the registry to store proxies. rN;Software\Microsoft\Windows\CurrentVersion\Internet Settings ProxyEnableZ ProxyServerrrrz ^([^/:]+)://z%s://%srrvrz http://%sz https://%srzftp://%sr8) winreg ImportErrorOpenKeyHKEY_CURRENT_USER QueryValueExr rrrClose WindowsErrorrSr)rVrinternetSettings proxyEnableZ proxyServerpraddressrcrcrdgetproxies_registry sF           rcCs tp tS)Return a dictionary of scheme -> proxy server URL mappings. Returns settings gathered from the environment, if specified, or the registry. )rrrcrcrcrdrF sc Csvz ddl}Wnty YdS0z6||jd}||dd}t||dd}WntylYdS0|rv|szdSt|\}}|g}z t |}||kr| |Wntj yYn0z t |}||kr| |Wntj yYn0| d}|D]j} | dkr$d|vr$dS| dd } | d d } | d d} |D] } t| | tjrLdSqLqdS) NrrrZ ProxyOverriderzrrz\.rz.*?)rrrrrr rrrrrxrgetfqdnrr1rrr) rrrrZ proxyOverrideZrawHostrzaddrZfqdnrrrcrcrdproxy_bypass_registry s`             r cCstrt|St|SdS)rN)rrr r-rcrcrdr\H s)NNN)r! __future__rrrrZfuture.builtinsrrrr r r r r Z future.utilsrrrr]rrrZfuture.backportsrZfuture.backports.httprrrrrrparserrrrrrrrrr r!r"r#r$r%r&r'rr(r)rrqr|rrsysrrtrnr collectionsr*collections.abcrTr+rrR__all__rYrr]r rArBrwrGrHrASCIIrrobjectr,r-rCr.r@r/r0rPr2r3r4r5r6r7urandomrr8r9r:rr;rr\rxr1r?rrr<r$r=r>rrvZ nturl2pathrErDr]rIrJrr rrrrrrrBrrrplatform_scproxyrrrrr\rFrr rcrcrcrdsV(  L    ?  y&hH*@ E  z   +4:8  AU  ^<    - 2