U
    ÝÁ]ú³  ã                   @   s¦  d 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	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mZ ddlmZ e e¡ZdZdZe ej ¡Z!dZ"dd„ Z#dd„ Z$dd„ Z%d7dd„Z&e '¡ fdd„Z(dd„ Z)dd„ Z*dd„ Z+d d!„ Z,d8d#d$„Z-d%d&„ Z.d'd(„ Z/d)d*„ Z0d+d,„ Z1d-d.„ Z2d/d0„ Z3d1d2„ Z4d3d4„ Z5G d5d6„ d6e6ƒZ7dS )9zRenewable certificates storage.é    N)Úcli)Ú	constants)Úcrypto_util)Úerror_handler)Úerrors)Úutil)Úos)Ú
filesystem)Úcommon)Údisco)ÚcertÚprivkeyÚchainÚ	fullchainÚREADMEi€  c                 C   s"   t   tj | jd¡¡}| ¡  |S )zÉBuild a list of all renewal configuration files.

    :param certbot.interfaces.IConfig config: Configuration object

    :returns: list of renewal configuration files
    :rtype: `list` of `str`

    z*.conf)Úglobr   ÚpathÚjoinÚrenewal_configs_dirÚsort)ÚconfigÚresult© r   ú1/usr/lib/python3/dist-packages/certbot/storage.pyÚrenewal_conf_files"   s    	r   c                 C   s8   t j | jd |¡¡}t j |¡s4t d ||¡¡‚|S )z;Return /path/to/certname.conf in the renewal conf directoryz{0}.confz2No certificate found with name {0} (expected {1}).)r   r   r   r   ÚformatÚexistsr   ÚCertStorageError)r   Úcertnamer   r   r   r   Úrenewal_file_for_certname/   s     ÿr   c              	   C   s<   t | |ƒ}t |¡d }t|ƒ}|| ¡ f}W 5 Q R X |S )zÅ If `--cert-name` was specified, but you need a value for `--cert-path`.

    :param `configuration.NamespaceConfig` config: parsed command line arguments
    :param str cert_name: cert name.

    r   )r   Ú	configobjÚ	ConfigObjÚopenÚread)r   Z	cert_nameZcert_name_implied_confÚfullchain_pathÚfÚ	cert_pathr   r   r   Úcert_path_for_cert_name8   s
    

r'   c                 C   s*   t  tj¡}| | dk	r| nt  ¡ ¡ |S )z?Merge supplied config, if provided, on top of builtin defaults.N)r    r!   r   ÚRENEWER_DEFAULTSÚmerge)r   Zdefaults_copyr   r   r   Úconfig_with_defaultsF   s    r*   c                 C   s4   |  ¡  ¡ r|d7 }| jptj}|j|| |dd S )a‚  Parse the time specified time interval, and add it to the base_time

    The interval can be in the English-language format understood by
    parsedatetime, e.g., '10 days', '3 weeks', '6 months', '9 hours', or
    a sequence of such intervals like '6 months 1 week' or '3 days 12
    hours'. If an integer is found with no associated unit, it is
    interpreted by default as a number of days.

    :param datetime.datetime base_time: The time to be added with the interval.
    :param str interval: The time interval to parse.

    :returns: The base_time plus the interpretation of the time interval.
    :rtype: :class:`datetime.datetime`z days)Útzinfor   )ÚstripÚisdigitr+   ÚpytzÚUTCZparseDT)Z	base_timeÚintervalZ
textparserr+   r   r   r   Úadd_time_intervalM   s    r1   c              	   C   s
  t  | ¡}tj|d< ||d< tD ]}|| ||< q d|krPi |d< ddg|jd< |d  |¡ |d  ¡ D ]}||krj|d |= qjd|kr tj	d }d| g|_
t d|¡ t|d	ƒ ¡  tj | ¡rät t | ¡j¡}	t ||	¡ t|d
ƒ}
|j|
d W 5 Q R X |S )a  Writes a renewal config file with the specified name and values.

    :param str o_filename: Absolute path to the previous version of config file
    :param str n_filename: Absolute path to the new destination of config file
    :param str archive_dir: Absolute path to the archive directory
    :param dict target: Maps ALL_FOUR to their symlink paths
    :param dict relevant_data: Renewal configuration options to save

    :returns: Configuration object for the new config file
    :rtype: configobj.ConfigObj

    ÚversionÚarchive_dirÚrenewalparamsÚ z#Options used in the renewal processÚrenew_before_expiryzrenew_before_expiry = zWriting new config %s.ÚaÚwb)Zoutfile)r    r!   ÚcertbotÚ__version__ÚALL_FOURZcommentsÚupdateÚkeysr   r(   Zinitial_commentÚloggerÚdebugr"   Úcloser   r   r   ÚstatÚS_IMODEÚlstatÚst_moder	   ÚchmodÚwrite)Z
