U
    [^                     @   s  d Z ddlZddlZddlZddlmZ ddlZddlZddlZddl	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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mZ e e!Z"e	j#dk rJzej$j%j&j'(  W n* e)k
rH   ddl*Z%e%j&j'(  Y nX dZ+dZ,G dd de-Z.G dd de.Z/G dd de.Z0G dd de-Z1G dd de-Z2dS )zACME client API.    N)parsedate_tz)HTTPAdapter)SourceAddressAdapter)http_client)crypto_util)errors)jws)messages)Dict)List)Set)Text)      	   -   zapplication/pkix-certc                   @   sv   e Zd ZdZdd ZedddZdd Zd	d
 ZdddZ	dd Z
dd ZdddZdd Zedd Zdd ZdS )
ClientBasezACME client base object.

    :ivar messages.Directory directory:
    :ivar .ClientNetwork net: Client network.
    :ivar int acme_version: ACME protocol version. 1 or 2.
    c                 C   s   || _ || _|| _dS )zInitialize.

        :param .messages.Directory directory: Directory Resource
        :param .ClientNetwork net: Client network.
        :param int acme_version: ACME protocol version. 1 or 2.
        N	directorynetacme_version)selfr   r   r    r   -/usr/lib/python3/dist-packages/acme/client.py__init__6   s    zClientBase.__init__Nc                 C   s>   d|j kr|j d d }tjtj| |jd||dS )Nzterms-of-serviceurlLocation)bodyuriterms_of_service)linksr	   ZRegistrationResourceZRegistration	from_jsonjsonheadersget)clsresponser   r   r   r   r   _regr_from_responseA   s    
zClientBase._regr_from_responsec                 C   s"   |  |j|}| j||j|jdS )Nr   r   )_postr   r'   r   )r   regrr   r&   r   r   r   _send_recv_regrK   s     zClientBase._send_recv_regrc                 O   s<   | d| j t| jdr.| dt| jd | jj||S )zBWrapper around self.net.post that adds the acme_version.

        r   newNoncenew_nonce_url)
