a
    `$                     @   s  d 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mZ ddlmZmZmZmZ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 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' ddl(m)Z* ddl(m+Z, ddl-m.Z. ddl-m/Z/ ddl-m0Z0 ddl1m2Z3 ddl1mZ4 ddl5m6Z6 dZ7e8e9Z:dd  Z;d!d" Z<dod#d$Z=d%d& Z>d'd( Z?d)d* Z@d+d, ZAd-d. ZBd/d0 ZCd1d2 ZDd3d4 ZEd5d6 ZFdpd7d8ZGdqd9d:ZHd;d< ZId=d> ZJd?d@ ZKdAdB ZLdCdD ZMdEdF ZNdrdGdHZOdIdJ ZPdKdL ZQdMdN ZRdOdP ZSdQdR ZTdSdT ZUdUdV ZVdWdX ZWdYdZ ZXd[d\ ZYd]d^ ZZd_d` Z[dadb Z\dcdd Z]dedf Z^dgdh Z_didj Z`dkdl ZadsdmdnZbdS )tzCertbot main entry point.    )print_functionN)errors)UnionIterableOptionalListTuple)crypto_util)
interfaces)util)account)cert_manager)cli)client)configuration)	constants)eff)hooks)log)renewal)reporter)snap_config)storage)updater)disco)	selection)
filesystem)misc)os)ops)enhancementsz?User chose to cancel the operation and may reinvoke the client.c                 C   s<   | j dksJ | jrdS tjtj}d}|||j dS )zPotentially suggest a donation to support Certbot.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :returns: `None`
    :rtype: None

    renewNzIf you like Certbot, please consider supporting our work by:

Donating to ISRG / Let's Encrypt:   https://letsencrypt.org/donate
Donating to EFF:                    https://eff.org/donate-le

)	verbZstagingzope	component
getUtilityr
   	IReporteradd_messageZLOW_PRIORITY)configreporter_utilmsg r+   8/usr/lib/python3/dist-packages/certbot/_internal/main.py _suggest_donation_if_appropriate2   s    
r-   c                 C   s2   t jtj}| jdksJ |jd|jdd dS )zReports on successful dry run

    :param config: Configuration object
    :type config: interfaces.IConfig

    :returns: `None`
    :rtype: None

    r!   zThe dry run was successful.F)Zon_crashN)r#   r$   r%   r
   r&   r"   r'   ZHIGH_PRIORITY)r(   r)   r+   r+   r,   _report_successful_dry_runF   s
    
r.   c              	   C   s   t | z|durRtdj|jr&dndt|p6| d t	||| | nj|dus^J tdj|jrpdndt|d | 
||}|du rtd	|durt || |j W t | nt | 0 |S )
a!  Authenticate and enroll certificate.

    This method finds the relevant lineage, figures out what to do with it,
    then performs that action. Includes calls to hooks, various reports,
    checks, and requests for user input.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param domains: List of domain names to get a certificate. Defaults to `None`
    :type domains: `list` of `str`

    :param certname: Name of new certificate. Defaults to `None`
    :type certname: str

    :param lineage: Certificate lineage object. Defaults to `None`
    :type lineage: storage.RenewableCert

    :returns: the issued certificate or `None` if doing a dry run
    :rtype: storage.RenewableCert or None

    :raises errors.Error: if certificate could not be obtained

    Nz{action} for {domains}z-Simulating renewal of an existing certificatez Renewing an existing certificate)actiondomainsz Simulating a certificate requestzRequesting a certificateFz!Certificate could not be obtained)r   Zpre_hookdisplay_utilnotifyformatdry_runZsummarize_domain_listnamesr   
renew_certZobtain_and_enroll_certificater   ErrorZdeploy_hooklive_dirZ	post_hook)	le_clientr(   r0   certnamelineager+   r+   r,   _get_and_save_certV   s6    


r<   c                 C   sR   t drt dsN| j }|j }||krNd}||j||}t|dS )a|  
    This function ensures that the user will not implicitly migrate an existing key
    from one type to another in the situation where a certificate for that lineage
    already exist and they have not provided explicitly --key-type and --cert-name.
    :param config: Current configuration provided by the client
    :param cert: Matching certificate that could be renewed
    key_typer:   zAre you trying to change the key type of the certificate named {0} from {1} to {2}? Please provide both --cert-name and --key-type on the command line confirm the change you are trying to make.N)	r   Z
set_by_clir=   upperZprivate_key_typer3   Zlineagenamer   r7   )r(   certZnew_key_typeZcur_key_typer*   r+   r+   r,   %_handle_unexpected_key_type_migration   s    	

r@   c              
   C   s   t | | d| }dj|jj|d|tjd}| js`| j	s`t
jtjj|dddddrhd	|fS td
j|tjd dtjdd tjd ttdS )a  Figure out what to do if a previous cert had a subset of the names now requested

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param domains: List of domain names
    :type domains: `list` of `str`

    :param cert: Certificate object
    :type cert: storage.RenewableCert

    :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname
              action can be: "newcert" | "renew" | "reinstall"
    :rtype: `tuple` of `str`

    z, a   You have an existing certificate that contains a portion of the domains you requested (ref: {0}){br}{br}It contains these names: {1}{br}{br}You requested these names for the new certificate: {2}.{br}{br}Do you want to expand and replace this existing certificate with the new certificate?brZExpandCancelz--expandTZcli_flagforce_interactiver!   zTo obtain a new certificate that contains these names without replacing your existing certificate for {0}, you must use the --duplicate option.{br}{br}For example:{br}{br}{1} --duplicate {2}r       N)r@   joinr5   r3   
configfilefilenamer   linesepexpandZrenew_by_defaultr#   r$   r%   r
   IDisplayyesnor1   r2   sysargvr   r7   USER_CANCELLED)r(   r0   r?   existingquestionr+   r+   r,   _handle_subset_cert_request   s2    

	rT   c                 C   s   t | | | sd|fS t| |r.d|fS | jr<d|fS dj|jjtj	d}| j
dkr`d}n| j
dkrnd}|d	g}tjtj}|j||d
dd}|d
 tjkrtd|d d
