
    M/ey                     d   d Z ddlZddlZddlmZ ddlm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 ddlmZ ddlmZ dd	lmZ dd
lmZ ddlm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 ddlmZ ddlmZ ddlm Z  ddlm!Z!  ejD                  e#      Z$dZ% G d d      Z& G d d      Z'y)zACME client API.    N)parsedate_tz)Any)cast)List)Mapping)Optional)Set)Tuple)Union)HTTPAdapter)parse_header_links)
challenges)crypto_util)errors)jws)messages-   c            
       t   e Zd ZdZdej
                  ddddfdZdej                  dej                  fd	Z	d
ej                  dej                  fdZ
	 d7d
ej                  deej                     dej                  fdZd8d
ej                  dedej                  fdZdedej"                  fdZdej&                  deej&                  ej,                  f   fdZ	 d7dej"                  deej0                     dej"                  fdZdej"                  dej0                  dej"                  fdZdej"                  dej"                  fdZ	 d8dej"                  dej0                  dedej"                  fdZ	 d8dej"                  dej0                  dedej"                  fdZdej>                  de ddfdZ!defdZ"d e#d!e#dej,                  fd"Z$d#ej,                  d$e%de&e%   fd%Z'e(d&e%dddej
                  fd'       Z)e(	 	 d9d#ej,                  d(ee%   d)ee%   dej                  fd*       Z*d
ej                  d+ej                  dej                  fd,Z+d e#d!e#dej,                  fd-Z,d
ej                  dej                  fd.Z-dej&                  dej&                  fd/Z.	 	 d9d#ej,                  d0eej^                     d(ee%   dej&                  fd1Z0d2ejb                  d#e2jf                  dejh                  fd3Z5e(d#ej,                  d4e dej0                  fd5       Z6dej>                  de d&e%ddfd6Z7y):ClientV2zuACME client for a v2 API.

    :ivar messages.Directory directory:
    :ivar .ClientNetwork net: Client network.
    	directorynetClientNetworkreturnNc                      || _         || _        y)zInitialize.

        :param .messages.Directory directory: Directory Resource
        :param .ClientNetwork net: Client network.
        N)r   r   )selfr   r   s      -/usr/lib/python3/dist-packages/acme/client.py__init__zClientV2.__init__*   s     #    new_accountc                    | j                  | j                  d   |      }|j                  dk(  r0d|j                  v r"t	        j
                  |j                  d         | j                  |      }|| j                  _        |S )zRegister.

        :param .NewRegistration new_account:

        :raises .ConflictError: in case the account already exists

        :returns: Registration Resource.
        :rtype: `.RegistrationResource`
        
newAccount   Location)	_postr   status_codeheadersr   ConflictError_regr_from_responser   account)r   r   responseregrs       r   r   zClientV2.new_account3   su     ::dnn\:KH3&:9I9I+I&&x'7'7
'CDD''1r   r+   c                 p    | j                  |d      | j                  _        | j                  j                  S )zQuery server about registration.

        :param messages.RegistrationResource regr: Existing Registration
            Resource.

        T)_get_v2_accountr   r)   r   r+   s     r   query_registrationzClientV2.query_registrationF   s-      //d;xxr   updatec                     | j                  |      }||j                  n|}t        j                  di t	        |      }| j                  ||      }|| j                  _        |S )aK  Update registration.

        :param messages.RegistrationResource regr: Registration Resource.
        :param messages.Registration update: Updated body of the
            resource. If not provided, body will be taken from `regr`.

        :returns: Updated Registration Resource.
        :rtype: `.RegistrationResource`

        body )r-   r3   r   UpdateRegistrationdict_send_recv_regrr   r)   )r   r+   r0   r3   updated_regrs        r   update_registrationzClientV2.update_registrationR   sa     ##D)$n&**:T&\:++Dt+<'r   update_bodyc                 v   d | j                   _        |j                  j                  d      }| j	                  | j
                  d   |      }|j                  d   }|j                  |r-t        j                  j                  |j                               n|j                  |      }|| j                   _        |S )NT)only_return_existingr!   r#   r3   uri)r   r)   r3   r0   r$   r   r&   r   Registration	from_jsonjson)r   r+   r:   only_existing_regr*   updated_urinew_regrs          r   r-   zClientV2._get_v2_accounth   s     II,,$,G::dnn\:<MN&&z2;;"- %-$9$9$C$CHMMO$T3799#.  0 $r   csr_pemc                 f   t         j                  j                  t         j                  j                  |      }t	        j
                  |      }t	        j                  |      }g }|D ]6  }|j                  t        j                  t        j                  |             8 |D ]6  }|j                  t        j                  t        j                  |             8 t        j                  |      }| j                  | j                  d   |      }	t        j                  j!                  |	j#                               }
