o
    Kgx                    @   s  d Z ddlmZmZmZmZ ddlmZmZm	Z	m
Z
mZmZmZmZ ddlmZmZmZ ddlZddlZddlZddlZddlmZ ddlmZ dd	lmZmZmZ dd
l m!Z!m"Z"m#Z#m$Z$m%Z%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1 ddl2m3Z3m4Z4 ddl5Z5ddl6Z6ddl7Z7ddl8Z8ddl9Z9ddl:Z:ddl;Z;ddl<Z<ddl=Z=ddl>Z>ddlmZ erddl?m@Z@ nddlAm@Z@ zddlBZBddlBmCZC W n eDy   dZEY nw dZEg dZFe:jGdd ZHdaIde9jJfddZKdd ZLg ZMdddZNdd ZOere8Pde8jQZRne8PdZRdd ZSG dd deTZUG d d! d!eTZVd"d# ZWG d$d% d%eTZXG d&d' d'eXZYG d(d) d)eXZZG d*d+ d+eXZ[d,d- Z\G d.d/ d/eXZ]G d0d1 d1eTZ^G d2d3 d3e^Z_G d4d5 d5eTZ`G d6d7 d7e`eXZaG d8d9 d9e`eXZbe6jcZdG d:d; d;eTZeG d<d= d=eXeeZfG d>d? d?eXeeZgG d@dA dAeXZhG dBdC dCehZiejedDrG dEdF dFehZkeFldF G dGdH dHeXZmG dIdJ dJeXZndKdL ZodMdN ZpG dOdP dPeXZqdQdR ZrG dSdT dTeXZsG dUdV dVesZtdWZue6jvdXkrddYlwmxZxmyZy ndZd[ Zxd\d] Zyi ZzG d^d_ d_eTZ{G d`da dae{Z|da}dbdc Z~daddde Zdadfdg Zdadhdi ZG djdk dkeTZdldm Zdndo Zdpdq Ze:jdrkrdddslmZmZ dtdu Zdvdw Zdxdy Zdzd{ ZdS e6jvdXkr|d|d} Zd~d{ Zdd Zddy ZdS eZeZdS )a
  
Ported using Python-Future from the Python 3.3 standard library.

An extensible library for opening URLs using a variety of protocols

The simplest way to use this module is to call the urlopen function,
which accepts a string containing a URL or a Request object (described
below).  It opens the URL and returns the results as file-like
object; the returned object has some extra methods described below.

The OpenerDirector manages a collection of Handler objects that do
all the actual work.  Each Handler implements a particular protocol or
option.  The OpenerDirector is a composite object that invokes the
Handlers needed to open the requested URL.  For example, the
HTTPHandler performs HTTP GET and POST requests and deals with
non-error returns.  The HTTPRedirectHandler automatically deals with
HTTP 301, 302, 303 and 307 redirect errors, and the HTTPDigestAuthHandler
deals with digest authentication.

urlopen(url, data=None) -- Basic usage is the same as original
urllib.  pass the url and optionally data to post to an HTTP URL, and
get a file-like object back.  One difference is that you can also pass
a Request instance instead of URL.  Raises a URLError (subclass of
IOError); for HTTP errors, raises an HTTPError, which can also be
treated as a valid response.

build_opener -- Function that creates a new OpenerDirector instance.
Will install the default handlers.  Accepts one or more Handlers as
arguments, either instances or Handler classes that it will
instantiate.  If one of the argument is a subclass of the default
handler, the argument will be installed instead of the default.

install_opener -- Installs a new opener as the default opener.

objects of interest:

OpenerDirector -- Sets up the User Agent as the Python-urllib client and manages
the Handler classes, while dealing with requests and responses.

Request -- An object that encapsulates the state of a request.  The
state can be as simple as the URL.  It can also include extra HTTP
headers, e.g. a User-Agent.

BaseHandler --

internals:
BaseHandler and parent
_call_chain conventions

Example usage:

import urllib.request

# set up authentication info
authinfo = urllib.request.HTTPBasicAuthHandler()
authinfo.add_password(realm='PDQ Application',
                      uri='https://mahler:8092/site-updates.py',
                      user='klem',
                      passwd='geheim$parole')

proxy_support = urllib.request.ProxyHandler({"http" : "http://ahad-haam:3128"})

# build a new opener that adds authentication and caching FTP handlers
opener = urllib.request.build_opener(proxy_support, authinfo,
                                     urllib.request.CacheFTPHandler)

# install it
urllib.request.install_opener(opener)

f = urllib.request.urlopen('http://www.python.org/')
    )absolute_importdivisionprint_functionunicode_literals)bytesdictfilterinputintmapopenstr)PY2PY3raise_with_tracebackN)email)client   )URLError	HTTPErrorContentTooShortError)urlparseurlspliturljoinunwrapquoteunquote	splittype	splithost	splitport	splitusersplitpasswd	splitattr
splitquery
splitvaluesplittagto_bytes
urlunparse)
addinfourladdclosehook)r   )Iterable)
SSLContextFT)RequestOpenerDirectorBaseHandlerHTTPDefaultErrorHandlerHTTPRedirectHandlerHTTPCookieProcessorProxyHandlerHTTPPasswordMgrHTTPPasswordMgrWithDefaultRealmAbstractBasicAuthHandlerHTTPBasicAuthHandlerProxyBasicAuthHandlerAbstractDigestAuthHandlerHTTPDigestAuthHandlerProxyDigestAuthHandlerHTTPHandlerFileHandler
FTPHandlerCacheFTPHandlerUnknownHandlerHTTPErrorProcessorurlopeninstall_openerbuild_openerpathname2urlurl2pathname
getproxiesurlretrieve
urlcleanup	URLopenerFancyURLopener   c           
      K   s   d|v r|d }|d= nd}d|v r|d }|d= nd }d|v r(|d }|d= nd }|s0|s0|rbt s6tdttj}| jtjO  _tj|_|sL|rS|	|| n|
  t|dd}t|}	ntd u rlt  a}	nt}	|	| ||S )N	cadefaultFcapathcafilezSSL support not availableTcontextcheck_hostname)	_have_ssl
ValueErrorsslr+   PROTOCOL_SSLv23optionsOP_NO_SSLv2CERT_REQUIREDverify_modeload_verify_locationsset_default_verify_pathsHTTPSHandlerrC   _openerr   )
urldatatimeout_3to2kwargsrL   rM   rN   rP   https_handleropener rd   d/var/www/html/status_management/venv/lib/python3.10/site-packages/future/backports/urllib/request.pyrA      s*   
rA   c                 C   s   | a d S N)r]   )rc   rd   rd   re   rB      s   rB   c              	   C   sb  t | \}}tt| |}| }|dkr(|s(tj||fW  d   S |r0t|d}nt	j
dd}|j}t| |G ||f}	d}
d}d}d}d	|v rWt|d
 }|r_|||
