From 364ffd5a0ff0848ec203f39397f00733a76d3350 Mon Sep 17 00:00:00 2001 From: Stanislav Laznicka Date: Mon, 19 Feb 2018 09:50:41 +0100 Subject: [PATCH] Fix FileStore.backup_file() not to backup same file FileStore.backup_file() docstring claimed not to store a copy of the same file but the behavior of the method did not match this description. This commit makes the backed-up file filename derivation deterministic by hashing its content by SHA-256, thus it should not back up two files with the same filename and content. Reviewed-By: Aleksei Slaikovskii --- ipalib/install/sysrestore.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/ipalib/install/sysrestore.py b/ipalib/install/sysrestore.py index b2e1a0048..fe79493b1 100644 --- a/ipalib/install/sysrestore.py +++ b/ipalib/install/sysrestore.py @@ -29,6 +29,8 @@ import os.path import shutil import random +from hashlib import sha256 + import six # pylint: disable=import-error if six.PY3: @@ -111,7 +113,7 @@ class FileStore(object): p.write(f) def backup_file(self, path): - """Create a copy of the file at @path - so long as a copy + """Create a copy of the file at @path - as long as an exact copy does not already exist - which will be restored to its original location by restore_files(). """ @@ -126,11 +128,11 @@ class FileStore(object): _reldir, backupfile = os.path.split(path) - filename = "" - for _i in range(8): - h = "%02x" % self.random.randint(0,255) - filename += h - filename += "-"+backupfile + with open(path, 'rb') as f: + cont_hash = sha256(f.read()).hexdigest() + + filename = "{hexhash}-{bcppath}".format( + hexhash=cont_hash, bcppath=backupfile) backup_path = os.path.join(self._path, filename) if os.path.exists(backup_path):