g }|
j$                  D ]3  }|j                  | j'                  | j)                  |      |             5 t        j*                  |
|	j,                  j/                  d      ||      S )zRequest a new Order object from the server.

        :param bytes csr_pem: A CSR in PEM format.

        :returns: The newly created order.
        :rtype: OrderResource
        )typvalue)identifiersnewOrderr>   r#   )r3   r>   authorizationsrE   )OpenSSLcryptoload_certificate_requestFILETYPE_PEMr    _pyopenssl_cert_or_req_all_names_pyopenssl_cert_or_req_san_ipappendr   
IdentifierIDENTIFIER_FQDNIDENTIFIER_IPNewOrderr$   r   Orderr@   rA   rL   _authzr_from_response_post_as_getOrderResourcer&   get)r   rE   csrdnsNamesipNamesrI   nameipsorderr*   r3   rL   urls                r   	new_orderzClientV2.new_ordert   ss    nn55gnn6Q6QSZ[??D;;C@ 	Dx22x7O7O  	  	Cx22x7M7M  	 !!k:::dnnZ8%@~~''8 && 	_C!!$"<"<T=N=Ns=SY\"<"]^	_%%  $$Z0)	 	r   authzrc                     | j                  |j                        }| j                  ||j                  j                  |j                        }||fS )a  Poll Authorization Resource for status.

        :param authzr: Authorization Resource
        :type authzr: `.AuthorizationResource`

        :returns: Updated Authorization Resource and HTTP response.

        :rtype: (`.AuthorizationResource`, `requests.Response`)

        )rZ   r>   rY   r3   
identifier)r   re   r*   updated_authzrs       r   pollzClientV2.poll   sH     $$VZZ033fkk,,fjj:x''r   orderrdeadlinec                     |5t         j                   j                         t        j                  d      z   }| j                  ||      }| j	                  ||      S )ad  Poll authorizations and finalize the order.

        If no deadline is provided, this method will timeout after 90
        seconds.

        :param messages.OrderResource orderr: order to finalize
        :param datetime.datetime deadline: when to stop polling and timeout

        :returns: finalized order
        :rtype: messages.OrderResource

        Z   seconds)datetimenow	timedeltapoll_authorizationsfinalize_order)r   rj   rk   s      r   poll_and_finalizezClientV2.poll_and_finalize   sS     ((,,.1C1CB1OOH))&(;""6844r   c                 H   g }|j                   j                  D ]  }t        j                  j                         |k  s%| j	                  | j                  |      |      }|j                   j                  t        j                  k7  r|j                  |       t        j                  d       t        j                  j                         |k  r t        |      t        |j                   j                        k  rt        j                         g }|D ]c  }|j                   j                  t        j                  k7  s+|j                   j                   D ]   }|j"                  |j                  |       " e |rt        j$                  |      |j'                  |      S )zPoll Order Resource for status.rK      )rL   )r3   rL   rp   rq   rY   rZ   statusr   STATUS_PENDINGrS   timesleeplenr   TimeoutErrorSTATUS_VALIDr   errorValidationErrorr0   )r   rj   rk   	responsesrc   re   failedchalls           r   rs   zClientV2.poll_authorizations   sU    	;;-- 	C##'')H433D4E4Ec4JPS3T;;%%)@)@@$$V,