krd|fS |d dkrd|fS tddS )a  Figure out what to do if a lineage has the same names as a previously obtained one

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param lineage: Certificate lineage object
    :type lineage: storage.RenewableCert

    :returns: Tuple of (str action, cert_or_None) as per _find_lineage_for_domains_and_certname
              action can be: "newcert" | "renew" | "reinstall"
    :rtype: `tuple` of `str`

    	reinstallr!   zYou have an existing certificate that has exactly the same domains or certificate name you requested and isn't close to expiry.{br}(ref: {0}){br}{br}What would you like to do?rA   runz.Attempt to reinstall this existing certificatecertonlyz%Keep the existing certificate for nowzBRenew & replace the certificate (may be subject to CA rate limits)r   T)defaultrE   z.Operation canceled. You may re-run the client.rG   zThis is impossibleN)r@   Zensure_deployedr   Zshould_renewrU   r3   rI   rJ   r   rK   r"   r#   r$   r%   r
   rM   Zmenur1   ZCANCELr   r7   AssertionError)r(   r;   rS   Zkeep_optchoicesdisplayZresponser+   r+   r,   _handle_identical_cert_request   s>    



r\   c                 C   sX   | j r
dS t| |\}}|du r.|du r.dS |dur@t| |S |durTt| ||S dS )a  Determine whether there are duplicated names and how to handle
    them (renew, reinstall, newcert, or raising an error to stop
    the client run if the user chooses to cancel the operation when
    prompted).

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param domains: List of domain names
    :type domains: `list` of `str`

    :returns: Two-element tuple containing desired new-certificate behavior as
              a string token ("reinstall", "renew", or "newcert"), plus either
              a RenewableCert instance or `None` if renewal shouldn't occur.
    :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None`

    :raises errors.Error: If the user would like to rerun the client again.

    ZnewcertNNNN)Z	duplicater   Zfind_duplicative_certsr\   rT   )r(   r0   Zident_names_certZsubset_names_certr+   r+   r,   _find_lineage_for_domains  s    
r_   c                 C   s.   t | ||\}}|dkr"td |dk|fS )aW  Finds an existing certificate object given domains and/or a certificate name.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param domains: List of domain names
    :type domains: `list` of `str`

    :param certname: Name of certificate
    :type certname: str

    :returns: Two-element tuple of a boolean that indicates if this function should be
              followed by a call to fetch a certificate from the server, and either a
              RenewableCert instance or None.
    :rtype: `tuple` of `bool` and :class:`storage.RenewableCert` or `None`

    rU   z Keeping the existing certificate)&_find_lineage_for_domains_and_certnameloggerinfo)r(   r0   r:   r/   r;   r+   r+   r,   
_find_cert9  s    
rc   c                 C   s   |st | |S t| |}|rh|r^tt| |t|kr^t| | t| |||  d|fS t| |S |rpdS t	
d|dS )a  Find appropriate lineage based on given domains and/or certname.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param domains: List of domain names
    :type domains: `list` of `str`

    :param certname: Name of certificate
    :type certname: str

    :returns: Two-element tuple containing desired new-certificate behavior as
              a string token ("reinstall", "renew", or "newcert"), plus either
              a RenewableCert instance or None if renewal should not occur.

    :rtype: `tuple` of `str` and :class:`storage.RenewableCert` or `None`

    :raises errors.Error: If the user would like to rerun the client again.

    r!   r]   z}No certificate with name {0} found. Use -d to specify domains, or run certbot certificates to see possible certificate names.N)r_   r   lineage_for_certnamesetdomains_for_certnamer@   _ask_user_to_confirm_new_namesr5   r\   r   ConfigurationErrorr3   )r(   r0   r:   r;   r+   r+   r,   r`   Q  s"    