o_filenameZ
n_filenamer3   ÚtargetZrelevant_datar   ÚkindÚkÚdefault_intervalZcurrent_permissionsr%   r   r   r   Úwrite_renewal_confige   s2    

ÿ

rK   c                 C   s^   t || ƒ}t ||ƒ}tj |¡r*t d¡‚zt ||¡ W n tk
rX   t d¡‚Y nX dS )z”Renames cli_config.certname's config to cli_config.new_certname.

    :param .NamespaceConfig cli_config: parsed command line
        arguments
    z+The new certificate name is already in use.z=Please specify a valid filename for the new certificate name.N)	Ú renewal_filename_for_lineagenamer   r   r   r   ZConfigurationErrorr	   ÚreplaceÚOSError)Z	prev_nameÚnew_nameÚ
cli_configZprev_filenameZnew_filenamer   r   r   Úrename_renewal_config™   s    


rQ   c                 C   s\   t || ƒ}|d }tj |¡r(t |¡ tt|jƒƒ}t|||||ƒ t	 
||¡ t |¡S )a²  Modifies lineagename's config to contain the specified values.

    :param str lineagename: Name of the lineage being modified
    :param str archive_dir: Absolute path to the archive directory
    :param dict target: Maps ALL_FOUR to their symlink paths
    :param .NamespaceConfig cli_config: parsed command line
        arguments

    :returns: Configuration object for the updated config file
    :rtype: configobj.ConfigObj

    z.new)rL   r   r   r   ÚunlinkÚrelevant_valuesÚvarsÚ	namespacerK   r	   rM   r    r!   )Úlineagenamer3   rG   rP   Úconfig_filenameZtemp_filenameÚvaluesr   r   r   Úupdate_configuration«   s    

rY   c                 C   sb   zt  | ¡}W n$ tk
r2   t d | ¡¡‚Y nX t j |¡sVt j t j 	| ¡|¡}t j 
|¡S )zÛGet an absolute path to the target of link.

    :param str link: Path to a symbolic link

    :returns: Absolute path to the target of link
    :rtype: str

    :raises .CertStorageError: If link does not exists.

    zExpected {0} to be a symlink)r   ÚreadlinkrN   r   r   r   r   Úisabsr   ÚdirnameÚabspath)ÚlinkrG   r   r   r   Úget_link_targetÇ   s    ÿ
r_   Fc              	   C   sD   d}|rd}t | dƒ$}t d| ¡ | dj|d¡ W 5 Q R X d S )Nr5   z[cert name]/ÚwzWriting README to %s.aÔ  This directory contains your keys and certificates.

`{prefix}privkey.pem`  : the private key for your certificate.
`{prefix}fullchain.pem`: the certificate file used in most server software.
`{prefix}chain.pem`    : used for OCSP stapling in Nginx >=1.3.7.
`{prefix}cert.pem`     : will break many server configurations, and should not be used
                 without reading further documentation (see link below).

WARNING: DO NOT MOVE OR RENAME THESE FILES!
         Certbot expects these files to remain in this location in order
         to function properly!

We recommend not moving these files. For more information, see the Certbot
User Guide at https://certbot.eff.org/docs/using.html#where-are-my-certificates.
)Úprefix)r"   r>   r?   rF   r   )Úreadme_pathÚis_base_dirra   r%   r   r   r   Ú_write_live_readme_toÜ   s    ôrd   c                    s,   ddl m} ˆ |jkp*t‡ fdd„| D ƒƒS )zú
    Is this option one that could be restored for future renewal purposes?

    :param namespaces: plugin namespaces for configuration options
    :type namespaces: `list` of `str`
    :param str option: the name of the option

    :rtype: bool
    r   )Úrenewalc                 3   s   | ]}ˆ   |¡V  qd S ©N)Ú
startswith)Ú.0rU   ©Úoptionr   r   Ú	<genexpr>þ   s     z_relevant.<locals>.<genexpr>)r9   re   ZCONFIG_ITEMSÚany)Ú
namespacesrj   re   r   ri   r   Ú	_relevantñ   s    

ÿrn   c                    sD   t j ¡ }dd„ |D ƒ‰ t‡ fdd„t | ¡D ƒƒ}| d |d< |S )zÔReturn a new dict containing only items relevant for renewal.

    :param dict all_values: The original values.

    :returns: A new dictionary containing items that can be used in renewal.
    :rtype dict:

    c                 S   s   g | ]}t  |¡‘qS r   )Úplugins_commonZdest_namespace)rh   Zpluginr   r   r   Ú
<listcomp>  s     z#relevant_values.<locals>.<listcomp>c                 3   s0   | ](\}}t ˆ |ƒrt ||¡r||fV  qd S rf   )rn   r   Zoption_was_set)rh   rj   Úvalue©rm   r   r   rk     s   
 þz"relevant_values.<locals>.<genexpr>Úserver)Úplugins_discoZPluginsRegistryZfind_allÚdictÚsixZ	iteritems)Z