| 	 ||
}|shn|t|7 }|| |d7 }|r|||
| q`W d   n1 sw   Y  W d   n1 sw   Y  |dkr||k rtd||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.
    fileNwbF)delete    r   content-lengthContent-LengthTr   1retrieval incomplete: got only %i out of %i bytes)r   
contextlibclosingrA   infoospathnormpathr   tempfileNamedTemporaryFilename_url_tempfilesappendr
   readlenwriter   )r^   filename
reporthookr_   url_typers   fpheaderstfpresultbssizerz   blocknumblockrd   rd   re   rG      sV   	


&rG   c               	   C   sD   t D ]} zt|  W q ty   Y qw t d d = tr d ad S d S rf   )rx   rr   unlinkEnvironmentErrorr]   )	temp_filerd   rd   re   rH      s   
rH   z:\d+$c                 C   s<   | j }t|d }|dkr| dd}td|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_resublower)requestr^   hostrd   rd   re   request_host  s   r   c                   @   s   e Zd Zdi dddfddZdd Zdd Zd	d
 Zdd Zdd Zdd Z	dd Z
dd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd)d%d&Zd'd( ZdS )*r,   NFc           	      C   s   t || _t| j\| _| _|| _i | _d | _| D ]
\}}| || qi | _	|d u r1t
| }|| _|| _|| _|   d S rf   )r   r   r%   fragmentr_   r   _tunnel_hostitems
add_headerunredirected_hdrsr   origin_req_hostunverifiablemethod_parse)	selfr^   r_   r   r   r   r   keyvaluerd   rd   re   __init__  s   
zRequest.__init__c                 C   sR   t | j\| _}| jd u rtd| j t|\| _| _| jr't| j| _d S d S )Nzunknown url type: %r)r   r   typerS   r   r   selectorr   )r   restrd   rd   re   r   .  s   
zRequest._parsec                 C   s"   | j dur| j S | jdurdS dS )z3Return a string indicating the HTTP request method.NPOSTGET)r   r_   r   rd   rd   re   
get_method6  s
   

zRequest.get_methodc                 C   s   | j rd| j| j f S | jS )Nz%s#%s)r   r   r   rd   rd   re   get_full_url?  s   zRequest.get_full_urlc                 C   s   d}t j|tdd || _d S )Nz&Request.add_data method is deprecated.r   
stacklevelwarningswarnDeprecationWarningr_   )r   r_   msgrd   rd   re   add_dataG     
zRequest.add_datac                 C   s   d}t j|tdd | jd uS )Nz&Request.has_data method is deprecated.r   r   r   r   r   rd   rd   re   has_dataL  r   zRequest.has_datac                 C      d}t j|tdd | jS )Nz&Request.get_data method is deprecated.r   r   r   r   rd   rd   re   get_dataQ     zRequest.get_datac                 C   r   )Nz&Request.get_type method is deprecated.r   r   )r   r   r   r   r   rd   rd   re   get_typeV  r   zRequest.get_typec                 C   r   )Nz&Request.get_host method is deprecated.r   r   )r   r   r   r   r   rd   rd   re   get_host[  r   zRequest.get_hostc                 C   r   )Nz*Request.get_selector method is deprecated.r   r   )r   r   r   r   r   rd   rd   re   get_selector`  r   zRequest.get_selectorc                 C   r   )Nz-Request.is_unverifiable method is deprecated.r   r   )r   r   r   r   r   rd   rd   re   is_unverifiablee  r   zRequest.is_unverifiablec                 C   r   )Nz1Request.get_origin_req_host method is deprecated.r   r   )r   r   r   r   r   rd   rd   re   get_origin_req_hostj  r   zRequest.get_origin_req_hostc                 C   s2   | j dkr| js| j| _n|| _ | j| _|| _d S )Nhttps)r   r   r   r   r   )r   r   r   rd   rd   re   	set_proxyq  s
   

zRequest.set_proxyc                 C   s   | j | jkS rf   )r   r   r   rd   rd   re   	has_proxyy     zRequest.has_proxyc                 C      || j | < d S rf   )r   
capitalizer   r   valrd   rd   re   r   |     zRequest.add_headerc                 C   r   rf   )r   r   r   rd   rd   re   add_unredirected_header  r   zRequest.add_unredirected_headerc                 C   s   || j v p	|| jv S rf   )r   r   )r   header_namerd   rd   re   
has_header  s   
zRequest.has_headerc                 C   s   | j || j||S rf   )r   getr   )r   r   defaultrd   rd   re   r     s   zRequest.get_headerc                 C   s"   | j  }|| j t| S rf   )r   copyupdater   listr   )r   hdrsrd   rd   re   header_items  s   
zRequest.header_itemsrf   )__name__
__module____qualname__r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rd   rd   rd   re   r,     s.    
	
r,   c                   @   sN   e Zd Zdd Zdd Zdd Zdd Zd	ejfd
dZ	dddZ
dd Zd	S )r-   c                 C   s6   dt  }d|fg| _g | _i | _i | _i | _i | _d S )NPython-urllib/%sz
User-agent)__version__
addheadershandlershandle_openhandle_errorprocess_responseprocess_request)r   client_versionrd   rd   re   r     s   
zOpenerDirector.__init__c              	   C   sP  t |dstdt| d}t|D ]}|dv rq|d}|d | }||d d  }|dr`|d| d }||d d  }zt|}W n	 tyR   Y nw | j	|i }	|	| j|< n|dkrj|}| j
}	n|d	krt|}| j}	n|d
kr~|}| j}	nq|	|g }
|
rt|
| n|
| d}q|rt| j| ||  d S d S )N
add_parentz%expected BaseHandler instance, got %rF)redirect_requestdo_open
proxy_open_r   errorr   responser   T)hasattr	TypeErrorr   dirfind
startswithr
   rS   r   r   r   r   r   
setdefaultbisectinsortry   r   r   )r   handleraddedmethiprotocol	conditionjkindlookupr   rd   rd   re   add_handler  sP   



zOpenerDirector.add_handlerc                 C      d S rf   rd   r   rd   rd   re   close     zOpenerDirector.closec           	      G   s<   | |d}|D ]}t||}|| }|d ur|  S qd S )Nrd   )r   getattr)	r   chainr   	meth_nameargsr   r   funcr   rd   rd   re   _call_chain  s   
zOpenerDirector._call_chainNc           
      C   s   t |tr	| }t |trt||}n	|}|dur||_||_|j}|d }| j	|g D ]}t
||}||}q.| ||}	|d }| j	|g D ]}t
||}|||	}	qK|	S )z
        Accept a URL or a Request object

        Python-Future: if the URL is passed as a byte-string, decode it first.
        N_request	_response)
isinstancer   decoder   r,   r_   r`   r   r   r   r   _openr   )
r   fullurlr_   r`   reqr   r   	processorr   r   rd   rd   re   r     s&   




zOpenerDirector.openc                 C   sP   |  | jdd|}|r|S |j}|  | j||d |}|r|S |  | jdd|S )Nr   default_openr  unknownunknown_open)r   r   r   )r   r  r_   r   r   rd   rd   re   r    s    

zOpenerDirector._openc                 G   s~   |dv r| j d }|d }d| }d}|}n	| j }|d }d}|||f| }| j| }|r/|S |r=|dd	f| }| j| S d S )
Nhttpr   r
     zhttp_error_%sr   _errorr   r   http_error_default)r   r   )r   protor   r   r   http_err	orig_argsr   rd   rd   re   r     s"   


zOpenerDirector.errorrf   )r   r   r   r   r   r   r   socket_GLOBAL_DEFAULT_TIMEOUTr   r  r   rd   rd   rd   re   r-     s    /
"r-   c                  G   s   dd }t  }ttttttttg}t	t
dr|t t }|D ] }| D ]}||r5t||r4|| q$t||r?|| q$q |D ]}|| qC|D ]}||  qM| D ]}||ra| }|| qX|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.
    c                 S   s   t | tp	t| dS )N	__bases__)r   r   r   )objrd   rd   re   isclass/  s   zbuild_opener.<locals>.isclassHTTPSConnection)r-   r2   r?   r;   r/   r0   r=   r<   r@   r   http_clientry   r\   set
issubclassaddr   remover   )r   r  rc   default_classesskipklasscheckhrd   rd   re   rC   &  s8   	





rC   c                   @   s(   e Zd ZdZdd Zdd Zdd ZdS )	r.     c                 C   
   || _ d S rf   )parent)r   r#  rd   rd   re   r   O     
zBaseHandler.add_parentc                 C   r   rf   rd   r   rd   rd   re   r   R  r   zBaseHandler.closec                 C   s   t |dsdS | j|jk S )Nhandler_orderT)r   r%  )r   otherrd   rd   re   __lt__V  s   
zBaseHandler.__lt__N)r   r   r   r%  r   r   r'  rd   rd   rd   re   r.   L  s
    r.   c                   @   s    e Zd ZdZdZdd ZeZdS )r@   zProcess HTTP error responses.i  c                 C   sH   |j |j| }}}d|  krdk s"n | jd|||||}|S )N   ,  r
  )coder   rq   r#  r   )r   r   r   r*  r   r   rd   rd   re   http_responsec  s   z HTTPErrorProcessor.http_responseN)r   r   r   __doc__r%  r+  https_responserd   rd   rd   re   r@   _  s
    r@   c                   @      e Zd Zdd ZdS )r/   c                 C   s   t |j||||rf   )r   r   )r   r  r   r*  r   r   rd   rd   re   r  q  s   z*HTTPDefaultErrorHandler.http_error_defaultN)r   r   r   r  rd   rd   rd   re   r/   p      r/   c                   @   s4   e Zd ZdZdZdd Zdd Ze Z ZZ	dZ
dS )	r0      
   c           	         sx   |  }|dv r|dv s|dv r|dkst|j|||||dd}d t fdd	|j D }t|||jd
dS )a  Return 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  )r   HEAD)r2  r3  r4  r    z%20)rl   zcontent-typec                 3   s(    | ]\}}|   vr||fV  qd S rf   )r   .0kvCONTENT_HEADERSrd   re   	<genexpr>  s   
 z7HTTPRedirectHandler.redirect_request.<locals>.<genexpr>T)r   r   r   )	r   r   r   replacer   r   r   r,   r   )	r   r  r   r*  r   r   newurlm
newheadersrd   r;  re   r   |  s   
z$HTTPRedirectHandler.redirect_requestc           
      C   s2  d|v r	|d }nd|v r|d }nd S t |}|jdvr)t||d||f |||js4t|}d|d< t|}t|j|}| ||||||}|d u rNd S t	|drv|j
 }	|_
|	|d| jksit|	| jkrut|j|| j| ||ni  }	 |_
|_
|	|dd	 |	|< |  |  | jj||jd
S )Nlocationurir
  r   ftpr   z+%s - Redirection to url '%s' is not allowed/r  redirect_dictr   r   r`   )r   schemer   rs   r   r'   r   r   r   r   rG  r   max_repeatsr{   max_redirectionsinf_msgrz   r   r#  r   r`   )
