a „oe¥vã@sldZddlZddlZddlZddlmZddlmZddlm Z ddl m Z ddl m Z dd lmZmZmZmZdd lmZmZmZmZdd lmZmZmZmZdd lmZmZdd l m!Z!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*m+Z+m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3ej4dk�r$ej5Z6nejZ6efdd„Z7efdd„Z8Gdd„dƒZ9Gdd„de9ƒZ:dd„Z;dS)z• requests.sessions ~~~~~~~~~~~~~~~~~ This module provides a Session object to manage and persist settings across requests (cookies, auth, proxies). éN)Ú OrderedDict)Ú timedeltaé)Úto_native_string)Ú HTTPAdapter)Ú_basic_auth_str)ÚMappingÚ cookielibÚurljoinÚurlparse)ÚRequestsCookieJarÚcookiejar_from_dictÚextract_cookies_to_jarÚ merge_cookies)ÚChunkedEncodingErrorÚContentDecodingErrorÚ InvalidSchemaÚTooManyRedirects)Ú default_hooksÚ dispatch_hook)ÚDEFAULT_REDIRECT_LIMITÚREDIRECT_STATIÚPreparedRequestÚRequest)Úcodes)ÚCaseInsensitiveDict) Ú DEFAULT_PORTSÚdefault_headersÚget_auth_from_urlÚget_environ_proxiesÚget_netrc_authÚ requote_uriÚresolve_proxiesÚ rewind_bodyÚshould_bypass_proxiesÚto_key_val_listÚwin32cCsp|dur |S|dur|St|tƒr,t|tƒs0|S|t|ƒƒ}| t|ƒ¡dd„| ¡Dƒ}|D] }||=q`|S)zèDetermines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` NcSsg|]\}}|dur|‘qS©N©)Ú.0ÚkÚvr(r(ú2C:\Program Files\Certbot\pkgs\requests\sessions.pyÚ Tóz!merge_setting..)Ú isinstancerr%ÚupdateÚitems)Zrequest_settingZsession_settingÚ dict_classZmerged_settingZ none_keysÚkeyr(r(r,Ú merge_setting=sÿÿ r4cCs@|dus| d¡gkr|S|dus0| d¡gkr4|St|||ƒS)z©Properly merges both requests and session hooks. This is necessary because when request_hooks == {'response': []}, the merge breaks Session hooks entirely. NÚresponse)Úgetr4)Z request_hooksZ session_hooksr2r(r(r,Ú merge_hooks[s r7c@s>eZdZdd„Zdd„Zddd „Zd d „Zd d „Zdd„ZdS)ÚSessionRedirectMixincCs(|jr$|jd}| d¡}t|dƒSdS)z7Receives a Response. Returns a redirect URI or ``None``ÚlocationÚlatin1Úutf8N)Z is_redirectÚheadersÚencoder)ÚselfÚrespr9r(r(r,Úget_redirect_targetks    z(SessionRedirectMixin.get_redirect_targetcCsšt|ƒ}t|ƒ}|j|jkr dS|jdkrL|jdvrL|jdkrL|jdvrLdS|j|jk}|j|jk}t |jd¡df}|s’|j|vr’|j|vr’dS|p˜|S)zFDecide whether Authorization header should be removed when redirectingTÚhttp)éPNÚhttps)i»NFN)r ÚhostnameÚschemeÚportrr6)r>Zold_urlZnew_urlZ old_parsedZ new_parsedZ changed_portZchanged_schemeZ default_portr(r(r,Úshould_strip_auths0 ÿþýü  ÿþýz&SessionRedirectMixin.should_strip_authFNTc  ksHg} | |¡} t|jƒj} | �rD| ¡} |  |¡| dd…|_z |jWn&tt t fyp|j j dd�Yn0t |jƒ|jkr˜td|j›d�|d�‚| ¡|  d¡rÈt|jƒ}d  t|jƒ| g¡} t| ƒ}|jd krì| rì|j| d �}n |jrø|j} | ¡} |j�st|jt| ƒƒ} nt| ƒ} t| ƒ| _| | |¡|jtjtjfv�rpd }|D]}| j  |d¡�qTd| _!| j}|  d d¡t"| j#||j ƒt$| j#|j%ƒ|  &| j#¡| '| |¡}| (| |¡| j)du�oàd|v�pàd|v}|�rðt*| ƒ| }|�r|Vq|j+|f|||||ddœ| ¤Ž}t"|j%| |j ƒ| |¡} |VqdS)zBReceives a Response. Returns a generator of Responses or Requests.rNF)Zdecode_contentz Exceeded z redirects.)r5z//ú:Ú)Úfragment)úContent-Lengthz Content-TypeúTransfer-EncodingZCookierKrL)ÚstreamÚtimeoutÚverifyÚcertÚproxiesÚallow_redirects),r@r ÚurlrJÚcopyÚappendÚhistoryÚcontentrrÚ RuntimeErrorÚrawÚreadÚlenÚ max_redirectsrÚcloseÚ startswithÚjoinrrEÚ_replaceÚgeturlÚnetlocr r!Úrebuild_methodÚ status_coderZtemporary_redirectZpermanent_redirectr<ÚpopÚbodyrZ_cookiesrÚcookiesZprepare_cookiesÚrebuild_proxiesÚ rebuild_authZ_body_positionr#Úsend)r>r?ÚreqrMrNrOrPrQÚyield_requestsZadapter_kwargsZhistrSZprevious_fragmentÚprepared_requestZ parsed_rurlÚparsedZpurged_headersÚheaderr<Z rewindabler(r(r,Úresolve_redirectsŸsˆ    ÿ    þ     ÿÿùø  z&SessionRedirectMixin.resolve_redirectscCsR|j}|j}d|vr*| |jj|¡r*|d=|jr8t|ƒnd}|durN| |¡dS)zéWhen being redirected we may want to strip authentication from the request to avoid leaking credentials. This method intelligently removes and reapplies authentication where possible to avoid credential loss. Z AuthorizationN)r<rSrGÚrequestÚ trust_envr Z prepare_auth)r>rmr5r<rSZnew_authr(r(r,ris ÿz!SessionRedirectMixin.rebuild_authcCs‚|j}t|jƒj}t|||jƒ}d|vr.|d=zt||ƒ\}}Wnty\d\}}Yn0| d¡s~|r~|r~t ||ƒ|d<|S)a°This method re-evaluates the proxy configuration by considering the environment variables. If we are redirected to a URL covered by NO_PROXY, we strip the proxy configuration. Otherwise, we set missing proxy keys for this URL (in case they were stripped by a previous redirect). This method also replaces the Proxy-Authorization header where necessary. :rtype: dict zProxy-Authorization)NNrC) r<r rSrEr"rrrÚKeyErrorr^r)r>rmrQr<rEZ new_proxiesÚusernameÚpasswordr(r(r,rh/s   z$SessionRedirectMixin.rebuild_proxiescCsX|j}|jtjkr|dkrd}|jtjkr6|dkr6d}|jtjkrN|dkrNd}||_dS)z‚When being redirected we may want to change the method of the request based on certain specs or browser behavior. ÚHEADÚGETÚPOSTN)ÚmethodrdrZ see_otherÚfoundZmoved)r>rmr5ryr(r(r,rcNsz#SessionRedirectMixin.rebuild_method)FNTNNF) Ú__name__Ú __module__Ú __qualname__r@rGrprirhrcr(r(r(r,r8js$÷ |r8c@s¸eZdZdZgd¢Zdd„Zdd„Zdd„Zd d „Zd+d d„Z dd„Z dd„Z dd„Z d,dd„Z d-dd„Zd.dd„Zdd„Zdd„Zdd „Zd!d"„Zd#d$„Zd%d&„Zd'd(„Zd)d*„Zd S)/ÚSessiona€A Requests session. Provides cookie persistence, connection-pooling, and configuration. Basic Usage:: >>> import requests >>> s = requests.Session() >>> s.get('https://httpbin.org/get') Or as a context manager:: >>> with requests.Session() as s: ... s.get('https://httpbin.org/get') ) r<rgÚauthrQÚhooksÚparamsrOrPÚadaptersrMrrr\cCsrtƒ|_d|_i|_tƒ|_i|_d|_d|_d|_ t |_ d|_ t iƒ|_tƒ|_| dtƒ¡| dtƒ¡dS)NFTzhttps://zhttp://)rr<rrQrr€r�rMrOrPrr\rrr rgrr‚Úmountr©r>r(r(r,Ú__init__‡s  zSession.__init__cCs|Sr'r(r„r(r(r,Ú __enter__ÅszSession.__enter__cGs | ¡dSr')r])r>Úargsr(r(r,Ú__exit__ÈszSession.__exit__c Cs²|jpi}t|tjƒst|ƒ}tttƒ|jƒ|ƒ}|j}|jrR|sR|jsRt |j ƒ}t ƒ}|j |j  ¡|j |j|j|jt|j|jtd�t|j|jƒt||jƒ|t|j|jƒd� |S)a‹Constructs a :class:`PreparedRequest ` for transmission and returns it. The :class:`PreparedRequest` has settings merged from the :class:`Request ` instance and those of the :class:`Session`. :param request: :class:`Request` instance to prepare with this session's settings. :rtype: requests.PreparedRequest )r2) ryrSÚfilesÚdataÚjsonr<r�rrgr€)rgr/r Z CookieJarr rr rrrr rSrZprepareryÚupperr‰rŠr‹r4r<rr�r7r€)r>rqrgZmerged_cookiesrÚpr(r(r,Úprepare_requestËs2  ÿ  ÿ   ôzSession.prepare_requestNTc Csxt| ¡||||pi||pi||| d� }| |¡}| p8i} | |j| | ||¡}| | dœ}| |¡|j|fi|¤Ž}|S)aw Constructs a :class:`Request `, prepares it and sends it. Returns :class:`Response ` object. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param headers: (optional) Dictionary of HTTP Headers to send with the :class:`Request`. :param cookies: (optional) Dict or CookieJar object to send with the :class:`Request`. :param files: (optional) Dictionary of ``'filename': file-like-objects`` for multipart encoding upload. :param auth: (optional) Auth tuple or callable to enable Basic/Digest/Custom HTTP Auth. :param timeout: (optional) How long to wait for the server to send data before giving up, as a float, or a :ref:`(connect timeout, read timeout) ` tuple. :type timeout: float or tuple :param allow_redirects: (optional) Set to True by default. :type allow_redirects: bool :param proxies: (optional) Dictionary mapping protocol or protocol and hostname to the URL of the proxy. :param stream: (optional) whether to immediately download the response content. Defaults to ``False``. :param verify: (optional) Either a boolean, in which case it controls whether we verify the server's TLS certificate, or a string, in which case it must be a path to a CA bundle to use. Defaults to ``True``. When set to ``False``, requests will accept any TLS certificate presented by the server, and will ignore hostname mismatches and/or expired certificates, which will make your application vulnerable to man-in-the-middle (MitM) attacks. Setting verify to ``False`` may be useful during local development or testing. :param cert: (optional) if String, path to ssl client cert file (.pem). If Tuple, ('cert', 'key') pair. :rtype: requests.Response ) ryrSr<r‰rŠr‹r�rrgr€)rNrR)rrŒrŽÚmerge_environment_settingsrSr0rj)r>ryrSr�rŠr<rgr‰rrNrRrQr€rMrOrPr‹rkZprepZsettingsZ send_kwargsr?r(r(r,rqös.=ö  ÿþ zSession.requestcKs | dd¡|jd|fi|¤ŽS)zåSends a GET request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response rRTrw©Ú setdefaultrq©r>rSÚkwargsr(r(r,r6Qs z Session.getcKs | dd¡|jd|fi|¤ŽS)zéSends a OPTIONS request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response rRTZOPTIONSr�r’r(r(r,Úoptions\s zSession.optionscKs | dd¡|jd|fi|¤ŽS)zæSends a HEAD request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response rRFrvr�r’r(r(r,Úheadgs z Session.headcKs|jd|f||dœ|¤ŽS)aÈSends a POST request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param json: (optional) json to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response rx)rŠr‹©rq)r>rSrŠr‹r“r(r(r,Úpostrs z Session.postcKs|jd|fd|i|¤ŽS)auSends a PUT request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ZPUTrŠr–©r>rSrŠr“r(r(r,Úputs z Session.putcKs|jd|fd|i|¤ŽS)awSends a PATCH request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param data: (optional) Dictionary, list of tuples, bytes, or file-like object to send in the body of the :class:`Request`. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ZPATCHrŠr–r˜r(r(r,Úpatch‹s z Session.patchcKs|jd|fi|¤ŽS)zèSends a DELETE request. Returns :class:`Response` object. :param url: URL for the new :class:`Request` object. :param \*\*kwargs: Optional arguments that ``request`` takes. :rtype: requests.Response ZDELETEr–r’r(r(r,Údelete—szSession.deletec Ks”| d|j¡| d|j¡| d|j¡d|vrFt||j|jƒ|d<t|tƒrXt dƒ‚|  dd¡}|  d¡}|j }|j |jd�}tƒ}|j|fi|¤Ž}tƒ|} t| d �|_td ||fi|¤Ž}|jrè|jD]} t|j| j| jƒqÐt|j||jƒ|�r"|j||fi|¤Ž} d d „| Dƒ} ng} | �rF|  d |¡|   ¡}| |_|�s„z"t|j||fddi|¤Žƒ|_Wnt�y‚Yn0|�s�|j|S)zISend a given PreparedRequest. :rtype: requests.Response rMrOrPrQz#You can only send PreparedRequests.rRT)rS)Zsecondsr5cSsg|]}|‘qSr(r()r)r?r(r(r,r-Õr.z Session.send..rrl)r‘rMrOrPr"rQrrr/rÚ ValueErrorrer6r€Ú get_adapterrSÚpreferred_clockrjrÚelapsedrrVrrgrqrYrpÚinsertÚnextZ_nextÚ StopIterationrW) r>rqr“rRrMr€ÚadapterÚstartÚrrŸr?ÚgenrVr(r(r,rj¡sL       ÿ z Session.sendc Cs°|jrr|dur| d¡nd}t||d�}| ¡D]\}} | || ¡q0|dusV|durrtj d¡pptj d¡pp|}t||jƒ}t||j ƒ}t||j ƒ}t||j ƒ}||||dœS)z^ Check the environment and merge it with some settings. :rtype: dict NÚno_proxy)r§TZREQUESTS_CA_BUNDLEZCURL_CA_BUNDLE)rQrMrOrP) rrr6rr1r‘ÚosÚenvironr4rQrMrOrP) r>rSrQrMrOrPr§Z env_proxiesr*r+r(r(r,r�ïs    ÿý    z"Session.merge_environment_settingscCs@|j ¡D]"\}}| ¡ | ¡¡r |Sq td|›�ƒ‚dS)z~ Returns the appropriate connection adapter for the given URL. :rtype: requests.adapters.BaseAdapter z&No connection adapters were found for N)r‚r1Úlowerr^r)r>rSÚprefixr£r(r(r,r�s zSession.get_adaptercCs|j ¡D] }| ¡q dS)z+Closes all adapters and as such the sessionN)r‚Úvaluesr])r>r+r(r(r,r]sz Session.closecs>||jˆ<‡fdd„|jDƒ}|D]}|j |¡|j|<q"dS)zwRegisters a connection adapter to a prefix. Adapters are sorted in descending order by prefix length. cs g|]}t|ƒtˆƒkr|‘qSr()r[)r)r*©r«r(r,r-'r.z!Session.mount..N)r‚re)r>r«r£Z keys_to_mover3r(r­r,rƒ!s z Session.mountcs‡fdd„ˆjDƒ}|S)Ncsi|]}|tˆ|dƒ“qSr')Úgetattr)r)Úattrr„r(r,Ú -r.z(Session.__getstate__..)Ú __attrs__)r>Ústater(r„r,Ú __getstate__,szSession.__getstate__cCs"| ¡D]\}}t|||ƒqdSr')r1Úsetattr)r>r²r¯Úvaluer(r(r,Ú __setstate__0szSession.__setstate__)NNNNNNNTNNNNNN)NN)N)N)r{r|r}Ú__doc__r±r…r†rˆrŽrqr6r”r•r—r™ršr›rjr�r�r]rƒr³r¶r(r(r(r,r~esF>/ï [    N r~cCstƒS)aZ Returns a :class:`Session` for context-management. .. deprecated:: 1.0.0 This method has been deprecated since version 1.0.0 and is only kept for backwards compatibility. New code should use :class:`~requests.sessions.Session` to create a session. This may be removed at a future date. :rtype: Session )r~r(r(r(r,Úsession5s r¸)s8       0   |S