1 ##'')H4	 y>C : :;;%%'' 	.F{{!!X%:%::#[[33 .E{{.f-.	.
 ((00}}I}66r   c                    t         j                  j                  t         j                  j                  |j                        }t        j                  t        j                  |            }| j                  |j                  j                  |      }|j                  t
        j                  j                  |j                                     }|S )a  Start the process of finalizing an order.

        :param messages.OrderResource orderr: order to finalize
        :param datetime.datetime deadline: when to stop polling and timeout

        :returns: updated order
        :rtype: messages.OrderResource
        )r]   r2   )rM   rN   rO   rP   rE   r   CertificateRequestjoseComparableX509r$   r3   finalizer0   rX   r@   rA   )r   rj   r]   wrapped_csrress        r   begin_finalizationzClientV2.begin_finalization   s     nn55NN''911d6I6I#6NOjj--{;HNN$<$<SXXZ$HIr   fetch_alternative_chainsc                    t         j                   j                         |k  rt        j                  d       | j	                  |j
                        }t        j                  j                  |j                               }|j                  t        j                  k(  r@|j                  t        j                  |j                        t        j                  d      |j                  t        j                   k(  r|j"                  | j	                  |j"                        }|j%                  ||j&                        }|rL| j)                  |d      }|D cg c]  }| j	                  |      j&                   }	}|j%                  |	      }|S t         j                   j                         |k  rt        j*                         c c}w )z
        Poll an order that has been finalized for its status.
        If it becomes valid, obtain the certificate.

        :returns: finalized order (with certificate)
        :rtype: messages.OrderResource
        rw   zPThe certificate order failed. No further information was provided by the server.)r3   fullchain_pem	alternate)alternative_fullchains_pem)rp   rq   rz   r{   rZ   r>   r   rX   r@   rA   rx   STATUS_INVALIDr   r   IssuanceErrorErrorr~   certificater0   text
_get_linksr}   )
r   rj   rk   r   r*   r3   certificate_responsealt_chains_urlsrc   
alt_chainss
             r   poll_finalizationzClientV2.poll_finalization   sg    ##%0JJqM((4H>>++HMMO<D{{h555::) ..tzz::ll%& &  5 55$:J:J:V'+'8'89I9I'J$D@T@Y@YZ+&*oo6JK&XOIX!Y#$"3"3C"8"="=!YJ!Y#]]j]QF# ##%0$ !!## "Zs   "Gc                 J    | j                  |       | j                  |||      S )a{  Finalize an order and obtain a certificate.

        :param messages.OrderResource orderr: order to finalize
        :param datetime.datetime deadline: when to stop polling and timeout
        :param bool fetch_alternative_chains: whether to also fetch alternative
            certificate chains

        :returns: finalized order
        :rtype: messages.OrderResource

        )r   r   )r   rj   rk   r   s       r   rt   zClientV2.finalize_order  s(     	'%%fh8PQQr   certrsnc                 D    | j                  ||| j                  d          y)a  Revoke certificate.

        :param .ComparableX509 cert: `OpenSSL.crypto.X509` wrapped in
            `.ComparableX509`

        :param int rsn: Reason code for certificate revocation.

        :raises .ClientError: If revocation is unsuccessful.

        
revokeCertN)_revoker   )r   r   r   s      r   revokezClientV2.revoke  s     	T3| <=r   c                     t        | j                  d      xrB t        | j                  j                  d      xr  | j                  j                  j                  S )zGChecks if ACME server requires External Account Binding authentication.metaexternal_account_required)hasattrr   r   r   r   s    r   r   z"ClientV2.external_account_required"  sG    t~~v. =t~~**,GH=~~""<<	=r   argskwargsc                 B    |dd dz   |dd z   } | j                   |i |S )z
        Send GET request using the POST-as-GET protocol.
        :param args:
        :param kwargs:
        :return:
        Nrw   N)r$   )r   r   r   new_argss       r   rZ   zClientV2._post_as_get(  s5     8g%QR0tzz8.v..r   r*   relation_typec                     d|j                   vrg S t        |j                   d         }|D cg c]  }d|v rd|v r|d   |k(  r|d    c}S c c}w )z
        Retrieves all Link URIs of relation_type from the response.
        :param requests.Response response: The requests HTTP response.
        :param str relation_type: The relation type to filter by.
        Linkrelrc   )r&   r   )r   r*   r   linksls        r   r   zClientV2._get_links2  sk     )))I"8#3#3F#;<"' LQA:%1*5]1J % L 	L Ls   Arc   c                 z    t         j                  j                  |j                  |      j	                               S )aB  
        Retrieves the ACME directory (RFC 8555 section 7.1.1) from the ACME server.
        :param str url: the URL where the ACME directory is available
        :param ClientNetwork net: the ClientNetwork to use to make the request

        :returns: the ACME directory object
        :rtype: messages.Directory
        )r   	Directoryr@   r\   rA   )clsrc   r   s      r   get_directoryzClientV2.get_directory@  s,     !!++CGGCL,=,=,?@@r   r>   terms_of_servicec                     d|j                   v r|j                   d   d   }t        j                  t        j                  j	                  |j                               |j                  j                  d|      |      S )Nzterms-of-servicerc   r#   )r3   r>   r   )r   r   RegistrationResourcer?   r@   rA   r&   r\   )r   r*   r>   r   s       r   r(   zClientV2._regr_from_responseL  sk     /'~~.@A%H,,&&00A  $$Z5-/ 	/r   r3   c                     | j                  |j                  |      }| j                  ||j                  |j                        S )N)r>   r   )r$   r>   r(   r   )r   r+   r3   r*   s       r   r7   zClientV2._send_recv_regrX  sB    ::dhh- ''$((!22 ( 4 	4r   c                     |j                  dt        | j                  d              | j                  j                  |i |S )zWrapper around self.net.post that adds the newNonce URL.

        This is used to retry the request in case of a badNonce error.

        new_nonce_urlnewNonce)