r   r  r   r*  r   r   r?  urlpartsnewvisitedrd   rd   re   http_error_302  sB   




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)r   r   r   rJ  rK  r   rP  http_error_301http_error_303http_error_307rL  rd   rd   rd   re   r0   t  s    "7r0   c           	      C   s   t | \}}|dsd}| }n|dstd|  |dd}|dkr'd}|d| }t|\}}|dur>t|\}}nd }}||||fS )a3  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:

    >>> _parse_proxy('file:/ftp.example.com/')
    Traceback (most recent call last):
    ValueError: proxy URL with no authority: 'file:/ftp.example.com/'

    The first three items of the returned tuple may be None.

    Examples of authority parsing:

    >>> _parse_proxy('proxy.example.com')
    (None, None, None, 'proxy.example.com')
    >>> _parse_proxy('proxy.example.com:3128')
    (None, None, None, 'proxy.example.com:3128')

    The authority component may optionally include userinfo (assumed to be
    username:password):

    >>> _parse_proxy('joe:password@proxy.example.com')
    (None, 'joe', 'password', 'proxy.example.com')
    >>> _parse_proxy('joe:password@proxy.example.com:3128')
    (None, 'joe', 'password', 'proxy.example.com:3128')

    Same examples, but with URLs instead:

    >>> _parse_proxy('http://proxy.example.com/')
    ('http', None, None, 'proxy.example.com')
    >>> _parse_proxy('http://proxy.example.com:3128/')
    ('http', None, None, 'proxy.example.com:3128')
    >>> _parse_proxy('http://joe:password@proxy.example.com/')
    ('http', 'joe', 'password', 'proxy.example.com')
    >>> _parse_proxy('http://joe:password@proxy.example.com:3128')
    ('http', 'joe', 'password', 'proxy.example.com:3128')

    Everything after the authority is ignored:

    >>> _parse_proxy('ftp://joe:password@proxy.example.com/rubbish:3128')
    ('ftp', 'joe', 'password', 'proxy.example.com')

    Test for no trailing '/' case:

    >>> _parse_proxy('http://joe:password@proxy.example.com')
    ('http', 'joe', 'password', 'proxy.example.com')

    rF  N//zproxy URL with no authority: %rr  rk   )r   r   rS   r   r    r!   )	proxyrI  r_scheme	authorityenduserinfohostportuserpasswordrd   rd   re   _parse_proxy  s   2

r]  c                   @   s"   e Zd ZdZdddZdd ZdS )r2   d   Nc                 C   sZ   |d u rt  }t|dsJ d|| _| D ]\}}t| d| ||| jfdd qd S )Nkeysproxies must be a mappingz%s_openc                 S   s   || ||S rf   rd   )rrU  r   r   rd   rd   re   <lambda>/  r   z'ProxyHandler.__init__.<locals>.<lambda>)rF   r   proxiesr   setattrr   )r   rc  r   r^   rd   rd   re   r   (  s   
zProxyHandler.__init__c                 C   s   |j }t|\}}}}|d u r|}|jrt|jrd S |r;|r;dt|t|f }	t|	 d}
|	dd|
  t|}|
|| ||ksM|dkrOd S | jj||jdS )N%s:%sasciiProxy-authorizationBasic r   rH  )r   r]  r   proxy_bypassr   base64	b64encodeencoder  r   r   r#  r   r`   )r   r  rU  r   	orig_type
proxy_typer[  r\  rZ  	user_passcredsrd   rd   re   r   2  s"   zProxyHandler.proxy_openrf   )r   r   r   r%  r   r   rd   rd   rd   re   r2   $  s    

r2   c                   @   s6   e Zd Zdd Zdd Zdd Zddd	Zd
d ZdS )r3   c                 C   s
   i | _ d S rf   )passwdr   rd   rd   re   r   P  r$  zHTTPPasswordMgr.__init__c                    s\   t |tr|g}|jvri j|< dD ] t fdd|D }||fj| |< qd S )NTFc                    s   g | ]} | qS rd   )
reduce_uri)r8  udefault_portr   rd   re   
<listcomp>[  s    z0HTTPPasswordMgr.add_password.<locals>.<listcomp>)r   r   rq  tuple)r   realmrC  r[  rq  reduced_urird   ru  re   add_passwordS  s   


zHTTPPasswordMgr.add_passwordc           	      C   s`   | j |i }dD ]$}| ||}| D ]\}}|D ]}| ||r+|      S qqq	dS )Nrr  NN)rq  r   rs  r   	is_suburi)	r   ry  authuridomainsrv  reduced_authuriurisauthinforC  rd   rd   re   find_user_password^  s   z"HTTPPasswordMgr.find_user_passwordTc           
      C   s   t |}|d r|d }|d }|d pd}nd}|}d}t|\}}|r?|du r?|dur?ddd|}	|	dur?d	||	f }||fS )
z@Accept authority or URI and extract only the authority and path.r   r   r  rF  NP   i  r	  z%s:%d)r   r   r   )
r   rC  rv  partsrI  rW  rs   r   portdportrd   rd   re   rs  h  s$   zHTTPPasswordMgr.reduce_uric                 C   sR   ||krdS |d |d krdS t |d |d f}t|t|d kr'dS dS )zcCheck if test is below base in a URI tree

        Both args must be URIs in reduced form.
        Tr   Fr   )	posixpathcommonprefixr{   )r   basetestcommonrd   rd   re   r}    s   zHTTPPasswordMgr.is_suburiN)T)r   r   r   r   r{  r  rs  r}  rd   rd   rd   re   r3   N  s    

r3   c                   @   r.  )r4   c                 C   s0   t | ||\}}|d ur||fS t | d |S rf   )r3   r  )r   ry  r~  r[  r\  rd   rd   re   r    s   z2HTTPPasswordMgrWithDefaultRealm.find_user_passwordN)r   r   r   r  rd   rd   rd   re   r4     s    r4   c                   @   s<   e Zd ZedejZdddZdd Zdd Z	d	d
 Z
dS )r5   z1(?:.*,)*[ 	]*([^ 	]+)[ 	]+realm=(["']?)([^"']*)\2Nc                 C   s(   |d u rt  }|| _| jj| _d| _d S Nr   )r3   rq  r{  retried)r   password_mgrrd   rd   re   r     s
   

z!AbstractBasicAuthHandler.__init__c                 C   
   d| _ d S r  r  r   rd   rd   re   reset_retry_count  r$  z*AbstractBasicAuthHandler.reset_retry_countc           
      C   s   | |d }| jdkrt| dd|d |  jd7  _|rc| d }| dkr0td| tj	|}|re|
 \}}}|dvrJtd	td
 | dkrg| |||}	|	ra|	jdkrad| _|	S d S d S d S )N     zbasic auth failedr   r   basiczDAbstractBasicAuthHandler does not support the following scheme: '%s')"'zBasic Auth Realm was unquotedr  )r   r  r   r   splitr   rS   r5   rxsearchgroupsr   r   UserWarningretry_http_basic_authr*  )
r   authreqr   r  r   rI  mor   ry  r   rd   rd   re   http_error_auth_reqed  s6   
z.AbstractBasicAuthHandler.http_error_auth_reqedc                 C   sz   | j ||\}}|d ur;d||f }dt| d }|j| jd |kr+d S |	| j| | j
j||jdS d S )Nre  rh  rf  rH  )rq  r  rj  rk  rl  r  r   r   auth_headerr   r#  r   r`   )r   r   r  ry  r[  pwrawauthrd   rd   re   r    s   z.AbstractBasicAuthHandler.retry_http_basic_authrf   )r   r   r   recompileIr  r   r  r  r  rd   rd   rd   re   r5     s    
 r5   c                   @      e Zd ZdZdd ZdS )r6   Authorizationc                 C   "   |j }| d|||}|   |S )Nwww-authenticate)r   r  r  )r   r  r   r*  r   r   r^   r   rd   rd   re   http_error_401     z#HTTPBasicAuthHandler.http_error_401N)r   r   r   r  r  rd   rd   rd   re   r6         r6   c                   @   r  )r7   rg  c                 C   r  Nproxy-authenticater   r  r  )r   r  r   r*  r   r   rW  r   rd   rd   re   http_error_407  s   z$ProxyBasicAuthHandler.http_error_407N)r   r   r   r  r  rd   rd   rd   re   r7     r  r7   c                   @   sN   e Zd ZdddZdd Zdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dS )r8   Nc                 C   s4   |d u rt  }|| _| jj| _d| _d| _d | _d S r  )r3   rq  r{  r  nonce_count
