a oe]@s&ddlmZddlZddlZddlZddlZddlZddlZddlmZ ddlm Z ddl m Z ddlmZmZmZmZmZmZmZmZddlmZmZmZmZmZmZmZmZm Z m!Z!m"Z"m#Z#m$Z$dd l%m&Z&dd l'm(Z(dd l)m*Z*dd l+m,Z,dd l-m.Z.ddl/m0Z0ddl1m2Z2ddl3m4Z4ddl5m6Z6ddl7m8Z8ddl9m:Z:ddl;mZ>m?Z?ddl=m@ZAddl=mBZBmCZCzddlDZDeDjEZFWn eGyddlHmFZFYn0e&jIjJZJeKeLZMeNZOGdddeNZPejQejRhZSGdddePe*ZTGdddeTZUdd ZVd!d"Z@d#d$ZWdS)%)absolute_importN)errortimeout)HTTPHeaderDict) BaseSSLErrorBrokenPipeErrorDummyConnectionHTTPConnection HTTPExceptionHTTPSConnectionVerifiedHTTPSConnectionport_by_scheme) ClosedPoolErrorEmptyPoolErrorHeaderParsingErrorHostChangedErrorInsecureRequestWarningLocationValueError MaxRetryErrorNewConnectionError ProtocolError ProxyErrorReadTimeoutErrorSSLError TimeoutError)six)queue)RequestMethods) HTTPResponse)is_connection_dropped)connection_requires_http_tunnel) LifoQueue)set_file_position)assert_header_parsing)Retry)CertificateError)Timeout)Url_encode_target)_normalize_host)get_host parse_url)weakref_finalizec@sBeZdZdZdZeZd ddZddZddZ d d Z d d Z dS)ConnectionPoola; Base class for all connection pools, such as :class:`.HTTPConnectionPool` and :class:`.HTTPSConnectionPool`. .. note:: ConnectionPool.urlopen() does not normalize or percent-encode target URIs which is useful if your target server doesn't support percent-encoded target URIs. NcCs0|s tdt||jd|_||_||_dS)NzNo host specified.scheme)rr+r1hostlower _proxy_hostport)selfr2r5r77C:\Program Files\Certbot\pkgs\urllib3\connectionpool.py__init__Ss  zConnectionPool.__init__cCsdt|j|j|jfS)Nz%s(host=%r, port=%r))type__name__r2r5r6r7r7r8__str__[szConnectionPool.__str__cCs|SNr7r<r7r7r8 __enter__^szConnectionPool.__enter__cCs |dS)NF)close)r6exc_typeZexc_valZexc_tbr7r7r8__exit__aszConnectionPool.__exit__cCsdSzD Close all pooled connections and disable the pool. Nr7r<r7r7r8r@fszConnectionPool.close)N) r; __module__ __qualname____doc__r1r#QueueClsr9r=r?rBr@r7r7r7r8r/Es  r/c @seZdZdZdZeZeZdde j dddddddf ddZ dd Z d!d d Z d d ZddZddZddZddZedfddZddZddZddZdddddeddddf dd ZdS)"HTTPConnectionPoola: Thread-safe connection pool for one host. :param host: Host used for this HTTP Connection (e.g. "localhost"), passed into :class:`http.client.HTTPConnection`. :param port: Port used for this HTTP Connection (None is equivalent to 80), passed into :class:`http.client.HTTPConnection`. :param strict: Causes BadStatusLine to be raised if the status line can't be parsed as a valid HTTP/1.0 or 1.1 status line, passed into :class:`http.client.HTTPConnection`. .. note:: Only works in Python 2. This parameter is ignored in Python 3. :param timeout: Socket timeout in seconds for each individual connection. This can be a float or integer, which sets the timeout for the HTTP request, or an instance of :class:`urllib3.util.Timeout` which gives you more fine-grained control over request timeouts. After the constructor has been parsed, this is always a `urllib3.util.Timeout` object. :param maxsize: Number of connections to save that can be reused. More than 1 is useful in multithreaded situations. If ``block`` is set to False, more connections will be created but they will not be saved once they've been used. :param block: If set to True, no more than ``maxsize`` connections will be used at a time. When no free connections are available, the call will block until a connection has been released. This is a useful side effect for particular multithreaded situations where one does not want to use more than maxsize connections per host to prevent flooding. :param headers: Headers to include with all requests, unless other headers are given explicitly. :param retries: Retry configuration to use by default with requests in this pool. :param _proxy: Parsed proxy URL, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param _proxy_headers: A dictionary with proxy headers, should not be used directly, instead, see :class:`urllib3.ProxyManager` :param \**conn_kw: Additional parameters are used to create fresh :class:`urllib3.connection.HTTPConnection`, :class:`urllib3.connection.HTTPSConnection` instances. httpNFrc Kst|||t||||_t|ts4t|}|durBtj}||_ ||_ | ||_ ||_ | |_| pli|_| |_t|D]} |j dq~d|_d|_| |_|jr|jdg|j|jd<|j|jd<|j }t|t|dS)NrZsocket_optionsproxy proxy_config)r/r9rstrict isinstancer( from_floatr&ZDEFAULTrretriesrGpoolblockrJ proxy_headersrKxrangeputnum_connections num_requestsconn_kw setdefaultr._close_pool_connections)r6r2r5rLrmaxsizerQheadersrO_proxy_proxy_headersZ _proxy_configrW_rPr7r7r8r9s2        zHTTPConnectionPool.__init__cCsR|jd7_td|j|j|jp$d|jf|j|j|jj|jd|j }|S)z9 Return a fresh :class:`HTTPConnection`. rz(Starting new HTTP connection (%d): %s:%sZ80)r2r5rrL) rUlogdebugr2r5 ConnectionClsrconnect_timeoutrLrWr6connr7r7r8 _new_conns zHTTPConnectionPool._new_conncCsd}z|jj|j|d}Wn>ty6t|dYn$tjyX|jrTt|dYn0|rt|rt d|j | t |dddkrd}|p|S) a Get a connection. Will return a pooled connection if one is available. If no connections are available and :prop:`.block` is ``False``, then a fresh connection is returned. :param timeout: Seconds to wait before giving up and raising :class:`urllib3.exceptions.EmptyPoolError` if the pool is empty and :prop:`.block` is ``True``. N)rQrzPool is closed.z>Pool reached maximum size and no more connections are allowed.z Resetting dropped connection: %sZ auto_openrr)rPgetrQAttributeErrorrrEmptyrr!r_r`r2r@getattrre)r6rrdr7r7r8 _get_conns$   zHTTPConnectionPool._get_connc Csbz|jj|ddWdSty(Yn*tjyPtd|j|jYn0|r^| dS)a Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are discarded frequently, then maxsize should be increased. If the pool is closed, then the connection will be closed and discarded. FrQNzLConnection pool is full, discarding connection: %s. Connection pool size: %s) rPrTrgrZFullr_warningr2Zqsizer@rcr7r7r8 _put_conn-s  zHTTPConnectionPool._put_conncCsdS)U Called right before a request is made, after the socket is created. Nr7rcr7r7r8_validate_connLsz!HTTPConnectionPool._validate_conncCsdSr>r7rcr7r7r8_prepare_proxyRsz!HTTPConnectionPool._prepare_proxycCs2|tur|jSt|tr$|St|SdS)z:Helper that always returns a :class:`urllib3.util.Timeout`N)_DefaultrZclonerMr(rN)r6rr7r7r8 _get_timeoutVs   zHTTPConnectionPool._get_timeoutcCsjt|trt||d|t|dr>|jtvr>t||d|dt|vsVdt|vrft||d|dS)zAIs the error actually a timeout? Will raise a ReadTimeout or pass!Read timed out. (read timeout=%s)errnoz timed outzdid not complete (read)N)rM SocketTimeoutrhasattrrt_blocking_errnosstr)r6errurl timeout_valuer7r7r8_raise_timeoutbs    z!HTTPConnectionPool._raise_timeoutc Ks|jd7_||}|t|j|_z||Wn<tt fyx}z |j |||jdWYd}~n d}~00z2|r|j ||fi|n|j ||fi|WnLt yYn<ty}z$|jtjtjtjhvrWYd}~n d}~00|j} t|ddrR| dkr(t||d| | tjurF|jtn |j| zjz|jdd} WnTtyz |} Wn2ty}zt|dWYd}~n d}~00Yn0Wn>tt t fy}z|j ||| dWYd}~n d}~00t|d d } t!"d |j#|j$|j%||| | j&| j' zt(| j)WnBt*tfy|} z$t!j+d |,|| dd WYd} ~ n d} ~ 00| S)a Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout value for the socket connect and the socket read, or an instance of :class:`urllib3.util.Timeout`, which gives you more fine-grained control over your timeouts. r)ryrzr{NsockrrsT) bufferingZ _http_vsn_strzHTTP/?z%s://%s:%s "%s %s %s" %s %sz$Failed to parse headers (url=%s): %s)exc_info)-rVrrZ start_connectr(Zresolve_default_timeoutrbrrorurr|Zrequest_chunkedrequestr IOErrorrtZEPIPEZ ESHUTDOWNZ EPROTOTYPE read_timeoutrirDEFAULT_TIMEOUTr}Z settimeoutsocketZgetdefaulttimeoutZ getresponse TypeError BaseExceptionrZ raise_from SocketErrorr_r`r1r2r5statuslengthr%msgrrl _absolute_url) r6rdmethodrzrchunkedZhttplib_request_kw timeout_objerhttplib_responseZ http_versionZhper7r7r8 _make_request{s       ,  z HTTPConnectionPool._make_requestcCst|j|j|j|djS)N)r1r2r5path)r)r1r2r5rz)r6rr7r7r8rsz HTTPConnectionPool._absolute_urlcCs(|jdurdS|jd}|_t|dSrC)rPrY)r6Zold_poolr7r7r8r@s zHTTPConnectionPool.closecCsx|drdSt|\}}}|dur0t||d}|jrF|sFt|}n|js^|t|kr^d}|||f|j|j|jfkS)zj Check if the given ``url`` is a member of the same host as this connection pool. /TNr0) startswithr,r+r5rrfr1r2)r6rzr1r2r5r7r7r8 is_same_hosts    zHTTPConnectionPool.is_same_hostTc Kst|}|j}|dur|j}t|ts8tj|||jd}| durL| dd} |rf||sft |||| drt t |}n t |j}d}| }t|j|j|}|s|}||jd}d}t|| } zz||}|j| d}|j|_|jduo t|dd }|r"|r"|||j||||||| d }| sD|nd}|| d <|jj|f|||d | }d}Wn"tyd}d}Ynt t!t"t#t$t%t&fy}zd}d d }t|t$r|jr||r|jr|jjdkrt'dt%|}nXt|t$t&frt%|}n>t|t"t(fr@|jr@t'd|}nt|t"t!frZt#d|}|j)||||t*+dd}|,|}WYd}~n d}~00W|s|o|-}d}|r|.|n*|s|o|-}d}|r|.|0|s.t/0d||||j1|||||||f|| | | | d| S|o:|2}|r|j3dkrbd}d}t4|5}z|j)||||d}Wn*t6y|j7r|8|YS0|8|9|t/:d|||j1||||f||||| | | | d| St;|jd}|<||j3|rz|j)||||d}Wn*t6yP|j=rH|8|YS0|8|,|t/:d||j1||||f||||| | | | d| S|S)a+ Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such as :meth:`request`. .. note:: `release_conn` will only behave as expected if `preload_content=False` because we want to make `preload_content=False` the default behaviour someday soon without breaking backwards compatibility. :param method: HTTP request method (such as GET, POST, PUT, etc.) :param url: The URL to perform the request on. :param body: Data to send in the request body, either :class:`str`, :class:`bytes`, an iterable of :class:`str`/:class:`bytes`, or a file-like object. :param headers: Dictionary of custom headers to send, such as User-Agent, If-None-Match, etc. If None, pool headers are used. If provided, these headers completely replace any pool-specific headers. :param retries: Configure the number of retries to allow before raising a :class:`~urllib3.exceptions.MaxRetryError` exception. Pass ``None`` to retry until you receive a response. Pass a :class:`~urllib3.util.retry.Retry` object for fine-grained control over different types of retries. Pass an integer number to retry connection errors that many times, but no other types of errors. Pass zero to never retry. If ``False``, then retries are disabled and any exception is raised immediately. Also, instead of raising a MaxRetryError on redirects, the redirect response will be returned. :type retries: :class:`~urllib3.util.retry.Retry`, False, or an int. :param redirect: If True, automatically handle redirects (status codes 301, 302, 303, 307, 308). Each redirect counts as a retry. Disabling retries will disable redirect, too. :param assert_same_host: If ``True``, will make sure that the host of the pool requests is consistent else will raise HostChangedError. When ``False``, you can use the pool on an HTTP proxy and request foreign hosts. :param timeout: If specified, overrides the default timeout for this one request. It may be a float (in seconds) or an instance of :class:`urllib3.util.Timeout`. :param pool_timeout: If set and the pool is set to block=True, then this method will block for ``pool_timeout`` seconds and raise EmptyPoolError if no connection is available within the time period. :param release_conn: If False, then the urlopen call will not release the connection back into the pool once a response is received (but will release if you read the entire contents of the response such as when `preload_content=True`). This is useful if you're not preloading the response's content immediately. You will need to call ``r.release_conn()`` on the response ``r`` to return the connection back into the pool. If None, it takes the value of ``response_kw.get('preload_content', True)``. :param chunked: If True, urllib3 will send the body using chunked transfer encoding. Otherwise, urllib3 will send the body using the standard content-length form. Defaults to False. :param int body_pos: Position to seek to in file-like body in the event of a retry or redirect. Typically this won't need to be set because urllib3 will auto-populate the value when needed. :param \**response_kw: Additional parameters are passed to :meth:`urllib3.response.HTTPResponse.from_httplib` N)redirectdefaultZpreload_contentTrFrr})rbodyr[rZrequest_method)rP connectionrOcSs*dtdt|}d|vp(d|vS)N z[^a-z]zwrong version numberzunknown protocol)joinresplitrxr3)Z ssl_errormessager7r7r8%_is_ssl_error_message_from_http_proxyszIHTTPConnectionPool.urlopen.._is_ssl_error_message_from_http_proxyhttpszYour proxy appears to only use HTTP and not HTTPS, try changing your proxy URL to be HTTP. See: https://urllib3.readthedocs.io/en/1.26.x/advanced-usage.html#https-proxy-error-http-proxyzCannot connect to proxy.zConnection aborted.)r_poolZ _stacktracez1Retrying (%r) after connection broken by '%r': %s)r pool_timeout release_connrbody_posi/ZGET)responserzRedirecting %s -> %s)rOrassert_same_hostrrrrrz Retry-Afterz Retry: %s)>r-r1r[rMr&Zfrom_intrOrfrrrrZ ensure_strr*rzr"rJrKcopyupdaterRr$rrrjrbrrirpr ResponseClsZ from_httplibrrr rrrrr'rrZ incrementsysrsleepr@rmr_rlurlopenZget_redirect_locationrrZ_prepare_for_method_changerZraise_on_redirectZ drain_connZsleep_for_retryr`boolZis_retryZraise_on_status)r6rrzrr[rOrrrrrrrZ response_kwZ parsed_urlZdestination_schemerdZrelease_this_connZhttp_tunnel_requiredryZ clean_exitrZis_new_proxy_connrZ response_connrrrZredirect_locationZhas_retry_afterr7r7r8rsxm                               zHTTPConnectionPool.urlopen)N)r;rDrErFr1r rar rr(rr9rerjrmrorprrr|rqrrr@rrr7r7r7r8rHqsL; @ '  w rHcspeZdZdZdZeZddejdddddddddddddddfddZ dd Z d d Z d d Z fddZ ZS)HTTPSConnectionPoola Same as :class:`.HTTPConnectionPool`, but HTTPS. :class:`.HTTPSConnection` uses one of ``assert_fingerprint``, ``assert_hostname`` and ``host`` in this order to verify connections. If ``assert_hostname`` is False, no verification is done. The ``key_file``, ``cert_file``, ``cert_reqs``, ``ca_certs``, ``ca_cert_dir``, ``ssl_version``, ``key_password`` are only used if :mod:`ssl` is available and are fed into :meth:`urllib3.util.ssl_wrap_socket` to upgrade the connection socket into an SSL socket. rNFrc Ks`tj|||||||||| | f i|| |_| |_| |_||_||_||_||_||_ ||_ dSr>) rHr9key_file cert_file cert_reqs key_passwordca_certs ca_cert_dir ssl_versionassert_hostnameassert_fingerprint)r6r2r5rLrrZrQr[rOr\r]rrrrrrrrrrWr7r7r8r9s0 zHTTPSConnectionPool.__init__c Cs@t|tr<|j|j|j|j|j|j|j|j |j d|j |_ |S)z Prepare the ``connection`` for :meth:`urllib3.util.ssl_wrap_socket` and establish the tunnel if proxy is used. )rrrrrrrr) rMrZset_certrrrrrrrrrrcr7r7r8 _prepare_conns  z!HTTPSConnectionPool._prepare_conncCs2||j|j|j|jjdkr&d|_|dS)z Establishes a tunnel connection through HTTP CONNECT. Tunnel connection is established early because otherwise httplib would improperly set Host: header to proxy's IP:port. rTN)Z set_tunnelr4r5rRrJr1Ztls_in_tls_requiredconnectrcr7r7r8rps z"HTTPSConnectionPool._prepare_proxyc Cs|jd7_td|j|j|jp$d|jr8|jtur@td|j}|j}|jdurf|jj}|jj}|jf|||j j |j |j |j |jd|j}||S)zF Return a fresh :class:`http.client.HTTPSConnection`. rz)Starting new HTTPS connection (%d): %s:%sZ443zCCan't connect to HTTPS URL because the SSL module is not available.N)r2r5rrLrrr)rUr_r`r2r5rar rrJrrbrLrrrrWr)r6Z actual_hostZ actual_portrdr7r7r8res8  zHTTPSConnectionPool._new_conncs\tt||t|dds$||js>> conn = connection_from_url('http://google.com/') >>> r = conn.request('GET', '/') Prr5N)r,rrfrrH)rzkwr1r2r5r7r7r8connection_from_url;s rcCs.t||}|dr*|dr*|dd}|S)z? Normalize hosts for comparisons and use with sockets. []r)normalize_hostrendswith)r2r1r7r7r8r+Ws  r+cCs8z|jdd}|r|qWntjy2Yn0dS)z2Drains a queue of connections and closes each one.FrkN)rfr@rrh)rPrdr7r7r8rYis  rY)XZ __future__rrtZloggingrrrrrrrru _collectionsrrrr r r r r rr exceptionsrrrrrrrrrrrrrZpackagesrZpackages.six.movesrrrrr Zutil.connectionr!Z util.proxyr"Z util.queuer#Z util.requestr$Z util.responser%Z util.retryr&Zutil.ssl_match_hostnamer'Z util.timeoutr(Zutil.urlr)r*r+rr,r-weakreffinalizer.rgZ#packages.backports.weakref_finalizeZmovesrSZ getLoggerr;r_objectrqr/ZEAGAINZ EWOULDBLOCKrwrHrrrYr7r7r7r8s`    ( <               ) &+