blob: 4e42ad24063fa1fda73972717ed035a813b369a9 [file] [log] [blame]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001"""Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
Guido van Rossum62448671996-09-17 21:33:15 +00002
Thomas Wouters89f507f2006-12-13 04:49:30 +00003# Notes for authors of new mailbox subclasses:
4#
5# Remember to fsync() changes to disk before closing a modified file
6# or returning from a flush() method. See functions _sync_flush() and
7# _sync_close().
8
Jack Jansen97157791995-10-23 13:59:53 +00009import os
Thomas Wouters477c8d52006-05-27 19:21:47 +000010import time
11import calendar
12import socket
13import errno
14import copy
R. David Murrayb7deff12011-01-30 06:21:28 +000015import warnings
Thomas Wouters477c8d52006-05-27 19:21:47 +000016import email
Thomas Woutersb2137042007-02-01 18:02:27 +000017import email.message
18import email.generator
Guido van Rossum34d19282007-08-09 01:03:29 +000019import io
R David Murray05ff9902011-06-17 12:54:56 -040020import contextlib
Thomas Wouters477c8d52006-05-27 19:21:47 +000021try:
Thomas Wouters0e3f5912006-08-11 14:57:12 +000022 import fcntl
Brett Cannoncd171c82013-07-04 17:43:24 -040023except ImportError:
Thomas Wouters477c8d52006-05-27 19:21:47 +000024 fcntl = None
Guido van Rossumc7b68821994-04-28 09:53:33 +000025
Thomas Wouters477c8d52006-05-27 19:21:47 +000026__all__ = [ 'Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
27 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
Benjamin Peterson8041d472008-05-11 16:17:24 +000028 'BabylMessage', 'MMDFMessage']
Thomas Wouters477c8d52006-05-27 19:21:47 +000029
R. David Murrayb7deff12011-01-30 06:21:28 +000030linesep = os.linesep.encode('ascii')
31
Thomas Wouters477c8d52006-05-27 19:21:47 +000032class Mailbox:
33 """A group of messages in a particular place."""
34
35 def __init__(self, path, factory=None, create=True):
36 """Initialize a Mailbox instance."""
37 self._path = os.path.abspath(os.path.expanduser(path))
38 self._factory = factory
39
40 def add(self, message):
41 """Add message and return assigned key."""
42 raise NotImplementedError('Method must be implemented by subclass')
43
44 def remove(self, key):
45 """Remove the keyed message; raise KeyError if it doesn't exist."""
46 raise NotImplementedError('Method must be implemented by subclass')
47
48 def __delitem__(self, key):
49 self.remove(key)
50
51 def discard(self, key):
52 """If the keyed message exists, remove it."""
53 try:
54 self.remove(key)
55 except KeyError:
56 pass
57
58 def __setitem__(self, key, message):
59 """Replace the keyed message; raise KeyError if it doesn't exist."""
60 raise NotImplementedError('Method must be implemented by subclass')
61
62 def get(self, key, default=None):
63 """Return the keyed message, or default if it doesn't exist."""
64 try:
65 return self.__getitem__(key)
66 except KeyError:
67 return default
68
69 def __getitem__(self, key):
70 """Return the keyed message; raise KeyError if it doesn't exist."""
71 if not self._factory:
72 return self.get_message(key)
73 else:
R David Murray05ff9902011-06-17 12:54:56 -040074 with contextlib.closing(self.get_file(key)) as file:
75 return self._factory(file)
Thomas Wouters477c8d52006-05-27 19:21:47 +000076
77 def get_message(self, key):
78 """Return a Message representation or raise a KeyError."""
79 raise NotImplementedError('Method must be implemented by subclass')
80
81 def get_string(self, key):
R. David Murrayb7deff12011-01-30 06:21:28 +000082 """Return a string representation or raise a KeyError.
83
84 Uses email.message.Message to create a 7bit clean string
85 representation of the message."""
86 return email.message_from_bytes(self.get_bytes(key)).as_string()
87
88 def get_bytes(self, key):
89 """Return a byte string representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +000090 raise NotImplementedError('Method must be implemented by subclass')
91
92 def get_file(self, key):
93 """Return a file-like representation or raise a KeyError."""
94 raise NotImplementedError('Method must be implemented by subclass')
95
96 def iterkeys(self):
97 """Return an iterator over keys."""
98 raise NotImplementedError('Method must be implemented by subclass')
99
100 def keys(self):
101 """Return a list of keys."""
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000102 return list(self.iterkeys())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000103
104 def itervalues(self):
105 """Return an iterator over all messages."""
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +0300106 for key in self.iterkeys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000107 try:
108 value = self[key]
109 except KeyError:
110 continue
111 yield value
112
113 def __iter__(self):
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000114 return self.itervalues()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000115
116 def values(self):
117 """Return a list of messages. Memory intensive."""
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000118 return list(self.itervalues())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000119
120 def iteritems(self):
121 """Return an iterator over (key, message) tuples."""
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +0300122 for key in self.iterkeys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000123 try:
124 value = self[key]
125 except KeyError:
126 continue
127 yield (key, value)
128
129 def items(self):
130 """Return a list of (key, message) tuples. Memory intensive."""
Guido van Rossumdde4c2c2007-02-12 00:22:55 +0000131 return list(self.iteritems())
Thomas Wouters477c8d52006-05-27 19:21:47 +0000132
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000133 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000134 """Return True if the keyed message exists, False otherwise."""
135 raise NotImplementedError('Method must be implemented by subclass')
136
Thomas Wouters477c8d52006-05-27 19:21:47 +0000137 def __len__(self):
138 """Return a count of messages in the mailbox."""
139 raise NotImplementedError('Method must be implemented by subclass')
140
141 def clear(self):
142 """Delete all messages."""
Guido van Rossumcc2b0162007-02-11 06:12:03 +0000143 for key in self.keys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000144 self.discard(key)
145
146 def pop(self, key, default=None):
147 """Delete the keyed message and return it, or default."""
148 try:
149 result = self[key]
150 except KeyError:
151 return default
152 self.discard(key)
153 return result
154
155 def popitem(self):
156 """Delete an arbitrary (key, message) pair and return it."""
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +0300157 for key in self.iterkeys():
Thomas Wouters477c8d52006-05-27 19:21:47 +0000158 return (key, self.pop(key)) # This is only run once.
159 else:
160 raise KeyError('No messages in mailbox')
161
162 def update(self, arg=None):
163 """Change the messages that correspond to certain keys."""
164 if hasattr(arg, 'iteritems'):
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +0300165 source = arg.iteritems()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000166 elif hasattr(arg, 'items'):
167 source = arg.items()
168 else:
169 source = arg
170 bad_key = False
171 for key, message in source:
172 try:
173 self[key] = message
174 except KeyError:
175 bad_key = True
176 if bad_key:
177 raise KeyError('No message with key(s)')
178
179 def flush(self):
180 """Write any pending changes to the disk."""
181 raise NotImplementedError('Method must be implemented by subclass')
182
183 def lock(self):
184 """Lock the mailbox."""
185 raise NotImplementedError('Method must be implemented by subclass')
186
187 def unlock(self):
188 """Unlock the mailbox if it is locked."""
189 raise NotImplementedError('Method must be implemented by subclass')
190
191 def close(self):
192 """Flush and close the mailbox."""
193 raise NotImplementedError('Method must be implemented by subclass')
194
R. David Murrayb7deff12011-01-30 06:21:28 +0000195 def _string_to_bytes(self, message):
196 # If a message is not 7bit clean, we refuse to handle it since it
197 # likely came from reading invalid messages in text mode, and that way
198 # lies mojibake.
199 try:
200 return message.encode('ascii')
201 except UnicodeError:
202 raise ValueError("String input must be ASCII-only; "
203 "use bytes or a Message instead")
204
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300205 # Whether each message must end in a newline
206 _append_newline = False
207
Thomas Wouters477c8d52006-05-27 19:21:47 +0000208 def _dump_message(self, message, target, mangle_from_=False):
R. David Murrayb7deff12011-01-30 06:21:28 +0000209 # This assumes the target file is open in binary mode.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000210 """Dump message contents to target file."""
Thomas Woutersb2137042007-02-01 18:02:27 +0000211 if isinstance(message, email.message.Message):
R. David Murrayb7deff12011-01-30 06:21:28 +0000212 buffer = io.BytesIO()
213 gen = email.generator.BytesGenerator(buffer, mangle_from_, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000214 gen.flatten(message)
215 buffer.seek(0)
Guido van Rossum671117a2007-08-31 04:25:05 +0000216 data = buffer.read()
R. David Murrayb7deff12011-01-30 06:21:28 +0000217 data = data.replace(b'\n', linesep)
Guido van Rossum671117a2007-08-31 04:25:05 +0000218 target.write(data)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300219 if self._append_newline and not data.endswith(linesep):
220 # Make sure the message ends with a newline
221 target.write(linesep)
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)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300233 if self._append_newline and not message.endswith(linesep):
234 # Make sure the message ends with a newline
235 target.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000236 elif hasattr(message, 'read'):
R. David Murrayb7deff12011-01-30 06:21:28 +0000237 if hasattr(message, 'buffer'):
238 warnings.warn("Use of text mode files is deprecated, "
239 "use a binary mode file instead", DeprecationWarning, 3)
240 message = message.buffer
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300241 lastline = None
Thomas Wouters477c8d52006-05-27 19:21:47 +0000242 while True:
243 line = message.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +0000244 # Universal newline support.
245 if line.endswith(b'\r\n'):
246 line = line[:-2] + b'\n'
247 elif line.endswith(b'\r'):
248 line = line[:-1] + b'\n'
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000249 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000250 break
R. David Murrayb7deff12011-01-30 06:21:28 +0000251 if mangle_from_ and line.startswith(b'From '):
252 line = b'>From ' + line[5:]
253 line = line.replace(b'\n', linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000254 target.write(line)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300255 lastline = line
256 if self._append_newline and lastline and not lastline.endswith(linesep):
257 # Make sure the message ends with a newline
258 target.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000259 else:
260 raise TypeError('Invalid message type: %s' % type(message))
261
262
263class Maildir(Mailbox):
264 """A qmail-style Maildir mailbox."""
265
266 colon = ':'
267
Georg Brandlaa5b4112008-05-11 20:51:18 +0000268 def __init__(self, dirname, factory=None, create=True):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000269 """Initialize a Maildir instance."""
270 Mailbox.__init__(self, dirname, factory, create)
R David Murraycaed7fe2011-05-06 22:07:19 -0400271 self._paths = {
272 'tmp': os.path.join(self._path, 'tmp'),
273 'new': os.path.join(self._path, 'new'),
274 'cur': os.path.join(self._path, 'cur'),
275 }
Thomas Wouters477c8d52006-05-27 19:21:47 +0000276 if not os.path.exists(self._path):
277 if create:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000278 os.mkdir(self._path, 0o700)
R David Murraycaed7fe2011-05-06 22:07:19 -0400279 for path in self._paths.values():
280 os.mkdir(path, 0o700)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000281 else:
282 raise NoSuchMailboxError(self._path)
283 self._toc = {}
Petri Lehtinen8c482ee2011-11-05 09:44:59 +0200284 self._toc_mtimes = {'cur': 0, 'new': 0}
285 self._last_read = 0 # Records last time we read cur/new
286 self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
Thomas Wouters477c8d52006-05-27 19:21:47 +0000287
288 def add(self, message):
289 """Add message and return assigned key."""
290 tmp_file = self._create_tmp()
291 try:
292 self._dump_message(message, tmp_file)
R. David Murrayfc141142011-02-11 22:47:17 +0000293 except BaseException:
294 tmp_file.close()
295 os.remove(tmp_file.name)
296 raise
297 _sync_close(tmp_file)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000298 if isinstance(message, MaildirMessage):
299 subdir = message.get_subdir()
300 suffix = self.colon + message.get_info()
301 if suffix == self.colon:
302 suffix = ''
303 else:
304 subdir = 'new'
305 suffix = ''
306 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
307 dest = os.path.join(self._path, subdir, uniq + suffix)
R David Murray41a22f12013-09-18 08:34:40 -0400308 if isinstance(message, MaildirMessage):
309 os.utime(tmp_file.name,
310 (os.path.getatime(tmp_file.name), message.get_date()))
311 # No file modification should be done after the file is moved to its
312 # final position in order to prevent race conditions with changes
313 # from other programs
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 return uniq
328
329 def remove(self, key):
330 """Remove the keyed message; raise KeyError if it doesn't exist."""
331 os.remove(os.path.join(self._path, self._lookup(key)))
332
333 def discard(self, key):
334 """If the keyed message exists, remove it."""
335 # This overrides an inapplicable implementation in the superclass.
336 try:
337 self.remove(key)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100338 except (KeyError, FileNotFoundError):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000339 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000340
341 def __setitem__(self, key, message):
342 """Replace the keyed message; raise KeyError if it doesn't exist."""
343 old_subpath = self._lookup(key)
344 temp_key = self.add(message)
345 temp_subpath = self._lookup(temp_key)
346 if isinstance(message, MaildirMessage):
347 # temp's subdir and suffix were specified by message.
348 dominant_subpath = temp_subpath
349 else:
350 # temp's subdir and suffix were defaults from add().
351 dominant_subpath = old_subpath
352 subdir = os.path.dirname(dominant_subpath)
353 if self.colon in dominant_subpath:
354 suffix = self.colon + dominant_subpath.split(self.colon)[-1]
355 else:
356 suffix = ''
357 self.discard(key)
R David Murray41a22f12013-09-18 08:34:40 -0400358 tmp_path = os.path.join(self._path, temp_subpath)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000359 new_path = os.path.join(self._path, subdir, key + suffix)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000360 if isinstance(message, MaildirMessage):
R David Murray41a22f12013-09-18 08:34:40 -0400361 os.utime(tmp_path,
362 (os.path.getatime(tmp_path), message.get_date()))
363 # No file modification should be done after the file is moved to its
364 # final position in order to prevent race conditions with changes
365 # from other programs
366 os.rename(tmp_path, new_path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000367
368 def get_message(self, key):
369 """Return a Message representation or raise a KeyError."""
370 subpath = self._lookup(key)
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +0100371 with open(os.path.join(self._path, subpath), 'rb') as f:
Christian Heimesfdab48e2008-01-20 09:06:41 +0000372 if self._factory:
373 msg = self._factory(f)
374 else:
375 msg = MaildirMessage(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000376 subdir, name = os.path.split(subpath)
377 msg.set_subdir(subdir)
378 if self.colon in name:
379 msg.set_info(name.split(self.colon)[-1])
380 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
381 return msg
382
R. David Murrayb7deff12011-01-30 06:21:28 +0000383 def get_bytes(self, key):
384 """Return a bytes representation or raise a KeyError."""
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +0100385 with open(os.path.join(self._path, self._lookup(key)), 'rb') as f:
R. David Murrayb7deff12011-01-30 06:21:28 +0000386 return f.read().replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000387
388 def get_file(self, key):
389 """Return a file-like representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000390 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000391 return _ProxyFile(f)
392
393 def iterkeys(self):
394 """Return an iterator over keys."""
395 self._refresh()
396 for key in self._toc:
397 try:
398 self._lookup(key)
399 except KeyError:
400 continue
401 yield key
402
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000403 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000404 """Return True if the keyed message exists, False otherwise."""
405 self._refresh()
406 return key in self._toc
407
408 def __len__(self):
409 """Return a count of messages in the mailbox."""
410 self._refresh()
411 return len(self._toc)
412
413 def flush(self):
414 """Write any pending changes to disk."""
Antoine Pitrou03f13442009-11-02 11:36:51 +0000415 # Maildir changes are always written immediately, so there's nothing
R David Murraycaed7fe2011-05-06 22:07:19 -0400416 # to do.
417 pass
Thomas Wouters477c8d52006-05-27 19:21:47 +0000418
419 def lock(self):
420 """Lock the mailbox."""
421 return
422
423 def unlock(self):
424 """Unlock the mailbox if it is locked."""
425 return
426
427 def close(self):
428 """Flush and close the mailbox."""
429 return
430
431 def list_folders(self):
432 """Return a list of folder names."""
433 result = []
434 for entry in os.listdir(self._path):
435 if len(entry) > 1 and entry[0] == '.' and \
436 os.path.isdir(os.path.join(self._path, entry)):
437 result.append(entry[1:])
438 return result
439
440 def get_folder(self, folder):
441 """Return a Maildir instance for the named folder."""
Thomas Wouters89f507f2006-12-13 04:49:30 +0000442 return Maildir(os.path.join(self._path, '.' + folder),
443 factory=self._factory,
444 create=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000445
446 def add_folder(self, folder):
447 """Create a folder and return a Maildir instance representing it."""
448 path = os.path.join(self._path, '.' + folder)
Thomas Wouters89f507f2006-12-13 04:49:30 +0000449 result = Maildir(path, factory=self._factory)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000450 maildirfolder_path = os.path.join(path, 'maildirfolder')
451 if not os.path.exists(maildirfolder_path):
Georg Brandl6aa2d1f2008-08-12 08:35:52 +0000452 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
453 0o666))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000454 return result
455
456 def remove_folder(self, folder):
457 """Delete the named folder, which must be empty."""
458 path = os.path.join(self._path, '.' + folder)
459 for entry in os.listdir(os.path.join(path, 'new')) + \
460 os.listdir(os.path.join(path, 'cur')):
461 if len(entry) < 1 or entry[0] != '.':
462 raise NotEmptyError('Folder contains message(s): %s' % folder)
463 for entry in os.listdir(path):
464 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
465 os.path.isdir(os.path.join(path, entry)):
466 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
467 (folder, entry))
468 for root, dirs, files in os.walk(path, topdown=False):
469 for entry in files:
470 os.remove(os.path.join(root, entry))
471 for entry in dirs:
472 os.rmdir(os.path.join(root, entry))
473 os.rmdir(path)
474
475 def clean(self):
476 """Delete old files in "tmp"."""
477 now = time.time()
478 for entry in os.listdir(os.path.join(self._path, 'tmp')):
479 path = os.path.join(self._path, 'tmp', entry)
480 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
481 os.remove(path)
482
483 _count = 1 # This is used to generate unique file names.
484
485 def _create_tmp(self):
486 """Create a file in the tmp subdirectory and open and return it."""
487 now = time.time()
488 hostname = socket.gethostname()
489 if '/' in hostname:
490 hostname = hostname.replace('/', r'\057')
491 if ':' in hostname:
492 hostname = hostname.replace(':', r'\072')
493 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
494 Maildir._count, hostname)
495 path = os.path.join(self._path, 'tmp', uniq)
496 try:
497 os.stat(path)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100498 except FileNotFoundError:
499 Maildir._count += 1
500 try:
501 return _create_carefully(path)
502 except FileExistsError:
503 pass
Thomas Wouters89f507f2006-12-13 04:49:30 +0000504
505 # Fall through to here if stat succeeded or open raised EEXIST.
506 raise ExternalClashError('Name clash prevented file creation: %s' %
507 path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000508
509 def _refresh(self):
510 """Update table of contents mapping."""
R David Murraycaed7fe2011-05-06 22:07:19 -0400511 # If it has been less than two seconds since the last _refresh() call,
512 # we have to unconditionally re-read the mailbox just in case it has
513 # been modified, because os.path.mtime() has a 2 sec resolution in the
514 # most common worst case (FAT) and a 1 sec resolution typically. This
515 # results in a few unnecessary re-reads when _refresh() is called
516 # multiple times in that interval, but once the clock ticks over, we
517 # will only re-read as needed. Because the filesystem might be being
518 # served by an independent system with its own clock, we record and
519 # compare with the mtimes from the filesystem. Because the other
520 # system's clock might be skewing relative to our clock, we add an
521 # extra delta to our wait. The default is one tenth second, but is an
522 # instance variable and so can be adjusted if dealing with a
523 # particularly skewed or irregular system.
524 if time.time() - self._last_read > 2 + self._skewfactor:
525 refresh = False
526 for subdir in self._toc_mtimes:
527 mtime = os.path.getmtime(self._paths[subdir])
528 if mtime > self._toc_mtimes[subdir]:
529 refresh = True
530 self._toc_mtimes[subdir] = mtime
531 if not refresh:
Benjamin Petersonf6489f92009-11-25 17:46:26 +0000532 return
R David Murraycaed7fe2011-05-06 22:07:19 -0400533 # Refresh toc
Thomas Wouters477c8d52006-05-27 19:21:47 +0000534 self._toc = {}
R David Murraycaed7fe2011-05-06 22:07:19 -0400535 for subdir in self._toc_mtimes:
536 path = self._paths[subdir]
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000537 for entry in os.listdir(path):
538 p = os.path.join(path, entry)
Guido van Rossumb5a755e2007-07-18 18:15:48 +0000539 if os.path.isdir(p):
540 continue
Thomas Wouters477c8d52006-05-27 19:21:47 +0000541 uniq = entry.split(self.colon)[0]
542 self._toc[uniq] = os.path.join(subdir, entry)
R David Murraycaed7fe2011-05-06 22:07:19 -0400543 self._last_read = time.time()
Andrew M. Kuchlingfa815342009-05-03 02:52:20 +0000544
Thomas Wouters477c8d52006-05-27 19:21:47 +0000545 def _lookup(self, key):
546 """Use TOC to return subpath for given key, or raise a KeyError."""
547 try:
548 if os.path.exists(os.path.join(self._path, self._toc[key])):
549 return self._toc[key]
550 except KeyError:
551 pass
552 self._refresh()
553 try:
554 return self._toc[key]
555 except KeyError:
556 raise KeyError('No message with key: %s' % key)
557
558 # This method is for backward compatibility only.
559 def next(self):
560 """Return the next message in a one-time iteration."""
561 if not hasattr(self, '_onetime_keys'):
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +0300562 self._onetime_keys = self.iterkeys()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000563 while True:
564 try:
Georg Brandla18af4e2007-04-21 15:47:16 +0000565 return self[next(self._onetime_keys)]
Thomas Wouters477c8d52006-05-27 19:21:47 +0000566 except StopIteration:
567 return None
568 except KeyError:
569 continue
570
571
572class _singlefileMailbox(Mailbox):
573 """A single-file mailbox."""
574
575 def __init__(self, path, factory=None, create=True):
576 """Initialize a single-file mailbox."""
577 Mailbox.__init__(self, path, factory, create)
578 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000579 f = open(self._path, 'rb+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200580 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000581 if e.errno == errno.ENOENT:
582 if create:
R. David Murrayb7deff12011-01-30 06:21:28 +0000583 f = open(self._path, 'wb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000584 else:
585 raise NoSuchMailboxError(self._path)
R. David Murray752b9502011-03-03 18:12:34 +0000586 elif e.errno in (errno.EACCES, errno.EROFS):
R. David Murrayb7deff12011-01-30 06:21:28 +0000587 f = open(self._path, 'rb')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000588 else:
589 raise
590 self._file = f
591 self._toc = None
592 self._next_key = 0
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300593 self._pending = False # No changes require rewriting the file.
594 self._pending_sync = False # No need to sync the file
Thomas Wouters477c8d52006-05-27 19:21:47 +0000595 self._locked = False
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300596 self._file_length = None # Used to record mailbox size
Thomas Wouters477c8d52006-05-27 19:21:47 +0000597
598 def add(self, message):
599 """Add message and return assigned key."""
600 self._lookup()
601 self._toc[self._next_key] = self._append_message(message)
602 self._next_key += 1
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300603 # _append_message appends the message to the mailbox file. We
604 # don't need a full rewrite + rename, sync is enough.
605 self._pending_sync = True
Thomas Wouters477c8d52006-05-27 19:21:47 +0000606 return self._next_key - 1
607
608 def remove(self, key):
609 """Remove the keyed message; raise KeyError if it doesn't exist."""
610 self._lookup(key)
611 del self._toc[key]
612 self._pending = True
613
614 def __setitem__(self, key, message):
615 """Replace the keyed message; raise KeyError if it doesn't exist."""
616 self._lookup(key)
617 self._toc[key] = self._append_message(message)
618 self._pending = True
619
620 def iterkeys(self):
621 """Return an iterator over keys."""
622 self._lookup()
Philip Jenvey4993cc02012-10-01 12:53:43 -0700623 yield from self._toc.keys()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000624
Guido van Rossume2b70bc2006-08-18 22:13:04 +0000625 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000626 """Return True if the keyed message exists, False otherwise."""
627 self._lookup()
628 return key in self._toc
629
630 def __len__(self):
631 """Return a count of messages in the mailbox."""
632 self._lookup()
633 return len(self._toc)
634
635 def lock(self):
636 """Lock the mailbox."""
637 if not self._locked:
638 _lock_file(self._file)
639 self._locked = True
640
641 def unlock(self):
642 """Unlock the mailbox if it is locked."""
643 if self._locked:
644 _unlock_file(self._file)
645 self._locked = False
646
647 def flush(self):
648 """Write any pending changes to disk."""
649 if not self._pending:
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300650 if self._pending_sync:
651 # Messages have only been added, so syncing the file
652 # is enough.
653 _sync_flush(self._file)
654 self._pending_sync = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000655 return
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000656
657 # In order to be writing anything out at all, self._toc must
658 # already have been generated (and presumably has been modified
659 # by adding or deleting an item).
660 assert self._toc is not None
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000661
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000662 # Check length of self._file; if it's changed, some other process
663 # has modified the mailbox since we scanned it.
664 self._file.seek(0, 2)
665 cur_len = self._file.tell()
666 if cur_len != self._file_length:
667 raise ExternalClashError('Size of mailbox file changed '
668 '(expected %i, found %i)' %
669 (self._file_length, cur_len))
Thomas Wouters9fe394c2007-02-05 01:24:16 +0000670
Thomas Wouters477c8d52006-05-27 19:21:47 +0000671 new_file = _create_temporary(self._path)
672 try:
673 new_toc = {}
674 self._pre_mailbox_hook(new_file)
675 for key in sorted(self._toc.keys()):
676 start, stop = self._toc[key]
677 self._file.seek(start)
678 self._pre_message_hook(new_file)
679 new_start = new_file.tell()
680 while True:
681 buffer = self._file.read(min(4096,
682 stop - self._file.tell()))
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000683 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000684 break
685 new_file.write(buffer)
686 new_toc[key] = (new_start, new_file.tell())
687 self._post_message_hook(new_file)
Petri Lehtinen02653f12012-06-15 20:50:51 +0300688 self._file_length = new_file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000689 except:
690 new_file.close()
691 os.remove(new_file.name)
692 raise
Thomas Wouters89f507f2006-12-13 04:49:30 +0000693 _sync_close(new_file)
694 # self._file is about to get replaced, so no need to sync.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000695 self._file.close()
Petri Lehtinen5b5619f2012-06-29 15:09:12 +0300696 # Make sure the new file's mode is the same as the old file's
697 mode = os.stat(self._path).st_mode
698 os.chmod(new_file.name, mode)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000699 try:
700 os.rename(new_file.name, self._path)
Giampaolo Rodola'0166a282013-02-12 15:14:17 +0100701 except FileExistsError:
702 os.remove(self._path)
703 os.rename(new_file.name, self._path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000704 self._file = open(self._path, 'rb+')
705 self._toc = new_toc
706 self._pending = False
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300707 self._pending_sync = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000708 if self._locked:
Thomas Wouters89f507f2006-12-13 04:49:30 +0000709 _lock_file(self._file, dotlock=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000710
711 def _pre_mailbox_hook(self, f):
712 """Called before writing the mailbox to file f."""
713 return
714
715 def _pre_message_hook(self, f):
716 """Called before writing each message to file f."""
717 return
718
719 def _post_message_hook(self, f):
720 """Called after writing each message to file f."""
721 return
722
723 def close(self):
724 """Flush and close the mailbox."""
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300725 try:
726 self.flush()
727 finally:
728 try:
729 if self._locked:
730 self.unlock()
731 finally:
732 self._file.close() # Sync has been done by self.flush() above.
Thomas Wouters477c8d52006-05-27 19:21:47 +0000733
734 def _lookup(self, key=None):
735 """Return (start, stop) or raise KeyError."""
736 if self._toc is None:
737 self._generate_toc()
738 if key is not None:
739 try:
740 return self._toc[key]
741 except KeyError:
742 raise KeyError('No message with key: %s' % key)
743
744 def _append_message(self, message):
745 """Append message to mailbox and return (start, stop) offsets."""
746 self._file.seek(0, 2)
R. David Murrayfc141142011-02-11 22:47:17 +0000747 before = self._file.tell()
Petri Lehtinenb6ee3d62012-06-29 13:43:37 +0300748 if len(self._toc) == 0 and not self._pending:
749 # This is the first message, and the _pre_mailbox_hook
750 # hasn't yet been called. If self._pending is True,
751 # messages have been removed, so _pre_mailbox_hook must
752 # have been called already.
Petri Lehtinenf29435f2012-06-28 13:48:17 +0300753 self._pre_mailbox_hook(self._file)
R. David Murrayfc141142011-02-11 22:47:17 +0000754 try:
755 self._pre_message_hook(self._file)
756 offsets = self._install_message(message)
757 self._post_message_hook(self._file)
758 except BaseException:
759 self._file.truncate(before)
760 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000761 self._file.flush()
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000762 self._file_length = self._file.tell() # Record current length of mailbox
Thomas Wouters477c8d52006-05-27 19:21:47 +0000763 return offsets
764
765
766
767class _mboxMMDF(_singlefileMailbox):
768 """An mbox or MMDF mailbox."""
769
770 _mangle_from_ = True
771
772 def get_message(self, key):
773 """Return a Message representation or raise a KeyError."""
774 start, stop = self._lookup(key)
775 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +0000776 from_line = self._file.readline().replace(linesep, b'')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000777 string = self._file.read(stop - self._file.tell())
R. David Murrayb7deff12011-01-30 06:21:28 +0000778 msg = self._message_factory(string.replace(linesep, b'\n'))
779 msg.set_from(from_line[5:].decode('ascii'))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000780 return msg
781
782 def get_string(self, key, from_=False):
783 """Return a string representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000784 return email.message_from_bytes(
785 self.get_bytes(key)).as_string(unixfrom=from_)
786
787 def get_bytes(self, key, from_=False):
788 """Return a string representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +0000789 start, stop = self._lookup(key)
790 self._file.seek(start)
791 if not from_:
792 self._file.readline()
793 string = self._file.read(stop - self._file.tell())
R. David Murrayb7deff12011-01-30 06:21:28 +0000794 return string.replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000795
796 def get_file(self, key, from_=False):
797 """Return a file-like representation or raise a KeyError."""
798 start, stop = self._lookup(key)
799 self._file.seek(start)
800 if not from_:
801 self._file.readline()
802 return _PartialFile(self._file, self._file.tell(), stop)
803
804 def _install_message(self, message):
805 """Format a message and blindly write to self._file."""
806 from_line = None
R. David Murrayb7deff12011-01-30 06:21:28 +0000807 if isinstance(message, str):
808 message = self._string_to_bytes(message)
809 if isinstance(message, bytes) and message.startswith(b'From '):
810 newline = message.find(b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000811 if newline != -1:
812 from_line = message[:newline]
813 message = message[newline + 1:]
814 else:
815 from_line = message
R. David Murrayb7deff12011-01-30 06:21:28 +0000816 message = b''
Thomas Wouters477c8d52006-05-27 19:21:47 +0000817 elif isinstance(message, _mboxMMDFMessage):
R. David Murrayb7deff12011-01-30 06:21:28 +0000818 author = message.get_from().encode('ascii')
819 from_line = b'From ' + author
Thomas Woutersb2137042007-02-01 18:02:27 +0000820 elif isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000821 from_line = message.get_unixfrom() # May be None.
R. David Murrayb7deff12011-01-30 06:21:28 +0000822 if from_line is not None:
823 from_line = from_line.encode('ascii')
Thomas Wouters477c8d52006-05-27 19:21:47 +0000824 if from_line is None:
R. David Murrayb7deff12011-01-30 06:21:28 +0000825 from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000826 start = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000827 self._file.write(from_line + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000828 self._dump_message(message, self._file, self._mangle_from_)
829 stop = self._file.tell()
830 return (start, stop)
831
832
833class mbox(_mboxMMDF):
834 """A classic mbox mailbox."""
835
836 _mangle_from_ = True
837
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300838 # All messages must end in a newline character, and
839 # _post_message_hooks outputs an empty line between messages.
840 _append_newline = True
841
Thomas Wouters477c8d52006-05-27 19:21:47 +0000842 def __init__(self, path, factory=None, create=True):
843 """Initialize an mbox mailbox."""
844 self._message_factory = mboxMessage
845 _mboxMMDF.__init__(self, path, factory, create)
846
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300847 def _post_message_hook(self, f):
848 """Called after writing each message to file f."""
849 f.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000850
851 def _generate_toc(self):
852 """Generate key-to-(start, stop) table of contents."""
853 starts, stops = [], []
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300854 last_was_empty = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000855 self._file.seek(0)
856 while True:
857 line_pos = self._file.tell()
858 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +0000859 if line.startswith(b'From '):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000860 if len(stops) < len(starts):
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300861 if last_was_empty:
862 stops.append(line_pos - len(linesep))
863 else:
864 # The last line before the "From " line wasn't
865 # blank, but we consider it a start of a
866 # message anyway.
867 stops.append(line_pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000868 starts.append(line_pos)
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300869 last_was_empty = False
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000870 elif not line:
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300871 if last_was_empty:
872 stops.append(line_pos - len(linesep))
873 else:
874 stops.append(line_pos)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000875 break
Petri Lehtinenf39884b2012-09-25 22:00:32 +0300876 elif line == linesep:
877 last_was_empty = True
878 else:
879 last_was_empty = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000880 self._toc = dict(enumerate(zip(starts, stops)))
881 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000882 self._file_length = self._file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000883
884
885class MMDF(_mboxMMDF):
886 """An MMDF mailbox."""
887
888 def __init__(self, path, factory=None, create=True):
889 """Initialize an MMDF mailbox."""
890 self._message_factory = MMDFMessage
891 _mboxMMDF.__init__(self, path, factory, create)
892
893 def _pre_message_hook(self, f):
894 """Called before writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000895 f.write(b'\001\001\001\001' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000896
897 def _post_message_hook(self, f):
898 """Called after writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +0000899 f.write(linesep + b'\001\001\001\001' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000900
901 def _generate_toc(self):
902 """Generate key-to-(start, stop) table of contents."""
903 starts, stops = [], []
904 self._file.seek(0)
905 next_pos = 0
906 while True:
907 line_pos = next_pos
908 line = self._file.readline()
909 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000910 if line.startswith(b'\001\001\001\001' + linesep):
Thomas Wouters477c8d52006-05-27 19:21:47 +0000911 starts.append(next_pos)
912 while True:
913 line_pos = next_pos
914 line = self._file.readline()
915 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +0000916 if line == b'\001\001\001\001' + linesep:
917 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000918 break
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000919 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000920 stops.append(line_pos)
921 break
Guido van Rossum7cad4f32007-06-07 23:58:54 +0000922 elif not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000923 break
924 self._toc = dict(enumerate(zip(starts, stops)))
925 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +0000926 self._file.seek(0, 2)
927 self._file_length = self._file.tell()
Thomas Wouters477c8d52006-05-27 19:21:47 +0000928
929
930class MH(Mailbox):
931 """An MH mailbox."""
932
933 def __init__(self, path, factory=None, create=True):
934 """Initialize an MH instance."""
935 Mailbox.__init__(self, path, factory, create)
936 if not os.path.exists(self._path):
937 if create:
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000938 os.mkdir(self._path, 0o700)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000939 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
Guido van Rossumcd16bf62007-06-13 18:07:49 +0000940 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
Thomas Wouters477c8d52006-05-27 19:21:47 +0000941 else:
942 raise NoSuchMailboxError(self._path)
943 self._locked = False
944
945 def add(self, message):
946 """Add message and return assigned key."""
947 keys = self.keys()
948 if len(keys) == 0:
949 new_key = 1
950 else:
951 new_key = max(keys) + 1
952 new_path = os.path.join(self._path, str(new_key))
953 f = _create_carefully(new_path)
R. David Murray774a66d2011-02-12 00:03:31 +0000954 closed = False
Thomas Wouters477c8d52006-05-27 19:21:47 +0000955 try:
956 if self._locked:
957 _lock_file(f)
958 try:
R. David Murrayfc141142011-02-11 22:47:17 +0000959 try:
960 self._dump_message(message, f)
961 except BaseException:
R. David Murray774a66d2011-02-12 00:03:31 +0000962 # Unlock and close so it can be deleted on Windows
963 if self._locked:
964 _unlock_file(f)
965 _sync_close(f)
966 closed = True
R. David Murrayfc141142011-02-11 22:47:17 +0000967 os.remove(new_path)
968 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +0000969 if isinstance(message, MHMessage):
970 self._dump_sequences(message, new_key)
971 finally:
972 if self._locked:
973 _unlock_file(f)
974 finally:
R. David Murray774a66d2011-02-12 00:03:31 +0000975 if not closed:
976 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000977 return new_key
978
979 def remove(self, key):
980 """Remove the keyed message; raise KeyError if it doesn't exist."""
981 path = os.path.join(self._path, str(key))
982 try:
983 f = open(path, 'rb+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200984 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000985 if e.errno == errno.ENOENT:
986 raise KeyError('No message with key: %s' % key)
987 else:
988 raise
Benjamin Peterson21896a32010-03-21 22:03:03 +0000989 else:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000990 f.close()
Benjamin Peterson21896a32010-03-21 22:03:03 +0000991 os.remove(path)
Thomas Wouters477c8d52006-05-27 19:21:47 +0000992
993 def __setitem__(self, key, message):
994 """Replace the keyed message; raise KeyError if it doesn't exist."""
995 path = os.path.join(self._path, str(key))
996 try:
R. David Murrayb7deff12011-01-30 06:21:28 +0000997 f = open(path, 'rb+')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +0200998 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +0000999 if e.errno == errno.ENOENT:
1000 raise KeyError('No message with key: %s' % key)
1001 else:
1002 raise
1003 try:
1004 if self._locked:
1005 _lock_file(f)
1006 try:
1007 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
1008 self._dump_message(message, f)
1009 if isinstance(message, MHMessage):
1010 self._dump_sequences(message, key)
1011 finally:
1012 if self._locked:
1013 _unlock_file(f)
1014 finally:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001015 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001016
1017 def get_message(self, key):
1018 """Return a Message representation or raise a KeyError."""
1019 try:
1020 if self._locked:
R. David Murrayb7deff12011-01-30 06:21:28 +00001021 f = open(os.path.join(self._path, str(key)), 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001022 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001023 f = open(os.path.join(self._path, str(key)), 'rb')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001024 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001025 if e.errno == errno.ENOENT:
1026 raise KeyError('No message with key: %s' % key)
1027 else:
1028 raise
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01001029 with f:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001030 if self._locked:
1031 _lock_file(f)
1032 try:
1033 msg = MHMessage(f)
1034 finally:
1035 if self._locked:
1036 _unlock_file(f)
R. David Murray548ac412009-04-02 19:44:43 +00001037 for name, key_list in self.get_sequences().items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001038 if key in key_list:
1039 msg.add_sequence(name)
1040 return msg
1041
R. David Murrayb7deff12011-01-30 06:21:28 +00001042 def get_bytes(self, key):
1043 """Return a bytes representation or raise a KeyError."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00001044 try:
1045 if self._locked:
R. David Murrayb7deff12011-01-30 06:21:28 +00001046 f = open(os.path.join(self._path, str(key)), 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001047 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001048 f = open(os.path.join(self._path, str(key)), 'rb')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001049 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001050 if e.errno == errno.ENOENT:
1051 raise KeyError('No message with key: %s' % key)
1052 else:
1053 raise
Giampaolo Rodola'2f50aaf2013-02-12 02:04:27 +01001054 with f:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001055 if self._locked:
1056 _lock_file(f)
1057 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001058 return f.read().replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001059 finally:
1060 if self._locked:
1061 _unlock_file(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001062
1063 def get_file(self, key):
1064 """Return a file-like representation or raise a KeyError."""
1065 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00001066 f = open(os.path.join(self._path, str(key)), 'rb')
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02001067 except OSError as e:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001068 if e.errno == errno.ENOENT:
1069 raise KeyError('No message with key: %s' % key)
1070 else:
1071 raise
1072 return _ProxyFile(f)
1073
1074 def iterkeys(self):
1075 """Return an iterator over keys."""
1076 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1077 if entry.isdigit()))
1078
Guido van Rossume2b70bc2006-08-18 22:13:04 +00001079 def __contains__(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001080 """Return True if the keyed message exists, False otherwise."""
1081 return os.path.exists(os.path.join(self._path, str(key)))
1082
1083 def __len__(self):
1084 """Return a count of messages in the mailbox."""
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +03001085 return len(list(self.iterkeys()))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001086
1087 def lock(self):
1088 """Lock the mailbox."""
1089 if not self._locked:
1090 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
1091 _lock_file(self._file)
1092 self._locked = True
1093
1094 def unlock(self):
1095 """Unlock the mailbox if it is locked."""
1096 if self._locked:
1097 _unlock_file(self._file)
Thomas Wouters89f507f2006-12-13 04:49:30 +00001098 _sync_close(self._file)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001099 del self._file
1100 self._locked = False
1101
1102 def flush(self):
1103 """Write any pending changes to the disk."""
1104 return
1105
1106 def close(self):
1107 """Flush and close the mailbox."""
1108 if self._locked:
1109 self.unlock()
1110
1111 def list_folders(self):
1112 """Return a list of folder names."""
1113 result = []
1114 for entry in os.listdir(self._path):
1115 if os.path.isdir(os.path.join(self._path, entry)):
1116 result.append(entry)
1117 return result
1118
1119 def get_folder(self, folder):
1120 """Return an MH instance for the named folder."""
Thomas Wouters89f507f2006-12-13 04:49:30 +00001121 return MH(os.path.join(self._path, folder),
1122 factory=self._factory, create=False)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001123
1124 def add_folder(self, folder):
1125 """Create a folder and return an MH instance representing it."""
Thomas Wouters89f507f2006-12-13 04:49:30 +00001126 return MH(os.path.join(self._path, folder),
1127 factory=self._factory)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001128
1129 def remove_folder(self, folder):
1130 """Delete the named folder, which must be empty."""
1131 path = os.path.join(self._path, folder)
1132 entries = os.listdir(path)
1133 if entries == ['.mh_sequences']:
1134 os.remove(os.path.join(path, '.mh_sequences'))
1135 elif entries == []:
1136 pass
1137 else:
1138 raise NotEmptyError('Folder not empty: %s' % self._path)
1139 os.rmdir(path)
1140
1141 def get_sequences(self):
1142 """Return a name-to-key-list dictionary to define each sequence."""
1143 results = {}
Victor Stinner5c267e22011-10-17 20:44:22 +02001144 with open(os.path.join(self._path, '.mh_sequences'), 'r', encoding='ASCII') as f:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001145 all_keys = set(self.keys())
1146 for line in f:
1147 try:
1148 name, contents = line.split(':')
1149 keys = set()
1150 for spec in contents.split():
1151 if spec.isdigit():
1152 keys.add(int(spec))
1153 else:
1154 start, stop = (int(x) for x in spec.split('-'))
1155 keys.update(range(start, stop + 1))
1156 results[name] = [key for key in sorted(keys) \
1157 if key in all_keys]
1158 if len(results[name]) == 0:
1159 del results[name]
1160 except ValueError:
1161 raise FormatError('Invalid sequence specification: %s' %
1162 line.rstrip())
Thomas Wouters477c8d52006-05-27 19:21:47 +00001163 return results
1164
1165 def set_sequences(self, sequences):
1166 """Set sequences using the given name-to-key-list dictionary."""
Victor Stinner5c267e22011-10-17 20:44:22 +02001167 f = open(os.path.join(self._path, '.mh_sequences'), 'r+', encoding='ASCII')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001168 try:
1169 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001170 for name, keys in sequences.items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001171 if len(keys) == 0:
1172 continue
R. David Murrayb7deff12011-01-30 06:21:28 +00001173 f.write(name + ':')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001174 prev = None
1175 completing = False
1176 for key in sorted(set(keys)):
1177 if key - 1 == prev:
1178 if not completing:
1179 completing = True
1180 f.write('-')
1181 elif completing:
1182 completing = False
1183 f.write('%s %s' % (prev, key))
1184 else:
1185 f.write(' %s' % key)
1186 prev = key
1187 if completing:
1188 f.write(str(prev) + '\n')
1189 else:
1190 f.write('\n')
1191 finally:
Thomas Wouters89f507f2006-12-13 04:49:30 +00001192 _sync_close(f)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001193
1194 def pack(self):
1195 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1196 sequences = self.get_sequences()
1197 prev = 0
1198 changes = []
Serhiy Storchakacd3aacf52014-08-13 09:35:21 +03001199 for key in self.iterkeys():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001200 if key - 1 != prev:
1201 changes.append((key, prev + 1))
Thomas Wouters89f507f2006-12-13 04:49:30 +00001202 if hasattr(os, 'link'):
1203 os.link(os.path.join(self._path, str(key)),
1204 os.path.join(self._path, str(prev + 1)))
1205 os.unlink(os.path.join(self._path, str(key)))
1206 else:
1207 os.rename(os.path.join(self._path, str(key)),
1208 os.path.join(self._path, str(prev + 1)))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001209 prev += 1
1210 self._next_key = prev + 1
1211 if len(changes) == 0:
1212 return
1213 for name, key_list in sequences.items():
1214 for old, new in changes:
1215 if old in key_list:
1216 key_list[key_list.index(old)] = new
1217 self.set_sequences(sequences)
1218
1219 def _dump_sequences(self, message, key):
1220 """Inspect a new MHMessage and update sequences appropriately."""
1221 pending_sequences = message.get_sequences()
1222 all_sequences = self.get_sequences()
Guido van Rossumcc2b0162007-02-11 06:12:03 +00001223 for name, key_list in all_sequences.items():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001224 if name in pending_sequences:
1225 key_list.append(key)
1226 elif key in key_list:
1227 del key_list[key_list.index(key)]
1228 for sequence in pending_sequences:
1229 if sequence not in all_sequences:
1230 all_sequences[sequence] = [key]
1231 self.set_sequences(all_sequences)
1232
1233
1234class Babyl(_singlefileMailbox):
1235 """An Rmail-style Babyl mailbox."""
1236
1237 _special_labels = frozenset(('unseen', 'deleted', 'filed', 'answered',
1238 'forwarded', 'edited', 'resent'))
1239
1240 def __init__(self, path, factory=None, create=True):
1241 """Initialize a Babyl mailbox."""
1242 _singlefileMailbox.__init__(self, path, factory, create)
1243 self._labels = {}
1244
1245 def add(self, message):
1246 """Add message and return assigned key."""
1247 key = _singlefileMailbox.add(self, message)
1248 if isinstance(message, BabylMessage):
1249 self._labels[key] = message.get_labels()
1250 return key
1251
1252 def remove(self, key):
1253 """Remove the keyed message; raise KeyError if it doesn't exist."""
1254 _singlefileMailbox.remove(self, key)
1255 if key in self._labels:
1256 del self._labels[key]
1257
1258 def __setitem__(self, key, message):
1259 """Replace the keyed message; raise KeyError if it doesn't exist."""
1260 _singlefileMailbox.__setitem__(self, key, message)
1261 if isinstance(message, BabylMessage):
1262 self._labels[key] = message.get_labels()
1263
1264 def get_message(self, key):
1265 """Return a Message representation or raise a KeyError."""
1266 start, stop = self._lookup(key)
1267 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +00001268 self._file.readline() # Skip b'1,' line specifying labels.
1269 original_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001270 while True:
1271 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001272 if line == b'*** EOOH ***' + linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001273 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001274 original_headers.write(line.replace(linesep, b'\n'))
1275 visible_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001276 while True:
1277 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001278 if line == linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001279 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001280 visible_headers.write(line.replace(linesep, b'\n'))
1281 # Read up to the stop, or to the end
1282 n = stop - self._file.tell()
1283 assert n >= 0
1284 body = self._file.read(n)
1285 body = body.replace(linesep, b'\n')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001286 msg = BabylMessage(original_headers.getvalue() + body)
1287 msg.set_visible(visible_headers.getvalue())
1288 if key in self._labels:
1289 msg.set_labels(self._labels[key])
1290 return msg
1291
R. David Murrayb7deff12011-01-30 06:21:28 +00001292 def get_bytes(self, key):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001293 """Return a string representation or raise a KeyError."""
1294 start, stop = self._lookup(key)
1295 self._file.seek(start)
R. David Murrayb7deff12011-01-30 06:21:28 +00001296 self._file.readline() # Skip b'1,' line specifying labels.
1297 original_headers = io.BytesIO()
Thomas Wouters477c8d52006-05-27 19:21:47 +00001298 while True:
1299 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001300 if line == b'*** EOOH ***' + linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001301 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001302 original_headers.write(line.replace(linesep, b'\n'))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001303 while True:
1304 line = self._file.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001305 if line == linesep or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001306 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001307 headers = original_headers.getvalue()
1308 n = stop - self._file.tell()
1309 assert n >= 0
1310 data = self._file.read(n)
1311 data = data.replace(linesep, b'\n')
1312 return headers + data
Thomas Wouters477c8d52006-05-27 19:21:47 +00001313
1314 def get_file(self, key):
1315 """Return a file-like representation or raise a KeyError."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001316 return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001317
1318 def get_labels(self):
1319 """Return a list of user-defined labels in the mailbox."""
1320 self._lookup()
1321 labels = set()
1322 for label_list in self._labels.values():
1323 labels.update(label_list)
1324 labels.difference_update(self._special_labels)
1325 return list(labels)
1326
1327 def _generate_toc(self):
1328 """Generate key-to-(start, stop) table of contents."""
1329 starts, stops = [], []
1330 self._file.seek(0)
1331 next_pos = 0
1332 label_lists = []
1333 while True:
1334 line_pos = next_pos
1335 line = self._file.readline()
1336 next_pos = self._file.tell()
R. David Murrayb7deff12011-01-30 06:21:28 +00001337 if line == b'\037\014' + linesep:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001338 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +00001339 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001340 starts.append(next_pos)
1341 labels = [label.strip() for label
R. David Murrayb7deff12011-01-30 06:21:28 +00001342 in self._file.readline()[1:].split(b',')
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001343 if label.strip()]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001344 label_lists.append(labels)
R. David Murrayb7deff12011-01-30 06:21:28 +00001345 elif line == b'\037' or line == b'\037' + linesep:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001346 if len(stops) < len(starts):
R. David Murrayb7deff12011-01-30 06:21:28 +00001347 stops.append(line_pos - len(linesep))
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001348 elif not line:
R. David Murrayb7deff12011-01-30 06:21:28 +00001349 stops.append(line_pos - len(linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001350 break
1351 self._toc = dict(enumerate(zip(starts, stops)))
1352 self._labels = dict(enumerate(label_lists))
1353 self._next_key = len(self._toc)
Thomas Wouters902d6eb2007-01-09 23:18:33 +00001354 self._file.seek(0, 2)
1355 self._file_length = self._file.tell()
Thomas Wouters9fe394c2007-02-05 01:24:16 +00001356
Thomas Wouters477c8d52006-05-27 19:21:47 +00001357 def _pre_mailbox_hook(self, f):
1358 """Called before writing the mailbox to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001359 babyl = b'BABYL OPTIONS:' + linesep
1360 babyl += b'Version: 5' + linesep
1361 labels = self.get_labels()
1362 labels = (label.encode() for label in labels)
1363 babyl += b'Labels:' + b','.join(labels) + linesep
1364 babyl += b'\037'
1365 f.write(babyl)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001366
1367 def _pre_message_hook(self, f):
1368 """Called before writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001369 f.write(b'\014' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001370
1371 def _post_message_hook(self, f):
1372 """Called after writing each message to file f."""
R. David Murrayb7deff12011-01-30 06:21:28 +00001373 f.write(linesep + b'\037')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001374
1375 def _install_message(self, message):
1376 """Write message contents and return (start, stop)."""
1377 start = self._file.tell()
1378 if isinstance(message, BabylMessage):
1379 special_labels = []
1380 labels = []
1381 for label in message.get_labels():
1382 if label in self._special_labels:
1383 special_labels.append(label)
1384 else:
1385 labels.append(label)
R. David Murrayb7deff12011-01-30 06:21:28 +00001386 self._file.write(b'1')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001387 for label in special_labels:
R. David Murrayb7deff12011-01-30 06:21:28 +00001388 self._file.write(b', ' + label.encode())
1389 self._file.write(b',,')
Thomas Wouters477c8d52006-05-27 19:21:47 +00001390 for label in labels:
R. David Murrayb7deff12011-01-30 06:21:28 +00001391 self._file.write(b' ' + label.encode() + b',')
1392 self._file.write(linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001393 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001394 self._file.write(b'1,,' + linesep)
Thomas Woutersb2137042007-02-01 18:02:27 +00001395 if isinstance(message, email.message.Message):
R. David Murrayb7deff12011-01-30 06:21:28 +00001396 orig_buffer = io.BytesIO()
1397 orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001398 orig_generator.flatten(message)
1399 orig_buffer.seek(0)
1400 while True:
1401 line = orig_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001402 self._file.write(line.replace(b'\n', linesep))
1403 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001404 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001405 self._file.write(b'*** EOOH ***' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001406 if isinstance(message, BabylMessage):
R. David Murrayb7deff12011-01-30 06:21:28 +00001407 vis_buffer = io.BytesIO()
1408 vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001409 vis_generator.flatten(message.get_visible())
1410 while True:
1411 line = vis_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001412 self._file.write(line.replace(b'\n', linesep))
1413 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001414 break
1415 else:
1416 orig_buffer.seek(0)
1417 while True:
1418 line = orig_buffer.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001419 self._file.write(line.replace(b'\n', linesep))
1420 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001421 break
1422 while True:
1423 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001424 if not buffer:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001425 break
R. David Murrayb7deff12011-01-30 06:21:28 +00001426 self._file.write(buffer.replace(b'\n', linesep))
1427 elif isinstance(message, (bytes, str, io.StringIO)):
1428 if isinstance(message, io.StringIO):
1429 warnings.warn("Use of StringIO input is deprecated, "
1430 "use BytesIO instead", DeprecationWarning, 3)
1431 message = message.getvalue()
1432 if isinstance(message, str):
1433 message = self._string_to_bytes(message)
1434 body_start = message.find(b'\n\n') + 2
Thomas Wouters477c8d52006-05-27 19:21:47 +00001435 if body_start - 2 != -1:
R. David Murrayb7deff12011-01-30 06:21:28 +00001436 self._file.write(message[:body_start].replace(b'\n', linesep))
1437 self._file.write(b'*** EOOH ***' + linesep)
1438 self._file.write(message[:body_start].replace(b'\n', linesep))
1439 self._file.write(message[body_start:].replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001440 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001441 self._file.write(b'*** EOOH ***' + linesep + linesep)
1442 self._file.write(message.replace(b'\n', linesep))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001443 elif hasattr(message, 'readline'):
R. David Murrayb7deff12011-01-30 06:21:28 +00001444 if hasattr(message, 'buffer'):
1445 warnings.warn("Use of text mode files is deprecated, "
1446 "use a binary mode file instead", DeprecationWarning, 3)
1447 message = message.buffer
Thomas Wouters477c8d52006-05-27 19:21:47 +00001448 original_pos = message.tell()
1449 first_pass = True
1450 while True:
1451 line = message.readline()
R. David Murrayb7deff12011-01-30 06:21:28 +00001452 # Universal newline support.
1453 if line.endswith(b'\r\n'):
1454 line = line[:-2] + b'\n'
1455 elif line.endswith(b'\r'):
1456 line = line[:-1] + b'\n'
1457 self._file.write(line.replace(b'\n', linesep))
1458 if line == b'\n' or not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001459 if first_pass:
1460 first_pass = False
Petri Lehtinen3d12c432012-08-15 14:00:40 +03001461 self._file.write(b'*** EOOH ***' + linesep)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001462 message.seek(original_pos)
1463 else:
1464 break
1465 while True:
Petri Lehtinen88614942012-08-16 07:22:15 +03001466 line = message.readline()
1467 if not line:
Thomas Wouters477c8d52006-05-27 19:21:47 +00001468 break
Petri Lehtinen88614942012-08-16 07:22:15 +03001469 # Universal newline support.
1470 if line.endswith(b'\r\n'):
1471 line = line[:-2] + linesep
1472 elif line.endswith(b'\r'):
1473 line = line[:-1] + linesep
1474 elif line.endswith(b'\n'):
1475 line = line[:-1] + linesep
1476 self._file.write(line)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001477 else:
1478 raise TypeError('Invalid message type: %s' % type(message))
1479 stop = self._file.tell()
1480 return (start, stop)
1481
1482
Thomas Woutersb2137042007-02-01 18:02:27 +00001483class Message(email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001484 """Message with mailbox-format-specific properties."""
1485
1486 def __init__(self, message=None):
1487 """Initialize a Message instance."""
Thomas Woutersb2137042007-02-01 18:02:27 +00001488 if isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001489 self._become_message(copy.deepcopy(message))
1490 if isinstance(message, Message):
1491 message._explain_to(self)
R. David Murrayb7deff12011-01-30 06:21:28 +00001492 elif isinstance(message, bytes):
1493 self._become_message(email.message_from_bytes(message))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001494 elif isinstance(message, str):
1495 self._become_message(email.message_from_string(message))
R. David Murrayb7deff12011-01-30 06:21:28 +00001496 elif isinstance(message, io.TextIOWrapper):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001497 self._become_message(email.message_from_file(message))
R. David Murrayb7deff12011-01-30 06:21:28 +00001498 elif hasattr(message, "read"):
1499 self._become_message(email.message_from_binary_file(message))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001500 elif message is None:
Thomas Woutersb2137042007-02-01 18:02:27 +00001501 email.message.Message.__init__(self)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001502 else:
1503 raise TypeError('Invalid message type: %s' % type(message))
1504
1505 def _become_message(self, message):
1506 """Assume the non-format-specific state of message."""
R David Murrayb019ee72012-04-08 22:36:07 -04001507 type_specific = getattr(message, '_type_specific_attributes', [])
1508 for name in message.__dict__:
1509 if name not in type_specific:
1510 self.__dict__[name] = message.__dict__[name]
Thomas Wouters477c8d52006-05-27 19:21:47 +00001511
1512 def _explain_to(self, message):
1513 """Copy format-specific state to message insofar as possible."""
1514 if isinstance(message, Message):
1515 return # There's nothing format-specific to explain.
1516 else:
1517 raise TypeError('Cannot convert to specified type')
1518
1519
1520class MaildirMessage(Message):
1521 """Message with Maildir-specific properties."""
1522
R David Murrayb019ee72012-04-08 22:36:07 -04001523 _type_specific_attributes = ['_subdir', '_info', '_date']
1524
Thomas Wouters477c8d52006-05-27 19:21:47 +00001525 def __init__(self, message=None):
1526 """Initialize a MaildirMessage instance."""
1527 self._subdir = 'new'
1528 self._info = ''
1529 self._date = time.time()
1530 Message.__init__(self, message)
1531
1532 def get_subdir(self):
1533 """Return 'new' or 'cur'."""
1534 return self._subdir
1535
1536 def set_subdir(self, subdir):
1537 """Set subdir to 'new' or 'cur'."""
1538 if subdir == 'new' or subdir == 'cur':
1539 self._subdir = subdir
1540 else:
1541 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1542
1543 def get_flags(self):
1544 """Return as a string the flags that are set."""
1545 if self._info.startswith('2,'):
1546 return self._info[2:]
1547 else:
1548 return ''
1549
1550 def set_flags(self, flags):
1551 """Set the given flags and unset all others."""
1552 self._info = '2,' + ''.join(sorted(flags))
1553
1554 def add_flag(self, flag):
1555 """Set the given flag(s) without changing others."""
1556 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1557
1558 def remove_flag(self, flag):
1559 """Unset the given string flag(s) without changing others."""
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001560 if self.get_flags():
Thomas Wouters477c8d52006-05-27 19:21:47 +00001561 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1562
1563 def get_date(self):
1564 """Return delivery date of message, in seconds since the epoch."""
1565 return self._date
1566
1567 def set_date(self, date):
1568 """Set delivery date of message, in seconds since the epoch."""
1569 try:
1570 self._date = float(date)
1571 except ValueError:
1572 raise TypeError("can't convert to float: %s" % date)
1573
1574 def get_info(self):
1575 """Get the message's "info" as a string."""
1576 return self._info
1577
1578 def set_info(self, info):
1579 """Set the message's "info" string."""
1580 if isinstance(info, str):
1581 self._info = info
1582 else:
1583 raise TypeError('info must be a string: %s' % type(info))
1584
1585 def _explain_to(self, message):
1586 """Copy Maildir-specific state to message insofar as possible."""
1587 if isinstance(message, MaildirMessage):
1588 message.set_flags(self.get_flags())
1589 message.set_subdir(self.get_subdir())
1590 message.set_date(self.get_date())
1591 elif isinstance(message, _mboxMMDFMessage):
1592 flags = set(self.get_flags())
1593 if 'S' in flags:
1594 message.add_flag('R')
1595 if self.get_subdir() == 'cur':
1596 message.add_flag('O')
1597 if 'T' in flags:
1598 message.add_flag('D')
1599 if 'F' in flags:
1600 message.add_flag('F')
1601 if 'R' in flags:
1602 message.add_flag('A')
1603 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1604 elif isinstance(message, MHMessage):
1605 flags = set(self.get_flags())
1606 if 'S' not in flags:
1607 message.add_sequence('unseen')
1608 if 'R' in flags:
1609 message.add_sequence('replied')
1610 if 'F' in flags:
1611 message.add_sequence('flagged')
1612 elif isinstance(message, BabylMessage):
1613 flags = set(self.get_flags())
1614 if 'S' not in flags:
1615 message.add_label('unseen')
1616 if 'T' in flags:
1617 message.add_label('deleted')
1618 if 'R' in flags:
1619 message.add_label('answered')
1620 if 'P' in flags:
1621 message.add_label('forwarded')
1622 elif isinstance(message, Message):
1623 pass
1624 else:
1625 raise TypeError('Cannot convert to specified type: %s' %
1626 type(message))
1627
1628
1629class _mboxMMDFMessage(Message):
1630 """Message with mbox- or MMDF-specific properties."""
1631
R David Murrayb019ee72012-04-08 22:36:07 -04001632 _type_specific_attributes = ['_from']
1633
Thomas Wouters477c8d52006-05-27 19:21:47 +00001634 def __init__(self, message=None):
1635 """Initialize an mboxMMDFMessage instance."""
1636 self.set_from('MAILER-DAEMON', True)
Thomas Woutersb2137042007-02-01 18:02:27 +00001637 if isinstance(message, email.message.Message):
Thomas Wouters477c8d52006-05-27 19:21:47 +00001638 unixfrom = message.get_unixfrom()
1639 if unixfrom is not None and unixfrom.startswith('From '):
1640 self.set_from(unixfrom[5:])
1641 Message.__init__(self, message)
1642
1643 def get_from(self):
1644 """Return contents of "From " line."""
1645 return self._from
1646
1647 def set_from(self, from_, time_=None):
1648 """Set "From " line, formatting and appending time_ if specified."""
1649 if time_ is not None:
1650 if time_ is True:
1651 time_ = time.gmtime()
1652 from_ += ' ' + time.asctime(time_)
1653 self._from = from_
1654
1655 def get_flags(self):
1656 """Return as a string the flags that are set."""
1657 return self.get('Status', '') + self.get('X-Status', '')
1658
1659 def set_flags(self, flags):
1660 """Set the given flags and unset all others."""
1661 flags = set(flags)
1662 status_flags, xstatus_flags = '', ''
1663 for flag in ('R', 'O'):
1664 if flag in flags:
1665 status_flags += flag
1666 flags.remove(flag)
1667 for flag in ('D', 'F', 'A'):
1668 if flag in flags:
1669 xstatus_flags += flag
1670 flags.remove(flag)
1671 xstatus_flags += ''.join(sorted(flags))
1672 try:
1673 self.replace_header('Status', status_flags)
1674 except KeyError:
1675 self.add_header('Status', status_flags)
1676 try:
1677 self.replace_header('X-Status', xstatus_flags)
1678 except KeyError:
1679 self.add_header('X-Status', xstatus_flags)
1680
1681 def add_flag(self, flag):
1682 """Set the given flag(s) without changing others."""
1683 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1684
1685 def remove_flag(self, flag):
1686 """Unset the given string flag(s) without changing others."""
1687 if 'Status' in self or 'X-Status' in self:
1688 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1689
1690 def _explain_to(self, message):
1691 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1692 if isinstance(message, MaildirMessage):
1693 flags = set(self.get_flags())
1694 if 'O' in flags:
1695 message.set_subdir('cur')
1696 if 'F' in flags:
1697 message.add_flag('F')
1698 if 'A' in flags:
1699 message.add_flag('R')
1700 if 'R' in flags:
1701 message.add_flag('S')
1702 if 'D' in flags:
1703 message.add_flag('T')
1704 del message['status']
1705 del message['x-status']
1706 maybe_date = ' '.join(self.get_from().split()[-5:])
1707 try:
1708 message.set_date(calendar.timegm(time.strptime(maybe_date,
1709 '%a %b %d %H:%M:%S %Y')))
1710 except (ValueError, OverflowError):
1711 pass
1712 elif isinstance(message, _mboxMMDFMessage):
1713 message.set_flags(self.get_flags())
1714 message.set_from(self.get_from())
1715 elif isinstance(message, MHMessage):
1716 flags = set(self.get_flags())
1717 if 'R' not in flags:
1718 message.add_sequence('unseen')
1719 if 'A' in flags:
1720 message.add_sequence('replied')
1721 if 'F' in flags:
1722 message.add_sequence('flagged')
1723 del message['status']
1724 del message['x-status']
1725 elif isinstance(message, BabylMessage):
1726 flags = set(self.get_flags())
1727 if 'R' not in flags:
1728 message.add_label('unseen')
1729 if 'D' in flags:
1730 message.add_label('deleted')
1731 if 'A' in flags:
1732 message.add_label('answered')
1733 del message['status']
1734 del message['x-status']
1735 elif isinstance(message, Message):
1736 pass
1737 else:
1738 raise TypeError('Cannot convert to specified type: %s' %
1739 type(message))
1740
1741
1742class mboxMessage(_mboxMMDFMessage):
1743 """Message with mbox-specific properties."""
1744
1745
1746class MHMessage(Message):
1747 """Message with MH-specific properties."""
1748
R David Murrayb019ee72012-04-08 22:36:07 -04001749 _type_specific_attributes = ['_sequences']
1750
Thomas Wouters477c8d52006-05-27 19:21:47 +00001751 def __init__(self, message=None):
1752 """Initialize an MHMessage instance."""
1753 self._sequences = []
1754 Message.__init__(self, message)
1755
1756 def get_sequences(self):
1757 """Return a list of sequences that include the message."""
1758 return self._sequences[:]
1759
1760 def set_sequences(self, sequences):
1761 """Set the list of sequences that include the message."""
1762 self._sequences = list(sequences)
1763
1764 def add_sequence(self, sequence):
1765 """Add sequence to list of sequences including the message."""
1766 if isinstance(sequence, str):
1767 if not sequence in self._sequences:
1768 self._sequences.append(sequence)
1769 else:
R. David Murrayb7deff12011-01-30 06:21:28 +00001770 raise TypeError('sequence type must be str: %s' % type(sequence))
Thomas Wouters477c8d52006-05-27 19:21:47 +00001771
1772 def remove_sequence(self, sequence):
1773 """Remove sequence from the list of sequences including the message."""
1774 try:
1775 self._sequences.remove(sequence)
1776 except ValueError:
1777 pass
1778
1779 def _explain_to(self, message):
1780 """Copy MH-specific state to message insofar as possible."""
1781 if isinstance(message, MaildirMessage):
1782 sequences = set(self.get_sequences())
1783 if 'unseen' in sequences:
1784 message.set_subdir('cur')
1785 else:
1786 message.set_subdir('cur')
1787 message.add_flag('S')
1788 if 'flagged' in sequences:
1789 message.add_flag('F')
1790 if 'replied' in sequences:
1791 message.add_flag('R')
1792 elif isinstance(message, _mboxMMDFMessage):
1793 sequences = set(self.get_sequences())
1794 if 'unseen' not in sequences:
1795 message.add_flag('RO')
1796 else:
1797 message.add_flag('O')
1798 if 'flagged' in sequences:
1799 message.add_flag('F')
1800 if 'replied' in sequences:
1801 message.add_flag('A')
1802 elif isinstance(message, MHMessage):
1803 for sequence in self.get_sequences():
1804 message.add_sequence(sequence)
1805 elif isinstance(message, BabylMessage):
1806 sequences = set(self.get_sequences())
1807 if 'unseen' in sequences:
1808 message.add_label('unseen')
1809 if 'replied' in sequences:
1810 message.add_label('answered')
1811 elif isinstance(message, Message):
1812 pass
1813 else:
1814 raise TypeError('Cannot convert to specified type: %s' %
1815 type(message))
1816
1817
1818class BabylMessage(Message):
1819 """Message with Babyl-specific properties."""
1820
R David Murrayb019ee72012-04-08 22:36:07 -04001821 _type_specific_attributes = ['_labels', '_visible']
1822
Thomas Wouters477c8d52006-05-27 19:21:47 +00001823 def __init__(self, message=None):
1824 """Initialize an BabylMessage instance."""
1825 self._labels = []
1826 self._visible = Message()
1827 Message.__init__(self, message)
1828
1829 def get_labels(self):
1830 """Return a list of labels on the message."""
1831 return self._labels[:]
1832
1833 def set_labels(self, labels):
1834 """Set the list of labels on the message."""
1835 self._labels = list(labels)
1836
1837 def add_label(self, label):
1838 """Add label to list of labels on the message."""
1839 if isinstance(label, str):
1840 if label not in self._labels:
1841 self._labels.append(label)
1842 else:
1843 raise TypeError('label must be a string: %s' % type(label))
1844
1845 def remove_label(self, label):
1846 """Remove label from the list of labels on the message."""
1847 try:
1848 self._labels.remove(label)
1849 except ValueError:
1850 pass
1851
1852 def get_visible(self):
1853 """Return a Message representation of visible headers."""
1854 return Message(self._visible)
1855
1856 def set_visible(self, visible):
1857 """Set the Message representation of visible headers."""
1858 self._visible = Message(visible)
1859
1860 def update_visible(self):
1861 """Update and/or sensibly generate a set of visible headers."""
1862 for header in self._visible.keys():
1863 if header in self:
1864 self._visible.replace_header(header, self[header])
1865 else:
1866 del self._visible[header]
1867 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1868 if header in self and header not in self._visible:
1869 self._visible[header] = self[header]
1870
1871 def _explain_to(self, message):
1872 """Copy Babyl-specific state to message insofar as possible."""
1873 if isinstance(message, MaildirMessage):
1874 labels = set(self.get_labels())
1875 if 'unseen' in labels:
1876 message.set_subdir('cur')
1877 else:
1878 message.set_subdir('cur')
1879 message.add_flag('S')
1880 if 'forwarded' in labels or 'resent' in labels:
1881 message.add_flag('P')
1882 if 'answered' in labels:
1883 message.add_flag('R')
1884 if 'deleted' in labels:
1885 message.add_flag('T')
1886 elif isinstance(message, _mboxMMDFMessage):
1887 labels = set(self.get_labels())
1888 if 'unseen' not in labels:
1889 message.add_flag('RO')
1890 else:
1891 message.add_flag('O')
1892 if 'deleted' in labels:
1893 message.add_flag('D')
1894 if 'answered' in labels:
1895 message.add_flag('A')
1896 elif isinstance(message, MHMessage):
1897 labels = set(self.get_labels())
1898 if 'unseen' in labels:
1899 message.add_sequence('unseen')
1900 if 'answered' in labels:
1901 message.add_sequence('replied')
1902 elif isinstance(message, BabylMessage):
1903 message.set_visible(self.get_visible())
1904 for label in self.get_labels():
1905 message.add_label(label)
1906 elif isinstance(message, Message):
1907 pass
1908 else:
1909 raise TypeError('Cannot convert to specified type: %s' %
1910 type(message))
1911
1912
1913class MMDFMessage(_mboxMMDFMessage):
1914 """Message with MMDF-specific properties."""
1915
1916
1917class _ProxyFile:
1918 """A read-only wrapper of a file."""
1919
1920 def __init__(self, f, pos=None):
1921 """Initialize a _ProxyFile."""
1922 self._file = f
1923 if pos is None:
1924 self._pos = f.tell()
1925 else:
1926 self._pos = pos
1927
1928 def read(self, size=None):
1929 """Read bytes."""
Guido van Rossum98297ee2007-11-06 21:34:58 +00001930 return self._read(size, self._file.read)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001931
R. David Murrayb7deff12011-01-30 06:21:28 +00001932 def read1(self, size=None):
1933 """Read bytes."""
1934 return self._read(size, self._file.read1)
1935
Thomas Wouters477c8d52006-05-27 19:21:47 +00001936 def readline(self, size=None):
1937 """Read a line."""
Guido van Rossum98297ee2007-11-06 21:34:58 +00001938 return self._read(size, self._file.readline)
Thomas Wouters477c8d52006-05-27 19:21:47 +00001939
1940 def readlines(self, sizehint=None):
1941 """Read multiple lines."""
1942 result = []
1943 for line in self:
1944 result.append(line)
1945 if sizehint is not None:
1946 sizehint -= len(line)
1947 if sizehint <= 0:
1948 break
1949 return result
1950
1951 def __iter__(self):
1952 """Iterate over lines."""
Guido van Rossum7cad4f32007-06-07 23:58:54 +00001953 while True:
1954 line = self.readline()
1955 if not line:
1956 raise StopIteration
1957 yield line
Thomas Wouters477c8d52006-05-27 19:21:47 +00001958
1959 def tell(self):
1960 """Return the position."""
1961 return self._pos
1962
1963 def seek(self, offset, whence=0):
1964 """Change position."""
1965 if whence == 1:
1966 self._file.seek(self._pos)
1967 self._file.seek(offset, whence)
1968 self._pos = self._file.tell()
1969
1970 def close(self):
1971 """Close the file."""
R David Murrayc88bce12011-06-17 22:24:05 -04001972 if hasattr(self, '_file'):
1973 if hasattr(self._file, 'close'):
1974 self._file.close()
1975 del self._file
Thomas Wouters477c8d52006-05-27 19:21:47 +00001976
1977 def _read(self, size, read_method):
1978 """Read size bytes using read_method."""
1979 if size is None:
1980 size = -1
1981 self._file.seek(self._pos)
1982 result = read_method(size)
1983 self._pos = self._file.tell()
1984 return result
1985
Georg Brandl6ce29fa2010-10-30 14:33:28 +00001986 def __enter__(self):
Serhiy Storchaka14867992014-09-10 23:43:41 +03001987 """Context management protocol support."""
Georg Brandl6ce29fa2010-10-30 14:33:28 +00001988 return self
1989
1990 def __exit__(self, *exc):
1991 self.close()
1992
R. David Murrayb7deff12011-01-30 06:21:28 +00001993 def readable(self):
1994 return self._file.readable()
1995
1996 def writable(self):
1997 return self._file.writable()
1998
1999 def seekable(self):
2000 return self._file.seekable()
2001
2002 def flush(self):
2003 return self._file.flush()
2004
2005 @property
2006 def closed(self):
R David Murrayc88bce12011-06-17 22:24:05 -04002007 if not hasattr(self, '_file'):
2008 return True
2009 if not hasattr(self._file, 'closed'):
2010 return False
R. David Murrayb7deff12011-01-30 06:21:28 +00002011 return self._file.closed
2012
Thomas Wouters477c8d52006-05-27 19:21:47 +00002013
2014class _PartialFile(_ProxyFile):
2015 """A read-only wrapper of part of a file."""
2016
2017 def __init__(self, f, start=None, stop=None):
2018 """Initialize a _PartialFile."""
2019 _ProxyFile.__init__(self, f, start)
2020 self._start = start
2021 self._stop = stop
2022
2023 def tell(self):
2024 """Return the position with respect to start."""
2025 return _ProxyFile.tell(self) - self._start
2026
2027 def seek(self, offset, whence=0):
2028 """Change position, possibly with respect to start or stop."""
2029 if whence == 0:
2030 self._pos = self._start
2031 whence = 1
2032 elif whence == 2:
2033 self._pos = self._stop
2034 whence = 1
2035 _ProxyFile.seek(self, offset, whence)
2036
2037 def _read(self, size, read_method):
2038 """Read size bytes using read_method, honoring start and stop."""
2039 remaining = self._stop - self._pos
2040 if remaining <= 0:
R. David Murrayb7deff12011-01-30 06:21:28 +00002041 return b''
Thomas Wouters477c8d52006-05-27 19:21:47 +00002042 if size is None or size < 0 or size > remaining:
2043 size = remaining
2044 return _ProxyFile._read(self, size, read_method)
2045
Georg Brandl6ce29fa2010-10-30 14:33:28 +00002046 def close(self):
2047 # do *not* close the underlying file object for partial files,
2048 # since it's global to the mailbox object
R David Murrayc88bce12011-06-17 22:24:05 -04002049 if hasattr(self, '_file'):
2050 del self._file
Georg Brandl6ce29fa2010-10-30 14:33:28 +00002051
Thomas Wouters477c8d52006-05-27 19:21:47 +00002052
2053def _lock_file(f, dotlock=True):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002054 """Lock file f using lockf and dot locking."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00002055 dotlock_done = False
2056 try:
2057 if fcntl:
2058 try:
2059 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002060 except OSError as e:
R. David Murray752b9502011-03-03 18:12:34 +00002061 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002062 raise ExternalClashError('lockf: lock unavailable: %s' %
2063 f.name)
2064 else:
2065 raise
Thomas Wouters477c8d52006-05-27 19:21:47 +00002066 if dotlock:
2067 try:
2068 pre_lock = _create_temporary(f.name + '.lock')
2069 pre_lock.close()
Andrew Svetlovf7a17b42012-12-25 16:47:37 +02002070 except OSError as e:
R. David Murray752b9502011-03-03 18:12:34 +00002071 if e.errno in (errno.EACCES, errno.EROFS):
Thomas Wouters477c8d52006-05-27 19:21:47 +00002072 return # Without write access, just skip dotlocking.
2073 else:
2074 raise
2075 try:
2076 if hasattr(os, 'link'):
2077 os.link(pre_lock.name, f.name + '.lock')
2078 dotlock_done = True
2079 os.unlink(pre_lock.name)
2080 else:
2081 os.rename(pre_lock.name, f.name + '.lock')
2082 dotlock_done = True
Giampaolo Rodola'0166a282013-02-12 15:14:17 +01002083 except FileExistsError:
2084 os.remove(pre_lock.name)
2085 raise ExternalClashError('dot lock unavailable: %s' %
2086 f.name)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002087 except:
2088 if fcntl:
2089 fcntl.lockf(f, fcntl.LOCK_UN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002090 if dotlock_done:
2091 os.remove(f.name + '.lock')
2092 raise
2093
2094def _unlock_file(f):
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002095 """Unlock file f using lockf and dot locking."""
Thomas Wouters477c8d52006-05-27 19:21:47 +00002096 if fcntl:
2097 fcntl.lockf(f, fcntl.LOCK_UN)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002098 if os.path.exists(f.name + '.lock'):
2099 os.remove(f.name + '.lock')
2100
2101def _create_carefully(path):
2102 """Create a file if it doesn't exist and open for reading and writing."""
Georg Brandl6aa2d1f2008-08-12 08:35:52 +00002103 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
Thomas Wouters477c8d52006-05-27 19:21:47 +00002104 try:
R. David Murrayb7deff12011-01-30 06:21:28 +00002105 return open(path, 'rb+')
Thomas Wouters477c8d52006-05-27 19:21:47 +00002106 finally:
2107 os.close(fd)
2108
2109def _create_temporary(path):
2110 """Create a temp file based on path and open for reading and writing."""
2111 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
2112 socket.gethostname(),
2113 os.getpid()))
2114
Thomas Wouters89f507f2006-12-13 04:49:30 +00002115def _sync_flush(f):
2116 """Ensure changes to file f are physically on disk."""
2117 f.flush()
Thomas Wouters902d6eb2007-01-09 23:18:33 +00002118 if hasattr(os, 'fsync'):
2119 os.fsync(f.fileno())
Thomas Wouters89f507f2006-12-13 04:49:30 +00002120
2121def _sync_close(f):
2122 """Close file f, ensuring all changes are physically on disk."""
2123 _sync_flush(f)
2124 f.close()
Thomas Wouters477c8d52006-05-27 19:21:47 +00002125
Guido van Rossum62448671996-09-17 21:33:15 +00002126
Thomas Wouters477c8d52006-05-27 19:21:47 +00002127class Error(Exception):
2128 """Raised for module-specific errors."""
2129
2130class NoSuchMailboxError(Error):
2131 """The specified mailbox does not exist and won't be created."""
2132
2133class NotEmptyError(Error):
2134 """The specified mailbox is not empty and deletion was requested."""
2135
2136class ExternalClashError(Error):
2137 """Another process caused an action to fail."""
2138
2139class FormatError(Error):
2140 """A file appears to have an invalid format."""