last_nonce)r   rq  rd   rd   re   r     s   

z"AbstractDigestAuthHandler.__init__c                 C   r  r  r  r   rd   rd   re   r    r$  z+AbstractDigestAuthHandler.reset_retry_countc                 C   s~   | |d }| jdkrt|jdd|d |  jd7  _|r;| d }| dkr/| ||S | dkr=td| d S d S )	Nr  r  zdigest auth failedr   r   digestr  zEAbstractDigestAuthHandler does not support the following scheme: '%s')r   r  r   r   r  r   retry_http_digest_authrS   )r   r  r   r  r   r  rI  rd   rd   re   r    s    

z/AbstractDigestAuthHandler.http_error_auth_reqedc                 C   sz   | dd\}}ttd t|}| ||}|r;d| }|j| jd |kr)d S || j| | j	j
||jd}|S d S )Nr6  r   z	Digest %srH  )r  parse_keqv_listr   parse_http_listget_authorizationr   r   r  r   r#  r   r`   )r   r  r  token	challengechalauth_valresprd   rd   re   r  (  s   z0AbstractDigestAuthHandler.retry_http_digest_authc                 C   s@   d| j |t f }|dtd }t| }|d d S )Nz	%s:%s:%s:rf        )r  timectimerl  _randombyteshashlibsha1	hexdigest)r   noncesbdigrd   rd   re   
get_cnonce4  s   z$AbstractDigestAuthHandler.get_cnoncec                 C   s  z|d }|d }| d}| dd}| dd }W n
 ty%   Y d S w | |\}}	|d u r3d S | j||j\}
}|
d u rCd S |jd urP| |j|}nd }d|
||f }d| |j	f }|d	kr|| j
krs|  jd
7  _nd
| _|| _
d| j }| |}d||||||f }|	|||}n|d u r|	||d|||f }ntd| d|
|||j	|f }|r|d| 7 }|r|d| 7 }|d| 7 }|r|d||f 7 }|S )Nry  r  qop	algorithmMD5opaquez%s:%s:%sre  r  r   z%08xz%s:%s:%s:%s:%szqop '%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")r   KeyErrorget_algorithm_implsrq  r  r   r_   get_entity_digestr   r   r  r  r  r   )r   r  r  ry  r  r  r  r  HKDr[  r  entdigA1A2ncvaluecnoncenoncebitrespdigr  rd   rd   re   r  ?  s^   





z+AbstractDigestAuthHandler.get_authorizationc                    s6   |dkr	dd  n|dkrdd   fdd} |fS )Nr  c                 S      t | d S Nrf  )r  md5rl  r  xrd   rd   re   rb  ~      z?AbstractDigestAuthHandler.get_algorithm_impls.<locals>.<lambda>SHAc                 S   r  r  )r  r  rl  r  r  rd   rd   re   rb    r  c                    s    d| |f S )Nre  rd   )r  dr  rd   re   rb    s    rd   )r   r  r  rd   r  re   r  {  s   
z-AbstractDigestAuthHandler.get_algorithm_implsc                 C   r   rf   rd   )r   r_   r  rd   rd   re   r    r   z+AbstractDigestAuthHandler.get_entity_digestrf   )r   r   r   r   r  r  r  r  r  r  r  rd   rd   rd   re   r8     s    
	<
r8   c                   @   s    e Zd ZdZdZdZdd ZdS )r9   zAn authentication protocol defined by RFC 2069

    Digest authentication improves on basic authentication because it
    does not transmit passwords in the clear.
    r    c                 C   s*   t |jd }| d|||}|   |S )Nr   r  )r   r   r  r  r   r  r   r*  r   r   r   retryrd   rd   re   r    s   z$HTTPDigestAuthHandler.http_error_401N)r   r   r   r,  r  r%  r  rd   rd   rd   re   r9     s
    r9   c                   @   s   e Zd ZdZdZdd ZdS )r:   Proxy-Authorizationr  c                 C   r  r  r  r  rd   rd   re   r    r  z%ProxyDigestAuthHandler.http_error_407N)r   r   r   r  r%  r  rd   rd   rd   re   r:     s    r:   c                   @   s.   e Zd ZdddZdd Zdd Zdd	 Zd
S )AbstractHTTPHandlerr   c                 C   r"  rf   _debuglevel)r   
debuglevelrd   rd   re   r     r$  zAbstractHTTPHandler.__init__c                 C   r"  rf   r  )r   levelrd   rd   re   set_http_debuglevel  r$  z'AbstractHTTPHandler.set_http_debuglevelc                 C   sH  |j }|s	td|jd url|j}t|trd}t||ds'|dd |dsld }ztr?t|t	j	r?t
||j }nt|}t
||j }W n tyc   t|tratdt||f Y n	w |dd|  |}| rt|j\}}	t|	\}}
|ds|d| | jjD ]\}}| }||s||| q|S )	Nno host givenzLPOST data should be bytes or an iterable of bytes. It cannot be of type str.zContent-type!application/x-www-form-urlencodedzContent-lengthzBContent-Length should be specified for iterable data of type %r %rz%dr   )r   r   r_   r   r   r   r   r   r   arrayr{   itemsize
memoryviewr*   rS   r   r   r   r   r   r#  r   r   )r   r   r   r_   r   r   mvsel_hostrI  selsel_pathrw   r   rd   rd   re   do_request_  sZ   






zAbstractHTTPHandler.do_request_c           
   
      s&  |j }|s	td||fd|ji|}t|j  t fdd|j D  d d< tdd   D  |jrUi }d}| v rM | ||<  |= |j	|j|d	 z|
| |j|j  W n tjyx } z|  t|d
}~ww | }	|jr|j  d
|_| |	_|	j|	_|	S )zReturn an HTTPResponse object for the request, using http_class.

        http_class must implement the HTTPConnection API from http.client.
        r  r`   c                 3   s$    | ]\}}| vr||fV  qd S rf   rd   r7  r   rd   re   r=    s   
 z.AbstractHTTPHandler.do_open.<locals>.<genexpr>r   
Connectionc                 s   s     | ]\}}|  |fV  qd S rf   )title)r8  rw   r   rd   rd   re   r=    s    r  r  N)r   r   r`   r   r   r   r   r   r   
set_tunnelr   r   r   r_   r  r   r   getresponsesockr   r^   reasonr   )
r   
http_classr  http_conn_argsr   r   tunnel_headersproxy_auth_hdrerrra  rd   r  re   r     s:   
"