setdefaultgetattrr   r   postr   r   r   s      r   r$   zClientV2._postf  s9     	/74>>:+NOtxx}}d-f--r   c                 f    | j                  |t        j                  j                  ddd            S )zDeactivate registration.

        :param messages.RegistrationResource regr: The Registration Resource
            to be deactivated.

        :returns: The Registration resource that was deactivated.
        :rtype: `.RegistrationResource`

        deactivatedN)rx   contact)r9   r   r?   r@   r.   s     r   deactivate_registrationz ClientV2.deactivate_registrationo  s4     ''h.C.C.M.M$6/8 9 	9r   c                     t        j                  d      }| j                  |j                  |      }| j	                  ||j
                  j                  |j                        S )a  Deactivate authorization.

        :param messages.AuthorizationResource authzr: The Authorization resource
            to be deactivated.

        :returns: The Authorization resource that was deactivated.
        :rtype: `.AuthorizationResource`

        r   )rx   )r   UpdateAuthorizationr$   r>   rY   r3   rg   )r   re   r3   r*   s       r   deactivate_authorizationz!ClientV2.deactivate_authorization}  sP     ++=A::fjj$/))(KK""FJJ0 	0r   rg   c                    t        j                  t         j                  j                  |j	                               |j
                  j                  d|            }|.|j                  j                  |k7  rt        j                  |      |S )Nr#   r=   )r   AuthorizationResourceAuthorizationr@   rA   r&   r\   r3   rg   r   UnexpectedUpdate)r   r*   rg   r>   re   s        r   rY   zClientV2._authzr_from_response  ss     //''11(--/B  $$Z57 !fkk&<&<
&J))&11r   challbc                    | j                  |j                  |      }	 |j                  d   d   }t        j                  |t        j                  j                  |j                                     }|j                  |j                  k7  rt	        j                  |j                        |S # t        $ r t	        j
                  d      w xY w)ah  Answer challenge.

        :param challb: Challenge Resource body.
        :type challb: `.ChallengeBody`

        :param response: Corresponding Challenge response
        :type response: `.challenges.ChallengeResponse`

        :returns: Challenge Resource with updated body.
        :rtype: `.ChallengeResource`

        :raises .UnexpectedUpdate:

        uprc   z"up" Link header missing)
authzr_urir3   )r$   r>   r   KeyErrorr   ClientErrorr   ChallengeResourceChallengeBodyr@   rA   r   )r   r   r*   respr   challrs         r   answer_challengezClientV2.answer_challenge  s      zz&**h/	AD)%0J ++!''11$))+>@ ::#))&**55  	A$$%?@@	As   B, ,Cdefaultc                    |j                   j                  dt        |            }	 t        |      }t        j                  j                         t        j                  |      z   S # t        $ ra t        |      }|O	 t        j                  |d   |d   nd      }t        j                  |dd  |z
  cY S # t        t        f$ r Y nw xY w|}Y w xY w)a  Compute next `poll` time based on response ``Retry-After`` header.

        Handles integers and various datestring formats per
        https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.37

        :param requests.Response response: Response from `poll`.
        :param int default: Default value (in seconds), used when
            ``Retry-After`` header is not present or invalid.

        :returns: Time point when next `poll` should be performed.
        :rtype: `datetime.datetime`

        zRetry-AfterNr      rn   )