all_valuesZpluginsÚrvr   rr   r   rS     s    	
þrS   c                 C   s.   |   d¡st d¡‚tj | dtdƒ … ¡S )ú:Returns the lineagename for a configuration filename.
    ú.confz*renewal config file name must end in .confN)Úendswithr   r   r   r   ÚbasenameÚlen)rW   r   r   r   Úlineagename_for_filename  s
    
ÿr}   c                 C   s   t j | j|¡d S )rx   ry   )r   r   r   r   )r   rV   r   r   r   rL     s    rL   c                 C   s   t j | t j |¡¡S )zPath to a directory from a file)r   r   Úrelpathr\   )r3   Ú	from_filer   r   r   Ú_relpath_from_file$  s    r€   c                 C   s$   | rd| kr| d S t j |j|¡S )aM  Returns the full archive path for a lineagename

    Uses cli_config to determine archive path if not available from config_obj.

    :param configobj.ConfigObj config_obj: Renewal conf file contents (can be None)
    :param configuration.NamespaceConfig cli_config: Main config file
    :param str lineagename: Certificate name
    r3   )r   r   r   Údefault_archive_dir)Z
config_objrP   rV   r   r   r   Úfull_archive_path(  s    	r‚   c                 C   s   t j | j|¡S )z4Returns the full default live path for a lineagename)r   r   r   Úlive_dir)rP   rV   r   r   r   Ú_full_live_path5  s    r„   c              
   C   sÞ  t | |ƒ}td| |ƒ}t| |ƒ}zJzt |¡}W n6 tj	k