zAbstractHTTPHandler.do_openNr   )r   r   r   r   r  r  r   rd   rd   rd   re   r    s
    
3r  c                   @   s   e Zd Zdd ZejZdS )r;   c                 C   s   |  tj|S rf   )r   r  HTTPConnectionr   r  rd   rd   re   	http_open$  s   zHTTPHandler.http_openN)r   r   r   r  r  r  http_requestrd   rd   rd   re   r;   "  s    
r;   r  c                   @   s$   e Zd ZdddZdd ZejZdS )r\   r   Nc                 C   s   t | | || _|| _d S rf   )r  r   _context_check_hostname)r   r  rP   rQ   rd   rd   re   r   -  s   
zHTTPSHandler.__init__c                 C   s   | j tj|| j| jdS )NrO   )r   r  r  r
  r  r  rd   rd   re   
https_open2  s   
zHTTPSHandler.https_open)r   NN)r   r   r   r   r  r  r  https_requestrd   rd   rd   re   r\   +  s    

r\   c                   @   s.   e Zd ZdddZdd Zdd ZeZeZdS )	r1   Nc                 C   s2   dd l m  m  m} |d u r| }|| _d S r  )future.backports.http.cookiejar	backportsr
  	cookiejar	CookieJar)r   r  http_cookiejarrd   rd   re   r   ;  s   
zHTTPCookieProcessor.__init__c                 C   s   | j | |S rf   )r  add_cookie_header)r   r   rd   rd   re   r	  A  s   z HTTPCookieProcessor.http_requestc                 C   s   | j || |S rf   )r  extract_cookies)r   r   r   rd   rd   re   r+  E  s   z!HTTPCookieProcessor.http_responserf   )r   r   r   r   r	  r+  r  r-  rd   rd   rd   re   r1   :  s    
r1   c                   @   r.  )r?   c                 C   s   |j }td| )Nzunknown url type: %s)r   r   )r   r  r   rd   rd   re   r  M  s   zUnknownHandler.unknown_openN)r   r   r   r  rd   rd   rd   re   r?   L  r/  r?   c                 C   sN   i }| D ] }| dd\}}|d dkr |d dkr |dd }|||< q|S )z>Parse list of key=value strings where keys are not duplicated.=r   r   r  rk   )r  )lparsedeltr9  r:  rd   rd   re   r  Q  s   
r  c                 C   s   g }d}d }}| D ]5}|r||7 }d}q
|r)|dkrd}q
|dkr$d}||7 }q
|dkr5| | d}q
|dkr;d}||7 }q
|rG| | dd |D S )	ap  Parse 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.
    r   F\Tr  ,c                 S      g | ]}|  qS rd   strip)r8  partrd   rd   re   rw    r  z#parse_http_list.<locals>.<listcomp>)ry   )r  resr  escaper   currd   rd   re   r  [  s4   	


r  c                   @   s(   e Zd Zdd ZdZdd Zdd ZdS )r<   c                 C   sZ   |j }|d d dkr(|dd dkr(|jr(|jdkr(|j|  ur&tdd S | |S )Nr  rT  rK   rF  	localhost-file:// scheme is supported only on localhost)r   r   	get_namesr   open_local_file)r   r  r^   rd   rd   re   	file_open  s   &

zFileHandler.file_openNc                 C   sf   t jd u r0zttdd tt d  t _W t jS  tjy/   tdft _Y t jS w t jS )Nr"  r  )r<   namesrx  r  gethostbyname_exgethostnamegaierrorgethostbynamer   rd   rd   re   r$    s   
zFileHandler.get_namesc              
   C   s  dd l m  m  m} dd l}|j}|j}t|}zXt	|}|j
}|j|jdd}	||d }
td|
p8d||	f }|rFt|\}}|rR|sit||  v rn|r[d| | }nd| }tt|d||W S W tdW td ty } zt|d }~ww )	Nr   Tusegmtz6Content-type: %s
Content-length: %d
Last-modified: %s

text/plainfile://rbzfile not on local host)future.backports.email.utilsr  r   utils	mimetypesr   r   rE   rr   statst_size
formatdatest_mtime
guess_typemessage_from_stringr   _safe_gethostbynamer$  r(   r   OSErrorr   )r   r  email_utilsr3  r   r}   	localfilestatsr   modifiedmtyper   r  origurlexprd   rd   re   r%    sB   

	zFileHandler.open_local_file)r   r   r   r&  r'  r$  r%  rd   rd   rd   re   r<     s
    
r<   c                 C   s$   zt | W S  t jy   Y d S w rf   )r  r+  r*  r   rd   rd   re   r:    s
   r:  c                   @   s   e Zd Zdd Zdd ZdS )r=   c              
   C   s  dd l }dd l}|j}|stdt|\}}|d u r|j}nt|}t|\}}|r2t|\}}nd }t	|}|p;d}|p?d}zt
|}W n t
jyX } zt|d }~ww t|j\}	}
|	d}ttt	|}|d d |d }}|r|d s|dd  }z_| ||||||j}|rdpd}|
D ]}t|\}}| d	kr|d
v r| }q|||\}}d}||jd }|r|d| 7 }|d ur|dkr|d| 7 }t|}t|||jW S  |jy } ztd| }t| W Y d }~d S d }~ww )Nr   ftp error: no host givenr   rF  rk   r   r  Dr   aAr   r  r  rE  zContent-type: %s
zContent-length: %d
ftp error: %r)ftplibr3  r   r   r   FTP_PORTr
   r    r!   r   r  r+  r   r"   r   r  r   r   connect_ftpr`   r$   r   upperretrfiler8  r   r   r9  r(   
all_errorsr   )r   r  rJ  r3  r   r  r[  rq  r   rs   attrsdirsrg   fwr   attrr   r   retrlenr   r@  rB  excrd   rd   re   ftp_open  sf   

zFTPHandler.ftp_openc              	   C   s   t ||||||ddS )NF)
persistent)
ftpwrapper)r   r[  rq  r   r  rQ  r`   rd   rd   re   rL    s   zFTPHandler.connect_ftpN)r   r   r   rV  rL  rd   rd   rd   re   r=     s    5r=   c                   @   s<   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd ZdS )r>   c                 C   s"   i | _ i | _d| _d| _d| _d S )Nr   <   r  )cacher`   soonestdelay	max_connsr   rd   rd   re   r     s
   
zCacheFTPHandler.__init__c                 C   r"  rf   )r\  )r   trd   rd   re   
setTimeout  r$  zCacheFTPHandler.setTimeoutc                 C   r"  rf   )r]  )r   r@  rd   rd   re   setMaxConns  r$  zCacheFTPHandler.setMaxConnsc                 C   sr   |||d ||f}|| jv rt | j | j|< nt||||||| j|< t | j | j|< |   | j| S )NrF  )joinrZ  r  r\  r`   rX  check_cache)r   r[  rq  r   r  rQ  r`   r   rd   rd   re   rL  
  s   



zCacheFTPHandler.connect_ftpc                 C   s   t   }| j|kr(t| j D ]\}}||k r'| j|   | j|= | j|= qtt| j | _t	| j| j
krat| j D ]\}}|| jkrT| j|= | j|=  nqAtt| j | _d S d S rf   )r  r[  r   r`   r   rZ  r   minvaluesr{   r]  )r   r^  r9  r:  rd   rd   re   rb    s$   

zCacheFTPHandler.check_cachec                 C   s0   | j  D ]}|  q| j   | j  d S rf   )rZ  rd  r   clearr`   )r   connrd   rd   re   clear_cache)  s   

