blob: c73fb95fe218349a14bc36145494079d32e95122 [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
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300211 # Whether each message must end in a newline
212 _append_newline = False
213
Thomas Wouters477c8d52006-05-27 19:21:47 +0000214 def _dump_message(self, message, target, mangle_from_=False):
R. David Murrayb7deff12011-01-30 06:21:28 +0000215 # This assumes the target file is open in binary mode.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000216 """Dump message contents to target file."""
Thomas Woutersb2137042007-02-01 18:02:27 +0000217 if isinstance(message, email.message.Message):
R. David Murrayb7deff12011-01-30 06:21:28 +0000218 buffer = io.BytesIO()
219 gen = email.generator.BytesGenerator(buffer, mangle_from_, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000220 gen.flatten(message)
221 buffer.seek(0)
Guido van Rossum671117a2007-08-31 04:25:05 +0000222 data = buffer.read()
R. David Murrayb7deff12011-01-30 06:21:28 +0000223 data = data.replace(b'\n', linesep)
Guido van Rossum671117a2007-08-31 04:25:05 +0000224 target.write(data)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300225 if self._append_newline and not data.endswith(linesep):
226 # Make sure the message ends with a newline
227 target.write(linesep)
R. David Murrayb7deff12011-01-30 06:21:28 +0000228 elif isinstance(message, (str, bytes, io.StringIO)):
229 if isinstance(message, io.StringIO):
230 warnings.warn("Use of StringIO input is deprecated, "
231 "use BytesIO instead", DeprecationWarning, 3)
232 message = message.getvalue()
233 if isinstance(message, str):
234 message = self._string_to_bytes(message)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000235 if mangle_from_:
R. David Murrayb7deff12011-01-30 06:21:28 +0000236 message = message.replace(b'\nFrom ', b'\n>From ')
237 message = message.replace(b'\n', linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000238 target.write(message)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300239 if self._append_newline and not message.endswith(linesep):
240 # Make sure the message ends with a newline
241 target.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000242 elif hasattr(message, 'read'):
R. David Murrayb7deff12011-01-30 06:21:28 +0000243 if hasattr(message, 'buffer'):
244 warnings.warn("Use of text mode files is deprecated, "
245 "use a binary mode file instead", DeprecationWarning, 3)
246 message = message.buffer
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300247 lastline = None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000248 while True:
249 line = message.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +0000250 # Universal newline support.
251 if line.endswith(b'\r\n'):
252 line = line[:-2] + b'\n'
253 elif line.endswith(b'\r'):
254 line = line[:-1] + b'\n'
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000255 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000256 break
R. David Murrayb7deff12011-01-30 06:21:28 +0000257 if mangle_from_ and line.startswith(b'From '):
258 line = b'>From ' + line[5:]
259 line = line.replace(b'\n', linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000260 target.write(line)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300261 lastline = line
262 if self._append_newline and lastline and not lastline.endswith(linesep):
263 # Make sure the message ends with a newline
264 target.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000265 else:
266 raise TypeError('Invalid message type: %s' % type(message))
267
268
269class Maildir(Mailbox):
270 """A qmail-style Maildir mailbox."""
271
272 colon = ':'
273
Georg Brandlaa5b4112008-05-11 20:51:18 +0000274 def __init__(self, dirname, factory=None, create=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000275 """Initialize a Maildir instance."""
276 Mailbox.__init__(self, dirname, factory, create)
R David Murraycaed7fe2011-05-06 22:07:19 -0400277 self._paths = {
278 'tmp': os.path.join(self._path, 'tmp'),
279 'new': os.path.join(self._path, 'new'),
280 'cur': os.path.join(self._path, 'cur'),
281 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000282 if not os.path.exists(self._path):
283 if create:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000284 os.mkdir(self._path, 0o700)
R David Murraycaed7fe2011-05-06 22:07:19 -0400285 for path in self._paths.values():
286 os.mkdir(path, 0o700)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000287 else:
288 raise NoSuchMailboxError(self._path)
289 self._toc = {}
Petri Lehtinen8c482ee2011-11-05 09:44:59 +0200290 self._toc_mtimes = {'cur': 0, 'new': 0}
291 self._last_read = 0 # Records last time we read cur/new
292 self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
Thomas Wouters477c8d52006-05-27 19:21:47 +0000293
294 def add(self, message):
295 """Add message and return assigned key."""
296 tmp_file = self._create_tmp()
297 try:
298 self._dump_message(message, tmp_file)
R. David Murrayfc141142011-02-11 22:47:17 +0000299 except BaseException:
300 tmp_file.close()
301 os.remove(tmp_file.name)
302 raise
303 _sync_close(tmp_file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000304 if isinstance(message, MaildirMessage):
305 subdir = message.get_subdir()
306 suffix = self.colon + message.get_info()
307 if suffix == self.colon:
308 suffix = ''
309 else:
310 subdir = 'new'
311 suffix = ''
312 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
313 dest = os.path.join(self._path, subdir, uniq + suffix)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000314 try:
315 if hasattr(os, 'link'):
316 os.link(tmp_file.name, dest)
317 os.remove(tmp_file.name)
318 else:
319 os.rename(tmp_file.name, dest)
Guido van Rossumb940e112007-01-10 16:19:56 +0000320 except OSError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000321 os.remove(tmp_file.name)
322 if e.errno == errno.EEXIST:
323 raise ExternalClashError('Name clash with existing message: %s'
324 % dest)
325 else:
326 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000327 if isinstance(message, MaildirMessage):
328 os.utime(dest, (os.path.getatime(dest), message.get_date()))
329 return uniq
330
331 def remove(self, key):
332 """Remove the keyed message; raise KeyError if it doesn't exist."""
333 os.remove(os.path.join(self._path, self._lookup(key)))
334
335 def discard(self, key):
336 """If the keyed message exists, remove it."""
337 # This overrides an inapplicable implementation in the superclass.
338 try:
339 self.remove(key)
340 except KeyError:
341 pass
Guido van Rossumb940e112007-01-10 16:19:56 +0000342 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000343 if e.errno != errno.ENOENT:
344 raise
345
346 def __setitem__(self, key, message):
347 """Replace the keyed message; raise KeyError if it doesn't exist."""
348 old_subpath = self._lookup(key)
349 temp_key = self.add(message)
350 temp_subpath = self._lookup(temp_key)
351 if isinstance(message, MaildirMessage):
352 # temp's subdir and suffix were specified by message.
353 dominant_subpath = temp_subpath
354 else:
355 # temp's subdir and suffix were defaults from add().
356 dominant_subpath = old_subpath
357 subdir = os.path.dirname(dominant_subpath)
358 if self.colon in dominant_subpath:
359 suffix = self.colon + dominant_subpath.split(self.colon)[-1]
360 else:
361 suffix = ''
362 self.discard(key)
363 new_path = os.path.join(self._path, subdir, key + suffix)
364 os.rename(os.path.join(self._path, temp_subpath), new_path)
365 if isinstance(message, MaildirMessage):
366 os.utime(new_path, (os.path.getatime(new_path),
367 message.get_date()))
368
369 def get_message(self, key):
370 """Return a Message representation or raise a KeyError."""
371 subpath = self._lookup(key)
R. David Murrayb7deff12011-01-30 06:21:28 +0000372 f = open(os.path.join(self._path, subpath), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000373 try:
Christian Heimesfdab48e2008-01-20 09:06:41 +0000374 if self._factory:
375 msg = self._factory(f)
376 else:
377 msg = MaildirMessage(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000378 finally:
379 f.close()
380 subdir, name = os.path.split(subpath)
381 msg.set_subdir(subdir)
382 if self.colon in name:
383 msg.set_info(name.split(self.colon)[-1])
384 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
385 return msg
386
R. David Murrayb7deff12011-01-30 06:21:28 +0000387 def get_bytes(self, key):
388 """Return a bytes representation or raise a KeyError."""
389 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000390 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000391 return f.read().replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000392 finally:
393 f.close()
394
395 def get_file(self, key):
396 """Return a file-like representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000397 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000398 return _ProxyFile(f)
399
400 def iterkeys(self):
401 """Return an iterator over keys."""
402 self._refresh()
403 for key in self._toc:
404 try:
405 self._lookup(key)
406 except KeyError:
407 continue
408 yield key
409
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000410 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000411 """Return True if the keyed message exists, False otherwise."""
412 self._refresh()
413 return key in self._toc
414
415 def __len__(self):
416 """Return a count of messages in the mailbox."""
417 self._refresh()
418 return len(self._toc)
419
420 def flush(self):
421 """Write any pending changes to disk."""
Antoine Pitrou03f13442009-11-02 11:36:51 +0000422 # Maildir changes are always written immediately, so there's nothing
R David Murraycaed7fe2011-05-06 22:07:19 -0400423 # to do.
424 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000425
426 def lock(self):
427 """Lock the mailbox."""
428 return
429
430 def unlock(self):
431 """Unlock the mailbox if it is locked."""
432 return
433
434 def close(self):
435 """Flush and close the mailbox."""
436 return
437
438 def list_folders(self):
439 """Return a list of folder names."""
440 result = []
441 for entry in os.listdir(self._path):
442 if len(entry) > 1 and entry[0] == '.' and \
443 os.path.isdir(os.path.join(self._path, entry)):
444 result.append(entry[1:])
445 return result
446
447 def get_folder(self, folder):
448 """Return a Maildir instance for the named folder."""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449 return Maildir(os.path.join(self._path, '.' + folder),
450 factory=self._factory,
451 create=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000452
453 def add_folder(self, folder):
454 """Create a folder and return a Maildir instance representing it."""
455 path = os.path.join(self._path, '.' + folder)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000456 result = Maildir(path, factory=self._factory)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000457 maildirfolder_path = os.path.join(path, 'maildirfolder')
458 if not os.path.exists(maildirfolder_path):
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000459 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
460 0o666))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000461 return result
462
463 def remove_folder(self, folder):
464 """Delete the named folder, which must be empty."""
465 path = os.path.join(self._path, '.' + folder)
466 for entry in os.listdir(os.path.join(path, 'new')) + \
467 os.listdir(os.path.join(path, 'cur')):
468 if len(entry) < 1 or entry[0] != '.':
469 raise NotEmptyError('Folder contains message(s): %s' % folder)
470 for entry in os.listdir(path):
471 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
472 os.path.isdir(os.path.join(path, entry)):
473 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
474 (folder, entry))
475 for root, dirs, files in os.walk(path, topdown=False):
476 for entry in files:
477 os.remove(os.path.join(root, entry))
478 for entry in dirs:
479 os.rmdir(os.path.join(root, entry))
480 os.rmdir(path)
481
482 def clean(self):
483 """Delete old files in "tmp"."""
484 now = time.time()
485 for entry in os.listdir(os.path.join(self._path, 'tmp')):
486 path = os.path.join(self._path, 'tmp', entry)
487 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
488 os.remove(path)
489
490 _count = 1 # This is used to generate unique file names.
491
492 def _create_tmp(self):
493 """Create a file in the tmp subdirectory and open and return it."""
494 now = time.time()
495 hostname = socket.gethostname()
496 if '/' in hostname:
497 hostname = hostname.replace('/', r'\057')
498 if ':' in hostname:
499 hostname = hostname.replace(':', r'\072')
500 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
501 Maildir._count, hostname)
502 path = os.path.join(self._path, 'tmp', uniq)
503 try:
504 os.stat(path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000505 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000506 if e.errno == errno.ENOENT:
507 Maildir._count += 1
Thomas Wouters89f507f2006-12-13 04:49:30 +0000508 try:
509 return _create_carefully(path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000510 except OSError as e:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000511 if e.errno != errno.EEXIST:
512 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000513 else:
514 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000515
516 # Fall through to here if stat succeeded or open raised EEXIST.
517 raise ExternalClashError('Name clash prevented file creation: %s' %
518 path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000519
520 def _refresh(self):
521 """Update table of contents mapping."""
R David Murraycaed7fe2011-05-06 22:07:19 -0400522 # If it has been less than two seconds since the last _refresh() call,
523 # we have to unconditionally re-read the mailbox just in case it has
524 # been modified, because os.path.mtime() has a 2 sec resolution in the
525 # most common worst case (FAT) and a 1 sec resolution typically. This
526 # results in a few unnecessary re-reads when _refresh() is called
527 # multiple times in that interval, but once the clock ticks over, we
528 # will only re-read as needed. Because the filesystem might be being
529 # served by an independent system with its own clock, we record and
530 # compare with the mtimes from the filesystem. Because the other
531 # system's clock might be skewing relative to our clock, we add an
532 # extra delta to our wait. The default is one tenth second, but is an
533 # instance variable and so can be adjusted if dealing with a
534 # particularly skewed or irregular system.
535 if time.time() - self._last_read > 2 + self._skewfactor:
536 refresh = False
537 for subdir in self._toc_mtimes:
538 mtime = os.path.getmtime(self._paths[subdir])
539 if mtime > self._toc_mtimes[subdir]:
540 refresh = True
541 self._toc_mtimes[subdir] = mtime
542 if not refresh:
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000543 return
R David Murraycaed7fe2011-05-06 22:07:19 -0400544 # Refresh toc
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545 self._toc = {}
R David Murraycaed7fe2011-05-06 22:07:19 -0400546 for subdir in self._toc_mtimes:
547 path = self._paths[subdir]
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000548 for entry in os.listdir(path):
549 p = os.path.join(path, entry)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000550 if os.path.isdir(p):
551 continue
Thomas Wouters477c8d52006-05-27 19:21:47 +0000552 uniq = entry.split(self.colon)[0]
553 self._toc[uniq] = os.path.join(subdir, entry)
R David Murraycaed7fe2011-05-06 22:07:19 -0400554 self._last_read = time.time()
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000555
Thomas Wouters477c8d52006-05-27 19:21:47 +0000556 def _lookup(self, key):
557 """Use TOC to return subpath for given key, or raise a KeyError."""
558 try:
559 if os.path.exists(os.path.join(self._path, self._toc[key])):
560 return self._toc[key]
561 except KeyError:
562 pass
563 self._refresh()
564 try:
565 return self._toc[key]
566 except KeyError:
567 raise KeyError('No message with key: %s' % key)
568
569 # This method is for backward compatibility only.
570 def next(self):
571 """Return the next message in a one-time iteration."""
572 if not hasattr(self, '_onetime_keys'):
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000573 self._onetime_keys = iter(self.keys())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000574 while True:
575 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000576 return self[next(self._onetime_keys)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000577 except StopIteration:
578 return None
579 except KeyError:
580 continue
581
582
583class _singlefileMailbox(Mailbox):
584 """A single-file mailbox."""
585
586 def __init__(self, path, factory=None, create=True):
587 """Initialize a single-file mailbox."""
588 Mailbox.__init__(self, path, factory, create)
589 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000590 f = open(self._path, 'rb+')
Guido van Rossumb940e112007-01-10 16:19:56 +0000591 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000592 if e.errno == errno.ENOENT:
593 if create:
R. David Murrayb7deff12011-01-30 06:21:28 +0000594 f = open(self._path, 'wb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000595 else:
596 raise NoSuchMailboxError(self._path)
R. David Murray752b9502011-03-03 18:12:34 +0000597 elif e.errno in (errno.EACCES, errno.EROFS):
R. David Murrayb7deff12011-01-30 06:21:28 +0000598 f = open(self._path, 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000599 else:
600 raise
601 self._file = f
602 self._toc = None
603 self._next_key = 0
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300604 self._pending = False # No changes require rewriting the file.
605 self._pending_sync = False # No need to sync the file
Thomas Wouters477c8d52006-05-27 19:21:47 +0000606 self._locked = False
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300607 self._file_length = None # Used to record mailbox size
Thomas Wouters477c8d52006-05-27 19:21:47 +0000608
609 def add(self, message):
610 """Add message and return assigned key."""
611 self._lookup()
612 self._toc[self._next_key] = self._append_message(message)
613 self._next_key += 1
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300614 # _append_message appends the message to the mailbox file. We
615 # don't need a full rewrite + rename, sync is enough.
616 self._pending_sync = True
Thomas Wouters477c8d52006-05-27 19:21:47 +0000617 return self._next_key - 1
618
619 def remove(self, key):
620 """Remove the keyed message; raise KeyError if it doesn't exist."""
621 self._lookup(key)
622 del self._toc[key]
623 self._pending = True
624
625 def __setitem__(self, key, message):
626 """Replace the keyed message; raise KeyError if it doesn't exist."""
627 self._lookup(key)
628 self._toc[key] = self._append_message(message)
629 self._pending = True
630
631 def iterkeys(self):
632 """Return an iterator over keys."""
633 self._lookup()
634 for key in self._toc.keys():
635 yield key
636
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000637 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000638 """Return True if the keyed message exists, False otherwise."""
639 self._lookup()
640 return key in self._toc
641
642 def __len__(self):
643 """Return a count of messages in the mailbox."""
644 self._lookup()
645 return len(self._toc)
646
647 def lock(self):
648 """Lock the mailbox."""
649 if not self._locked:
650 _lock_file(self._file)
651 self._locked = True
652
653 def unlock(self):
654 """Unlock the mailbox if it is locked."""
655 if self._locked:
656 _unlock_file(self._file)
657 self._locked = False
658
659 def flush(self):
660 """Write any pending changes to disk."""
661 if not self._pending:
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300662 if self._pending_sync:
663 # Messages have only been added, so syncing the file
664 # is enough.
665 _sync_flush(self._file)
666 self._pending_sync = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000667 return
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000668
669 # In order to be writing anything out at all, self._toc must
670 # already have been generated (and presumably has been modified
671 # by adding or deleting an item).
672 assert self._toc is not None
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000673
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000674 # Check length of self._file; if it's changed, some other process
675 # has modified the mailbox since we scanned it.
676 self._file.seek(0, 2)
677 cur_len = self._file.tell()
678 if cur_len != self._file_length:
679 raise ExternalClashError('Size of mailbox file changed '
680 '(expected %i, found %i)' %
681 (self._file_length, cur_len))
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000682
Thomas Wouters477c8d52006-05-27 19:21:47 +0000683 new_file = _create_temporary(self._path)
684 try:
685 new_toc = {}
686 self._pre_mailbox_hook(new_file)
687 for key in sorted(self._toc.keys()):
688 start, stop = self._toc[key]
689 self._file.seek(start)
690 self._pre_message_hook(new_file)
691 new_start = new_file.tell()
692 while True:
693 buffer = self._file.read(min(4096,
694 stop - self._file.tell()))
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000695 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000696 break
697 new_file.write(buffer)
698 new_toc[key] = (new_start, new_file.tell())
699 self._post_message_hook(new_file)
Petri Lehtinen02653f12012-06-15 20:50:51 +0300700 self._file_length = new_file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000701 except:
702 new_file.close()
703 os.remove(new_file.name)
704 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000705 _sync_close(new_file)
706 # self._file is about to get replaced, so no need to sync.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000707 self._file.close()
Petri Lehtinen5b5619f2012-06-29 15:09:12 +0300708 # Make sure the new file's mode is the same as the old file's
709 mode = os.stat(self._path).st_mode
710 os.chmod(new_file.name, mode)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000711 try:
712 os.rename(new_file.name, self._path)
Guido van Rossumb940e112007-01-10 16:19:56 +0000713 except OSError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000714 if e.errno == errno.EEXIST or \
715 (os.name == 'os2' and e.errno == errno.EACCES):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000716 os.remove(self._path)
717 os.rename(new_file.name, self._path)
718 else:
719 raise
720 self._file = open(self._path, 'rb+')
721 self._toc = new_toc
722 self._pending = False
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300723 self._pending_sync = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000724 if self._locked:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000725 _lock_file(self._file, dotlock=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000726
727 def _pre_mailbox_hook(self, f):
728 """Called before writing the mailbox to file f."""
729 return
730
731 def _pre_message_hook(self, f):
732 """Called before writing each message to file f."""
733 return
734
735 def _post_message_hook(self, f):
736 """Called after writing each message to file f."""
737 return
738
739 def close(self):
740 """Flush and close the mailbox."""
741 self.flush()
742 if self._locked:
743 self.unlock()
Thomas Wouters89f507f2006-12-13 04:49:30 +0000744 self._file.close() # Sync has been done by self.flush() above.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000745
746 def _lookup(self, key=None):
747 """Return (start, stop) or raise KeyError."""
748 if self._toc is None:
749 self._generate_toc()
750 if key is not None:
751 try:
752 return self._toc[key]
753 except KeyError:
754 raise KeyError('No message with key: %s' % key)
755
756 def _append_message(self, message):
757 """Append message to mailbox and return (start, stop) offsets."""
758 self._file.seek(0, 2)
R. David Murrayfc141142011-02-11 22:47:17 +0000759 before = self._file.tell()
Petri Lehtinenb6ee3d62012-06-29 13:43:37 +0300760 if len(self._toc) == 0 and not self._pending:
761 # This is the first message, and the _pre_mailbox_hook
762 # hasn't yet been called. If self._pending is True,
763 # messages have been removed, so _pre_mailbox_hook must
764 # have been called already.
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300765 self._pre_mailbox_hook(self._file)
R. David Murrayfc141142011-02-11 22:47:17 +0000766 try:
767 self._pre_message_hook(self._file)
768 offsets = self._install_message(message)
769 self._post_message_hook(self._file)
770 except BaseException:
771 self._file.truncate(before)
772 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000773 self._file.flush()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000774 self._file_length = self._file.tell() # Record current length of mailbox
Thomas Wouters477c8d52006-05-27 19:21:47 +0000775 return offsets
776
777
778
779class _mboxMMDF(_singlefileMailbox):
780 """An mbox or MMDF mailbox."""
781
782 _mangle_from_ = True
783
784 def get_message(self, key):
785 """Return a Message representation or raise a KeyError."""
786 start, stop = self._lookup(key)
787 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +0000788 from_line = self._file.readline().replace(linesep, b'')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000789 string = self._file.read(stop - self._file.tell())
R. David Murrayb7deff12011-01-30 06:21:28 +0000790 msg = self._message_factory(string.replace(linesep, b'\n'))
791 msg.set_from(from_line[5:].decode('ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000792 return msg
793
794 def get_string(self, key, from_=False):
795 """Return a string representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000796 return email.message_from_bytes(
797 self.get_bytes(key)).as_string(unixfrom=from_)
798
799 def get_bytes(self, key, from_=False):
800 """Return a string representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +0000801 start, stop = self._lookup(key)
802 self._file.seek(start)
803 if not from_:
804 self._file.readline()
805 string = self._file.read(stop - self._file.tell())
R. David Murrayb7deff12011-01-30 06:21:28 +0000806 return string.replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000807
808 def get_file(self, key, from_=False):
809 """Return a file-like representation or raise a KeyError."""
810 start, stop = self._lookup(key)
811 self._file.seek(start)
812 if not from_:
813 self._file.readline()
814 return _PartialFile(self._file, self._file.tell(), stop)
815
816 def _install_message(self, message):
817 """Format a message and blindly write to self._file."""
818 from_line = None
R. David Murrayb7deff12011-01-30 06:21:28 +0000819 if isinstance(message, str):
820 message = self._string_to_bytes(message)
821 if isinstance(message, bytes) and message.startswith(b'From '):
822 newline = message.find(b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000823 if newline != -1:
824 from_line = message[:newline]
825 message = message[newline + 1:]
826 else:
827 from_line = message
R. David Murrayb7deff12011-01-30 06:21:28 +0000828 message = b''
Thomas Wouters477c8d52006-05-27 19:21:47 +0000829 elif isinstance(message, _mboxMMDFMessage):
R. David Murrayb7deff12011-01-30 06:21:28 +0000830 author = message.get_from().encode('ascii')
831 from_line = b'From ' + author
Thomas Woutersb2137042007-02-01 18:02:27 +0000832 elif isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000833 from_line = message.get_unixfrom() # May be None.
R. David Murrayb7deff12011-01-30 06:21:28 +0000834 if from_line is not None:
835 from_line = from_line.encode('ascii')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000836 if from_line is None:
R. David Murrayb7deff12011-01-30 06:21:28 +0000837 from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000838 start = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000839 self._file.write(from_line + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000840 self._dump_message(message, self._file, self._mangle_from_)
841 stop = self._file.tell()
842 return (start, stop)
843
844
845class mbox(_mboxMMDF):
846 """A classic mbox mailbox."""
847
848 _mangle_from_ = True
849
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300850 # All messages must end in a newline character, and
851 # _post_message_hooks outputs an empty line between messages.
852 _append_newline = True
853
Thomas Wouters477c8d52006-05-27 19:21:47 +0000854 def __init__(self, path, factory=None, create=True):
855 """Initialize an mbox mailbox."""
856 self._message_factory = mboxMessage
857 _mboxMMDF.__init__(self, path, factory, create)
858
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300859 def _post_message_hook(self, f):
860 """Called after writing each message to file f."""
861 f.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000862
863 def _generate_toc(self):
864 """Generate key-to-(start, stop) table of contents."""
865 starts, stops = [], []
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300866 last_was_empty = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000867 self._file.seek(0)
868 while True:
869 line_pos = self._file.tell()
870 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +0000871 if line.startswith(b'From '):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000872 if len(stops) < len(starts):
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300873 if last_was_empty:
874 stops.append(line_pos - len(linesep))
875 else:
876 # The last line before the "From " line wasn't
877 # blank, but we consider it a start of a
878 # message anyway.
879 stops.append(line_pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000880 starts.append(line_pos)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300881 last_was_empty = False
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000882 elif not line:
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300883 if last_was_empty:
884 stops.append(line_pos - len(linesep))
885 else:
886 stops.append(line_pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000887 break
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300888 elif line == linesep:
889 last_was_empty = True
890 else:
891 last_was_empty = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000892 self._toc = dict(enumerate(zip(starts, stops)))
893 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000894 self._file_length = self._file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000895
896
897class MMDF(_mboxMMDF):
898 """An MMDF mailbox."""
899
900 def __init__(self, path, factory=None, create=True):
901 """Initialize an MMDF mailbox."""
902 self._message_factory = MMDFMessage
903 _mboxMMDF.__init__(self, path, factory, create)
904
905 def _pre_message_hook(self, f):
906 """Called before writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000907 f.write(b'\001\001\001\001' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000908
909 def _post_message_hook(self, f):
910 """Called after writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000911 f.write(linesep + b'\001\001\001\001' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000912
913 def _generate_toc(self):
914 """Generate key-to-(start, stop) table of contents."""
915 starts, stops = [], []
916 self._file.seek(0)
917 next_pos = 0
918 while True:
919 line_pos = next_pos
920 line = self._file.readline()
921 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000922 if line.startswith(b'\001\001\001\001' + linesep):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000923 starts.append(next_pos)
924 while True:
925 line_pos = next_pos
926 line = self._file.readline()
927 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000928 if line == b'\001\001\001\001' + linesep:
929 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000930 break
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000931 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000932 stops.append(line_pos)
933 break
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000934 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000935 break
936 self._toc = dict(enumerate(zip(starts, stops)))
937 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000938 self._file.seek(0, 2)
939 self._file_length = self._file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000940
941
942class MH(Mailbox):
943 """An MH mailbox."""
944
945 def __init__(self, path, factory=None, create=True):
946 """Initialize an MH instance."""
947 Mailbox.__init__(self, path, factory, create)
948 if not os.path.exists(self._path):
949 if create:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000950 os.mkdir(self._path, 0o700)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000951 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000952 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000953 else:
954 raise NoSuchMailboxError(self._path)
955 self._locked = False
956
957 def add(self, message):
958 """Add message and return assigned key."""
959 keys = self.keys()
960 if len(keys) == 0:
961 new_key = 1
962 else:
963 new_key = max(keys) + 1
964 new_path = os.path.join(self._path, str(new_key))
965 f = _create_carefully(new_path)
R. David Murray774a66d2011-02-12 00:03:31 +0000966 closed = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000967 try:
968 if self._locked:
969 _lock_file(f)
970 try:
R. David Murrayfc141142011-02-11 22:47:17 +0000971 try:
972 self._dump_message(message, f)
973 except BaseException:
R. David Murray774a66d2011-02-12 00:03:31 +0000974 # Unlock and close so it can be deleted on Windows
975 if self._locked:
976 _unlock_file(f)
977 _sync_close(f)
978 closed = True
R. David Murrayfc141142011-02-11 22:47:17 +0000979 os.remove(new_path)
980 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000981 if isinstance(message, MHMessage):
982 self._dump_sequences(message, new_key)
983 finally:
984 if self._locked:
985 _unlock_file(f)
986 finally:
R. David Murray774a66d2011-02-12 00:03:31 +0000987 if not closed:
988 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000989 return new_key
990
991 def remove(self, key):
992 """Remove the keyed message; raise KeyError if it doesn't exist."""
993 path = os.path.join(self._path, str(key))
994 try:
995 f = open(path, 'rb+')
Guido van Rossumb940e112007-01-10 16:19:56 +0000996 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000997 if e.errno == errno.ENOENT:
998 raise KeyError('No message with key: %s' % key)
999 else:
1000 raise
Benjamin Peterson21896a32010-03-21 22:03:03 +00001001 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001002 f.close()
Benjamin Peterson21896a32010-03-21 22:03:03 +00001003 os.remove(path)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001004
1005 def __setitem__(self, key, message):
1006 """Replace the keyed message; raise KeyError if it doesn't exist."""
1007 path = os.path.join(self._path, str(key))
1008 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001009 f = open(path, 'rb+')
Guido van Rossumb940e112007-01-10 16:19:56 +00001010 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001011 if e.errno == errno.ENOENT:
1012 raise KeyError('No message with key: %s' % key)
1013 else:
1014 raise
1015 try:
1016 if self._locked:
1017 _lock_file(f)
1018 try:
1019 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
1020 self._dump_message(message, f)
1021 if isinstance(message, MHMessage):
1022 self._dump_sequences(message, key)
1023 finally:
1024 if self._locked:
1025 _unlock_file(f)
1026 finally:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001027 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001028
1029 def get_message(self, key):
1030 """Return a Message representation or raise a KeyError."""
1031 try:
1032 if self._locked:
R. David Murrayb7deff12011-01-30 06:21:28 +00001033 f = open(os.path.join(self._path, str(key)), 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001034 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001035 f = open(os.path.join(self._path, str(key)), 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +00001036 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001037 if e.errno == errno.ENOENT:
1038 raise KeyError('No message with key: %s' % key)
1039 else:
1040 raise
1041 try:
1042 if self._locked:
1043 _lock_file(f)
1044 try:
1045 msg = MHMessage(f)
1046 finally:
1047 if self._locked:
1048 _unlock_file(f)
1049 finally:
1050 f.close()
R. David Murray548ac412009-04-02 19:44:43 +00001051 for name, key_list in self.get_sequences().items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001052 if key in key_list:
1053 msg.add_sequence(name)
1054 return msg
1055
R. David Murrayb7deff12011-01-30 06:21:28 +00001056 def get_bytes(self, key):
1057 """Return a bytes representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00001058 try:
1059 if self._locked:
R. David Murrayb7deff12011-01-30 06:21:28 +00001060 f = open(os.path.join(self._path, str(key)), 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001061 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001062 f = open(os.path.join(self._path, str(key)), 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +00001063 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001064 if e.errno == errno.ENOENT:
1065 raise KeyError('No message with key: %s' % key)
1066 else:
1067 raise
1068 try:
1069 if self._locked:
1070 _lock_file(f)
1071 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001072 return f.read().replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001073 finally:
1074 if self._locked:
1075 _unlock_file(f)
1076 finally:
1077 f.close()
1078
1079 def get_file(self, key):
1080 """Return a file-like representation or raise a KeyError."""
1081 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001082 f = open(os.path.join(self._path, str(key)), 'rb')
Guido van Rossumb940e112007-01-10 16:19:56 +00001083 except IOError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001084 if e.errno == errno.ENOENT:
1085 raise KeyError('No message with key: %s' % key)
1086 else:
1087 raise
1088 return _ProxyFile(f)
1089
1090 def iterkeys(self):
1091 """Return an iterator over keys."""
1092 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1093 if entry.isdigit()))
1094
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001095 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001096 """Return True if the keyed message exists, False otherwise."""
1097 return os.path.exists(os.path.join(self._path, str(key)))
1098
1099 def __len__(self):
1100 """Return a count of messages in the mailbox."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001101 return len(list(self.keys()))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001102
1103 def lock(self):
1104 """Lock the mailbox."""
1105 if not self._locked:
1106 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
1107 _lock_file(self._file)
1108 self._locked = True
1109
1110 def unlock(self):
1111 """Unlock the mailbox if it is locked."""
1112 if self._locked:
1113 _unlock_file(self._file)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001114 _sync_close(self._file)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001115 del self._file
1116 self._locked = False
1117
1118 def flush(self):
1119 """Write any pending changes to the disk."""
1120 return
1121
1122 def close(self):
1123 """Flush and close the mailbox."""
1124 if self._locked:
1125 self.unlock()
1126
1127 def list_folders(self):
1128 """Return a list of folder names."""
1129 result = []
1130 for entry in os.listdir(self._path):
1131 if os.path.isdir(os.path.join(self._path, entry)):
1132 result.append(entry)
1133 return result
1134
1135 def get_folder(self, folder):
1136 """Return an MH instance for the named folder."""
Thomas Wouters89f507f2006-12-13 04:49:30 +00001137 return MH(os.path.join(self._path, folder),
1138 factory=self._factory, create=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001139
1140 def add_folder(self, folder):
1141 """Create a folder and return an MH instance representing it."""
Thomas Wouters89f507f2006-12-13 04:49:30 +00001142 return MH(os.path.join(self._path, folder),
1143 factory=self._factory)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001144
1145 def remove_folder(self, folder):
1146 """Delete the named folder, which must be empty."""
1147 path = os.path.join(self._path, folder)
1148 entries = os.listdir(path)
1149 if entries == ['.mh_sequences']:
1150 os.remove(os.path.join(path, '.mh_sequences'))
1151 elif entries == []:
1152 pass
1153 else:
1154 raise NotEmptyError('Folder not empty: %s' % self._path)
1155 os.rmdir(path)
1156
1157 def get_sequences(self):
1158 """Return a name-to-key-list dictionary to define each sequence."""
1159 results = {}
R. David Murrayb7deff12011-01-30 06:21:28 +00001160 f = open(os.path.join(self._path, '.mh_sequences'), 'r')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001161 try:
1162 all_keys = set(self.keys())
1163 for line in f:
1164 try:
1165 name, contents = line.split(':')
1166 keys = set()
1167 for spec in contents.split():
1168 if spec.isdigit():
1169 keys.add(int(spec))
1170 else:
1171 start, stop = (int(x) for x in spec.split('-'))
1172 keys.update(range(start, stop + 1))
1173 results[name] = [key for key in sorted(keys) \
1174 if key in all_keys]
1175 if len(results[name]) == 0:
1176 del results[name]
1177 except ValueError:
1178 raise FormatError('Invalid sequence specification: %s' %
1179 line.rstrip())
1180 finally:
1181 f.close()
1182 return results
1183
1184 def set_sequences(self, sequences):
1185 """Set sequences using the given name-to-key-list dictionary."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001186 f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001187 try:
1188 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001189 for name, keys in sequences.items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001190 if len(keys) == 0:
1191 continue
R. David Murrayb7deff12011-01-30 06:21:28 +00001192 f.write(name + ':')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193 prev = None
1194 completing = False
1195 for key in sorted(set(keys)):
1196 if key - 1 == prev:
1197 if not completing:
1198 completing = True
1199 f.write('-')
1200 elif completing:
1201 completing = False
1202 f.write('%s %s' % (prev, key))
1203 else:
1204 f.write(' %s' % key)
1205 prev = key
1206 if completing:
1207 f.write(str(prev) + '\n')
1208 else:
1209 f.write('\n')
1210 finally:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001211 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001212
1213 def pack(self):
1214 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1215 sequences = self.get_sequences()
1216 prev = 0
1217 changes = []
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001218 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001219 if key - 1 != prev:
1220 changes.append((key, prev + 1))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001221 if hasattr(os, 'link'):
1222 os.link(os.path.join(self._path, str(key)),
1223 os.path.join(self._path, str(prev + 1)))
1224 os.unlink(os.path.join(self._path, str(key)))
1225 else:
1226 os.rename(os.path.join(self._path, str(key)),
1227 os.path.join(self._path, str(prev + 1)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001228 prev += 1
1229 self._next_key = prev + 1
1230 if len(changes) == 0:
1231 return
1232 for name, key_list in sequences.items():
1233 for old, new in changes:
1234 if old in key_list:
1235 key_list[key_list.index(old)] = new
1236 self.set_sequences(sequences)
1237
1238 def _dump_sequences(self, message, key):
1239 """Inspect a new MHMessage and update sequences appropriately."""
1240 pending_sequences = message.get_sequences()
1241 all_sequences = self.get_sequences()
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001242 for name, key_list in all_sequences.items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001243 if name in pending_sequences:
1244 key_list.append(key)
1245 elif key in key_list:
1246 del key_list[key_list.index(key)]
1247 for sequence in pending_sequences:
1248 if sequence not in all_sequences:
1249 all_sequences[sequence] = [key]
1250 self.set_sequences(all_sequences)
1251
1252
1253class Babyl(_singlefileMailbox):
1254 """An Rmail-style Babyl mailbox."""
1255
1256 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1257 'forwarded', 'edited', 'resent'))
1258
1259 def __init__(self, path, factory=None, create=True):
1260 """Initialize a Babyl mailbox."""
1261 _singlefileMailbox.__init__(self, path, factory, create)
1262 self._labels = {}
1263
1264 def add(self, message):
1265 """Add message and return assigned key."""
1266 key = _singlefileMailbox.add(self, message)
1267 if isinstance(message, BabylMessage):
1268 self._labels[key] = message.get_labels()
1269 return key
1270
1271 def remove(self, key):
1272 """Remove the keyed message; raise KeyError if it doesn't exist."""
1273 _singlefileMailbox.remove(self, key)
1274 if key in self._labels:
1275 del self._labels[key]
1276
1277 def __setitem__(self, key, message):
1278 """Replace the keyed message; raise KeyError if it doesn't exist."""
1279 _singlefileMailbox.__setitem__(self, key, message)
1280 if isinstance(message, BabylMessage):
1281 self._labels[key] = message.get_labels()
1282
1283 def get_message(self, key):
1284 """Return a Message representation or raise a KeyError."""
1285 start, stop = self._lookup(key)
1286 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +00001287 self._file.readline() # Skip b'1,' line specifying labels.
1288 original_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001289 while True:
1290 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001291 if line == b'*** EOOH ***' + linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001292 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001293 original_headers.write(line.replace(linesep, b'\n'))
1294 visible_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001295 while True:
1296 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001297 if line == linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001298 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001299 visible_headers.write(line.replace(linesep, b'\n'))
1300 # Read up to the stop, or to the end
1301 n = stop - self._file.tell()
1302 assert n >= 0
1303 body = self._file.read(n)
1304 body = body.replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001305 msg = BabylMessage(original_headers.getvalue() + body)
1306 msg.set_visible(visible_headers.getvalue())
1307 if key in self._labels:
1308 msg.set_labels(self._labels[key])
1309 return msg
1310
R. David Murrayb7deff12011-01-30 06:21:28 +00001311 def get_bytes(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001312 """Return a string representation or raise a KeyError."""
1313 start, stop = self._lookup(key)
1314 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +00001315 self._file.readline() # Skip b'1,' line specifying labels.
1316 original_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001317 while True:
1318 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001319 if line == b'*** EOOH ***' + linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001320 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001321 original_headers.write(line.replace(linesep, b'\n'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001322 while True:
1323 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001324 if line == linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001325 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001326 headers = original_headers.getvalue()
1327 n = stop - self._file.tell()
1328 assert n >= 0
1329 data = self._file.read(n)
1330 data = data.replace(linesep, b'\n')
1331 return headers + data
Thomas Wouters477c8d52006-05-27 19:21:47 +00001332
1333 def get_file(self, key):
1334 """Return a file-like representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001335 return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001336
1337 def get_labels(self):
1338 """Return a list of user-defined labels in the mailbox."""
1339 self._lookup()
1340 labels = set()
1341 for label_list in self._labels.values():
1342 labels.update(label_list)
1343 labels.difference_update(self._special_labels)
1344 return list(labels)
1345
1346 def _generate_toc(self):
1347 """Generate key-to-(start, stop) table of contents."""
1348 starts, stops = [], []
1349 self._file.seek(0)
1350 next_pos = 0
1351 label_lists = []
1352 while True:
1353 line_pos = next_pos
1354 line = self._file.readline()
1355 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +00001356 if line == b'\037\014' + linesep:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +00001358 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001359 starts.append(next_pos)
1360 labels = [label.strip() for label
R. David Murrayb7deff12011-01-30 06:21:28 +00001361 in self._file.readline()[1:].split(b',')
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001362 if label.strip()]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001363 label_lists.append(labels)
R. David Murrayb7deff12011-01-30 06:21:28 +00001364 elif line == b'\037' or line == b'\037' + linesep:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001365 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +00001366 stops.append(line_pos - len(linesep))
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001367 elif not line:
R. David Murrayb7deff12011-01-30 06:21:28 +00001368 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001369 break
1370 self._toc = dict(enumerate(zip(starts, stops)))
1371 self._labels = dict(enumerate(label_lists))
1372 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001373 self._file.seek(0, 2)
1374 self._file_length = self._file.tell()
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001375
Thomas Wouters477c8d52006-05-27 19:21:47 +00001376 def _pre_mailbox_hook(self, f):
1377 """Called before writing the mailbox to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001378 babyl = b'BABYL OPTIONS:' + linesep
1379 babyl += b'Version: 5' + linesep
1380 labels = self.get_labels()
1381 labels = (label.encode() for label in labels)
1382 babyl += b'Labels:' + b','.join(labels) + linesep
1383 babyl += b'\037'
1384 f.write(babyl)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001385
1386 def _pre_message_hook(self, f):
1387 """Called before writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001388 f.write(b'\014' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001389
1390 def _post_message_hook(self, f):
1391 """Called after writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001392 f.write(linesep + b'\037')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393
1394 def _install_message(self, message):
1395 """Write message contents and return (start, stop)."""
1396 start = self._file.tell()
1397 if isinstance(message, BabylMessage):
1398 special_labels = []
1399 labels = []
1400 for label in message.get_labels():
1401 if label in self._special_labels:
1402 special_labels.append(label)
1403 else:
1404 labels.append(label)
R. David Murrayb7deff12011-01-30 06:21:28 +00001405 self._file.write(b'1')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001406 for label in special_labels:
R. David Murrayb7deff12011-01-30 06:21:28 +00001407 self._file.write(b', ' + label.encode())
1408 self._file.write(b',,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001409 for label in labels:
R. David Murrayb7deff12011-01-30 06:21:28 +00001410 self._file.write(b' ' + label.encode() + b',')
1411 self._file.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001412 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001413 self._file.write(b'1,,' + linesep)
Thomas Woutersb2137042007-02-01 18:02:27 +00001414 if isinstance(message, email.message.Message):
R. David Murrayb7deff12011-01-30 06:21:28 +00001415 orig_buffer = io.BytesIO()
1416 orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001417 orig_generator.flatten(message)
1418 orig_buffer.seek(0)
1419 while True:
1420 line = orig_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001421 self._file.write(line.replace(b'\n', linesep))
1422 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001423 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001424 self._file.write(b'*** EOOH ***' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001425 if isinstance(message, BabylMessage):
R. David Murrayb7deff12011-01-30 06:21:28 +00001426 vis_buffer = io.BytesIO()
1427 vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001428 vis_generator.flatten(message.get_visible())
1429 while True:
1430 line = vis_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001431 self._file.write(line.replace(b'\n', linesep))
1432 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001433 break
1434 else:
1435 orig_buffer.seek(0)
1436 while True:
1437 line = orig_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001438 self._file.write(line.replace(b'\n', linesep))
1439 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440 break
1441 while True:
1442 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001443 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001444 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001445 self._file.write(buffer.replace(b'\n', linesep))
1446 elif isinstance(message, (bytes, str, io.StringIO)):
1447 if isinstance(message, io.StringIO):
1448 warnings.warn("Use of StringIO input is deprecated, "
1449 "use BytesIO instead", DeprecationWarning, 3)
1450 message = message.getvalue()
1451 if isinstance(message, str):
1452 message = self._string_to_bytes(message)
1453 body_start = message.find(b'\n\n') + 2
Thomas Wouters477c8d52006-05-27 19:21:47 +00001454 if body_start - 2 != -1:
R. David Murrayb7deff12011-01-30 06:21:28 +00001455 self._file.write(message[:body_start].replace(b'\n', linesep))
1456 self._file.write(b'*** EOOH ***' + linesep)
1457 self._file.write(message[:body_start].replace(b'\n', linesep))
1458 self._file.write(message[body_start:].replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001459 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001460 self._file.write(b'*** EOOH ***' + linesep + linesep)
1461 self._file.write(message.replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001462 elif hasattr(message, 'readline'):
R. David Murrayb7deff12011-01-30 06:21:28 +00001463 if hasattr(message, 'buffer'):
1464 warnings.warn("Use of text mode files is deprecated, "
1465 "use a binary mode file instead", DeprecationWarning, 3)
1466 message = message.buffer
Thomas Wouters477c8d52006-05-27 19:21:47 +00001467 original_pos = message.tell()
1468 first_pass = True
1469 while True:
1470 line = message.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001471 # Universal newline support.
1472 if line.endswith(b'\r\n'):
1473 line = line[:-2] + b'\n'
1474 elif line.endswith(b'\r'):
1475 line = line[:-1] + b'\n'
1476 self._file.write(line.replace(b'\n', linesep))
1477 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001478 if first_pass:
1479 first_pass = False
Petri Lehtinen3d12c432012-08-15 14:00:40 +03001480 self._file.write(b'*** EOOH ***' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001481 message.seek(original_pos)
1482 else:
1483 break
1484 while True:
Petri Lehtinen88614942012-08-16 07:22:15 +03001485 line = message.readline()
1486 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001487 break
Petri Lehtinen88614942012-08-16 07:22:15 +03001488 # Universal newline support.
1489 if line.endswith(b'\r\n'):
1490 line = line[:-2] + linesep
1491 elif line.endswith(b'\r'):
1492 line = line[:-1] + linesep
1493 elif line.endswith(b'\n'):
1494 line = line[:-1] + linesep
1495 self._file.write(line)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001496 else:
1497 raise TypeError('Invalid message type: %s' % type(message))
1498 stop = self._file.tell()
1499 return (start, stop)
1500
1501
Thomas Woutersb2137042007-02-01 18:02:27 +00001502class Message(email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001503 """Message with mailbox-format-specific properties."""
1504
1505 def __init__(self, message=None):
1506 """Initialize a Message instance."""
Thomas Woutersb2137042007-02-01 18:02:27 +00001507 if isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001508 self._become_message(copy.deepcopy(message))
1509 if isinstance(message, Message):
1510 message._explain_to(self)
R. David Murrayb7deff12011-01-30 06:21:28 +00001511 elif isinstance(message, bytes):
1512 self._become_message(email.message_from_bytes(message))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001513 elif isinstance(message, str):
1514 self._become_message(email.message_from_string(message))
R. David Murrayb7deff12011-01-30 06:21:28 +00001515 elif isinstance(message, io.TextIOWrapper):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001516 self._become_message(email.message_from_file(message))
R. David Murrayb7deff12011-01-30 06:21:28 +00001517 elif hasattr(message, "read"):
1518 self._become_message(email.message_from_binary_file(message))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001519 elif message is None:
Thomas Woutersb2137042007-02-01 18:02:27 +00001520 email.message.Message.__init__(self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001521 else:
1522 raise TypeError('Invalid message type: %s' % type(message))
1523
1524 def _become_message(self, message):
1525 """Assume the non-format-specific state of message."""
1526 for name in ('_headers', '_unixfrom', '_payload', '_charset',
1527 'preamble', 'epilogue', 'defects', '_default_type'):
1528 self.__dict__[name] = message.__dict__[name]
1529
1530 def _explain_to(self, message):
1531 """Copy format-specific state to message insofar as possible."""
1532 if isinstance(message, Message):
1533 return # There's nothing format-specific to explain.
1534 else:
1535 raise TypeError('Cannot convert to specified type')
1536
1537
1538class MaildirMessage(Message):
1539 """Message with Maildir-specific properties."""
1540
1541 def __init__(self, message=None):
1542 """Initialize a MaildirMessage instance."""
1543 self._subdir = 'new'
1544 self._info = ''
1545 self._date = time.time()
1546 Message.__init__(self, message)
1547
1548 def get_subdir(self):
1549 """Return 'new' or 'cur'."""
1550 return self._subdir
1551
1552 def set_subdir(self, subdir):
1553 """Set subdir to 'new' or 'cur'."""
1554 if subdir == 'new' or subdir == 'cur':
1555 self._subdir = subdir
1556 else:
1557 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1558
1559 def get_flags(self):
1560 """Return as a string the flags that are set."""
1561 if self._info.startswith('2,'):
1562 return self._info[2:]
1563 else:
1564 return ''
1565
1566 def set_flags(self, flags):
1567 """Set the given flags and unset all others."""
1568 self._info = '2,' + ''.join(sorted(flags))
1569
1570 def add_flag(self, flag):
1571 """Set the given flag(s) without changing others."""
1572 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1573
1574 def remove_flag(self, flag):
1575 """Unset the given string flag(s) without changing others."""
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001576 if self.get_flags():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001577 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1578
1579 def get_date(self):
1580 """Return delivery date of message, in seconds since the epoch."""
1581 return self._date
1582
1583 def set_date(self, date):
1584 """Set delivery date of message, in seconds since the epoch."""
1585 try:
1586 self._date = float(date)
1587 except ValueError:
1588 raise TypeError("can't convert to float: %s" % date)
1589
1590 def get_info(self):
1591 """Get the message's "info" as a string."""
1592 return self._info
1593
1594 def set_info(self, info):
1595 """Set the message's "info" string."""
1596 if isinstance(info, str):
1597 self._info = info
1598 else:
1599 raise TypeError('info must be a string: %s' % type(info))
1600
1601 def _explain_to(self, message):
1602 """Copy Maildir-specific state to message insofar as possible."""
1603 if isinstance(message, MaildirMessage):
1604 message.set_flags(self.get_flags())
1605 message.set_subdir(self.get_subdir())
1606 message.set_date(self.get_date())
1607 elif isinstance(message, _mboxMMDFMessage):
1608 flags = set(self.get_flags())
1609 if 'S' in flags:
1610 message.add_flag('R')
1611 if self.get_subdir() == 'cur':
1612 message.add_flag('O')
1613 if 'T' in flags:
1614 message.add_flag('D')
1615 if 'F' in flags:
1616 message.add_flag('F')
1617 if 'R' in flags:
1618 message.add_flag('A')
1619 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1620 elif isinstance(message, MHMessage):
1621 flags = set(self.get_flags())
1622 if 'S' not in flags:
1623 message.add_sequence('unseen')
1624 if 'R' in flags:
1625 message.add_sequence('replied')
1626 if 'F' in flags:
1627 message.add_sequence('flagged')
1628 elif isinstance(message, BabylMessage):
1629 flags = set(self.get_flags())
1630 if 'S' not in flags:
1631 message.add_label('unseen')
1632 if 'T' in flags:
1633 message.add_label('deleted')
1634 if 'R' in flags:
1635 message.add_label('answered')
1636 if 'P' in flags:
1637 message.add_label('forwarded')
1638 elif isinstance(message, Message):
1639 pass
1640 else:
1641 raise TypeError('Cannot convert to specified type: %s' %
1642 type(message))
1643
1644
1645class _mboxMMDFMessage(Message):
1646 """Message with mbox- or MMDF-specific properties."""
1647
1648 def __init__(self, message=None):
1649 """Initialize an mboxMMDFMessage instance."""
1650 self.set_from('MAILER-DAEMON', True)
Thomas Woutersb2137042007-02-01 18:02:27 +00001651 if isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001652 unixfrom = message.get_unixfrom()
1653 if unixfrom is not None and unixfrom.startswith('From '):
1654 self.set_from(unixfrom[5:])
1655 Message.__init__(self, message)
1656
1657 def get_from(self):
1658 """Return contents of "From " line."""
1659 return self._from
1660
1661 def set_from(self, from_, time_=None):
1662 """Set "From " line, formatting and appending time_ if specified."""
1663 if time_ is not None:
1664 if time_ is True:
1665 time_ = time.gmtime()
1666 from_ += ' ' + time.asctime(time_)
1667 self._from = from_
1668
1669 def get_flags(self):
1670 """Return as a string the flags that are set."""
1671 return self.get('Status', '') + self.get('X-Status', '')
1672
1673 def set_flags(self, flags):
1674 """Set the given flags and unset all others."""
1675 flags = set(flags)
1676 status_flags, xstatus_flags = '', ''
1677 for flag in ('R', 'O'):
1678 if flag in flags:
1679 status_flags += flag
1680 flags.remove(flag)
1681 for flag in ('D', 'F', 'A'):
1682 if flag in flags:
1683 xstatus_flags += flag
1684 flags.remove(flag)
1685 xstatus_flags += ''.join(sorted(flags))
1686 try:
1687 self.replace_header('Status', status_flags)
1688 except KeyError:
1689 self.add_header('Status', status_flags)
1690 try:
1691 self.replace_header('X-Status', xstatus_flags)
1692 except KeyError:
1693 self.add_header('X-Status', xstatus_flags)
1694
1695 def add_flag(self, flag):
1696 """Set the given flag(s) without changing others."""
1697 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1698
1699 def remove_flag(self, flag):
1700 """Unset the given string flag(s) without changing others."""
1701 if 'Status' in self or 'X-Status' in self:
1702 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1703
1704 def _explain_to(self, message):
1705 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1706 if isinstance(message, MaildirMessage):
1707 flags = set(self.get_flags())
1708 if 'O' in flags:
1709 message.set_subdir('cur')
1710 if 'F' in flags:
1711 message.add_flag('F')
1712 if 'A' in flags:
1713 message.add_flag('R')
1714 if 'R' in flags:
1715 message.add_flag('S')
1716 if 'D' in flags:
1717 message.add_flag('T')
1718 del message['status']
1719 del message['x-status']
1720 maybe_date = ' '.join(self.get_from().split()[-5:])
1721 try:
1722 message.set_date(calendar.timegm(time.strptime(maybe_date,
1723 '%a %b %d %H:%M:%S %Y')))
1724 except (ValueError, OverflowError):
1725 pass
1726 elif isinstance(message, _mboxMMDFMessage):
1727 message.set_flags(self.get_flags())
1728 message.set_from(self.get_from())
1729 elif isinstance(message, MHMessage):
1730 flags = set(self.get_flags())
1731 if 'R' not in flags:
1732 message.add_sequence('unseen')
1733 if 'A' in flags:
1734 message.add_sequence('replied')
1735 if 'F' in flags:
1736 message.add_sequence('flagged')
1737 del message['status']
1738 del message['x-status']
1739 elif isinstance(message, BabylMessage):
1740 flags = set(self.get_flags())
1741 if 'R' not in flags:
1742 message.add_label('unseen')
1743 if 'D' in flags:
1744 message.add_label('deleted')
1745 if 'A' in flags:
1746 message.add_label('answered')
1747 del message['status']
1748 del message['x-status']
1749 elif isinstance(message, Message):
1750 pass
1751 else:
1752 raise TypeError('Cannot convert to specified type: %s' %
1753 type(message))
1754
1755
1756class mboxMessage(_mboxMMDFMessage):
1757 """Message with mbox-specific properties."""
1758
1759
1760class MHMessage(Message):
1761 """Message with MH-specific properties."""
1762
1763 def __init__(self, message=None):
1764 """Initialize an MHMessage instance."""
1765 self._sequences = []
1766 Message.__init__(self, message)
1767
1768 def get_sequences(self):
1769 """Return a list of sequences that include the message."""
1770 return self._sequences[:]
1771
1772 def set_sequences(self, sequences):
1773 """Set the list of sequences that include the message."""
1774 self._sequences = list(sequences)
1775
1776 def add_sequence(self, sequence):
1777 """Add sequence to list of sequences including the message."""
1778 if isinstance(sequence, str):
1779 if not sequence in self._sequences:
1780 self._sequences.append(sequence)
1781 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001782 raise TypeError('sequence type must be str: %s' % type(sequence))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001783
1784 def remove_sequence(self, sequence):
1785 """Remove sequence from the list of sequences including the message."""
1786 try:
1787 self._sequences.remove(sequence)
1788 except ValueError:
1789 pass
1790
1791 def _explain_to(self, message):
1792 """Copy MH-specific state to message insofar as possible."""
1793 if isinstance(message, MaildirMessage):
1794 sequences = set(self.get_sequences())
1795 if 'unseen' in sequences:
1796 message.set_subdir('cur')
1797 else:
1798 message.set_subdir('cur')
1799 message.add_flag('S')
1800 if 'flagged' in sequences:
1801 message.add_flag('F')
1802 if 'replied' in sequences:
1803 message.add_flag('R')
1804 elif isinstance(message, _mboxMMDFMessage):
1805 sequences = set(self.get_sequences())
1806 if 'unseen' not in sequences:
1807 message.add_flag('RO')
1808 else:
1809 message.add_flag('O')
1810 if 'flagged' in sequences:
1811 message.add_flag('F')
1812 if 'replied' in sequences:
1813 message.add_flag('A')
1814 elif isinstance(message, MHMessage):
1815 for sequence in self.get_sequences():
1816 message.add_sequence(sequence)
1817 elif isinstance(message, BabylMessage):
1818 sequences = set(self.get_sequences())
1819 if 'unseen' in sequences:
1820 message.add_label('unseen')
1821 if 'replied' in sequences:
1822 message.add_label('answered')
1823 elif isinstance(message, Message):
1824 pass
1825 else:
1826 raise TypeError('Cannot convert to specified type: %s' %
1827 type(message))
1828
1829
1830class BabylMessage(Message):
1831 """Message with Babyl-specific properties."""
1832
1833 def __init__(self, message=None):
1834 """Initialize an BabylMessage instance."""
1835 self._labels = []
1836 self._visible = Message()
1837 Message.__init__(self, message)
1838
1839 def get_labels(self):
1840 """Return a list of labels on the message."""
1841 return self._labels[:]
1842
1843 def set_labels(self, labels):
1844 """Set the list of labels on the message."""
1845 self._labels = list(labels)
1846
1847 def add_label(self, label):
1848 """Add label to list of labels on the message."""
1849 if isinstance(label, str):
1850 if label not in self._labels:
1851 self._labels.append(label)
1852 else:
1853 raise TypeError('label must be a string: %s' % type(label))
1854
1855 def remove_label(self, label):
1856 """Remove label from the list of labels on the message."""
1857 try:
1858 self._labels.remove(label)
1859 except ValueError:
1860 pass
1861
1862 def get_visible(self):
1863 """Return a Message representation of visible headers."""
1864 return Message(self._visible)
1865
1866 def set_visible(self, visible):
1867 """Set the Message representation of visible headers."""
1868 self._visible = Message(visible)
1869
1870 def update_visible(self):
1871 """Update and/or sensibly generate a set of visible headers."""
1872 for header in self._visible.keys():
1873 if header in self:
1874 self._visible.replace_header(header, self[header])
1875 else:
1876 del self._visible[header]
1877 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1878 if header in self and header not in self._visible:
1879 self._visible[header] = self[header]
1880
1881 def _explain_to(self, message):
1882 """Copy Babyl-specific state to message insofar as possible."""
1883 if isinstance(message, MaildirMessage):
1884 labels = set(self.get_labels())
1885 if 'unseen' in labels:
1886 message.set_subdir('cur')
1887 else:
1888 message.set_subdir('cur')
1889 message.add_flag('S')
1890 if 'forwarded' in labels or 'resent' in labels:
1891 message.add_flag('P')
1892 if 'answered' in labels:
1893 message.add_flag('R')
1894 if 'deleted' in labels:
1895 message.add_flag('T')
1896 elif isinstance(message, _mboxMMDFMessage):
1897 labels = set(self.get_labels())
1898 if 'unseen' not in labels:
1899 message.add_flag('RO')
1900 else:
1901 message.add_flag('O')
1902 if 'deleted' in labels:
1903 message.add_flag('D')
1904 if 'answered' in labels:
1905 message.add_flag('A')
1906 elif isinstance(message, MHMessage):
1907 labels = set(self.get_labels())
1908 if 'unseen' in labels:
1909 message.add_sequence('unseen')
1910 if 'answered' in labels:
1911 message.add_sequence('replied')
1912 elif isinstance(message, BabylMessage):
1913 message.set_visible(self.get_visible())
1914 for label in self.get_labels():
1915 message.add_label(label)
1916 elif isinstance(message, Message):
1917 pass
1918 else:
1919 raise TypeError('Cannot convert to specified type: %s' %
1920 type(message))
1921
1922
1923class MMDFMessage(_mboxMMDFMessage):
1924 """Message with MMDF-specific properties."""
1925
1926
1927class _ProxyFile:
1928 """A read-only wrapper of a file."""
1929
1930 def __init__(self, f, pos=None):
1931 """Initialize a _ProxyFile."""
1932 self._file = f
1933 if pos is None:
1934 self._pos = f.tell()
1935 else:
1936 self._pos = pos
1937
1938 def read(self, size=None):
1939 """Read bytes."""
Guido van Rossum98297ee2007-11-06 21:34:58 +00001940 return self._read(size, self._file.read)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001941
R. David Murrayb7deff12011-01-30 06:21:28 +00001942 def read1(self, size=None):
1943 """Read bytes."""
1944 return self._read(size, self._file.read1)
1945
Thomas Wouters477c8d52006-05-27 19:21:47 +00001946 def readline(self, size=None):
1947 """Read a line."""
Guido van Rossum98297ee2007-11-06 21:34:58 +00001948 return self._read(size, self._file.readline)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001949
1950 def readlines(self, sizehint=None):
1951 """Read multiple lines."""
1952 result = []
1953 for line in self:
1954 result.append(line)
1955 if sizehint is not None:
1956 sizehint -= len(line)
1957 if sizehint <= 0:
1958 break
1959 return result
1960
1961 def __iter__(self):
1962 """Iterate over lines."""
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001963 while True:
1964 line = self.readline()
1965 if not line:
1966 raise StopIteration
1967 yield line
Thomas Wouters477c8d52006-05-27 19:21:47 +00001968
1969 def tell(self):
1970 """Return the position."""
1971 return self._pos
1972
1973 def seek(self, offset, whence=0):
1974 """Change position."""
1975 if whence == 1:
1976 self._file.seek(self._pos)
1977 self._file.seek(offset, whence)
1978 self._pos = self._file.tell()
1979
1980 def close(self):
1981 """Close the file."""
R David Murrayc88bce12011-06-17 22:24:05 -04001982 if hasattr(self, '_file'):
1983 if hasattr(self._file, 'close'):
1984 self._file.close()
1985 del self._file
Thomas Wouters477c8d52006-05-27 19:21:47 +00001986
1987 def _read(self, size, read_method):
1988 """Read size bytes using read_method."""
1989 if size is None:
1990 size = -1
1991 self._file.seek(self._pos)
1992 result = read_method(size)
1993 self._pos = self._file.tell()
1994 return result
1995
Georg Brandl6ce29fa2010-10-30 14:33:28 +00001996 def __enter__(self):
1997 """Context manager protocol support."""
1998 return self
1999
2000 def __exit__(self, *exc):
2001 self.close()
2002
R. David Murrayb7deff12011-01-30 06:21:28 +00002003 def readable(self):
2004 return self._file.readable()
2005
2006 def writable(self):
2007 return self._file.writable()
2008
2009 def seekable(self):
2010 return self._file.seekable()
2011
2012 def flush(self):
2013 return self._file.flush()
2014
2015 @property
2016 def closed(self):
R David Murrayc88bce12011-06-17 22:24:05 -04002017 if not hasattr(self, '_file'):
2018 return True
2019 if not hasattr(self._file, 'closed'):
2020 return False
R. David Murrayb7deff12011-01-30 06:21:28 +00002021 return self._file.closed
2022
Thomas Wouters477c8d52006-05-27 19:21:47 +00002023
2024class _PartialFile(_ProxyFile):
2025 """A read-only wrapper of part of a file."""
2026
2027 def __init__(self, f, start=None, stop=None):
2028 """Initialize a _PartialFile."""
2029 _ProxyFile.__init__(self, f, start)
2030 self._start = start
2031 self._stop = stop
2032
2033 def tell(self):
2034 """Return the position with respect to start."""
2035 return _ProxyFile.tell(self) - self._start
2036
2037 def seek(self, offset, whence=0):
2038 """Change position, possibly with respect to start or stop."""
2039 if whence == 0:
2040 self._pos = self._start
2041 whence = 1
2042 elif whence == 2:
2043 self._pos = self._stop
2044 whence = 1
2045 _ProxyFile.seek(self, offset, whence)
2046
2047 def _read(self, size, read_method):
2048 """Read size bytes using read_method, honoring start and stop."""
2049 remaining = self._stop - self._pos
2050 if remaining <= 0:
R. David Murrayb7deff12011-01-30 06:21:28 +00002051 return b''
Thomas Wouters477c8d52006-05-27 19:21:47 +00002052 if size is None or size < 0 or size > remaining:
2053 size = remaining
2054 return _ProxyFile._read(self, size, read_method)
2055
Georg Brandl6ce29fa2010-10-30 14:33:28 +00002056 def close(self):
2057 # do *not* close the underlying file object for partial files,
2058 # since it's global to the mailbox object
R David Murrayc88bce12011-06-17 22:24:05 -04002059 if hasattr(self, '_file'):
2060 del self._file
Georg Brandl6ce29fa2010-10-30 14:33:28 +00002061
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062
2063def _lock_file(f, dotlock=True):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002064 """Lock file f using lockf and dot locking."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00002065 dotlock_done = False
2066 try:
2067 if fcntl:
2068 try:
2069 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
Guido van Rossumb940e112007-01-10 16:19:56 +00002070 except IOError as e:
R. David Murray752b9502011-03-03 18:12:34 +00002071 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072 raise ExternalClashError('lockf: lock unavailable: %s' %
2073 f.name)
2074 else:
2075 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +00002076 if dotlock:
2077 try:
2078 pre_lock = _create_temporary(f.name + '.lock')
2079 pre_lock.close()
Guido van Rossumb940e112007-01-10 16:19:56 +00002080 except IOError as e:
R. David Murray752b9502011-03-03 18:12:34 +00002081 if e.errno in (errno.EACCES, errno.EROFS):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002082 return # Without write access, just skip dotlocking.
2083 else:
2084 raise
2085 try:
2086 if hasattr(os, 'link'):
2087 os.link(pre_lock.name, f.name + '.lock')
2088 dotlock_done = True
2089 os.unlink(pre_lock.name)
2090 else:
2091 os.rename(pre_lock.name, f.name + '.lock')
2092 dotlock_done = True
Guido van Rossumb940e112007-01-10 16:19:56 +00002093 except OSError as e:
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002094 if e.errno == errno.EEXIST or \
2095 (os.name == 'os2' and e.errno == errno.EACCES):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002096 os.remove(pre_lock.name)
2097 raise ExternalClashError('dot lock unavailable: %s' %
2098 f.name)
2099 else:
2100 raise
2101 except:
2102 if fcntl:
2103 fcntl.lockf(f, fcntl.LOCK_UN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002104 if dotlock_done:
2105 os.remove(f.name + '.lock')
2106 raise
2107
2108def _unlock_file(f):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002109 """Unlock file f using lockf and dot locking."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00002110 if fcntl:
2111 fcntl.lockf(f, fcntl.LOCK_UN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002112 if os.path.exists(f.name + '.lock'):
2113 os.remove(f.name + '.lock')
2114
2115def _create_carefully(path):
2116 """Create a file if it doesn't exist and open for reading and writing."""
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00002117 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002118 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00002119 return open(path, 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00002120 finally:
2121 os.close(fd)
2122
2123def _create_temporary(path):
2124 """Create a temp file based on path and open for reading and writing."""
2125 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
2126 socket.gethostname(),
2127 os.getpid()))
2128
Thomas Wouters89f507f2006-12-13 04:49:30 +00002129def _sync_flush(f):
2130 """Ensure changes to file f are physically on disk."""
2131 f.flush()
Thomas Wouters902d6eb2007-01-09 23:18:33 +00002132 if hasattr(os, 'fsync'):
2133 os.fsync(f.fileno())
Thomas Wouters89f507f2006-12-13 04:49:30 +00002134
2135def _sync_close(f):
2136 """Close file f, ensuring all changes are physically on disk."""
2137 _sync_flush(f)
2138 f.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +00002139
Guido van Rossum62448671996-09-17 21:33:15 +00002140
Thomas Wouters477c8d52006-05-27 19:21:47 +00002141class Error(Exception):
2142 """Raised for module-specific errors."""
2143
2144class NoSuchMailboxError(Error):
2145 """The specified mailbox does not exist and won't be created."""
2146
2147class NotEmptyError(Error):
2148 """The specified mailbox is not empty and deletion was requested."""
2149
2150class ExternalClashError(Error):
2151 """Another process caused an action to fail."""
2152
2153class FormatError(Error):
2154 """A file appears to have an invalid format."""