setdefaultr   hasattrr   getattrr   postr   argskwargsr   r   r   r)   X   s    zClientBase._postc                 C   s<   |dkr|j n|}tjf t|}| j||d}|| j_|S )K  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`

        Nr   )r   r	   UpdateRegistrationdictr+   r   account)r   r*   updater   Zupdated_regrr   r   r   update_registrationa   s
    zClientBase.update_registrationc                 C   s   | j |ddidS )zDeactivate registration.

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

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

        statusdeactivated)r:   )r;   r   r*   r   r   r   deactivate_registrationr   s    
z"ClientBase.deactivate_registrationc                 C   s.   t jdd}| |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=   )r<   )r	   ZUpdateAuthorizationr)   r   _authzr_from_responser   
identifier)r   authzrr   r&   r   r   r   deactivate_authorization~   s     z#ClientBase.deactivate_authorizationc                 C   sF   t jt j| |jd|d}|d k	rB|jj|krBt	
||S )Nr   )r   r   )r	   ZAuthorizationResourceZAuthorizationr!   r"   r#   r$   r   rA   r   UnexpectedUpdate)r   r&   rA   r   rB   r   r   r   r@      s    
z ClientBase._authzr_from_responsec                 C   sv   |  |j|}z|jd d }W n tk
r>   tdY nX tj|tj	|
 d}|j|jkrrt|j|S )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:

        upr   z"up" Link header missing)
authzr_urir   )r)   r   r    KeyErrorr   ClientErrorr	   ZChallengeResourceZChallengeBodyr!   r"   rD   )r   Zchallbr&   rF   Zchallrr   r   r   answer_challenge   s    zClientBase.answer_challengec                 C   s   |j dt|}zt|}W nx tk
r   t|}|dk	rz6t|d rT|d nd}tj|dd  | W  Y S  ttfk
r   Y nX |}Y nX tj	 tj|d S )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   r   seconds)
r#   r$   strint
ValueErrorr   datetime	timedeltaOverflowErrornow)r%   r&   defaultretry_afterrL   whenZtz_secsr   r   r   rU      s    
zClientBase.retry_afterc                 C   s0   |  |tj||d}|jtjkr,tddS )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.

        )certificatereasonz0Successful revocation must return HTTP OK statusN)r)   r	   
Revocationstatus_coder   ZOKr   rH   )r   certrsnr   r&   r   r   r   _revoke   s    zClientBase._revoke)NN)N)NN)__name__
__module____qualname____doc__r   classmethodr'   r+   r)   r;   r?   rC   r@   rI   rU   r]   r   r   r   r   r   /   s   		


r   c                       s   e Zd ZdZejddf fdd	Zd"ddZdd	 Zd
d Z	d#ddZ
d$ddZdd Zdd Zd%ddZdd Zdd Zdd Zd&ddZd d! Z  ZS )'Clienta  ACME client for a v1 API.

    .. todo::
       Clean up raised error types hierarchy, document, and handle (wrap)
       instances of `.DeserializationError` raised in `from_json()`.

    :ivar messages.Directory directory:
    :ivar key: `josepy.JWK` (private)
    :ivar alg: `josepy.JWASignature`
    :ivar bool verify_ssl: Verify SSL certificates?
    :ivar .ClientNetwork net: Client network. Useful for testing. If not
        supplied, it will be initialized using `key`, `alg` and
        `verify_ssl`.

    TNc                    sX   || _ |dkrt|||d}t|tjr>tj||	 }t
t| j||dd dS )zInitialize.

        :param directory: Directory Resource (`.messages.Directory`) or
            URI from which the resource will be downloaded.

        N)alg
verify_ssl   r   )keyClientNetwork
isinstancesixZstring_typesr	   	Directoryr!   r$   r"   superrc   r   )r   r   rg   rd   re   r   	__class__r   r   r      s     zClient.__init__c                 C   s@   |dkrt  n|}| | j| |}|jtjks6t| |S )zRegister.

        :param .NewRegistration new_reg:

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

        N)	r	   ZNewRegistrationr)   r   rZ   r   CREATEDAssertionErrorr'   )r   Znew_regr&   r   r   r   register  s    	zClient.registerc                 C   s   |  |t S )Query server about registration.

        :param messages.RegistrationResource: Existing Registration
            Resource.

        )r+   r	   r7   r>   r   r   r   query_registration  s    zClient.query_registrationc                 C   s   |  |j|jj|jddS )a  Agree to the terms-of-service.

        Agree to the terms-of-service in a Registration Resource.

        :param regr: Registration Resource.
        :type regr: `.RegistrationResource`

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

        )Z	agreementr6   )r;   r:   r   r   r>   r   r   r   agree_to_tos%  s    zClient.agree_to_tosc                 C   s`   |dk	rt d |jdr(tdtj|d}| | j	j
|}|jtjksTt| ||S )aG  Request challenges.

        :param .messages.Identifier identifier: Identifier to be challenged.
        :param str new_authzr_uri: Deprecated. Do not use.

        :returns: Authorization Resource.
        :rtype: `.AuthorizationResource`

        :raises errors.WildcardUnsupportedError: if a wildcard is requested

        Nz2request_challenges with new_authzr_uri deprecated.*zbRequesting an authorization for a wildcard name is forbidden by this version of the ACME protocol.)rA   )loggerdebugvalue
startswithr   ZWildcardUnsupportedErrorr	   ZNewAuthorizationr)   r   	new_authzrZ   r   ro   rp   r@   )r   rA   new_authzr_urirz   r&   r   r   r   request_challenges4  s    
zClient.request_challengesc                 C   s   |  tjtj|d|S )a"  Request challenges for domain names.

        This is simply a convenience function that wraps around
        `request_challenges`, but works with domain names instead of
        generic identifiers. See ``request_challenges`` for more
        documentation.

        :param str domain: Domain name to be challenged.
        :param str new_authzr_uri: Deprecated. Do not use.

        :returns: Authorization Resource.
        :rtype: `.AuthorizationResource`

        :raises errors.WildcardUnsupportedError: if a wildcard is requested

        typrx   )r|   r	   
IdentifierIDENTIFIER_FQDN)r   domainr{   r   r   r   request_domain_challengesN  s     z Client.request_domain_challengesc              
   C   s   |st dtd tj|d}t}| j| jj||d|id}|j	
