M/e5VdZddlZddlZddlZddlZddlZddlZddlmZddlm Z ddlm Z ddlm Z ddlm Z ddl mZdd l mZdd l mZdd lmZdd lmZdd lmZej,eZGddZy)zGReverter class saves configuration checkpoints and allows for recovery.N)Iterable)List)Set)TextIO)Tuple) configuration)errors)util) constants) filesystem)oscpeZdZdZdej ddfdZd!dZd"deddfdZ d e e d e ddfd Z d e e d e ddfd Z d e d e e d e ddfdZde deeee ffdZd e ddfdZde ddfdZd e e ddfdZdede ddfdZdedee ddfdZdede fdZd!dZde defdZde ddfdZde fdZd!d Zy)#ReverteraqReverter 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.configuration.NamespaceConfig` configreturnNc||_tj|jtj |jj y)N)rr make_or_verify_dir backup_dirr CONFIG_DIRS_MODEstrict_permissions)selfrs 2/usr/lib/python3/dist-packages/certbot/reverter.py__init__zReverter.__init__Bs5     y994;;;Y;Y [cdtjj|jjr' |j |jjyy#t j$r@tjd|jjt jdwxYw)aReload 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 pathisdirrtemp_checkpoint_dir_recover_checkpointr ReverterErrorloggercriticalrs rrevert_temporary_configz Reverter.revert_temporary_configHs 77==88 9 P(()H)HI :'' P:KK33**+NOO  Ps %AAB/rollbackc> t|}|dkr*tjdt j dt j|jj}|j|stjdn.t||kr tjd|t||dkDrf|rct jj|jj|j} |j!||dz}|dkDr|ray y y y #t$r+tjdt j dwxYw#tj $r+tj#dt j dwxYw) ayRevert '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 InputrzHCertbot 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 rollbackN)int ValueErrorr!errorr r r listdirrrsortwarninglenrjoinpoprr")rr%backupscp_dirs rrollback_checkpointszReverter.rollback_checkpoints\s] 88}H a< LLG H&&7 7**T[[334  NN# $\H $ NNM#S\ 3lwWW\\$++"8"8'++-HF A((0 MHlwlwl' 8 LLG H&&7 7 8.'' A KL**?AA As D'E'4E>F save_files save_notescR|j|jj||y)zAdd 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_dirrrrr4r5s radd_to_temp_checkpointzReverter.add_to_temp_checkpoints$ ## KK + +Z Erct|j||j|jj||y)zAdd 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_savesr7rin_progress_dirr8s radd_to_checkpointzReverter.add_to_checkpoints2 "":. ## KK ' 'Z Arr2c tj|tj|jj |j tjj|d\}}t|}|D]}||vstjd| tj|tjj|tjj|dzt!|z|j#dj%||dz }|j)t1tjj|dd 5}|j#|d d d y #t&$rM|j)tj+d||t-j.dj%||wxYw#1swYy xYw) agAdd 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 FILEPATHSzCreating backup of %s_{0} z&Unable to add file %s to checkpoint %sz(Unable to add file {0} to checkpoint {1}r' CHANGES_SINCEaN)r rr rrr_read_and_appendr rr/r.r!debugshutilcopy2basenamestrwriteformatIOErrorcloser*r r open) rr2r4r5op_fdexisting_filepathsidxfilenamenotes_fds rr7zReverter._add_to_checkpoint_dirs  I.. 0N0N P%)$9$9 GGLL -%/!!$%" H11 4h? 8LL277<< 0 0 :S @3s8 K,MNKKx 89q) *  "'',,v7 = ' NN: & ' '8KKMLL@ &*!..$fXv688 8 ' 'sBE4G 4AG  Gfilepathctjj|r.t|d}|j j }||fSg}t|d}||fS)zReads the file lines and returns a file obj. Read the file returning the lines, and a pointer to the end of the file. zr+w)r risfilerNread splitlines)rrTrOliness rrDzReverter._read_and_appends] 77>>( #4(EJJL++-E e|E3'Ee|rc ztjjtjj|dr/|j tjj|dtjjtjj|dr t tjj|d5}|j j}t|D]e\}}tjtjj|tjj|dzt|z|g ddd|j'tjj|d tj(|y#1swYOxYw#ttf$r/tj!d|t#j$d|wxYw#t$r/tj!d|t#j$d|zwxYw) aRecover 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?r@NzUnable to recover files from %szUnable to recover files from NEW_FILESzUnable to remove directory: %s)r rrWr/_run_undo_commandsrNrXrY enumeraterFrGrHrIrLOSErrorr!r*r r _remove_contained_filesrmtree)rr2paths_fd filepathsrQrs rrzReverter._recover_checkpoints 77>>"'',,vz: ;  # #BGGLL$D E 77>>"'',,v{; < U"'',,v{;<L (  : : G**-J6(+STT U ; LL96 B&&069; ; ;s1+)GBF5'GH5F>:G>G?8H:c Vddi}t|dfi|5}tj|}tt |D]} t j | dddy#tj$r(tjddj|Y_wxYw#1swYyxYw)zRun all commands in a file.newlinerzUnable to run undo command: %s N) rNcsvreaderreversedlistr run_scriptr SubprocessErrorr!r*r/)rrTkwargscsvfile csvreadercommands rr^zReverter._run_undo_commandss R (C *6 * Mg 7+I#DO4 MMOOG, M M M --MLL8#((7:KMM  M Ms/-BA!B!8BBBBB(cg}tjj|jjd}tjj |rBt |d5}|j|jjdddtjj|jjd}tjj |rBt |d5}|j|jjddd|D]}||vstjd|y#1swYxYw#1swY9xYw)zVerify 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?rhNr]z)Attempting to overwrite challenge file - ) r rr/rrrWrNextendrXrYr r )rr4protected_files temp_path protected_fdnew_pathrRs rr;zReverter._check_tempfile_savess)GGLL!@!@+N 77>>) $i% I&&|'8'8':'E'E'GH I77<< ? ?M 77>>( #h$ I &&|'8'8':'E'E'GH I( cH:%**-VW_V`+abb c I I  I Is".E7.EEE& temporaryfilesc|stjd|j|}d} |jtj j |d\}}|D]'}||vs|jdj|) ||jyy#ttf$r;tjd|tjdj|wxYw#||jwwxYw)aARegister 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]rAz(Unable to register file creation(s) - %sz)Unable to register file creation(s) - {0})r r _get_cp_dirrDr rr/rJrKrLr`r!r*rM)rrzr{r2new_fdex_filesrs rregister_file_creationzReverter.register_file_creation+s$&&'UV V!!), #44RWW\\&+5VW FH 7x'LL!56 7! " ! K LLCU K&&;BB5IK K K ! "s;B("BA C))C,,Drsctjj|j|d}ddi} tjj |rdnd}t ||fi|5}t j|}|j|dddy#1swYyxYw#ttf$r+tjdtjdwxYw) aRegister 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\rfrgrCrVNzUnable to register undo commandz Unable to register undo command.)r rr/r}rWrNrjwriterwriterowrLr`r!r*r r )rrzrs commands_fprpmodef csvwriters rregister_undo_commandzReverter.register_undo_commandRs ggll4#3#3I#> K R 4''..533Dk4262 ,aJJqM ""7+ , , ,! 4 LL: ;&&24 4 4s)0B!%'B B!BB!B!!:Cc|r|jj}n|jj}tj|t j |jj|S)z%Return the proper reverter directory.)rrr<r rr rr)rrzr2s rr}zReverter._get_cp_dirpsP [[44F[[00F  I.. 0N0N P rc|jtjj|jj r' |j |jj yy#tj$rWtjd|jj tjd|jj zwxYw)aCRevert 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 rrrr<rr r r!r"r#s rrecovery_routinezReverter.recovery_routine|s $$& 77==44 5 :(()D)DE 6'' :!/![[88:**![[889::  :s %A,,A*C file_listctjj|sy t|d5}|j j }|D]M}tjj |rtj|8tjd|O dddy#1swYyxYw#ttf$r;tjd|tjdj|wxYw)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 FrhzVFile: %s - Could not be found to be deleted - Certbot probably shut down unexpectedlyNz.Unable to remove filepaths contained within %sz/Unable to remove filepaths contained within {0}T)r rrWrNrXrYlexistsremover!r-rLr`r"r r rK)rrlist_fdrdrs rraz Reverter._remove_contained_filessww~~i( )i% "#LLN557 % "Dwwt, $I " " "&' "&! ) OO@) M&&fY') ) )s* B5A1B) B5)B2.B52B55A C?titlec tjj|jjsytjj |jjd}tjj |jjd}tjj |s;tjdt|d5}|jdddd t|d5}|jd|zt|d5}|j|jddddddtj|||j-y#1swYxYw#1swYDxYw#1swYHxYw#ttf$rStj!d tj#d t%j&t)j*d wxYw) aZFinalize 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. NrBzCHANGES_SINCE.tmpz/Rollback checkpoint is empty (no changes made?)rVz No changes z -- %s -- rhz,Unable to finalize checkpoint - adding titlezException was: %szUnable to add title)r rrrr<r/existsr!inforNrJrXrFmoverLr`r*rE traceback format_excr r _timestamp_progress_dir)rrchanges_since_pathchanges_since_tmp_pathr changes_tmp changes_origs rfinalize_checkpointzReverter.finalize_checkpointsww}}T[[889 WW\\$++*E*EW!#dkk.I.IK^!_ww~~01 KKI J(#. (!' ( >,c2 ;k!!,"67,c2;l%%l&7&7&9:; ; KK.0B C $$&% ( (;; ; ;! > LLG H LL-y/C/C/E F&&'<= = >sIE<8 F !F% FF F <FF FFF A"Hc|ttj}tjtjj |j jd}|Dcgc]!}tjj|#}}|j||j|d|k7r5tt|ddz}tjd|||}|St|dkDr:|d|k(r2tjd|tt|ddz}|}|Scc}w)zBDetermine the timestamp of the checkpoint, enforcing monotonicity.z[0-9]*r'zyCurrent timestamp %s does not correspond to newest reverter checkpoint; your clock probably jumped. Time travelling to %sz6Race condition with timestamp %s, incrementing by 0.01g{Gz?)rItimeglobr rr/rrrHappendr,floatr!r-r.rE)r timestampothersd timetravels r_checkpoint_timestampzReverter._checkpoint_timestamps  $ 277<< (>(>IJ/56!"''""1%66 i  ": "U6":.23J NNP: '#I [1_y!8 LLQS\ ]U6":.56J"I7s)&D9ctdD]r}|j}tjj |j j |} tj|j j|ytjd|j jtjd#t$rtjd|YwxYw)zTimestamp the checkpoint.Nz(Unexpected race condition, retrying (%s)z'Unable to finalize checkpoint, %s -> %sz&Unable to finalize checkpoint renaming)rangerr rr/rrr replacer<r`r!r-r*r r )rr@r final_dirs rrz Reverter._timestamp_progress_dirs q VA224I T[[%;%;YGI V""4;;#>#> J  V  5 KK ' ' 4"" 46 6 VI9U Vs*CC#"C#)rN)r') __name__ __module__ __qualname____doc__rNamespaceConfigrr$r(r3rrIr9r=r7rrrrDrr^r;boolrrrr}rrarrrrrrrs(R[}<<[[ P((S((TESEsEtE ACH A# A$ A+'S+'c#h+'TW+'\`+'ZvtCy7H1I"$;#$;$$;L M3 M4 McCcTc8%%c%d%N4t4hsm4PT4< T c :8$$$L''''''Rs*6rr)rrjrloggingrFrrtypingrrrrrcertbotrr r certbot._internalr certbot.compatr r getLoggerrr!rrrrrsYM  !'%   8 $w6w6r