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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G d	d
„ d
eƒZdS )zGReverter class saves configuration checkpoints and allows for recovery.é    N)Ú	constants)Úerrors)Ú
interfaces)Úutil)Úos)Ú
filesystemc                   @   sª   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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)S )+ÚReverteraf  Reverter Class - save and revert configuration checkpoints.

    This class can be used by the plugins, especially Installers, to
    undo changes made to the user's system. Modifications to files and
    commands to do undo actions taken by the plugin should be registered
    with this class before the action is taken.

    Once a change has been registered with this class, there are three
    states the change can be in. First, the change can be a temporary
    change. This should be used for changes that will soon be reverted,
    such as config changes for the purpose of solving a challenge.
    Changes are added to this state through calls to
    :func:`~add_to_temp_checkpoint` and reverted when
    :func:`~revert_temporary_config` or :func:`~recovery_routine` is
    called.

    The second state a change can be in is in progress. These changes
    are not temporary, however, they also have not been finalized in a
    checkpoint. A change must become in progress before it can be
    finalized. Changes are added to this state through calls to
    :func:`~add_to_checkpoint` and reverted when
    :func:`~recovery_routine` is called.

    The last state a change can be in is finalized in a checkpoint. A
    change is put into this state by first becoming an in progress
    change and then calling :func:`~finalize_checkpoint`. Changes
    in this state can be reverted through calls to
    :func:`~rollback_checkpoints`.

    As a final note, creating new files and registering undo commands
    are handled specially and use the methods
    :func:`~register_file_creation` and :func:`~register_undo_command`
    respectively. Both of these methods can be used to create either
    temporary or in progress changes.

    .. note:: Consider moving everything over to CSV format.

    :param config: Configuration.
    :type config: :class:`certbot.interfaces.IConfig`

    c                 C   s    || _ t |jtj| j j¡ d S )N)Úconfigr   Úmake_or_verify_dirÚ
backup_dirr   ÚCONFIG_DIRS_MODEÚstrict_permissions)Úselfr	   © r   ú2/usr/lib/python3/dist-packages/certbot/reverter.pyÚ__init__B   s      ÿzReverter.__init__c                 C   sX   t j | jj¡rTz|  | jj¡ W n0 tjk
rR   t 	d| jj¡ t d¡‚Y nX dS )a  Reload users original configuration files after a temporary save.

        This function should reinstall the users original configuration files
        for all saves with temporary=True

        :raises .ReverterError: when unable to revert config

        z$Incomplete or failed recovery for %sz!Unable to revert temporary configN)
r   ÚpathÚisdirr	   Útemp_checkpoint_dirÚ_recover_checkpointr   ÚReverterErrorÚloggerÚcritical©r   r   r   r   Úrevert_temporary_configH   s    	þz Reverter.revert_temporary_configé   c                 C   s   zt |ƒ}W n( tk
r4   t d¡ t d¡‚Y nX |dk rRt d¡ t d¡‚t | jj	¡}| 
¡  |sxt d¡ nt|ƒ|k r–t d|t|ƒ¡ |dkrü|rütj | jj	| ¡ ¡}z|  |¡ W n* tjk
rð   t d¡ t d¡‚Y nX |d8 }q–d	S )
ay  Revert 'rollback' number of configuration checkpoints.

        :param int rollback: Number of checkpoints to reverse. A str num will be
           cast to an integer. So "2" is also acceptable.

        :raises .ReverterError:
            if there is a problem with the input or if the function is
            unable to correctly revert the configuration checkpoints

        z,Rollback argument must be a positive integerzInvalid Inputr   zHCertbot hasn't modified your configuration, so rollback isn't available.z0Unable to rollback %d checkpoints, only %d existz)Failed to load checkpoint during rollbackz)Unable to load checkpoint during rollbackr   N)ÚintÚ