zCacheFTPHandler.clear_cacheN)	r   r   r   r   r_  r`  rL  rb  rg  rd   rd   rd   re   r>     s    r>   r1  nt)rE   rD   c                 C      t | S )zOS-specific conversion from a relative URL of the 'file' scheme
        to a file system path; not recommended for general use.)r   pathnamerd   rd   re   rE   8     rE   c                 C   ri  )zOS-specific conversion from a file system path to a relative URL
        of the 'file' scheme; not recommended for general use.)r   rj  rd   rd   re   rD   =  rl  rD   c                   @   s   e Zd ZdZdZde Zd*ddZdd Zdd	 Z	d
d Z
dd Zd*ddZd*ddZd*ddZd+ddZdd Zd*ddZd*ddZdd ZerRdd Zd*d d!Zd"d# Zd$d% Zd&d' Zd*d(d)ZdS ),rI   a,  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).Nr   c                 K   s   dd| j ji }tj|tdd |d u rt }t|ds J d|| _|d| _	|d| _
d	| jfg| _g | _tj| _d | _t| _d S )
NzW%(class)s style of invoking requests is deprecated. Use newer urlopen functions/methodsclassrK   r   r_  r`  key_file	cert_filez
User-Agent)	__class__r   r   r   r   rF   r   rc  r   rn  ro  versionr   _URLopener__tempfilesrr   r   _URLopener__unlink	tempcacheftpcache)r   rc  x509r   rd   rd   re   r   W  s   

zURLopener.__init__c                 C      |    d S rf   )r   r   rd   rd   re   __del__q  r   zURLopener.__del__c                 C   rw  rf   )cleanupr   rd   rd   re   r   t  r   zURLopener.closec              	   C   sV   | j r| j D ]}z| | W q ty   Y qw | j d d = | jr)| j  d S d S rf   )rr  rs  r;  rt  re  )r   rg   rd   rd   re   ry  w  s   
zURLopener.cleanupc                 G   s   | j | dS )zdAdd a header to be used by the HTTP interface only
        e.g. u.addheader('Accept', 'sound/basic')N)r   ry   )r   r   rd   rd   re   	addheader  s   zURLopener.addheaderc              
   C   sL  t t|}t|dd}| jr&|| jv r&| j| \}}t|d}t|||S t|\}}|s0d}|| jv rK| j| }t|\}}	t|	\}
}|
|f}nd}d| }|| _	|
dd}t| |sn|rh| |||S | ||S z|du r{t| ||W S t| |||W S  ty     tjy } zttd	| W Y d}~dS d}~ww )
z6Use URLopener().open(file) instead of open(file, 'r').z%/:=&?~#+!$,;'@()*[]|safer0  rg   Nopen_-r   zsocket error)r   r&   r   rt  r   r(   r   rc  r   r   r>  r   open_unknown_proxyopen_unknownr   r   r  r   r   IOError)r   r  r_   r}   r   r   urltyper^   rU  	proxyhostr   r   rw   r   rd   rd   re   r     s@   




zURLopener.openc                 C   s   t |\}}tdd|)/Overridable interface to open unknown URL type.	url errorzunknown url typer   r  )r   r  r_   r   r^   rd   rd   re   r    s   zURLopener.open_unknownc                 C   s   t |\}}tdd| |)r  r  zinvalid proxy for %sr  )r   rU  r  r_   r   r^   rd   rd   re   r    s   zURLopener.open_unknown_proxyc              
   C   s&  t t|}| jr|| jv r| j| S t|\}}|du rN|r#|dkrNz| |}| }|  tt|d |fW S  t	yM }	 zW Y d}	~	nd}	~	ww | 
||}z| }
|rat
|d}n=ddl}t|\}}t|pod\}}t|pwd\}}t|pd\}}tj|d }||\}}| j| t|d}zO||
f}| jdur|| j|< d}d}d}d}d	|
v rt|
d
 }|r|||| 	 ||}|sn|t|7 }|| |d7 }|r|||| qW |  n|  w W |  n|  w |dkr||k rtd||f ||S )ztretrieve(url) returns (filename, headers) for a local object
        or (tempfilename, headers) for a remote object.Nrg   r   rh   r   r   rj   rk   rl   rm   rn   )r   r&   rt  r   r%  rq   r   rE   r   r  r   ru   r#   r"   rr   rs   splitextmkstemprr  ry   fdopenr
   rz   r{   r|   r   )r   r^   r}   r~   r_   r   url1r   r   r   r   r   ru   garbagers   suffixfdr   r   r   rz   r   r   rd   rd   re   retrieve  sz   





zURLopener.retrievec                 C   s  d}d}t |trt|\}}|rt|\}}t|}|}n:|\}}t|\}}t|\}	}
|
}d}|	 dkr;d}nt|
\}}
|rIt|\}}|rRd|	||
f }t|rX|}|s_tdd|rpt|}t	
| d}nd}|rt|}t	
| d}nd}||}i }|rd| |d< |rd| |d	< |r||d
< d|d< | jD ]\}}|||< q|durd|d< |d||| n|jd||d z| }W n tjy   tdw d|j  krdk rn nt||jd| |jS | ||j|j|j|j|S )a  Make 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.
        Nr
  z	%s://%s%sz
http errorr  rf  zBasic %sr  r  r   r   r  r  zContent-Typer   r   r  z$http protocol error: bad status liner(  r)  http:)r   r   r   r    r   r   r   ri  r  rj  rk  rl  r  r   r   r  r  BadStatusLiner   statusr(   r   
http_errorr   r  )r   connection_factoryr^   r_   user_passwdproxy_passwdr   r   realhostr  r   
proxy_authr  	http_connr   headerr   r   rd   rd   re   _open_generic_http  sv   

zURLopener._open_generic_httpc                 C   s   |  tj||S )zUse HTTP protocol.)r  r  r  r   r^   r_   rd   rd   re   	open_httpX     zURLopener.open_httpc           
      C   sb   d| }t | |r(t| |}|du r||||||}	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)r   r   r  )
r   r^   r   errcodeerrmsgr   r_   rw   r   r   rd   rd   re   r  \  s   

zURLopener.http_errorc                 C   s   |   t||||d)z>Default error handler: close the connection and raise IOError.N)r   r   r   r^   r   r  r  r   rd   rd   re   r  l  s   zURLopener.http_error_defaultc                 C   s   t j|| j| jdS )N)rn  ro  )r  r  rn  ro  )r   r   rd   rd   re   _https_connectionr  s   zURLopener._https_connectionc                 C   s   |  | j||S )zUse HTTPS protocol.)r  r  r  rd   rd   re   
open_httpsw  r  zURLopener.open_httpsc                 C   sX   t |ts	td|dd dkr'|dd dkr'|dd  dkr'td	| |S )
z/Use local file or FTP depending on form of URL.zEfile error: proxy support for file protocol currently not implementedNr  rT  rK   rF     z
localhost/r#  )r   r   r   r   rS   r%  )r   r^   rd   rd   re   	open_file{  s
   
4
zURLopener.open_filec              
   C   sT  ddl m  m  m} ddl}t|\}}t|}zt|}W n t	y4 } zt
|j|jd}~ww |j}	|j|jdd}
||d }td|pMd|	|
f }|sl|}|dd dkrcd	| }tt|d
||S t|\}}|st|t ft  v r|}|dd dkrd	| }n|dd dkrtd| tt|d
||S t
d)zUse local file.r   NTr,  z6Content-Type: %s
Content-Length: %d
Last-modified: %s
r.  r   rF  r/  r0  r  z./zAlocal file url may start with / or file:. Unknown url of type: %sz#local file error: not on local host)r1  r  r   r2  r3  r   rE   rr   r4  r;  r   strerrorr}   r5  r6  r7  r8  r9  r(   r   r   r  r+  r"  thishostrS   )r   r^   r<  r3  r   rg   	localnamer>  er   r?  r@  r   urlfiler  rd   rd   re   r%    sB   
zURLopener.open_local_filec              
   C   sl  t |ts	tdddl}t|\}}|stdt|\}}t|\}}|r.t|\}}nd}t|}t|p8d}t|p>d}t	