rf   t 
d|||¡ t d |¡¡‚Y nX W 5 t |¡ t d|¡ X tƒ }tD ]`}| |¡}zt |¡ t d|¡ W n  tk
rÖ   t d|¡ Y nX tj |¡}	| |	¡ qŽt|ƒdkr| ¡ }	tj |	t¡}
zt |
¡ t d|
¡ W n" tk
rP   t d|
¡ Y nX zt |	¡ t d|	¡ W n" tk
rŽ   t d|	¡ Y nX z&t|| |ƒ}t |¡ t d|¡ W n" tk
rØ   t d|¡ Y nX dS )	zmDelete all files related to the certificate.

    If some files are not found, ignore them and continue.
    Nz
Removed %szNCould not parse %s. You may wish to manually delete the contents of %s and %s.úerror parsing {0}zUnable to delete %sé   z&Unable to remove %s; may not be empty.zUnable to remove %s)r   r‚   r„   r   Úremover>   r?   r    r!   ÚConfigObjErrorÚwarningr   r   r   Úsetr;   ÚgetrN   r   r\   Úaddr|   Úpopr   r   ÚrmdirÚshutilZrmtree)r   r   Zrenewal_filenameZfull_default_archive_dirZfull_default_live_dirZrenewal_configZdirectory_namesrH   r^   Z	directoryrb   Zarchive_pathr   r   r   Údelete_files9  sZ    

 þÿ





r   c                   @   s6  e Zd ZdZdDdd„Zedd„ ƒZedd„ ƒZed	d
„ ƒZedd„ ƒZ	edd„ ƒZ
edd„ ƒZdd„ Zedd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ Zdd „ Zd!d"„ Zd#d$„ Zd%d&„ Zd'd(„ Zd)d*„ Zd+d,„ Zd-d.„ Zd/d0„ Zd1d2„ Zd3d4„ Zd5d6„ ZdEd8d9„ZdFd:d;„Z d<d=„ Z!d>d?„ Z"e#d@dA„ ƒZ$dBdC„ Z%d7S )GÚRenewableCerta  Renewable certificate.

    Represents a lineage of certificates that is under the management of
    Certbot, indicated by the existence of an associated renewal
    configuration file.

    Note that the notion of "current version" for a lineage is
    maintained on disk in the structure of symbolic links, and is not
    explicitly stored in any instance variable in this object. The
    RenewableCert object is able to determine information about the
    current (or other) version by accessing data on disk, but does not
    inherently know any of this information except by examining the
    symbolic links as needed. The instance variables mentioned below
    point to symlinks that reflect the notion of "current version" of
    each managed object, and it is these paths that should be used when
    configuring servers to use the certificate managed in a lineage.
    These paths are normally within the "live" directory, and their
    symlink targets -- the actual cert files -- are normally found
    within the "archive" directory.

    :ivar str cert: The path to the symlink representing the current
        version of the certificate managed by this lineage.
    :ivar str privkey: The path to the symlink representing the current
        version of the private key managed by this lineage.
    :ivar str chain: The path to the symlink representing the current version
        of the chain managed by this lineage.
    :ivar str fullchain: The path to the symlink representing the
        current version of the fullchain (combined chain and cert)
        managed by this lineage.
    :ivar configobj.ConfigObj configuration: The renewal configuration
        options associated with this lineage, obtained from parsing the
        renewal configuration file and/or systemwide defaults.

    Fc                    s  |ˆ _ t|ƒˆ _zt |¡ˆ _W n& tjk
rF   t d 	|¡¡‚Y nX t
ˆ jƒˆ _t‡ fdd„tD ƒƒs|t d 	ˆ j¡¡‚ˆ j d¡}|dk	r°t |¡tkr°t d||tj¡ ˆ jd ˆ _ˆ jd	 ˆ _ˆ jd
 ˆ _ˆ jd ˆ _tj ˆ j¡ˆ _ˆ  ¡  |rˆ  ¡  ˆ   ¡  dS )a  Instantiate a RenewableCert object from an existing lineage.

        :param str config_filename: the path to the renewal config file
            that defines this lineage.
        :param .NamespaceConfig: parsed command line arguments

        :raises .CertStorageError: if the configuration file's name didn't end
            in ".conf", or the file is missing or broken.

        r…   c                 3   s   | ]}|ˆ j kV  qd S rf   ©Úconfiguration©rh   Úx©Úselfr   r   rk   »  s     z)RenewableCert.__init__.<locals>.<genexpr>z<renewal config file {0} is missing a required file referencer2   NzzAttempting to parse the version %s renewal configuration file found at %s with version %s of Certbot. This might not work.r   r   r   r   )!rP   r}   rV   r    r!   Ú
configfilerˆ   r   r   r   r*   r“   Úallr;   r‹   r   Úget_strict_versionÚCURRENT_VERSIONr>   Úinfor9   r:   r   r   r   r   r   r   r\   rƒ   Ú_fix_symlinksÚ_update_symlinksÚ_check_symlinks)r—   rW   rP   Zupdate_symlinksZconf_versionr   r–   r   Ú__init__Ÿ  sD    
ÿ
ÿÿÿ  ýzRenewableCert.__init__c                 C   s   | j S )zDuck type for self.privkey)r   r–   r   r   r   Úkey_pathÓ  s    zRenewableCert.key_pathc                 C   s   | j S )zDuck type for self.cert)r   r–   r   r   r   r&   Ø  s    zRenewableCert.cert_pathc                 C   s   | j S )zDuck type for self.chain)r   r–   r   r   r   Ú
chain_pathÝ  s    zRenewableCert.chain_pathc                 C   s   | j S )zDuck type for self.fullchain)r   r–   r   r   r   r$   â  s    zRenewableCert.fullchain_pathc                 C   s   t  |  d¡¡S )z±The current target certificate's expiration datetime

        :returns: Expiration datetime of the current target certificate
        :rtype: :class:`datetime.datetime`
        r   )r   ÚnotAfterÚcurrent_targetr–   r   r   r   Útarget_expiryç  s    zRenewableCert.target_expiryc                 C   s   t | j| j| jƒS )z2Returns the default or specified archive directory)r‚   r“   rP   rV   r–   r   r   r   r3   ð  s     ÿzRenewableCert.archive_dirc                 C   s   t | j|ƒS )zyReturns the default or specified archive directory as a relative path

        Used for creating symbolic links.
        )r€   r3   )r—   r   r   r   r   Úrelative_archive_dirö  s    z"RenewableCert.relative_archive_dirc                 C   s$   | j d  dd¡}|r t |¡S dS )z:Returns true if this is a test cert from a staging server.r4   rs   NF)r“   r‹   r   Z
is_staging)r—   rs   r   r   r   Úis_test_certý  s    
zRenewableCert.is_test_certc                 C   sZ   t D ]P}t| |ƒ}tj |¡s.t d |¡¡‚t|ƒ}tj 	|¡st d ||¡¡‚qdS )z.Raises an exception if a symlink doesn't existzexpected {0} to be a symlinkz(target {0} of symlink {1} does not existN)
r;   Úgetattrr   r   Úislinkr   r   r   r_   r   )r—   rH   r^   rG   r   r   r   rŸ     s    
ÿ ÿzRenewableCert._check_symlinksc                 C   sR   t D ]H}t| |ƒ}t|ƒ}tj |  |¡tj |¡¡}t |¡ t 	||¡ qdS )z#Updates symlinks to use archive_dirN)
r;   r¨   r_   r   r   r   r¦   r{   rR   Úsymlink)r—   rH   r^   Úprevious_linkZnew_linkr   r   r   rž     s    

ÿ
zRenewableCert._update_symlinksc                 C   s  | j | j| j| jfD ]"}tj |¡st d|¡  dS q| j | j| j| jfD ]"}tj 	|¡sLt d|¡  dS qLt
D ]¢}t| |ƒ}t|ƒ}tj tj |¡| j¡sÂt d|tj |¡| j¡  dS tj |¡sât d||¡  dS t d |¡¡}| tj |¡¡stt d|¡  dS qtdS )	zôAre the files associated with this lineage self-consistent?

        :returns: Whether the files stored in connection with this
            lineage appear to be correct and consistent with one
            another.
        :rtype: bool

        z3Element %s is not referenced with an absolute path.Fz"Element %s is not a symbolic link.a-  Element's link does not point within the cert lineage's directory within the official archive directory. Link: %s, target directory: %s, archive directory: %s. If you've specified the archive directory in the renewal configuration file, you may need to update links by running certbot update_symlinks.z.Link %s points to file %s that does not exist.ú^{0}([0-9]+)\.pem$z1%s does not follow the archive naming convention.T)r   r   r   r   r   r   r[   r>   r?   r©   r;   r¨   r_   Úsamefiler\   r3   r   ÚreÚcompiler   Úmatchr{   )r—   r•   rH   r^   rG   Úpatternr   r   r   Ú_consistent  sB    
ÿ
 
 ø	 ÿÿzRenewableCert._consistentc                 C   s   dS )zpAttempt to fix defects or inconsistencies in this lineage.

        .. todo:: Currently unimplemented.

        Nr   r–   r   r   r   Ú_fix`  s    zRenewableCert._fixc                 C   sF   g }t D ]8}tj t| |ƒ¡}d |¡}| |tj ||¡f¡ q|S )zŒReturns the kind and path of all symlinks used in recovery.

        :returns: list of (kind, symlink) tuples
        :rtype: list

        zprevious_{0}.pem)r;   r   r   r\   r¨   r   Úappendr   )r—   Úprevious_symlinksrH   Zlink_dirZ	link_baser   r   r   Ú_previous_symlinksr  s    
