From 7ea928c452e2baaa929e5a078d796ece3720e765 Mon Sep 17 00:00:00 2001 From: "Andrew M. Kuchling" Date: Fri, 10 Nov 2006 13:15:58 +0000 Subject: [PATCH] [Patch #1514543] mailbox (Maildir): avoid losing messages on name clash Two changes: Where possible, use link()/remove() to move files into a directory; this makes it easier to avoid overwriting an existing file. Use _create_carefully() to create files in tmp/, which uses O_EXCL. --- Lib/mailbox.py | 27 ++++++++++++++++++++++----- Misc/NEWS | 4 ++++ 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/Lib/mailbox.py b/Lib/mailbox.py index 51c2ccc80f5..c6b0fa00e3c 100755 --- a/Lib/mailbox.py +++ b/Lib/mailbox.py @@ -255,7 +255,19 @@ class Maildir(Mailbox): suffix = '' uniq = os.path.basename(tmp_file.name).split(self.colon)[0] dest = os.path.join(self._path, subdir, uniq + suffix) - os.rename(tmp_file.name, dest) + try: + if hasattr(os, 'link'): + os.link(tmp_file.name, dest) + os.remove(tmp_file.name) + else: + os.rename(tmp_file.name, dest) + except OSError, e: + os.remove(tmp_file.name) + if e.errno == errno.EEXIST: + raise ExternalClashError('Name clash with existing message: %s' + % dest) + else: + raise if isinstance(message, MaildirMessage): os.utime(dest, (os.path.getatime(dest), message.get_date())) return uniq @@ -431,12 +443,17 @@ class Maildir(Mailbox): except OSError, e: if e.errno == errno.ENOENT: Maildir._count += 1 - return open(path, 'wb+') + try: + return _create_carefully(path) + except OSError, e: + if e.errno != errno.EEXIST: + raise else: raise - else: - raise ExternalClashError('Name clash prevented file creation: %s' % - path) + + # Fall through to here if stat succeeded or open raised EEXIST. + raise ExternalClashError('Name clash prevented file creation: %s' % + path) def _refresh(self): """Update table of contents mapping.""" diff --git a/Misc/NEWS b/Misc/NEWS index d91e64dbc53..d41d7cc30f0 100644 --- a/Misc/NEWS +++ b/Misc/NEWS @@ -140,6 +140,10 @@ Library - Bug #1575506: mailbox.py: Single-file mailboxes didn't re-lock properly in their flush() method. +- Patch #1514543: mailbox.py: In the Maildir class, report errors if there's + a filename clash instead of possibly losing a message. (Patch by David + Watson.) + - Patch #1514544: mailbox.py: Try to ensure that messages/indexes have been physically written to disk after calling .flush() or .close(). (Patch by David Watson.)