o w[eώ@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlmZmZmZddlmZmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(ddl)m*Z*m+Z+zddl,Z,Wn e-ydZ.YnwdZ.gdZ/d e j0dd Z1da2de j3fddddd d d Z4ddZ5gZ6dddZ7ddZ8e 9de j:Z;ddZddZ?GdddZ@Gdd d e@ZAGd!d"d"e@ZBGd#d$d$e@ZCd%d&ZDGd'd(d(e@ZEGd)d*d*ZFGd+d,d,eFZGGd-d.d.eGZHGd/d0d0ZIGd1d2d2eIe@ZJGd3d4d4eIe@ZKejLZMGd5d6d6ZNGd7d8d8e@eNZOGd9d:d:e@eNZPGd;d<dd>eQZReSejTd?rtGd@dAdAeQZUe/VdAGdBdCdCe@ZWGdDdEdEe@ZXdFdGZYdHdIZZGdJdKdKe@Z[dLdMZ\GdNdOdOe@Z]GdPdQdQe]Z^GdRdSdSe@Z_dTZ`ejadUkrddVlbmcZcmdZdndWdXZcdYdZZdiZeGd[d\d\ZfGd]d^d^efZgdahd_d`ZidajdadbZkdaldcddZmdandedfZoGdgdhdhZpdidjZqddkdlZrdmdnZse jtdokr&ddplumvZvmwZwdqdrZxdsdtZydudvZzdwdxZ{dSejadUkr>dydzZ|d{dxZ{d|d}Z}d~dvZzdSeqZ{erZzdS)a 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 OSError); 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('https://www.python.org/') N)URLError HTTPErrorContentTooShortError)urlparseurlspliturljoinunwrapquoteunquote _splittype _splithost _splitport _splituser _splitpasswd _splitattr _splitquery _splitvalue _splittag _to_bytesunquote_to_bytes urlunparse) addinfourl addclosehookFT)!RequestOpenerDirector BaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessor ProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmHTTPPasswordMgrWithPriorAuthAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandler HTTPHandler FileHandler FTPHandlerCacheFTPHandler DataHandlerUnknownHandlerHTTPErrorProcessorurlopeninstall_opener build_opener pathname2url url2pathname getproxies urlretrieve urlcleanup URLopenerFancyURLopenerz%d.%d)cafilecapath cadefaultcontextc Cs|s|s|r9ddl}|dtd|durtdtstdtjtjj||d}| dgt |d }t |} n|rEt |d }t |} n t durOt a } nt } | |||S) aOpen the URL url, which can be either a string or a Request object. *data* must be an object specifying additional data to be sent to the server, or None if no such data is needed. See Request for details. urllib.request module uses HTTP/1.1 and includes a "Connection:close" header in its HTTP requests. The optional *timeout* parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). This only works for HTTP, HTTPS and FTP connections. If *context* is specified, it must be a ssl.SSLContext instance describing the various SSL options. See HTTPSConnection for more details. The optional *cafile* and *capath* parameters specify a set of trusted CA certificates for HTTPS requests. cafile should point to a single file containing a bundle of CA certificates, whereas capath should point to a directory of hashed certificate files. More information can be found in ssl.SSLContext.load_verify_locations(). The *cadefault* parameter is ignored. This function always returns an object which can work as a context manager and has the properties url, headers, and status. See urllib.response.addinfourl for more detail on these properties. For HTTP and HTTPS URLs, this function returns a http.client.HTTPResponse object slightly modified. In addition to the three new methods above, the msg attribute contains the same information as the reason attribute --- the reason phrase returned by the server --- instead of the response headers as it is specified in the documentation for HTTPResponse. For FTP, file, and data URLs and requests explicitly handled by legacy URLopener and FancyURLopener classes, this function returns a urllib.response.addinfourl object. Note that None may be returned if no handler handles the request (though the default installed global OpenerDirector uses UnknownHandler to ensure this never happens). In addition, if proxy settings are detected (for example, when a *_proxy environment variable like http_proxy is set), ProxyHandler is default installed and makes sure the requests are handled through the proxy. rNzJcafile, capath and cadefault are deprecated, use a custom context instead.r:zDYou can't pass both context and any of cafile, capath, and cadefaultzSSL support not available)r;r<zhttp/1.1)r>)warningswarnDeprecationWarning ValueError _have_sslsslcreate_default_contextPurpose SERVER_AUTHset_alpn_protocols HTTPSHandlerr2_openeropen) urldatatimeoutr;r<r=r>r? https_handleropenerrQ%/usr/lib/python3.10/urllib/request.pyr0s2 4       r0cCs|adSN)rJ)rPrQrQrRr1sr1c Csbt|\}}tt||}|}|dkr(|s(tj||fWdS|r0t|d}nt j dd}|j }t ||G||f} d} d} d} d} d |vrWt|d } |r_|| | |  || }|shn| t|7} ||| d 7} |r|| | | q`Wdn1swYWdn1swY| dkr| | krtd | | 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-LengthT1retrieval incomplete: got only %i out of %i bytes)r contextlibclosingr0infoospathnormpathrKtempfileNamedTemporaryFilename_url_tempfilesappendintreadlenwriter)rLfilename reporthookrMurl_typerafpheaderstfpresultbssizeriblocknumblockrQrQrRr6sV           &r6c CsDtD]}zt|WqtyYqwtdd=tr dadSdS)z0Clean up temporary files from urlretrieve calls.N)rfr`unlinkOSErrorrJ) temp_filerQrQrRr7s  r7z:\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. r[Host)full_urlr get_header _cut_port_resublower)requestrLhostrQrQrR request_host-s   rc@seZdZdidddfddZeddZejddZejddZed d Zejd d Zejd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZd#ddZdd Zd!d"ZdS)$rNFc Csp||_i|_i|_d|_||_d|_|D] \}}|||q|dur)t|}||_ ||_ |r6||_ dSdSrS) r|rpunredirected_hdrs_datarM _tunnel_hostitems add_headerrorigin_req_host unverifiablemethod) selfrLrMrprrrkeyvaluerQrQrR__init__?s zRequest.__init__cCs|jr d|j|jS|jS)Nz{}#{})fragmentformat _full_urlrrQrQrRr|QszRequest.full_urlcCs(t||_t|j\|_|_|dSrS)rrrr_parserrLrQrQrRr|Ws  cCsd|_d|_d|_dS)Nrz)rrselectorrrQrQrRr|^s cC|jSrS)rrrQrQrRrMdsz Request.datacCs0||jkr||_|dr|ddSdSdS)NContent-length)r has_header remove_header)rrMrQrQrRrMhs  cCs d|_dSrS)rMrrQrQrRrMrs cCsRt|j\|_}|jdurtd|jt|\|_|_|jr't|j|_dSdS)Nzunknown url type: %r) r rtyperBr|r rrr )rrestrQrQrRrvs zRequest._parsecCs|jdurdnd}t|d|S)z3Return a string indicating the HTTP request method.NPOSTGETr)rMgetattr)rdefault_methodrQrQrR get_method~s zRequest.get_methodcCrrS)r|rrQrQrR get_full_urlszRequest.get_full_urlcCs2|jdkr |js |j|_n||_|j|_||_dS)Nhttps)rrrr|r)rrrrQrQrR set_proxys   zRequest.set_proxycCs |j|jkSrS)rr|rrQrQrR has_proxy zRequest.has_proxycC||j|<dSrS)rp capitalizerrvalrQrQrRrzRequest.add_headercCrrS)rrrrQrQrRadd_unredirected_headerrzRequest.add_unredirected_headercCs||jvp ||jvSrS)rprr header_namerQrQrRrs zRequest.has_headercCs|j||j||SrS)rpgetr)rrdefaultrQrQrRr}s zRequest.get_headercCs |j|d|j|ddSrS)rppoprrrQrQrRrszRequest.remove_headercCsi|j|j}t|SrS)rrplistr)rhdrsrQrQrR header_itemss zRequest.header_itemsrS)__name__ __module__ __qualname__rpropertyr|setterdeleterrMrrrrrrrrr}rrrQrQrQrRr=s8         rc@sNeZdZddZddZddZddZd ejfd d Z dd d Z ddZ d S)rcCs6dt}d|fg|_g|_i|_i|_i|_i|_dS)NPython-urllib/%sz User-agent) __version__ addheadershandlers handle_open handle_errorprocess_responseprocess_request)rclient_versionrQrQrRrs  zOpenerDirector.__init__c CsPt|ds tdt|d}t|D]}|dvrq|d}|d|}||dd}|dr`|d|d}||dd}zt|}Wn tyRYnw|j |i} | |j|<n|dkrj|}|j } n|d krt|}|j } n |d kr~|}|j } nq| |g} | rt| |n| |d }q|rt|j|||dSdS) N add_parentz%expected BaseHandler instance, got %rF)redirect_requestdo_open proxy_open_r[errorrKresponserT)hasattr TypeErrorrdirfind startswithrhrBrrrrr setdefaultbisectinsortrgrr) rhandleraddedmethiprotocol conditionjkindlookuprrQrQrR add_handlersP          zOpenerDirector.add_handlercCdSrSrQrrQrQrRclosezOpenerDirector.closec Gs<||d}|D]}t||}||}|dur|SqdS)NrQ)rr) rchainr meth_nameargsrrfuncrrrQrQrR _call_chains  zOpenerDirector._call_chainNc Cst|tr t||}n |}|dur||_||_|j}|d}|j|gD] }t||}||}q%t d|j |j|j | |||} |d}|j|gD] }t||}||| } qP| S)N_requestzurllib.Request _response) isinstancestrrrMrNrrrrsysauditr|rpr_openr) rfullurlrMrNreqrr processorrrrQrQrRrKs$       zOpenerDirector.opencCsP||jdd|}|r |S|j}||j||d|}|r|S||jdd|S)Nr default_openrunknown unknown_open)rrr)rrrMrrrrQrQrRrs   zOpenerDirector._opencGs~|dvr|jd}|d}d|}d}|}n |j}|d}d}|||f|}|j|}|r/|S|r=|dd f|}|j|SdS) Nhttprrr:z http_error_%sr[_errorrrhttp_error_default)rr)rprotordictrhttp_err orig_argsrrrQrQrRr s"   zOpenerDirector.errorrS) rrrrrrrsocket_GLOBAL_DEFAULT_TIMEOUTrKrrrQrQrQrRrs /  rc Gst}ttttttttt g }t t j dr| tt}|D]!}|D]}t|tr4t||r3||q"t||r>||q"q|D]}||qB|D]}||qL|D]}t|tra|}||qW|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. HTTPSConnection)rrr.r)rrr+r*r/r-rrclientrgrIsetrr issubclassaddremover)rrPdefault_classesskipklasscheckhrQrQrRr29s8           r2c@s(eZdZdZddZddZddZdS) rcC ||_dSrS)parent)rr rQrQrRr` zBaseHandler.add_parentcCrrSrQrrQrQrRrcrzBaseHandler.closecCst|dsdS|j|jkS)N handler_orderT)rr )rotherrQrQrR__lt__gs  zBaseHandler.__lt__N)rrrr rrr rQrQrQrRr]s  rc@s eZdZdZdZddZeZdS)r/zProcess HTTP error responses.icCsH|j|j|}}}d|krdks"n|jd|||||}|S)N,r)codemsgr_r r)rrrrrrrQrQrR http_responsets  z HTTPErrorProcessor.http_responseN)rrr__doc__r rhttps_responserQrQrQrRr/ps  r/c@eZdZddZdS)rcCst|j||||rS)rr|)rrrorrrrQrQrRrsz*HTTPDefaultErrorHandler.http_error_defaultN)rrrrrQrQrQrRr rc@s4eZdZdZdZddZddZeZZZ dZ dS) r c st|}|dvr |dvs|dvr|dkst|j|||||dd}dfdd |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)rrrr z%20)rYz content-typecs"i|] \}}|vr||qSrQ)r.0kvCONTENT_HEADERSrQrR s z8HTTPRedirectHandler.redirect_request..T)rprr)rrr|replacerprrr) rrrorrrpnewurlm newheadersrQr"rRrs  z$HTTPRedirectHandler.redirect_requestc CsHd|vr |d}n d|vr|d}ndSt|}|jdvr)t||d||f|||js7|jr7t|}d|d<t|}t|dtj d}t |j |}| ||||||}|durYdSt |d r|j} |_| |d |jkstt| |jkrt|j ||j|||ni} |_|_| |d d | |<|||jj||jd S) Nlocationurirrftprzz+%s - Redirection to url '%s' is not allowed/r:z iso-8859-1)encodingsafe redirect_dictrr[rN)rschemerranetlocrrr string punctuationrr|rrr0r max_repeatsrjmax_redirectionsinf_msgrirr rKrN) rrrorrrpr&urlpartsnewvisitedrQrQrRhttp_error_302sH         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) rrrr6r7rr<http_error_301http_error_303http_error_307r8rQrQrQrRrs& <rc Cst|\}}|dsd}|}n-|dstd|d|vr+|d}|d|}n|dd}|dkr7d}|d|}t|\}}|durNt|\}} nd}} ||| |fS)a Return (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. r-N//zproxy URL with no authority: %r@r:rX)r rrBrrr) proxyr2r_scheme authorityhost_separatorenduserinfohostportuserpasswordrQrQrR _parse_proxys$         rKc@s"eZdZdZdddZddZdS)rdNcCsb|durt}t|dsJd||_|D]\}}|}t|d||||jfddqdS)Nkeysproxies must be a mappingz%s_opencSs ||||SrSrQ)rrBrrrQrQrR#rz'ProxyHandler.__init__..)r5rproxiesrrsetattrr)rrQrrLrQrQrRrs zProxyHandler.__init__c Cs|j}t|\}}}}|dur|}|jrt|jrdS|r;|r;dt|t|f} t| d} | dd| t|}| ||||ksM|dkrOdS|j j ||j dS)N%s:%sasciiProxy-authorizationBasic rr1)rrKr proxy_bypassr base64 b64encodeencodedecoderrr rKrN) rrrBr orig_type proxy_typerIrJrH user_passcredsrQrQrRr&s" zProxyHandler.proxy_openrS)rrrr rrrQrQrQrRrs  rc@s6eZdZddZddZddZd dd Zd d Zd S)r cCs i|_dSrS)passwdrrQrQrRrDr zHTTPPasswordMgr.__init__cs\t|tr|g}|jvrij|<dD]tfdd|D}||fj||<qdS)NTFc3s|] }|VqdSrS) reduce_uri)ru default_portrrQrR Ns  z/HTTPPasswordMgr.add_password..)rrr`tuple)rrealmr*rIr` reduced_urirQrdrR add_passwordGs   zHTTPPasswordMgr.add_passwordc Cs`|j|i}dD]$}|||}|D]\}}|D]}|||r+|Sqqq dS)NraNN)r`rrbr is_suburi) rrhauthuridomainsrereduced_authuriurisauthinfor*rQrQrRfind_user_passwordRs  z"HTTPPasswordMgr.find_user_passwordTc Cst|}|dr|d}|d}|dpd}nd}|}d}t|\}}|r?|dur?|dur?ddd|} | dur?d || f}||fS) z@Accept authority or URI and extract only the authority and path.r[rr:r-NPirz%s:%d)rr r) rr*repartsr2rDrarportdportrQrQrRrb\s$  zHTTPPasswordMgr.reduce_uricCsN||krdS|d|dkrdS|d}|dddkr |d7}|d|S)zcCheck if test is below base in a URI tree Both args must be URIs in reduced form. TrFr[rXNr-)r)rbasetestprefixrQrQrRrlsszHTTPPasswordMgr.is_suburiN)T)rrrrrjrrrbrlrQrQrQrRr Bs  r c@r)r!cCs0t|||\}}|dur||fSt|d|SrS)r rr)rrhrmrIrJrQrQrRrrs z2HTTPPasswordMgrWithDefaultRealm.find_user_passwordN)rrrrrrQrQrQrRr!s r!cs<eZdZfddZd fdd Zd ddZdd ZZS) r"csi|_tj|i|dSrS) authenticatedsuperrrrkwargs __class__rQrRrsz%HTTPPasswordMgrWithPriorAuth.__init__Fcs<||||durtd|||t||||dSrS)update_authenticatedr{rj)rrhr*rIr`is_authenticatedr~rQrRrjs z)HTTPPasswordMgrWithPriorAuth.add_passwordcCs>t|tr|g}dD]}|D] }|||}||j|<qq dSNra)rrrbrz)rr*rrercrirQrQrRrs   z1HTTPPasswordMgrWithPriorAuth.update_authenticatedcCsDdD]}|||}|jD]}|||r|j|Sq qdSr)rbrzrl)rrmreror*rQrQrRrs   z-HTTPPasswordMgrWithPriorAuth.is_authenticated)F)rrrrrjrr __classcell__rQrQr~rRr"s    r"c@sTeZdZedejZdddZddZddZ d d Z d d Z d dZ e Z e ZdS)r#z1(?:^|,)[ ]*([^ ,]+)[ ]+realm=(["']?)([^"']*)\2NcCs"|durt}||_|jj|_dSrS)r r`rj)r password_mgrrQrQrRrsz!AbstractBasicAuthHandler.__init__ccsvd}tj|D]}|\}}}|dvrtdtd||fVd}q |s9|r0|d}nd}|dfVdSdS)NF)"'zBasic Auth Realm was unquotedTrrz)r#rxfinditergroupsr?r@ UserWarningsplit)rheaderfound_challengemor2r rhrQrQrR _parse_realms  z%AbstractBasicAuthHandler._parse_realmc Cs~||}|s dSd}|D]$}||D]\}}|dkr!|}q|dur0||||Sqq |dur=td|fdS)NbasiczBAbstractBasicAuthHandler does not support the following scheme: %r)get_allrrretry_http_basic_authrB) rauthreqrrrp unsupportedrr2rhrQrQrRhttp_error_auth_reqeds$   z.AbstractBasicAuthHandler.http_error_auth_reqedcCsx|j||\}}|dur:d||f}dt|d}||jd|kr*dS||j||j j ||j dSdS)NrSrVrTr1) r`rrrXrYrZr[r} auth_headerrr rKrN)rrrrhrIpwrawauthrQrQrRrs z.AbstractBasicAuthHandler.retry_http_basic_authcCstt|jdr |j|js|S|ds8|jd|j\}}d||}t | }| dd| |S)Nr Authorizationz{0}:{1}zBasic {}) rr`rr|rrrrrZrXstandard_b64encoder[rstrip)rrrIr` credentialsauth_strrQrQrR http_requests    z%AbstractBasicAuthHandler.http_requestcCsNt|jdr%d|jkrdkrnn |j|jd|S|j|jd|S)NrrrTF)rr`rrr|)rrrrQrQrRr s z&AbstractBasicAuthHandler.http_responserS)rrrrecompileIrrrrrrr https_requestrrQrQrQrRr#s   r#c@eZdZdZddZdS)r$rcC|j}|d|||}|S)Nwww-authenticate)r|r)rrrorrrprLrrQrQrRhttp_error_401s z#HTTPBasicAuthHandler.http_error_401N)rrrrrrQrQrQrRr$ r$c@r)r%rUcCrNproxy-authenticate)rr)rrrorrrprDrrQrQrRhttp_error_407)s z$ProxyBasicAuthHandler.http_error_407N)rrrrrrQrQrQrRr%%rr%c@sNeZdZdddZddZddZdd Zd d Zd d ZddZ ddZ dS)r&NcCs4|durt}||_|jj|_d|_d|_d|_dSNr)r r`rjretried nonce_count last_nonce)rr`rQrQrRrCs  z"AbstractDigestAuthHandler.__init__cC d|_dSr)rrrQrQrRreset_retry_countLr z+AbstractDigestAuthHandler.reset_retry_countcCs~||d}|jdkrt|jdd|d|jd7_|r;|d}|dkr/|||S|dkr=td|dSdS) Nizdigest auth failedr[rdigestrzEAbstractDigestAuthHandler does not support the following scheme: '%s')rrrr|rrretry_http_digest_authrB)rrrrrprr2rQrQrRrOs       z/AbstractDigestAuthHandler.http_error_auth_reqedcCsz|dd\}}ttdt|}|||}|r;d|}|j|jd|kr)dS||j||j j ||j d}|SdS)Nrr[z Digest %sr1) rparse_keqv_listfilterparse_http_listget_authorizationrprrrr rKrN)rrrtoken challengechalauth_valresprQrQrRrcs z0AbstractDigestAuthHandler.retry_http_digest_authcCs@d|j|tf}|dtd}t|}|ddS)Nz %s:%s:%s:rT)rtimectimerZ _randombyteshashlibsha1 hexdigest)rnoncesbdigrQrQrR get_cnonceos z$AbstractDigestAuthHandler.get_cnoncecCsz|d}|d}|d}|dd}|dd}Wn ty%YdSw||\}} |dur3dS|j||j\} } | durCdS|jdurP||j|} nd} d| || f} d||j f}|durt| || d|||f}n=d | d vr||j kr|j d 7_ nd |_ ||_ d |j }| |}d |||d ||f}| || |}ntd|d| |||j |f}|r|d|7}| r|d| 7}|d|7}|r|d||f7}|S)Nrhrqop algorithmMD5opaquez%s:%s:%srSr,r[z%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_implsr`rrr|rMget_entity_digestrrrrrrr)rrrrhrrrrHKDrIrentdigA1A2respdigncvaluecnoncenoncebitrwrQrQrRrzs^            z+AbstractDigestAuthHandler.get_authorizationcsD|dkr ddn|dkrddntd|fdd}|fS)NrcSt|dSNrT)rmd5rZrxrQrQrRrPz?AbstractDigestAuthHandler.get_algorithm_impls..SHAcSrr)rrrZrrrQrQrRrPrz.Unsupported digest authentication algorithm %rcsd||fS)NrSrQ)rdrrQrRrPs)rB)rrrrQrrRrs   z-AbstractDigestAuthHandler.get_algorithm_implscCrrSrQ)rrMrrQrQrRrrz+AbstractDigestAuthHandler.get_entity_digestrS) rrrrrrrrrrrrQrQrQrRr&8s    > r&c@s eZdZdZdZdZddZdS)r'zAn 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)Nr[r)rr|rrrrrorrrprretryrQrQrRrs z$HTTPDigestAuthHandler.http_error_401N)rrrrrr rrQrQrQrRr's  r'c@seZdZdZdZddZdS)r(Proxy-AuthorizationrcCs"|j}|d|||}||Sr)rrrrrQrQrRrs z%ProxyDigestAuthHandler.http_error_407N)rrrrr rrQrQrQrRr(s r(c@s6eZdZd ddZddZddZdd Zd d Zd S)AbstractHTTPHandlerrcCrrS _debuglevel)r debuglevelrQrQrRrr zAbstractHTTPHandler.__init__cCrrSr)rlevelrQrQrRset_http_debuglevelr z'AbstractHTTPHandler.set_http_debuglevelcCstjj|j|SrS)rrHTTPConnection_get_content_lengthrMrrrrQrQrRrsz'AbstractHTTPHandler._get_content_lengthc Cs|j}|s td|jdurI|j}t|trd}t||ds'|dd|dsI|dsI||}|durC|dt|n|dd|}| r\t |j \}}t |\}} |dsg|d||j jD]\} } | } || s~|| | qk|S) N no host givenz\POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.z Content-type!application/x-www-form-urlencodedrTransfer-encodingchunkedr{)rrrMrrrrrrrr rr r rr) rrrrMrcontent_lengthsel_hostr2selsel_pathrerrQrQrR do_request_sH          zAbstractHTTPHandler.do_request_c s@|j}|s td||fd|ji|}||jt|jfdd|j Ddd<dd D|j rWi}d}|vrO|||<|=|j |j |d z*z|j | |j|j|d d Wnty{}zt|d }~ww|} Wn||jr|jd |_|| _| j| _| S) zReturn an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client. rrNcsi|] \}}|vr||qSrQrQrrprQrRr$)s z/AbstractHTTPHandler.do_open..r ConnectioncSsi|] \}}||qSrQ)title)rrerrQrQrRr$6srrr)encode_chunkedN)rrrNset_debuglevelrrrupdaterprr set_tunnelrrrrMrrx getresponsersockrrLreasonr) r http_classrhttp_conn_argsrrtunnel_headersproxy_auth_hdrerrrOrQrrRrsF        zAbstractHTTPHandler.do_openNr)rrrrrrrrrQrQrQrRrs   &rc@seZdZddZejZdS)r)cCs|tjj|SrS)rrrrrrrQrQrR http_open`szHTTPHandler.http_openN)rrrr rrrrQrQrQrRr)^s r)rc@s$eZdZdddZddZejZdS)rIrNcCst||||_||_dSrS)rr_context_check_hostname)rrr>check_hostnamerQrQrRris  zHTTPSHandler.__init__cCs|jtjj||j|jdS)N)r>r)rrrrrrr rQrQrR https_openns zHTTPSHandler.https_open)rNN)rrrrrrrrrQrQrQrRrIgs  rIc@s.eZdZdddZddZddZeZeZdS) rNcCs$ddl}|dur |j}||_dSr)http.cookiejar cookiejar CookieJar)rrrrQrQrRrws  zHTTPCookieProcessor.__init__cCs|j||SrS)radd_cookie_headerrrQrQrRr}s z HTTPCookieProcessor.http_requestcCs|j|||SrS)rextract_cookies)rrrrQrQrRrsz!HTTPCookieProcessor.http_responserS)rrrrrrrrrQrQrQrRrvs  rc@r)r.cCs|j}td|)Nzunknown url type: %s)rr)rrrrQrQrRrs zUnknownHandler.unknown_openN)rrrrrQrQrQrRr.rr.cCsNi}|D] }|dd\}}|ddkr |ddkr |dd}|||<q|S)z>Parse list of key=value strings where keys are not duplicated.=r[rrrX)r)lparsedeltr r!rQrQrRrs  rcCsg}d}d}}|D]5}|r||7}d}q |r)|dkrd}q |dkr$d}||7}q |dkr5||d}q |dkr;d}||7}q |rG||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. rzF\TrrcSsg|]}|qSrQ)r)rpartrQrQrR rz#parse_http_list..)rg)rresrescaper currQrQrRrs4    rc@s(eZdZddZdZddZddZdS)r*cCsZ|j}|dddkr(|dddkr(|jr(|jdkr(|j|vr&tddS||S)Nr:r@rr- localhost-file:// scheme is supported only on localhost)rr get_namesropen_local_file)rrrLrQrQrR file_opens&  zFileHandler.file_openNcCsftjdur0zttddttdt_WtjStjy/tdft_YtjSwtjS)Nr!r:)r*namesrgrgethostbyname_ex gethostnamegaierror gethostbynamerrQrQrRr#s  zFileHandler.get_namesc Csddl}ddl}|j}|j}t|}zYt|}|j}|jj |j dd} | |d} | d| p1d|| f} |r?t |\}} |rK| sbt||vrg|rTd||} nd|} tt|d| | WSWtdWtdty{}zt|d}~ww) NrTusegmtz6Content-type: %s Content-length: %d Last-modified: %s text/plainfile://rbzfile not on local host) email.utils mimetypesrrr4r`statst_sizeutils formatdatest_mtime guess_typemessage_from_stringr _safe_gethostbynamer#rrKrxr)rremailr1rrl localfilestatsrtmodifiedmtyperpruorigurlexprQrQrRr$sB    zFileHandler.open_local_file)rrrr%r&r#r$rQrQrQrRr*s   r*cCs$zt|WStjyYdSwrS)rr*r))rrQrQrRr9s  r9c@seZdZddZddZdS)r+c Csddl}ddl}|j}|stdt|\}}|dur|j}nt|}t|\}}|r2t|\}}nd}t |}|p;d}|p?d}zt |}Wnt yW}zt|d}~wwt |j\} } | d} ttt | } | dd| d} } | r| ds| dd} z_|||||| |j} | rdpd}| D]}t|\}}|d kr|d vr|}q| | |\}}d}||jd}|r|d |7}|dur|dkr|d |7}t|}t|||jWS|jy}zt||d}~ww) Nrftp error: no host givenrzr-rXr[rDraArrrrBzContent-type: %s zContent-length: %d )ftplibr1rrr FTP_PORTrhrrr rr*rxrrrrmap connect_ftprNrrupperretrfiler7r|r:r8r all_errors)rrrFr1rrurIr`rraattrsdirsrTfwrattrrroretrlenrpr>r@rQrQrRftp_opensd            zFTPHandler.ftp_openc Cst||||||ddS)NF) persistent) ftpwrapper)rrIr`rrurNrNrQrQrRrI0szFTPHandler.connect_ftpN)rrrrRrIrQrQrQrRr+s 4r+c@s<eZdZddZddZddZddZd d Zd d Zd S)r,cCs"i|_i|_d|_d|_d|_dS)Nr<r)cacherNsoonestdelay max_connsrrQrQrRr7s  zCacheFTPHandler.__init__cCrrS)rX)rtrQrQrR setTimeout>r zCacheFTPHandler.setTimeoutcCrrS)rY)rr'rQrQrR setMaxConnsAr zCacheFTPHandler.setMaxConnscCsr|||d||f}||jvrt|j|j|<nt|||||||j|<t|j|j|<||j|S)Nr-)joinrVrrXrNrT check_cache)rrIr`rrurNrNrrQrQrRrIDs    zCacheFTPHandler.connect_ftpcCst}|j|kr(t|jD]\}}||kr'|j||j|=|j|=qtt|j|_t |j|j krat|jD]\}}||jkrT|j|=|j|=nqAtt|j|_dSdSrS) rrWrrNrrVrminvaluesrjrY)rrZr r!rQrQrRr^Os$  zCacheFTPHandler.check_cachecCs0|jD]}|q|j|jdSrS)rVr`rclearrN)rconnrQrQrR clear_cachecs  zCacheFTPHandler.clear_cacheN) rrrrr[r\rIr^rcrQrQrQrRr,4s r,c@r)r-cCs~|j}|dd\}}|dd\}}t|}|dr't|}|dd}|s+d}td|t|f}t t |||S)N:r[rz;base64itext/plain;charset=US-ASCIIz$Content-type: %s Content-length: %d ) r|rrendswithrX decodebytesr:r8rjrioBytesIO)rrrLr2rM mediatyperprQrQrR data_openjs     zDataHandler.data_openN)rrrrkrQrQrQrRr-irr-rnt)r4r3cCt|S)zOS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.)r pathnamerQrQrRr4r4cCrm)zOS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.)r rnrQrQrRr3rpr3c@seZdZdZdZdeZd*ddZddZdd Z d d Z d d Z d*ddZ d*ddZ d*ddZd+ddZddZd*ddZd*ddZddZerRddZd*d d!Zd"d#Zd$d%Zd&d'Zd*d(d)ZdS),r8a,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|durt}t|ds Jd||_|d|_ |d|_ d |j fd g|_ g|_ tj|_d|_t|_dS) NzW%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methodsclassr) stacklevelrMrNkey_file cert_filez User-Agent)Acceptz*/*)rrr?r@rAr5rrQrrsrtversionr_URLopener__tempfilesr`rw_URLopener__unlink tempcacheftpcache)rrQx509rrQrQrRrs    zURLopener.__init__cC |dSrS)rrrQrQrR__del__rzURLopener.__del__cCr|rS)cleanuprrQrQrRrrzURLopener.closec CsV|jr|jD]}z||WqtyYqw|jdd=|jr)|jdSdSrS)rwrxrxryra)rrTrQrQrRr~s   zURLopener.cleanupcGs|j|dS)zdAdd a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')N)rrg)rrrQrQrR addheaderszURLopener.addheaderc CsRtt|}t|dd}|jr&||jvr&|j|\}}t|d}t|||St|\}}|s0d}||jvrK|j|}t|\}} t| \} } | |f}nd}d|} ||_ | dd} t || rc| d krr|rl| |||S| ||Sz|durt|| |WSt|| ||WSttfyty} z td | td d} ~ ww) z6Use URLopener().open(file) instead of open(file, 'r').z%/:=&?~#+!$,;'@()*[]|r/r/rTNopen_-rr$z socket errorr:)rrr ryrKrr rQr rr%ropen_unknown_proxy open_unknownrrrrxwith_tracebackrexc_info)rrrMrlrprourltyperLrB proxyhostrrrerrQrQrRrKs@            zURLopener.opencCst|\}}tdd|)/Overridable interface to open unknown URL type. url errorzunknown url typer rx)rrrMrrLrQrQrRrs  zURLopener.open_unknowncCst|\}}tdd||)rrzinvalid proxy for %sr)rrBrrMrrLrQrQrRrs zURLopener.open_unknown_proxycCs tt|}|jr||jvr|j|St|\}}|durE|r#|dkrEz||}|}|tt|d|fWSt yDYnw| ||}z|} |rXt |d} n9t|\} } t| pbd\} } t | pjd\} } t | prd\} } t j| d} t| \}}|j|t |d} zO|| f}|jdur||j|<d}d}d}d}d | vrt| d }|r|||| ||}|sn|t|7}| ||d7}|r||||qW| n| wW|n|w|dkr||krtd ||f||S) ztretrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.NrTr[rUrzrWrXrrYrZr\)rrryr r$r_rr4r rxrKrrr`rasplitextrcmkstemprwrgfdopenrhrirjrkr)rrLrlrmrMrurl1rorrprqgarbagerasuffixfdrrrsrtrirurvrQrQrRretrievesv                  zURLopener.retrievecCsd}d}t|trt|\}}|rt|\}}t|}|}n:|\}}t|\}}t|\} } | }d}| dkr;d}nt| \}} |rIt|\}}|rRd| || f}t|rX|}|s_tdd|rpt|}t |  d} nd} |rt|}t |  d} nd} ||} i}| rd| |d<| rd| |d <|r||d <d |d <|j D]\}}|||<q|durd |d<| d|||n| jd||dz| }Wn tjjytdwd|jkrdkrnn t||jd||jS|||j|j|j|j|S)aMake an HTTP connection using connection_class. This is an internal method that should be called from open_http() or open_https(). Arguments: - connection_factory should take a host name and return an HTTPConnection instance. - url is the url to retrieval or a host, relative-path pair. - data is payload for a POST request or None. Nrz %s://%s%sz http errorrrTzBasic %srrr{rrrz Content-Typerrrz$http protocol error: bad status linerrhttp:)rrr rr r rrWrxrXrYrZr[rrrrr BadStatusLinerstatusrr http_errorror)rconnection_factoryrLrM user_passwd proxy_passwdrrrealhostrr proxy_authr http_connrprrrrQrQrR_open_generic_httpOsv             zURLopener._open_generic_httpcCs|tjj||S)zUse HTTP protocol.)rrrrrrLrMrQrQrR open_httprzURLopener.open_httpc Csbd|}t||r(t||}|dur||||||} n |||||||} | r(| S||||||S)zHandle http errors. Derived class can override this, or provide specific handlers named http_error_DDD where DDD is the 3-digit error code.z http_error_%dN)rrr) rrLroerrcodeerrmsgrprMrerrrrQrQrRrs  zURLopener.http_errorcCs|t||||d)z>Default error handler: close the connection and raise OSError.N)rrrrLrorrrprQrQrRrszURLopener.http_error_defaultcCstjj||j|jdS)N)rsrt)rrrrsrt)rrrQrQrR_https_connectionszURLopener._https_connectioncCs||j||S)zUse HTTPS protocol.)rrrrQrQrR open_httpsszURLopener.open_httpscCsXt|ts td|dddkr'|dddkr'|dddkr'td ||S) z/Use local file or FTP depending on form of URL.zEfile error: proxy support for file protocol currently not implementedNr:r@rr- z localhost/r")rrrrrBr$rrQrQrR open_files 4 zURLopener.open_filec CsFddl}ddl}t|\}}t|}zt|}Wnty,}zt|j|j d}~ww|j } |j j |j dd} ||d} |d| pFd| | f} |se|} |dddkr\d |} tt|d | | St|\}}|st|tftvr|} |dddkrd |} n|dd d krtd |tt|d | | Std)zUse local file.rNTr+z6Content-Type: %s Content-Length: %d Last-modified: %s r-r[r-r.r/r:z./zAlocal file url may start with / or file:. Unknown url of type: %sz#local file error: not on local host)r0r1r r4r`r2rxrstrerrorrlr3r4r5r6r7r8rrKr rr*r!thishostrB)rrLr:r1rrT localnamer<ertr=r>rpurlfilerurQrQrRr$sB     zURLopener.open_local_filec Csht|ts tdddl}t|\}}|stdt|\}}t|\}}|r.t|\}}nd}t|}t|p8d}t|p>d}t |}|sOddl }|j }nt |}t|\}} t|}|d} | dd| d} } | ry| dsy| dd} | r| dsd| d<|||d| f} t|jtkrt|jD]} | | kr|j| }|j| =|qzl| |jvrt||||| |j| <| sd }nd }| D]}t|\}}|d kr|d vr|}q|j| | |\}}|d |d}d}|r|d|7}|dur |dkr |d|7}t|}t||d |WSty3}z td| t!"dd}~ww)zUse FTP protocol.zCftp error: proxy support for ftp protocol currently not implementedrNrArzr-rXr[rBrrrCzftp:zContent-Type: %s zContent-Length: %d z ftp error %rr:)#rrrr1r r rrr rr*rFrGrhrrr]rjrz MAXFTPCACHErrrTrrrJrKr7r:r8r ftperrorsrrr)rrLr1rrarurIr`rFrMrNrTrr r!rrPrrorQr>rpr@rQrQrRopen_ftpsp                  zURLopener.open_ftpc Cs6t|ts tdz |dd\}}Wn tytddw|s$d}|d}|dkrDd ||d vrD||dd }|d |}nd }g}|d t d t t|d||dkrot | dd}nt|}|dt||d ||d|}t|}t|}t|||S)zUse "data" URL.zEdata error: proxy support for data protocol currently not implementedrr[z data errorz bad data URLre;rrNrzzDate: %sz%a, %d %b %Y %H:%M:%S GMTzContent-type: %srXrTzlatin-1zContent-Length: %d )rrrrrBrxrfindrgrstrftimegmtimerXrgrZr[r rjr]r:r8rhStringIOr) rrLrMrsemir.rrpfrQrQrR open_data1s:            zURLopener.open_datarSNNN)rrrrrwrrvrr}rr~rrKrrrrrrrrCrrrr$rrrQrQrQrRr8s0   $  A \    :r8c@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)&r9z?Derived class with handlers for errors we can handle (perhaps).cOs.tj|g|Ri|i|_d|_d|_dS)Nrr)r8r auth_cachetriesmaxtriesr|rQrQrRr^s zFancyURLopener.__init__cCst||d||S)z3Default error handling -- don't raise an exception.r)rrrQrQrRrdrz!FancyURLopener.http_error_defaultNc Csz|jd7_z1|jr)|j|jkr)t|dr|j}n|j}|||dd|Wd|_S|||||||}|Wd|_Sd|_w)z%Error 302 -- relocated (temporarily).r[http_error_500rz)Internal Server Error: Redirect Recursionr)rrrrrredirect_internal) rrLrorrrprMrrrrQrQrRr<hs   zFancyURLopener.http_error_302c Csxd|vr |d}n d|vr|d}ndS|t|jd||}t|}|jdvr7t|||d|||||S)Nr)r*rdr+z( Redirection to url '%s' is not allowed.)rrrrr2rrK) rrLrorrrprMr&r9rQrQrRrzs     z FancyURLopener.redirect_internalcC|||||||S)z*Error 301 -- also relocated (permanently).r<rrLrorrrprMrQrQrRr=zFancyURLopener.http_error_301cCr)z;Error 303 -- also relocated (essentially identical to 302).rrrQrQrRr>rzFancyURLopener.http_error_303cCs.|dur|||||||S||||||S)z1Error 307 -- relocated, but turn POST into error.N)r<rrrQrQrRr?szFancyURLopener.http_error_307Fc Cd|vrt|||||||d}td|} | s$t||||||| \} } | dkr:t|||||||sFt||||||d|jd} |durYt|| || St|| || |S)z_Error 401 -- authentication required. This function supports Basic authentication only.r![ ]*([^ ]+)[ ]+realm="([^"]*)"rretry_ _basic_authNr8rrmatchrrrr rrLrorrrprMrstuffrr2rhrerQrQrRr.      zFancyURLopener.http_error_401c Cr)zeError 407 -- proxy authentication required. This function supports Basic authentication only.rrr retry_proxy_rNrrrQrQrRrrzFancyURLopener.http_error_407cCt|\}}d||}|jd}t|\}} t| \} } | dd} | | d} || || \} } | s9| s9dSdt| ddt| dd| f} d| | |jd<|durZ||S|||S)Nhttp://rrAr[%s:%s@%srzrr rQr rget_user_passwdr rKrrLrhrMrrr&rBrr proxyselectorrrIr`rQrQrRretry_proxy_http_basic_auth           z*FancyURLopener.retry_proxy_http_basic_authcCr)Nhttps://rrAr[rrzrrrrQrQrRretry_proxy_https_basic_authrz+FancyURLopener.retry_proxy_https_basic_authc Ct|\}}|dd}||d}||||\}}|s"|s"dSdt|ddt|dd|f}d||} |dur@|| S|| |S)NrAr[rrzrrr rrr rK rrLrhrMrrrrIr`r&rQrQrRr        z$FancyURLopener.retry_http_basic_authc Cr)NrAr[rrzrrrrrQrQrRretry_https_basic_auth rz%FancyURLopener.retry_https_basic_authrcCs`|d|}||jvr|r|j|=n|j|S|||\}}|s%|r,||f|j|<||fS)NrA)rrprompt_user_passwd)rrrhrcrrIr`rQrQrRr s   zFancyURLopener.get_user_passwdcCsRddl}ztd||f}|d|||f}||fWSty(tYdSw)z#Override this in a GUI environment!rNzEnter username for %s at %s: z#Enter password for %s in %s at %s: rk)getpassinputKeyboardInterruptprint)rrrhrrIr`rQrQrRr" s  z!FancyURLopener.prompt_user_passwdrS)NFr )rrrrrrr<rr=r>r?rrrrrrrrrQrQrQrRr9[s*           r9cCtdur tdatS)z8Return the IP address of the magic hostname 'localhost'.Nr!) _localhostrr*rQrQrQrRr!2  r!cCsRtdur'ztttdaWtStjy&ttddaYtSwtS)z,Return the IP addresses of the current host.Nr:r!) _thishostrgrr'r(r)rQrQrQrRr: srcCstdur ddl}|jatS)z1Return the set of errors raised by the FTP class.Nr) _ftperrorsrFrL)rFrQrQrRrE srcCr)z%Return an empty email Message object.Nrz) _noheadersr:r8rQrQrQrR noheadersN rrc@sNeZdZdZ  dddZddZdd Zd d Zd d ZddZ ddZ dS)rTz;Class used by open_ftp() for cache of open FTP connections.NTcCsP||_||_||_||_||_||_d|_||_z|WdS| r) rIr`rrurNrNrefcount keepaliveinitr)rrIr`rrurNrNrSrQrQrRr[ szftpwrapper.__init__cCs\ddl}d|_||_|j|j|j|j|j|j |j d |j }|j |dS)Nrr-)rFbusyFTPr,connectrrurNloginrIr`r]rNcwd)rrF_targetrQrQrRrk s  zftpwrapper.initc Csddl}||dvrd}d}nd|}d}z|j|Wn|jy3||j|Ynwd}|rs|sszd|}|j|\}}Wn*|jyr}zt|dddkrht d | t d WYd}~nd}~ww|s|jd|r|j } z%z|j|Wn|jy}zt d ||d}~wwW|j| n|j| wd |}nd }|j|\}}d|_t|d |j} |jd7_|| |fS)Nr)rrBzTYPE Ar[zTYPE zRETR r550z ftp error: %rr:zLIST LISTr/)rF endtransferr,voidcmdrLr ntransfercmd error_permrrrrrpwdrrrmakefile file_closerr) rrTrrFcmdisdirrbrQrrftpobjrQrQrRrKt sX       zftpwrapper.retrfilecCrr)rrrQrQrRr r zftpwrapper.endtransfercCs d|_|jdkr|dSdS)NFr)rr real_closerrQrQrRr s  zftpwrapper.closecCs:||jd8_|jdkr|js|dSdSdS)Nr[r)rrrrrrQrQrRr s  zftpwrapper.file_closecCs0|z|jWdStyYdSwrS)rr,rrrrQrQrRr s zftpwrapper.real_close)NT) rrrrrrrKrrrrrQrQrQrRrTX s  - rTcCsi}g}tjD]3}t|dkr<|ddkr<|dddkr 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. rirNrBREQUEST_METHODr_proxy)r`environrMrjrrgr)rQ environmentrer proxy_namerQrQrRgetproxies_environment s& ,     rcCs|durt}z|d}Wn tyYdSw|dkrdS|}t|\}}|dD]-}|}|rZ|d}|}||ksF||krIdSd|}||sW||rZdSq-dS)zTest if proxies should not be used for a particular host. Checks the proxy dict for the value of no_proxy, which should be a list of comma separated DNS suffixes, or '*' for all hosts. NnoF*Tr.)rrrr rrlstriprf)rrQno_proxyhostonlyrurerQrQrRproxy_bypass_environment s.    r c Cs&ddlm}t|\}}dd}d|vr|drdSd}|d d D]n}|s'q"td |}|dur|durJz t|}||}Wn tyIYq"w||d } |d } | durgd|d  dd } nt | d d} | dksw| dkrxq"d| } || ?| | ?krdSq"|||rdSq"dS)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|dkr|gddd}|dd>|dd>B|dd >B|d BS) Nrr)rrrrrr[rr:rr)rrrHrhrj)ipAddrrtrQrQrRip2num s  ,z,_proxy_bypass_macosx_sysconf..ip2numrexclude_simpleTN exceptionsrQz(\d+(?:\.\d+)*)(/\d+)?r[r:r F) r r rrrrr*rxgroupcountrh) rproxy_settingsr r rurhostIPrr'rwmaskrQrQrR_proxy_bypass_macosx_sysconf sB       rdarwin)_get_proxy_settings _get_proxiescCst}t||SrS)rr)rrrQrQrRproxy_bypass_macosx_sysconfE s rcCstS)zReturn a dictionary of scheme -> proxy server URL mappings. This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. )rrQrQrQrRgetproxies_macosx_sysconfI srcCt}|r t||St|S)zReturn True, if host should be bypassed. Checks proxy settings gathered from the environment, if specified, or from the MacOSX framework SystemConfiguration. )rr rrrQrQrQrRrWS  rWcC tptSrS)rrrQrQrQrRr5` rr5c Cs8i}zddl}Wn ty|YSwzz||jd}||dd}|rt||dd}d|vr=d|vr=d|}|dD]%}|dd \}}t d |sc|d vr[d |}n|d krcd|}|||<qB| d rt dd|d }| dp|||d<| dp||d<| W|St ttfyY|Sw)zxReturn a dictionary of scheme -> proxy server URL mappings. Win32 uses the registry to store proxies. rN;Software\Microsoft\Windows\CurrentVersion\Internet Settings ProxyEnable ProxyServerrrzhttp={0};https={0};ftp={0}r[z (?:[^/:]+)://)rrr,rsockszsocks://z ^socks://z socks4://rr)winreg ImportErrorOpenKeyHKEY_CURRENT_USER QueryValueExrrrrrrrCloserxrBr)rQr'internetSettings proxyEnable proxyServerpraddressrQrQrRgetproxies_registrye sR        r2cCr")zReturn a dictionary of scheme -> proxy server URL mappings. Returns settings gathered from the environment, if specified, or the registry. )rr2rQrQrQrRr5 s c Cshzddl}Wn tyYdSwz||jd}||dd}t||dd}Wn ty6YdSw|r;|s=dSt|\}}|g}zt |}||krU| |Wn ty_Ynwzt |}||kro| |Wn tyyYnw| d}|D]0} | dkrd|vrdS| dd } | d d } | d d} |D]} t| | tjrdSqqdS) Nrr#r$ ProxyOverriderzrr[z\.rz.*?)r'r(r)r*r+rrxr rr*rggetfqdnrr%rrr) rr'r-r. proxyOverriderawHostruaddrfqdnrxrrQrQrRproxy_bypass_registry sp              r:cCr)zReturn True, if host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. )rr r:r rQrQrRrW r!rrS)~rrXrr:r http.clientrrhr` posixpathrrr4rrrcr]r? urllib.errorrrr urllib.parserrrrr r r r r rrrrrrrrrurllib.responserrrDr(rC__all__ version_inforrJrr0r1rfr6r7rASCIIr~rrrr2rr/rrrKrr r!r"r#r$r%urandomrr&r'r(rr)rrrIrgrr.rrr*r9r+r,r-rre nturl2pathr4r3rzr8r9rr!rrrrrrrTrr rplatform_scproxyrrrrrWr5r2r:rQrQrQrRsSP   O ?m$q!+@ o  v  +395! @W  _ %% A 1 2