ValueErrorr   Úerrorr   r   r   Úlistdirr	   r   ÚsortÚwarningÚlenr   ÚjoinÚpopr   r   )r   ZrollbackÚbackupsÚcp_dirr   r   r   Úrollback_checkpoints\   s:    


ÿ ÿ
ÿ
zReverter.rollback_checkpointsc           
   
   C   sÄ  t jdtdd t | jj¡}|jdd |s<t 	d¡ dS z|D ]}t
|ƒ qBW n( tk
rz   t d | jj¡¡‚Y nX g }|D ]}| t t
|ƒ¡¡ tj | jj|¡}ttj |d	¡ƒ}| | ¡ ¡ W 5 Q R X | d
¡ ttj |d¡ƒ.}| ¡  ¡ }|D ]}| d |¡¡ q
W 5 Q R X tj tj |d¡¡r”ttj |d¡ƒ8}	| d¡ |	 ¡  ¡ }|D ]}| d |¡¡ qrW 5 Q R X | d¡ q„tj tj¡jd |¡ddd dS )a   Displays all saved checkpoints.

        All checkpoints are printed by
        :meth:`certbot.interfaces.IDisplay.notification`.

        .. todo:: Decide on a policy for error handling, OSError IOError...

        :raises .errors.ReverterError: If invalid directory structure.

        a  The view_config_changes method has been deprecated and will be removed in a future release. If you were using this method to implement the view_config_changes method of IInstaller, know that that method has been removed from the plugin interface and is no longer used by Certbot.é   )Ú
stacklevelT)Úreversez3Certbot has not saved backups of your configurationNzInvalid directories in {0}ÚCHANGES_SINCEzAffected files:Ú	FILEPATHSz  {0}Ú	NEW_FILESzNew Configuration Files:Ú
F)Zforce_interactiveÚpause)ÚwarningsÚwarnÚDeprecationWarningr   r   r	   r   r    r   ÚinfoÚfloatr   r   r   ÚformatÚappendÚtimeÚctimer   r#   ÚopenÚreadÚ
splitlinesÚisfileÚzopeZ	componentZ
getUtilityr   ZIDisplayZnotification)
r   r%   ZbkupÚoutputZcur_dirZ
changes_fdÚpaths_fdÚ	filepathsr   Únew_fdr   r   r   Úview_config_changes†   sR     û
ÿ



  ÿzReverter.view_config_changesc                 C   s   |   | jj||¡ dS )z¨Add files to temporary checkpoint.

        :param set save_files: set of filepaths to save
        :param str save_notes: notes about changes during the save

        N)Ú_add_to_checkpoint_dirr	   r   ©r   Ú
save_filesÚ
save_notesr   r   r   Úadd_to_temp_checkpointÀ   s
      ÿzReverter.add_to_temp_checkpointc                 C   s    |   |¡ |  | jj||¡ dS )zªAdd files to a permanent checkpoint.

        :param set save_files: set of filepaths to save
        :param str save_notes: notes about changes during the save

        N)Ú_check_tempfile_savesrC   r	   Úin_progress_dirrD   r   r   r   Úadd_to_checkpointÊ   s    
  ÿzReverter.add_to_checkpointc           	   
   C   s  t  |tj| jj¡ |  tj 	|d¡¡\}}t
|ƒ}|D ]œ}||kr8t d|¡ z>t |tj 	|tj |¡d t|ƒ ¡¡ | d |¡¡ W n< tk
rÊ   | ¡  t d||¡ t d ||¡¡‚Y nX |d7 }q8| ¡  ttj 	|d¡d	ƒ}| |¡ W 5 Q R X d
S )ag  Add save files to checkpoint directory.

        :param str cp_dir: Checkpoint directory filepath
        :param set save_files: set of files to save
        :param str save_notes: notes about changes made during the save

        :raises IOError: if unable to open cp_dir + FILEPATHS file
        :raises .ReverterError: if unable to add checkpoint

        r,   zCreating backup of %sÚ_ú{0}
