3 f~)@sdZddlZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl Z ddl Z ddl Z ddlZddlZddlZddlZddlZddlmZmZmZddlmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)ddl*m+Z+m,Z,y ddl-Z-Wne.k r&dZ/YnXdZ/dd d d d d ddddddddddddddddddd d!d"d#d$d%d&d'd(g!Z0d)e j1dd*Z2da3de j4fddddd+d,dZ5d-d Z6gZ7d~d.d%Z8d/d&Z9e j:d0e j;ZGd4d d Z?d5d!Z@Gd6d d ZAGd7ddeAZBGd8d d eAZCGd9d d eAZDd:d;ZEGdddeGZHGd?ddeHZIGd@ddZJGdAddeJeAZKGdBddeJeAZLejMZNGdCddZOGdDddeAeOZPGdEddeAeOZQGdFdGdGeAZRGdHddeRZSeTejUdIr2GdJdKdKeRZVe0jWdKGdLd d eAZXGdMddeAZYdNdOZZdPdQZ[GdRddeAZ\dSdTZ]GdUddeAZ^GdVdde^Z_GdWddeAZ`dXZaejbdYkrddZlcmdZdmeZend[d#Zdd\d"ZeiZfGd]d'd'ZgGd^d(d(egZhdaid_d`ZjdakdadbZldamdcddZndaodedfZpGdgdhdhZqdidjZrddkdlZsdmdnZte judokrddplvmwZwmxZxdqdrZydsdtZzdudvZ{dwd$Z|n6ejbdYkrdxdyZ}dzd$Z|d{d|Z~d}dvZ{nerZ|esZ{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('http://www.python.org/') N)URLError HTTPErrorContentTooShortError)urlparseurlspliturljoinunwrapquoteunquote splittype splithost splitport splituser splitpasswd splitattr splitquery splitvaluesplittagto_bytesunquote_to_bytes urlunparse) addinfourl addclosehookFTRequestOpenerDirector BaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessor ProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmHTTPPasswordMgrWithPriorAuthAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandler HTTPHandler FileHandler FTPHandlerCacheFTPHandler DataHandlerUnknownHandlerHTTPErrorProcessorurlopeninstall_opener build_opener pathname2url url2pathname getproxies urlretrieve urlcleanup URLopenerFancyURLopenerz%d.%d)cafilecapath cadefaultcontextc Cs|s |s |rfddl}|jdtd|dk r2tdts>tdtjtjj||d}t |d}t |} n0|r~t |d}t |} nt dkrt a } nt } | j |||S) a$ Open 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 methods such as * geturl() - return the URL of the resource retrieved, commonly used to determine if a redirect was followed * info() - return the meta-information of the page, such as headers, in the form of an email.message_from_string() instance (see Quick Reference to HTTP Headers) * getcode() - return the HTTP status code of the response. Raises URLError on errors. 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<)r>) warningswarnDeprecationWarning ValueError _have_sslsslZcreate_default_contextZPurposeZ SERVER_AUTH HTTPSHandlerr2_openeropen) urldatatimeoutr;r<r=r>r?Z https_handleropenerrL&/usr/lib64/python3.6/urllib/request.pyr0s*<       cCs|adS)N)rF)rKrLrLrMr1scCs4t|\}}tjt||}|j}|dkrD| rDtjj||fS|rTt|d}nt j dd}|j }t j ||||f} d } d} d} d} d |krt|d } |r|| | | xB|j| }|sP| t|7} |j|| d7} |r|| | | qWWd QRXWd QRX| dkr0| | kr0td | | 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. filewbF)deleteirzcontent-lengthzContent-LengthNz1retrieval incomplete: got only %i out of %i bytesi )r contextlibclosingr0infoospathnormpathrGtempfileZNamedTemporaryFilename_url_tempfilesappendintreadlenwriter)rHfilename reporthookrIZurl_typerXfpheaderstfpresultbssizer_blocknumblockrLrLrMr6sD         $c CsHx0tD](}ytj|Wqtk r,YqXqWtdd=trDdadS)z0Clean up temporary files from urlretrieve calls.N)r\rWunlinkOSErrorrF)Z temp_filerLrLrMr7%s   z:\d+$cCs<|j}t|d}|dkr&|jdd}tjd|d}|jS)zReturn request-host, as defined by RFC 2965. Variation from RFC: returned value is lowercased, for convenient comparison. rRHost)full_urlr get_header _cut_port_resublower)requestrHhostrLrLrM request_host4s   rwc@seZdZdidddfddZeddZejddZejddZed d Zejd d Zejd d Zd dZ ddZ ddZ ddZ ddZ ddZddZddZd#ddZdd Zd!d"ZdS)$rNFc Csp||_i|_i|_d|_||_d|_x |jD]\}}|j||q.W|dkrVt|}||_ ||_ |rl||_ dS)N) rpreunredirected_hdrs_datarI _tunnel_hostitems add_headerrworigin_req_host unverifiablemethod) selfrHrIrer}r~rkeyvaluerLrLrM__init__FszRequest.__init__cCs|jrdj|j|jS|jS)Nz{}#{})fragmentformat _full_url)rrLrLrMrpXszRequest.full_urlcCs(t||_t|j\|_|_|jdS)N)rrrr_parse)rrHrLrLrMrp^s cCsd|_d|_d|_dS)Nrn)rrselector)rrLrLrMrpescCs|jS)N)ry)rrLrLrMrIksz Request.datacCs(||jkr$||_|jdr$|jddS)NzContent-length)ry has_header remove_header)rrIrLrLrMrIos  cCs d|_dS)N)rI)rrLrLrMrIyscCsNt|j\|_}|jdkr(td|jt|\|_|_|jrJt|j|_dS)Nzunknown url type: %r) r rtyperBrpr rvrr )rrestrLrLrMr}s  zRequest._parsecCs|jdk rdnd}t|d|S)z3Return a string indicating the HTTP request method.NPOSTGETr)rIgetattr)rZdefault_methodrLrLrM get_methodszRequest.get_methodcCs|jS)N)rp)rrLrLrM get_full_urlszRequest.get_full_urlcCs4|jdkr|j r|j|_n||_|j|_||_dS)Nhttps)rrzrvrpr)rrvrrLrLrM set_proxys  zRequest.set_proxycCs |j|jkS)N)rrp)rrLrLrM has_proxyszRequest.has_proxycCs||j|j<dS)N)re capitalize)rrvalrLrLrMr|szRequest.add_headercCs||j|j<dS)N)rxr)rrrrLrLrMadd_unredirected_headerszRequest.add_unredirected_headercCs||jkp||jkS)N)rerx)r header_namerLrLrMrs zRequest.has_headercCs|jj||jj||S)N)regetrx)rrdefaultrLrLrMrqszRequest.get_headercCs |jj|d|jj|ddS)N)repoprx)rrrLrLrMrszRequest.remove_headercCs"|jj}|j|jt|jS)N)rxcopyupdaterelistr{)rhdrsrLrLrM header_itemss  zRequest.header_items)N)__name__ __module__ __qualname__rpropertyrpsetterdeleterrIrrrrrr|rrrqrrrLrLrLrMrDs(     c@sNeZdZddZddZddZddZd ejfd d Z dd d Z ddZ d S)rcCs6dt}d|fg|_g|_i|_i|_i|_i|_dS)NzPython-urllib/%sz User-agent) __version__ addheadershandlers handle_open handle_errorprocess_responseprocess_request)rZclient_versionrLrLrMrs zOpenerDirector.__init__c CsZt|dstdt|d}xt|D]}|dkr:q*|jd}|d|}||dd}|jd r|jd|d}||dd}y t|}Wntk rYnX|jj |i} | |j|<n>|d kr|}|j } n*|d kr|}|j } n|d kr*|}|j } nq*| j |g} | r&tj| |n | j|d }q*W|rVtj|j||j|dS)N add_parentz%expected BaseHandler instance, got %rFredirect_requestdo_open proxy_open_rRerrorrGresponseruT)rrr)hasattr TypeErrorrdirfind startswithr^rBrrrrr setdefaultbisectZinsortr]rr) rhandlerZaddedmethiprotocolZ conditionjkindlookuprrLrLrM add_handlersJ         zOpenerDirector.add_handlercCsdS)NrL)rrLrLrMcloseszOpenerDirector.closec Gs<|j|f}x*|D]"}t||}||}|dk r|SqWdS)N)rr) rchainr meth_nameargsrrfuncrgrLrLrM _call_chains    zOpenerDirector._call_chainNc Cst|trt||}n|}|dk r(||_||_|j}|d}x(|jj|gD]}t||}||}qLW|j ||} |d}x*|j j|gD]}t||}||| } qW| S)NZ_requestZ _response) isinstancestrrrIrJrrrr_openr) rfullurlrIrJreqrrZ processorrrrLrLrMrGs"      zOpenerDirector.opencCsP|j|jdd|}|r|S|j}|j|j||d|}|r>|S|j|jdd|S)NrZ default_openrunknown unknown_open)rrr)rrrIrgrrLrLrMrs    zOpenerDirector._opencGs~|d kr,|jd}|d}d|}d}|}n|j}|d}d}|||f|}|j|}|r^|S|rz|dd f|}|j|SdS) Nhttprr:z http_error_%srRZ_errorrrhttp_error_default)rr)rr)rprotordictrZhttp_errZ orig_argsrgrLrLrMr's   zOpenerDirector.error)N) rrrrrrrsocket_GLOBAL_DEFAULT_TIMEOUTrGrrrLrLrLrMrs /  c Gst}ttttttttt g }t t j dr2|j tt}xN|D]F}x@|D]8}t|trlt||r|j|qHt||rH|j|qHWq>Wx|D]}|j|qWx|D]}|j|qWx&|D]}t|tr|}|j|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-rrclientr]rEsetrr issubclassaddremover)rrKZdefault_classesskipklassZcheckhrLrLrMr2@s0             c@s(eZdZdZddZddZddZdS) ricCs ||_dS)N)parent)rrrLrLrMrgszBaseHandler.add_parentcCsdS)NrL)rrLrLrMrjszBaseHandler.closecCst|dsdS|j|jkS)N handler_orderT)rr)rotherrLrLrM__lt__ns zBaseHandler.__lt__N)rrrrrrrrLrLrLrMrdsc@s eZdZdZdZddZeZdS)r/zProcess HTTP error responses.icCsJ|j|j|j}}}d|ko*dknsF|jjd|||||}|S)Ni,r)codemsgrVrr)rrurrrrrLrLrM http_response{s z HTTPErrorProcessor.http_responseN)rrr__doc__rrhttps_responserLrLrLrMr/ws c@seZdZddZdS)rcCst|j||||dS)N)rrp)rrrdrrrrLrLrMrsz*HTTPDefaultErrorHandler.http_error_defaultN)rrrrrLrLrLrMrsc@s4eZdZdZdZddZddZeZZZ dZ dS) r c sx|j}|dkr|dkp&|dko&|dks:t|j|||||jdd }dtfd d |jjD}t|||jddS)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. -./3rHEADr z%20content-length content-typec3s&|]\}}|jkr||fVqdS)N)rt).0kv)CONTENT_HEADERSrLrM sz7HTTPRedirectHandler.redirect_request..T)rer}r~)rrrr)rr)rrr)rr) rrrpreplacerrer{rr}) rrrdrrrenewurlmZ newheadersrL)rrMrs  z$HTTPRedirectHandler.redirect_requestc CsNd|kr|d}nd|kr$|d}ndSt|}|jdkrRt||d||f|||j rp|jrpt|}d|d <t|}t|d tj d }t |j |}|j ||||||}|dkrdSt |d r|j} |_| j|d |jkst| |jkrt|j ||j|||ni} |_|_| j|d d| |<|j|j|jj||jdS)Nlocationurirrftprnz+%s - Redirection to url '%s' is not allowed/r:z iso-8859-1)encodingsafe redirect_dictrrR)rJ)rrrrn)rschemerrXZnetlocrrr stringZ punctuationrrprrrr max_repeatsr`max_redirectionsinf_msgr_rrrGrJ) rrrdrrrerurlpartsnewZvisitedrLrLrMhttp_error_302s@       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 &< c Cst|\}}|jds d}|}n:|jds6td||jdd}|dkrNd}|d|}t|\}}|dk r|t|\}}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. rNz//zproxy URL with no authority: %rr:rRrS)r rrBrrr) proxyrZr_scheme authorityendZuserinfohostportuserpasswordrLrLrM _parse_proxys       rc@s"eZdZdZdddZddZdS)rdNcCs^|dkrt}t|ds td||_x2|jD]&\}}t|d||||jfddq0WdS)Nkeyszproxies must be a mappingz%s_opencSs ||||S)NrL)rrrrrLrLrM%sz'ProxyHandler.__init__..)r5rAssertionErrorproxiesr{setattrr)rrrrHrLrLrMrs zProxyHandler.__init__c Cs|j}t|\}}}}|dkr"|}|jr6t|jr6dS|rv|rvdt|t|f} tj| jjd} |j dd| t|}|j ||||ks|dkrdS|j j ||j dSdS)Nz%s:%sasciizProxy-authorizationzBasic r)rJ)rrrv proxy_bypassr base64 b64encodeencodedecoder|rrrGrJ) rrrrZ orig_typeZ proxy_typerrrZ user_passZcredsrLrLrMr(s   zProxyHandler.proxy_open)N)rrrrrrrLrLrLrMrs c@s6eZdZddZddZddZd dd Zd d Zd S)r cCs i|_dS)N)passwd)rrLrLrMrFszHTTPPasswordMgr.__init__cs`t|tr|g}|jkr$ij|<x6dD].tfdd|D}||fj||<q*WdS)NTFcsg|]}j|qSrL) reduce_uri)ru) default_portrrLrM Qsz0HTTPPasswordMgr.add_password..)TF)rrr"tuple)rrealmrrr" reduced_urirL)r%rrM add_passwordIs    zHTTPPasswordMgr.add_passwordc Cs`|jj|i}xLdD]D}|j||}x2|jD]&\}}x|D]}|j||r<|SqdD]6}|j||}x$|jD]}|j||r|j|SqWqWdS)NTF)TF)r#r7r+)rr,r%r-rrLrLrMr<s     z-HTTPPasswordMgrWithPriorAuth.is_authenticated)F)F)rrrrr*r;r< __classcell__rLrL)r:rMr"s  c@sTeZdZejdejZdddZddZddZ d d Z d d Z d dZ e Z e ZdS)r#z1(?:^|,)[ ]*([^ ,]+)[ ]+realm=(["']?)([^"']*)\2NcCs"|dkrt}||_|jj|_dS)N)r r"r*)rZ password_mgrrLrLrMrsz!AbstractBasicAuthHandler.__init__ccstd}xFtjj|D]6}|j\}}}|d kr:tjdtd||fVd}qW|sp|rb|jd}nd}|dfVdS) NF"'zBasic Auth Realm was unquotedTrrn)r>r?)r#rxfinditergroupsr?r@ UserWarningsplit)rheaderZfound_challengeZmorr r(rLrLrM _parse_realms z%AbstractBasicAuthHandler._parse_realmc Cs~|j|}|sdSd}xL|D]D}x>|j|D]0\}}|jdkrF|}q,|dk r,|j|||Sq,WqW|dk rztd|fdS)NbasiczBAbstractBasicAuthHandler does not support the following scheme: %r)Zget_allrGrtretry_http_basic_authrB) rauthreqrvrreZ unsupportedrFrr(rLrLrMhttp_error_auth_reqeds   z.AbstractBasicAuthHandler.http_error_auth_reqedcCs||jj||\}}|dk rtd||f}dtj|jjd}|j|jd|krTdS|j|j||j j ||j dSdSdS)Nz%s:%szBasic r)rJ) r"r.rrr r!rq auth_headerrrrGrJ)rrvrr(rpwrawauthrLrLrMrIs z.AbstractBasicAuthHandler.retry_http_basic_authcCsxt|jd s|jj|j r"|S|jdst|jjd|j\}}dj||j}tj |j }|j ddj|j |S)Nr< Authorizationz{0}:{1}zBasic {}) rr"r<rprr.rr rZstandard_b64encoder!rstrip)rrrr"Z credentialsZauth_strrLrLrM http_requests z%AbstractBasicAuthHandler.http_requestcCsLt|jdrHd|jko dknr8|jj|jdn|jj|jd|S)Nr<ri,TF)rr"rr;rp)rrrrLrLrMrs  z&AbstractBasicAuthHandler.http_response)N)rrrrecompileIrArrGrKrIrRr https_requestrrLrLrLrMr#s   c@seZdZdZddZdS)r$rPcCs|j}|jd|||}|S)Nzwww-authenticate)rprK)rrrdrrrerHrrLrLrMhttp_error_401 s z#HTTPBasicAuthHandler.http_error_401N)rrrrLrWrLrLrLrMr$sc@seZdZdZddZdS)r%zProxy-authorizationcCs|j}|jd|||}|S)Nzproxy-authenticate)rvrK)rrrdrrrerrrLrLrMhttp_error_407+s z$ProxyBasicAuthHandler.http_error_407N)rrrrLrXrLrLrLrMr%'sc@sNeZdZdddZddZddZdd Zd d Zd d ZddZ ddZ dS)r&NcCs4|dkrt}||_|jj|_d|_d|_d|_dS)Nr)r r"r*retried nonce_count last_nonce)rr"rLrLrMrEs z"AbstractDigestAuthHandler.__init__cCs d|_dS)Nr)rY)rrLrLrMreset_retry_countNsz+AbstractDigestAuthHandler.reset_retry_countcCs||j|d}|jdkr*t|jdd|dn|jd7_|rx|jd}|jdkr`|j||S|jdkrxtd|dS) Nizdigest auth failedrRrZdigestrHzEAbstractDigestAuthHandler does not support the following scheme: '%s')rrYrrprErtretry_http_digest_authrB)rrLrvrrerJrrLrLrMrKQs        z/AbstractDigestAuthHandler.http_error_auth_reqedcCsz|jdd\}}ttdt|}|j||}|rvd|}|jj|jd|krRdS|j|j||j j ||j d}|SdS)NrrRz Digest %s)rJ) rEparse_keqv_listfilterparse_http_listget_authorizationrerrLrrrGrJ)rrrOtokenZ challengechalZauth_valZresprLrLrMr^es z0AbstractDigestAuthHandler.retry_http_digest_authcCs@d|j|tjf}|jdtd}tj|j}|ddS)Nz %s:%s:%s:rrQ)rZtimeZctimer  _randombyteshashlibsha1 hexdigest)rnoncesbdigrLrLrM get_cnonceqsz$AbstractDigestAuthHandler.get_cnoncecCsy6|d}|d}|jd}|jdd}|jdd}Wntk rJdSX|j|\}} |dkrfdS|jj||j\} } | dkrdS|jdk r|j|j|} nd} d| || f} d|j|j f}|d kr.||j kr|j d 7_ n d |_ ||_ d |j }|j |}d ||||||f}| || |}n2|dkrT| || d|||f}n t d |d| |||j |f}|r|d|7}| r|d| 7}|d|7}|r|d||f7}|S)Nr(rkqop algorithmMD5opaquez%s:%s:%sz%s:%srOrRz%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"r.rprIget_entity_digestrrr[rZror)rrrdr(rkrprqrsHKDrrMZentdigZA1ZA2ZncvalueZcnonceZnoncebitZrespdigr4rLrLrMrb|sV              z+AbstractDigestAuthHandler.get_authorizationcsD|dkrddn|dkr$ddn td|fdd}|fS)NrrcSstj|jdjS)Nr)rhZmd5r rj)xrLrLrMrsz?AbstractDigestAuthHandler.get_algorithm_impls..ZSHAcSstj|jdjS)Nr)rhrir rj)ryrLrLrMrsz.Unsupported digest authentication algorithm %rcsd||fS)Nz%s:%srL)rld)rwrLrMrs)rB)rrqrxrL)rwrMrus   z-AbstractDigestAuthHandler.get_algorithm_implscCsdS)NrL)rrIrdrLrLrMrvsz+AbstractDigestAuthHandler.get_entity_digest)N) rrrrr\rKr^rorbrurvrLrLrLrMr&:s   < 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. rPicCs*t|jd}|jd|||}|j|S)NrRzwww-authenticate)rrprKr\)rrrdrrrervretryrLrLrMrWs  z$HTTPDigestAuthHandler.http_error_401N)rrrrrLrrWrLrLrLrMr'sc@seZdZdZdZddZdS)r(zProxy-AuthorizationicCs"|j}|jd|||}|j|S)Nzproxy-authenticate)rvrKr\)rrrdrrrervr{rLrLrMrXs  z%ProxyDigestAuthHandler.http_error_407N)rrrrLrrXrLrLrLrMr(sc@s6eZdZd ddZddZddZdd Zd d Zd S)AbstractHTTPHandlerrcCs ||_dS)N) _debuglevel)r debuglevelrLrLrMrszAbstractHTTPHandler.__init__cCs ||_dS)N)r})rlevelrLrLrMset_http_debuglevelsz'AbstractHTTPHandler.set_http_debuglevelcCstjjj|j|jS)N)rrHTTPConnection_get_content_lengthrIr)rrurLrLrMrsz'AbstractHTTPHandler._get_content_lengthc Cs |j}|std|jdk r|j}t|tr8d}t||jdsN|jdd|jd r|jd r|j|}|dk r|jdt|n |jdd|}|j rt |j \}}t |\}} |jds|jd|x2|j jD]&\} } | j} |j| s|j| | qW|S) Nz no host givenz\POST data should be bytes, an iterable of bytes, or a file object. It cannot be of type str.z Content-typez!application/x-www-form-urlencodedzContent-lengthzTransfer-encodingZchunkedro)rvrrIrrrrrrrr rr rrr) rrurvrIrZcontent_lengthZsel_hostrZselZsel_pathr[rrLrLrM do_request_s>          zAbstractHTTPHandler.do_request_c  s\|j}|std||fd|ji|}|j|jt|jjtfdd|jj Ddd<tddj D|j ri}d}|kr|||<|=|j |j |d y`y&|j |j |j|j|jd d Wn,tk r }zt|WYd d }~XnX|j} Wn|jYnX|jrF|jjd |_|j| _| j| _| S) zReturn an HTTPResponse object for the request, using http_class. http_class must implement the HTTPConnection API from http.client. z no host givenrJc3s"|]\}}|kr||fVqdS)NrL)rrr)rerLrMr)sz.AbstractHTTPHandler.do_open..r Connectioncss|]\}}|j|fVqdS)N)title)rr[rrLrLrMr6szProxy-Authorization)rezTransfer-encoding)Zencode_chunkedN)rvrrJZset_debuglevelr}rrxrrer{rzZ set_tunnelrurrrIrrm getresponserZsockrrHreasonr) rZ http_classrZhttp_conn_argsrvrZtunnel_headersZproxy_auth_hdrerrrrL)rerMrs@  "     zAbstractHTTPHandler.do_openN)r)rrrrrrrrrLrLrLrMr|s  &r|c@seZdZddZejZdS)r)cCs|jtjj|S)N)rrrr)rrrLrLrM http_open`szHTTPHandler.http_openN)rrrrr|rrRrLrLrLrMr)^src@s$eZdZdddZddZejZdS)rErNcCstj||||_||_dS)N)r|r_context_check_hostname)rr~r>check_hostnamerLrLrMris zHTTPSHandler.__init__cCs|jtjj||j|jdS)N)r>r)rrrrrr)rrrLrLrM https_openns zHTTPSHandler.https_open)rNN)rrrrrr|rrVrLrLrLrMrEgs rEc@s.eZdZdddZddZddZeZeZdS) rNcCs$ddl}|dkr|jj}||_dS)Nr)Zhttp.cookiejar cookiejarZ CookieJar)rrrrLrLrMrws zHTTPCookieProcessor.__init__cCs|jj||S)N)rZadd_cookie_header)rrurLrLrMrR}s z HTTPCookieProcessor.http_requestcCs|jj|||S)N)rZextract_cookies)rrurrLrLrMrsz!HTTPCookieProcessor.http_response)N)rrrrrRrrVrrLrLrLrMrvs  c@seZdZddZdS)r.cCs|j}td|dS)Nzunknown url type: %s)rr)rrrrLrLrMrszUnknownHandler.unknown_openN)rrrrrLrLrLrMr.scCsRi}xH|D]@}|jdd\}}|ddkrB|ddkrB|dd}|||<q W|S)z>Parse list of key=value strings where keys are not duplicated.=rRrr>rSrS)rE)lZparsedZeltrrrLrLrMr_s   r_cCsg}d}d}}xt|D]l}|r,||7}d}q|rV|dkr@d}qn |dkrLd}||7}q|dkrn|j|d}q|dkrzd}||7}qW|r|j|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. rnF\Tr>,cSsg|] }|jqSrL)rQ)rpartrLrLrMr&sz#parse_http_list..)r])rlresrescaper ZcurrLrLrMras4     rac@s(eZdZddZdZddZddZdS)r*cCs\|j}|dddkrN|dddkrN|jrN|jdkrN|j|jkrXtdn |j|SdS)Nr:z//r@r localhostz-file:// scheme is supported only on localhost)rrv get_namesropen_local_file)rrrHrLrLrM file_opens &  zFileHandler.file_openNc Cs`tjdkrZy*ttjddtjtjdt_Wn$tjk rXtjdft_YnXtjS)Nrr:)r*namesr'rgethostbyname_ex gethostnamegaierror gethostbyname)rrLrLrMrs  zFileHandler.get_namescCsddl}ddl}|j}|j}t|}ytj|}|j}|jj |j dd} |j |d} |j d| pbd|| f} |r~t |\}} | s| rt||jkr|rd||} nd|} tt|d| | SWn*tk r}zt|WYdd}~XnXtddS) NrT)usegmtz6Content-type: %s Content-length: %d Last-modified: %s z text/plainzfile://rbzfile not on local host) email.utils mimetypesrvrr4rWstatst_sizeutils formatdatest_mtime guess_typemessage_from_stringr _safe_gethostbynamerrrGrmr)rremailrrvrbZ localfilestatsrimodifiedmtyperer1ZorigurlexprLrLrMrs0  zFileHandler.open_local_file)rrrrrrrrLrLrLrMr*s  c Cs&y tj|Stjk r dSXdS)N)rrr)rvrLrLrMrs rc@seZdZddZddZdS)r+cCs.ddl}ddl}|j}|s"tdt|\}}|dkr>|j}nt|}t|\}}|rdt|\}}nd}t |}|pvd}|p~d}yt j |}Wn*t k r}zt|WYdd}~XnXt |j\} } | jd} ttt | } | dd| d} } | r| d r| dd} y|j||||| |j} | r8dp:d}x:| D]2}t|\}}|jdkrB|dkrB|j}qBW| j| |\}}d}|j|jd}|r|d |7}|dk r|dkr|d|7}tj|}t|||jS|jk r(}z$td|}|jtj dWYdd}~XnXdS)Nrzftp error: no host givenrnrrRrUDraArrzzContent-type: %s zContent-length: %d z ftp error: %rr:rSrS)rrrrUrzr)!ftplibrrvrr FTP_PORTr^rrr rrrmrrrErmap connect_ftprJrrtupperretrfilerrprrr all_errorswith_tracebacksysexc_info)rrrrrvr1rr"rrXattrsdirsrNfwrattrrrdretrlenrerrexcrLrLrMftp_opens\           zFTPHandler.ftp_openc Cst||||||ddS)NF) persistent) ftpwrapper)rrr"rvr1rrJrLrLrMr1szFTPHandler.connect_ftpN)rrrrrrLrLrLrMr+s5c@s<eZdZddZddZddZddZd d Zd d Zd S)r,cCs"i|_i|_d|_d|_d|_dS)Nr<re)cacherJsoonestdelay max_conns)rrLrLrMr8s zCacheFTPHandler.__init__cCs ||_dS)N)r)rtrLrLrM setTimeout?szCacheFTPHandler.setTimeoutcCs ||_dS)N)r)rrrLrLrM setMaxConnsBszCacheFTPHandler.setMaxConnscCsr|||dj||f}||jkr4tj|j|j|<n,t|||||||j|<tj|j|j|<|j|j|S)Nr)joinrrfrrJr check_cache)rrr"rvr1rrJrrLrLrMrEs  zCacheFTPHandler.connect_ftpcCstj}|j|krTx@t|jjD].\}}||kr"|j|j|j|=|j|=q"Wtt|jj|_t |j|j krx6t|jjD]$\}}||jkr|j|=|j|=PqWtt|jj|_dS)N) rfrrrJr{rrminvaluesr`r)rrrrrLrLrMrPs   zCacheFTPHandler.check_cachecCs4x|jjD] }|jq W|jj|jjdS)N)rrrclearrJ)rconnrLrLrM clear_cacheds  zCacheFTPHandler.clear_cacheN) rrrrrrrrrrLrLrLrMr,5s  c@seZdZddZdS)r-cCs~|j}|jdd\}}|jdd\}}t|}|jdrNtj|}|dd}|sVd}tjd|t|f}t t j |||S) N:rRrz;base64ztext/plain;charset=US-ASCIIz$Content-type: %s Content-length: %d i) rprErendswithr decodebytesrrr`rioBytesIO)rrrHrrIZ mediatypererLrLrM data_openks    zDataHandler.data_openN)rrrrrLrLrLrMr-jsrnt)r4r3cCst|S)zOS-specific conversion from a relative URL of the 'file' scheme to a file system path; not recommended for general use.)r )pathnamerLrLrMr4scCst|S)zOS-specific conversion from a file system path to a relative URL of the 'file' scheme; not recommended for general use.)r )rrLrLrMr3sc@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)3r8a,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).NzPython-urllib/%scKsdd|jji}tj|tdd|dkr.t}t|ds@td||_|j d|_ |j d|_ d |j fd g|_ g|_tj|_d|_t|_dS) NzW%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methodsclassr@) stacklevelrzproxies must be a mappingkey_file cert_filez User-AgentAccept*/*)rr)r:rr?r@rAr5rrrrrrversionr_URLopener__tempfilesrWrl_URLopener__unlink tempcacheftpcache)rrZx509rrLrLrMrs  zURLopener.__init__cCs |jdS)N)r)rrLrLrM__del__szURLopener.__del__cCs |jdS)N)cleanup)rrLrLrMrszURLopener.closec CsZ|jrFx2|jD](}y|j|Wqtk r4YqXqW|jdd=|jrV|jjdS)N)rrrmrr)rrNrLrLrMrs   zURLopener.cleanupcGs|jj|dS)zdAdd a header to be used by the HTTP interface only e.g. u.addheader('Accept', 'sound/basic')N)rr])rrrLrLrM addheaderszURLopener.addheadercCsntt|}t|dd}|jrL||jkrL|j|\}}t|d}t|||St|\}}|s`d}||jkr|j|}t|\}} t| \} } | |f}nd}d|} ||_ | j dd} t ||  s| d kr|r|j |||S|j ||Sy,|dkrt|| |St|| ||SWnVttfk r.Yn<tk rh} ztd | jtjd WYdd} ~ XnXdS) z6Use URLopener().open(file) instead of open(file, 'r').z%/:=&?~#+!$,;'@()*[]|)rrrNNZopen_-rrz socket errorr:)rrr rrGrr rr rrropen_unknown_proxy open_unknownrrrrmrrr)rrrIrbrerdurltyperHr proxyhostrvrr[rrLrLrMrGs<             zURLopener.opencCst|\}}tdd|dS)z/Overridable interface to open unknown URL type.z url errorzunknown url typeN)r rm)rrrIrrHrLrLrMrs zURLopener.open_unknowncCs t|\}}tdd||dS)z/Overridable interface to open unknown URL type.z url errorzinvalid proxy for %sN)r rm)rrrrIrrHrLrLrMr s zURLopener.open_unknown_proxyc Cs&tt|}|jr&||jkr&|j|St|\}}|dkr| sH|dkry.|j|}|j}|jtt|d|fSt k r} zWYdd} ~ XnX|j ||}zH|j} |rt |d} n|ddl } t|\} }t|pd\} }t |pd\}} t |pd\}} tjj|d}| j|\}}|jj|tj|d} z|| f}|jdk r^||j|<d }d }d}d}d | krt| d }|r||||xH|j|}|sP|t|7}| j||d7}|r||||qWWd| jXWd|jX|dkr"||kr"td ||f||S)ztretrieve(url) returns (filename, headers) for a local object or (tempfilename, headers) for a remote object.NrNrRrOrrnirQzcontent-lengthzContent-Lengthz1retrieval incomplete: got only %i out of %i bytesi rS)rrrr rrVrr4r rmrGrZrrrWrXsplitextZmkstemprr]fdopenr^r_r`rar)rrHrbrcrIrZurl1rdrrrerfrZZgarbagerXsuffixfdrgrhrir_rjrkrLrLrMretrievesl                  zURLopener.retrievecCs(d}d}t|trDefault error handler: close the connection and raise OSError.N)rr)rrHrdrrrerLrLrMrszURLopener.http_error_defaultcCstjj||j|jdS)N)rr)rrrrr)rrvrLrLrM_https_connectionszURLopener._https_connectioncCs|j|j||S)zUse HTTPS protocol.)rr)rrHrIrLrLrM open_httpsszURLopener.open_httpscCs^t|tstd|dddkrP|dddkrP|ddjdkrPtd n |j|SdS) z/Use local file or FTP depending on form of URL.zEfile error: proxy support for file protocol currently not implementedNr:z//r@r z localhost/z-file:// scheme is supported only on localhost)rrrrtrBr)rrHrLrLrM open_files  4 zURLopener.open_filecCs\ddl}ddl}t|\}}t|}ytj|}Wn0tk rb}zt|j|j WYdd}~XnX|j } |j j |j dd} |j|d} |jd| pd| | f} |s|} |dddkrd |} tt|d | | St|\}}| otj|tftkrP|} |dddkr d |} n|dd d kr>td |tt|d | | StddS)zUse local file.rNT)rz6Content-Type: %s Content-Length: %d Last-modified: %s z text/plainrRrzfile://rr:z./zAlocal file url may start with / or file:. Unknown url of type: %sz#local file error: not on local host)rrr r4rWrrmrstrerrorrbrrrrrrrrGr rrrthishostrB)rrHrrrvrNZ localnamererirrreZurlfiler1rLrLrMrs:     zURLopener.open_local_filecCst|tstdddl}t|\}}|s2tdt|\}}t|\}}|r\t|\}}nd}t|}t|ppd}t|p|d}t j |}|sddl }|j }nt |}t|\}} t|}|jd} | dd| d} } | o| d r| dd} | r| d rd| d<|||dj| f} t|jtkrlx8t|jD]*} | | kr>|j| }|j| =|jq>Wy| |jkrt||||| |j| <| sd}nd }x:| D]2}t|\}}|jd kr|dkr|j}qW|j| j| |\}}|jd|d}d}|r|d|7}|dk r:|dkr:|d|7}tj|}t||d|Stk r}z td|j t!j"dWYdd}~XnXdS)zUse FTP protocol.zCftp error: proxy support for ftp protocol currently not implementedrNzftp error: no host givenrnrrRrrUrrrrrzzftp:zContent-Type: %s zContent-Length: %d z ftp error %rr:rSrS)rrrrUrzr)#rrrrr r rrr rrrrr^rrErr`r MAXFTPCACHErrrrrtrrrrrr ftperrorsrrr)rrHrrvrXr1rr"rrrrNrrrrrrrdrrrerrLrLrMopen_ftpsp                   zURLopener.open_ftpc Cs<t|tstdy|jdd\}}Wntk rDtddYnX|sNd}|jd}|dkrd ||d kr||dd }|d |}nd }g}|jd tj d tj tj|jd||dkrt j |j djd}nt|}|jdt||jd |j|dj|}tj|}tj|}t|||S)zUse "data" URL.zEdata error: proxy support for data protocol currently not implementedrrRz data errorz bad data URLztext/plain;charset=US-ASCII;rrNrnzDate: %sz%a, %d %b %Y %H:%M:%S GMTzContent-type: %srrzlatin-1zContent-Length: %d )rrrrErBrmrfindr]rfZstrftimeZgmtimerrr r!r r`rrrrStringIOr) rrHrIrZsemirrrefrLrLrM open_data3s6        zURLopener.open_data)N)N)N)N)NNN)N)N)N)N)rrrrrrrrrrrrrGrrrrrrrrCrrrrrr rLrLrLrMr8s.  $   B\     :c@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|f||i|_d|_d|_dS)Nrr)r8r auth_cachetriesmaxtries)rrr9rLrLrMr`szFancyURLopener.__init__cCst||d||S)z3Default error handling -- don't raise an exception.zhttp:)r)rrHrdrrrerLrLrMrfsz!FancyURLopener.http_error_defaultNc Csn|jd7_zR|jrJ|j|jkrJt|dr4|j}n|j}|||dd|S|j||||||}|Sd|_XdS)z%Error 302 -- relocated (temporarily).rRhttp_error_500iz)Internal Server Error: Redirect RecursionNr)r r rrrredirect_internal) rrHrdrrrerIrrgrLrLrMr js  zFancyURLopener.http_error_302c Csxd|kr|d}nd|kr$|d}ndS|jt|jd||}t|}|jd krnt|||d||||j|S) Nrrrrrrrnz( Redirection to url '%s' is not allowed.)rrrrn)rrrrrrrG) rrHrdrrrerIrrrLrLrMr|s   z FancyURLopener.redirect_internalcCs|j||||||S)z*Error 301 -- also relocated (permanently).)r )rrHrdrrrerIrLrLrMr szFancyURLopener.http_error_301cCs|j||||||S)z;Error 303 -- also relocated (essentially identical to 302).)r )rrHrdrrrerIrLrLrMr szFancyURLopener.http_error_303cCs2|dkr|j||||||S|j|||||SdS)z1Error 307 -- relocated, but turn POST into error.N)r r)rrHrdrrrerIrLrLrMr szFancyURLopener.http_error_307Fc Csd|krtj|||||||d}tjd|} | sHtj||||||| j\} } | jdkrttj|||||||stj||||||d|jd} |dkrt|| || St|| || |SdS)z_Error 401 -- authentication required. This function supports Basic authentication only.zwww-authenticatez![ ]*([^ ]+)[ ]+realm="([^"]*)"rHZretry_ _basic_authN)r8rrSmatchrCrtrr) rrHrdrrrerIr{stuffrrr(r[rLrLrMrWs&         zFancyURLopener.http_error_401c Csd|krtj|||||||d}tjd|} | sHtj||||||| j\} } | jdkrttj|||||||stj||||||d|jd} |dkrt|| || St|| || |SdS)zeError 407 -- proxy authentication required. This function supports Basic authentication only.zproxy-authenticatez![ ]*([^ ]+)[ ]+realm="([^"]*)"rHZ retry_proxy_rN)r8rrSrrCrtrr) rrHrdrrrerIr{rrrr(r[rLrLrMrXs&         zFancyURLopener.http_error_407cCst|\}}d||}|jd}t|\}} t| \} } | jdd} | | d} |j| || \} } | pl| srdSdt| ddt| dd| f} d| | |jd<|dkr|j|S|j||SdS)Nzhttp://r@rRz%s:%s@%srn)r)r rr rget_user_passwdr rG)rrHr(rIrvrrrrr proxyselectorrrr"rLrLrMretry_proxy_http_basic_auths         z*FancyURLopener.retry_proxy_http_basic_authcCst|\}}d||}|jd}t|\}} t| \} } | jdd} | | d} |j| || \} } | pl| srdSdt| ddt| dd| f} d| | |jd<|dkr|j|S|j||SdS)Nzhttps://rrrRz%s:%s@%srn)r)r rr rrr rG)rrHr(rIrvrrrrrrrrr"rLrLrMretry_proxy_https_basic_auths         z+FancyURLopener.retry_proxy_https_basic_authc Cst|\}}|jdd}||d}|j|||\}}|p>|sDdSdt|ddt|dd|f}d||} |dkr|j| S|j| |SdS)NrrRz%s:%s@%srn)rzhttp://)r rrr rG) rrHr(rIrvrrrr"rrLrLrMrIs     z$FancyURLopener.retry_http_basic_authc Cst|\}}|jdd}||d}|j|||\}}|p>|sDdSdt|ddt|dd|f}d||} |dkr|j| S|j| |SdS)NrrRz%s:%s@%srn)rzhttps://)r rrr rG) rrHr(rIrvrrrr"rrLrLrMretry_https_basic_auth s     z%FancyURLopener.retry_https_basic_authrcCs`|d|j}||jkr2|r(|j|=n |j|S|j||\}}|sJ|rX||f|j|<||fS)Nr)rtr prompt_user_passwd)rrvr(rrrr"rLrLrMr s   zFancyURLopener.get_user_passwdc CsTddl}y,td||f}|jd|||f}||fStk rNtdSXdS)z#Override this in a GUI environment!rNzEnter username for %s at %s: z#Enter password for %s in %s at %s: )NN)getpassinputKeyboardInterruptprint)rrvr(rrr"rLrLrMr$ sz!FancyURLopener.prompt_user_passwd)N)N)N)N)NF)NF)N)N)N)N)r)rrrrrrr rr r r rWrXrrrIrrrrLrLrLrMr9]s$           cCstdkrtjdatS)z8Return the IP address of the magic hostname 'localhost'.Nr) _localhostrrrLrLrLrMr4 s rc CsPtdkrLyttjtjdaWn(tjk rJttjddaYnXtS)z,Return the IP addresses of the current host.Nr:r) _thishostr'rrrrrLrLrLrMr< s rcCstdkrddl}|jatS)z1Return the set of errors raised by the FTP class.Nr) _ftperrorsrr)rrLrLrMrG srcCstdkrtjdatS)z%Return an empty email Message object.Nrn) _noheadersrrrLrLrLrM noheadersP s r"c@sJeZdZdZdddZddZdd Zd d Zd d ZddZ ddZ dS)rz;Class used by open_ftp() for cache of open FTP connections.NTc CsX||_||_||_||_||_||_d|_||_y |jWn|j YnXdS)Nr) rr"rvr1rrJrefcount keepaliveinitr)rrr"rvr1rrJrrLrLrMr] s zftpwrapper.__init__cCs\ddl}d|_|j|_|jj|j|j|j|jj|j |j dj |j }|jj |dS)Nrr)rbusyZFTPrZconnectrvr1rJZloginrr"rrcwd)rrZ_targetrLrLrMr%m s  zftpwrapper.initc -Csddl}|j|dkr"d}d}n d|}d}y|jj|Wn*|jk rh|j|jj|YnXd}|r| ryd|}|jj|\}}WnR|jk r}z4t|ddd krt d |j t j d WYdd}~XnX|s|jjd|rn|jj } zJy|jj|Wn4|jk rP}zt d ||WYdd}~XnXWd|jj| Xd |}nd }|jj|\}}d|_t|jd|j} |jd7_|j| |fS)NrrzrzTYPE ArRzTYPE zRETR r@Z550z ftp error: %rr:zLIST ZLISTr)rzr)r endtransferrZvoidcmdrr%Z ntransfercmdZ error_permrrrrrpwdr'r&rmakefile file_closer#r) rrNrrcmdisdirrrrr)ZftpobjrLrLrMrv sN     $ zftpwrapper.retrfilecCs d|_dS)Nr)r&)rrLrLrMr( szftpwrapper.endtransfercCsd|_|jdkr|jdS)NFr)r$r# real_close)rrLrLrMr s zftpwrapper.closecCs4|j|jd8_|jdkr0|j r0|jdS)NrRr)r(r#r$r.)rrLrLrMr+ szftpwrapper.file_closec Cs2|jy|jjWntk r,YnXdS)N)r(rrr)rrLrLrMr. s zftpwrapper.real_close)NT) rrrrrr%rr(rr+r.rLrLrLrMrZ s  -rcCsi}xBtjjD]4\}}|j}|r|dddkr|||dd<qWdtjkr^|jddxXtjjD]J\}}|dddkrj|j}|r|||dd <qj|j|dd dqjW|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. N_proxyZREQUEST_METHODriiiii)rWenvironr{rtr)rr[rrLrLrMgetproxies_environment s   r2c Cs|dkrt}y |d}Wntk r.dSX|dkr.r.z (.+\.)?%s$) r2rtr rElstriprSrrrU)rvrZno_proxyhostonlyr1Z no_proxy_listr[patternrLrLrMproxy_bypass_environment s&     r9c Csddlm}t|\}}dd}d|kr4|dr4dSd}x|jd fD]}|sPqFtjd |}|dk r|dkrytj|}||}Wntk rwFYnX||jd } |jd } | dkrd |jd j dd } nt | d d} d| } || ?| | ?krdSqF|||rFdSqFWdS)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)fnmatchcSsh|jd}ttt|}t|dkr<|ddddgdd}|dd>|dd>B|dd>B|d BS) Nr5rrrRrer:rQr@)rErrr^r`)ZipAddrr0rLrLrMip2num s   z,_proxy_bypass_macosx_sysconf..ip2numr5Zexclude_simpleTN exceptionsz(\d+(?:\.\d+)*)(/\d+)?rRr:rQ F) r:r rrSrrrrmgroupcountr^) rvproxy_settingsr:r7r1r<ZhostIPrrr4maskrLrLrM_proxy_bypass_macosx_sysconf s:        rCdarwin)_get_proxy_settings _get_proxiescCst}t||S)N)rErC)rvrArLrLrMproxy_bypass_macosx_sysconf: srGcCstS)zReturn a dictionary of scheme -> proxy server URL mappings. This function uses the MacOSX framework SystemConfiguration to fetch the proxy information. )rFrLrLrLrMgetproxies_macosx_sysconf> srHcCs t}|rt||St|SdS)zReturn True, if host should be bypassed. Checks proxy settings gathered from the environment, if specified, or from the MacOSX framework SystemConfiguration. N)r2r9rG)rvrrLrLrMrH s rcCs tp tS)N)r2rHrLrLrLrMr5U scCsi}y ddl}Wntk r$|SXy|j|jd}|j|dd}|rt|j|dd}d|krx|jdD]4}|jdd\}}tjd |sd ||f}|||<qrWn>|dd d kr||d <n$d||d <d||d<d||d<|j Wnt t t fk rYnX|S)zxReturn a dictionary of scheme -> proxy server URL mappings. Win32 uses the registry to store proxies. rNz;Software\Microsoft\Windows\CurrentVersion\Internet Settings ProxyEnableZ ProxyServerrrrRz ^([^/:]+)://z%s://%sr]zhttp:rz http://%sz https://%srzftp://%sr) winreg ImportErrorOpenKeyHKEY_CURRENT_USER QueryValueExrrErSrZClosermrBr)rrJinternetSettings proxyEnableZ proxyServerprZaddressrLrLrMgetproxies_registryZ s8          rRcCs tp tS)zReturn a dictionary of scheme -> proxy server URL mappings. Returns settings gathered from the environment, if specified, or the registry. )r2rRrLrLrLrMr5 sc &Cs~y ddl}Wntk r dSXy6|j|jd}|j|dd}t|j|dd}Wntk rldSX| sz| r~dSt|\}}|g}y tj |}||kr|j |Wntk rYnXy tj |}||kr|j |Wntk rYnX|j d}xp|D]h} | dkr*d|kr*dS| j dd } | j d d } | j d d} x$|D]} tj| | tjrTdSqTWqWdS) Nrz;Software\Microsoft\Windows\CurrentVersion\Internet SettingsrIZ ProxyOverriderzr5rRz\.r4z.*?)rJrKrLrMrNrrmr rrr]ZgetfqdnrErrSrrU) rvrJrOrPZ proxyOverrideZrawHostr1ZaddrZfqdnr5rrLrLrMproxy_bypass_registry sR              rTcCs t}|rt||St|SdS)zReturn True, if host should be bypassed. Checks proxy settings gathered from the environment, if specified, or the registry. N)r2r9rT)rvrrLrLrMr s )NNN)N)rrrrrhZ http.clientrrrWr2rSrrrrf collectionsrZrTr?Z urllib.errorrrrZ urllib.parserrrrr r r r r rrrrrrrrrZurllib.responserrrDrKrC__all__ version_inforrFrr0r1r\r6r7rTASCIIrrrwrrr2rr/rrrrr r!r"r#r$r%urandomrgr&r'r(r|r)rrrEr]rr.r_rar*rr+r,r-rr[Z nturl2pathr4r3rr8r9rrrrr rr!r"rr2r9rCplatformZ_scproxyrErFrGrHrr5rRrTrLrLrLrMDsP   T ?n$q*@ o  v  +3:5! AW  _ #<    - 2