o ?Ogn@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`ZidajdadbZkdaldcddZmdandedfZoGdgdhdhZpdidjZqddkdlZrdmdnZsdodpZte judqkr*ddrlvmwZwmxZxdsdtZydudvZzdwdxZ{dydzZ|dSejadUkrBd{d|Z}d}dzZ|d~dZ~ddxZ{dSeqZ|erZ{dS)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_sslsslZcreate_default_contextZPurposeZ SERVER_AUTHZset_alpn_protocols HTTPSHandlerr2_openeropen) urldatatimeoutr;r<r=r>r?Z https_handleropenerrL5/opt/alt/python310/lib64/python3.10/urllib/request.pyr0s2 4       r0cCs|adSN)rF)rKrLrLrMr1sr1c 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 contextlibclosingr0infoospathnormpathrGtempfileZNamedTemporaryFilename_url_tempfilesappendintreadlenwriter)rHfilename reporthookrIZurl_typer\fpheaderstfpresultbssizercblocknumblockrLrLrMr6sV           &r6c CsDtD]}zt|WqtyYqwtdd=tr dadSdS)z0Clean up temporary files from urlretrieve calls.N)r`r[unlinkOSErrorrF)Z temp_filerLrLrMr7s  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. rVHost)full_urlr get_header _cut_port_resublower)requestrHhostrLrLrM request_host-s   r{c@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||_ dSdSrN) rtriunredirected_hdrs_datarI _tunnel_hostitems add_headerr{origin_req_host unverifiablemethod) selfrHrIrirrrkeyvaluerLrLrM__init__?s zRequest.__init__cCs|jr d|j|jS|jS)Nz{}#{})fragmentformat _full_urlrrLrLrMrtQszRequest.full_urlcCs(t||_t|j\|_|_|dSrN)rrrr_parserrHrLrLrMrtWs  cCsd|_d|_d|_dS)Nrr)rrselectorrrLrLrMrt^s cC|jSrN)r}rrLrLrMrIdsz Request.datacCs0||jkr||_|dr|ddSdSdS)NContent-length)r} has_header remove_header)rrIrLrLrMrIhs  cCs d|_dSrN)rIrrLrLrMrIrs cCsRt|j\|_}|jdurtd|jt|\|_|_|jr't|j|_dSdS)Nzunknown url type: %r) r rtyperBrtr rzrr )rrestrLrLrMrvs zRequest._parsecCs|jdurdnd}t|d|S)z3Return a string indicating the HTTP request method.NPOSTGETr)rIgetattr)rZdefault_methodrLrLrM get_method~s zRequest.get_methodcCrrN)rtrrLrLrM get_full_urlszRequest.get_full_urlcCs2|jdkr |js |j|_n||_|j|_||_dS)Nhttps)rr~rzrtr)rrzrrLrLrM set_proxys   zRequest.set_proxycCs |j|jkSrN)rrtrrLrLrM has_proxy zRequest.has_proxycC||j|<dSrN)ri capitalizerrvalrLrLrMrzRequest.add_headercCrrN)r|rrrLrLrMadd_unredirected_headerrzRequest.add_unredirected_headercCs||jvp ||jvSrN)rir|r header_namerLrLrMrs zRequest.has_headercCs|j||j||SrN)rigetr|)rrdefaultrLrLrMrus zRequest.get_headercCs |j|d|j|ddSrN)ripopr|rrLrLrMrszRequest.remove_headercCsi|j|j}t|SrN)r|rilistr)rhdrsrLrLrM header_itemss zRequest.header_itemsrN)__name__ __module__ __qualname__rpropertyrtsetterdeleterrIrrrrrrrrrurrrLrLrLrMr=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)rZclient_versionrLrLrMrs  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_rVerrorrGresponseryT)hasattr TypeErrorrdirfind startswithrbrBrrrrr setdefaultbisectZinsortrarr) rhandlerZaddedmethiprotocolZ conditionjkindlookuprrLrLrM add_handlersP          zOpenerDirector.add_handlercCdSrNrLrrLrLrMclosezOpenerDirector.closec Gs<||d}|D]}t||}||}|dur|SqdS)NrL)rr) rchainr meth_nameargsrrfuncrkrLrLrM _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)NZ_requestzurllib.RequestZ _response) isinstancestrrrIrJrrrrsysauditrtrir_openr) rfullurlrIrJreqrrZ processorrrrLrLrMrGs$       zOpenerDirector.opencCsP||jdd|}|r |S|j}||j||d|}|r|S||jdd|S)NrZ default_openrunknown unknown_open)rrr)rrrIrkrrLrLrMrs   zOpenerDirector._opencGs~|dvr|jd}|d}d|}d}|}n |j}|d}d}|||f|}|j|}|r/|S|r=|dd f|}|j|SdS) Nhttprrr:z http_error_%srVZ_errorrrhttp_error_default)rr)rprotordictrZhttp_errZ orig_argsrkrLrLrMr s"   zOpenerDirector.errorrN) rrrrrrrsocket_GLOBAL_DEFAULT_TIMEOUTrGrrrLrLrLrMrs /  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-rrclientrarEsetrr issubclassaddremover)rrKZdefault_classesskipklassZcheckhrLrLrMr29s8           r2c@s(eZdZdZddZddZddZdS) rcC ||_dSrN)parent)rrrLrLrMr` zBaseHandler.add_parentcCrrNrLrrLrLrMrcrzBaseHandler.closecCst|dsdS|j|jkS)N handler_orderT)rr)rotherrLrLrM__lt__gs  zBaseHandler.__lt__N)rrrrrrrrLrLrLrMr]s  rc@s eZdZdZdZddZeZdS)r/zProcess HTTP error responses.icCsH|j|j|}}}d|krdks"n|jd|||||}|S)N,r)codemsgrZrr)rryrrrrrLrLrM http_responsets  z HTTPErrorProcessor.http_responseN)rrr__doc__rrhttps_responserLrLrLrMr/ps  r/c@eZdZddZdS)rcCst|j||||rN)rrt)rrrhrrrrLrLrMrsz*HTTPDefaultErrorHandler.http_error_defaultN)rrrrrLrLrLrMr 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)rZHEAD)rrrr z%20)rTz content-typecs"i|] \}}|vr||qSrL)rx.0kvZCONTENT_HEADERSrLrM s z8HTTPRedirectHandler.redirect_request..T)rirr)rrrtreplacerirrr) rrrhrrrinewurlmZ newheadersrLr rMrs  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) Nlocationurirrftprrz+%s - Redirection to url '%s' is not allowed/r:z iso-8859-1)encodingsafe redirect_dictrrVrJ)rschemerr\Znetlocrrr stringZ punctuationrrtrrrr max_repeatsrdmax_redirectionsinf_msgrcrrrGrJ) rrrhrrrirurlpartsnewZvisitedrLrLrMhttp_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) rrrrrrr http_error_301http_error_303http_error_307rrLrLrLrMrs& <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. rN//zproxy URL with no authority: %r@r:rS)r rrBrrr) proxyrZr_scheme authorityZhost_separatorendZuserinfohostportuserpasswordrLrLrM _parse_proxys$         r,c@s"eZdZdZdddZddZdS)rdNcCsb|durt}t|dsJd||_|D]\}}|}t|d||||jfddqdS)Nkeysproxies must be a mappingz%s_opencSs ||||SrNrL)rr&rrrLrLrM#rz'ProxyHandler.__init__..)r5rproxiesrrxsetattrr)rr2rrHrLrLrMrs 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 rr)rr,rz proxy_bypassr base64 b64encodeencodedecoderrrrGrJ) rrr&rZ orig_typeZ proxy_typer*r+r)Z user_passZcredsrLrLrMr&s" zProxyHandler.proxy_openrN)rrrrrrrLrLrLrMrs  rc@s6eZdZddZddZddZd dd Zd d Zd S)r cCs i|_dSrN)passwdrrLrLrMrDrzHTTPPasswordMgr.__init__cs\t|tr|g}|jvrij|<dD]tfdd|D}||fj||<qdS)NTFc3s|] }|VqdSrN) reduce_uri)ru default_portrrLrM Ns  z/HTTPPasswordMgr.add_password..)rrr=tuple)rrealmrr*r= reduced_urirLrArM add_passwordGs   zHTTPPasswordMgr.add_passwordc Cs`|j|i}dD]$}|||}|D]\}}|D]}|||r+|Sqqq dS)Nr>NN)r=rr?r is_suburi) rrEauthuriZdomainsrBreduced_authuriZurisZauthinforrLrLrMfind_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.rVrr:rNPirz%s:%d)rr r) rrrBpartsrr'r\rzportZdportrLrLrMr?\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. TrFrVrSNr)r)rbasetestprefixrLrLrMrIsszHTTPPasswordMgr.is_suburiN)T)rrrrrGrLr?rIrLrLrLrMr Bs  r c@r)r!cCs0t|||\}}|dur||fSt|d|SrN)r rL)rrErJr*r+rLrLrMrLs z2HTTPPasswordMgrWithDefaultRealm.find_user_passwordN)rrrrLrLrLrLrMr!s r!cs<eZdZfddZd fdd Zd ddZdd ZZS) r"csi|_tj|i|dSrN) authenticatedsuperrrrkwargs __class__rLrMrsz%HTTPPasswordMgrWithPriorAuth.__init__Fcs<||||durtd|||t||||dSrN)update_authenticatedrTrG)rrErr*r=is_authenticatedrWrLrMrGs z)HTTPPasswordMgrWithPriorAuth.add_passwordcCs>t|tr|g}dD]}|D] }|||}||j|<qq dSNr>)rrr?rS)rrrZrBr@rFrLrLrMrYs   z1HTTPPasswordMgrWithPriorAuth.update_authenticatedcCsDdD]}|||}|jD]}|||r|j|Sq qdSr[)r?rSrI)rrJrBrKrrLrLrMrZs   z-HTTPPasswordMgrWithPriorAuth.is_authenticated)F)rrrrrGrYrZ __classcell__rLrLrWrMr"s    r"c@sTeZdZedejZdddZddZddZ d d Z d d Z d dZ e Z e ZdS)r#z1(?:^|,)[ ]*([^ ,]+)[ ]+realm=(["']?)([^"']*)\2NcCs"|durt}||_|jj|_dSrN)r r=rG)rZ password_mgrrLrLrMrsz!AbstractBasicAuthHandler.__init__ccsvd}tj|D]}|\}}}|dvrtdtd||fVd}q |s9|r0|d}nd}|dfVdSdS)NF)"'zBasic Auth Realm was unquotedTrrr)r#rxfinditergroupsr?r@ UserWarningsplit)rheaderZfound_challengeZmorr rErLrLrM _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)Zget_allrfrxretry_http_basic_authrB) rauthreqrzrriZ unsupportedrerrErLrLrMhttp_error_auth_reqeds$   z.AbstractBasicAuthHandler.http_error_auth_reqedcCsx|j||\}}|dur:d||f}dt|d}||jd|kr*dS||j||j j ||j dSdS)Nr4r7r5r) r=rLr9r:r;r<ru auth_headerrrrGrJ)rrzrrEr*pwrawauthrLrLrMrhs z.AbstractBasicAuthHandler.retry_http_basic_authcCstt|jdr |j|js|S|ds8|jd|j\}}d||}t | }| dd| |S)NrZ Authorizationz{0}:{1}zBasic {}) rr=rZrtrrLrr;r9Zstandard_b64encoder<rstrip)rrr*r=Z credentialsZauth_strrLrLrM http_requests    z%AbstractBasicAuthHandler.http_requestcCsNt|jdr%d|jkrdkrnn |j|jd|S|j|jd|S)NrZrrTF)rr=rrYrt)rrrrLrLrMr s z&AbstractBasicAuthHandler.http_responserN)rrrrecompileIr`rrfrjrhrqr https_requestrrLrLrLrMr#s   r#c@eZdZdZddZdS)r$rocC|j}|d|||}|S)Nwww-authenticate)rtrj)rrrhrrrirHrrLrLrMhttp_error_401s z#HTTPBasicAuthHandler.http_error_401N)rrrrkryrLrLrLrMr$ r$c@rv)r%r6cCrwNproxy-authenticate)rzrj)rrrhrrrir'rrLrLrMhttp_error_407)s z$ProxyBasicAuthHandler.http_error_407N)rrrrkr}rLrLrLrMr%%rzr%c@sNeZdZdddZddZddZdd Zd d Zd d ZddZ ddZ dS)r&NcCs4|durt}||_|jj|_d|_d|_d|_dSNr)r r=rGretried nonce_count last_nonce)rr=rLrLrMrCs  z"AbstractDigestAuthHandler.__init__cC d|_dSr~)rrrLrLrMreset_retry_countLrz+AbstractDigestAuthHandler.reset_retry_countcCs~||d}|jdkrt|jdd|d|jd7_|r;|d}|dkr/|||S|dkr=td|dSdS) Nizdigest auth failedrVrZdigestrgzEAbstractDigestAuthHandler does not support the following scheme: '%s')rrrrtrdrxretry_http_digest_authrB)rrkrzrririrrLrLrMrjOs       z/AbstractDigestAuthHandler.http_error_auth_reqedcCsz|dd\}}ttdt|}|||}|r;d|}|j|jd|kr)dS||j||j j ||j d}|SdS)NrrVz Digest %sr) rdparse_keqv_listfilterparse_http_listget_authorizationrirrkrrrGrJ)rrrntokenZ challengechalZauth_valZresprLrLrMrcs z0AbstractDigestAuthHandler.retry_http_digest_authcCs@d|j|tf}|dtd}t|}|ddS)Nz %s:%s:%s:r5)rtimectimer; _randombyteshashlibsha1 hexdigest)rnoncesbdigrLrLrM 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)NrErqop algorithmMD5opaquez%s:%s:%sr4rn,rVz%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=rLrtrIget_entity_digestrrrdrrrr)rrrrErrrrHKDr*rlZentdigZA1ZA2ZrespdigZncvalueZcnonceZnoncebitrPrLrLrMrzs^            z+AbstractDigestAuthHandler.get_authorizationcsD|dkr ddn|dkrddntd|fdd}|fS)NrcSt|dSNr5)rZmd5r;rxrLrLrMr1z?AbstractDigestAuthHandler.get_algorithm_impls..ZSHAcSrr)rrr;rrrLrLrMr1rz.Unsupported digest authentication algorithm %rcsd||fS)Nr4rL)rdrrLrMr1s)rB)rrrrLrrMrs   z-AbstractDigestAuthHandler.get_algorithm_implscCrrNrL)rrIrrLrLrMrrz+AbstractDigestAuthHandler.get_entity_digestrN) rrrrrrjrrrrrrLrLrLrMr&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. rocCs*t|jd}|d|||}||S)NrVrx)rrtrjrrrrhrrrirzretryrLrLrMrys z$HTTPDigestAuthHandler.http_error_401N)rrrrrkrryrLrLrLrMr's  r'c@seZdZdZdZddZdS)r(Proxy-AuthorizationrcCs"|j}|d|||}||Sr{)rzrjrrrLrLrMr}s z%ProxyDigestAuthHandler.http_error_407N)rrrrkrr}rLrLrLrMr(s r(c@s6eZdZd ddZddZddZdd Zd d Zd S)AbstractHTTPHandlerrcCrrN _debuglevel)r debuglevelrLrLrMrrzAbstractHTTPHandler.__init__cCrrNr)rlevelrLrLrMset_http_debuglevelrz'AbstractHTTPHandler.set_http_debuglevelcCstjj|j|SrN)rrHTTPConnection_get_content_lengthrIrrryrLrLrMrsz'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-encodingZchunkedrs)rzrrIrrrrrrrr rr rrr) rryrzrIrZcontent_lengthZsel_hostrZselZsel_pathr_rrLrLrM 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. rrJcsi|] \}}|vr||qSrLrLrrirLrMr )s z/AbstractHTTPHandler.do_open..r ConnectioncSsi|] \}}||qSrL)title)rr_rrLrLrMr 6srrr)Zencode_chunkedN)rzrrJZset_debuglevelrrr|updaterirr~Z set_tunnelryrrrIrrq getresponserZsockrrHreasonr) rZ http_classrZhttp_conn_argsrzrZtunnel_headersZproxy_auth_hdrerrr0rLrrMrsF        zAbstractHTTPHandler.do_openNr)rrrrrrrrrLrLrLrMrs   &rc@seZdZddZejZdS)r)cCs|tjj|SrN)rrrrrrrLrLrM http_open`szHTTPHandler.http_openN)rrrrrrrqrLrLrLrMr)^s r)rc@s$eZdZdddZddZejZdS)rErNcCst||||_||_dSrN)rr_context_check_hostname)rrr>check_hostnamerLrLrMris  zHTTPSHandler.__init__cCs|jtjj||j|jdS)N)r>r)rrrrrrrrLrLrM https_openns zHTTPSHandler.https_open)rNN)rrrrrrrrurLrLrLrMrEgs  rEc@s.eZdZdddZddZddZeZeZdS) rNcCs$ddl}|dur |j}||_dSr~)Zhttp.cookiejar cookiejarZ CookieJar)rrrrLrLrMrws  zHTTPCookieProcessor.__init__cCs|j||SrN)rZadd_cookie_headerrrLrLrMrq}s z HTTPCookieProcessor.http_requestcCs|j|||SrN)rZextract_cookies)rryrrLrLrMrsz!HTTPCookieProcessor.http_responserN)rrrrrqrrurrLrLrLrMrvs  rc@r)r.cCs|j}td|)Nzunknown url type: %s)rr)rrrrLrLrMrs zUnknownHandler.unknown_openN)rrrrrLrLrLrMr.rr.cCsNi}|D] }|dd\}}|ddkr |ddkr |dd}|||<q|S)z>Parse list of key=value strings where keys are not duplicated.=rVrr]rS)rd)lZparsedeltr r rLrLrMrs  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. rrF\Tr]rcSsg|]}|qSrL)rp)rpartrLrLrM rz#parse_http_list..)ra)rresrescaper ZcurrLrLrMrs4    rc@s(eZdZddZdZddZddZdS)r*cCsZ|j}|dddkr(|dddkr(|jr(|jdkr(|j|vr&tddS||S)Nr:r$r_r localhost-file:// scheme is supported only on localhost)rrz get_namesropen_local_file)rrrHrLrLrM file_opens&  zFileHandler.file_openNcCsftjdur0zttddttdt_WtjStjy/tdft_YtjSwtjS)Nrr:)r*namesrDrgethostbyname_ex gethostnamegaierror gethostbynamerrLrLrMrs  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) NrTZusegmtz6Content-type: %s Content-length: %d Last-modified: %s text/plainfile://rbzfile not on local host) email.utils mimetypesrzrr4r[statst_sizeutils formatdatest_mtime guess_typemessage_from_stringr _safe_gethostbynamerrrGrqr)rremailrrzrfZ localfilestatsrmmodifiedmtyperirOZorigurlexprLrLrMrsB    zFileHandler.open_local_file)rrrrrrrrLrLrLrMr*s   r*cCs$zt|WStjyYdSwrN)rrr)rzrLrLrMrs  rc@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 givenrrrrSrVrtDraArrtrrzContent-type: %s zContent-length: %d )ftplibrrzrr FTP_PORTrbrrr rrrqrrrdrmap connect_ftprJrrxupperretrfilerrtrrr all_errors)rrrrrzrOr*r=rr\attrsdirsrOfwrattrrrhretrlenrirrrLrLrMftp_opensd            zFTPHandler.ftp_openc Cst||||||ddS)NF) persistent) ftpwrapper)rr*r=rzrOrrJrLrLrMr0szFTPHandler.connect_ftpN)rrrrrrLrLrLrMr+s 4r+c@s<eZdZddZddZddZddZd d Zd d Zd S)r,cCs"i|_i|_d|_d|_d|_dS)Nr<r)cacherJsoonestdelay max_connsrrLrLrMr7s  zCacheFTPHandler.__init__cCrrN)r)rtrLrLrM setTimeout>rzCacheFTPHandler.setTimeoutcCrrN)r)rrrLrLrM setMaxConnsArzCacheFTPHandler.setMaxConnscCsr|||d||f}||jvrt|j|j|<nt|||||||j|<t|j|j|<||j|S)Nr)joinrrrrJr check_cache)rr*r=rzrOrrJrrLrLrMrDs    zCacheFTPHandler.connect_ftpcCst}|j|kr(t|jD]\}}||kr'|j||j|=|j|=qtt|j|_t |j|j krat|jD]\}}||jkrT|j|=|j|=nqAtt|j|_dSdSrN) rrrrJrrrminvaluesrdr)rrr r rLrLrMr Os$  zCacheFTPHandler.check_cachecCs0|jD]}|q|j|jdSrN)rrrclearrJ)rconnrLrLrM clear_cachecs  zCacheFTPHandler.clear_cacheN) rrrrr r rr rrLrLrLrMr,4s r,c@r)r-cCs~|j}|dd\}}|dd\}}t|}|dr't|}|dd}|s+d}td|t|f}t t |||S)N:rVrz;base64itext/plain;charset=US-ASCIIz$Content-type: %s Content-length: %d ) rtrdrendswithr9 decodebytesrrrdrioBytesIO)rrrHrrIZ mediatyperirLrLrM data_openjs     zDataHandler.data_openN)rrrrrLrLrLrMr-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 pathnamerLrLrMr4r4cCr)zOS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.)r rrLrLrMr3rr3c@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_) stacklevelr.r/key_file cert_filez User-Agent)ZAcceptz*/*)rXrr?r@rAr5rr2rr r!versionr_URLopener__tempfilesr[rp_URLopener__unlink tempcacheftpcache)rr2Zx509rrLrLrMrs    zURLopener.__init__cC |dSrN)rrrLrLrM__del__rzURLopener.__del__cCr'rN)cleanuprrLrLrMrrzURLopener.closec CsV|jr|jD]}z||WqtyYqw|jdd=|jr)|jdSdSrN)r#r$rqr%r)rrOrLrLrMr)s   zURLopener.cleanupcGs|j|dS)zdAdd a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')N)rra)rrrLrLrM 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%/:=&?~#+!$,;'@()*[]|rrrONZopen_-rrz socket errorr:)rrr r%rGrr r2r rr ropen_unknown_proxy open_unknownrrrrqwith_tracebackrexc_info)rrrIrfrirhurltyperHr& proxyhostrzrr_rrLrLrMrGs@            zURLopener.opencCst|\}}tdd|)/Overridable interface to open unknown URL type. url errorzunknown url typer rq)rrrIrrHrLrLrMr.s  zURLopener.open_unknowncCst|\}}tdd||)r3r4zinvalid proxy for %sr5)rr&rrIrrHrLrLrMr-s 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.NrOrVrPrrrRrSrrTrUrW)rrr%r rrZrr4r rqrGrrr[r\splitextr^Zmkstempr#rafdopenrbrcrdrer)rrHrfrgrIrZurl1rhrrirjZgarbager\suffixfdrkrlrmrcrnrorLrLrMretrievesv                  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 errorrr5zBasic %srrorsrrrz Content-Typerrrz$http protocol error: bad status linerrhttp:)rrr rr r rxr8rqr9r:r;r<rryrrrZ BadStatusLinerZstatusrr http_errorrhr)rZconnection_factoryrHrIZ user_passwdZ proxy_passwdrzrZrealhostr1rZ proxy_authrnZ http_connrirerrrLrLrM_open_generic_httpOsv             zURLopener._open_generic_httpcCs|tjj||S)zUse HTTP protocol.)r=rrrrrHrIrLrLrM 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) rrHrherrcodeerrmsgrirIr_rrkrLrLrMr<s  zURLopener.http_errorcCs|t||||d)z>Default error handler: close the connection and raise OSError.N)rrrrHrhr@rArirLrLrMrszURLopener.http_error_defaultcCstjj||j|jdS)N)r r!)rrrr r!)rrzrLrLrM_https_connectionszURLopener._https_connectioncCs||j||S)zUse HTTPS protocol.)r=rCr>rLrLrM 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$r_r z localhost/r)rrrrxrBrrrLrLrM 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.rNTrz6Content-Type: %s Content-Length: %d Last-modified: %s rrVrrrr:z./zAlocal file url may start with / or file:. Unknown url of type: %sz#local file error: not on local host)rrr r4r[rrqrstrerrorrfrrrrrrrrGr rrrthishostrB)rrHrrrzrOZ localnamerermrrriZurlfilerOrLrLrMrsB     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 implementedrNrrrrrSrVrrtrrzftp:zContent-Type: %s zContent-Length: %d z ftp error %rr:)#rrrrr r rrr rrrrrbrrdr rdr& MAXFTPCACHErrrrrxrrrrrr ftperrorsr/rr0)rrHrrzr\rOr*r=rrrrOrr r rrrrhrrrirrLrLrMopen_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 implementedrrVz data errorz bad data URLr;rrNrrzDate: %sz%a, %d %b %Y %H:%M:%S GMTzContent-type: %sr9r5zlatin-1zContent-Length: %d )rrrrdrBrqrfindrarstrftimegmtimer9rr;r<r rdr rrrStringIOr) rrHrIrZsemirrrifrLrLrM open_data1s:            zURLopener.open_datarNNNN)rrrrr#rr"rr(rr)r*rGr.r-r:r=r?r<rrCrCrDrFrrLrTrLrLrLrMr8s0   $  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_cachetriesmaxtriesrUrLrLrMr^s zFancyURLopener.__init__cCst||d||S)z3Default error handling -- don't raise an exception.r;)rrBrLrLrMrdrz!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).rVhttp_error_500rz)Internal Server Error: Redirect Recursionr)rWrXrrYrredirect_internal) rrHrhr@rArirIrrkrLrLrMr hs   zFancyURLopener.http_error_302c Csxd|vr |d}n d|vr|d}ndS|t|jd||}t|}|jdvr7t|||d|||||S)Nrrrrz( Redirection to url '%s' is not allowed.)rrrrrrrG) rrHrhr@rArirIrrrLrLrMrZzs     z FancyURLopener.redirect_internalcC|||||||S)z*Error 301 -- also relocated (permanently).r rrHrhr@rArirIrLrLrMr!zFancyURLopener.http_error_301cCr[)z;Error 303 -- also relocated (essentially identical to 302).r\r]rLrLrMr"r^zFancyURLopener.http_error_303cCs.|dur|||||||S||||||S)z1Error 307 -- relocated, but turn POST into error.N)r rr]rLrLrMr#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.rx![ ]*([^ ]+)[ ]+realm="([^"]*)"rgZretry_ _basic_authNr8rrrmatchrbrxrr rrHrhr@rArirIrZstuffrcrrEr_rLrLrMry.      zFancyURLopener.http_error_401c Cr_)zeError 407 -- proxy authentication required. This function supports Basic authentication only.r|r`rgZ retry_proxy_raNrbrdrLrLrMr}rezFancyURLopener.http_error_407cCt|\}}d||}|jd}t|\}} t| \} } | dd} | | d} || || \} } | s9| s9dSdt| ddt| dd| f} d| | |jd<|durZ||S|||S)Nhttp://rr%rV%s:%s@%srrr+r r2r rget_user_passwdr rGrrHrErIrzrrr&r1r2Z proxyselectorrr*r=rLrLrMretry_proxy_http_basic_auth           z*FancyURLopener.retry_proxy_http_basic_authcCrf)Nhttps://rr%rVrhrrr+rirkrLrLrMretry_proxy_https_basic_authrmz+FancyURLopener.retry_proxy_https_basic_authc Ct|\}}|dd}||d}||||\}}|s"|s"dSdt|ddt|dd|f}d||} |dur@|| S|| |S)Nr%rVrhrrr+rgr rrjr rG rrHrErIrzrrr*r=rrLrLrMrh        z$FancyURLopener.retry_http_basic_authc Crp)Nr%rVrhrrr+rnrqrrrLrLrMretry_https_basic_auth rsz%FancyURLopener.retry_https_basic_authrcCs`|d|}||jvr|r|j|=n|j|S|||\}}|s%|r,||f|j|<||fS)Nr%)rxrVprompt_user_passwd)rrzrErrr*r=rLrLrMrj 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: rH)getpassinputKeyboardInterruptprint)rrzrErvr*r=rLrLrMru" s  z!FancyURLopener.prompt_user_passwdrN)NFr)rrrrrrr rZr!r"r#ryr}rlrorhrtrjrurLrLrLrMr9[s*           r9cCtdur tdatS)z8Return the IP address of the magic hostname 'localhost'.Nr) _localhostrrrLrLrLrMr2  rcCsRtdur'ztttdaWtStjy&ttddaYtSwtS)z,Return the IP addresses of the current host.Nr:r) _thishostrDrrrrrLrLrLrMrH: srHcCstdur ddl}|jatS)z1Return the set of errors raised by the FTP class.Nr) _ftperrorsrr)rrLrLrMrKE srKcCrz)z%Return an empty email Message object.Nrr) _noheadersrrrLrLrLrM noheadersN r|rc@sNeZdZdZ  dddZddZdd Zd d Zd d ZddZ ddZ dS)rz;Class used by open_ftp() for cache of open FTP connections.NTcCsP||_||_||_||_||_||_d|_||_z|WdS| r~) r*r=rzrOrrJrefcount keepaliveinitr)rr*r=rzrOrrJrrLrLrMr[ szftpwrapper.__init__cCs\ddl}d|_||_|j|j|j|j|j|j |j d |j }|j |dS)Nrr)rbusyZFTPrZconnectrzrOrJZloginr*r=r rcwd)rrZ_targetrLrLrMrk 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)rrzTYPE ArVzTYPE zRETR r_Z550z ftp error: %rr:zLIST ZLISTr)r endtransferrZvoidcmdrrZ ntransfercmdZ error_permrrr/rr0pwdrrrZmakefile file_closerr) rrOrrcmdisdirrrrrZftpobjrLrLrMrt sX       zftpwrapper.retrfilecCrr~)rrrLrLrMr rzftpwrapper.endtransfercCs d|_|jdkr|dSdS)NFr)rr real_closerrLrLrMr s  zftpwrapper.closecCs:||jd8_|jdkr|js|dSdSdS)NrVr)rrrrrrLrLrMr s  zftpwrapper.file_closecCs0|z|jWdStyYdSwrN)rrrrKrrLrLrMr s zftpwrapper.real_close)NT) rrrrrrrrrrrrLrLrLrMrX s  - rcCsi}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. rirNr&ZREQUEST_METHODr_proxy)r[environr.rdrxrar)r2Z environmentr_rZ proxy_namerLrLrMgetproxies_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. NZnoF*Tr.)rrrxr rdrplstripr)rzr2Zno_proxyhostonlyrOr_rLrLrMproxy_bypass_environment s.    rc Cs0ddlm}ddlm}m}t|\}}dd}d|vr"|dr"dSd }zt||}Wn |y5Ynw|d d D]Y} | sAq|dd>B|dd >B|d BS) Nrr)rrrrrrVrr:rr_)rdrrrbrd)ZipAddrrNrLrLrMip2num s  ,z,_proxy_bypass_macosx_sysconf..ip2numrZexclude_simpleTN exceptionsrLz(\d+(?:\.\d+)*)(/\d+)?rVr:r F) rZ ipaddressrrr rbrrrrcgroupcount) rzproxy_settingsrrrrrOrZhostIPrrrPmaskrLrLrM_proxy_bypass_macosx_sysconf s@      rcCs`ddlm}t|\}}|d}|D]}|}|dkr%d|vr$dSq|||r-dSqdS)a Return True if the host should bypass the proxy server. The proxy override list is obtained from the Windows Internet settings proxy override registry value. An example of a proxy override value is: "www.example.com;*.example.net; 192.168.0.1" rrrMzrTF)rr rdrp)rzoverriderrZproxy_overriderQrLrLrM_proxy_bypass_winreg_overrideA s   rdarwin)_get_proxy_settings _get_proxiescCst}t||SrN)rr)rzrrLrLrMproxy_bypass_macosx_sysconf\ s rcCstS)zReturn a dictionary of scheme -> proxy server URL mappings. This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. )rrLrLrLrMgetproxies_macosx_sysconf` 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. )rrrrzr2rLrLrMr8j  r8cC tptSrN)rrrLrLrLrMr5w 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 ProxyEnableZ ProxyServerrrMzhttp={0};https={0};ftp={0}rVz (?:[^/:]+)://)rrrrgZsockszsocks://z ^socks://z socks4://rr)winreg ImportErrorOpenKeyHKEY_CURRENT_USER QueryValueExrrrdrrrcrrwZCloserqrBr)r2rinternetSettings proxyEnableZ proxyServerprZaddressrLrLrMgetproxies_registry| sR        rcCr)zReturn a dictionary of scheme -> proxy server URL mappings. Returns settings gathered from the environment, if specified, or the registry. )rrrLrLrLrMr5 s cCszddl}Wn tyYdSwz||jd}||dd}t||dd}Wn ty6YdSw|r;|s=dSt||S)NrFrrZ ProxyOverride)rrrrrrrqr)rzrrrZ proxyOverriderLrLrMproxy_bypass_registry s2    rcCr)zReturn True, if host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. )rrrrrLrLrMr8 rrUrN)rr9rrrZ http.clientrrr[ posixpathrrrrrrr^rXr?Z urllib.errorrrrZ urllib.parserrrrr r r r r rrrrrrrrrZurllib.responserrrDrrC__all__ version_inforrFrr0r1r`r6r7rsASCIIrvr{rrr2rr/rrr,rr r!r"r#r$r%urandomrr&r'r(rr)rrrErarr.rrr*rr+r,r-rJr_Z nturl2pathr4r3r&r8r9r{rr}rHr~rKrrrrrrrplatformZ_scproxyrrrrr8r5rrrLrLrLrMsSP   O ?m$q!+@ o  v  +395! @W  _ %%@  1