z&Unable to add file %s to checkpoint %sz(Unable to add file {0} to checkpoint {1}r   r+   ÚaN)r   r
   r   r   r	   r   Ú_read_and_appendr   r   r#   r"   r   ÚdebugÚshutilÚcopy2ÚbasenameÚstrÚwriter5   ÚIOErrorÚcloser   r   r   r9   )	r   r&   rE   rF   Úop_fdZexisting_filepathsÚidxÚfilenameZnotes_fdr   r   r   rC   Ö   sF      ÿÿ ÿ þ ÿÿ

zReverter._add_to_checkpoint_dirc                 C   s:   t j |¡r$t|dƒ}| ¡  ¡ }ng }t|dƒ}||fS )zˆReads the file lines and returns a file obj.

        Read the file returning the lines, and a pointer to the end of the file.

        zr+Úw)r   r   r<   r9   r:   r;   )r   ÚfilepathrW   Úlinesr   r   r   rN     s    

zReverter._read_and_appendc              
   C   s6  t j t j |d¡¡r*|  t j |d¡¡ t j t j |d¡¡rÞzjtt j |d¡ƒN}| ¡  ¡ }t|ƒD ]2\}}t	 
t j |t j |¡d t|ƒ ¡|¡ qjW 5 Q R X W n2 ttfk
rÜ   t d|¡ t d| ¡‚Y nX |  t j |d¡¡ zt	 |¡ W n0 tk
r0   t d|¡ t d| ¡‚Y nX dS )a  Recover a specific checkpoint.

        Recover a specific checkpoint provided by cp_dir
        Note: this function does not reload augeas.

        :param str cp_dir: checkpoint directory file path

        :raises errors.ReverterError: If unable to recover checkpoint

        ÚCOMMANDSr,   rK   zUnable to recover files from %sr-   zUnable to remove directory: %sN)r   r   r<   r#   Ú_run_undo_commandsr9   r:   r;   Ú	enumeraterP   rQ   rR   rS   rU   ÚOSErrorr   r   r   r   Ú_remove_contained_filesZrmtree)r   r&   r?   r@   rX   r   r   r   r   r     s4    
þþÿ
ÿzReverter._recover_checkpointc                 C   sŒ   t jd dkrddini }t|df|ŽZ}t |¡}tt|ƒƒD ]<}zt |¡ W q@ t	j
k
rz   t dd |¡¡ Y q@X q@W 5 Q R X dS )	zRun all commands in a file.r   r(   ÚnewlineÚ ÚrzUnable to run undo command: %sú N)ÚsysÚversion_infor9   ÚcsvÚreaderÚreversedÚlistr   Z
run_scriptr   ZSubprocessErrorr   r   r#   )r   r[   ÚkwargsZcsvfileZ	csvreaderÚcommandr   r   r   r^   :  s    
 ÿzReverter._run_undo_commandsc              	   C   s´   g }t j | jjd¡}t j |¡rJt|dƒ}| | ¡  	¡ ¡ W 5 Q R X t j | jjd¡}t j |¡rt|dƒ}| | ¡  	¡ ¡ W 5 Q R X |D ]}||kr”t
 d| ¡‚q”dS )zîVerify save isn't overwriting any temporary files.

        :param set save_files: Set of files about to be saved.

        :raises certbot.errors.ReverterError:
            when save is attempting to overwrite a temporary file.

        r,   rd   r-   z+Attempting to overwrite challenge file - %sN)r   r   r#   r	   r   r<   r9   Úextendr:   r;   r   r   )r   rE   Zprotected_filesZ	temp_pathZprotected_fdÚnew_pathrY   r   r   r   rH   J  s     	ÿÿzReverter._check_tempfile_savesc              	   G   s¬   |st  d¡‚|  |¡}d}zxz>|  tj |d¡¡\}}|D ]}||kr<| d 	|¡¡ q<W n4 t