r&   r\   strint
ValueErrorr   rp   rr   OverflowErrorrq   )r   r*   r   retry_afterro   whentz_secss          r   r   zClientV2.retry_after  s     &&**=#g,G	+&G   $$&););G)LLL  
	  ,D&00T"X=QbWXYG#,,d2Ah7'AA"M2 G
	s5   A' 'C>6B74C7C	CC		CCc                     | j                  |t        j                  ||            }|j                  t        j
                  k7  rt        j                  d      y)a.  Revoke certificate.

        :param .ComparableX509 cert: `OpenSSL.crypto.X509` wrapped in
            `.ComparableX509`

        :param int rsn: Reason code for certificate revocation.

        :param str url: ACME URL to post to

        :raises .ClientError: If revocation is unsuccessful.

        )r   reasonz0Successful revocation must return HTTP OK statusN)r$   r   
Revocationr%   http_clientOKr   r   )r   r   r   rc   r*   s        r   r   zClientV2._revoke  sY     ::c&11,0'*,- ;>>1$$BD D 2r   r   )F)NN)8__name__
__module____qualname____doc__r   r   r   NewRegistrationr   r   r/   r   r?   r9   boolr-   bytesr[   rd   r   r
   requestsResponseri   rp   ru   rs   r   r   rt   r   r   r   r   r   r   rZ   r   r   r   classmethodr   r(   r7   r$   r   r   rT   rY   r   r   ChallengeResponser   r   r   r   r4   r   r   r   r   #   sx   ("4"4 ? t x'?'? HDaDa &
 x'D'D 
  ( = =
  GK(E(E $,X-B-B$C!)!>!>,
H$A$A 
PT 
$99
! !8+A+A !F(899 (668I8IIJ($ CG5(>(> 5$,X->->$?5KSKaKa5&7(*@*@ 7HL]L] 7!)!7!772)?)?  ( 6 6& <A$(>(> $$,$5$5$48$  (55$B 9>RX%;%; RxGXGX R15RBJBXBXR >4.. >S >T >=4 =/# / /9J9J /L8#4#4 LS LTRUY L 	A 	A/ 	Ah>P>P 	A 	A SW>B	/8+<+< 	/8C= 	/.6sm	/!)!>!>	/ 	/4H$A$A 4&3348@8U8U4.3 .# .(2C2C .9H,I,I 9%-%B%B90)1)G)G0&.&D&D0$ KO37h.?.? *283F3F*G#+C=<D<Z<Zx'='= #-#?#?DLD^D^: M8#4#4 Ms MxGXGX M M>DD// Dc D D Dr   r   c                   \   e Zd ZdZdZdZdZdZ	 dej                  dde
fd	ej                  d
eej                     dej                  dedededdfdZd$dZdej*                  dededefdZe	 d%dej2                  dee   dej2                  fd       Zdededededej2                  f
dZdededej2                  fdZefdedededej2                  fdZdej2                  ddfdZded edefd!Z dededej2                  fd"Z!efdedej*                  dededej2                  f
d#Z"y)&r   zvWrapper around requests that signs POSTs for authentication.

    Also adds user agent, and handles Content-Type.
    zapplication/jsonzapplication/jose+jsonzapplication/problem+jsonzReplay-NonceNTzacme-pythonkeyr)   alg
verify_ssl
user_agenttimeoutr   c                 ,   || _         || _        || _        || _        t	               | _        || _        t        j                         | _	        || _
        t               }| j                  j                  d|       | j                  j                  d|       y )Nzhttp://zhttps://)r   r)   r   r   set_noncesr   r   Sessionsession_default_timeoutr   mount)r   r   r)   r   r   r   r   adapters           r   r   zClientNetwork.__init__   sw     $!$$'') '-9g.:w/r   c                 X    	 | j                   j                          y # t        $ r Y y w xY wr   )r   close	Exceptionr   s    r   __del__zClientNetwork.__del__  s)    	LL  		s    	))objnoncerc   c           	         |r |j                  d      j                         nd}t        j                  d|       | j                  ||d}| j
                  | j
                  d   |d<   | j                  |d<   t        j                  j                  |fi t        t        t        t        f   |      j                  d      S )	zWrap `JSONDeSerializable` object in JWS.

        .. todo:: Implement ``acmePath``.

        :param josepy.JSONDeSerializable obj:
        :param str url: The URL to which this object will be POSTed
        :param str nonce:
        :rtype: str

           )indentr   zJWS payload:
%s)r   r  rc   r>   kidr   )
json_dumpsencodeloggerdebugr   r)   r   r   JWSsignr   r   r   r   )r   r  r  rc   jobjr   s         r   _wrap_in_jwszClientNetwork._wrap_in_jws  s     58s~~Q~'..0S'.88
 <<# LL/F5Muww||DDDc):F$CDOOWXOYYr   r*   content_typec                    |j                   j                  d      }|r"|j                  d      d   j                         }	 |j	                         }|j                  dk(  r/t        j                  |j                   j                  dd            |j                  s\|E|| j                  k7  rt        j                  d|       	 t        j                  j                  |      t        j$                  |      |%|| j&                  k7  rt        j                  d	|       || j&                  k(  r|t        j$                  d
