2002-03-31 01:31:11 +00:00
|
|
|
#! /usr/bin/env python
|
2002-03-26 03:53:09 +00:00
|
|
|
############################################################################
|
2006-10-12 23:02:03 +00:00
|
|
|
# Copyright (C) 2002 Paul Rodger <paul@paulrodger.com>,
|
|
|
|
# (C) 2006 Peter Poeml <poeml@suse.de>,
|
2010-07-29 18:00:56 +00:00
|
|
|
# (C) 2006-2010 Nikolaus Schulz <microschulz@web.de>
|
2002-03-26 03:53:09 +00:00
|
|
|
#
|
|
|
|
# This program is free software; you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation; either version 2 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# This program is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with this program; if not, write to the Free Software
|
|
|
|
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
|
|
|
|
############################################################################
|
2002-03-31 01:31:11 +00:00
|
|
|
"""
|
2002-04-21 01:14:54 +00:00
|
|
|
Archive and compress old mail in mbox, MH or maildir-format mailboxes.
|
2002-03-31 01:31:11 +00:00
|
|
|
Website: http://archivemail.sourceforge.net/
|
|
|
|
"""
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-04-08 13:39:03 +00:00
|
|
|
# global administrivia
|
2010-07-29 18:38:01 +00:00
|
|
|
__version__ = "archivemail v0.8.0"
|
2006-10-14 22:45:25 +00:00
|
|
|
__copyright__ = """\
|
|
|
|
Copyright (C) 2002 Paul Rodger <paul@paulrodger.com>
|
|
|
|
(C) 2006 Peter Poeml <poeml@suse.de>,
|
2010-07-29 18:00:56 +00:00
|
|
|
(C) 2006-2010 Nikolaus Schulz <microschulz@web.de>
|
2002-04-08 13:39:03 +00:00
|
|
|
This is free software; see the source for copying conditions. There is NO
|
|
|
|
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE."""
|
|
|
|
|
2002-03-31 05:32:14 +00:00
|
|
|
import sys
|
|
|
|
|
|
|
|
def check_python_version():
|
2006-10-14 23:22:25 +00:00
|
|
|
"""Abort if we are running on python < v2.3"""
|
|
|
|
too_old_error = "This program requires python v2.3 or greater. " + \
|
2002-10-03 06:27:08 +00:00
|
|
|
"Your version of python is:\n%s""" % sys.version
|
2002-03-31 05:32:14 +00:00
|
|
|
try:
|
|
|
|
version = sys.version_info # we might not even have this function! :)
|
2006-10-14 23:22:25 +00:00
|
|
|
if (version[0] < 2) or (version[0] == 2 and version[1] < 3):
|
2002-03-31 05:32:14 +00:00
|
|
|
print too_old_error
|
|
|
|
sys.exit(1)
|
|
|
|
except AttributeError:
|
|
|
|
print too_old_error
|
|
|
|
sys.exit(1)
|
|
|
|
|
2006-10-29 03:10:45 +00:00
|
|
|
# define & run this early
|
2006-10-14 23:22:25 +00:00
|
|
|
# (IMAP over SSL requires Python >= 2.3)
|
|
|
|
check_python_version()
|
2002-03-31 05:32:14 +00:00
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
import fcntl
|
|
|
|
import getopt
|
2002-04-12 05:31:59 +00:00
|
|
|
import gzip
|
2002-03-26 03:53:09 +00:00
|
|
|
import mailbox
|
|
|
|
import os
|
2002-09-15 06:14:57 +00:00
|
|
|
import pwd
|
2002-04-04 02:41:37 +00:00
|
|
|
import re
|
2002-03-26 03:53:09 +00:00
|
|
|
import rfc822
|
2002-04-12 05:31:59 +00:00
|
|
|
import shutil
|
2002-03-31 01:31:11 +00:00
|
|
|
import signal
|
2002-04-03 10:51:26 +00:00
|
|
|
import stat
|
2002-03-26 03:53:09 +00:00
|
|
|
import string
|
|
|
|
import tempfile
|
|
|
|
import time
|
2006-06-16 08:34:22 +00:00
|
|
|
import urlparse
|
2006-10-30 19:29:15 +00:00
|
|
|
import errno
|
2010-01-15 23:58:35 +00:00
|
|
|
import socket
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2006-10-12 18:19:01 +00:00
|
|
|
# From_ mangling regex.
|
|
|
|
from_re = re.compile(r'^From ', re.MULTILINE)
|
2008-03-15 15:59:05 +00:00
|
|
|
imapsize_re = re.compile(r'^(?P<msn>[0-9]+) \(RFC822\.SIZE (?P<size>[0-9]+)\)')
|
2006-10-12 18:19:01 +00:00
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
############## class definitions ###############
|
|
|
|
|
2007-10-23 22:27:57 +00:00
|
|
|
class ArchivemailException(Exception):
|
|
|
|
pass
|
|
|
|
class UserError(ArchivemailException):
|
|
|
|
pass
|
|
|
|
class UnexpectedError(ArchivemailException):
|
|
|
|
pass
|
2009-05-22 17:40:07 +00:00
|
|
|
class LockUnavailable(ArchivemailException):
|
|
|
|
pass
|
2007-10-23 22:27:57 +00:00
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
class Stats:
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Class to collect and print statistics about mailbox archival"""
|
|
|
|
__archived = 0
|
2006-10-31 03:07:02 +00:00
|
|
|
__archived_size = 0
|
2002-03-31 01:31:11 +00:00
|
|
|
__mailbox_name = None
|
|
|
|
__archive_name = None
|
|
|
|
__start_time = 0
|
|
|
|
__total = 0
|
2006-10-31 03:07:02 +00:00
|
|
|
__total_size = 0
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
def __init__(self, mailbox_name, final_archive_name):
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Constructor for a new set of statistics.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
mailbox_name -- filename/dirname of the original mailbox
|
|
|
|
final_archive_name -- filename for the final 'mbox' archive, without
|
|
|
|
compression extension (eg .gz)
|
|
|
|
|
|
|
|
"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
|
|
|
assert final_archive_name
|
2002-03-31 01:31:11 +00:00
|
|
|
self.__start_time = time.time()
|
|
|
|
self.__mailbox_name = mailbox_name
|
2002-04-12 05:31:59 +00:00
|
|
|
self.__archive_name = final_archive_name + ".gz"
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2006-10-31 03:07:02 +00:00
|
|
|
def another_message(self, size):
|
|
|
|
"""Add one to the internal count of total messages processed
|
|
|
|
and record message size."""
|
2002-03-31 01:31:11 +00:00
|
|
|
self.__total = self.__total + 1
|
2006-10-31 03:07:02 +00:00
|
|
|
self.__total_size = self.__total_size + size
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2006-10-31 03:07:02 +00:00
|
|
|
def another_archived(self, size):
|
|
|
|
"""Add one to the internal count of messages archived
|
|
|
|
and record message size."""
|
2002-03-31 01:31:11 +00:00
|
|
|
self.__archived = self.__archived + 1
|
2006-10-31 03:07:02 +00:00
|
|
|
self.__archived_size = self.__archived_size + size
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
def display(self):
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Print statistics about how many messages were archived"""
|
2002-03-26 03:53:09 +00:00
|
|
|
end_time = time.time()
|
2002-03-31 01:31:11 +00:00
|
|
|
time_seconds = end_time - self.__start_time
|
2002-03-26 03:53:09 +00:00
|
|
|
action = "archived"
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.delete_old_mail:
|
2002-03-26 03:53:09 +00:00
|
|
|
action = "deleted"
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.dry_run:
|
2002-03-31 01:31:11 +00:00
|
|
|
action = "I would have " + action
|
2006-11-02 05:36:17 +00:00
|
|
|
print "%s:\n %s %d of %d message(s) (%s of %s) in %.1f seconds" % \
|
2002-03-31 01:31:11 +00:00
|
|
|
(self.__mailbox_name, action, self.__archived, self.__total,
|
2006-10-31 03:07:02 +00:00
|
|
|
nice_size_str(self.__archived_size),
|
|
|
|
nice_size_str(self.__total_size), time_seconds)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
class StaleFiles:
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Class to keep track of files to be deleted on abnormal exit"""
|
2009-12-29 18:43:23 +00:00
|
|
|
dotlock_files = [] # dotlock files for source mbox and final archive
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
temp_mboxes = [] # temporary retain and archive mboxes
|
2002-05-20 06:14:54 +00:00
|
|
|
temp_dir = None # our tempfile directory container
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
def clean(self):
|
|
|
|
"""Delete any temporary files or lockfiles that exist"""
|
2009-12-29 18:43:23 +00:00
|
|
|
while self.dotlock_files:
|
|
|
|
dotlock = self.dotlock_files.pop()
|
|
|
|
vprint("removing stale dotlock file '%s'" % dotlock)
|
2006-10-29 00:04:09 +00:00
|
|
|
try:
|
2009-12-29 18:43:23 +00:00
|
|
|
os.remove(dotlock)
|
2002-03-31 01:31:11 +00:00
|
|
|
except (IOError, OSError): pass
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
while self.temp_mboxes:
|
|
|
|
mbox = self.temp_mboxes.pop()
|
|
|
|
vprint("removing stale temporary mbox '%s'" % mbox)
|
2006-10-29 00:04:09 +00:00
|
|
|
try:
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
os.remove(mbox)
|
2002-03-31 01:31:11 +00:00
|
|
|
except (IOError, OSError): pass
|
2002-05-20 06:14:54 +00:00
|
|
|
if self.temp_dir:
|
|
|
|
vprint("removing stale tempfile directory '%s'" % self.temp_dir)
|
2006-10-29 00:04:09 +00:00
|
|
|
try:
|
|
|
|
os.rmdir(self.temp_dir)
|
2010-07-16 15:47:25 +00:00
|
|
|
except OSError, e:
|
|
|
|
if e.errno == errno.ENOTEMPTY: # Probably a bug
|
|
|
|
user_warning("cannot remove temporary directory '%s', "
|
|
|
|
"directory not empty" % self.temp_dir)
|
|
|
|
except IOError: pass
|
|
|
|
else: self.temp_dir = None
|
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
class Options:
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Class to store runtime options, including defaults"""
|
2010-07-30 21:26:22 +00:00
|
|
|
archive_prefix = None
|
2010-07-31 12:58:50 +00:00
|
|
|
archive_suffix = None
|
|
|
|
archive_default_suffix = "_archive"
|
2002-03-26 03:53:09 +00:00
|
|
|
days_old_max = 180
|
2002-04-23 03:01:26 +00:00
|
|
|
date_old_max = None
|
2010-07-16 17:13:59 +00:00
|
|
|
delete_old_mail = False
|
|
|
|
dry_run = False
|
2006-06-27 04:40:24 +00:00
|
|
|
filter_append = None
|
2010-07-16 17:13:59 +00:00
|
|
|
include_flagged = False
|
2009-05-22 17:40:07 +00:00
|
|
|
locking_attempts = 5
|
2002-03-26 03:53:09 +00:00
|
|
|
lockfile_extension = ".lock"
|
2010-07-16 17:13:59 +00:00
|
|
|
lock_sleep = True
|
|
|
|
no_compress = False
|
|
|
|
only_archive_read = False
|
2002-04-04 11:14:00 +00:00
|
|
|
output_dir = None
|
2006-06-16 08:34:22 +00:00
|
|
|
pwfile = None
|
2010-07-16 17:13:59 +00:00
|
|
|
preserve_unread = False
|
|
|
|
mangle_from = True
|
|
|
|
quiet = False
|
2002-04-17 06:26:31 +00:00
|
|
|
read_buffer_size = 8192
|
2002-03-26 03:53:09 +00:00
|
|
|
script_name = os.path.basename(sys.argv[0])
|
2002-04-29 12:20:45 +00:00
|
|
|
min_size = None
|
2010-07-16 17:13:59 +00:00
|
|
|
verbose = False
|
|
|
|
debug_imap = False
|
|
|
|
warn_duplicates = False
|
|
|
|
copy_old_mail = False
|
|
|
|
archive_all = False
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
def parse_args(self, args, usage):
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Set our runtime options from the command-line arguments.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
args -- this is sys.argv[1:]
|
|
|
|
usage -- a usage message to display on '--help' or bad arguments
|
|
|
|
|
|
|
|
Returns the remaining command-line arguments that have not yet been
|
|
|
|
parsed as a string.
|
|
|
|
|
|
|
|
"""
|
2002-03-26 03:53:09 +00:00
|
|
|
try:
|
2010-07-30 21:26:22 +00:00
|
|
|
opts, args = getopt.getopt(args, '?D:S:Vd:hno:F:P:qs:p:uv',
|
2002-04-23 03:01:26 +00:00
|
|
|
["date=", "days=", "delete", "dry-run", "help",
|
2002-04-29 12:20:45 +00:00
|
|
|
"include-flagged", "no-compress", "output-dir=",
|
2006-10-30 19:34:39 +00:00
|
|
|
"filter-append=", "pwfile=", "dont-mangle",
|
2002-04-29 12:20:45 +00:00
|
|
|
"preserve-unread", "quiet", "size=", "suffix=",
|
2010-07-30 21:26:22 +00:00
|
|
|
"prefix=", "verbose", "debug-imap=", "version",
|
2008-03-15 20:24:46 +00:00
|
|
|
"warn-duplicate", "copy", "all"])
|
2002-03-26 03:53:09 +00:00
|
|
|
except getopt.error, msg:
|
|
|
|
user_error(msg)
|
2002-04-08 13:39:03 +00:00
|
|
|
|
2002-04-23 03:01:26 +00:00
|
|
|
archive_by = None
|
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
for o, a in opts:
|
|
|
|
if o == '--delete':
|
2007-11-02 17:44:38 +00:00
|
|
|
if self.copy_old_mail:
|
|
|
|
user_error("found conflicting options --copy and --delete")
|
2010-07-16 17:13:59 +00:00
|
|
|
self.delete_old_mail = True
|
2002-04-17 13:15:04 +00:00
|
|
|
if o == '--include-flagged':
|
2010-07-16 17:13:59 +00:00
|
|
|
self.include_flagged = True
|
2002-04-17 06:26:31 +00:00
|
|
|
if o == '--no-compress':
|
2010-07-16 17:13:59 +00:00
|
|
|
self.no_compress = True
|
2002-03-31 03:46:59 +00:00
|
|
|
if o == '--warn-duplicate':
|
2010-07-16 17:13:59 +00:00
|
|
|
self.warn_duplicates = True
|
2002-04-23 03:01:26 +00:00
|
|
|
if o in ('-D', '--date'):
|
|
|
|
if archive_by:
|
|
|
|
user_error("you cannot specify both -d and -D options")
|
|
|
|
archive_by = "date"
|
|
|
|
self.date_old_max = self.date_argument(a)
|
2002-03-26 03:53:09 +00:00
|
|
|
if o in ('-d', '--days'):
|
2002-04-23 03:01:26 +00:00
|
|
|
if archive_by:
|
|
|
|
user_error("you cannot specify both -d and -D options")
|
|
|
|
archive_by = "days"
|
2002-03-26 03:53:09 +00:00
|
|
|
self.days_old_max = string.atoi(a)
|
2002-03-31 01:31:11 +00:00
|
|
|
if o in ('-o', '--output-dir'):
|
2006-11-14 22:20:37 +00:00
|
|
|
self.output_dir = os.path.expanduser(a)
|
2006-06-16 08:34:22 +00:00
|
|
|
if o in ('-P', '--pwfile'):
|
2007-11-02 21:06:59 +00:00
|
|
|
self.pwfile = os.path.expanduser(a)
|
2006-06-27 04:40:24 +00:00
|
|
|
if o in ('-F', '--filter-append'):
|
|
|
|
self.filter_append = a
|
2002-03-26 03:53:09 +00:00
|
|
|
if o in ('-h', '-?', '--help'):
|
|
|
|
print usage
|
|
|
|
sys.exit(0)
|
2002-04-17 13:15:04 +00:00
|
|
|
if o in ('-n', '--dry-run'):
|
2010-07-16 17:13:59 +00:00
|
|
|
self.dry_run = True
|
2002-03-26 03:53:09 +00:00
|
|
|
if o in ('-q', '--quiet'):
|
2010-07-16 17:13:59 +00:00
|
|
|
self.quiet = True
|
2002-03-26 03:53:09 +00:00
|
|
|
if o in ('-s', '--suffix'):
|
|
|
|
self.archive_suffix = a
|
2010-07-30 21:26:22 +00:00
|
|
|
if o in ('-p', '--prefix'):
|
|
|
|
self.archive_prefix = a
|
2002-04-29 12:20:45 +00:00
|
|
|
if o in ('-S', '--size'):
|
|
|
|
self.min_size = string.atoi(a)
|
2002-04-17 13:15:04 +00:00
|
|
|
if o in ('-u', '--preserve-unread'):
|
2010-07-16 17:13:59 +00:00
|
|
|
self.preserve_unread = True
|
2006-10-30 19:34:39 +00:00
|
|
|
if o == '--dont-mangle':
|
2010-07-16 17:13:59 +00:00
|
|
|
self.mangle_from = False
|
2002-04-17 13:15:04 +00:00
|
|
|
if o in ('-v', '--verbose'):
|
2010-07-16 17:13:59 +00:00
|
|
|
self.verbose = True
|
2008-02-14 22:26:10 +00:00
|
|
|
if o == '--debug-imap':
|
|
|
|
self.debug_imap = int(a)
|
2007-11-07 19:52:52 +00:00
|
|
|
if o == '--copy':
|
2007-11-02 17:44:38 +00:00
|
|
|
if self.delete_old_mail:
|
|
|
|
user_error("found conflicting options --copy and --delete")
|
2010-07-16 17:13:59 +00:00
|
|
|
self.copy_old_mail = True
|
2008-03-15 20:24:46 +00:00
|
|
|
if o == '--all':
|
2010-07-16 17:13:59 +00:00
|
|
|
self.archive_all = True
|
2002-03-26 03:53:09 +00:00
|
|
|
if o in ('-V', '--version'):
|
2002-03-31 01:31:11 +00:00
|
|
|
print __version__ + "\n\n" + __copyright__
|
2002-03-26 03:53:09 +00:00
|
|
|
sys.exit(0)
|
|
|
|
return args
|
|
|
|
|
2002-04-03 10:51:26 +00:00
|
|
|
def sanity_check(self):
|
|
|
|
"""Complain bitterly about our options now rather than later"""
|
2002-04-04 11:14:00 +00:00
|
|
|
if self.output_dir:
|
2006-10-31 04:09:31 +00:00
|
|
|
check_sane_destdir(self.output_dir)
|
2007-11-02 21:18:23 +00:00
|
|
|
if self.days_old_max < 0:
|
|
|
|
user_error("--days argument must be positive")
|
2002-04-28 04:00:11 +00:00
|
|
|
if self.days_old_max >= 10000:
|
2002-04-29 12:20:45 +00:00
|
|
|
user_error("--days argument must be less than 10000")
|
|
|
|
if self.min_size is not None and self.min_size < 1:
|
|
|
|
user_error("--size argument must be greater than zero")
|
2002-04-28 04:00:11 +00:00
|
|
|
if self.quiet and self.verbose:
|
|
|
|
user_error("you cannot use both the --quiet and --verbose options")
|
2006-06-16 08:34:22 +00:00
|
|
|
if self.pwfile:
|
|
|
|
if not os.path.isfile(self.pwfile):
|
|
|
|
user_error("pwfile %s does not exist" % self.pwfile)
|
2002-04-03 10:51:26 +00:00
|
|
|
|
2002-04-23 03:01:26 +00:00
|
|
|
def date_argument(self, string):
|
|
|
|
"""Converts a date argument string into seconds since the epoch"""
|
|
|
|
date_formats = (
|
|
|
|
"%Y-%m-%d", # ISO format
|
|
|
|
"%d %b %Y" , # Internet format
|
|
|
|
"%d %B %Y" , # Internet format with full month names
|
|
|
|
)
|
2010-07-16 17:13:59 +00:00
|
|
|
time.accept2dyear = False # I'm not going to support 2-digit years
|
2002-04-23 03:01:26 +00:00
|
|
|
for format in date_formats:
|
|
|
|
try:
|
|
|
|
date = time.strptime(string, format)
|
|
|
|
seconds = time.mktime(date)
|
|
|
|
return seconds
|
|
|
|
except (ValueError, OverflowError):
|
|
|
|
pass
|
|
|
|
user_error("cannot parse the date argument '%s'\n"
|
|
|
|
"The date should be in ISO format (eg '2002-04-23'),\n"
|
|
|
|
"Internet format (eg '23 Apr 2002') or\n"
|
|
|
|
"Internet format with full month names (eg '23 April 2002')" %
|
|
|
|
string)
|
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2009-12-29 18:43:23 +00:00
|
|
|
class LockableMboxMixin:
|
|
|
|
"""Locking methods for mbox files."""
|
2008-08-05 19:24:56 +00:00
|
|
|
|
2009-12-29 18:43:23 +00:00
|
|
|
def __init__(self, mbox_file, mbox_file_name):
|
|
|
|
self.mbox_file = mbox_file
|
|
|
|
self.mbox_file_name = mbox_file_name
|
2009-05-22 17:40:07 +00:00
|
|
|
self._locked = False
|
2010-07-30 11:24:36 +00:00
|
|
|
self._use_dotlock = True
|
2002-04-08 13:39:03 +00:00
|
|
|
|
2009-05-22 17:40:07 +00:00
|
|
|
def lock(self):
|
|
|
|
"""Lock this mbox with both a dotlock and a posix lock."""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert not self._locked
|
2009-05-22 17:40:07 +00:00
|
|
|
attempt = 1
|
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
self._posix_lock()
|
|
|
|
self._dotlock_lock()
|
|
|
|
break
|
|
|
|
except LockUnavailable, e:
|
|
|
|
self._posix_unlock()
|
|
|
|
attempt += 1
|
|
|
|
if (attempt > options.locking_attempts):
|
|
|
|
unexpected_error(str(e))
|
|
|
|
vprint("%s - sleeping..." % e)
|
|
|
|
time.sleep(options.lock_sleep)
|
|
|
|
except:
|
|
|
|
self._posix_unlock()
|
|
|
|
raise
|
|
|
|
self._locked = True
|
|
|
|
|
|
|
|
def unlock(self):
|
|
|
|
"""Unlock this mbox."""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert self._locked
|
2009-05-22 17:40:07 +00:00
|
|
|
self._dotlock_unlock()
|
|
|
|
self._posix_unlock()
|
|
|
|
self._locked = False
|
|
|
|
|
|
|
|
def _posix_lock(self):
|
2009-03-03 03:33:09 +00:00
|
|
|
"""Set an exclusive posix lock on the 'mbox' mailbox"""
|
2009-05-22 17:40:07 +00:00
|
|
|
vprint("trying to acquire posix lock on file '%s'" % self.mbox_file_name)
|
|
|
|
try:
|
|
|
|
fcntl.lockf(self.mbox_file, fcntl.LOCK_EX|fcntl.LOCK_NB)
|
|
|
|
except IOError, e:
|
|
|
|
if e.errno in (errno.EAGAIN, errno.EACCES):
|
|
|
|
raise LockUnavailable("posix lock for '%s' unavailable" % \
|
|
|
|
self.mbox_file_name)
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
vprint("acquired posix lock on file '%s'" % self.mbox_file_name)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2009-05-22 17:40:07 +00:00
|
|
|
def _posix_unlock(self):
|
2009-03-03 03:33:09 +00:00
|
|
|
"""Unset any posix lock on the 'mbox' mailbox"""
|
|
|
|
vprint("dropping posix lock on file '%s'" % self.mbox_file_name)
|
|
|
|
fcntl.lockf(self.mbox_file, fcntl.LOCK_UN)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2009-05-22 17:40:07 +00:00
|
|
|
def _dotlock_lock(self):
|
|
|
|
"""Create a dotlock file for the 'mbox' mailbox"""
|
2006-10-30 19:29:15 +00:00
|
|
|
hostname = socket.gethostname()
|
|
|
|
pid = os.getpid()
|
|
|
|
box_dir, prelock_prefix = os.path.split(self.mbox_file_name)
|
|
|
|
prelock_suffix = ".%s.%s%s" % (hostname, pid, options.lockfile_extension)
|
2010-01-15 22:02:54 +00:00
|
|
|
lock_name = self.mbox_file_name + options.lockfile_extension
|
|
|
|
vprint("trying to create dotlock file '%s'" % lock_name)
|
2009-11-23 19:12:57 +00:00
|
|
|
try:
|
|
|
|
plfd, prelock_name = tempfile.mkstemp(prelock_suffix, prelock_prefix,
|
|
|
|
dir=box_dir)
|
|
|
|
except OSError, e:
|
|
|
|
if e.errno == errno.EACCES:
|
|
|
|
if not options.quiet:
|
|
|
|
user_warning("no write permissions: omitting dotlock for '%s'" % \
|
|
|
|
self.mbox_file_name)
|
2010-07-30 11:24:36 +00:00
|
|
|
self._use_dotlock = False
|
2009-11-23 19:12:57 +00:00
|
|
|
return
|
|
|
|
raise
|
2006-10-30 19:29:15 +00:00
|
|
|
try:
|
2009-05-22 17:40:07 +00:00
|
|
|
try:
|
|
|
|
os.link(prelock_name, lock_name)
|
|
|
|
# We've got the lock.
|
|
|
|
except OSError, e:
|
|
|
|
if os.fstat(plfd)[stat.ST_NLINK] == 2:
|
|
|
|
# The Linux man page for open(2) claims that in this
|
|
|
|
# case we have actually succeeded to create the link,
|
|
|
|
# and this assumption seems to be folklore.
|
|
|
|
# So we've got the lock.
|
|
|
|
pass
|
|
|
|
elif e.errno == errno.EEXIST:
|
|
|
|
raise LockUnavailable("Dotlock for '%s' unavailable" % self.mbox_file_name)
|
|
|
|
else:
|
|
|
|
raise
|
2010-01-15 22:03:32 +00:00
|
|
|
_stale.dotlock_files.append(lock_name)
|
2006-10-30 19:29:15 +00:00
|
|
|
finally:
|
|
|
|
os.close(plfd)
|
|
|
|
os.unlink(prelock_name)
|
|
|
|
vprint("acquired lockfile '%s'" % lock_name)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2009-05-22 17:40:07 +00:00
|
|
|
def _dotlock_unlock(self):
|
|
|
|
"""Delete the dotlock file for the 'mbox' mailbox."""
|
2010-07-30 11:24:36 +00:00
|
|
|
if not self._use_dotlock:
|
|
|
|
return
|
2002-04-12 05:31:59 +00:00
|
|
|
lock_name = self.mbox_file_name + options.lockfile_extension
|
2002-03-26 03:53:09 +00:00
|
|
|
vprint("removing lockfile '%s'" % lock_name)
|
2002-03-31 04:32:31 +00:00
|
|
|
os.remove(lock_name)
|
2009-12-29 18:43:23 +00:00
|
|
|
_stale.dotlock_files.remove(lock_name)
|
|
|
|
|
2010-01-16 00:06:30 +00:00
|
|
|
def commit(self):
|
|
|
|
"""Sync the mbox file to disk."""
|
|
|
|
self.mbox_file.flush()
|
|
|
|
os.fsync(self.mbox_file.fileno())
|
|
|
|
|
2009-12-29 18:43:23 +00:00
|
|
|
def close(self):
|
|
|
|
"""Close the mbox file"""
|
|
|
|
vprint("closing file '%s'" % self.mbox_file_name)
|
2010-07-16 16:54:06 +00:00
|
|
|
assert not self._locked
|
2009-12-29 18:43:23 +00:00
|
|
|
self.mbox_file.close()
|
|
|
|
|
|
|
|
|
|
|
|
class Mbox(mailbox.UnixMailbox, LockableMboxMixin):
|
|
|
|
"""A mostly-read-only mbox with locking. The mbox content can only be
|
|
|
|
modified by overwriting the entire underlying file."""
|
|
|
|
|
|
|
|
def __init__(self, path):
|
|
|
|
"""Constructor for opening an existing 'mbox' mailbox.
|
|
|
|
Extends constructor for mailbox.UnixMailbox()
|
|
|
|
|
|
|
|
Named Arguments:
|
|
|
|
path -- file name of the 'mbox' file to be opened
|
|
|
|
"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert path
|
2009-12-29 18:43:23 +00:00
|
|
|
fd = safe_open_existing(path)
|
|
|
|
st = os.fstat(fd)
|
|
|
|
self.original_atime = st.st_atime
|
|
|
|
self.original_mtime = st.st_mtime
|
|
|
|
self.starting_size = st.st_size
|
|
|
|
self.mbox_file = os.fdopen(fd, "r+")
|
|
|
|
self.mbox_file_name = path
|
|
|
|
LockableMboxMixin.__init__(self, self.mbox_file, path)
|
|
|
|
mailbox.UnixMailbox.__init__(self, self.mbox_file)
|
|
|
|
|
|
|
|
def reset_timestamps(self):
|
|
|
|
"""Set the file timestamps to the original values"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert self.original_atime
|
|
|
|
assert self.original_mtime
|
|
|
|
assert self.mbox_file_name
|
2009-12-29 18:43:23 +00:00
|
|
|
os.utime(self.mbox_file_name, (self.original_atime, \
|
|
|
|
self.original_mtime))
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-04-19 00:19:44 +00:00
|
|
|
def get_size(self):
|
2009-12-30 21:01:03 +00:00
|
|
|
"""Return the current size of the mbox file on disk"""
|
2002-04-19 00:19:44 +00:00
|
|
|
return os.path.getsize(self.mbox_file_name)
|
|
|
|
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
def overwrite_with(self, mbox_filename):
|
|
|
|
"""Overwrite the mbox content with the content of the given mbox file."""
|
|
|
|
fin = open(mbox_filename, "r")
|
|
|
|
self.mbox_file.seek(0)
|
|
|
|
shutil.copyfileobj(fin, self.mbox_file)
|
|
|
|
self.mbox_file.truncate()
|
|
|
|
|
|
|
|
|
2009-12-29 18:43:23 +00:00
|
|
|
class ArchiveMbox(LockableMboxMixin):
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
"""Simple append-only access to the archive mbox. Entirely content-agnostic."""
|
|
|
|
|
|
|
|
def __init__(self, path):
|
|
|
|
fd = safe_open(path)
|
|
|
|
self.mbox_file = os.fdopen(fd, "a")
|
2009-12-29 18:43:23 +00:00
|
|
|
LockableMboxMixin.__init__(self, self.mbox_file, path)
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
|
|
|
|
def append(self, filename):
|
|
|
|
"""Append the content of the given file to the mbox."""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert self._locked
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
fin = open(filename, "r")
|
2010-01-15 23:58:35 +00:00
|
|
|
oldsize = os.fstat(self.mbox_file.fileno()).st_size
|
|
|
|
try:
|
|
|
|
shutil.copyfileobj(fin, self.mbox_file)
|
|
|
|
except:
|
|
|
|
# We can safely abort here without data loss, because
|
|
|
|
# we have not yet changed the original mailbox
|
|
|
|
self.mbox_file.truncate(oldsize)
|
|
|
|
raise
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
fin.close()
|
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2008-08-05 19:24:56 +00:00
|
|
|
class TempMbox:
|
2009-12-30 21:01:03 +00:00
|
|
|
"""A write-only temporary mbox. No locking methods."""
|
2008-08-05 19:24:56 +00:00
|
|
|
|
|
|
|
def __init__(self, prefix=tempfile.template):
|
|
|
|
"""Creates a temporary mbox file."""
|
|
|
|
fd, filename = tempfile.mkstemp(prefix=prefix)
|
|
|
|
self.mbox_file_name = filename
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
_stale.temp_mboxes.append(filename)
|
2008-08-05 19:24:56 +00:00
|
|
|
self.mbox_file = os.fdopen(fd, "w")
|
2008-08-09 00:56:19 +00:00
|
|
|
# an empty gzip file is not really empty (it contains the gzip header
|
|
|
|
# and trailer), so we need to track manually if this mbox is empty
|
|
|
|
self.empty = True
|
2008-08-05 19:24:56 +00:00
|
|
|
|
|
|
|
def write(self, msg):
|
|
|
|
"""Write a rfc822 message object to the 'mbox' mailbox.
|
|
|
|
If the rfc822 has no Unix 'From_' line, then one is constructed
|
|
|
|
from other headers in the message.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
msg -- rfc822 message object to be written
|
|
|
|
|
|
|
|
"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert msg
|
|
|
|
assert self.mbox_file
|
2008-08-05 19:24:56 +00:00
|
|
|
|
2008-08-09 00:56:19 +00:00
|
|
|
self.empty = False
|
2008-08-05 19:24:56 +00:00
|
|
|
vprint("saving message to file '%s'" % self.mbox_file_name)
|
|
|
|
unix_from = msg.unixfrom
|
|
|
|
if unix_from:
|
|
|
|
msg_has_mbox_format = True
|
|
|
|
else:
|
|
|
|
msg_has_mbox_format = False
|
|
|
|
unix_from = make_mbox_from(msg)
|
|
|
|
self.mbox_file.write(unix_from)
|
2010-07-16 16:54:06 +00:00
|
|
|
assert msg.headers
|
2008-08-05 19:24:56 +00:00
|
|
|
self.mbox_file.writelines(msg.headers)
|
|
|
|
self.mbox_file.write(os.linesep)
|
|
|
|
|
|
|
|
# The following while loop is about twice as fast in
|
|
|
|
# practice to 'self.mbox_file.writelines(msg.fp.readlines())'
|
2010-07-16 16:54:06 +00:00
|
|
|
assert options.read_buffer_size > 0
|
2008-08-05 19:24:56 +00:00
|
|
|
linebuf = ""
|
2010-07-16 17:13:59 +00:00
|
|
|
while True:
|
2008-08-05 19:24:56 +00:00
|
|
|
body = msg.fp.read(options.read_buffer_size)
|
|
|
|
if (not msg_has_mbox_format) and options.mangle_from:
|
|
|
|
# Be careful not to break pattern matching
|
|
|
|
splitindex = body.rfind(os.linesep)
|
|
|
|
nicebody = linebuf + body[:splitindex]
|
|
|
|
linebuf = body[splitindex:]
|
|
|
|
body = from_re.sub('>From ', nicebody)
|
|
|
|
if not body:
|
|
|
|
break
|
|
|
|
self.mbox_file.write(body)
|
|
|
|
if not msg_has_mbox_format:
|
|
|
|
self.mbox_file.write(os.linesep)
|
|
|
|
|
2010-01-16 00:06:30 +00:00
|
|
|
def commit(self):
|
|
|
|
"""Sync the mbox file to disk."""
|
|
|
|
self.mbox_file.flush()
|
|
|
|
os.fsync(self.mbox_file.fileno())
|
|
|
|
|
2008-08-05 19:24:56 +00:00
|
|
|
def close(self):
|
|
|
|
"""Close the mbox file"""
|
|
|
|
vprint("closing file '%s'" % self.mbox_file_name)
|
|
|
|
self.mbox_file.close()
|
|
|
|
|
2010-01-15 23:58:35 +00:00
|
|
|
def saveas(self, filename):
|
|
|
|
"""Rename this temporary mbox file to the given name, making it
|
|
|
|
permanent. Emergency use only."""
|
|
|
|
os.rename(self.mbox_file_name, filename)
|
2010-07-17 00:41:05 +00:00
|
|
|
_stale.temp_mboxes.remove(self.mbox_file_name)
|
2010-01-15 23:58:35 +00:00
|
|
|
|
2008-08-05 19:24:56 +00:00
|
|
|
def remove(self):
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
"""Delete the temporary mbox file."""
|
|
|
|
os.remove(self.mbox_file_name)
|
|
|
|
_stale.temp_mboxes.remove(self.mbox_file_name)
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2009-12-30 21:01:03 +00:00
|
|
|
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
class CompressedTempMbox(TempMbox):
|
|
|
|
"""A compressed version of a TempMbox."""
|
2002-03-26 03:53:09 +00:00
|
|
|
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
def __init__(self, prefix=tempfile.template):
|
|
|
|
TempMbox.__init__(self, prefix)
|
|
|
|
self.raw_file = self.mbox_file
|
|
|
|
self.mbox_file = gzip.GzipFile(mode="a", fileobj=self.mbox_file)
|
2010-01-16 00:06:30 +00:00
|
|
|
# Workaround that GzipFile.close() isn't idempotent in Python < 2.6
|
|
|
|
# (python issue #2959). There is no GzipFile.closed, so we need a
|
|
|
|
# replacement.
|
|
|
|
self.gzipfile_closed = False
|
|
|
|
|
|
|
|
def commit(self):
|
|
|
|
"""Finish gzip file and sync it to disk."""
|
|
|
|
# This method is currently not used
|
|
|
|
self.mbox_file.close() # close GzipFile, writing gzip trailer
|
|
|
|
self.gzipfile_closed = True
|
|
|
|
self.raw_file.flush()
|
|
|
|
os.fsync(self.raw_file.fileno())
|
2008-08-05 19:24:56 +00:00
|
|
|
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
def close(self):
|
2010-01-16 00:06:30 +00:00
|
|
|
"""Close the gzip file."""
|
|
|
|
if not self.gzipfile_closed:
|
|
|
|
self.mbox_file.close()
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
self.raw_file.close()
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
class IdentityCache:
|
2002-04-17 06:26:31 +00:00
|
|
|
"""Class used to remember Message-IDs and warn if they are seen twice"""
|
2002-03-31 01:31:11 +00:00
|
|
|
seen_ids = {}
|
|
|
|
mailbox_name = None
|
2002-04-02 13:37:49 +00:00
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
def __init__(self, mailbox_name):
|
2002-04-17 06:26:31 +00:00
|
|
|
"""Constructor: takes the mailbox name as an argument"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
2002-03-31 01:31:11 +00:00
|
|
|
self.mailbox_name = mailbox_name
|
2002-04-02 13:37:49 +00:00
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
def warn_if_dupe(self, msg):
|
2002-04-17 06:26:31 +00:00
|
|
|
"""Print a warning message if the message has already appeared"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert msg
|
2002-03-31 01:31:11 +00:00
|
|
|
message_id = msg.get('Message-ID')
|
2010-07-16 16:54:06 +00:00
|
|
|
assert message_id
|
2002-04-26 03:04:02 +00:00
|
|
|
if self.seen_ids.has_key(message_id):
|
2002-03-31 01:31:11 +00:00
|
|
|
user_warning("duplicate message id: '%s' in mailbox '%s'" %
|
|
|
|
(message_id, self.mailbox_name))
|
2010-07-16 17:13:59 +00:00
|
|
|
self.seen_ids[message_id] = True
|
2002-03-31 01:31:11 +00:00
|
|
|
|
|
|
|
|
|
|
|
# global class instances
|
2002-04-09 12:59:26 +00:00
|
|
|
options = Options() # the run-time options object
|
2002-04-08 13:39:03 +00:00
|
|
|
_stale = StaleFiles() # remember what we have to delete on abnormal exit
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
def main(args = sys.argv[1:]):
|
2002-03-31 01:31:11 +00:00
|
|
|
global _stale
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-04-17 06:26:31 +00:00
|
|
|
# this usage message is longer than 24 lines -- bad idea?
|
2002-03-26 03:53:09 +00:00
|
|
|
usage = """Usage: %s [options] mailbox [mailbox...]
|
2002-10-03 06:27:08 +00:00
|
|
|
Moves old mail in IMAP, mbox, MH or maildir-format mailboxes to an mbox-format
|
2002-04-17 06:26:31 +00:00
|
|
|
mailbox compressed with gzip.
|
2002-03-31 01:31:11 +00:00
|
|
|
|
|
|
|
Options are as follows:
|
2002-04-23 03:01:26 +00:00
|
|
|
-d, --days=NUM archive messages older than NUM days (default: %d)
|
|
|
|
-D, --date=DATE archive messages older than DATE
|
2002-04-17 06:26:31 +00:00
|
|
|
-o, --output-dir=DIR directory to store archives (default: same as original)
|
2006-06-16 08:34:22 +00:00
|
|
|
-P, --pwfile=FILE file to read imap password from (default: None)
|
2006-06-27 04:40:24 +00:00
|
|
|
-F, --filter-append=STRING append arbitrary string to the IMAP filter string
|
2010-07-30 21:26:22 +00:00
|
|
|
-p, --prefix=NAME prefix for archive filename (default: none)
|
2002-04-17 06:26:31 +00:00
|
|
|
-s, --suffix=NAME suffix for archive filename (default: '%s')
|
2002-04-29 12:20:45 +00:00
|
|
|
-S, --size=NUM only archive messages NUM bytes or larger
|
2002-04-17 06:26:31 +00:00
|
|
|
-n, --dry-run don't write to anything - just show what would be done
|
|
|
|
-u, --preserve-unread never archive unread messages
|
2006-10-30 19:34:39 +00:00
|
|
|
--dont-mangle do not mangle From_ in message bodies
|
2002-04-17 06:26:31 +00:00
|
|
|
--delete delete rather than archive old mail (use with caution!)
|
2007-11-02 21:21:17 +00:00
|
|
|
--copy copy rather than archive old mail
|
2002-04-17 13:15:04 +00:00
|
|
|
--include-flagged messages flagged important can also be archived
|
2008-03-15 20:24:46 +00:00
|
|
|
--all archive all messages
|
2002-04-17 06:26:31 +00:00
|
|
|
--no-compress do not compress archives with gzip
|
|
|
|
--warn-duplicate warn about duplicate Message-IDs in the same mailbox
|
|
|
|
-v, --verbose report lots of extra debugging information
|
2008-02-14 22:26:10 +00:00
|
|
|
--debug-imap=NUM set IMAP debugging output level (0 is none)
|
2002-04-17 06:26:31 +00:00
|
|
|
-q, --quiet quiet mode - print no statistics (suitable for crontab)
|
|
|
|
-V, --version display version information
|
|
|
|
-h, --help display this message
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2002-04-21 01:14:54 +00:00
|
|
|
Example: %s linux-kernel
|
2002-03-31 01:31:11 +00:00
|
|
|
This will move all messages older than %s days to a 'mbox' mailbox called
|
2002-04-21 01:14:54 +00:00
|
|
|
'linux-kernel_archive.gz', deleting them from the original 'linux-kernel'
|
|
|
|
mailbox. If the 'linux-kernel_archive.gz' mailbox already exists, the
|
2002-03-26 03:53:09 +00:00
|
|
|
newly archived messages are appended.
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2002-10-03 06:27:08 +00:00
|
|
|
To archive IMAP mailboxes, format your mailbox argument like this:
|
|
|
|
imap://username:password@server/mailbox
|
2006-06-16 08:34:22 +00:00
|
|
|
(substitute 'imap' with 'imaps' for an SSL connection)
|
2002-10-03 06:27:08 +00:00
|
|
|
|
2002-03-31 04:32:31 +00:00
|
|
|
Website: http://archivemail.sourceforge.net/ """ % \
|
2002-04-09 12:59:26 +00:00
|
|
|
(options.script_name, options.days_old_max, options.archive_suffix,
|
|
|
|
options.script_name, options.days_old_max)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-04-09 12:59:26 +00:00
|
|
|
args = options.parse_args(args, usage)
|
2002-03-26 03:53:09 +00:00
|
|
|
if len(args) == 0:
|
|
|
|
print usage
|
|
|
|
sys.exit(1)
|
|
|
|
|
2002-04-09 12:59:26 +00:00
|
|
|
options.sanity_check()
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
for mailbox_path in args:
|
|
|
|
archive(mailbox_path)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
|
|
|
|
######## errors and debug ##########
|
|
|
|
|
|
|
|
def vprint(string):
|
2002-03-31 01:31:11 +00:00
|
|
|
"""Print the string argument if we are in verbose mode"""
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.verbose:
|
2002-03-26 03:53:09 +00:00
|
|
|
print string
|
|
|
|
|
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
def unexpected_error(string):
|
2007-10-23 22:27:57 +00:00
|
|
|
"""Print the string argument, a 'shutting down' message and abort. Raise
|
|
|
|
UnexpectedErrors if archivemail is run as a module. This function never
|
|
|
|
returns."""
|
|
|
|
if not __name__ == '__main__':
|
|
|
|
raise UnexpectedError(string)
|
2002-04-09 12:59:26 +00:00
|
|
|
sys.stderr.write("%s: %s\n" % (options.script_name, string))
|
2002-03-31 01:31:11 +00:00
|
|
|
sys.stderr.write("%s: unexpected error encountered - shutting down\n" %
|
2002-04-09 12:59:26 +00:00
|
|
|
options.script_name)
|
2002-03-31 01:31:11 +00:00
|
|
|
sys.exit(1)
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
|
|
|
|
def user_error(string):
|
2007-10-23 22:27:57 +00:00
|
|
|
"""Print the string argument and abort. Raise UserError if archivemail is
|
|
|
|
run as a module. This function never returns."""
|
|
|
|
if not __name__ == '__main__':
|
|
|
|
raise UserError(string)
|
2002-04-09 12:59:26 +00:00
|
|
|
sys.stderr.write("%s: %s\n" % (options.script_name, string))
|
2002-03-26 03:53:09 +00:00
|
|
|
sys.exit(1)
|
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
|
|
|
|
def user_warning(string):
|
|
|
|
"""Print the string argument"""
|
2002-04-09 12:59:26 +00:00
|
|
|
sys.stderr.write("%s: Warning - %s\n" % (options.script_name, string))
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
########### operations on a message ############
|
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
def make_mbox_from(message):
|
|
|
|
"""Return a string suitable for use as a 'From_' mbox header for the
|
|
|
|
message.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
message -- the rfc822 message object
|
|
|
|
|
|
|
|
"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert message
|
2002-09-15 06:14:57 +00:00
|
|
|
address = guess_return_path(message)
|
2002-04-04 02:41:37 +00:00
|
|
|
time_message = guess_delivery_time(message)
|
2007-11-13 02:59:31 +00:00
|
|
|
date = time.localtime(time_message)
|
2010-07-16 16:54:06 +00:00
|
|
|
assert date
|
2007-11-13 02:59:31 +00:00
|
|
|
date_string = time.asctime(date)
|
2002-03-31 01:31:11 +00:00
|
|
|
mbox_from = "From %s %s\n" % (address, date_string)
|
|
|
|
return mbox_from
|
|
|
|
|
2002-04-03 11:12:25 +00:00
|
|
|
|
2002-09-15 06:14:57 +00:00
|
|
|
def guess_return_path(message):
|
|
|
|
"""Return a guess at the Return Path address of an rfc822 message"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert message
|
2002-09-15 06:14:57 +00:00
|
|
|
|
|
|
|
for header in ('Return-path', 'From'):
|
2006-09-28 22:26:07 +00:00
|
|
|
address_header = message.get(header)
|
2002-09-15 06:14:57 +00:00
|
|
|
if address_header:
|
|
|
|
(name, address) = rfc822.parseaddr(address_header)
|
|
|
|
if address:
|
|
|
|
return address
|
|
|
|
# argh, we can't find any valid 'Return-path' guesses - just
|
|
|
|
# just use the current unix username like mutt does
|
|
|
|
login = pwd.getpwuid(os.getuid())[0]
|
2010-07-16 16:54:06 +00:00
|
|
|
assert login
|
2002-09-15 06:14:57 +00:00
|
|
|
return login
|
|
|
|
|
|
|
|
|
2002-04-04 02:41:37 +00:00
|
|
|
def guess_delivery_time(message):
|
|
|
|
"""Return a guess at the delivery date of an rfc822 message"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert message
|
2002-04-04 02:41:37 +00:00
|
|
|
# try to guess the delivery date from various headers
|
|
|
|
# get more desparate as we go through the array
|
2007-11-13 21:13:38 +00:00
|
|
|
for header in 'Delivery-date', 'Received', 'Resent-Date', 'Date':
|
|
|
|
try:
|
|
|
|
if header == 'Received':
|
|
|
|
# This should be good enough for almost all headers in the wild;
|
|
|
|
# if we're guessing wrong, parsedate_tz() will fail graciously.
|
|
|
|
token = message.getrawheader(header).rsplit(';', 1)[-1]
|
|
|
|
else:
|
|
|
|
token = message.get(header)
|
|
|
|
date = rfc822.parsedate_tz(token)
|
2002-05-07 12:14:29 +00:00
|
|
|
if date:
|
2007-11-13 02:59:31 +00:00
|
|
|
time_message = rfc822.mktime_tz(date)
|
2002-04-04 02:41:37 +00:00
|
|
|
vprint("using valid time found from '%s' header" % header)
|
|
|
|
return time_message
|
2007-11-13 21:13:38 +00:00
|
|
|
except (AttributeError, IndexError, ValueError, OverflowError): pass
|
2002-04-04 02:41:37 +00:00
|
|
|
# as a second-last resort, try the date from the 'From_' line (ugly)
|
|
|
|
# this will only work from a mbox-format mailbox
|
|
|
|
if (message.unixfrom):
|
2007-11-13 02:59:31 +00:00
|
|
|
# Hmm. This will break with full-blown RFC 2822 addr-spec's.
|
|
|
|
header = message.unixfrom.split(None, 2)[-1]
|
|
|
|
# Interpret no timezone as localtime
|
|
|
|
date = rfc822.parsedate_tz(header)
|
2002-04-04 02:41:37 +00:00
|
|
|
if date:
|
|
|
|
try:
|
2007-11-13 02:59:31 +00:00
|
|
|
time_message = rfc822.mktime_tz(date)
|
2002-04-04 02:41:37 +00:00
|
|
|
vprint("using valid time found from unix 'From_' header")
|
|
|
|
return time_message
|
|
|
|
except (ValueError, OverflowError): pass
|
|
|
|
# the headers have no valid dates -- last resort, try the file timestamp
|
|
|
|
# this will not work for mbox mailboxes
|
|
|
|
try:
|
2007-10-22 22:03:44 +00:00
|
|
|
file_name = get_filename(message)
|
2002-04-04 02:41:37 +00:00
|
|
|
except AttributeError:
|
|
|
|
# we are looking at a 'mbox' mailbox - argh!
|
|
|
|
# Just return the current time - this will never get archived :(
|
|
|
|
vprint("no valid times found at all -- using current time!")
|
|
|
|
return time.time()
|
|
|
|
if not os.path.isfile(file_name):
|
|
|
|
unexpected_error("mailbox file name '%s' has gone missing" % \
|
|
|
|
file_name)
|
2007-10-22 22:03:44 +00:00
|
|
|
time_message = os.path.getmtime(file_name)
|
2002-04-04 02:41:37 +00:00
|
|
|
vprint("using valid time found from '%s' last-modification time" % \
|
|
|
|
file_name)
|
2002-03-31 01:31:11 +00:00
|
|
|
return time_message
|
2002-04-17 06:26:31 +00:00
|
|
|
|
|
|
|
|
2002-04-18 12:02:33 +00:00
|
|
|
def add_status_headers(message):
|
|
|
|
"""
|
|
|
|
Add Status and X-Status headers to a message from a maildir mailbox.
|
|
|
|
|
|
|
|
Maildir messages store their information about being read/replied/etc in
|
|
|
|
the suffix of the filename rather than in Status and X-Status headers in
|
|
|
|
the message. In order to archive maildir messages into mbox format, it is
|
|
|
|
nice to preserve this information by putting it into the status headers.
|
|
|
|
|
|
|
|
"""
|
|
|
|
status = ""
|
|
|
|
x_status = ""
|
2007-10-22 22:03:44 +00:00
|
|
|
file_name = get_filename(message)
|
|
|
|
match = re.search(":2,(.+)$", file_name)
|
2002-04-18 12:02:33 +00:00
|
|
|
if match:
|
|
|
|
flags = match.group(1)
|
|
|
|
for flag in flags:
|
|
|
|
if flag == "D": # (draft): the user considers this message a draft
|
|
|
|
pass # does this make any sense in mbox?
|
|
|
|
elif flag == "F": # (flagged): user-defined 'important' flag
|
|
|
|
x_status = x_status + "F"
|
|
|
|
elif flag == "R": # (replied): the user has replied to this message
|
|
|
|
x_status = x_status + "A"
|
|
|
|
elif flag == "S": # (seen): the user has viewed this message
|
|
|
|
status = status + "R"
|
|
|
|
elif flag == "T": # (trashed): user has moved this message to trash
|
|
|
|
pass # is this Status: D ?
|
|
|
|
else:
|
|
|
|
pass # no whingeing here, although it could be a good experiment
|
|
|
|
|
|
|
|
# files in the maildir 'cur' directory are no longer new,
|
|
|
|
# they are the same as messages with 'Status: O' headers in mbox
|
2007-10-22 22:03:44 +00:00
|
|
|
last_dir = os.path.basename(os.path.dirname(file_name))
|
2002-04-18 12:02:33 +00:00
|
|
|
if last_dir == "cur":
|
|
|
|
status = status + "O"
|
|
|
|
|
2007-11-02 23:35:50 +00:00
|
|
|
# Overwrite existing 'Status' and 'X-Status' headers. They add no value in
|
|
|
|
# maildirs, and we better don't listen to them.
|
|
|
|
if status:
|
2002-04-18 12:02:33 +00:00
|
|
|
vprint("converting maildir status into Status header '%s'" % status)
|
|
|
|
message['Status'] = status
|
2007-11-13 00:32:49 +00:00
|
|
|
else:
|
|
|
|
del message['Status']
|
2007-11-02 23:35:50 +00:00
|
|
|
if x_status:
|
2002-04-18 12:02:33 +00:00
|
|
|
vprint("converting maildir status into X-Status header '%s'" % x_status)
|
|
|
|
message['X-Status'] = x_status
|
2007-11-13 00:32:49 +00:00
|
|
|
else:
|
|
|
|
del message['X-Status']
|
2002-04-18 12:02:33 +00:00
|
|
|
|
2002-10-03 06:27:08 +00:00
|
|
|
def add_status_headers_imap(message, flags):
|
|
|
|
"""Add Status and X-Status headers to a message from an imap mailbox."""
|
|
|
|
status = ""
|
|
|
|
x_status = ""
|
|
|
|
for flag in flags:
|
|
|
|
if flag == "\\Draft": # (draft): the user considers this message a draft
|
|
|
|
pass # does this make any sense in mbox?
|
|
|
|
elif flag == "\\Flagged": # (flagged): user-defined 'important' flag
|
|
|
|
x_status = x_status + "F"
|
|
|
|
elif flag == "\\Answered": # (replied): the user has replied to this message
|
|
|
|
x_status = x_status + "A"
|
|
|
|
elif flag == "\\Seen": # (seen): the user has viewed this message
|
|
|
|
status = status + "R"
|
|
|
|
elif flag == "\\Deleted": # (trashed): user has moved this message to trash
|
|
|
|
pass # is this Status: D ?
|
|
|
|
else:
|
|
|
|
pass # no whingeing here, although it could be a good experiment
|
2007-11-07 19:52:52 +00:00
|
|
|
if not "\\Recent" in flags:
|
2007-11-02 11:26:20 +00:00
|
|
|
status = status + "O"
|
2002-10-03 06:27:08 +00:00
|
|
|
|
2007-11-02 23:35:50 +00:00
|
|
|
# As with maildir folders, overwrite Status and X-Status headers
|
|
|
|
# if they exist.
|
2007-11-07 23:51:41 +00:00
|
|
|
vprint("converting imap status (%s)..." % " ".join(flags))
|
2007-11-02 23:35:50 +00:00
|
|
|
if status:
|
2007-11-07 23:51:41 +00:00
|
|
|
vprint("generating Status header '%s'" % status)
|
2002-10-03 06:27:08 +00:00
|
|
|
message['Status'] = status
|
2007-11-07 23:51:41 +00:00
|
|
|
else:
|
|
|
|
vprint("not generating Status header")
|
2007-11-13 00:32:49 +00:00
|
|
|
del message['Status']
|
2007-11-02 23:35:50 +00:00
|
|
|
if x_status:
|
2007-11-07 23:51:41 +00:00
|
|
|
vprint("generating X-Status header '%s'" % x_status)
|
2002-10-03 06:27:08 +00:00
|
|
|
message['X-Status'] = x_status
|
2007-11-07 23:51:41 +00:00
|
|
|
else:
|
|
|
|
vprint("not generating X-Status header")
|
2007-11-13 00:32:49 +00:00
|
|
|
del message['X-Status']
|
2002-04-18 12:02:33 +00:00
|
|
|
|
2002-04-17 13:15:04 +00:00
|
|
|
def is_flagged(message):
|
|
|
|
"""return true if the message is flagged important, false otherwise"""
|
|
|
|
# MH and mbox mailboxes use the 'X-Status' header to indicate importance
|
|
|
|
x_status = message.get('X-Status')
|
|
|
|
if x_status and re.search('F', x_status):
|
|
|
|
vprint("message is important (X-Status header='%s')" % x_status)
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
2002-04-17 13:15:04 +00:00
|
|
|
file_name = None
|
|
|
|
try:
|
2007-10-22 22:03:44 +00:00
|
|
|
file_name = get_filename(message)
|
2002-04-17 13:15:04 +00:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
# maildir mailboxes use the filename suffix to indicate flagged status
|
|
|
|
if file_name and re.search(":2,.*F.*$", file_name):
|
|
|
|
vprint("message is important (filename info has 'F')")
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
2002-04-17 13:15:04 +00:00
|
|
|
vprint("message is not flagged important")
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-17 13:15:04 +00:00
|
|
|
|
|
|
|
|
2002-04-17 06:26:31 +00:00
|
|
|
def is_unread(message):
|
|
|
|
"""return true if the message is unread, false otherwise"""
|
|
|
|
# MH and mbox mailboxes use the 'Status' header to indicate read status
|
|
|
|
status = message.get('Status')
|
2002-04-17 13:15:04 +00:00
|
|
|
if status and re.search('R', status):
|
2002-04-17 06:26:31 +00:00
|
|
|
vprint("message has been read (status header='%s')" % status)
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-17 06:26:31 +00:00
|
|
|
file_name = None
|
|
|
|
try:
|
2007-10-22 22:03:44 +00:00
|
|
|
file_name = get_filename(message)
|
2002-04-17 06:26:31 +00:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
# maildir mailboxes use the filename suffix to indicate read status
|
|
|
|
if file_name and re.search(":2,.*S.*$", file_name):
|
|
|
|
vprint("message has been read (filename info has 'S')")
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-17 06:26:31 +00:00
|
|
|
vprint("message is unread")
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
2002-04-17 06:26:31 +00:00
|
|
|
|
|
|
|
|
2006-10-31 03:07:02 +00:00
|
|
|
def sizeof_message(message):
|
|
|
|
"""Return size of message in bytes (octets)."""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert message
|
2002-04-29 12:20:45 +00:00
|
|
|
file_name = None
|
|
|
|
message_size = None
|
|
|
|
try:
|
2007-10-22 22:03:44 +00:00
|
|
|
file_name = get_filename(message)
|
2002-04-29 12:20:45 +00:00
|
|
|
except AttributeError:
|
|
|
|
pass
|
|
|
|
if file_name:
|
|
|
|
# with maildir and MH mailboxes, we can just use the file size
|
|
|
|
message_size = os.path.getsize(file_name)
|
|
|
|
else:
|
|
|
|
# with mbox mailboxes, not so easy
|
|
|
|
message_size = 0
|
|
|
|
if message.unixfrom:
|
|
|
|
message_size = message_size + len(message.unixfrom)
|
|
|
|
for header in message.headers:
|
|
|
|
message_size = message_size + len(header)
|
|
|
|
message_size = message_size + 1 # the blank line after the headers
|
|
|
|
start_offset = message.fp.tell()
|
|
|
|
message.fp.seek(0, 2) # seek to the end of the message
|
|
|
|
end_offset = message.fp.tell()
|
|
|
|
message.rewindbody()
|
|
|
|
message_size = message_size + (end_offset - start_offset)
|
2006-10-31 03:07:02 +00:00
|
|
|
return message_size
|
|
|
|
|
|
|
|
def is_smaller(message, size):
|
|
|
|
"""Return true if the message is smaller than size bytes, false otherwise"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert message
|
|
|
|
assert size > 0
|
2006-10-31 03:07:02 +00:00
|
|
|
message_size = sizeof_message(message)
|
2002-04-29 12:20:45 +00:00
|
|
|
if message_size < size:
|
|
|
|
vprint("message is too small (%d bytes), minimum bytes : %d" % \
|
|
|
|
(message_size, size))
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
2002-04-29 12:20:45 +00:00
|
|
|
else:
|
|
|
|
vprint("message is not too small (%d bytes), minimum bytes: %d" % \
|
|
|
|
(message_size, size))
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-29 12:20:45 +00:00
|
|
|
|
|
|
|
|
2002-04-17 06:26:31 +00:00
|
|
|
def should_archive(message):
|
2002-04-23 03:01:26 +00:00
|
|
|
"""Return true if we should archive the message, false otherwise"""
|
2008-03-15 20:24:46 +00:00
|
|
|
if options.archive_all:
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
|
|
|
old = False
|
2002-04-17 06:26:31 +00:00
|
|
|
time_message = guess_delivery_time(message)
|
2002-04-23 03:01:26 +00:00
|
|
|
if options.date_old_max == None:
|
|
|
|
old = is_older_than_days(time_message, options.days_old_max)
|
|
|
|
else:
|
|
|
|
old = is_older_than_time(time_message, options.date_old_max)
|
|
|
|
|
2002-04-17 06:26:31 +00:00
|
|
|
# I could probably do this in one if statement, but then I wouldn't
|
2002-04-23 03:01:26 +00:00
|
|
|
# understand it.
|
|
|
|
if not old:
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-23 03:01:26 +00:00
|
|
|
if not options.include_flagged and is_flagged(message):
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-29 12:20:45 +00:00
|
|
|
if options.min_size and is_smaller(message, options.min_size):
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-23 03:01:26 +00:00
|
|
|
if options.preserve_unread and is_unread(message):
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
|
|
|
return True
|
2002-04-23 03:01:26 +00:00
|
|
|
|
2002-04-17 06:26:31 +00:00
|
|
|
|
2002-04-23 03:01:26 +00:00
|
|
|
def is_older_than_time(time_message, max_time):
|
|
|
|
"""Return true if a message is older than the specified time,
|
|
|
|
false otherwise.
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2002-04-23 03:01:26 +00:00
|
|
|
Arguments:
|
|
|
|
time_message -- the delivery date of the message measured in seconds
|
|
|
|
since the epoch
|
|
|
|
max_time -- maximum time allowed for message
|
|
|
|
|
|
|
|
"""
|
|
|
|
days_old = (max_time - time_message) / 24 / 60 / 60
|
|
|
|
if time_message < max_time:
|
|
|
|
vprint("message is %.2f days older than the specified date" % days_old)
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
2002-04-23 03:01:26 +00:00
|
|
|
vprint("message is %.2f days younger than the specified date" % \
|
|
|
|
abs(days_old))
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-23 03:01:26 +00:00
|
|
|
|
|
|
|
|
|
|
|
def is_older_than_days(time_message, max_days):
|
|
|
|
"""Return true if a message is older than the specified number of days,
|
2002-03-31 01:31:11 +00:00
|
|
|
false otherwise.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
time_message -- the delivery date of the message measured in seconds
|
|
|
|
since the epoch
|
2002-04-23 03:01:26 +00:00
|
|
|
max_days -- maximum number of days before message is considered old
|
2002-03-31 01:31:11 +00:00
|
|
|
"""
|
2002-03-26 03:53:09 +00:00
|
|
|
time_now = time.time()
|
|
|
|
if time_message > time_now:
|
2002-03-31 01:31:11 +00:00
|
|
|
vprint("warning: message has date in the future")
|
2010-07-16 17:13:59 +00:00
|
|
|
return False
|
2002-04-08 13:39:03 +00:00
|
|
|
secs_old_max = (max_days * 24 * 60 * 60)
|
2002-03-26 03:53:09 +00:00
|
|
|
days_old = (time_now - time_message) / 24 / 60 / 60
|
|
|
|
vprint("message is %.2f days old" % days_old)
|
|
|
|
if ((time_message + secs_old_max) < time_now):
|
2010-07-16 17:13:59 +00:00
|
|
|
return True
|
|
|
|
return False
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2006-11-01 05:27:30 +00:00
|
|
|
def build_imap_filter():
|
2002-10-03 06:27:08 +00:00
|
|
|
"""Return an imap filter string"""
|
|
|
|
|
2006-11-01 00:40:26 +00:00
|
|
|
imap_filter = []
|
2002-10-03 06:27:08 +00:00
|
|
|
if options.date_old_max == None:
|
|
|
|
time_now = time.time()
|
|
|
|
secs_old_max = (options.days_old_max * 24 * 60 * 60)
|
|
|
|
time_old = time.gmtime(time_now - secs_old_max)
|
|
|
|
else:
|
|
|
|
time_old = time.gmtime(options.date_old_max)
|
2006-10-31 00:35:19 +00:00
|
|
|
time_str = time.strftime('%d-%b-%Y', time_old)
|
2006-11-01 00:40:26 +00:00
|
|
|
imap_filter.append("BEFORE %s" % time_str)
|
2002-10-03 06:27:08 +00:00
|
|
|
|
|
|
|
if not options.include_flagged:
|
2006-11-01 00:40:26 +00:00
|
|
|
imap_filter.append("UNFLAGGED")
|
2002-10-03 06:27:08 +00:00
|
|
|
if options.min_size:
|
2006-11-01 00:40:26 +00:00
|
|
|
imap_filter.append("LARGER %d" % options.min_size)
|
2002-10-03 06:27:08 +00:00
|
|
|
if options.preserve_unread:
|
2006-11-01 00:40:26 +00:00
|
|
|
imap_filter.append("SEEN")
|
2006-06-27 04:40:24 +00:00
|
|
|
if options.filter_append:
|
2006-11-01 00:40:26 +00:00
|
|
|
imap_filter.append(options.filter_append)
|
2006-06-27 04:40:24 +00:00
|
|
|
|
2006-11-01 05:27:30 +00:00
|
|
|
return '(' + string.join(imap_filter, ' ') + ')'
|
2002-03-26 03:53:09 +00:00
|
|
|
|
|
|
|
############### mailbox operations ###############
|
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
def archive(mailbox_name):
|
|
|
|
"""Archives a mailbox.
|
|
|
|
|
|
|
|
Arguments:
|
2009-12-30 21:01:03 +00:00
|
|
|
mailbox_name -- the filename/dirname/url of the mailbox to be archived
|
2002-03-31 01:31:11 +00:00
|
|
|
"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2002-08-18 12:17:56 +00:00
|
|
|
# strip any trailing slash (we could be archiving a maildir or MH format
|
|
|
|
# mailbox and somebody was pressing <tab> in bash) - we don't want to use
|
|
|
|
# the trailing slash in the archive name
|
2007-11-07 19:52:52 +00:00
|
|
|
mailbox_name = mailbox_name.rstrip("/")
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
2002-08-18 12:17:56 +00:00
|
|
|
|
2002-04-08 13:39:03 +00:00
|
|
|
set_signal_handlers()
|
|
|
|
os.umask(077) # saves setting permissions on mailboxes/tempfiles
|
|
|
|
|
2008-04-11 00:21:04 +00:00
|
|
|
final_archive_name = make_archive_name(mailbox_name)
|
2008-08-04 18:15:08 +00:00
|
|
|
vprint("archiving '%s' to '%s' ..." % (mailbox_name, final_archive_name))
|
2008-08-04 18:03:16 +00:00
|
|
|
check_archive(final_archive_name)
|
2006-10-31 04:09:31 +00:00
|
|
|
dest_dir = os.path.dirname(final_archive_name)
|
|
|
|
if not dest_dir:
|
|
|
|
dest_dir = os.getcwd()
|
|
|
|
check_sane_destdir(dest_dir)
|
2008-08-04 12:12:34 +00:00
|
|
|
is_imap = urlparse.urlparse(mailbox_name)[0] in ('imap', 'imaps')
|
|
|
|
if not is_imap:
|
|
|
|
# Check if the mailbox exists, and refuse to mess with other people's
|
|
|
|
# stuff
|
|
|
|
try:
|
|
|
|
fuid = os.stat(mailbox_name).st_uid
|
|
|
|
except OSError, e:
|
|
|
|
user_error(str(e))
|
|
|
|
else:
|
|
|
|
if fuid != os.getuid():
|
|
|
|
user_error("'%s' is owned by someone else!" % mailbox_name)
|
2006-10-31 04:09:31 +00:00
|
|
|
|
2002-09-16 11:35:03 +00:00
|
|
|
old_temp_dir = tempfile.tempdir
|
2006-10-29 03:10:45 +00:00
|
|
|
try:
|
|
|
|
# create a temporary directory for us to work in securely
|
|
|
|
tempfile.tempdir = None
|
|
|
|
new_temp_dir = tempfile.mkdtemp('archivemail')
|
2010-07-16 16:54:06 +00:00
|
|
|
assert new_temp_dir
|
2006-10-29 03:10:45 +00:00
|
|
|
_stale.temp_dir = new_temp_dir
|
|
|
|
tempfile.tempdir = new_temp_dir
|
|
|
|
vprint("set tempfile directory to '%s'" % new_temp_dir)
|
|
|
|
|
2008-04-11 00:21:04 +00:00
|
|
|
if is_imap:
|
2006-10-29 03:10:45 +00:00
|
|
|
vprint("guessing mailbox is of type: imap(s)")
|
|
|
|
_archive_imap(mailbox_name, final_archive_name)
|
|
|
|
elif os.path.isfile(mailbox_name):
|
|
|
|
vprint("guessing mailbox is of type: mbox")
|
|
|
|
_archive_mbox(mailbox_name, final_archive_name)
|
|
|
|
elif os.path.isdir(mailbox_name):
|
|
|
|
cur_path = os.path.join(mailbox_name, "cur")
|
|
|
|
new_path = os.path.join(mailbox_name, "new")
|
|
|
|
if os.path.isdir(cur_path) and os.path.isdir(new_path):
|
|
|
|
vprint("guessing mailbox is of type: maildir")
|
|
|
|
_archive_dir(mailbox_name, final_archive_name, "maildir")
|
|
|
|
else:
|
|
|
|
vprint("guessing mailbox is of type: MH")
|
|
|
|
_archive_dir(mailbox_name, final_archive_name, "mh")
|
2002-03-31 01:31:11 +00:00
|
|
|
else:
|
2008-08-04 12:12:34 +00:00
|
|
|
user_error("'%s' is not a normal file or directory" % mailbox_name)
|
2002-03-31 01:31:11 +00:00
|
|
|
|
2006-10-29 03:10:45 +00:00
|
|
|
# remove our special temp directory - hopefully empty
|
|
|
|
os.rmdir(new_temp_dir)
|
|
|
|
_stale.temp_dir = None
|
2002-09-16 11:35:03 +00:00
|
|
|
|
2006-10-29 03:10:45 +00:00
|
|
|
finally:
|
|
|
|
tempfile.tempdir = old_temp_dir
|
|
|
|
clean_up()
|
2002-04-04 07:40:13 +00:00
|
|
|
|
2002-03-31 01:31:11 +00:00
|
|
|
def _archive_mbox(mailbox_name, final_archive_name):
|
|
|
|
"""Archive a 'mbox' style mailbox - used by archive_mailbox()
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
mailbox_name -- the filename/dirname of the mailbox to be archived
|
|
|
|
final_archive_name -- the filename of the 'mbox' mailbox to archive
|
|
|
|
old messages to - appending if the archive
|
|
|
|
already exists
|
|
|
|
"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
|
|
|
assert final_archive_name
|
2002-03-26 03:53:09 +00:00
|
|
|
stats = Stats(mailbox_name, final_archive_name)
|
2002-03-31 01:31:11 +00:00
|
|
|
cache = IdentityCache(mailbox_name)
|
2008-08-09 00:56:19 +00:00
|
|
|
original = Mbox(path=mailbox_name)
|
|
|
|
if options.dry_run or options.copy_old_mail:
|
|
|
|
retain = None
|
|
|
|
else:
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
retain = TempMbox(prefix="retain")
|
|
|
|
archive = prepare_temp_archive()
|
2002-03-31 04:32:31 +00:00
|
|
|
|
2009-05-22 17:40:07 +00:00
|
|
|
original.lock()
|
2002-03-31 01:31:11 +00:00
|
|
|
msg = original.next()
|
2002-04-23 04:30:42 +00:00
|
|
|
if not msg and (original.starting_size > 0):
|
|
|
|
user_error("'%s' is not a valid mbox-format mailbox" % mailbox_name)
|
2010-07-30 17:13:14 +00:00
|
|
|
if msg and 'X-IMAP' in msg:
|
|
|
|
# Dovecot and UW-IMAP pseudo message for mailbox meta data
|
|
|
|
vprint("detected IMAP pseudo message")
|
|
|
|
if retain:
|
|
|
|
retain.write(msg)
|
|
|
|
msg = original.next()
|
2002-03-26 03:53:09 +00:00
|
|
|
while (msg):
|
2006-10-31 03:07:02 +00:00
|
|
|
msg_size = sizeof_message(msg)
|
|
|
|
stats.another_message(msg_size)
|
2002-03-31 01:31:11 +00:00
|
|
|
vprint("processing message '%s'" % msg.get('Message-ID'))
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.warn_duplicates:
|
2002-03-31 01:31:11 +00:00
|
|
|
cache.warn_if_dupe(msg)
|
2002-04-17 06:26:31 +00:00
|
|
|
if should_archive(msg):
|
2006-10-31 03:07:02 +00:00
|
|
|
stats.another_archived(msg_size)
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.delete_old_mail:
|
2002-03-26 03:53:09 +00:00
|
|
|
vprint("decision: delete message")
|
|
|
|
else:
|
|
|
|
vprint("decision: archive message")
|
2008-08-09 00:56:19 +00:00
|
|
|
if archive:
|
2002-03-31 01:31:11 +00:00
|
|
|
archive.write(msg)
|
2002-03-26 03:53:09 +00:00
|
|
|
else:
|
|
|
|
vprint("decision: retain message")
|
2008-08-09 00:56:19 +00:00
|
|
|
if retain:
|
2002-03-31 01:31:11 +00:00
|
|
|
retain.write(msg)
|
|
|
|
msg = original.next()
|
2002-03-26 03:53:09 +00:00
|
|
|
vprint("finished reading messages")
|
2002-04-19 00:19:44 +00:00
|
|
|
if original.starting_size != original.get_size():
|
|
|
|
unexpected_error("the mailbox '%s' changed size during reading!" % \
|
|
|
|
mailbox_name)
|
2010-01-15 23:58:35 +00:00
|
|
|
# Write the new archive before modifying the mailbox, to prevent
|
|
|
|
# losing data if something goes wrong
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
commit_archive(archive, final_archive_name)
|
2008-08-09 00:56:19 +00:00
|
|
|
if retain:
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
pending_changes = original.mbox_file.tell() != retain.mbox_file.tell()
|
|
|
|
if pending_changes:
|
2010-01-16 00:06:30 +00:00
|
|
|
retain.commit()
|
|
|
|
retain.close()
|
2010-01-15 23:58:35 +00:00
|
|
|
vprint("writing back changed mailbox '%s'..." % \
|
|
|
|
original.mbox_file_name)
|
|
|
|
# Prepare for recovery on error.
|
|
|
|
# FIXME: tempfile.tempdir is our nested dir.
|
|
|
|
saved_name = "%s/%s.%s.%s-%s-%s" % \
|
|
|
|
(tempfile.tempdir, options.script_name,
|
|
|
|
os.path.basename(original.mbox_file_name),
|
|
|
|
socket.gethostname(), os.getuid(),
|
|
|
|
os.getpid())
|
|
|
|
try:
|
|
|
|
original.overwrite_with(retain.mbox_file_name)
|
2010-01-16 00:06:30 +00:00
|
|
|
original.commit()
|
2010-01-15 23:58:35 +00:00
|
|
|
except:
|
|
|
|
retain.saveas(saved_name)
|
|
|
|
print "Error writing back changed mailbox; saved good copy to " \
|
|
|
|
"%s" % saved_name
|
|
|
|
raise
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
else:
|
2010-01-16 00:06:30 +00:00
|
|
|
retain.close()
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
vprint("no changes to mbox '%s'" % original.mbox_file_name)
|
|
|
|
retain.remove()
|
2009-05-22 17:40:07 +00:00
|
|
|
original.unlock()
|
2008-08-05 16:02:56 +00:00
|
|
|
original.close()
|
2010-07-16 16:03:10 +00:00
|
|
|
original.reset_timestamps() # Minor race here; mutt has this too.
|
2002-04-09 12:59:26 +00:00
|
|
|
if not options.quiet:
|
2002-03-31 01:31:11 +00:00
|
|
|
stats.display()
|
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2002-04-02 13:37:49 +00:00
|
|
|
def _archive_dir(mailbox_name, final_archive_name, type):
|
|
|
|
"""Archive a 'maildir' or 'MH' style mailbox - used by archive_mailbox()"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
|
|
|
assert final_archive_name
|
|
|
|
assert type
|
2002-03-31 01:31:11 +00:00
|
|
|
stats = Stats(mailbox_name, final_archive_name)
|
2002-03-31 04:32:31 +00:00
|
|
|
delete_queue = []
|
2002-04-02 13:37:49 +00:00
|
|
|
|
|
|
|
if type == "maildir":
|
|
|
|
original = mailbox.Maildir(mailbox_name)
|
|
|
|
elif type == "mh":
|
|
|
|
original = mailbox.MHMailbox(mailbox_name)
|
|
|
|
else:
|
|
|
|
unexpected_error("unknown type: %s" % type)
|
2002-03-31 04:32:31 +00:00
|
|
|
cache = IdentityCache(mailbox_name)
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
archive = prepare_temp_archive()
|
2002-03-31 04:32:31 +00:00
|
|
|
|
2007-10-24 02:23:59 +00:00
|
|
|
for msg in original:
|
|
|
|
if not msg:
|
|
|
|
vprint("ignoring invalid message '%s'" % get_filename(msg))
|
|
|
|
continue
|
2006-10-31 03:07:02 +00:00
|
|
|
msg_size = sizeof_message(msg)
|
|
|
|
stats.another_message(msg_size)
|
2002-03-31 01:31:11 +00:00
|
|
|
vprint("processing message '%s'" % msg.get('Message-ID'))
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.warn_duplicates:
|
2002-03-31 01:31:11 +00:00
|
|
|
cache.warn_if_dupe(msg)
|
2002-04-17 06:26:31 +00:00
|
|
|
if should_archive(msg):
|
2006-10-31 03:07:02 +00:00
|
|
|
stats.another_archived(msg_size)
|
2002-04-09 12:59:26 +00:00
|
|
|
if options.delete_old_mail:
|
2002-03-31 01:31:11 +00:00
|
|
|
vprint("decision: delete message")
|
|
|
|
else:
|
|
|
|
vprint("decision: archive message")
|
2008-08-09 00:56:19 +00:00
|
|
|
if archive:
|
2002-04-18 12:02:33 +00:00
|
|
|
if type == "maildir":
|
|
|
|
add_status_headers(msg)
|
2002-03-31 01:31:11 +00:00
|
|
|
archive.write(msg)
|
2007-11-02 17:44:38 +00:00
|
|
|
if not options.dry_run and not options.copy_old_mail:
|
|
|
|
delete_queue.append(get_filename(msg))
|
2002-03-26 03:53:09 +00:00
|
|
|
else:
|
2002-03-31 01:31:11 +00:00
|
|
|
vprint("decision: retain message")
|
|
|
|
vprint("finished reading messages")
|
2010-01-15 23:58:35 +00:00
|
|
|
# Write the new archive before modifying the mailbox, to prevent
|
|
|
|
# losing data if something goes wrong
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
commit_archive(archive, final_archive_name)
|
2008-08-09 00:56:19 +00:00
|
|
|
for file_name in delete_queue:
|
2008-08-09 01:27:25 +00:00
|
|
|
vprint("removing original message: '%s'" % file_name)
|
|
|
|
try: os.remove(file_name)
|
|
|
|
except OSError, e:
|
|
|
|
if e.errno != errno.ENOENT: raise
|
2002-04-09 12:59:26 +00:00
|
|
|
if not options.quiet:
|
2002-03-26 03:53:09 +00:00
|
|
|
stats.display()
|
|
|
|
|
2002-10-03 06:27:08 +00:00
|
|
|
def _archive_imap(mailbox_name, final_archive_name):
|
|
|
|
"""Archive an imap mailbox - used by archive_mailbox()"""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert mailbox_name
|
|
|
|
assert final_archive_name
|
2002-10-03 06:27:08 +00:00
|
|
|
import imaplib
|
|
|
|
import cStringIO
|
2006-06-16 08:34:22 +00:00
|
|
|
import getpass
|
2002-03-26 03:53:09 +00:00
|
|
|
|
2008-02-14 22:26:10 +00:00
|
|
|
vprint("Setting imaplib.Debug = %d" % options.debug_imap)
|
|
|
|
imaplib.Debug = options.debug_imap
|
2002-10-03 06:27:08 +00:00
|
|
|
archive = None
|
|
|
|
stats = Stats(mailbox_name, final_archive_name)
|
2007-11-02 21:53:20 +00:00
|
|
|
cache = IdentityCache(mailbox_name)
|
2006-06-16 08:34:22 +00:00
|
|
|
imap_str = mailbox_name[mailbox_name.find('://') + 3:]
|
2007-10-23 22:48:15 +00:00
|
|
|
imap_username, imap_password, imap_server, imap_folder = \
|
|
|
|
parse_imap_url(imap_str)
|
|
|
|
if not imap_password:
|
|
|
|
if options.pwfile:
|
|
|
|
imap_password = open(options.pwfile).read().rstrip()
|
|
|
|
else:
|
2006-11-01 20:57:58 +00:00
|
|
|
if (not os.isatty(sys.stdin.fileno())) or options.quiet:
|
|
|
|
unexpected_error("No imap password specified")
|
2006-11-01 21:05:10 +00:00
|
|
|
imap_password = getpass.getpass('IMAP password: ')
|
2006-06-16 08:34:22 +00:00
|
|
|
|
2008-02-14 22:24:16 +00:00
|
|
|
is_ssl = mailbox_name[:5].lower() == 'imaps'
|
|
|
|
if is_ssl:
|
2007-11-07 14:33:17 +00:00
|
|
|
vprint("establishing secure connection to server %s" % imap_server)
|
2006-06-16 08:34:22 +00:00
|
|
|
imap_srv = imaplib.IMAP4_SSL(imap_server)
|
|
|
|
else:
|
2007-11-07 14:33:17 +00:00
|
|
|
vprint("establishing connection to server %s" % imap_server)
|
2006-06-16 08:34:22 +00:00
|
|
|
imap_srv = imaplib.IMAP4(imap_server)
|
2008-02-14 22:19:34 +00:00
|
|
|
if "AUTH=CRAM-MD5" in imap_srv.capabilities:
|
|
|
|
vprint("authenticating (cram-md5) to server as %s" % imap_username)
|
2006-06-16 08:34:22 +00:00
|
|
|
result, response = imap_srv.login_cram_md5(imap_username, imap_password)
|
2008-02-14 22:24:16 +00:00
|
|
|
elif not "LOGINDISABLED" in imap_srv.capabilities:
|
2008-02-14 22:19:34 +00:00
|
|
|
vprint("logging in to server as %s" % imap_username)
|
2006-06-16 08:34:22 +00:00
|
|
|
result, response = imap_srv.login(imap_username, imap_password)
|
2008-02-14 22:24:16 +00:00
|
|
|
else:
|
2008-03-21 01:05:15 +00:00
|
|
|
user_error("imap server %s has login disabled (hint: "
|
2008-02-14 22:24:16 +00:00
|
|
|
"try ssl/imaps)" % imap_server)
|
2006-11-01 05:27:30 +00:00
|
|
|
|
2008-04-08 19:06:42 +00:00
|
|
|
imap_smart_select(imap_srv, imap_folder)
|
|
|
|
total_msg_count = int(imap_srv.response("EXISTS")[1][0])
|
2006-11-01 05:27:30 +00:00
|
|
|
vprint("folder has %d message(s)" % total_msg_count)
|
2006-10-31 03:07:02 +00:00
|
|
|
|
2006-11-01 05:27:30 +00:00
|
|
|
# IIUIC the message sequence numbers are stable for the whole session, since
|
|
|
|
# we just send SEARCH, FETCH and STORE commands, which should prevent the
|
|
|
|
# server from sending untagged EXPUNGE responses -- see RFC 3501 (IMAP4rev1)
|
|
|
|
# 7.4.1 and RFC 2180 (Multi-Accessed Mailbox Practice).
|
|
|
|
# Worst thing should be that we bail out FETCHing a message that has been
|
|
|
|
# deleted.
|
|
|
|
|
2008-03-15 20:24:46 +00:00
|
|
|
if options.archive_all:
|
2008-03-19 18:30:43 +00:00
|
|
|
message_list = [str(n) for n in range(1, total_msg_count+1)]
|
2008-03-15 20:24:46 +00:00
|
|
|
else:
|
|
|
|
imap_filter = build_imap_filter()
|
|
|
|
vprint("imap filter: '%s'" % imap_filter)
|
|
|
|
vprint("searching messages matching criteria")
|
|
|
|
result, response = imap_srv.search(None, imap_filter)
|
|
|
|
if result != 'OK': unexpected_error("imap search failed; server says '%s'" %
|
|
|
|
response[0])
|
|
|
|
# response is a list with a single item, listing message sequence numbers
|
|
|
|
# like ['1 2 3 1016']
|
|
|
|
message_list = response[0].split()
|
|
|
|
vprint("%d messages are matching filter" % len(message_list))
|
2006-10-31 03:07:02 +00:00
|
|
|
|
2006-11-01 05:27:30 +00:00
|
|
|
# First, gather data for the statistics.
|
|
|
|
if total_msg_count > 0:
|
2007-11-07 14:33:17 +00:00
|
|
|
vprint("fetching size of messages...")
|
2006-11-01 05:27:30 +00:00
|
|
|
result, response = imap_srv.fetch('1:*', '(RFC822.SIZE)')
|
2006-11-01 20:35:53 +00:00
|
|
|
if result != 'OK': unexpected_error("Failed to fetch message sizes; "
|
|
|
|
"server says '%s'" % response[0])
|
2006-10-31 03:07:02 +00:00
|
|
|
# response is a list with entries like '1016 (RFC822.SIZE 3118)',
|
2006-11-01 06:11:55 +00:00
|
|
|
# where the first number is the message sequence number, the second is
|
|
|
|
# the size.
|
2006-10-31 03:07:02 +00:00
|
|
|
for x in response:
|
2008-03-15 15:59:05 +00:00
|
|
|
m = imapsize_re.match(x)
|
|
|
|
msn, msg_size = m.group('msn'), int(m.group('size'))
|
2006-10-31 03:07:02 +00:00
|
|
|
stats.another_message(msg_size)
|
2006-11-01 05:27:30 +00:00
|
|
|
if msn in message_list:
|
|
|
|
stats.another_archived(msg_size)
|
2002-10-03 06:27:08 +00:00
|
|
|
|
|
|
|
if not options.dry_run:
|
2006-10-12 01:02:35 +00:00
|
|
|
if not options.delete_old_mail:
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
archive = prepare_temp_archive()
|
2007-11-07 14:33:17 +00:00
|
|
|
vprint("fetching messages...")
|
2006-11-01 06:11:55 +00:00
|
|
|
for msn in message_list:
|
2007-11-02 13:21:18 +00:00
|
|
|
# Fetching message flags and body together always finds \Seen
|
|
|
|
# set. To check \Seen, we must fetch the flags first.
|
|
|
|
result, response = imap_srv.fetch(msn, '(FLAGS)')
|
|
|
|
if result != 'OK': unexpected_error("Failed to fetch message "
|
|
|
|
"flags; server says '%s'" % response[0])
|
|
|
|
msg_flags = imaplib.ParseFlags(response[0])
|
|
|
|
result, response = imap_srv.fetch(msn, '(RFC822)')
|
2006-11-01 20:35:53 +00:00
|
|
|
if result != 'OK': unexpected_error("Failed to fetch message; "
|
|
|
|
"server says '%s'" % response[0])
|
2007-11-07 19:52:52 +00:00
|
|
|
msg_str = response[0][1].replace("\r\n", os.linesep)
|
2006-10-12 01:02:35 +00:00
|
|
|
msg = rfc822.Message(cStringIO.StringIO(msg_str))
|
|
|
|
vprint("processing message '%s'" % msg.get('Message-ID'))
|
2007-11-07 14:33:17 +00:00
|
|
|
add_status_headers_imap(msg, msg_flags)
|
2006-10-12 01:02:35 +00:00
|
|
|
if options.warn_duplicates:
|
|
|
|
cache.warn_if_dupe(msg)
|
|
|
|
archive.write(msg)
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
commit_archive(archive, final_archive_name)
|
2007-11-02 17:44:38 +00:00
|
|
|
if not options.copy_old_mail:
|
|
|
|
vprint("Deleting %s messages" % len(message_list))
|
|
|
|
# do not delete more than a certain number of messages at a time,
|
|
|
|
# because the command length is limited. This avoids that servers
|
|
|
|
# terminate the connection with EOF or TCP RST.
|
|
|
|
max_delete = 100
|
|
|
|
for i in range(0, len(message_list), max_delete):
|
|
|
|
result, response = imap_srv.store( \
|
|
|
|
string.join(message_list[i:i+max_delete], ','),
|
|
|
|
'+FLAGS.SILENT', '\\Deleted')
|
|
|
|
if result != 'OK': unexpected_error("Error while deleting "
|
|
|
|
"messages; server says '%s'" % response[0])
|
2007-11-07 14:33:17 +00:00
|
|
|
vprint("Closing mailbox and terminating connection.")
|
2006-10-11 19:28:36 +00:00
|
|
|
imap_srv.close()
|
|
|
|
imap_srv.logout()
|
2006-10-31 03:07:02 +00:00
|
|
|
if not options.quiet:
|
|
|
|
stats.display()
|
2002-10-03 06:27:08 +00:00
|
|
|
|
2002-04-08 13:39:03 +00:00
|
|
|
|
2008-04-07 20:16:29 +00:00
|
|
|
############### IMAP functions ###############
|
2002-03-31 01:31:11 +00:00
|
|
|
|
|
|
|
|
2007-10-23 22:48:15 +00:00
|
|
|
def parse_imap_url(url):
|
|
|
|
"""Parse IMAP URL and return username, password (if appliciable), servername
|
|
|
|
and foldername."""
|
|
|
|
|
|
|
|
def split_qstr(string, delim):
|
|
|
|
"""Split string once at delim, keeping quoted substring intact.
|
|
|
|
Strip and unescape quotes where necessary."""
|
|
|
|
rm = re.match(r'"(.+?(?<!\\))"(.)(.*)', string)
|
|
|
|
if rm:
|
|
|
|
a, d, b = rm.groups()
|
|
|
|
if not d == delim:
|
|
|
|
raise ValueError
|
|
|
|
a = a.replace('\\"', '"')
|
|
|
|
else:
|
|
|
|
a, b = string.split(delim, 1)
|
|
|
|
return a, b
|
|
|
|
|
|
|
|
password = None
|
|
|
|
try:
|
|
|
|
if options.pwfile:
|
|
|
|
username, url = split_qstr(url, '@')
|
|
|
|
else:
|
|
|
|
try:
|
|
|
|
username, url = split_qstr(url, ':')
|
|
|
|
except ValueError:
|
|
|
|
# request password interactively later
|
|
|
|
username, url = split_qstr(url, '@')
|
|
|
|
else:
|
|
|
|
password, url = split_qstr(url, '@')
|
|
|
|
server, folder = url.split('/', 1)
|
|
|
|
except ValueError:
|
|
|
|
unexpected_error("Invalid IMAP connection string")
|
|
|
|
return username, password, server, folder
|
|
|
|
|
2008-04-07 20:16:29 +00:00
|
|
|
|
2007-11-07 19:52:52 +00:00
|
|
|
def imap_getdelim(imap_server):
|
2007-11-07 16:31:49 +00:00
|
|
|
"""Return the IMAP server's hierarchy delimiter. Assumes there is only one."""
|
|
|
|
# This function will break if the LIST reply doesn't meet our expectations.
|
|
|
|
# Imaplib and IMAP itself are both little beasts, and I do not know how
|
|
|
|
# fragile this function will be in the wild.
|
|
|
|
try:
|
|
|
|
result, response = imap_server.list(pattern='""')
|
|
|
|
except ValueError:
|
|
|
|
# Stolen from offlineimap:
|
|
|
|
# Some buggy IMAP servers do not respond well to LIST "" ""
|
|
|
|
# Work around them.
|
|
|
|
result, response = imap_server.list(pattern='%')
|
|
|
|
if result != 'OK': unexpected_error("Error listing directory; "
|
|
|
|
"server says '%s'" % response[0])
|
2008-03-15 15:59:05 +00:00
|
|
|
|
2007-11-07 16:31:49 +00:00
|
|
|
# Response should be a list of strings like
|
|
|
|
# '(\\Noselect \\HasChildren) "." "boxname"'
|
|
|
|
# We parse only the first list item and just grab the delimiter.
|
2008-03-15 15:59:05 +00:00
|
|
|
m = re.match(r'\([^\)]*\) (?P<delim>"."|NIL)', response[0])
|
|
|
|
if not m:
|
|
|
|
unexpected_error("imap_getdelim(): cannot parse '%s'" % response[0])
|
|
|
|
delim = m.group('delim').strip('"')
|
2007-11-07 16:31:49 +00:00
|
|
|
vprint("Found mailbox hierarchy delimiter: '%s'" % delim)
|
|
|
|
if delim == "NIL":
|
|
|
|
return None
|
|
|
|
return delim
|
|
|
|
|
2008-04-07 20:16:29 +00:00
|
|
|
|
2008-04-08 15:38:51 +00:00
|
|
|
def imap_get_namespace(srv):
|
|
|
|
"""Return the IMAP namespace prefixes and hierarchy delimiters."""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert 'NAMESPACE' in srv.capabilities
|
2008-04-08 15:38:51 +00:00
|
|
|
result, response = srv.namespace()
|
|
|
|
if result != 'OK':
|
|
|
|
unexpected_error("Cannot retrieve IMAP namespace; server says: '%s'"
|
|
|
|
% response[0])
|
|
|
|
vprint("NAMESPACE response: %s" % repr(response[0]))
|
|
|
|
# Typical response is e.g.
|
|
|
|
# ['(("INBOX." ".")) NIL (("#shared." ".")("shared." "."))'] or
|
|
|
|
# ['(("" ".")) NIL NIL'], see RFC 2342.
|
|
|
|
# Make a reasonable guess parsing this beast.
|
2008-12-18 20:56:00 +00:00
|
|
|
try:
|
|
|
|
m = re.match(r'\(\("([^"]*)" (?:"(.)"|NIL)', response[0])
|
|
|
|
nsprefix, hdelim = m.groups()
|
|
|
|
except:
|
|
|
|
print "Cannot parse IMAP NAMESPACE response %s" % repr(response)
|
|
|
|
raise
|
|
|
|
return nsprefix, hdelim
|
2008-04-08 15:38:51 +00:00
|
|
|
|
|
|
|
|
2008-04-08 19:10:41 +00:00
|
|
|
def imap_smart_select(srv, mailbox):
|
2008-04-08 19:06:42 +00:00
|
|
|
"""Select the given mailbox on the IMAP server, correcting an invalid
|
|
|
|
mailbox path if possible."""
|
2008-04-08 19:10:41 +00:00
|
|
|
mailbox = imap_find_mailbox(srv, mailbox)
|
2008-04-08 19:06:42 +00:00
|
|
|
roflag = options.dry_run or options.copy_old_mail
|
|
|
|
# Work around python bug #1277098 (still pending in python << 2.5)
|
|
|
|
if not roflag:
|
|
|
|
roflag = None
|
|
|
|
if roflag:
|
2008-04-08 19:10:41 +00:00
|
|
|
vprint("examining imap folder '%s' read-only" % mailbox)
|
2008-04-08 19:06:42 +00:00
|
|
|
else:
|
2008-04-08 19:10:41 +00:00
|
|
|
vprint("selecting imap folder '%s'" % mailbox)
|
|
|
|
result, response = srv.select(mailbox, roflag)
|
2008-04-08 19:06:42 +00:00
|
|
|
if result != 'OK':
|
|
|
|
unexpected_error("selecting '%s' failed; server says: '%s'." \
|
2008-04-08 19:10:41 +00:00
|
|
|
% (mailbox, response[0]))
|
2008-04-08 23:06:10 +00:00
|
|
|
if not roflag:
|
2008-04-08 19:31:11 +00:00
|
|
|
# Sanity check that we don't silently fail to delete messages.
|
|
|
|
# As to the following indices: IMAP4.response(key) returns
|
|
|
|
# a tuple (key, ['<all_items>']) if the key is found, (key, [None])
|
|
|
|
# otherwise. Imaplib just *loves* to nest trivial lists!
|
|
|
|
permflags = srv.response("PERMANENTFLAGS")[1][0]
|
|
|
|
if permflags:
|
|
|
|
permflags = permflags.strip('()').lower().split()
|
|
|
|
if not '\\deleted' in permflags:
|
|
|
|
unexpected_error("Server doesn't allow deleting messages in " \
|
|
|
|
"'%s'." % mailbox)
|
|
|
|
elif "IMAP4REV1" in srv.capabilities:
|
|
|
|
vprint("Suspect IMAP4rev1 server, doesn't send PERMANENTFLAGS " \
|
|
|
|
"upon SELECT")
|
2008-04-08 19:06:42 +00:00
|
|
|
|
|
|
|
|
2008-04-08 15:38:51 +00:00
|
|
|
def imap_find_mailbox(srv, mailbox):
|
|
|
|
"""Find the given mailbox on the IMAP server, correcting an invalid
|
|
|
|
mailbox path if possible. Return the found mailbox name."""
|
|
|
|
for curbox in imap_guess_mailboxnames(srv, mailbox):
|
|
|
|
vprint("Looking for mailbox '%s'..." % curbox)
|
|
|
|
result, response = srv.list(pattern=curbox)
|
|
|
|
if result != 'OK':
|
|
|
|
unexpected_error("LIST command failed; " \
|
|
|
|
"server says: '%s'" % response[0])
|
|
|
|
# Say we queried for the mailbox "foo".
|
|
|
|
# Upon success, response is e.g. ['(\\HasChildren) "." "foo"'].
|
|
|
|
# Upon failure, response is [None]. Funky imaplib!
|
|
|
|
if response[0] != None:
|
|
|
|
break
|
|
|
|
else:
|
|
|
|
user_error("Cannot find mailbox '%s' on server." % mailbox)
|
|
|
|
vprint("Found mailbox '%s'" % curbox)
|
|
|
|
# Catch \NoSelect here to avoid misleading errors later.
|
|
|
|
m = re.match(r'\((?P<attrs>[^\)]*)\)', response[0])
|
|
|
|
if '\\noselect' in m.group('attrs').lower().split():
|
|
|
|
user_error("Server indicates that mailbox '%s' is not selectable" \
|
|
|
|
% curbox)
|
|
|
|
return curbox
|
|
|
|
|
|
|
|
|
|
|
|
def imap_guess_mailboxnames(srv, mailbox):
|
|
|
|
"""Return a list of possible real IMAP mailbox names in descending order
|
|
|
|
of preference, compiled by prepending an IMAP namespace prefix if necessary,
|
|
|
|
and by translating hierarchy delimiters."""
|
|
|
|
if 'NAMESPACE' in srv.capabilities:
|
2008-12-18 20:56:00 +00:00
|
|
|
nsprefix, hdelim = imap_get_namespace(srv)
|
2008-04-08 15:38:51 +00:00
|
|
|
else:
|
|
|
|
vprint("Server doesn't support NAMESPACE command.")
|
|
|
|
nsprefix = ""
|
|
|
|
hdelim = imap_getdelim(srv)
|
|
|
|
vprint("IMAP namespace prefix: '%s', hierarchy delimiter: '%s'" % \
|
|
|
|
(nsprefix, hdelim))
|
2008-12-18 20:56:00 +00:00
|
|
|
if mailbox.startswith(nsprefix):
|
|
|
|
boxnames = [mailbox]
|
|
|
|
else:
|
|
|
|
boxnames = [nsprefix + mailbox]
|
|
|
|
if os.path.sep in mailbox and hdelim is not None:
|
2008-04-08 15:38:51 +00:00
|
|
|
mailbox = mailbox.replace(os.path.sep, hdelim)
|
2008-12-18 20:56:00 +00:00
|
|
|
if mailbox.startswith(nsprefix):
|
|
|
|
boxnames.append(mailbox)
|
2008-04-08 15:38:51 +00:00
|
|
|
if nsprefix:
|
|
|
|
boxnames.append(nsprefix + mailbox)
|
|
|
|
return boxnames
|
|
|
|
|
|
|
|
|
2008-04-07 20:16:29 +00:00
|
|
|
############### misc functions ###############
|
|
|
|
|
|
|
|
|
|
|
|
def set_signal_handlers():
|
|
|
|
"""set signal handlers to clean up temporary files on unexpected exit"""
|
2009-03-03 02:59:40 +00:00
|
|
|
# Make sure we clean up nicely - we don't want to leave stale dotlock
|
|
|
|
# files about if something bad happens to us. This is quite
|
2008-04-07 20:16:29 +00:00
|
|
|
# important, even though procmail will delete stale files after a while.
|
|
|
|
signal.signal(signal.SIGHUP, clean_up_signal) # signal 1
|
|
|
|
# SIGINT (signal 2) is handled as a python exception
|
|
|
|
signal.signal(signal.SIGQUIT, clean_up_signal) # signal 3
|
|
|
|
signal.signal(signal.SIGTERM, clean_up_signal) # signal 15
|
|
|
|
|
|
|
|
|
|
|
|
def clean_up():
|
|
|
|
"""Delete stale files"""
|
|
|
|
vprint("cleaning up ...")
|
|
|
|
_stale.clean()
|
|
|
|
|
|
|
|
|
|
|
|
def clean_up_signal(signal_number, stack_frame):
|
|
|
|
"""Delete stale files -- to be registered as a signal handler.
|
|
|
|
|
|
|
|
Arguments:
|
|
|
|
signal_number -- signal number of the terminating signal
|
|
|
|
stack_frame -- the current stack frame
|
|
|
|
|
|
|
|
"""
|
|
|
|
# this will run the above clean_up(), since unexpected_error()
|
|
|
|
# will abort with sys.exit() and clean_up will be registered
|
|
|
|
# at this stage
|
|
|
|
unexpected_error("received signal %s" % signal_number)
|
|
|
|
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
def prepare_temp_archive():
|
|
|
|
"""Create temporary archive mbox."""
|
|
|
|
if options.dry_run or options.delete_old_mail:
|
|
|
|
return None
|
|
|
|
if options.no_compress:
|
|
|
|
return TempMbox()
|
|
|
|
else:
|
|
|
|
return CompressedTempMbox()
|
|
|
|
|
|
|
|
def commit_archive(archive, final_archive_name):
|
|
|
|
"""Finalize temporary archive and write it to its final destination."""
|
|
|
|
if not options.no_compress:
|
|
|
|
final_archive_name = final_archive_name + '.gz'
|
|
|
|
if archive:
|
|
|
|
archive.close()
|
|
|
|
if not archive.empty:
|
|
|
|
final_archive = ArchiveMbox(final_archive_name)
|
2009-12-29 18:43:23 +00:00
|
|
|
final_archive.lock()
|
|
|
|
try:
|
|
|
|
final_archive.append(archive.mbox_file_name)
|
2010-01-16 00:06:30 +00:00
|
|
|
final_archive.commit()
|
2009-12-29 18:43:23 +00:00
|
|
|
finally:
|
|
|
|
final_archive.unlock()
|
|
|
|
final_archive.close()
|
Refactoring of the mbox classes
The RetainMbox and ArchiveMbox classes are now gone, mainly because their
finalise() methods were messing with the archived mbox and the archive,
respectively, which was not good OO design.
The core functionality of the finalise() methods of both removed classes
is moved to the objects that are manipulated: the Mbox class representing
the mbox that is being archived gains a new method overwrite_with(), and
there is a new class ArchiveMbox that represents the actual archive, which
has an append() method (yes, unfortunately the new class has the same name
like the removed class).
The RetainMbox instance is replaced with a TempMbox, and the ArchiveMbox
instance either with a TempMbox, or a CompressedTempMbox if archive
compression is enabled.
Finally, a compressed TempMbox is now a implemented as a subclass of
TempMbox, named CompressedMbox.
Cooperation with the StaleFiles class moves into the TempMbox class.
This means slightly less detailed verbose cleanup reporting, oh well.
2009-12-28 22:13:19 +00:00
|
|
|
archive.remove()
|
2008-04-07 20:16:29 +00:00
|
|
|
|
2008-04-11 00:21:04 +00:00
|
|
|
def make_archive_name(mailbox_name):
|
|
|
|
"""Derive archive name and (relative) path from the mailbox name."""
|
2010-07-30 21:26:22 +00:00
|
|
|
# allow the user to embed time formats such as '%B' in the prefix or suffix string
|
2008-04-11 00:21:04 +00:00
|
|
|
if options.date_old_max == None:
|
2010-07-30 21:26:22 +00:00
|
|
|
tm = time.localtime(time.time() - options.days_old_max*24*60*60)
|
2008-04-11 00:21:04 +00:00
|
|
|
else:
|
2010-07-30 21:26:22 +00:00
|
|
|
tm = time.localtime(options.date_old_max)
|
|
|
|
prefix = suffix = ""
|
2010-07-31 12:58:50 +00:00
|
|
|
if options.archive_prefix is None and options.archive_suffix is None:
|
|
|
|
suffix = options.archive_default_suffix
|
|
|
|
else:
|
|
|
|
if options.archive_prefix:
|
|
|
|
prefix = time.strftime(options.archive_prefix, tm)
|
|
|
|
if options.archive_suffix:
|
|
|
|
suffix = time.strftime(options.archive_suffix, tm)
|
2008-04-11 00:21:04 +00:00
|
|
|
if re.match(r'imaps?://', mailbox_name.lower()):
|
2010-07-31 14:43:07 +00:00
|
|
|
archive_head = ""
|
|
|
|
archive_tail = mailbox_name.rsplit('/', 1)[-1]
|
2010-07-30 21:26:22 +00:00
|
|
|
else:
|
2010-07-31 14:43:07 +00:00
|
|
|
archive_head, archive_tail = os.path.split(mailbox_name)
|
2010-07-31 13:35:31 +00:00
|
|
|
if not prefix:
|
|
|
|
# Don't create hidden archives, e.g. when processing Maildir++ subfolders
|
2010-07-31 14:43:07 +00:00
|
|
|
archive_tail = archive_tail.lstrip('.')
|
2008-04-11 00:21:04 +00:00
|
|
|
if options.output_dir:
|
2010-07-31 14:43:07 +00:00
|
|
|
archive_head = options.output_dir
|
|
|
|
archive_name = os.path.join(archive_head, prefix + archive_tail + suffix)
|
2010-07-30 21:26:22 +00:00
|
|
|
return archive_name
|
2008-04-11 00:21:04 +00:00
|
|
|
|
2008-04-07 20:16:29 +00:00
|
|
|
def check_sane_destdir(dir):
|
|
|
|
"""Do a very primitive check if the given directory looks like a reasonable
|
|
|
|
destination directory and bail out if it doesn't."""
|
2010-07-16 16:54:06 +00:00
|
|
|
assert dir
|
2008-04-07 20:16:29 +00:00
|
|
|
if not os.path.isdir(dir):
|
|
|
|
user_error("output directory does not exist: '%s'" % dir)
|
|
|
|
if not os.access(dir, os.W_OK):
|
|
|
|
user_error("no write permission on output directory: '%s'" % dir)
|
|
|
|
|
2008-08-04 18:03:16 +00:00
|
|
|
def check_archive(archive_name):
|
|
|
|
"""Check if existing archive files are (not) compressed as expected."""
|
|
|
|
compressed_archive = archive_name + ".gz"
|
|
|
|
if options.no_compress:
|
|
|
|
if os.path.isfile(compressed_archive):
|
|
|
|
user_error("There is already a file named '%s'!\n"
|
|
|
|
"Have you been previously compressing this archive?\n"
|
|
|
|
"You probably should uncompress it manually, and try running me "
|
|
|
|
"again." % compressed_archive)
|
|
|
|
elif os.path.isfile(archive_name):
|
|
|
|
user_error("There is already a file named '%s'!\n"
|
|
|
|
"Have you been reading this archive?\n"
|
|
|
|
"You probably should re-compress it manually, and try running me "
|
|
|
|
"again." % archive_name)
|
2008-04-07 20:16:29 +00:00
|
|
|
|
|
|
|
def nice_size_str(size):
|
|
|
|
"""Return given size in bytes as '12kB', '1.2MB'"""
|
|
|
|
kb = size / 1024.0
|
|
|
|
mb = kb / 1024.0
|
|
|
|
if mb >= 1.0: return str(round(mb, 1)) + 'MB'
|
|
|
|
if kb >= 1.0: return str(round(kb)) + 'kB'
|
|
|
|
return str(size) + 'B'
|
|
|
|
|
|
|
|
|
2007-10-22 22:03:44 +00:00
|
|
|
def get_filename(msg):
|
|
|
|
"""If the given rfc822.Message can be identified with a file (no mbox),
|
|
|
|
return the filename, otherwise raise AttributeError."""
|
|
|
|
try:
|
|
|
|
return msg.fp.name
|
|
|
|
except AttributeError:
|
|
|
|
# Ugh, that's ugly. msg.fp is not a plain file, it may be an
|
|
|
|
# instance of
|
|
|
|
# a. mailbox._Subfile
|
|
|
|
# (msg from mailbox.UnixMailbox, Python <= 2.4)
|
|
|
|
# File object is msg.fp.fp, we don't want that
|
|
|
|
# b. mailbox._PartialFile, subclass of mailbox._ProxyFile
|
|
|
|
# (msg from mailbox.UnixMailbox, Python >= 2.5)
|
|
|
|
# File object is msg.fp._file, we don't want that
|
|
|
|
# c. mailbox._ProxyFile
|
|
|
|
# (msg from mailbox.Maildir, Python >= 2.5)
|
|
|
|
# File object is msg.fp._file, we do want that.
|
|
|
|
if msg.fp.__class__ == mailbox._ProxyFile:
|
2010-07-16 16:54:06 +00:00
|
|
|
assert hasattr(mailbox, "_PartialFile")
|
2007-10-22 22:03:44 +00:00
|
|
|
return msg.fp._file.name
|
|
|
|
raise
|
2006-10-31 03:07:02 +00:00
|
|
|
|
2009-12-27 23:40:28 +00:00
|
|
|
def safe_open_create(filename):
|
|
|
|
"""Create and open a file in a NFSv2-safe way, and return a r/w file descriptor.
|
|
|
|
The new file is created with mode 600."""
|
|
|
|
# This is essentially a simplified version of the dotlocking function.
|
|
|
|
vprint("Creating file '%s'" % filename)
|
|
|
|
dir, basename = os.path.split(filename)
|
|
|
|
# We rely on tempfile.mkstemp to create files safely and with 600 mode.
|
|
|
|
fd, pre_name = tempfile.mkstemp(prefix=basename+".pre-", dir=dir)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
os.link(pre_name, filename)
|
|
|
|
except OSError, e:
|
|
|
|
if os.fstat(fd).st_nlink == 2:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
raise
|
|
|
|
finally:
|
|
|
|
os.unlink(pre_name)
|
|
|
|
return fd
|
|
|
|
|
|
|
|
def safe_open_existing(filename):
|
|
|
|
"""Safely open an existing file, and return a r/w file descriptor."""
|
|
|
|
lst = os.lstat(filename)
|
|
|
|
if stat.S_ISLNK(lst.st_mode):
|
|
|
|
unexpected_error("file '%s' is a symlink." % filename)
|
|
|
|
fd = os.open(filename, os.O_RDWR)
|
|
|
|
fst = os.fstat(fd)
|
|
|
|
if fst.st_nlink != 1:
|
|
|
|
unexpected_error("file '%s' has %d hard links." % \
|
|
|
|
(filename, fst.st_nlink))
|
|
|
|
if stat.S_ISDIR(fst.st_mode):
|
|
|
|
unexpected_error("file '%s' is a directory." % filename)
|
|
|
|
for i in stat.ST_DEV, stat.ST_INO, stat.ST_UID, stat.ST_GID, stat.ST_MODE, stat.ST_NLINK:
|
|
|
|
if fst[i] != lst[i]:
|
|
|
|
unexpected_error("file status changed unexpectedly")
|
|
|
|
return fd
|
|
|
|
|
|
|
|
def safe_open(filename):
|
|
|
|
"""Safely open a file, creating it if it doesn't exist, and return a
|
|
|
|
r/w file descriptor."""
|
|
|
|
# This borrows from postfix code.
|
|
|
|
vprint("Opening archive...")
|
|
|
|
try:
|
|
|
|
fd = safe_open_existing(filename)
|
|
|
|
except OSError, e:
|
|
|
|
if e.errno != errno.ENOENT: raise
|
|
|
|
fd = safe_open_create(filename)
|
|
|
|
return fd
|
|
|
|
|
2002-03-26 03:53:09 +00:00
|
|
|
# this is where it all happens, folks
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|