tfk
r   t d|¡ t  d 	|¡¡‚Y nX W 5 |dk	r¦| ¡  X dS )aA  Register the creation of all files during certbot execution.

        Call this method before writing to the file to make sure that the
        file will be cleaned up if the program exits unexpectedly.
        (Before a save occurs)

        :param bool temporary: If the file creation registry is for
            a temp or permanent save.
        :param \*files: file paths (str) to be registered

        :raises certbot.errors.ReverterError: If
            call does not contain necessary parameters or if the file creation
            is unable to be registered.

        z,Forgot to provide files to registration callNr-   rL   z(Unable to register file creation(s) - %sz)Unable to register file creation(s) - {0})r   r   Ú_get_cp_dirrV   rN   r   r   r#   rT   r5   rU   r`   r   r   )r   Ú	temporaryÚfilesr&   rA   Zex_filesr   r   r   r   Úregister_file_creationh  s     

ÿzReverter.register_file_creationc              	   C   s¾   t j |  |¡d¡}d}tjd dkr.ddini }ztzBt j |¡rRt|df|Ž}nt|df|Ž}t	 
|¡}| |¡ W n, ttfk
r¢   t d	¡ t d
¡‚Y nX W 5 |dk	r¸| ¡  X dS )aÒ  Register a command to be run to undo actions taken.

        .. warning:: This function does not enforce order of operations in terms
            of file modification vs. command registration.  All undo commands
            are run first before all normal files are reverted to their previous
            state.  If you need to maintain strict order, you may create
            checkpoints before and after the the command registration. This
            function may be improved in the future based on demand.

        :param bool temporary: Whether the command should be saved in the
            IN_PROGRESS or TEMPORARY checkpoints.
        :param command: Command to be run.
        :type command: list of str

        r]   Nr   r(   rb   rc   rM   rZ   zUnable to register undo commandz Unable to register undo command.)r   r   r#   rp   rf   rg   rV   r<   r9   rh   ÚwriterZwriterowrU   r`   r   r   r   r   )r   rq   rm   Zcommands_fpZcommand_filerl   Z	csvwriterr   r   r   Úregister_undo_command  s     

ÿzReverter.register_undo_commandc                 C   s.   |r| j j}n| j j}t |tj| j j¡ |S )z%Return the proper reverter directory.)r	   r   rI   r   r
   r   r   r   )r   rq   r&   r   r   r   rp   µ  s    
  ÿzReverter._get_cp_dirc                 C   sh   |   ¡  tj | jj¡rdz|  | jj¡ W n8 tjk
rb   t	 
d| jj¡ t d| jj ¡‚Y nX dS )aC  Revert configuration to most recent finalized checkpoint.

        Remove all changes (temporary and permanent) that have not been
        finalized. This is useful to protect against crashes and other
        execution interruptions.

        :raises .errors.ReverterError: If unable to recover the configuration

        z=Incomplete or failed recovery for IN_PROGRESS checkpoint - %sN)r   r   r   r   r	   rI   r   r   r   r   r   r   r   r   r   Úrecovery_routineÁ  s    þÿÿzReverter.recovery_routinec              	   C   sž   t j |¡sdS zTt|dƒ@}| ¡  ¡ }|D ](}t j |¡rJt  |¡ q.t 	d|¡ q.W 5 Q R X W n4 t
