From 081b1e69e99ea968781688fae766a9e1d0a46794 Mon Sep 17 00:00:00 2001 From: Michael Hanselmann <hansmi@google.com> Date: Thu, 27 Sep 2007 13:03:08 +0000 Subject: [PATCH] Prevent race condition in CreateBackup(). Reviewed-by: ultrotter --- lib/utils.py | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/utils.py b/lib/utils.py index d964f8687..bc9a1046f 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -748,10 +748,20 @@ def CreateBackup(file_name): raise errors.ProgrammerError("Can't make a backup of a non-file '%s'" % file_name) - # Warning: the following code contains a race condition when we create more - # than one backup of the same file in a second. - backup_name = file_name + '.backup-%d' % int(time.time()) - shutil.copyfile(file_name, backup_name) + prefix = '%s.backup-%d.' % (os.path.basename(file_name), int(time.time())) + dir = os.path.dirname(file_name) + + fsrc = open(file_name, 'rb') + try: + (fd, backup_name) = tempfile.mkstemp(prefix=prefix, dir=dir) + fdst = os.fdopen(fd, 'wb') + try: + shutil.copyfileobj(fsrc, fdst) + finally: + fdst.close() + finally: + fsrc.close() + return backup_name -- GitLab