di 
d}z|jd }W n tk
r   td	Y nX tj|||ttjtjj|jd
S )a  Request issuance.

        :param csr: CSR
        :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`

        :param authzrs: `list` of `.AuthorizationResource`

        :returns: Issued certificate
        :rtype: `.messages.CertificateResource`

        zAuthorizations list is emptyzRequesting issuance...csrAccept)content_typer#   rE   r   r   z"Location" Header missing)r   authzrscert_chain_urir   )rp   rv   rw   r	   CertificateRequestDER_CONTENT_TYPEr)   r   Znew_certr    r$   r#   rG   r   rH   ZCertificateResourcejoseComparableX509OpenSSLcryptoload_certificateFILETYPE_ASN1content)r   r   r   Zreqr   r&   r   r   r   r   r   request_issuanceb  s0    
  
 zClient.request_issuancec                 C   s*   | 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`)

        )r   r$   r   r@   r   rA   r   rB   r&   updated_authzrr   r   r   poll  s      zClient.poll   
   c                    sX  |dkst tt}t }dd t|D }t| tdd |D  |rt	|\}}	}
t
j
 }||kr|| j}td| t| |  |
 \}}| |
< ||
  d7  < |jjtjtjfkrJ||
 |k rt|| j||d|	|
f qJ||
 qJ|s&td	d t D r2t| t fd
d|D }|  |||fS )a  Poll and request issuance.

        This function polls all provided Authorization Resource URIs
        until all challenges are valid, respecting ``Retry-After`` HTTP
        headers, and then calls `request_issuance`.

        :param .ComparableX509 csr: CSR (`OpenSSL.crypto.X509Req`
            wrapped in `.ComparableX509`)
        :param authzrs: `list` of `.AuthorizationResource`
        :param int mintime: Minimum time before next attempt, used if
            ``Retry-After`` is not present in the response.
        :param int max_attempts: Maximum number of attempts (per
            authorization) before `PollError` with non-empty ``waiting``
            is raised.

        :returns: ``(cert, updated_authzrs)`` `tuple` where ``cert`` is
            the issued certificate (`.messages.CertificateResource`),
            and ``updated_authzrs`` is a `tuple` consisting of updated
            Authorization Resources (`.AuthorizationResource`) as
            present in the responses from server, and in the same order
            as the input ``authzrs``.
        :rtype: `tuple`

        :raises PollError: in case of timeout or if some authorization
            was marked by the CA as invalid

        r   c                 S   s    g | ]\}}t j  ||fqS r   )rP   rS   ).0indexrB   r   r   r   
<listcomp>  s   z4Client.poll_and_request_issuance.<locals>.<listcomp>c                 s   s   | ]}||fV  qd S Nr   r   rB   r   r   r   	<genexpr>  s     z3Client.poll_and_request_issuance.<locals>.<genexpr>zSleeping for %d secondsrf   )rT   c                 s   s   | ]}|j jtjkV  qd S r   )r   r<   r	   STATUS_INVALIDr   r   r   r   r     s   c                 3   s   | ]} | V  qd S r   r   r   updatedr   r   r     s     )!rp   collectionsdefaultdictrN   set	enumerateheapqheapifyr8   heappoprP   rS   rL   rv   rw   timesleepr   r   r<   r	   STATUS_VALIDr   heappushrU   addanyrj   Z
itervaluesr   Z	PollErrortupler   )r   r   r   ZmintimeZmax_attemptsZattemptsZ	exhaustedZwaitingrV   r   rB   rS   rL   r   r&   Zupdated_authzrsr   r   r   poll_and_request_issuance  sJ    




 
  
z Client.poll_and_request_issuancec                 C   s8   t }| jj|d|i|d}|ttjtjj|j	fS )zReturns certificate from URI.

        :param str uri: URI of certificate

        :returns: tuple of the form
            (response, :class:`josepy.util.ComparableX509`)
        :rtype: tuple

        r   )r#   r   )
r   r   r$   r   r   r   r   r   r   r   )r   r   r   r&   r   r   r   	_get_cert  s    
 zClient._get_certc                 C   sL   |  |j\}}d|jkr$td|jd |jkr@t|j|j|dS )zCheck for new cert.

        :param certr: Certificate Resource
        :type certr: `.CertificateResource`

        :returns: Updated Certificate Resource.
        :rtype: `.CertificateResource`

        r   zLocation header missingr6   )r   r   r#   r   rH   rD   textr:   )r   certrr&   r[   r   r   r   
check_cert  s    