r`   c                 C   s@   t t| t| }t t|t|  }|  |  ||fS )zWGet lists of items removed from `before`
    and a lists of items added to `after`
    )listre   sort)ZafterZbeforeaddedremovedr+   r+   r,   _get_added_removed|  s
    rm   c                 C   s(   |s
d}ndd | }|j| tjdS )z%Format list with given character
    z
{br}(None)z	{br}{ch} )ZchrB   )rH   r3   r   rK   )	characterZstringsZ	formattedr+   r+   r,   _format_list  s    ro   c                 C   sf   | j r
dS t||\}}dj|td|td|tjd}tjt	j
}|j|dddd	sbtd
dS )a  Ask user to confirm update cert certname to contain new_domains.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param new_domains: List of new domain names
    :type new_domains: `list` of `str`

    :param certname: Name of certificate
    :type certname: str

    :param old_domains: List of old domain names
    :type old_domains: `list` of `str`

    :returns: None
    :rtype: None

    :raises errors.ConfigurationError: if cert name and domains mismatch

    NzYou are updating certificate {0} to include new domain(s): {1}{br}{br}You are also removing previously included domain(s): {2}{br}{br}Did you intend to make this change?+-rA   zUpdate certificaterC   T)rX   z2Specified mismatched certificate name and domains.)Zrenew_with_new_domainsrm   r3   ro   r   rK   r#   r$   r%   r
   rM   rN   r   rh   )r(   Znew_domainsr:   Zold_domainsrk   rl   r*   objr+   r+   r,   rg     s    rg   c                 C   sR   d}| j }| jr| j}n|r(t| |}|s8t||}|sJ|sJtd||fS )a	  Retrieve domains and certname from config or user input.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param installer: Installer object
    :type installer: interfaces.IInstaller

    :param `str` question: Overriding default question to ask the user if asked
        to choose from domain names.

    :returns: Two-part tuple of domains and certname
    :rtype: `tuple` of list of `str` and `str`

    :raises errors.Error: Usage message, if parameters are not used correctly

    NzPlease specify --domains, or --installer that will help in domain names autodiscovery, or --cert-name for an existing certificate name.)r:   r0   r   rf   display_opsZchoose_namesr   r7   )r(   	installerrS   r0   r:   r+   r+   r,   _find_domains_or_certname  s    
ru   c           	      C   s   | j rt|  dS |r|s"J dt| }tjtj	}| j
dkrLdnd}|rddj|tjdnd}dj|||tj|tjd}|||j dS )	aD  Reports the creation of a new certificate to the user.

    :param cert_path: path to certificate
    :type cert_path: str

    :param fullchain_path: path to full chain
    :type fullchain_path: str

    :param key_path: path to private key, if available
    :type key_path: str

    :returns: `None`
    :rtype: None

    Nz No certificates saved to report.rV   z with the "certonly" option z+Your key file has been saved at:{br}{0}{br}rA   a  Congratulations! Your certificate and chain have been saved at:{br}{0}{br}{1}Your certificate will expire on {2}. To obtain a new or tweaked version of this certificate in the future, simply run {3} again{4}. To non-interactively renew *all* of your certificates, run "{3} renew")r4   r.   r	   ZnotAfterdater#   r$   r%   r
   r&   r"   r3   r   rK   r   Zcli_commandr'   ZMEDIUM_PRIORITY)	r(   	cert_pathfullchain_pathkey_pathZexpiryr)   Z
verbswitchZprivkey_statementr*   r+   r+   r,   _report_new_cert  s$    r{   c                    s    fdd}t  }d} j dur2| j }n| }t|dkrRt|}nt|dkrh|d }n~ jdu r jst	  _z"t
j ||d\}}td W n@ tjy    Y n, tjy   tjdd	d
 tdY n0 |j _ ||fS )a  Determine which account to use.

    If ``config.account`` is ``None``, it will be updated based on the
    user input. Same for ``config.email``.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :returns: Account and optionally ACME client API (biproduct of new
        registration).
    :rtype: tuple of :class:`certbot._internal.account.Account` and :class:`acme.client.Client`

    :raises errors.Error: If unable to register an account with ACME server

    c                    sD    j r
dS d| }tjtj}|j|ddd}|s@t	dd S )NTzpPlease read the Terms of Service at {0}. You must agree in order to register with the ACME server. Do you agree?z--agree-tosrD   z?Registration cannot proceed without accepting Terms of Service.)
Ztosr3   r#   r$   r%   r
   rM   rN   r   r7   )Zterms_of_servicer*   rr   resultr(   r+   r,   _tos_cb  s    z#_determine_account.<locals>._tos_cbNrG   r   )Ztos_cbzAccount registered.rv   T)exc_infoz.Unable to register an account with ACME server)r   AccountFileStorageloadfind_alllenrs   Zchoose_accountemailregister_unsafely_without_email	get_emailr   registerr1   r2   r   ZMissingCommandlineFlagr7   ra   debugid)r(   r~   account_storageacmeaccaccountsr+   r}   r,   _determine_account  s4    





r   c              
      s  t jtj}| j}|du r4d}|j|ddddd}|s<dS | jsFJ | jsXt	
| | _ttt| | j| | j z&t	|  fddgd	d d
d  W nh tjy   td  Y dS  ty } z.d}|| j| j |}t|W Y d}~n
d}~0 0 t	|  dS )a  Does the user want to delete their now-revoked certs? If run in non-interactive mode,
    deleting happens automatically.

    :param config: parsed command line arguments
    :type config: interfaces.IConfig

    :returns: `None`
    :rtype: None

    :raises errors.Error: If anything goes wrong, including bad user input, if an overlapping
        archive dir is found for the specified lineage, etc ...
    Nz{Would you like to delete the certificate(s) you just revoked, along with all earlier and later versions of the certificate?zYes (recommended)ZNoT)	yes_labelno_labelrE   rX   c                    s    S Nr+   xZarchive_dirr+   r,   <lambda>k      z(_delete_if_appropriate.<locals>.<lambda>c                 S   s   | j S r   r   r   r+   r+   r,   r   l  r   c                 S   s   | S r   r+   r   r+   r+   r,   r   l  r   zhNot deleting revoked certificates due to overlapping archive dirs. More than one certificate is using %sz_config.default_archive_dir: {0}, config.live_dir: {1}, archive_dir: {2},original exception: {3})r#   r$   r%   r
   rM   Zdelete_after_revokerN   rx   r:   r   Zcert_path_to_lineager   Zfull_archive_path	configobjZ	ConfigObjZrenewal_file_for_certnameZmatch_and_check_overlapsr   ZOverlappingMatchFoundra   warning	Exceptionr3   Zdefault_archive_dirr8   r7   delete)r(   r[   Zattempt_deletionr*   er+   r   r,   _delete_if_appropriateF  s<    

 r   c                 C   s>   |dur"t | \}}td| nd\}}tj| ||||dS )ax  Initialize Let's Encrypt Client

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param authenticator: Acme authentication handler
    :type authenticator: Optional[interfaces.IAuthenticator]
    :param installer: Installer object
    :type installer: interfaces.IInstaller

    :returns: client: Client object
    :rtype: client.Client

    NzPicked account: %rr^   r   )r   ra   r   r   Client)r(   authenticatorrt   r   r   r+   r+   r,   _init_le_clientz  s
    r   c                 C   s   t | }| }|sdS tjtjj}d}||dddd}|sFdS t	| \}}t
j| |dd|d	}	|	j|j t | }
|
| j  td
 dS )a  Deactivate account on server

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    z.Could not find existing account to deactivate.zCAre you sure you would like to irrevocably deactivate your account?Z
DeactivateZAbortT)r   r   rX   zDeactivation aborted.Nr   zAccount deactivated.)r   r   r   r#   r$   r%   r
   rM   rN   r   r   r   r   Zdeactivate_registrationregrr   r1   r2   )r(   unused_pluginsr   r   rN   promptZwants_deactivater   r   	cb_clientZaccount_filesr+   r+   r,   
unregister  s$    


r   c                 C   s&   t | }| }|rdS t|  dS )a2  Create accounts on the server.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None` or a string indicating and error
    :rtype: None or str

    zmThere is an existing account; registration of a duplicate account with this command is currently unsupported.N)r   r   r   r   )r(   r   r   r   r+   r+   r,   r     s    
r   c           	      C   s   t | }| }|sdS | jdu r8| js8tjdd| _t| \}}tj	| |dd|d}d}| jrxdd | j
d	D }|jj}|j|jj|jjj|d
d|_|jj|d|_|||j | jstd nt| | td| j dS )a2  Modify accounts on the server.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None` or a string indicating and error
    :rtype: None or str

    z-Could not find an existing account to update.NF)Zoptionalr   r+   c                 S   s   g | ]}d | qS )zmailto:r+   ).0r   r+   r+   r,   
<listcomp>  r   z"update_account.<locals>.<listcomp>,)Zcontact)body)urizFAny contact information associated with this account has been removed.z'Your e-mail address was updated to {0}.)r   r   r   r   r   rs   r   r   r   r   splitr   r   r   Zupdate_registrationupdater   Zupdate_regrr1   r2   r   Zprepare_subscriptionr3   )	r(   r   r   r   r   r   r   Zacc_contactsZprev_regr_urir+   r+   r,   update_account  s,    

r   c                 C   sF   |r|n| }|j dusJ |||j|j |j|j |||j dS )a  Install a cert

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param le_client: Client object
    :type le_client: client.Client

    :param domains: List of domains
    :type domains: `list` of `str`

    :param lineage: Certificate lineage object. Defaults to `None`
    :type lineage: storage.RenewableCert

    :returns: `None`
    :rtype: None

    N)rx   Zdeploy_certificaterz   
chain_pathry   enhance_config)r(   r9   r0   r;   Zpath_providerr+   r+   r,   _install_cert  s    
r   c           
   
   C   s(  zt | |d\}}W n. tjyD } zt|W  Y d}~S d}~0 0 | joP| j}| jsx|sxd}tj	| dd|dd | _t
| |std| jrt| } nt
| rtd| jr| jrt|  t| |\}}t| d|d	}t| || n
td
t
| r$t| | j}	t
|	|||  dS )a   Install a previously obtained cert in a server.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    installNz,Which certificate would you like to install?FZallow_multipleZcustom_promptr   VOne ore more of the requested enhancements are not supported by the selected installerzLOne or more of the requested enhancements require --cert-name to be providedr   rt   zPath to certificate or key was not defined. If your certificate is managed by Certbot, please use --cert-name to define which certificate you would like to install.)plug_selchoose_configurator_pluginsr   PluginSelectionErrorstrrz   rx   r:   r   get_certnamesr    are_supportedNotSupportedError_populate_from_certnameare_requestedrh   _check_certificate_and_keyru   r   r   rd   enable)
r(   pluginsrt   _r   Zcustom_certcertname_questionr0   r9   r;   r+   r+   r,   r   (  s:    





r   c                 C   sZ   t | | j}|s| S | js&|j| j_| js6|j| j_| jsF|j| j_| jsV|j| j_| S )zfHelper function for install to populate missing config values from lineage
    defined by --cert-name.)r   rd   r:   rz   	namespacerx   r   ry   )r(   r;   r+   r+   r,   r   c  s    



r   c                 C   sP   t jt| js&td| jt jt| j	sLtd| j	d S )Nz-Error while reading certificate from path {0}z-Error while reading private key from path {0})
r   pathisfiler   realpathrx   r   rh   r3   rz   r}   r+   r+   r,   r   t  s    r   c                 C   s   t d| j | jdu rg n| j}| |}t d| tjtjt	j
jdd}| jsr| jsr|t| dS ||  ||}t d| | js|t| dS |  | }t d| |t| dS )zList server software plugins.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    zExpected interfaces: %sNzFiltered plugins: %rFpausezVerified plugins: %rzPrepared plugins: %s)ra   r   ifacesZvisible	functoolspartialr#   r$   r%   r
   rM   notificationZinitZpreparer   Zverify	available)r(   r   r   Zfilteredr2   Zverifiedr   r+   r+   r,   plugins_cmd{  s,    


r   c              
      sb  g d}t  fdd|D }t sL|sLd}t|tjd  tdzt	
 |d\}}W n. tjy } zt|W  Y d}~S d}~0 0 t |std	d
}tj dd|dd  _t  j}	 jr|	}
n d}t|	|}
|
 stdt  j} js|j _|rBt d|d}|j|
 jdd t r^t||
|  dS )a  Add security enhancements to existing configuration

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    )ZhstsZredirectZuirZstaplec                 3   s   | ]}t  |V  qd S r   )getattr)r   Zenhr}   r+   r,   	<genexpr>  r   zenhance.<locals>.<genexpr>z|Please specify one or more enhancement types to configure. To list the available enhancement types, run:

%s --help enhance
r   z#No enhancements requested, exiting.enhanceNr   zFWhich certificate would you like to use to enhance your configuration?Fr   zJWhich domain names would you like to enable the selected enhancements for?zAUser cancelled the domain selection. No domains defined, exiting.r   )Zredirect_default)anyr    r   ra   r   rO   rP   r   ZMisconfigurationErrorr   r   r   r   r   r   r   r   r:   rf   noninteractive_moders   Zchoose_valuesr7   rd   r   r   r   r   )r(   r   Zsupported_enhancementsZoldstyle_enhr*   rt   r   r   r   Zcert_domainsr0   Zdomain_questionr;   r9   r+   r}   r,   r     sF    


r   c                 C   s   t | j| j| | dS )a  Rollback server configuration changes made during install.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    N)r   rollbackrt   Zcheckpoints)r(   r   r+   r+   r,   r     s    r   c                 C   s   t |  dS )a  Update the certificate file family symlinks

    Use the information in the config file to make symlinks point to
    the correct archive directory.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    N)r   Zupdate_live_symlinksr(   r   r+   r+   r,   update_symlinks  s    r   c                 C   s   t |  dS )aO  Rename a certificate

    Use the information in the config file to rename an existing
    lineage.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    N)r   Zrename_lineager   r+   r+   r,   rename  s    r   c                 C   s   t |  dS )aO  Delete a certificate

    Use the information in the config file to delete an existing
    lineage.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    N)r   r   r   r+   r+   r,   r     s    r   c                 C   s   t |  dS )a#  Display information about certs configured with Certbot

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    N)r   certificatesr   r+   r+   r,   r   #  s    r   c              
   C   s^  d | _ | _| jdu r.| jr.t| | j| _n| jr@| jrJ| jrJtd| jdurt	
d| jd | jd  t| jd | jd  tj| jd }t| |}n0t	
d| jd  t| \}}t| |j|j}t| jd d }t	
d| j z |t|| j t|  W n0 tjyH } zt|W  Y d}~S d}~0 0 t| jd  dS )aH  Revoke a previously obtained certificate.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None` or string indicating error in case of error
    :rtype: None or str

    NzCError! Exactly one of --cert-path or --cert-name must be specified!z$Revoking %s using certificate key %sr   rG   zRevoking %s using Account KeyzReason code for revocation: %s)rt   r   rx   r:   r   Zcert_path_for_cert_namer   r7   rz   ra   r   r	   Zverify_cert_matches_priv_keyjoseZJWKr   r   Zacme_from_config_keyr   keyr   Zpyopenssl_load_certificatereasonrevokeZComparableX509r   acme_errorsZClientErrorr   rs   Zsuccess_revocation)r(   r   r   r   r   r   r?   r   r+   r+   r,   r   4  s0    

r   c              
   C   sJ  zt | |d\}}W n. tjyD } zt|W  Y d}~S d}~0 0 t| |s\tdt| ||}t	| |\}}t