z RenewableCert._previous_symlinksc                 C   s‚   |   ¡ }tdd„ |D ƒƒrZ|D ]:\}}t| |ƒ}tj |¡rFt |¡ t t |¡|¡ q|D ]\}}tj 	|¡r^t |¡ q^dS )z¦Fixes symlinks in the event of an incomplete version update.

        If there is no problem with the current symlinks, this function
        has no effect.

        c                 s   s   | ]}t j |d  ¡V  qdS )r†   N)r   r   r   )rh   r^   r   r   r   rk   ‰  s     z.RenewableCert._fix_symlinks.<locals>.<genexpr>N)
r¶   r™   r¨   r   r   ÚlexistsrR   rª   rZ   r   )r—   rµ   rH   r«   Zcurrent_linkÚ_r^   r   r   r   r     s    

zRenewableCert._fix_symlinksc                 C   sB   |t krt d¡‚t| |ƒ}tj |¡s:t d||¡ dS t	|ƒS )a(  Returns full path to which the specified item currently points.

        :param str kind: the lineage member item ("cert", "privkey",
            "chain", or "fullchain")

        :returns: The path to the current version of the specified
            member.
        :rtype: str or None

        úunknown kind of itemz*Expected symlink %s for %s does not exist.N)
r;   r   r   r¨   r   r   r   r>   r?   r_   )r—   rH   r^   r   r   r   r¤   ”  s    

 ÿzRenewableCert.current_targetc                 C   sˆ   |t krt d¡‚t d |¡¡}|  |¡}|dks@tj 	|¡sRt
 d||¡ d}| tj |¡¡}|rxt| ¡ d ƒS t
 d|¡ dS )a  Returns numerical version of the specified item.

        For example, if kind is "chain" and the current chain link
        points to a file named "chain7.pem", returns the integer 7.

        :param str kind: the lineage member item ("cert", "privkey",
            "chain", or "fullchain")

        :returns: the current version of the specified member.
        :rtype: int

        r¹   r¬   Nz3Current-version target for %s does not exist at %s.r5   r   zNo matches for target %s.)r;   r   r   r®   r¯   r   r¤   r   r   r   r>   r?   r°   r{   ÚintÚgroups)r—   rH   r±   rG   Úmatchesr   r   r   Úcurrent_version¨  s    

 ÿzRenewableCert.current_versionc                 C   s:   |t krt d¡‚tj |  |¡¡}tj |d ||¡¡S )aú  The filename that corresponds to the specified version and kind.

        .. warning:: The specified version may not exist in this
           lineage. There is no guarantee that the file path returned
           by this method actually exists.

        :param str kind: the lineage member item ("cert", "privkey",
            "chain", or "fullchain")
        :param int version: the desired version

        :returns: The path to the specified version of the specified member.
        :rtype: str

        r¹   ú
{0}{1}.pem)	r;   r   r   r   r   r\   r¤   r   r   )r—   rH   r2   Úwherer   r   r   r2   Ã  s    
zRenewableCert.versionc                    sb   |t krt d¡‚tj |  |¡¡}t |¡}t 	d 
|¡¡‰ ‡ fdd„|D ƒ}tdd„ |D ƒƒS )aœ  Which alternative versions of the specified kind of item exist?

        The archive directory where the current version is stored is
        consulted to obtain the list of alternatives.

        :param str kind: the lineage member item (
            ``cert``, ``privkey``, ``chain``, or ``fullchain``)

        :returns: all of the version numbers that currently exist
        :rtype: `list` of `int`

        r¹   r¬   c                    s   g | ]}ˆ   |¡‘qS r   )r°   )rh   r%   ©r±   r   r   rp   é  s     z4RenewableCert.available_versions.<locals>.<listcomp>c                 S   s    g | ]}|rt | ¡ d  ƒ‘qS )r   )rº   r»   )rh   Úmr   r   r   rp   ê  s      )r;   r   r   r   r   r\   r¤   Úlistdirr®   r¯   r   Úsorted)r—   rH   r¿   Úfilesr¼   r   rÀ   r   Úavailable_versions×  s    