zClient.check_certc                 C   s
   |  |S )zRefresh certificate.

        :param certr: Certificate Resource
        :type certr: `.CertificateResource`

        :returns: Updated Certificate Resource.
        :rtype: `.CertificateResource`

        )r   )r   r   r   r   r   refresh  s    zClient.refreshc                 C   sh   g }|j }|dk	rLt||k rL| |\}}|jdi d}|| q
|dk	rdtd||S )a  Fetch chain for certificate.

        :param .CertificateResource certr: Certificate Resource
        :param int max_length: Maximum allowed length of the chain.
            Note that each element in the certificate requires new
            ``HTTP GET`` request, and the length of the chain is
            controlled by the ACME CA.

        :raises errors.Error: if recursion exceeds `max_length`

        :returns: Certificate chain for the Certificate Resource. It is
            a list ordered so that the first element is a signer of the
            certificate from Certificate Resource. Will be empty if
            ``cert_chain_uri`` is ``None``.
        :rtype: `list` of `OpenSSL.crypto.X509` wrapped in `.ComparableX509`

        NrE   r   z'Recursion limit reached. Didn't get {0})	r   lenr   r    r$   appendr   Errorformat)r   r   Z
max_lengthchainr   r&   r[   r   r   r   fetch_chain  s    zClient.fetch_chainc                 C   s   |  ||| jtj S   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.

        )r]   r   r	   rY   r   r[   r\   r   r   r   revoke1  s    zClient.revoke)N)N)N)r   r   )r   )r^   r_   r`   ra   r   RS256r   rq   rs   rt   r|   r   r   r   r   r   r   r   r   r   __classcell__r   r   rm   r   rc      s&   
	

%   
K
rc   c                       s   e Zd ZdZ fddZdd Zdd Zd fd	d
	Zdd Zdd Z	dd Z
dddZdd Zdd Zdd Zdd Zdd Z  ZS )ClientV2zuACME client for a v2 API.

    :ivar messages.Directory directory:
    :ivar .ClientNetwork net: Client network.
    c                    s   t t| j||dd dS )zInitialize.

        :param .messages.Directory directory: Directory Resource
        :param .ClientNetwork net: Client network.
        r   r   N)rl   r   r   )r   r   r   rm   r   r   r   F  s     zClientV2.__init__c                 C   sN   |  | jd |}|jdkr8d|jkr8t|jd| |}|| j_	|S )zRegister.

        :param .NewRegistration new_account:

        :raises .ConflictError: in case the account already exists

        :returns: Registration Resource.
        :rtype: `.RegistrationResource`
        
newAccount   r   )
r)   r   rZ   r#   r   ConflictErrorr$   r'   r   r9   )r   new_accountr&   r*   r   r   r   r   O  s    

zClientV2.new_accountc                 C   s6   || j _| |jd}| j||j|jd| j _| j jS )rr   Nr(   )r   r9   r)   r   r'   r   )r   r*   r&   r   r   r   rs   b  s    

zClientV2.query_registrationNc                    s   |  |}tt| ||S )r5   )_get_v2_accountrl   r   r;   )r   r*   r:   new_regrrm   r   r   r;   q  s    
zClientV2.update_registrationc                 C   sJ   d | j _|jjdd}| | jd |}|jd }|j|d}|| j _|S )NT)Zonly_return_existingr   r   r   )r   r9   r   r:   r)   r   r#   )r   r*   Zonly_existing_regr&   Zupdated_urir   r   r   r   r     s    
zClientV2._get_v2_accountc                 C   s   t jt jj|}t|}g }|D ]}|tjtj	|d q$tj
|d}| | jd |}tj| }g }	|jD ]}
|	| j| |
|
d qxtj||jd|	|dS )zRequest a new Order object from the server.

        :param str csr_pem: A CSR in PEM format.

        :returns: The newly created order.
        :rtype: OrderResource
        r}   )identifiersZnewOrderr   r   )r   r   authorizationscsr_pem)r   r   load_certificate_requestFILETYPE_PEMr    _pyopenssl_cert_or_req_all_namesr   r	   r   r   ZNewOrderr)   r   Orderr!   r"   r   r@   _post_as_getOrderResourcer#   r$   )r   r   r   dnsNamesr   nameorderr&   r   r   r   r   r   r   	new_order  s&    



zClientV2.new_orderc                 C   s(   |  |j}| ||jj|j}||fS r   )r   r   r@   r   rA   r   r   r   r   r     s      zClientV2.pollc                 C   s6   |dkrt j  t jdd }| ||}| ||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

        NZ   rK   )rP   rS   rQ   poll_authorizationsfinalize_order)r   orderrdeadliner   r   r   poll_and_finalize  s    zClientV2.poll_and_finalizec                 C   s   g }|j jD ]L}tj |k r| j| ||d}|j jtjkrL|	| qt
d qqt|t|j jk rvt g }|D ]4}|j jtjkr~|j jD ]}|jdk	r|	| qq~|rt||j|dS )zPoll Order Resource for status.r   rf   N)r   )r   r   rP   rS   r@   r   r<   r	   ZSTATUS_PENDINGr   r   r   r   r   TimeoutErrorr   Z
challengeserrorZValidationErrorr:   )r   r   r   Z	responsesr   rB   ZfailedZchallr   r   r   r     s&    


zClientV2.poll_authorizationsc                 C   s   t jt jj|j}tjt|d}| 	|j
j| tj |k rtd | |j}tj| }|jdk	rt|j|jdk	r6| |jj}|j||dS q6t dS )  Finalize an order and obtain a certificate.

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

        :returns: finalized order
        :rtype: messages.OrderResource

        r   rf   N)r   fullchain_pem)r   r   r   r   r   r	   r   r   r   r)   r   finalizerP   rS   r   r   r   r   r   r!   r"   r   r   ZIssuanceErrorrW   r   r:   r   )r   r   r   r   Zwrapped_csrr&   r   Zcertificate_responser   r   r   r     s     
 


zClientV2.finalize_orderc                 C   s   |  ||| jd S )r   Z
revokeCert)r]   r   r   r   r   r   r     s    zClientV2.revokec                 C   s   t | jdo| jjjS )zGChecks if ACME server requires External Account Binding authentication.meta)r/   r   r   external_account_requiredr   r   r   r   r     s    z"ClientV2.external_account_requiredc                 O   s(   |dd d |dd  }| j ||S )z
        Send GET request using the POST-as-GET protocol.
        :param args:
        :param kwargs:
        :return:
        Nrf   r   )r)   )r   r3   r4   Znew_argsr   r   r   r   	  s    zClientV2._post_as_get)N)N)r^   r_   r`   ra   r   r   rs   r;   r   r   r   r   r   r   r   r   r   r   r   r   rm   r   r   ?  s   		