|       |S # t
        $ r d}Y w xY w# t         j"                  $ r}t        j$                  ||f      d}~ww xY w)a  Check response content and its type.

        .. note::
           Checking is not strict: wrong server response ``Content-Type``
           HTTP header is ignored if response is an expected JSON object
           (c.f. Boulder #56).

        :param str content_type: Expected Content-Type response header.
            If JSON is expected and not present in server response, this
            function will raise an error. Otherwise, wrong Content-Type
            is ignored, but logged.

        :raises .messages.Error: If server response body
            carries HTTP Problem (https://datatracker.ietf.org/doc/html/rfc7807).
        :raises .ClientError: In case of other networking errors.

        Content-Type;r   Ni  r#   zUNKNOWN-LOCATIONz/Ignoring wrong Content-Type (%r) for JSON Errorz<Ignoring wrong Content-Type (%r) for JSON decodable responsez"Unexpected response Content-Type: )r&   r\   splitstriprA   r   r%   r   r'   okJSON_ERROR_CONTENT_TYPEr  r  r   r   r@   r   DeserializationErrorr   JSON_CONTENT_TYPE)r   r*   r  response_ctr  r   s         r   _check_responsezClientNetwork._check_response1  s{   ( &&**>:%++C0399;K	 ==?D 3&&&x'7'7';';JHZ'[\\{{#"="==LLI#%@"..22488 ((22K33H3H$H +- s444((+Mk])[\\;  	D	 00 @ ,,h->??@s*   E	 E 	EEF
.FF
methodr   r   c           	      h   |dk(  rt         j                  d||d          nt         j                  d||       | j                  |d<   |j                  di        |d   j                  d| j                         |j                  d| j
                         	  | j                  j                  ||g|i |}d|d   v r t!        j"                  |j$                        }nd|_        |j(                  }t         j                  d|j*                  dj-                  d |j.                  j1                         D              |       |S # t        j                  j                  $ rR}	 d	}t        j                  |t        |            }| |j                         \  }	}
}}t        d|	 |
 d|       d
}~ww xY w)a  Send HTTP request.

        Makes sure that `verify_ssl` is respected. Logs request and
        response (with headers). For allowed parameters please see
        `requests.request`.

        :param str method: method for the new `requests.Request` object
        :param str url: URL for the new `requests.Request` object

        :raises requests.exceptions.RequestException: in case of any problems

        :returns: HTTP Response
        :rtype: `requests.Response`


        POSTzSending POST request to %s:
%sdatazSending %s request to %s.verifyr&   z
User-Agentr   zT.*host='(\S*)'.*Max retries exceeded with url\: (\/\w*).*(\[Errno \d+\])([A-Za-z ]*)NzRequesting :Acceptzutf-8z!Received response:
HTTP %d
%s