| ||\}}	|	}
|rt|| |||	}
|
r|
jnd}|
r|
jnd}|
r|
jnd}|rt| ||| t| |||
 t| r
|
r
t|
|||  |	du s|s&t| n
t| t|  t| |j dS )zObtain a certificate and install.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    rV   Nr   )r   r   r   r   r   r    r   r   r   ru   rc   r<   rx   ry   rz   r{   r   r   r   rs   Zsuccess_installationZsuccess_renewalr-   r   handle_subscriptionr   )r(   r   rt   r   r   r9   r0   r:   should_get_certr;   Znew_lineagerx   ry   rz   r+   r+   r,   rV   a  s8    

rV   c              	   C   sn   | j \}}||\}}| jr0td| j dS |||tj	| jtj	| j
tj	| j\}}}||fS )a  Obtain a cert using a user-supplied CSR

    This works differently in the CSR case (for now) because we don't
    have the privkey, and therefore can't construct the files for a lineage.
    So we just save the cert & chain to disk :/

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param client: Client object
    :type client: client.Client

    :returns: `cert_path` and `fullchain_path` as absolute paths to the actual files
    :rtype: `tuple` of `str`

    z*Dry run: skipping saving certificate to %sr^   )Z
actual_csrZobtain_certificate_from_csrr4   ra   r   rx   Zsave_certificater   r   normpathr   ry   )r(   r9   csrr   r?   chainrx   ry   r+   r+   r,   _csr_get_and_save_cert  s    

r   c           	   
   C   s   zt | |d\}}W n4 tjyJ } ztd|  W Y d}~n