r   c                   @   sR   e Zd ZdZdd Zdd ZdddZd	d
 Zdd Zdd Z	dd Z
dd ZdS )BackwardsCompatibleClientV2a  ACME client wrapper that tends towards V2-style calls, but
    supports V1 servers.

    .. note:: While this class handles the majority of the differences
        between versions of the ACME protocol, if you need to support an
        ACME server based on version 3 or older of the IETF ACME draft
        that uses combinations in authorizations (or lack thereof) to
        signal that the client needs to complete something other than
        any single challenge in the authorization to make it valid, the
        user of this class needs to understand and handle these
        differences themselves.  This does not apply to either of Let's
        Encrypt's endpoints where successfully completing any challenge
        in an authorization will make it valid.

    :ivar int acme_version: 1 or 2, corresponding to the Let's Encrypt endpoint
    :ivar .ClientBase client: either Client or ClientV2
    c                 C   sP   t j|| }| || _| jdkr>t|||d| _nt	||d| _d S )Nrf   )rg   r   )r   )
r	   rk   r!   r$   r"   _acme_version_from_directoryr   rc   clientr   )r   r   rg   Zserverr   r   r   r   r   '  s
    
z$BackwardsCompatibleClientV2.__init__c                 C   s   t | j|S r   )r0   r   )r   r   r   r   r   __getattr__/  s    z'BackwardsCompatibleClientV2.__getattr__Nc                    s    fdd}| j dkrF| j|}|jdk	rB||j | j|S |S d| jjjkrp|| jjjj |jdd}| j|S dS )zCombined register and agree_tos for V1, new_account for V2

        :param .NewRegistration regr:
        :param callable check_tos_cb: callback that raises an error if
            the check does not work
        c                    s    d k	r |  d S r   r   )Ztoscheck_tos_cbr   r   _assess_tos9  s    zDBackwardsCompatibleClientV2.new_account_and_tos.<locals>._assess_tosrf   Nr   T)Zterms_of_service_agreed)	r   r   rq   r   rt   r   r   r:   r   )r   r*   r   r   r   r   r   new_account_and_tos2  s    