%s
c              3   F   K   | ]  \  }}d j                  ||        yw)z{0}: {1}N)format).0kvs      r   	<genexpr>z.ClientNetwork._send_request.<locals>.<genexpr>  s+      F$(Aq  *00A6 Fs   !)r  r  r   r   r   r   r   requestr   
exceptionsRequestExceptionrematchr   groupsr   base64	b64encodecontentencodingr   r%   joinr&   items)r   r  rc   r   r   r*   e	err_regexmhostpath_err_noerr_msgdebug_contents                 r   _send_requestzClientNetwork._send_requestl  s   " VLL:vf~/ LL4fcB??x)R(y$$\4??C)T%:%:;	C+t||++FCI$I&IH8 vi((",,X-=-=>M !(H$MMM<))YY F,4,<,<,B,B,DF F"		$
 S ""33 	C/ pICF+Ay+,88:(D${4&ayABB+	Cs   !E F1AF,,F1c                 .     | j                   dg|i |S )a  Send HEAD request without checking the response.

        Note, that `_check_response` is not called, as it is expected
        that status code other than successfully 2xx will be returned, or
        messages2.Error will be raised by the server.

        HEAD)r@  r   s      r   headzClientNetwork.head  s!     "t!!&:4:6::r   c                 L    | j                   | j                  d|fi ||      S )z$Send GET request and check response.GETr  )r  r@  )r   rc   r  r   s       r   r\   zClientNetwork.get  s7     ##Duc4V4< $ Q 	Qr   c                    | j                   |j                  v rx|j                  | j                      }	 t        j                  j                  d   j                  |      }t        j                  d|       | j                  j                  |       y t        j                  |      # t        j                  $ r}t        j                  ||      d }~ww xY w)Nr  zStoring nonce: %s)REPLAY_NONCE_HEADERr&   r   Header_fieldsdecoder   r  r   BadNoncer  r  r   addMissingNonce)r   r*   r  decoded_noncer   s        r   
_add_noncezClientNetwork._add_nonce  s    ##x'7'77$$T%=%=>E4 #

 2 27 ; B B5 I LL,e4LL]+%%h// ,, 4ooeU334s   ,B& &C9CCr   c                    | j                   s\t        j                  d       || j                  |      }n"| j	                  | j                  |      d       }| j                  |       | j                   j                         S )NzRequesting fresh noncerF  )r   r  r  rC  r  rP  pop)r   rc   r   r*   s       r   
_get_noncezClientNetwork._get_nonce  si    ||LL12$99S>  //		-0HW[/\OOH%||!!r   c                     	  | j                   |i |S # t        j                  $ rB}|j                  dk(  r-t        j                  d|        | j                   |i |cY d}~S  d}~ww xY w)zPOST object wrapped in `.JWS` and check response.

        If the server responded with a badNonce error, the request will
        be retried once.

        badNoncez Retrying request after error:
%sN)
_post_oncer   r   coder  r  )r   r   r   r   s       r   r   zClientNetwork.post  se    	"4??D3F33~~ 	zzZ'@%H&t777		s     A)6A$A)#A$$A)c                    |j                  dd       }| j                  || j                  ||      |      }|j                  dd|i        | j                  d|fd|i|}| j                  ||      }| j                  |       |S )Nr   r&   r  r   r!  rF  )rR  r  rS  r   r@  r  rP  )r   rc   r  r  r   r   r!  r*   s           r   rV  zClientNetwork._post_once  s    

?D9  dooc=&I3O)nl%CD%4%%fcGGG''|'L!r   )r   Nr   )#r   r   r   r   r  JOSE_CONTENT_TYPEr  rH  r   RS256DEFAULT_NETWORK_TIMEOUTJWKr   r   r   JWASignaturer   r   r   r   r  JSONDeSerializabler  r   r   r   r  r   r@  rC  r\   rP  rS  r   rV  r4   r   r   r   r     s    +/8(
 Z^*.**#0AX0DHH 0x8U8U/V 0''0BF0 0;>0]a0 Z 7 7 Z Z# ZRU Z2 6:8x'8'8 8&.sm8?G?P?P8 8tEC Ec E# E EQYQbQb EN;# ; ;1B1B ; 1B Qs Q# QQ&//Q
08#4#4 
0 
0	"c 	"# 	"# 	"#  1B1B   (9c (?(? !$DGLTL]L]r   r   )(r   r2  rp   email.utilsr   http.clientclientr   loggingr/  rz   typingr   r   r   r   r   r	   r
   r   josepyr   rM   r   requests.adaptersr   requests.utilsr   acmer   r   r   r   r   	getLoggerr   r  r[  r   r   r4   r   r   <module>ri     s       $ !  	             ) -     			8	$ ED EDPF Fr   