d}~0 0 t| ||}t|| |d}tj	
tjj}|du r|d|jdd n.t| || |  |d| j|jdd dS )	a  Renew & save an existing cert. Do not install it.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :param lineage: Certificate lineage object
    :type lineage: storage.RenewableCert

    :returns: `None`
    :rtype: None

    :raises errors.PluginSelectionError: MissingCommandlineFlag if supplied parameters do not pass

    rW   'Could not choose appropriate plugin: %sN)r;   z9new certificate deployed without reload, fullchain is {0}Fr   zDnew certificate deployed with reload of {0} server; fullchain is {1})r   r   r   r   ra   rb   r   r<   r#   r$   r%   r
   rM   r   r3   Z	fullchainr   Zrun_renewal_deployerZrestartrt   )	r(   r   r;   rt   authr   r9   Zrenewed_lineager2   r+   r+   r,   r6     s*    r6   c              
   C   s8  zt | |d\}}W n4 tjyJ } ztd|  W Y d}~n
d}~0 0 t| ||}| jrt| |\}}t	| || t
|  t| |j dS t| |\}}	t| ||	\}
}|
stjtjj}|ddd dS t|| ||	|}|r|jnd}|r|jnd}|r|jnd}t	| ||| t
|  t| |j dS )at  Authenticate & obtain cert, but do not install it.

    This implements the 'certonly' subcommand.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param plugins: List of plugins
    :type plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    :raises errors.Error: If specified plugin could not be used

    rW   r   Nz5Certificate not yet due for renewal; no action taken.Fr   )r   r   r   r   ra   rb   r   r   r   r{   r-   r   r   r   ru   rc   r#   r$   r%   r
   rM   r   r<   rx   ry   rz   )r(   r   rt   r   r   r9   rx   ry   r0   r:   r   r;   r2   rz   r+   r+   r,   rW     s2    rW   c                 C   s&   zt |  W t  n
t  0 dS )a  Renew previously-obtained certificates.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :param unused_plugins: List of plugins (deprecated)
    :type unused_plugins: plugins_disco.PluginsRegistry

    :returns: `None`
    :rtype: None

    N)r   Zhandle_renewal_requestr   Zrun_saved_post_hooksr   r+   r+   r,   r!     s    r!   c                 C   sV   t | jtj| j t | jtj| j | j| j| j	f}|D ]}t j