z/BackwardsCompatibleClientV2.new_account_and_tosc                 C   s`   | j dkrTtjtjj|}t|}g }|D ]}|| j	| q.t
j||dS | j|S )a  Request a new Order object from the server.

        If using ACMEv1, returns a dummy OrderResource with only
        the authorizations field filled in.

        :param str csr_pem: A CSR in PEM format.

        :returns: The newly created order.
        :rtype: OrderResource

        :raises errors.WildcardUnsupportedError: if a wildcard domain is
            requested but unsupported by the ACME version

        rf   )r   r   )r   r   r   r   r   r   r   r   r   r   r	   r   r   )r   r   r   r   r   r   r   r   r   r   H  s    

z%BackwardsCompatibleClientV2.new_orderc                 C   s   | j dkr|j}| jttjtjj	||j
}d}tj |k r~z| j|}W q~W q8 tjk
rz   td Y q8X q8|dkrtdtjtjj	|jj }t| }|j|| dS | j||S )r   rf   NzoFailed to fetch chain. You should not deploy the generated certificate, please rerun the command for a new one.)r   )r   r   r   r   r   r   r   r   r   r   r   rP   rS   r   r   r   r   r   r   Zdump_certificater   wrappeddecoder   Zdump_pyopenssl_chainr:   r   )r   r   r   r   r   r   r[   r   r   r   r   a  s4    

 z*BackwardsCompatibleClientV2.finalize_orderc                 C   s   | j ||S r   )r   r   r   r   r   r   r     s    z"BackwardsCompatibleClientV2.revokec                 C   s   t |drdS dS )Nr,   r   rf   )r/   )r   r   r   r   r   r     s    
z8BackwardsCompatibleClientV2._acme_version_from_directoryc                 C   s   | j dkrdS | j S )zChecks if the server requires an external account for ACMEv2 servers.

        Always return False for ACMEv1 servers, as it doesn't use External Account Binding.rf   F)r   r   r   r   r   r   r   r     s    
z5BackwardsCompatibleClientV2.external_account_required)N)r^   r_   r`   ra   r   r   r   r   r   r   r   r   r   r   r   r   r     s   
%r   c                   @   s   e Zd ZdZdZdZdZdZdej	dde
dfd	d
Zdd Zdd Zed ddZdd Zdd ZefddZdd Zdd Zdd ZedfddZdS )!rh   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-pythonc           	      C   sl   || _ || _|| _|| _t | _|| _t | _	|| _
t }|d k	rLt|}| j	d| | j	d| d S )Nzhttp://zhttps://)rg   r9   rd   re   r   _nonces
user_agentrequestsZSessionsession_default_timeoutr   r   Zmount)	r   rg   r9   rd   re   r   timeoutZsource_addressZadapterr   r   r   r     s    
zClientNetwork.__init__c                 C   s(   z| j   W n tk
r"   Y nX d S r   )r   close	Exceptionr   r   r   r   __del__  s    zClientNetwork.__del__c                 C   sz   |r|j dd nd}td| | j|d}|dkrX||d< | jdk	rX| jd |d	< | j|d
< tjj	|f|j ddS )a	  Wrap `JSONDeSerializable` object in JWS.

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

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

        r   )indent    zJWS payload:
%s)rd   noncer   Nr   Zkidrg   )
Z
json_dumpsencoderv   rw   rd   r9   rg   r   ZJWSZsign)r   objr   r   r   jobjr4   r   r   r   _wrap_in_jws  s    

zClientNetwork._wrap_in_jwsc              
   C   s  |j d}z| }W n tk