tfk
r˜   t d|¡ t d |¡¡‚Y nX dS )a   Erase all files contained within file_list.

        :param str file_list: file containing list of file paths to be deleted

        :returns: Success
        :rtype: bool

        :raises certbot.errors.ReverterError: If
            all files within file_list cannot be removed

        Frd   zVFile: %s - Could not be found to be deleted
 - Certbot probably shut down unexpectedlyz.Unable to remove filepaths contained within %sz/Unable to remove filepaths contained within {0}T)r   r   r<   r9   r:   r;   ÚlexistsÚremover   r!   rU   r`   r   r   r   r5   )r   Z	file_listZlist_fdr@   r   r   r   r   ra   Ý  s.    ý ÿÿÿ
z Reverter._remove_contained_filesc              
   C   s  t j | jj¡sdS t j | jjd¡}t j | jjd¡}t j |¡snt d¡ t	|dƒ}| 
d¡ W 5 Q R X zXt	|dƒ8}| 
d| ¡ t	|dƒ}| 
| ¡ ¡ W 5 Q R X W 5 Q R X t ||¡ W n> ttfk
r   t d	¡ t d
t ¡ ¡ t d¡‚Y nX |  ¡  dS )aZ  Finalize the checkpoint.

        Timestamps and permanently saves all changes made through the use
        of :func:`~add_to_checkpoint` and :func:`~register_file_creation`

        :param str title: Title describing checkpoint

        :raises certbot.errors.ReverterError: when the
            checkpoint is not able to be finalized.

        Nr+   zCHANGES_SINCE.tmpz/Rollback checkpoint is empty (no changes made?)rZ   zNo changes
z	-- %s --
rd   z,Unable to finalize checkpoint - adding titlezException was:
%szUnable to add title)r   r   r   r	   rI   r#   Úexistsr   r3   r9   rT   r:   rP   ZmoverU   r`   r   rO   Ú	tracebackÚ
format_excr   r   Ú_timestamp_progress_dir)r   ÚtitleZchanges_since_pathZchanges_since_tmp_pathÚfZchanges_tmpZchanges_origr   r   r   Úfinalize_checkpoint  s&    
"
zReverter.finalize_checkpointc                 C   s¸   t t ¡ ƒ}t tj | jjd¡¡}dd„ |D ƒ}| |¡ | 	¡  |d |krxt t
|d ƒd ƒ}t d||¡ |}n<t|ƒdkr´|d |kr´t d|¡ t t
|d ƒd	 ƒ}|}|S )
zBDetermine the timestamp of the checkpoint, enforcing monotonicity.z[0-9]*c                 S   s   g | ]}t j |¡‘qS r   )r   r   rR   )Ú.0Údr   r   r   Ú
<listcomp>0  s     z2Reverter._checkpoint_timestamp.<locals>.<listcomp>éÿÿÿÿr   zyCurrent timestamp %s does not correspond to newest reverter checkpoint; your clock probably jumped. Time travelling to %séþÿÿÿz6Race condition with timestamp %s, incrementing by 0.01g{®Gáz„?)rS   r7   Úglobr   r   r#   r	   r   r6   r    r4   r   r!   r"   rO   )r   Ú	timestampZothersZ
timetravelr   r   r   Ú_checkpoint_timestamp,  s"    
 þzReverter._checkpoint_timestampc              	   C   s†   t j d¡D ]X}|  ¡ }tj | jj|¡}zt	 
| jj|¡ W  dS  tk
rb   t d|¡ Y qX qt d| jj|¡ t d¡‚dS )zTimestamp the checkpoint.r(   Nz1Extreme, unexpected race condition, retrying (%s)z'Unable to finalize checkpoint, %s -> %sz&Unable to finalize checkpoint renaming)ÚsixZmovesÚranger‡   r   r   r#   r	   r   r   ÚreplacerI   r`   r   r!   r   r   r   )r   rK   r†   Z	final_dirr   r   r   r|   A  s      þÿz Reverter._timestamp_progress_dirN)r   )Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r   r'   rB   rG   rJ   rC   rN   r   r^   rH   rs   ru   rp   rv   ra   r   r‡   r|   r   r   r   r   r      s(   )
*:
-''&&)r   )rŽ   rh   r…   ZloggingrP   rf   r7   rz   r0   rˆ   Zzope.componentr=   Zcertbotr   r   r   r   Zcertbot.compatr   r   Z	getLoggerr‹   r   Úobjectr   r   r   r   r   Ú<module>   s$   