z RenewableCert.available_versionsc                 C   s   t |  |¡ƒS )a  Newest available version of the specified kind of item?

        :param str kind: the lineage member item (``cert``,
            ``privkey``, ``chain``, or ``fullchain``)

        :returns: the newest available version of this member
        :rtype: int

        )ÚmaxrÅ   )r—   rH   r   r   r   Únewest_available_versionì  s    
z&RenewableCert.newest_available_versionc                    s,   ‡ fdd„t D ƒ‰t‡fdd„ˆd D ƒƒS )zÛNewest version for which all items are available?

        :returns: the newest available version for which all members
            (``cert, ``privkey``, ``chain``, and ``fullchain``) exist
        :rtype: int

        c                    s   g | ]}ˆ   |¡‘qS r   )rÅ   r”   r–   r   r   rp     s     z7RenewableCert.latest_common_version.<locals>.<listcomp>c                 3   s0   | ](‰ t ‡ fd d„ˆdd… D ƒƒrˆ V  qdS )c                 3   s   | ]}ˆ |kV  qd S rf   r   )rh   Úv©Únr   r   rk     s     z@RenewableCert.latest_common_version.<locals>.<genexpr>.<genexpr>r†   N)r™   )rh   )ÚversionsrÉ   r   rk     s      z6RenewableCert.latest_common_version.<locals>.<genexpr>r   )r;   rÆ   r–   r   )r—   rË   r   Úlatest_common_versionø  s    z#RenewableCert.latest_common_versionc                    s   t ‡ fdd„tD ƒƒd S )zßSmallest version newer than all full or partial versions?

        :returns: the smallest version number that is larger than any
            version of any item currently stored in this lineage
        :rtype: int

        c                 3   s   | ]}ˆ   |¡V  qd S rf   )rÇ   r”   r–   r   r   rk     s     z2RenewableCert.next_free_version.<locals>.<genexpr>r†   )rÆ   r;   r–   r   r–   r   Únext_free_version  s    zRenewableCert.next_free_versionc                 C   s(   |   ¡ r$t d¡ |  |  ¡ ¡ dS dS )zÆMake sure we've deployed the latest version.

        :returns: False if a change was needed, True otherwise
        :rtype: bool

        May need to recover from rare interrupted / crashed states.zFFound a new cert /archive/ that was not linked to in /live/; fixing...FT)Úhas_pending_deploymentr>   r‰   Úupdate_all_links_torÌ   r–   r   r   r   Úensure_deployed  s
    
zRenewableCert.ensure_deployedc                    s"   t ‡ fdd„tD ƒƒ}|ˆ  ¡ k S )a  Is there a later version of all of the managed items?

        :returns: ``True`` if there is a complete version of this
            lineage with a larger version number than the current
            version, and ``False`` otherwise
        :rtype: bool

        c                 3   s   | ]}ˆ   |¡V  qd S rf   )r½   r”   r–   r   r   rk   0  s     z7RenewableCert.has_pending_deployment.<locals>.<genexpr>)Úminr;   rÌ   )r—   Zsmallest_currentr   r–   r   rÎ   %  s    z$RenewableCert.has_pending_deploymentc                 C   s^   |t krt d¡‚t| |ƒ}d ||¡}tj t |¡¡}t 	|¡ t 
tj ||¡|¡ dS )a7  Make the specified item point at the specified version.

        (Note that this method doesn't verify that the specified version
        exists.)

        :param str kind: the lineage member item ("cert", "privkey",
            "chain", or "fullchain")
        :param int version: the desired version

        r¹   r¾   N)r;   r   r   r¨   r   r   r   r\   rZ   rR   rª   r   )r—   rH   r2   r^   ÚfilenameZtarget_directoryr   r   r   Ú_update_link_to3  s    


zRenewableCert._update_link_toc              	   C   sr   t  | j¡\ |  ¡ }|D ]\}}t |  |¡|¡ qtD ]}|  ||¡ q:|D ]\}}t 	|¡ qPW 5 Q R X dS )zwChange all member objects to point to the specified version.

        :param int version: the desired version

        N)