r0   d}Y nX |jdkrNt|j d|js|dk	r|| jkrrt	
d| ztj|W q tjk
r } zt||fW 5 d}~X Y qX n
t|nD|dk	r|| jkrt	
d| || jkr|dkrtd||S )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 (draft-ietf-appsawg-http-problem-00).
        :raises .ClientError: In case of other networking errors.

        Content-TypeNi  r   z/Ignoring wrong Content-Type (%r) for JSON Errorz<Ignoring wrong Content-Type (%r) for JSON decodable responsez%Unexpected response Content-Type: {0})r#   r$   r"   rO   rZ   r   r   okJSON_ERROR_CONTENT_TYPErv   rw   r	   r   r!   r   DeserializationErrorrH   JSON_CONTENT_TYPEr   )r%   r&   r   Zresponse_ctr   r   r   r   r   _check_response  s:    


"zClientNetwork._check_responsec              
   O   s:  |dkrt d||d  nt d|| | j|d< |di  |d d| j |d| j z| jj||f||}W nf tj	j
k
r } zDd	}t|t|}|d
kr | \}	}
}}td|	|
|W 5 d
}~X Y nX |jdtkrt|j}n|jd}t d|jddd |j D | |S )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.Zverifyr#   z
User-Agentr   zT.*host='(\S*)'.*Max retries exceeded with url\: (\/\w*).*(\[Errno \d+\])([A-Za-z ]*)NzRequesting {0}{1}:{2}r   zutf-8z!Received response:
HTTP %d
%s

%s
c                 S   s   g | ]\}}d  ||qS )z{0}: {1})r   )r   kvr   r   r   r   `  s   z/ClientNetwork._send_request.<locals>.<listcomp>)rv   rw   re   r.   r   r   r   Zrequestr   
exceptionsZRequestExceptionrematchrM   groupsrO   r   r#   r$   r   base64Z	b64encoder   r   rZ   joinitems)r   methodr   r3   r4   r&   eZ	err_regexmZhostpathZ_err_noerr_msgZdebug_contentr   r   r   _send_request%  s<     
$
zClientNetwork._send_requestc                 O   s   | j d||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  r2   r   r   r   heade  s    zClientNetwork.headc                 K   s   | j | jd|f||dS )z$Send GET request and check response.ZGETr   )r  r  )r   r   r   r4   r   r   r   r$   o  s     zClientNetwork.getc              
   C   s   | j |jkrz|j| j  }ztjjd |}W n0 tjk
r^ } zt	||W 5 d }~X Y nX t
d| | j| n
t|d S )Nr   zStoring nonce: %s)REPLAY_NONCE_HEADERr#   r   ZHeader_fieldsr   r   r  r   ZBadNoncerv   rw   r   r   ZMissingNonce)r   r&   r   Zdecoded_noncer   r   r   r   
_add_noncet  s    zClientNetwork._add_noncec                 C   sL   | j sBtd |d kr$| |}n| j| |d d}| | | j  S )NzRequesting fresh noncer  )r   rv   rw   r  r  r  pop)r   r   r-   r&   r   r   r   
_get_nonce  s    

zClientNetwork._get_noncec              
   O   sd   z| j ||W S  tjk
r^ } z0|jdkrLtd| | j || W Y S  W 5 d}~X Y nX dS )zPOST object wrapped in `.JWS` and check response.

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

        ZbadNoncez Retrying request after error:
%sN)
_post_oncer	   r   coderv   rw   )r   r3   r4   r   r   r   r   r1     s    
zClientNetwork.postrf   c           	      K   sh   | dd }| || ||||}|dd|i | jd|fd|i|}| j||d}| | |S )Nr-   r#   r   r  r  r  )r  r   r  r.   r  r  r  )	r   r   r   r   r   r4   r-   r  r&   r   r   r   r    s    
zClientNetwork._post_once)N)r^   r_   r`   ra   r  ZJOSE_CONTENT_TYPEr  r  r   r   DEFAULT_NETWORK_TIMEOUTr   r   r   rb   r  r  r  r$   r  r  r1   r  r   r   r   r   rh     s.    
7@
rh   )3ra   r  r   rP   Zemail.utilsr   r   Zloggingr  sysr   Zjosepyr   r   r   Zrequests.adaptersr   Z!requests_toolbelt.adapters.sourcer   rj   Z	six.movesr   Zacmer   r   r   r	   Zacme.magic_typingr
   r   r   r   Z	getLoggerr^   rv   version_infoZpackagesZurllib3ZcontribZ	pyopensslZinject_into_urllib3AttributeErrorZurllib3.contrib.pyopensslr!  r   objectr   rc   r   r   rh   r   r   r   r   <module>   sV   
 :  Y V 