|}|sOddl}|j}nt|}t|\}}	t|}|d}
|
dd |
d }
}|
ry|
d sy|
dd }
|
r|
d sd|
d< |||d|
f}t| jtkr| j D ]}||kr| j| }| j|= |  qzl|| jvrt|||||
| j|< |sd	}nd
}|	D ]}t|\}}| dkr|dv r| }q| j| ||\}}|d| d }d}|r|d| 7 }|dur|dkr|d| 7 }t|}t||d| W S  t y5 } zt td|  W Y d}~dS d}~ww )zUse FTP protocol.zCftp error: proxy support for ftp protocol currently not implementedr   NrD  r   rF  rk   r   rE  r  r   rF  zftp:zContent-Type: %s
zContent-Length: %d
zftp error %r)!r   r   r   r3  r   r   r    r!   r   r  r+  rJ  rK  r
   r"   r  ra  r{   ru  MAXFTPCACHEr_  r   rX  r$   r   rM  rN  r8  r   r9  r(   	ftperrorsr   )r   r^   r3  r   rs   r  r[  rq  rJ  rP  rQ  rg   r   r9  r:  r   rS  r   r   rT  r@  r   rB  rd   rd   re   open_ftp  sp   






zURLopener.open_ftpc           	   
   C   s6  t |ts	tdz
|dd\}}W n ty   tddw |s$d}|d}|dkrDd	||d
 vrD||d d
 }|d
| }nd}g }|dt	dt
t   |d|  |dkrot|dd}nt|}|dt|  |d || d|}t|}t|}t|||S )zUse "data" URL.zEdata error: proxy support for data protocol currently not implementedr  r   z
data errorzbad data URLztext/plain;charset=US-ASCII;r   r  Nr   zDate: %sz%a, %d %b %Y %H:%M:%S GMTzContent-type: %srj  rf  zlatin-1zContent-Length: %d
)r   r   r   r  rS   r  rfindry   r  strftimegmtimerj  decodebytesrl  r  r   r{   ra  r   r9  ioStringIOr(   )	r   r^   r_   r   semiencodingr   r   frd   rd   re   	open_data  s:   







zURLopener.open_datarf   NNN)r   r   r   r,  rr  r   rq  r   rx  r   ry  rz  r   r  r  r  r  r  r  r  rR   r  r  r  r%  r  r  rd   rd   rd   re   rI   J  s0    


$

B
\

	 :rI   c                   @   s   e Zd ZdZdd Zdd Zd#ddZd	d
 Zd#ddZd#ddZ	d#ddZ
		d$ddZ		d$ddZd#ddZd#ddZd#ddZd#ddZd%dd Zd!d" ZdS )&rJ   z?Derived class with handlers for errors we can handle (perhaps).c                 O   s.   t j| g|R i | i | _d| _d| _d S )Nr   r1  )rI   r   
auth_cachetriesmaxtries)r   r   kwargsrd   rd   re   r     s   
zFancyURLopener.__init__c                 C   s   t ||d| |S )z3Default error handling -- don't raise an exception.r  )r(   r  rd   rd   re   r    r   z!FancyURLopener.http_error_defaultNc           	      C   sl   |  j d7  _ | jr'| j | jkr't| dr| j}n| j}d| _ |||dd|S | ||||||}d| _ |S )z%Error 302 -- relocated (temporarily).r   http_error_500r   r!  z)Internal Server Error: Redirect Recursion)r  r  r   r  r  redirect_internal)	r   r^   r   r  r  r   r_   r   r   rd   rd   re   rP    s   
zFancyURLopener.http_error_302c           	      C   sx   d|v r	|d }nd|v r|d }nd S |   t| jd | |}t|}|jdvr7t|||d|  ||| |S )NrB  rC  :rD  z( Redirection to url '%s' is not allowed.)r   r   r   r   rI  r   r   )	r   r^   r   r  r  r   r_   r?  rM  rd   rd   re   r  %  s    



z FancyURLopener.redirect_internalc                 C      |  ||||||S )z*Error 301 -- also relocated (permanently).rP  r   r^   r   r  r  r   r_   rd   rd   re   rQ  A     zFancyURLopener.http_error_301c                 C   r  )z;Error 303 -- also relocated (essentially identical to 302).r  r  rd   rd   re   rR  E  r  zFancyURLopener.http_error_303c                 C   s.   |du r|  ||||||S | |||||S )z1Error 307 -- relocated, but turn POST into error.N)rP  r  r  rd   rd   re   rS  I  s   zFancyURLopener.http_error_307Fc                 C      d|vrt | ||||| |d }td|}	|	s$t | ||||| |	 \}
}|
 dkr:t | ||||| |sFt | ||||| d| j d }|du rYt| |||S t| ||||S )z_Error 401 -- authentication required.
        This function supports Basic authentication only.r  ![ 	]*([^ 	]+)[ 	]+realm="([^"]*)"r  retry__basic_authNrI   r  r  matchr  r   r   r   r   r^   r   r  r  r   r_   r  stuffr  rI  ry  rw   rd   rd   re   r  P  .   


zFancyURLopener.http_error_401c                 C   r  )zeError 407 -- proxy authentication required.
        This function supports Basic authentication only.r  r  r  retry_proxy_r  Nr  r  rd   rd   re   r  i  r  zFancyURLopener.http_error_407c                 C      t |\}}d| | }| jd }t|\}}	t |	\}	}
|	dd }|	|d  }	| |	||\}}|s9|s9d S dt|ddt|dd|	f }	d|	 |
 | jd< |d u rZ| |S | ||S )Nhttp://r
  @r   %s:%s@%sr   r{  r   rc  r   r   get_user_passwdr   r   r   r^   ry  r_   r   r   r?  rU  r  r  proxyselectorr   r[  rq  rd   rd   re   retry_proxy_http_basic_auth      

z*FancyURLopener.retry_proxy_http_basic_authc                 C   r  )Nhttps://r   r  r   r  r   r{  r  r  rd   rd   re   retry_proxy_https_basic_auth  r  z+FancyURLopener.retry_proxy_https_basic_authc           
      C      t |\}}|dd }||d  }| |||\}}|s"|s"d S dt|ddt|dd|f }d| | }	|d u r@| |	S | |	|S )Nr  r   r  r   r{  r  r   r   r  r   r   
r   r^   ry  r_   r   r   r   r[  rq  r?  rd   rd   re   r       
z$FancyURLopener.retry_http_basic_authc           
      C   r  )Nr  r   r  r   r{  r  r  r  rd   rd   re   retry_https_basic_auth  r  z%FancyURLopener.retry_https_basic_authr   c                 C   s`   |d |   }|| jv r|r| j|= n| j| S | ||\}}|s%|r,||f| j|< ||fS )Nr  )r   r  prompt_user_passwd)r   r   ry  rg  r   r[  rq  rd   rd   re   r    s   


zFancyURLopener.get_user_passwdc                 C   sR   ddl }ztd||f }| d|||f }||fW S  ty(   t  Y dS w )z#Override this in a GUI environment!r   NzEnter username for %s at %s: z#Enter password for %s in %s at %s: r|  )getpassr	   KeyboardInterruptprint)r   r   ry  r  r[  rq  rd   rd   re   r    s   
z!FancyURLopener.prompt_user_passwdrf   )NFr  )r   r   r   r,  r   r  rP  r  rQ  rR  rS  r  r  r  r  r  r  r  r  rd   rd   rd   re   rJ     s*    










rJ   c                   C      t du r	tda t S )z8Return the IP address of the magic hostname 'localhost'.Nr"  )
_localhostr  r+  rd   rd   rd   re   r"       
r"  c                   C   sR   t du r'zttt d a W t S  tjy&   ttdd a Y t S w t S )z,Return the IP addresses of the current host.Nr  r"  )	_thishostrx  r  r(  r)  r*  rd   rd   rd   re   r    s   r  c                  C   s   t du rddl} | ja t S )z1Return the set of errors raised by the FTP class.Nr   )
_ftperrorsrJ  rO  )rJ  rd   rd   re   r    s   r  c                   C   r  )z%Return an empty email Message object.Nr   )
_noheadersr   r9  rd   rd   rd   re   	noheaders  r  r  c                   @   sN   e Zd ZdZ		dddZdd Zdd	 Zd
d Zdd Zdd Z	dd Z
dS )rX  z;Class used by open_ftp() for cache of open FTP connections.NTc                 C   s<   || _ || _|| _|| _|| _|| _d| _|| _|   d S r  )	r[  rq  r   r  rQ  r`   refcount	keepaliveinit)r   r[  rq  r   r  rQ  r`   rW  rd   rd   re   r   	  s   zftpwrapper.__init__c                 C   s\   dd l }d| _| | _| j| j| j| j | j| j	| j
 d| j}| j| d S )Nr   rF  )rJ  busyFTPrE  connectr   r  r`   loginr[  rq  ra  rQ  cwd)r   rJ  _targetrd   rd   re   r  	  s   
zftpwrapper.initc              
   C   s  dd l }|   |dv rd}d}nd| }d}z| j| W n |jy3   |   | j| Y nw d }|rn|snzd| }| j|\}}W n% |jym } zt|d d dkrct	t