r   ZErrorHandlerr   r¶   r   rª   r¤   r;   rÓ   rR   )r—   r2   Zprevious_linksrH   r^   r¸   r   r   r   rÏ   M  s    z!RenewableCert.update_all_links_toNc              
   C   s`   |dkr|   d¡}n|  d|¡}|dkr2t d¡‚t|ƒ}t | ¡ ¡W  5 Q R £ S Q R X dS )a5  What are the subject names of this certificate?

        (If no version is specified, use the current version.)

        :param int version: the desired version number
        :returns: the subject names
        :rtype: `list` of `str`
        :raises .CertStorageError: if could not find cert file.

        Nr   zcould not find cert file)r¤   r2   r   r   r"   r   Zget_names_from_certr#   )r—   r2   rG   r%   r   r   r   Únames^  s    

zRenewableCert.namesc                 C   s   dS )añ  Is the specified cert version revoked according to OCSP?

        Also returns True if the cert version is declared as intended
        to be revoked according to Let's Encrypt OCSP extensions.
        (If no version is specified, uses the current version.)

        This method is not yet implemented and currently always returns
        False.

        :param int version: the desired version number

        :returns: whether the certificate is or will be revoked
        :rtype: bool

        Fr   )r—   r2   r   r   r   Úocsp_revokedr  s    zRenewableCert.ocsp_revokedc                 C   s   d| j d kp| j d  d¡S )z¼Is automatic renewal enabled for this cert?

        If autorenew is not specified, defaults to True.

        :returns: True if automatic renewal is enabled
        :rtype: bool

        Z	autorenewr4   )r“   Zas_boolr–   r   r   r   Úautorenewal_is_enabledˆ  s    	ÿz$RenewableCert.autorenewal_is_enabledc                 C   sŽ   |   ¡ rŠ|  |  ¡ ¡r$t d¡ dS tjd }| j d|¡}t	 
|  d|  ¡ ¡¡}tj tj ¡ ¡}|t||ƒk rŠt d|| d¡¡ dS dS )aT  Should we now try to autorenew the most recent cert version?

        This is a policy question and does not only depend on whether
        the cert is expired. (This considers whether autorenewal is
        enabled, whether the cert is revoked, and whether the time
        interval for autorenewal has been reached.)

        Note that this examines the numerically most recent cert version,
        not the currently deployed version.

        :returns: whether an attempt should now be made to autorenew the
            most current cert version in this lineage
        :rtype: bool

        z%Should renew, certificate is revoked.Tr6   r   z8Should renew, less than %s before certificate expiry %s.z%Y-%m-%d %H:%M:%S %ZF)rÖ   rÕ   rÌ   r>   r?   r   r(   r“   r‹   r   r£   r2   r.   r/   ZfromutcÚdatetimeZutcnowr1   Ústrftime)r—   rJ   r0   ZexpiryZnowr   r   r   Úshould_autorenew”  s$    

 ÿþzRenewableCert.should_autorenewc              	      sp  |j |j|jfD ](}tj |¡st |d¡ t 	d|¡ qt
 |j |¡\}}tj |jt¡}	tj |	¡stt|	dd t|ƒ}td||ƒ‰ t||ƒ‰tj ˆ ¡r´| ¡  t d| ¡‚tj ˆ¡rÖ| ¡  t d| ¡‚t ˆ ¡ t ˆ¡ t 	dˆ ˆ¡ t‡fd	d
„tD ƒƒ}
t‡ fdd
„tD ƒƒ}tD ]$}t t|| |
| ƒ|
| ¡ q(t|
d dƒ }t 	d|
d ¡ | |¡ W 5 Q R X t
j|d dtd }t 	d|
d ¡ | |¡ W 5 Q R X t|
d dƒ }t 	d|
d ¡ | |¡ W 5 Q R X t|
d dƒ$}t 	d|
d ¡ | || ¡ W 5 Q R X tj ˆt¡}t|ƒ | ¡  tt|j ƒƒ}t!||ˆ |
|ƒ}| |j"|ƒS )a¿  Create a new certificate lineage.

        Attempts to create a certificate lineage -- enrolled for
        potential future renewal -- with the (suggested) lineage name
        lineagename, and the associated cert, privkey, and chain (the
        associated fullchain will be created automatically). Optional
        configurator and renewalparams record the configuration that was
        originally used to obtain this cert, so that it can be reused
        later during automated renewal.

        Returns a new RenewableCert object referring to the created
        lineage. (The actual lineage name, as well as all the relevant
        file paths, will be available within this object.)

        :param str lineagename: the suggested name for this lineage
            (normally the current cert's first subject DNS name)
        :param str cert: the initial certificate version in PEM format
        :param str privkey: the private key in PEM format
        :param str chain: the certificate chain in PEM format
        :param .NamespaceConfig cli_config: parsed command line
            arguments

        :returns: the newly-created RenewalCert object
        :rtype: :class:`storage.renewableCert`

        iÀ  zCreating directory %s.T)rc   Nzarchive directory exists for zlive directory exists for z3Archive directory %s and live directory %s created.c                    s"   g | ]}|t j ˆ |d  ¡f‘qS )z.pem©r   r   r   ©rh   rH   )rƒ   r   r   rp   ÷  s   ÿz-RenewableCert.new_lineage.<locals>.<listcomp>c                    s"   g | ]}|t j ˆ |d  ¡f‘qS )z1.pemrÚ   rÛ   )Úarchiver   r   rp   ù  s   ÿr   r8   úWriting certificate to %s.r   ©rE   zWriting private key to %s.r   úWriting chain to %s.r   úWriting full chain to %s.)#r   r   rƒ   r   r   r   r	   Úmakedirsr>   r?   r   Zunique_lineage_namer   r   rd   r}   r‚   r„   r@   r   r   Úmkdirru   r;   rª   r€   r"   rF   Ú	safe_openÚBASE_PRIVKEY_MODErS   rT   rU   rK   rÒ   )ÚclsrV   r   r   r   rP   ÚiZconfig_filerW   Zbase_readme_pathrG   Zarchive_targetrH   r%   rb   rX   Z
new_configr   )rÜ   rƒ   r   Únew_lineage¹  sz    ÿ ÿ
ÿÿ

 ÿÿÿ" ÿzRenewableCert.new_lineagec              	      s¼  |ˆ _ ˆ  ¡ ‰t‡ ‡fdd„tD ƒƒ}tj ˆ jd |¡¡}|dkr„tj 	|¡r\t 
|¡}n
d |¡}t d|¡ t ||d ¡ n^tj|d dtd }t d	|d ¡ | |¡ W 5 Q R X t |t¡}	tj||d |	d
dd t|d dƒ }t d|d ¡ | |¡ W 5 Q R X t|d dƒ }t d|d ¡ | |¡ W 5 Q R X t|d dƒ$}t d|d ¡ | || ¡ W 5 Q R X t‡ fdd„tD ƒƒ}
tˆ jˆ j|
|ƒˆ _tˆ jƒˆ _ˆS )aˆ  Save new cert and chain as a successor of a prior version.

        Returns the new version number that was created.

        .. note:: this function does NOT update links to deploy this
                  version

        :param int prior_version: the old version to which this version
            is regarded as a successor (used to choose a privkey, if the
            key has not changed, but otherwise this information is not
            permanently recorded anywhere)
        :param bytes new_cert: the new certificate, in PEM format
        :param bytes new_privkey: the new private key, in PEM format,
            or ``None``, if the private key has not changed
        :param bytes new_chain: the new chain, in PEM format
        :param .NamespaceConfig cli_config: parsed command line
            arguments

        :returns: the new version number that was created
        :rtype: int

        c              
      s(   g | ] }|t j ˆ jd  |ˆ¡¡f‘qS )r¾   )r   r   r   r3   r   rÛ   ©r—   Ztarget_versionr   r   rp   <  s   þÿz0RenewableCert.save_successor.<locals>.<listcomp>zprivkey{0}.pemNz'Writing symlink to old private key, %s.r   r8   rÞ   zWriting new private key to %s.FT)Z	copy_userZ
copy_groupr   rÝ   r   rß   r   rà   c                 3   s   | ]}|ˆ j | fV  qd S rf   r’   rÛ   r–   r   r   rk   d  s     z/RenewableCert.save_successor.<locals>.<genexpr>)rP   rÍ   ru   r;   r   r   r   r3   r   r©   rZ   r>   r?   rª   r   rã   rä   rF   r	   Zcompute_private_key_modeZcopy_ownership_and_apply_moder"   rY   rV   r˜   r*   r“   )r—   Zprior_versionZnew_certZnew_privkeyZ	new_chainrP   rG   Zold_privkeyr%   ÚmodeZsymlinksr   rè   r   Úsave_successor  s\    þÿ ÿ
    ÿ   ÿzRenewableCert.save_successor)F)N)N)&Ú__name__Ú
__module__Ú__qualname__Ú__doc__r    Úpropertyr¡   r&   r¢   r$   r¥   r3   r¦   r§   rŸ   rž   r²   r³   r¶   r   r¤   r½   r2   rÅ   rÇ   rÌ   rÍ   rÐ   rÎ   rÓ   rÏ   rÔ   rÕ   rÖ   rÙ   Úclassmethodrç   rê   r   r   r   r   r‘   {  sR   "
4






D

%
ar‘   )N)F)8rî   r×   r   Zloggingr®   r   rA   r    Zparsedatetimer.   rv   r9   r   r   r   r   r   r   Zcertbot.compatr   r	   Zcertbot.pluginsr
   ro   r   rt   Z	getLoggerrë   r>   r;   r   rš   r:   r›   rä   r   r   r'   r*   ZCalendarr1   rK   rQ   rY   r_   rd   rn   rS   r}   rL   r€   r‚   r„   r   Úobjectr‘   r   r   r   r   Ú<module>   sZ   
	
4
B