blob: e23ea8c6329c6a54e460c43b458694c761dedc8c [file] [log] [blame]
Benjamin Peterson90f5ba52010-03-11 22:53:45 +00001#! /usr/bin/env python3
Guido van Rossum62448671996-09-17 21:33:15 +00002
Thomas Wouters477c8d52006-05-27 19:21:47 +00003"""Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
Guido van Rossum62448671996-09-17 21:33:15 +00004
Thomas Wouters89f507f2006-12-13 04:49:30 +00005# Notes for authors of new mailbox subclasses:
6#
7# Remember to fsync() changes to disk before closing a modified file
8# or returning from a flush() method. See functions _sync_flush() and
9# _sync_close().
10
Thomas Wouters477c8d52006-05-27 19:21:47 +000011import sys
Jack Jansen97157791995-10-23 13:59:53 +000012import os
Thomas Wouters477c8d52006-05-27 19:21:47 +000013import time
14import calendar
15import socket
16import errno
17import copy
R. David Murrayb7deff12011-01-30 06:21:28 +000018import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +000019import email
Thomas Woutersb2137042007-02-01 18:02:27 +000020import email.message
21import email.generator
Guido van Rossum34d19282007-08-09 01:03:29 +000022import io
R David Murray05ff9902011-06-17 12:54:56 -040023import contextlib
Thomas Wouters477c8d52006-05-27 19:21:47 +000024try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000025 if sys.platform == 'os2emx':
26 # OS/2 EMX fcntl() not adequate
27 raise ImportError
28 import fcntl
Thomas Wouters477c8d52006-05-27 19:21:47 +000029except ImportError:
30 fcntl = None
Guido van Rossumc7b68821994-04-28 09:53:33 +000031
Thomas Wouters477c8d52006-05-27 19:21:47 +000032__all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
33 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
Benjamin Peterson8041d472008-05-11 16:17:24 +000034 'BabylMessage', 'MMDFMessage']
Thomas Wouters477c8d52006-05-27 19:21:47 +000035
R. David Murrayb7deff12011-01-30 06:21:28 +000036linesep = os.linesep.encode('ascii')
37
Thomas Wouters477c8d52006-05-27 19:21:47 +000038class Mailbox:
39 """A group of messages in a particular place."""
40
41 def __init__(self, path, factory=None, create=True):
42 """Initialize a Mailbox instance."""
43 self._path = os.path.abspath(os.path.expanduser(path))
44 self._factory = factory
45
46 def add(self, message):
47 """Add message and return assigned key."""
48 raise NotImplementedError('Method must be implemented by subclass')
49
50 def remove(self, key):
51 """Remove the keyed message; raise KeyError if it doesn't exist."""
52 raise NotImplementedError('Method must be implemented by subclass')
53
54 def __delitem__(self, key):
55 self.remove(key)
56
57 def discard(self, key):
58 """If the keyed message exists, remove it."""
59 try:
60 self.remove(key)
61 except KeyError:
62 pass
63
64 def __setitem__(self, key, message):
65 """Replace the keyed message; raise KeyError if it doesn't exist."""
66 raise NotImplementedError('Method must be implemented by subclass')
67
68 def get(self, key, default=None):
69 """Return the keyed message, or default if it doesn't exist."""
70 try:
71 return self.__getitem__(key)
72 except KeyError:
73 return default
74
75 def __getitem__(self, key):
76 """Return the keyed message; raise KeyError if it doesn't exist."""
77 if not self._factory:
78 return self.get_message(key)
79 else:
R David Murray05ff9902011-06-17 12:54:56 -040080 with contextlib.closing(self.get_file(key)) as file:
81 return self._factory(file)
Thomas Wouters477c8d52006-05-27 19:21:47 +000082
83 def get_message(self, key):
84 """Return a Message representation or raise a KeyError."""
85 raise NotImplementedError('Method must be implemented by subclass')
86
87 def get_string(self, key):
R. David Murrayb7deff12011-01-30 06:21:28 +000088 """Return a string representation or raise a KeyError.
89
90 Uses email.message.Message to create a 7bit clean string
91 representation of the message."""
92 return email.message_from_bytes(self.get_bytes(key)).as_string()
93
94 def get_bytes(self, key):
95 """Return a byte string representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +000096 raise NotImplementedError('Method must be implemented by subclass')
97
98 def get_file(self, key):
99 """Return a file-like representation or raise a KeyError."""
100 raise NotImplementedError('Method must be implemented by subclass')
101
102 def iterkeys(self):
103 """Return an iterator over keys."""
104 raise NotImplementedError('Method must be implemented by subclass')
105
106 def keys(self):
107 """Return a list of keys."""
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000108 return list(self.iterkeys())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000109
110 def itervalues(self):
111 """Return an iterator over all messages."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000112 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000113 try:
114 value = self[key]
115 except KeyError:
116 continue
117 yield value
118
119 def __iter__(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000120 return self.itervalues()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000121
122 def values(self):
123 """Return a list of messages. Memory intensive."""
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000124 return list(self.itervalues())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000125
126 def iteritems(self):
127 """Return an iterator over (key, message) tuples."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000128 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000129 try:
130 value = self[key]
131 except KeyError:
132 continue
133 yield (key, value)
134
135 def items(self):
136 """Return a list of (key, message) tuples. Memory intensive."""
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000137 return list(self.iteritems())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000138
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000139 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000140 """Return True if the keyed message exists, False otherwise."""
141 raise NotImplementedError('Method must be implemented by subclass')
142
Thomas Wouters477c8d52006-05-27 19:21:47 +0000143 def __len__(self):
144 """Return a count of messages in the mailbox."""
145 raise NotImplementedError('Method must be implemented by subclass')
146
147 def clear(self):
148 """Delete all messages."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000149 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000150 self.discard(key)
151
152 def pop(self, key, default=None):
153 """Delete the keyed message and return it, or default."""
154 try:
155 result = self[key]
156 except KeyError:
157 return default
158 self.discard(key)
159 return result
160
161 def popitem(self):
162 """Delete an arbitrary (key, message) pair and return it."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000163 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000164 return (key, self.pop(key)) # This is only run once.
165 else:
166 raise KeyError('No messages in mailbox')
167
168 def update(self, arg=None):
169 """Change the messages that correspond to certain keys."""
170 if hasattr(arg, 'iteritems'):
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000171 source = arg.items()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000172 elif hasattr(arg, 'items'):
173 source = arg.items()
174 else:
175 source = arg
176 bad_key = False
177 for key, message in source:
178 try:
179 self[key] = message
180 except KeyError:
181 bad_key = True
182 if bad_key:
183 raise KeyError('No message with key(s)')
184
185 def flush(self):
186 """Write any pending changes to the disk."""
187 raise NotImplementedError('Method must be implemented by subclass')
188
189 def lock(self):
190 """Lock the mailbox."""
191 raise NotImplementedError('Method must be implemented by subclass')
192
193 def unlock(self):
194 """Unlock the mailbox if it is locked."""
195 raise NotImplementedError('Method must be implemented by subclass')
196
197 def close(self):
198 """Flush and close the mailbox."""
199 raise NotImplementedError('Method must be implemented by subclass')
200
R. David Murrayb7deff12011-01-30 06:21:28 +0000201 def _string_to_bytes(self, message):
202 # If a message is not 7bit clean, we refuse to handle it since it
203 # likely came from reading invalid messages in text mode, and that way
204 # lies mojibake.
205 try:
206 return message.encode('ascii')
207 except UnicodeError:
208 raise ValueError("String input must be ASCII-only; "
209 "use bytes or a Message instead")
210
Thomas Wouters477c8d52006-05-27 19:21:47 +0000211 def _dump_message(self, message, target, mangle_from_=False):
R. David Murrayb7deff12011-01-30 06:21:28 +0000212 # This assumes the target file is open in binary mode.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000213 """Dump message contents to target file."""
Thomas Woutersb2137042007-02-01 18:02:27 +0000214 if isinstance(message, email.message.Message):
R. David Murrayb7deff12011-01-30 06:21:28 +0000215 buffer = io.BytesIO()
216 gen = email.generator.BytesGenerator(buffer, mangle_from_, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000217 gen.flatten(message)
218 buffer.seek(0)
Guido van Rossum671117a2007-08-31 04:25:05 +0000219 data = buffer.read()
R. David Murrayb7deff12011-01-30 06:21:28 +0000220 data = data.replace(b'\n', linesep)
Guido van Rossum671117a2007-08-31 04:25:05 +0000221 target.write(data)
R. David Murrayb7deff12011-01-30 06:21:28 +0000222 elif isinstance(message, (str, bytes, io.StringIO)):
223 if isinstance(message, io.StringIO):
224 warnings.warn("Use of StringIO input is deprecated, "
225 "use BytesIO instead", DeprecationWarning, 3)
226 message = message.getvalue()
227 if isinstance(message, str):
228 message = self._string_to_bytes(message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000229 if mangle_from_:
R. David Murrayb7deff12011-01-30 06:21:28 +0000230 message = message.replace(b'\nFrom ', b'\n>From ')
231 message = message.replace(b'\n', linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000232 target.write(message)
233 elif hasattr(message, 'read'):
R. David Murrayb7deff12011-01-30 06:21:28 +0000234 if hasattr(message, 'buffer'):
235 warnings.warn("Use of text mode files is deprecated, "
236 "use a binary mode file instead", DeprecationWarning, 3)
237 message = message.buffer
Thomas Wouters477c8d52006-05-27 19:21:47 +0000238 while True:
239 line = message.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +0000240 # Universal newline support.
241 if line.endswith(b'\r\n'):
242 line = line[:-2] + b'\n'
243 elif line.endswith(b'\r'):
244 line = line[:-1] + b'\n'
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000245 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000246 break
R. David Murrayb7deff12011-01-30 06:21:28 +0000247 if mangle_from_ and line.startswith(b'From '):
248 line = b'>From ' + line[5:]
249 line = line.replace(b'\n', linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000250 target.write(line)
251 else:
252 raise TypeError('Invalid message type: %s' % type(message))
253
254
255class Maildir(Mailbox):
256 """A qmail-style Maildir mailbox."""
257
258 colon = ':'
259
Georg Brandlaa5b4112008-05-11 20:51:18 +0000260 def __init__(self, dirname, factory=None, create=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000261 """Initialize a Maildir instance."""
262 Mailbox.__init__(self, dirname, factory, create)
R David Murraycaed7fe2011-05-06 22:07:19 -0400263 self._paths = {
264 'tmp': os.path.join(self._path, 'tmp'),
265 'new': os.path.join(self._path, 'new'),
266 'cur': os.path.join(self._path, 'cur'),
267 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000268 if not os.path.exists(self._path):
269 if create:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000270 os.mkdir(self._path, 0o700)
R David Murraycaed7fe2011-05-06 22:07:19 -0400271 for path in self._paths.values():
272 os.mkdir(path, 0o700)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000273 else:
274 raise NoSuchMailboxError(self._path)
275 self._toc = {}
R David Murraycaed7fe2011-05-06 22:07:19 -0400276 self._toc_mtimes = {}
277 for subdir in ('cur', 'new'):
278 self._toc_mtimes[subdir] = os.path.getmtime(self._paths[subdir])
279 self._last_read = time.time() # Records last time we read cur/new
280 self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
Thomas Wouters477c8d52006-05-27 19:21:47 +0000281
282 def add(self, message):
283 """Add message and return assigned key."""
284 tmp_file = self._create_tmp()
285 try:
286 self._dump_message(message, tmp_file)
R. David Murrayfc141142011-02-11 22:47:17 +0000287 except BaseException:
288 tmp_file.close()
289 os.remove(tmp_file.name)
290 raise
291 _sync_close(tmp_file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000292 if isinstance(message, MaildirMessage):
293 subdir = message.get_subdir()
294 suffix = self.colon + message.get_info()
295 if suffix == self.colon:
296 suffix = ''
297 else:
298 subdir = 'new'
299 suffix = ''
300 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
301 dest = os.path.join(self._path, subdir, uniq + suffix)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000302 try:
303 if hasattr(os, 'link'):
304 os.link(tmp_file.name, dest)
305 os.remove(tmp_file.name)
306 else:
307 os.rename(tmp_file.name, dest)
Guido van Rossumb940e112007-01-10 16:19:56 +0000308 except OSError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000309 os.remove(tmp_file.name)
310 if e.errno == errno.EEXIST:
311 raise ExternalClashError('Name clash with existing message: %s'
312 % dest)
313 else:
314 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000315 if isinstance(message, MaildirMessage):
316 os.utime(dest, (os.path.getatime(dest), message.get_date()))
317 return uniq
318
319 def remove(self, key):
320 """Remove the keyed message; raise KeyError if it doesn't exist."""
321 os.remove(os.path.join(self._path, self._lookup(key)))
322
323 def discard(self, key):
324 """If the keyed message exists, remove it."""
325 # This overrides an inapplicable implementation in the superclass.
326 try:
327 self.remove(key)
328 except KeyError:
329 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000330 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000331 if e.errno != errno.ENOENT:
332 raise
333
334 def __setitem__(self, key, message):
335 """Replace the keyed message; raise KeyError if it doesn't exist."""
336 old_subpath = self._lookup(key)
337 temp_key = self.add(message)
338 temp_subpath = self._lookup(temp_key)
339 if isinstance(message, MaildirMessage):
340 # temp's subdir and suffix were specified by message.
341 dominant_subpath = temp_subpath
342 else:
343 # temp's subdir and suffix were defaults from add().
344 dominant_subpath = old_subpath
345 subdir = os.path.dirname(dominant_subpath)
346 if self.colon in dominant_subpath:
347 suffix = self.colon + dominant_subpath.split(self.colon)[-1]
348 else:
349 suffix = ''
350 self.discard(key)
351 new_path = os.path.join(self._path, subdir, key + suffix)
352 os.rename(os.path.join(self._path, temp_subpath), new_path)
353 if isinstance(message, MaildirMessage):
354 os.utime(new_path, (os.path.getatime(new_path),
355 message.get_date()))
356
357 def get_message(self, key):
358 """Return a Message representation or raise a KeyError."""
359 subpath = self._lookup(key)
R. David Murrayb7deff12011-01-30 06:21:28 +0000360 f = open(os.path.join(self._path, subpath), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000361 try:
Christian Heimesfdab48e2008-01-20 09:06:41 +0000362 if self._factory:
363 msg = self._factory(f)
364 else:
365 msg = MaildirMessage(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000366 finally:
367 f.close()
368 subdir, name = os.path.split(subpath)
369 msg.set_subdir(subdir)
370 if self.colon in name:
371 msg.set_info(name.split(self.colon)[-1])
372 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
373 return msg
374
R. David Murrayb7deff12011-01-30 06:21:28 +0000375 def get_bytes(self, key):
376 """Return a bytes representation or raise a KeyError."""
377 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000378 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000379 return f.read().replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000380 finally:
381 f.close()
382
383 def get_file(self, key):
384 """Return a file-like representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000385 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000386 return _ProxyFile(f)
387
388 def iterkeys(self):
389 """Return an iterator over keys."""
390 self._refresh()
391 for key in self._toc:
392 try:
393 self._lookup(key)
394 except KeyError:
395 continue
396 yield key
397
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000398 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000399 """Return True if the keyed message exists, False otherwise."""
400 self._refresh()
401 return key in self._toc
402
403 def __len__(self):
404 """Return a count of messages in the mailbox."""
405 self._refresh()
406 return len(self._toc)
407
408 def flush(self):
409 """Write any pending changes to disk."""
Antoine Pitrou03f13442009-11-02 11:36:51 +0000410 # Maildir changes are always written immediately, so there's nothing
R David Murraycaed7fe2011-05-06 22:07:19 -0400411 # to do.
412 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000413
414 def lock(self):
415 """Lock the mailbox."""
416 return
417
418 def unlock(self):
419 """Unlock the mailbox if it is locked."""
420 return
421
422 def close(self):
423 """Flush and close the mailbox."""
424 return
425
426 def list_folders(self):
427 """Return a list of folder names."""
428 result = []
429 for entry in os.listdir(self._path):
430 if len(entry) > 1 and entry[0] == '.' and \
431 os.path.isdir(os.path.join(self._path, entry)):
432 result.append(entry[1:])
433 return result
434
435 def get_folder(self, folder):
436 """Return a Maildir instance for the named folder."""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000437 return Maildir(os.path.join(self._path, '.' + folder),
438 factory=self._factory,
439 create=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000440
441 def add_folder(self, folder):
442 """Create a folder and return a Maildir instance representing it."""
443 path = os.path.join(self._path, '.' + folder)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000444 result = Maildir(path, factory=self._factory)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445 maildirfolder_path = os.path.join(path, 'maildirfolder')
446 if not os.path.exists(maildirfolder_path):
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000447 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
448 0o666))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000449 return result
450
451 def remove_folder(self, folder):
452 """Delete the named folder, which must be empty."""
453 path = os.path.join(self._path, '.' + folder)
454 for entry in os.listdir(os.path.join(path, 'new')) + \
455 os.listdir(os.path.join(path, 'cur')):
456 if len(entry) < 1 or entry[0] != '.':
457 raise NotEmptyError('Folder contains message(s): %s' % folder)
458 for entry in os.listdir(path):
459 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
460 os.path.isdir(os.path.join(path, entry)):
461 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
462 (folder, entry))
463 for root, dirs, files in os.walk(path, topdown=False):
464 for entry in files:
465 os.remove(os.path.join(root, entry))
466 for entry in dirs:
467 os.rmdir(os.path.join(root, entry))
468 os.rmdir(path)
469
470 def clean(self):
471 """Delete old files in "tmp"."""
472 now = time.time()
473 for entry in os.listdir(os.path.join(self._path, 'tmp')):
474 path = os.path.join(self._path, 'tmp', entry)
475 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
476 os.remove(path)
477
478 _count = 1 # This is used to generate unique file names.
479
480 def _create_tmp(self):
481 """Create a file in the tmp subdirectory and open and return it."""
482 now = time.time()
483 hostname = socket.gethostname()
484 if '/' in hostname:
485 hostname = hostname.replace('/', r'\057')
486 if ':' in hostname:
487 hostname = hostname.replace(':', r'\072')
488 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
489 Maildir._count, hostname)
490 path = os.path.join(self._path, 'tmp', uniq)
491 try:
492 os.stat(path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000493 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000494 if e.errno == errno.ENOENT:
495 Maildir._count += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000496 try:
497 return _create_carefully(path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000498 except OSError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000499 if e.errno != errno.EEXIST:
500 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000501 else:
502 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000503
504 # Fall through to here if stat succeeded or open raised EEXIST.
505 raise ExternalClashError('Name clash prevented file creation: %s' %
506 path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000507
508 def _refresh(self):
509 """Update table of contents mapping."""
R David Murraycaed7fe2011-05-06 22:07:19 -0400510 # If it has been less than two seconds since the last _refresh() call,
511 # we have to unconditionally re-read the mailbox just in case it has
512 # been modified, because os.path.mtime() has a 2 sec resolution in the
513 # most common worst case (FAT) and a 1 sec resolution typically. This
514 # results in a few unnecessary re-reads when _refresh() is called
515 # multiple times in that interval, but once the clock ticks over, we
516 # will only re-read as needed. Because the filesystem might be being
517 # served by an independent system with its own clock, we record and
518 # compare with the mtimes from the filesystem. Because the other
519 # system's clock might be skewing relative to our clock, we add an
520 # extra delta to our wait. The default is one tenth second, but is an
521 # instance variable and so can be adjusted if dealing with a
522 # particularly skewed or irregular system.
523 if time.time() - self._last_read > 2 + self._skewfactor:
524 refresh = False
525 for subdir in self._toc_mtimes:
526 mtime = os.path.getmtime(self._paths[subdir])
527 if mtime > self._toc_mtimes[subdir]:
528 refresh = True
529 self._toc_mtimes[subdir] = mtime
530 if not refresh:
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000531 return
R David Murraycaed7fe2011-05-06 22:07:19 -0400532 # Refresh toc
Thomas Wouters477c8d52006-05-27 19:21:47 +0000533 self._toc = {}
R David Murraycaed7fe2011-05-06 22:07:19 -0400534 for subdir in self._toc_mtimes:
535 path = self._paths[subdir]
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000536 for entry in os.listdir(path):
537 p = os.path.join(path, entry)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000538 if os.path.isdir(p):
539 continue
Thomas Wouters477c8d52006-05-27 19:21:47 +0000540 uniq = entry.split(self.colon)[0]
541 self._toc[uniq] = os.path.join(subdir, entry)
R David Murraycaed7fe2011-05-06 22:07:19 -0400542 self._last_read = time.time()
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000543
Thomas Wouters477c8d52006-05-27 19:21:47 +0000544 def _lookup(self, key):
545 """Use TOC to return subpath for given key, or raise a KeyError."""
546 try:
547 if os.path.exists(os.path.join(self._path, self._toc[key])):
548 return self._toc[key]
549 except KeyError:
550 pass
551 self._refresh()
552 try:
553 return self._toc[key]
554 except KeyError:
555 raise KeyError('No message with key: %s' % key)
556
557 # This method is for backward compatibility only.
558 def next(self):
559 """Return the next message in a one-time iteration."""
560 if not hasattr(self, '_onetime_keys'):
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000561 self._onetime_keys = iter(self.keys())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000562 while True:
563 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000564 return self[next(self._onetime_keys)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000565 except StopIteration:
566 return None
567 except KeyError:
568 continue
569
570
571class _singlefileMailbox(Mailbox):
572 """A single-file mailbox."""
573
574 def __init__(self, path, factory=None, create=True):
575 """Initialize a single-file mailbox."""
576 Mailbox.__init__(self, path, factory, create)
577 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000578 f = open(self._path, 'rb+')
Guido van Rossumb940e112007-01-10 16:19:56 +0000579 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000580 if e.errno == errno.ENOENT:
581 if create:
R. David Murrayb7deff12011-01-30 06:21:28 +0000582 f = open(self._path, 'wb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000583 else:
584 raise NoSuchMailboxError(self._path)
R. David Murray752b9502011-03-03 18:12:34 +0000585 elif e.errno in (errno.EACCES, errno.EROFS):
R. David Murrayb7deff12011-01-30 06:21:28 +0000586 f = open(self._path, 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000587 else:
588 raise
589 self._file = f
590 self._toc = None
591 self._next_key = 0
592 self._pending = False # No changes require rewriting the file.
593 self._locked = False
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000594 self._file_length = None # Used to record mailbox size
Thomas Wouters477c8d52006-05-27 19:21:47 +0000595
596 def add(self, message):
597 """Add message and return assigned key."""
598 self._lookup()
599 self._toc[self._next_key] = self._append_message(message)
600 self._next_key += 1
601 self._pending = True
602 return self._next_key - 1
603
604 def remove(self, key):
605 """Remove the keyed message; raise KeyError if it doesn't exist."""
606 self._lookup(key)
607 del self._toc[key]
608 self._pending = True
609
610 def __setitem__(self, key, message):
611 """Replace the keyed message; raise KeyError if it doesn't exist."""
612 self._lookup(key)
613 self._toc[key] = self._append_message(message)
614 self._pending = True
615
616 def iterkeys(self):
617 """Return an iterator over keys."""
618 self._lookup()
619 for key in self._toc.keys():
620 yield key
621
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000622 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000623 """Return True if the keyed message exists, False otherwise."""
624 self._lookup()
625 return key in self._toc
626
627 def __len__(self):
628 """Return a count of messages in the mailbox."""
629 self._lookup()
630 return len(self._toc)
631
632 def lock(self):
633 """Lock the mailbox."""
634 if not self._locked:
635 _lock_file(self._file)
636 self._locked = True
637
638 def unlock(self):
639 """Unlock the mailbox if it is locked."""
640 if self._locked:
641 _unlock_file(self._file)
642 self._locked = False
643
644 def flush(self):
645 """Write any pending changes to disk."""
646 if not self._pending:
647 return
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000648
649 # In order to be writing anything out at all, self._toc must
650 # already have been generated (and presumably has been modified
651 # by adding or deleting an item).
652 assert self._toc is not None
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000653
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000654 # Check length of self._file; if it's changed, some other process
655 # has modified the mailbox since we scanned it.
656 self._file.seek(0, 2)
657 cur_len = self._file.tell()
658 if cur_len != self._file_length:
659 raise ExternalClashError('Size of mailbox file changed '
660 '(expected %i, found %i)' %
661 (self._file_length, cur_len))
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000662
Thomas Wouters477c8d52006-05-27 19:21:47 +0000663 new_file = _create_temporary(self._path)
664 try:
665 new_toc = {}
666 self._pre_mailbox_hook(new_file)
667 for key in sorted(self._toc.keys()):
668 start, stop = self._toc[key]
669 self._file.seek(start)
670 self._pre_message_hook(new_file)
671 new_start = new_file.tell()
672 while True:
673 buffer = self._file.read(min(4096,
674 stop - self._file.tell()))
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000675 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000676 break
677 new_file.write(buffer)
678 new_toc[key] = (new_start, new_file.tell())
679 self._post_message_hook(new_file)
680 except:
681 new_file.close()
682 os.remove(new_file.name)
683 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000684 _sync_close(new_file)
685 # self._file is about to get replaced, so no need to sync.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000686 self._file.close()
687 try:
688 os.rename(new_file.name, self._path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000689 except OSError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000690 if e.errno == errno.EEXIST or \
691 (os.name == 'os2' and e.errno == errno.EACCES):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000692 os.remove(self._path)
693 os.rename(new_file.name, self._path)
694 else:
695 raise
696 self._file = open(self._path, 'rb+')
697 self._toc = new_toc
698 self._pending = False
699 if self._locked:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000700 _lock_file(self._file, dotlock=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000701
702 def _pre_mailbox_hook(self, f):
703 """Called before writing the mailbox to file f."""
704 return
705
706 def _pre_message_hook(self, f):
707 """Called before writing each message to file f."""
708 return
709
710 def _post_message_hook(self, f):
711 """Called after writing each message to file f."""
712 return
713
714 def close(self):
715 """Flush and close the mailbox."""
716 self.flush()
717 if self._locked:
718 self.unlock()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000719 self._file.close() # Sync has been done by self.flush() above.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000720
721 def _lookup(self, key=None):
722 """Return (start, stop) or raise KeyError."""
723 if self._toc is None:
724 self._generate_toc()
725 if key is not None:
726 try:
727 return self._toc[key]
728 except KeyError:
729 raise KeyError('No message with key: %s' % key)
730
731 def _append_message(self, message):
732 """Append message to mailbox and return (start, stop) offsets."""
733 self._file.seek(0, 2)
R. David Murrayfc141142011-02-11 22:47:17 +0000734 before = self._file.tell()
735 try:
736 self._pre_message_hook(self._file)
737 offsets = self._install_message(message)
738 self._post_message_hook(self._file)
739 except BaseException:
740 self._file.truncate(before)
741 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000742 self._file.flush()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000743 self._file_length = self._file.tell() # Record current length of mailbox
Thomas Wouters477c8d52006-05-27 19:21:47 +0000744 return offsets
745
746
747
748class _mboxMMDF(_singlefileMailbox):
749 """An mbox or MMDF mailbox."""
750
751 _mangle_from_ = True
752
753 def get_message(self, key):
754 """Return a Message representation or raise a KeyError."""
755 start, stop = self._lookup(key)
756 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +0000757 from_line = self._file.readline().replace(linesep, b'')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000758 string = self._file.read(stop - self._file.tell())
R. David Murrayb7deff12011-01-30 06:21:28 +0000759 msg = self._message_factory(string.replace(linesep, b'\n'))
760 msg.set_from(from_line[5:].decode('ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761 return msg
762
763 def get_string(self, key, from_=False):
764 """Return a string representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000765 return email.message_from_bytes(
766 self.get_bytes(key)).as_string(unixfrom=from_)
767
768 def get_bytes(self, key, from_=False):
769 """Return a string representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +0000770 start, stop = self._lookup(key)
771 self._file.seek(start)
772 if not from_:
773 self._file.readline()
774 string = self._file.read(stop - self._file.tell())
R. David Murrayb7deff12011-01-30 06:21:28 +0000775 return string.replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000776
777 def get_file(self, key, from_=False):
778 """Return a file-like representation or raise a KeyError."""
779 start, stop = self._lookup(key)
780 self._file.seek(start)
781 if not from_:
782 self._file.readline()
783 return _PartialFile(self._file, self._file.tell(), stop)
784
785 def _install_message(self, message):
786 """Format a message and blindly write to self._file."""
787 from_line = None
R. David Murrayb7deff12011-01-30 06:21:28 +0000788 if isinstance(message, str):
789 message = self._string_to_bytes(message)
790 if isinstance(message, bytes) and message.startswith(b'From '):
791 newline = message.find(b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000792 if newline != -1:
793 from_line = message[:newline]
794 message = message[newline + 1:]
795 else:
796 from_line = message
R. David Murrayb7deff12011-01-30 06:21:28 +0000797 message = b''
Thomas Wouters477c8d52006-05-27 19:21:47 +0000798 elif isinstance(message, _mboxMMDFMessage):
R. David Murrayb7deff12011-01-30 06:21:28 +0000799 author = message.get_from().encode('ascii')
800 from_line = b'From ' + author
Thomas Woutersb2137042007-02-01 18:02:27 +0000801 elif isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000802 from_line = message.get_unixfrom() # May be None.
R. David Murrayb7deff12011-01-30 06:21:28 +0000803 if from_line is not None:
804 from_line = from_line.encode('ascii')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000805 if from_line is None:
R. David Murrayb7deff12011-01-30 06:21:28 +0000806 from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807 start = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000808 self._file.write(from_line + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000809 self._dump_message(message, self._file, self._mangle_from_)
810 stop = self._file.tell()
811 return (start, stop)
812
813
814class mbox(_mboxMMDF):
815 """A classic mbox mailbox."""
816
817 _mangle_from_ = True
818
819 def __init__(self, path, factory=None, create=True):
820 """Initialize an mbox mailbox."""
821 self._message_factory = mboxMessage
822 _mboxMMDF.__init__(self, path, factory, create)
823
824 def _pre_message_hook(self, f):
825 """Called before writing each message to file f."""
826 if f.tell() != 0:
R. David Murrayb7deff12011-01-30 06:21:28 +0000827 f.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000828
829 def _generate_toc(self):
830 """Generate key-to-(start, stop) table of contents."""
831 starts, stops = [], []
832 self._file.seek(0)
833 while True:
834 line_pos = self._file.tell()
835 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +0000836 if line.startswith(b'From '):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000837 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +0000838 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000839 starts.append(line_pos)
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000840 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000841 stops.append(line_pos)
842 break
843 self._toc = dict(enumerate(zip(starts, stops)))
844 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000845 self._file_length = self._file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000846
847
848class MMDF(_mboxMMDF):
849 """An MMDF mailbox."""
850
851 def __init__(self, path, factory=None, create=True):
852 """Initialize an MMDF mailbox."""
853 self._message_factory = MMDFMessage
854 _mboxMMDF.__init__(self, path, factory, create)
855
856 def _pre_message_hook(self, f):
857 """Called before writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000858 f.write(b'\001\001\001\001' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000859
860 def _post_message_hook(self, f):
861 """Called after writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000862 f.write(linesep + b'\001\001\001\001' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000863
864 def _generate_toc(self):
865 """Generate key-to-(start, stop) table of contents."""
866 starts, stops = [], []
867 self._file.seek(0)
868 next_pos = 0
869 while True:
870 line_pos = next_pos
871 line = self._file.readline()
872 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000873 if line.startswith(b'\001\001\001\001' + linesep):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000874 starts.append(next_pos)
875 while True:
876 line_pos = next_pos
877 line = self._file.readline()
878 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000879 if line == b'\001\001\001\001' + linesep:
880 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000881 break
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000882 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000883 stops.append(line_pos)
884 break
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000885 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000886 break
887 self._toc = dict(enumerate(zip(starts, stops)))
888 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000889 self._file.seek(0, 2)
890 self._file_length = self._file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000891
892
893class MH(Mailbox):
894 """An MH mailbox."""
895
896 def __init__(self, path, factory=None, create=True):
897 """Initialize an MH instance."""
898 Mailbox.__init__(self, path, factory, create)
899 if not os.path.exists(self._path):
900 if create:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000901 os.mkdir(self._path, 0o700)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000902 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000903 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000904 else:
905 raise NoSuchMailboxError(self._path)
906 self._locked = False
907
908 def add(self, message):
909 """Add message and return assigned key."""
910 keys = self.keys()
911 if len(keys) == 0:
912 new_key = 1
913 else:
914 new_key = max(keys) + 1
915 new_path = os.path.join(self._path, str(new_key))
916 f = _create_carefully(new_path)
R. David Murray774a66d2011-02-12 00:03:31 +0000917 closed = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000918 try:
919 if self._locked:
920 _lock_file(f)
921 try:
R. David Murrayfc141142011-02-11 22:47:17 +0000922 try:
923 self._dump_message(message, f)
924 except BaseException:
R. David Murray774a66d2011-02-12 00:03:31 +0000925 # Unlock and close so it can be deleted on Windows
926 if self._locked:
927 _unlock_file(f)
928 _sync_close(f)
929 closed = True
R. David Murrayfc141142011-02-11 22:47:17 +0000930 os.remove(new_path)
931 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000932 if isinstance(message, MHMessage):
933 self._dump_sequences(message, new_key)
934 finally:
935 if self._locked:
936 _unlock_file(f)
937 finally:
R. David Murray774a66d2011-02-12 00:03:31 +0000938 if not closed:
939 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000940 return new_key
941
942 def remove(self, key):
943 """Remove the keyed message; raise KeyError if it doesn't exist."""
944 path = os.path.join(self._path, str(key))
945 try:
946 f = open(path, 'rb+')
Guido van Rossumb940e112007-01-10 16:19:56 +0000947 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000948 if e.errno == errno.ENOENT:
949 raise KeyError('No message with key: %s' % key)
950 else:
951 raise
Benjamin Peterson21896a32010-03-21 22:03:03 +0000952 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000953 f.close()
Benjamin Peterson21896a32010-03-21 22:03:03 +0000954 os.remove(path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000955
956 def __setitem__(self, key, message):
957 """Replace the keyed message; raise KeyError if it doesn't exist."""
958 path = os.path.join(self._path, str(key))
959 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000960 f = open(path, 'rb+')
Guido van Rossumb940e112007-01-10 16:19:56 +0000961 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000962 if e.errno == errno.ENOENT:
963 raise KeyError('No message with key: %s' % key)
964 else:
965 raise
966 try:
967 if self._locked:
968 _lock_file(f)
969 try:
970 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
971 self._dump_message(message, f)
972 if isinstance(message, MHMessage):
973 self._dump_sequences(message, key)
974 finally:
975 if self._locked:
976 _unlock_file(f)
977 finally:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000978 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000979
980 def get_message(self, key):
981 """Return a Message representation or raise a KeyError."""
982 try:
983 if self._locked:
R. David Murrayb7deff12011-01-30 06:21:28 +0000984 f = open(os.path.join(self._path, str(key)), 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985 else:
R. David Murrayb7deff12011-01-30 06:21:28 +0000986 f = open(os.path.join(self._path, str(key)), 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +0000987 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000988 if e.errno == errno.ENOENT:
989 raise KeyError('No message with key: %s' % key)
990 else:
991 raise
992 try:
993 if self._locked:
994 _lock_file(f)
995 try:
996 msg = MHMessage(f)
997 finally:
998 if self._locked:
999 _unlock_file(f)
1000 finally:
1001 f.close()
R. David Murray548ac412009-04-02 19:44:43 +00001002 for name, key_list in self.get_sequences().items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001003 if key in key_list:
1004 msg.add_sequence(name)
1005 return msg
1006
R. David Murrayb7deff12011-01-30 06:21:28 +00001007 def get_bytes(self, key):
1008 """Return a bytes representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00001009 try:
1010 if self._locked:
R. David Murrayb7deff12011-01-30 06:21:28 +00001011 f = open(os.path.join(self._path, str(key)), 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001012 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001013 f = open(os.path.join(self._path, str(key)), 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +00001014 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001015 if e.errno == errno.ENOENT:
1016 raise KeyError('No message with key: %s' % key)
1017 else:
1018 raise
1019 try:
1020 if self._locked:
1021 _lock_file(f)
1022 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001023 return f.read().replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001024 finally:
1025 if self._locked:
1026 _unlock_file(f)
1027 finally:
1028 f.close()
1029
1030 def get_file(self, key):
1031 """Return a file-like representation or raise a KeyError."""
1032 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001033 f = open(os.path.join(self._path, str(key)), 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +00001034 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001035 if e.errno == errno.ENOENT:
1036 raise KeyError('No message with key: %s' % key)
1037 else:
1038 raise
1039 return _ProxyFile(f)
1040
1041 def iterkeys(self):
1042 """Return an iterator over keys."""
1043 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1044 if entry.isdigit()))
1045
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001046 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001047 """Return True if the keyed message exists, False otherwise."""
1048 return os.path.exists(os.path.join(self._path, str(key)))
1049
1050 def __len__(self):
1051 """Return a count of messages in the mailbox."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001052 return len(list(self.keys()))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001053
1054 def lock(self):
1055 """Lock the mailbox."""
1056 if not self._locked:
1057 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
1058 _lock_file(self._file)
1059 self._locked = True
1060
1061 def unlock(self):
1062 """Unlock the mailbox if it is locked."""
1063 if self._locked:
1064 _unlock_file(self._file)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001065 _sync_close(self._file)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001066 del self._file
1067 self._locked = False
1068
1069 def flush(self):
1070 """Write any pending changes to the disk."""
1071 return
1072
1073 def close(self):
1074 """Flush and close the mailbox."""
1075 if self._locked:
1076 self.unlock()
1077
1078 def list_folders(self):
1079 """Return a list of folder names."""
1080 result = []
1081 for entry in os.listdir(self._path):
1082 if os.path.isdir(os.path.join(self._path, entry)):
1083 result.append(entry)
1084 return result
1085
1086 def get_folder(self, folder):
1087 """Return an MH instance for the named folder."""
Thomas Wouters89f507f2006-12-13 04:49:30 +00001088 return MH(os.path.join(self._path, folder),
1089 factory=self._factory, create=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001090
1091 def add_folder(self, folder):
1092 """Create a folder and return an MH instance representing it."""
Thomas Wouters89f507f2006-12-13 04:49:30 +00001093 return MH(os.path.join(self._path, folder),
1094 factory=self._factory)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001095
1096 def remove_folder(self, folder):
1097 """Delete the named folder, which must be empty."""
1098 path = os.path.join(self._path, folder)
1099 entries = os.listdir(path)
1100 if entries == ['.mh_sequences']:
1101 os.remove(os.path.join(path, '.mh_sequences'))
1102 elif entries == []:
1103 pass
1104 else:
1105 raise NotEmptyError('Folder not empty: %s' % self._path)
1106 os.rmdir(path)
1107
1108 def get_sequences(self):
1109 """Return a name-to-key-list dictionary to define each sequence."""
1110 results = {}
R. David Murrayb7deff12011-01-30 06:21:28 +00001111 f = open(os.path.join(self._path, '.mh_sequences'), 'r')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001112 try:
1113 all_keys = set(self.keys())
1114 for line in f:
1115 try:
1116 name, contents = line.split(':')
1117 keys = set()
1118 for spec in contents.split():
1119 if spec.isdigit():
1120 keys.add(int(spec))
1121 else:
1122 start, stop = (int(x) for x in spec.split('-'))
1123 keys.update(range(start, stop + 1))
1124 results[name] = [key for key in sorted(keys) \
1125 if key in all_keys]
1126 if len(results[name]) == 0:
1127 del results[name]
1128 except ValueError:
1129 raise FormatError('Invalid sequence specification: %s' %
1130 line.rstrip())
1131 finally:
1132 f.close()
1133 return results
1134
1135 def set_sequences(self, sequences):
1136 """Set sequences using the given name-to-key-list dictionary."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001137 f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001138 try:
1139 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001140 for name, keys in sequences.items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001141 if len(keys) == 0:
1142 continue
R. David Murrayb7deff12011-01-30 06:21:28 +00001143 f.write(name + ':')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001144 prev = None
1145 completing = False
1146 for key in sorted(set(keys)):
1147 if key - 1 == prev:
1148 if not completing:
1149 completing = True
1150 f.write('-')
1151 elif completing:
1152 completing = False
1153 f.write('%s %s' % (prev, key))
1154 else:
1155 f.write(' %s' % key)
1156 prev = key
1157 if completing:
1158 f.write(str(prev) + '\n')
1159 else:
1160 f.write('\n')
1161 finally:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001162 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163
1164 def pack(self):
1165 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1166 sequences = self.get_sequences()
1167 prev = 0
1168 changes = []
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001169 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001170 if key - 1 != prev:
1171 changes.append((key, prev + 1))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001172 if hasattr(os, 'link'):
1173 os.link(os.path.join(self._path, str(key)),
1174 os.path.join(self._path, str(prev + 1)))
1175 os.unlink(os.path.join(self._path, str(key)))
1176 else:
1177 os.rename(os.path.join(self._path, str(key)),
1178 os.path.join(self._path, str(prev + 1)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001179 prev += 1
1180 self._next_key = prev + 1
1181 if len(changes) == 0:
1182 return
1183 for name, key_list in sequences.items():
1184 for old, new in changes:
1185 if old in key_list:
1186 key_list[key_list.index(old)] = new
1187 self.set_sequences(sequences)
1188
1189 def _dump_sequences(self, message, key):
1190 """Inspect a new MHMessage and update sequences appropriately."""
1191 pending_sequences = message.get_sequences()
1192 all_sequences = self.get_sequences()
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001193 for name, key_list in all_sequences.items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001194 if name in pending_sequences:
1195 key_list.append(key)
1196 elif key in key_list:
1197 del key_list[key_list.index(key)]
1198 for sequence in pending_sequences:
1199 if sequence not in all_sequences:
1200 all_sequences[sequence] = [key]
1201 self.set_sequences(all_sequences)
1202
1203
1204class Babyl(_singlefileMailbox):
1205 """An Rmail-style Babyl mailbox."""
1206
1207 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1208 'forwarded', 'edited', 'resent'))
1209
1210 def __init__(self, path, factory=None, create=True):
1211 """Initialize a Babyl mailbox."""
1212 _singlefileMailbox.__init__(self, path, factory, create)
1213 self._labels = {}
1214
1215 def add(self, message):
1216 """Add message and return assigned key."""
1217 key = _singlefileMailbox.add(self, message)
1218 if isinstance(message, BabylMessage):
1219 self._labels[key] = message.get_labels()
1220 return key
1221
1222 def remove(self, key):
1223 """Remove the keyed message; raise KeyError if it doesn't exist."""
1224 _singlefileMailbox.remove(self, key)
1225 if key in self._labels:
1226 del self._labels[key]
1227
1228 def __setitem__(self, key, message):
1229 """Replace the keyed message; raise KeyError if it doesn't exist."""
1230 _singlefileMailbox.__setitem__(self, key, message)
1231 if isinstance(message, BabylMessage):
1232 self._labels[key] = message.get_labels()
1233
1234 def get_message(self, key):
1235 """Return a Message representation or raise a KeyError."""
1236 start, stop = self._lookup(key)
1237 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +00001238 self._file.readline() # Skip b'1,' line specifying labels.
1239 original_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001240 while True:
1241 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001242 if line == b'*** EOOH ***' + linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001244 original_headers.write(line.replace(linesep, b'\n'))
1245 visible_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001246 while True:
1247 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001248 if line == linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001249 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001250 visible_headers.write(line.replace(linesep, b'\n'))
1251 # Read up to the stop, or to the end
1252 n = stop - self._file.tell()
1253 assert n >= 0
1254 body = self._file.read(n)
1255 body = body.replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001256 msg = BabylMessage(original_headers.getvalue() + body)
1257 msg.set_visible(visible_headers.getvalue())
1258 if key in self._labels:
1259 msg.set_labels(self._labels[key])
1260 return msg
1261
R. David Murrayb7deff12011-01-30 06:21:28 +00001262 def get_bytes(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001263 """Return a string representation or raise a KeyError."""
1264 start, stop = self._lookup(key)
1265 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +00001266 self._file.readline() # Skip b'1,' line specifying labels.
1267 original_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001268 while True:
1269 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001270 if line == b'*** EOOH ***' + linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001271 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001272 original_headers.write(line.replace(linesep, b'\n'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001273 while True:
1274 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001275 if line == linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001277 headers = original_headers.getvalue()
1278 n = stop - self._file.tell()
1279 assert n >= 0
1280 data = self._file.read(n)
1281 data = data.replace(linesep, b'\n')
1282 return headers + data
Thomas Wouters477c8d52006-05-27 19:21:47 +00001283
1284 def get_file(self, key):
1285 """Return a file-like representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001286 return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001287
1288 def get_labels(self):
1289 """Return a list of user-defined labels in the mailbox."""
1290 self._lookup()
1291 labels = set()
1292 for label_list in self._labels.values():
1293 labels.update(label_list)
1294 labels.difference_update(self._special_labels)
1295 return list(labels)
1296
1297 def _generate_toc(self):
1298 """Generate key-to-(start, stop) table of contents."""
1299 starts, stops = [], []
1300 self._file.seek(0)
1301 next_pos = 0
1302 label_lists = []
1303 while True:
1304 line_pos = next_pos
1305 line = self._file.readline()
1306 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +00001307 if line == b'\037\014' + linesep:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001308 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +00001309 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001310 starts.append(next_pos)
1311 labels = [label.strip() for label
R. David Murrayb7deff12011-01-30 06:21:28 +00001312 in self._file.readline()[1:].split(b',')
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001313 if label.strip()]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001314 label_lists.append(labels)
R. David Murrayb7deff12011-01-30 06:21:28 +00001315 elif line == b'\037' or line == b'\037' + linesep:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001316 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +00001317 stops.append(line_pos - len(linesep))
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001318 elif not line:
R. David Murrayb7deff12011-01-30 06:21:28 +00001319 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001320 break
1321 self._toc = dict(enumerate(zip(starts, stops)))
1322 self._labels = dict(enumerate(label_lists))
1323 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001324 self._file.seek(0, 2)
1325 self._file_length = self._file.tell()
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001326
Thomas Wouters477c8d52006-05-27 19:21:47 +00001327 def _pre_mailbox_hook(self, f):
1328 """Called before writing the mailbox to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001329 babyl = b'BABYL OPTIONS:' + linesep
1330 babyl += b'Version: 5' + linesep
1331 labels = self.get_labels()
1332 labels = (label.encode() for label in labels)
1333 babyl += b'Labels:' + b','.join(labels) + linesep
1334 babyl += b'\037'
1335 f.write(babyl)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001336
1337 def _pre_message_hook(self, f):
1338 """Called before writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001339 f.write(b'\014' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001340
1341 def _post_message_hook(self, f):
1342 """Called after writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001343 f.write(linesep + b'\037')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344
1345 def _install_message(self, message):
1346 """Write message contents and return (start, stop)."""
1347 start = self._file.tell()
1348 if isinstance(message, BabylMessage):
1349 special_labels = []
1350 labels = []
1351 for label in message.get_labels():
1352 if label in self._special_labels:
1353 special_labels.append(label)
1354 else:
1355 labels.append(label)
R. David Murrayb7deff12011-01-30 06:21:28 +00001356 self._file.write(b'1')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357 for label in special_labels:
R. David Murrayb7deff12011-01-30 06:21:28 +00001358 self._file.write(b', ' + label.encode())
1359 self._file.write(b',,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001360 for label in labels:
R. David Murrayb7deff12011-01-30 06:21:28 +00001361 self._file.write(b' ' + label.encode() + b',')
1362 self._file.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001364 self._file.write(b'1,,' + linesep)
Thomas Woutersb2137042007-02-01 18:02:27 +00001365 if isinstance(message, email.message.Message):
R. David Murrayb7deff12011-01-30 06:21:28 +00001366 orig_buffer = io.BytesIO()
1367 orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001368 orig_generator.flatten(message)
1369 orig_buffer.seek(0)
1370 while True:
1371 line = orig_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001372 self._file.write(line.replace(b'\n', linesep))
1373 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001374 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001375 self._file.write(b'*** EOOH ***' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001376 if isinstance(message, BabylMessage):
R. David Murrayb7deff12011-01-30 06:21:28 +00001377 vis_buffer = io.BytesIO()
1378 vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001379 vis_generator.flatten(message.get_visible())
1380 while True:
1381 line = vis_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001382 self._file.write(line.replace(b'\n', linesep))
1383 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001384 break
1385 else:
1386 orig_buffer.seek(0)
1387 while True:
1388 line = orig_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001389 self._file.write(line.replace(b'\n', linesep))
1390 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001391 break
1392 while True:
1393 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001394 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001395 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001396 self._file.write(buffer.replace(b'\n', linesep))
1397 elif isinstance(message, (bytes, str, io.StringIO)):
1398 if isinstance(message, io.StringIO):
1399 warnings.warn("Use of StringIO input is deprecated, "
1400 "use BytesIO instead", DeprecationWarning, 3)
1401 message = message.getvalue()
1402 if isinstance(message, str):
1403 message = self._string_to_bytes(message)
1404 body_start = message.find(b'\n\n') + 2
Thomas Wouters477c8d52006-05-27 19:21:47 +00001405 if body_start - 2 != -1:
R. David Murrayb7deff12011-01-30 06:21:28 +00001406 self._file.write(message[:body_start].replace(b'\n', linesep))
1407 self._file.write(b'*** EOOH ***' + linesep)
1408 self._file.write(message[:body_start].replace(b'\n', linesep))
1409 self._file.write(message[body_start:].replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001410 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001411 self._file.write(b'*** EOOH ***' + linesep + linesep)
1412 self._file.write(message.replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001413 elif hasattr(message, 'readline'):
R. David Murrayb7deff12011-01-30 06:21:28 +00001414 if hasattr(message, 'buffer'):
1415 warnings.warn("Use of text mode files is deprecated, "
1416 "use a binary mode file instead", DeprecationWarning, 3)
1417 message = message.buffer
Thomas Wouters477c8d52006-05-27 19:21:47 +00001418 original_pos = message.tell()
1419 first_pass = True
1420 while True:
1421 line = message.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001422 # Universal newline support.
1423 if line.endswith(b'\r\n'):
1424 line = line[:-2] + b'\n'
1425 elif line.endswith(b'\r'):
1426 line = line[:-1] + b'\n'
1427 self._file.write(line.replace(b'\n', linesep))
1428 if line == b'\n' or not line:
1429 self._file.write(b'*** EOOH ***' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001430 if first_pass:
1431 first_pass = False
1432 message.seek(original_pos)
1433 else:
1434 break
1435 while True:
1436 buffer = message.read(4096) # Buffer size is arbitrary.
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001437 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001438 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001439 self._file.write(buffer.replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440 else:
1441 raise TypeError('Invalid message type: %s' % type(message))
1442 stop = self._file.tell()
1443 return (start, stop)
1444
1445
Thomas Woutersb2137042007-02-01 18:02:27 +00001446class Message(email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001447 """Message with mailbox-format-specific properties."""
1448
1449 def __init__(self, message=None):
1450 """Initialize a Message instance."""
Thomas Woutersb2137042007-02-01 18:02:27 +00001451 if isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001452 self._become_message(copy.deepcopy(message))
1453 if isinstance(message, Message):
1454 message._explain_to(self)
R. David Murrayb7deff12011-01-30 06:21:28 +00001455 elif isinstance(message, bytes):
1456 self._become_message(email.message_from_bytes(message))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001457 elif isinstance(message, str):
1458 self._become_message(email.message_from_string(message))
R. David Murrayb7deff12011-01-30 06:21:28 +00001459 elif isinstance(message, io.TextIOWrapper):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001460 self._become_message(email.message_from_file(message))
R. David Murrayb7deff12011-01-30 06:21:28 +00001461 elif hasattr(message, "read"):
1462 self._become_message(email.message_from_binary_file(message))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001463 elif message is None:
Thomas Woutersb2137042007-02-01 18:02:27 +00001464 email.message.Message.__init__(self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001465 else:
1466 raise TypeError('Invalid message type: %s' % type(message))
1467
1468 def _become_message(self, message):
1469 """Assume the non-format-specific state of message."""
1470 for name in ('_headers', '_unixfrom', '_payload', '_charset',
1471 'preamble', 'epilogue', 'defects', '_default_type'):
1472 self.__dict__[name] = message.__dict__[name]
1473
1474 def _explain_to(self, message):
1475 """Copy format-specific state to message insofar as possible."""
1476 if isinstance(message, Message):
1477 return # There's nothing format-specific to explain.
1478 else:
1479 raise TypeError('Cannot convert to specified type')
1480
1481
1482class MaildirMessage(Message):
1483 """Message with Maildir-specific properties."""
1484
1485 def __init__(self, message=None):
1486 """Initialize a MaildirMessage instance."""
1487 self._subdir = 'new'
1488 self._info = ''
1489 self._date = time.time()
1490 Message.__init__(self, message)
1491
1492 def get_subdir(self):
1493 """Return 'new' or 'cur'."""
1494 return self._subdir
1495
1496 def set_subdir(self, subdir):
1497 """Set subdir to 'new' or 'cur'."""
1498 if subdir == 'new' or subdir == 'cur':
1499 self._subdir = subdir
1500 else:
1501 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1502
1503 def get_flags(self):
1504 """Return as a string the flags that are set."""
1505 if self._info.startswith('2,'):
1506 return self._info[2:]
1507 else:
1508 return ''
1509
1510 def set_flags(self, flags):
1511 """Set the given flags and unset all others."""
1512 self._info = '2,' + ''.join(sorted(flags))
1513
1514 def add_flag(self, flag):
1515 """Set the given flag(s) without changing others."""
1516 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1517
1518 def remove_flag(self, flag):
1519 """Unset the given string flag(s) without changing others."""
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001520 if self.get_flags():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1522
1523 def get_date(self):
1524 """Return delivery date of message, in seconds since the epoch."""
1525 return self._date
1526
1527 def set_date(self, date):
1528 """Set delivery date of message, in seconds since the epoch."""
1529 try:
1530 self._date = float(date)
1531 except ValueError:
1532 raise TypeError("can't convert to float: %s" % date)
1533
1534 def get_info(self):
1535 """Get the message's "info" as a string."""
1536 return self._info
1537
1538 def set_info(self, info):
1539 """Set the message's "info" string."""
1540 if isinstance(info, str):
1541 self._info = info
1542 else:
1543 raise TypeError('info must be a string: %s' % type(info))
1544
1545 def _explain_to(self, message):
1546 """Copy Maildir-specific state to message insofar as possible."""
1547 if isinstance(message, MaildirMessage):
1548 message.set_flags(self.get_flags())
1549 message.set_subdir(self.get_subdir())
1550 message.set_date(self.get_date())
1551 elif isinstance(message, _mboxMMDFMessage):
1552 flags = set(self.get_flags())
1553 if 'S' in flags:
1554 message.add_flag('R')
1555 if self.get_subdir() == 'cur':
1556 message.add_flag('O')
1557 if 'T' in flags:
1558 message.add_flag('D')
1559 if 'F' in flags:
1560 message.add_flag('F')
1561 if 'R' in flags:
1562 message.add_flag('A')
1563 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1564 elif isinstance(message, MHMessage):
1565 flags = set(self.get_flags())
1566 if 'S' not in flags:
1567 message.add_sequence('unseen')
1568 if 'R' in flags:
1569 message.add_sequence('replied')
1570 if 'F' in flags:
1571 message.add_sequence('flagged')
1572 elif isinstance(message, BabylMessage):
1573 flags = set(self.get_flags())
1574 if 'S' not in flags:
1575 message.add_label('unseen')
1576 if 'T' in flags:
1577 message.add_label('deleted')
1578 if 'R' in flags:
1579 message.add_label('answered')
1580 if 'P' in flags:
1581 message.add_label('forwarded')
1582 elif isinstance(message, Message):
1583 pass
1584 else:
1585 raise TypeError('Cannot convert to specified type: %s' %
1586 type(message))
1587
1588
1589class _mboxMMDFMessage(Message):
1590 """Message with mbox- or MMDF-specific properties."""
1591
1592 def __init__(self, message=None):
1593 """Initialize an mboxMMDFMessage instance."""
1594 self.set_from('MAILER-DAEMON', True)
Thomas Woutersb2137042007-02-01 18:02:27 +00001595 if isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001596 unixfrom = message.get_unixfrom()
1597 if unixfrom is not None and unixfrom.startswith('From '):
1598 self.set_from(unixfrom[5:])
1599 Message.__init__(self, message)
1600
1601 def get_from(self):
1602 """Return contents of "From " line."""
1603 return self._from
1604
1605 def set_from(self, from_, time_=None):
1606 """Set "From " line, formatting and appending time_ if specified."""
1607 if time_ is not None:
1608 if time_ is True:
1609 time_ = time.gmtime()
1610 from_ += ' ' + time.asctime(time_)
1611 self._from = from_
1612
1613 def get_flags(self):
1614 """Return as a string the flags that are set."""
1615 return self.get('Status', '') + self.get('X-Status', '')
1616
1617 def set_flags(self, flags):
1618 """Set the given flags and unset all others."""
1619 flags = set(flags)
1620 status_flags, xstatus_flags = '', ''
1621 for flag in ('R', 'O'):
1622 if flag in flags:
1623 status_flags += flag
1624 flags.remove(flag)
1625 for flag in ('D', 'F', 'A'):
1626 if flag in flags:
1627 xstatus_flags += flag
1628 flags.remove(flag)
1629 xstatus_flags += ''.join(sorted(flags))
1630 try:
1631 self.replace_header('Status', status_flags)
1632 except KeyError:
1633 self.add_header('Status', status_flags)
1634 try:
1635 self.replace_header('X-Status', xstatus_flags)
1636 except KeyError:
1637 self.add_header('X-Status', xstatus_flags)
1638
1639 def add_flag(self, flag):
1640 """Set the given flag(s) without changing others."""
1641 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1642
1643 def remove_flag(self, flag):
1644 """Unset the given string flag(s) without changing others."""
1645 if 'Status' in self or 'X-Status' in self:
1646 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1647
1648 def _explain_to(self, message):
1649 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1650 if isinstance(message, MaildirMessage):
1651 flags = set(self.get_flags())
1652 if 'O' in flags:
1653 message.set_subdir('cur')
1654 if 'F' in flags:
1655 message.add_flag('F')
1656 if 'A' in flags:
1657 message.add_flag('R')
1658 if 'R' in flags:
1659 message.add_flag('S')
1660 if 'D' in flags:
1661 message.add_flag('T')
1662 del message['status']
1663 del message['x-status']
1664 maybe_date = ' '.join(self.get_from().split()[-5:])
1665 try:
1666 message.set_date(calendar.timegm(time.strptime(maybe_date,
1667 '%a %b %d %H:%M:%S %Y')))
1668 except (ValueError, OverflowError):
1669 pass
1670 elif isinstance(message, _mboxMMDFMessage):
1671 message.set_flags(self.get_flags())
1672 message.set_from(self.get_from())
1673 elif isinstance(message, MHMessage):
1674 flags = set(self.get_flags())
1675 if 'R' not in flags:
1676 message.add_sequence('unseen')
1677 if 'A' in flags:
1678 message.add_sequence('replied')
1679 if 'F' in flags:
1680 message.add_sequence('flagged')
1681 del message['status']
1682 del message['x-status']
1683 elif isinstance(message, BabylMessage):
1684 flags = set(self.get_flags())
1685 if 'R' not in flags:
1686 message.add_label('unseen')
1687 if 'D' in flags:
1688 message.add_label('deleted')
1689 if 'A' in flags:
1690 message.add_label('answered')
1691 del message['status']
1692 del message['x-status']
1693 elif isinstance(message, Message):
1694 pass
1695 else:
1696 raise TypeError('Cannot convert to specified type: %s' %
1697 type(message))
1698
1699
1700class mboxMessage(_mboxMMDFMessage):
1701 """Message with mbox-specific properties."""
1702
1703
1704class MHMessage(Message):
1705 """Message with MH-specific properties."""
1706
1707 def __init__(self, message=None):
1708 """Initialize an MHMessage instance."""
1709 self._sequences = []
1710 Message.__init__(self, message)
1711
1712 def get_sequences(self):
1713 """Return a list of sequences that include the message."""
1714 return self._sequences[:]
1715
1716 def set_sequences(self, sequences):
1717 """Set the list of sequences that include the message."""
1718 self._sequences = list(sequences)
1719
1720 def add_sequence(self, sequence):
1721 """Add sequence to list of sequences including the message."""
1722 if isinstance(sequence, str):
1723 if not sequence in self._sequences:
1724 self._sequences.append(sequence)
1725 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001726 raise TypeError('sequence type must be str: %s' % type(sequence))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001727
1728 def remove_sequence(self, sequence):
1729 """Remove sequence from the list of sequences including the message."""
1730 try:
1731 self._sequences.remove(sequence)
1732 except ValueError:
1733 pass
1734
1735 def _explain_to(self, message):
1736 """Copy MH-specific state to message insofar as possible."""
1737 if isinstance(message, MaildirMessage):
1738 sequences = set(self.get_sequences())
1739 if 'unseen' in sequences:
1740 message.set_subdir('cur')
1741 else:
1742 message.set_subdir('cur')
1743 message.add_flag('S')
1744 if 'flagged' in sequences:
1745 message.add_flag('F')
1746 if 'replied' in sequences:
1747 message.add_flag('R')
1748 elif isinstance(message, _mboxMMDFMessage):
1749 sequences = set(self.get_sequences())
1750 if 'unseen' not in sequences:
1751 message.add_flag('RO')
1752 else:
1753 message.add_flag('O')
1754 if 'flagged' in sequences:
1755 message.add_flag('F')
1756 if 'replied' in sequences:
1757 message.add_flag('A')
1758 elif isinstance(message, MHMessage):
1759 for sequence in self.get_sequences():
1760 message.add_sequence(sequence)
1761 elif isinstance(message, BabylMessage):
1762 sequences = set(self.get_sequences())
1763 if 'unseen' in sequences:
1764 message.add_label('unseen')
1765 if 'replied' in sequences:
1766 message.add_label('answered')
1767 elif isinstance(message, Message):
1768 pass
1769 else:
1770 raise TypeError('Cannot convert to specified type: %s' %
1771 type(message))
1772
1773
1774class BabylMessage(Message):
1775 """Message with Babyl-specific properties."""
1776
1777 def __init__(self, message=None):
1778 """Initialize an BabylMessage instance."""
1779 self._labels = []
1780 self._visible = Message()
1781 Message.__init__(self, message)
1782
1783 def get_labels(self):
1784 """Return a list of labels on the message."""
1785 return self._labels[:]
1786
1787 def set_labels(self, labels):
1788 """Set the list of labels on the message."""
1789 self._labels = list(labels)
1790
1791 def add_label(self, label):
1792 """Add label to list of labels on the message."""
1793 if isinstance(label, str):
1794 if label not in self._labels:
1795 self._labels.append(label)
1796 else:
1797 raise TypeError('label must be a string: %s' % type(label))
1798
1799 def remove_label(self, label):
1800 """Remove label from the list of labels on the message."""
1801 try:
1802 self._labels.remove(label)
1803 except ValueError:
1804 pass
1805
1806 def get_visible(self):
1807 """Return a Message representation of visible headers."""
1808 return Message(self._visible)
1809
1810 def set_visible(self, visible):
1811 """Set the Message representation of visible headers."""
1812 self._visible = Message(visible)
1813
1814 def update_visible(self):
1815 """Update and/or sensibly generate a set of visible headers."""
1816 for header in self._visible.keys():
1817 if header in self:
1818 self._visible.replace_header(header, self[header])
1819 else:
1820 del self._visible[header]
1821 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1822 if header in self and header not in self._visible:
1823 self._visible[header] = self[header]
1824
1825 def _explain_to(self, message):
1826 """Copy Babyl-specific state to message insofar as possible."""
1827 if isinstance(message, MaildirMessage):
1828 labels = set(self.get_labels())
1829 if 'unseen' in labels:
1830 message.set_subdir('cur')
1831 else:
1832 message.set_subdir('cur')
1833 message.add_flag('S')
1834 if 'forwarded' in labels or 'resent' in labels:
1835 message.add_flag('P')
1836 if 'answered' in labels:
1837 message.add_flag('R')
1838 if 'deleted' in labels:
1839 message.add_flag('T')
1840 elif isinstance(message, _mboxMMDFMessage):
1841 labels = set(self.get_labels())
1842 if 'unseen' not in labels:
1843 message.add_flag('RO')
1844 else:
1845 message.add_flag('O')
1846 if 'deleted' in labels:
1847 message.add_flag('D')
1848 if 'answered' in labels:
1849 message.add_flag('A')
1850 elif isinstance(message, MHMessage):
1851 labels = set(self.get_labels())
1852 if 'unseen' in labels:
1853 message.add_sequence('unseen')
1854 if 'answered' in labels:
1855 message.add_sequence('replied')
1856 elif isinstance(message, BabylMessage):
1857 message.set_visible(self.get_visible())
1858 for label in self.get_labels():
1859 message.add_label(label)
1860 elif isinstance(message, Message):
1861 pass
1862 else:
1863 raise TypeError('Cannot convert to specified type: %s' %
1864 type(message))
1865
1866
1867class MMDFMessage(_mboxMMDFMessage):
1868 """Message with MMDF-specific properties."""
1869
1870
1871class _ProxyFile:
1872 """A read-only wrapper of a file."""
1873
1874 def __init__(self, f, pos=None):
1875 """Initialize a _ProxyFile."""
1876 self._file = f
1877 if pos is None:
1878 self._pos = f.tell()
1879 else:
1880 self._pos = pos
1881
1882 def read(self, size=None):
1883 """Read bytes."""
Guido van Rossum98297ee2007-11-06 21:34:58 +00001884 return self._read(size, self._file.read)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001885
R. David Murrayb7deff12011-01-30 06:21:28 +00001886 def read1(self, size=None):
1887 """Read bytes."""
1888 return self._read(size, self._file.read1)
1889
Thomas Wouters477c8d52006-05-27 19:21:47 +00001890 def readline(self, size=None):
1891 """Read a line."""
Guido van Rossum98297ee2007-11-06 21:34:58 +00001892 return self._read(size, self._file.readline)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001893
1894 def readlines(self, sizehint=None):
1895 """Read multiple lines."""
1896 result = []
1897 for line in self:
1898 result.append(line)
1899 if sizehint is not None:
1900 sizehint -= len(line)
1901 if sizehint <= 0:
1902 break
1903 return result
1904
1905 def __iter__(self):
1906 """Iterate over lines."""
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001907 while True:
1908 line = self.readline()
1909 if not line:
1910 raise StopIteration
1911 yield line
Thomas Wouters477c8d52006-05-27 19:21:47 +00001912
1913 def tell(self):
1914 """Return the position."""
1915 return self._pos
1916
1917 def seek(self, offset, whence=0):
1918 """Change position."""
1919 if whence == 1:
1920 self._file.seek(self._pos)
1921 self._file.seek(offset, whence)
1922 self._pos = self._file.tell()
1923
1924 def close(self):
1925 """Close the file."""
R David Murrayc88bce12011-06-17 22:24:05 -04001926 if hasattr(self, '_file'):
1927 if hasattr(self._file, 'close'):
1928 self._file.close()
1929 del self._file
Thomas Wouters477c8d52006-05-27 19:21:47 +00001930
1931 def _read(self, size, read_method):
1932 """Read size bytes using read_method."""
1933 if size is None:
1934 size = -1
1935 self._file.seek(self._pos)
1936 result = read_method(size)
1937 self._pos = self._file.tell()
1938 return result
1939
Georg Brandl6ce29fa2010-10-30 14:33:28 +00001940 def __enter__(self):
1941 """Context manager protocol support."""
1942 return self
1943
1944 def __exit__(self, *exc):
1945 self.close()
1946
R. David Murrayb7deff12011-01-30 06:21:28 +00001947 def readable(self):
1948 return self._file.readable()
1949
1950 def writable(self):
1951 return self._file.writable()
1952
1953 def seekable(self):
1954 return self._file.seekable()
1955
1956 def flush(self):
1957 return self._file.flush()
1958
1959 @property
1960 def closed(self):
R David Murrayc88bce12011-06-17 22:24:05 -04001961 if not hasattr(self, '_file'):
1962 return True
1963 if not hasattr(self._file, 'closed'):
1964 return False
R. David Murrayb7deff12011-01-30 06:21:28 +00001965 return self._file.closed
1966
Thomas Wouters477c8d52006-05-27 19:21:47 +00001967
1968class _PartialFile(_ProxyFile):
1969 """A read-only wrapper of part of a file."""
1970
1971 def __init__(self, f, start=None, stop=None):
1972 """Initialize a _PartialFile."""
1973 _ProxyFile.__init__(self, f, start)
1974 self._start = start
1975 self._stop = stop
1976
1977 def tell(self):
1978 """Return the position with respect to start."""
1979 return _ProxyFile.tell(self) - self._start
1980
1981 def seek(self, offset, whence=0):
1982 """Change position, possibly with respect to start or stop."""
1983 if whence == 0:
1984 self._pos = self._start
1985 whence = 1
1986 elif whence == 2:
1987 self._pos = self._stop
1988 whence = 1
1989 _ProxyFile.seek(self, offset, whence)
1990
1991 def _read(self, size, read_method):
1992 """Read size bytes using read_method, honoring start and stop."""
1993 remaining = self._stop - self._pos
1994 if remaining <= 0:
R. David Murrayb7deff12011-01-30 06:21:28 +00001995 return b''
Thomas Wouters477c8d52006-05-27 19:21:47 +00001996 if size is None or size < 0 or size > remaining:
1997 size = remaining
1998 return _ProxyFile._read(self, size, read_method)
1999
Georg Brandl6ce29fa2010-10-30 14:33:28 +00002000 def close(self):
2001 # do *not* close the underlying file object for partial files,
2002 # since it's global to the mailbox object
R David Murrayc88bce12011-06-17 22:24:05 -04002003 if hasattr(self, '_file'):
2004 del self._file
Georg Brandl6ce29fa2010-10-30 14:33:28 +00002005
Thomas Wouters477c8d52006-05-27 19:21:47 +00002006
2007def _lock_file(f, dotlock=True):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002008 """Lock file f using lockf and dot locking."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00002009 dotlock_done = False
2010 try:
2011 if fcntl:
2012 try:
2013 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
Guido van Rossumb940e112007-01-10 16:19:56 +00002014 except IOError as e:
R. David Murray752b9502011-03-03 18:12:34 +00002015 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002016 raise ExternalClashError('lockf: lock unavailable: %s' %
2017 f.name)
2018 else:
2019 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +00002020 if dotlock:
2021 try:
2022 pre_lock = _create_temporary(f.name + '.lock')
2023 pre_lock.close()
Guido van Rossumb940e112007-01-10 16:19:56 +00002024 except IOError as e:
R. David Murray752b9502011-03-03 18:12:34 +00002025 if e.errno in (errno.EACCES, errno.EROFS):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002026 return # Without write access, just skip dotlocking.
2027 else:
2028 raise
2029 try:
2030 if hasattr(os, 'link'):
2031 os.link(pre_lock.name, f.name + '.lock')
2032 dotlock_done = True
2033 os.unlink(pre_lock.name)
2034 else:
2035 os.rename(pre_lock.name, f.name + '.lock')
2036 dotlock_done = True
Guido van Rossumb940e112007-01-10 16:19:56 +00002037 except OSError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002038 if e.errno == errno.EEXIST or \
2039 (os.name == 'os2' and e.errno == errno.EACCES):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002040 os.remove(pre_lock.name)
2041 raise ExternalClashError('dot lock unavailable: %s' %
2042 f.name)
2043 else:
2044 raise
2045 except:
2046 if fcntl:
2047 fcntl.lockf(f, fcntl.LOCK_UN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002048 if dotlock_done:
2049 os.remove(f.name + '.lock')
2050 raise
2051
2052def _unlock_file(f):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002053 """Unlock file f using lockf and dot locking."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00002054 if fcntl:
2055 fcntl.lockf(f, fcntl.LOCK_UN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002056 if os.path.exists(f.name + '.lock'):
2057 os.remove(f.name + '.lock')
2058
2059def _create_carefully(path):
2060 """Create a file if it doesn't exist and open for reading and writing."""
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00002061 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00002063 return open(path, 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00002064 finally:
2065 os.close(fd)
2066
2067def _create_temporary(path):
2068 """Create a temp file based on path and open for reading and writing."""
2069 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
2070 socket.gethostname(),
2071 os.getpid()))
2072
Thomas Wouters89f507f2006-12-13 04:49:30 +00002073def _sync_flush(f):
2074 """Ensure changes to file f are physically on disk."""
2075 f.flush()
Thomas Wouters902d6eb2007-01-09 23:18:33 +00002076 if hasattr(os, 'fsync'):
2077 os.fsync(f.fileno())
Thomas Wouters89f507f2006-12-13 04:49:30 +00002078
2079def _sync_close(f):
2080 """Close file f, ensuring all changes are physically on disk."""
2081 _sync_flush(f)
2082 f.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +00002083
Guido van Rossum62448671996-09-17 21:33:15 +00002084
Thomas Wouters477c8d52006-05-27 19:21:47 +00002085class Error(Exception):
2086 """Raised for module-specific errors."""
2087
2088class NoSuchMailboxError(Error):
2089 """The specified mailbox does not exist and won't be created."""
2090
2091class NotEmptyError(Error):
2092 """The specified mailbox is not empty and deletion was requested."""
2093
2094class ExternalClashError(Error):
2095 """Another process caused an action to fail."""
2096
2097class FormatError(Error):
2098 """A file appears to have an invalid format."""