|| jd q<dS )zCreate or verify existence of config, work, and hook directories.

    :param config: Configuration object
    :type config: interfaces.IConfig

    :returns: `None`
    :rtype: None

    )strictN)r   Zset_up_core_dirZ
config_dirr   ZCONFIG_DIRS_MODEZstrict_permissionsZwork_dirZrenewal_pre_hooks_dirZrenewal_deploy_hooks_dirZrenewal_post_hooks_dirZmake_or_verify_dir)r(   Z	hook_dirsZhook_dirr+   r+   r,   make_or_verify_needed_dirs*  s    
r   c                 C   sT   | j r d| _tttjd}n$| jr4ttj}nt	tj| j
}tj| dS )zSet the displayer

    :param config: Configuration object
    :type config: interfaces.IConfig

    :returns: `None`
    :rtype: None

    TwN)quietr   r1   ZNoninteractiveDisplayopenr   devnullrO   stdoutZFileDisplayrE   r#   r$   provideUtility)r(   Z	displayerr+   r+   r,   set_displayer>  s    
r   c                 C   s  | st jdd } t  tjddkr4t| } t	j
 }tdtj tdt jd  td|  td	| t|| }t|}tj| t  zt| t| W n  tjy   |jtkr҂ Y n0 t| t !|}tj| t"#|j$ |||S )