d	|  W Y d }~nd }~ww |s| jd |r| j }	z)z| j| W n |jy } zt
d	| }
||
_|
d }~ww W | j|	 n| j|	 w d
| }nd}| j|\}}d| _t|d| j}|  jd7  _|  ||fS )Nr   )r  rE  zTYPE Ar   zTYPE zRETR rK   550rI  zLIST LISTr0  )rJ  endtransferrE  voidcmdrO  r  ntransfercmd
error_permr   r   r   pwdr  	__cause__r  r)   makefile
file_closer  r   )r   rg   r   rJ  cmdisdirrf  rT  r  r  rU  ftpobjrd   rd   re   rN  	  sV   

zftpwrapper.retrfilec                 C   r  r  )r  r   rd   rd   re   r  K	  r$  zftpwrapper.endtransferc                 C   s    d| _ | jdkr|   d S d S )NFr   )r  r  
real_closer   rd   rd   re   r   N	  s   
zftpwrapper.closec                 C   s:   |    |  jd8  _| jdkr| js|   d S d S d S )Nr   r   )r  r  r  r  r   rd   rd   re   r  S	  s
   zftpwrapper.file_closec                 C   s0   |    z| j  W d S  t y   Y d S w rf   )r  rE  r   r  r   rd   rd   re   r  Y	  s   zftpwrapper.real_close)NT)r   r   r   r,  r   r  rN  r  r   r  r  rd   rd   rd   re   rX  	  s    
	0rX  c                  C   sH   i } t j D ]\}}| }|r!|dd dkr!|| |dd < q| S )a  Return a dictionary of scheme -> proxy server URL mappings.

    Scan the environment for variables named <scheme>_proxy;
    this seems to be the standard convention.  If you need a
    different way, you can pass a proxies dictionary to the
    [Fancy]URLopener constructor.

    iN_proxy)rr   environr   r   )rc  rw   r   rd   rd   re   getproxies_environmenta	  s   	r  c                 C   st   t jddpt jdd}|dkrdS t| \}}dd |dD }|D ]}|r7||s4| |r7 dS q&d	S )
zTest if proxies should not be used for a particular host.

    Checks the environment for a variable named no_proxy, which should
    be a list of DNS suffixes separated by commas, or '*' for all hosts.
    no_proxyr   NO_PROXY*r   c                 S   r  rd   r  )r8  rU  rd   rd   re   rw  ~	  r  z,proxy_bypass_environment.<locals>.<listcomp>r  r   )rr   r  r   r   r  endswith)r   r  hostonlyr  no_proxy_listrw   rd   rd   re   proxy_bypass_environmentq	  s   r  c              	   C   s  ddl m } t| \}}dd }d| vr|d rdS d}|d	d
D ]f}|s'q"td|}|dur|du rKzt|}||}W n
 tjyJ   Y q"w ||d}	|d}
|
du rhd|d	dd  }
nt
|
dd }
d|
 }
||
? |	|
? kr dS q"|| |r dS q"dS )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   )fnmatchc                 S   sd   |  d}ttt|}t|dkr|g d d d }|d d> |d d> B |d d	> B |d
 B S )N.r0  )r   r   r   r   r      r   r  r  r  rK   )r  r   r   r
   r{   )ipAddrr  rd   rd   re   ip2num	  s
   
,z,_proxy_bypass_macosx_sysconf.<locals>.ip2numr  exclude_simpleTN
exceptionsrd   z(\d+(?:\.\d+)*)(/\d+)?r   r  r      F)r  r   r   r  r  r  r+  r   groupcountr
   )r   proxy_settingsr  r	  r  r  hostIPr   r@  r  maskrd   rd   re   _proxy_bypass_macosx_sysconf	  s>   


r  darwin)_get_proxy_settings_get_proxiesc                 C   s   t  }t| |S rf   )r  r  )r   r  rd   rd   re   proxy_bypass_macosx_sysconf	  s   
r  c                   C   s   t  S )zReturn a dictionary of scheme -> proxy server URL mappings.

        This function uses the MacOSX framework SystemConfiguration
        to fetch the proxy information.
        )r  rd   rd   rd   re   getproxies_macosx_sysconf	  s   r  c                 C      t  rt| S t| S rf   )r  r  r  rC  rd   rd   re   ri  	  s   ri  c                   C      t  pt S rf   )r  r  rd   rd   rd   re   rF   	  r   rF   c               
   C   s  i } zddl }W n ty   |  Y S w zf||jd}||dd }|rtt||dd }d|v rU|dD ]}|dd\}}td	|sOd
||f }|| |< q9n|dd dkrb|| d< nd| | d< d| | d< d| | d< |	  W | S  t
ttfy   Y | S w )zxReturn a dictionary of scheme -> proxy server URL mappings.

        Win32 uses the registry to store proxies.

        r   N;Software\Microsoft\Windows\CurrentVersion\Internet SettingsProxyEnableProxyServerr  r  r   z^([^/:]+)://z%s://%sr  r  r
  z	http://%sz
https://%sr   zftp://%srE  )winregImportErrorOpenKeyHKEY_CURRENT_USERQueryValueExr   r  r  r  CloseWindowsErrorrS   r   )rc  r$  internetSettingsproxyEnableproxyServerpr   addressrd   rd   re   getproxies_registry	  sN   


r0  c                   C   r   zReturn a dictionary of scheme -> proxy server URL mappings.

        Returns settings gathered from the environment, if specified,
        or the registry.

        )r  r0  rd   rd   rd   re   rF   
  s   c                 C   sl  zdd l }W n
 ty   Y dS w z||jd}||dd }t||dd }W n
 ty6   Y dS w |r;|s=dS t| \}}|g} zt	|}||krU| 
| W n
 tjy`   Y nw zt|}||krp| 
| W n
 tjy{   Y nw |d}|D ]0}	|	dkrd|vr dS |	dd	}	|	d
d}	|	dd}	| D ]}
t|	|
tjr  dS qqdS )Nr   r!  r"  ProxyOverrider  z<local>r  r   z\.r  z.*?)r$  r%  r&  r'  r(  r   r*  r   r  r+  ry   r   getfqdnr  r>  r  r  r  )r   r$  r+  r,  proxyOverriderawHostr  addrfqdnr  r   rd   rd   re   proxy_bypass_registry
  sp   





r9  c                 C   r  r1  )r  r  r9  rC  rd   rd   re   ri  H
  s   r  )r,  
__future__r   r   r   r   future.builtinsr   r   r   r	   r
   r   r   r   future.utilsr   r   r   rj  r   r  r  future.backportsr   future.backports.httpr   r  r   r   r   r   parser   r   r   r   r   r   r   r   r   r    r!   r"   r#   r$   r%   r&   r'   r   r(   r)   r  rr   r  r  r  sysr  ru   ro   r   collectionsr*   collections.abcrT   r+   r%  rR   __all__rq  r   r]   r  rA   rB   rx   rG   rH   r  ASCIIr   r   objectr,   r-   rC   r.   r@   r/   r0   r]  r2   r3   r4   r5   r6   r7   urandomr  r8   r9   r:   r  r;   r   r\   ry   r1   r?   r  r  r<   r:  r=   r>   r  rw   
nturl2pathrE   rD   ru  rI   rJ   r  r"  r  r  r  r  r  r  rX  r  r  r  platform_scproxyr  r  r  r  ri  rF   r0  r9  rd   rd   rd   re   <module>   s    V(L
?
y &hH*@
E z

+4:8   A U

^<
-	2