zRun Certbot.

    :param cli_args: command line to Certbot, defaults to ``sys.argv[1:]``
    :type cli_args: `list` of `str`

    :returns: value for `sys.exit` about the exit status of Certbot
    :rtype: `str` or `int` or `None`

    rG   NZCERTBOT_SNAPPEDTruezcertbot version: %sz#Location of certbot entry point: %sr   zArguments: %rzDiscovered plugins: %r)%rO   rP   r   Zpre_arg_parse_setupr   environgetr   Zprepare_envplugins_discoZPluginsRegistryr   ra   r   certbot__version__r   Zprepare_and_parse_argsr   ZNamespaceConfigr#   r$   r   r   Z+raise_for_non_administrative_windows_rightsZpost_arg_parse_setupr   r   r7   funcr   r   r   ZReporterr   Zatexit_registerZprint_messages)Zcli_argsr   argsr(   Zreportr+   r+   r,   mainT  s2    






r   )NNN)N)N)N)N)c__doc__Z
__future__r   r   Zlogging.handlersZloggingrO   r   Zjosepyr   Zzope.componentr#   r   r   r   Zacme.magic_typingr   r   r   r   r   r   r	   r
   r   Zcertbot._internalr   r   r   r   r   r   r   r   r   r   r   r   r   r   Zcertbot._internal.pluginsr   r   r   r   Zcertbot.compatr   r   r   Zcertbot.displayr   rs   r1   Zcertbot.pluginsr    rQ   Z	getLogger__name__ra   r-   r.   r<   r@   rT   r\   r_   rc   r`   rm   ro   rg   ru   r{   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rV   r   r6   rW   r!   r   r   r   r+   r+   r+   r,   <module>   s   

;37(+
&
)
*;4(2
;';-:+4