Debian Codegraph @

lib-python/3/mailbox.py

raw symbols SCIP
1 """Read/write support for Maildir, mbox, MH, Babyl, and MMDF mailboxes."""
2
3 # 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
9 import os
10 import time
11 import calendar
12 import socket
13 import errno
14 import copy
15 import warnings
16 import email
17 import email.message
18 import email.generator
19 import io
20 import contextlib
21 from types import GenericAlias
22 try:
23 import fcntl
24 except ImportError:
25 fcntl = None
26
27 __all__ = ['Mailbox', 'Maildir', 'mbox', 'MH', 'Babyl', 'MMDF',
28 'Message', 'MaildirMessage', 'mboxMessage', 'MHMessage',
29 'BabylMessage', 'MMDFMessage', 'Error', 'NoSuchMailboxError',
30 'NotEmptyError', 'ExternalClashError', 'FormatError']
31
32 linesep = os.linesep.encode('ascii')
33
34 class Mailbox:
35 """A group of messages in a particular place."""
36
37 def __init__(self, path, factory=None, create=True):
38 """Initialize a Mailbox instance."""
39 self._path = os.path.abspath(os.path.expanduser(path))
40 self._factory = factory
41
42 def add(self, message):
43 """Add message and return assigned key."""
44 raise NotImplementedError('Method must be implemented by subclass')
45
46 def remove(self, key):
47 """Remove the keyed message; raise KeyError if it doesn't exist."""
48 raise NotImplementedError('Method must be implemented by subclass')
49
50 def __delitem__(self, key):
51 self.remove(key)
52
53 def discard(self, key):
54 """If the keyed message exists, remove it."""
55 try:
56 self.remove(key)
57 except KeyError:
58 pass
59
60 def __setitem__(self, key, message):
61 """Replace the keyed message; raise KeyError if it doesn't exist."""
62 raise NotImplementedError('Method must be implemented by subclass')
63
64 def get(self, key, default=None):
65 """Return the keyed message, or default if it doesn't exist."""
66 try:
67 return self.__getitem__(key)
68 except KeyError:
69 return default
70
71 def __getitem__(self, key):
72 """Return the keyed message; raise KeyError if it doesn't exist."""
73 if not self._factory:
74 return self.get_message(key)
75 else:
76 with contextlib.closing(self.get_file(key)) as file:
77 return self._factory(file)
78
79 def get_message(self, key):
80 """Return a Message representation or raise a KeyError."""
81 raise NotImplementedError('Method must be implemented by subclass')
82
83 def get_string(self, key):
84 """Return a string representation or raise a KeyError.
85
86 Uses email.message.Message to create a 7bit clean string
87 representation of the message."""
88 return email.message_from_bytes(self.get_bytes(key)).as_string()
89
90 def get_bytes(self, key):
91 """Return a byte string representation or raise a KeyError."""
92 raise NotImplementedError('Method must be implemented by subclass')
93
94 def get_file(self, key):
95 """Return a file-like representation or raise a KeyError."""
96 raise NotImplementedError('Method must be implemented by subclass')
97
98 def iterkeys(self):
99 """Return an iterator over keys."""
100 raise NotImplementedError('Method must be implemented by subclass')
101
102 def keys(self):
103 """Return a list of keys."""
104 return list(self.iterkeys())
105
106 def itervalues(self):
107 """Return an iterator over all messages."""
108 for key in self.iterkeys():
109 try:
110 value = self[key]
111 except KeyError:
112 continue
113 yield value
114
115 def __iter__(self):
116 return self.itervalues()
117
118 def values(self):
119 """Return a list of messages. Memory intensive."""
120 return list(self.itervalues())
121
122 def iteritems(self):
123 """Return an iterator over (key, message) tuples."""
124 for key in self.iterkeys():
125 try:
126 value = self[key]
127 except KeyError:
128 continue
129 yield (key, value)
130
131 def items(self):
132 """Return a list of (key, message) tuples. Memory intensive."""
133 return list(self.iteritems())
134
135 def __contains__(self, key):
136 """Return True if the keyed message exists, False otherwise."""
137 raise NotImplementedError('Method must be implemented by subclass')
138
139 def __len__(self):
140 """Return a count of messages in the mailbox."""
141 raise NotImplementedError('Method must be implemented by subclass')
142
143 def clear(self):
144 """Delete all messages."""
145 for key in self.keys():
146 self.discard(key)
147
148 def pop(self, key, default=None):
149 """Delete the keyed message and return it, or default."""
150 try:
151 result = self[key]
152 except KeyError:
153 return default
154 self.discard(key)
155 return result
156
157 def popitem(self):
158 """Delete an arbitrary (key, message) pair and return it."""
159 for key in self.iterkeys():
160 return (key, self.pop(key)) # This is only run once.
161 else:
162 raise KeyError('No messages in mailbox')
163
164 def update(self, arg=None):
165 """Change the messages that correspond to certain keys."""
166 if hasattr(arg, 'iteritems'):
167 source = arg.iteritems()
168 elif hasattr(arg, 'items'):
169 source = arg.items()
170 else:
171 source = arg
172 bad_key = False
173 for key, message in source:
174 try:
175 self[key] = message
176 except KeyError:
177 bad_key = True
178 if bad_key:
179 raise KeyError('No message with key(s)')
180
181 def flush(self):
182 """Write any pending changes to the disk."""
183 raise NotImplementedError('Method must be implemented by subclass')
184
185 def lock(self):
186 """Lock the mailbox."""
187 raise NotImplementedError('Method must be implemented by subclass')
188
189 def unlock(self):
190 """Unlock the mailbox if it is locked."""
191 raise NotImplementedError('Method must be implemented by subclass')
192
193 def close(self):
194 """Flush and close the mailbox."""
195 raise NotImplementedError('Method must be implemented by subclass')
196
197 def _string_to_bytes(self, message):
198 # If a message is not 7bit clean, we refuse to handle it since it
199 # likely came from reading invalid messages in text mode, and that way
200 # lies mojibake.
201 try:
202 return message.encode('ascii')
203 except UnicodeError:
204 raise ValueError("String input must be ASCII-only; "
205 "use bytes or a Message instead")
206
207 # Whether each message must end in a newline
208 _append_newline = False
209
210 def _dump_message(self, message, target, mangle_from_=False):
211 # This assumes the target file is open in binary mode.
212 """Dump message contents to target file."""
213 if isinstance(message, email.message.Message):
214 buffer = io.BytesIO()
215 gen = email.generator.BytesGenerator(buffer, mangle_from_, 0)
216 gen.flatten(message)
217 buffer.seek(0)
218 data = buffer.read()
219 data = data.replace(b'\n', linesep)
220 target.write(data)
221 if self._append_newline and not data.endswith(linesep):
222 # Make sure the message ends with a newline
223 target.write(linesep)
224 elif isinstance(message, (str, bytes, io.StringIO)):
225 if isinstance(message, io.StringIO):
226 warnings.warn("Use of StringIO input is deprecated, "
227 "use BytesIO instead", DeprecationWarning, 3)
228 message = message.getvalue()
229 if isinstance(message, str):
230 message = self._string_to_bytes(message)
231 if mangle_from_:
232 message = message.replace(b'\nFrom ', b'\n>From ')
233 message = message.replace(b'\n', linesep)
234 target.write(message)
235 if self._append_newline and not message.endswith(linesep):
236 # Make sure the message ends with a newline
237 target.write(linesep)
238 elif hasattr(message, 'read'):
239 if hasattr(message, 'buffer'):
240 warnings.warn("Use of text mode files is deprecated, "
241 "use a binary mode file instead", DeprecationWarning, 3)
242 message = message.buffer
243 lastline = None
244 while True:
245 line = message.readline()
246 # Universal newline support.
247 if line.endswith(b'\r\n'):
248 line = line[:-2] + b'\n'
249 elif line.endswith(b'\r'):
250 line = line[:-1] + b'\n'
251 if not line:
252 break
253 if mangle_from_ and line.startswith(b'From '):
254 line = b'>From ' + line[5:]
255 line = line.replace(b'\n', linesep)
256 target.write(line)
257 lastline = line
258 if self._append_newline and lastline and not lastline.endswith(linesep):
259 # Make sure the message ends with a newline
260 target.write(linesep)
261 else:
262 raise TypeError('Invalid message type: %s' % type(message))
263
264 __class_getitem__ = classmethod(GenericAlias)
265
266
267 class Maildir(Mailbox):
268 """A qmail-style Maildir mailbox."""
269
270 colon = ':'
271
272 def __init__(self, dirname, factory=None, create=True):
273 """Initialize a Maildir instance."""
274 Mailbox.__init__(self, dirname, factory, create)
275 self._paths = {
276 'tmp': os.path.join(self._path, 'tmp'),
277 'new': os.path.join(self._path, 'new'),
278 'cur': os.path.join(self._path, 'cur'),
279 }
280 if not os.path.exists(self._path):
281 if create:
282 os.mkdir(self._path, 0o700)
283 for path in self._paths.values():
284 os.mkdir(path, 0o700)
285 else:
286 raise NoSuchMailboxError(self._path)
287 self._toc = {}
288 self._toc_mtimes = {'cur': 0, 'new': 0}
289 self._last_read = 0 # Records last time we read cur/new
290 self._skewfactor = 0.1 # Adjust if os/fs clocks are skewing
291
292 def add(self, message):
293 """Add message and return assigned key."""
294 tmp_file = self._create_tmp()
295 try:
296 self._dump_message(message, tmp_file)
297 except BaseException:
298 tmp_file.close()
299 os.remove(tmp_file.name)
300 raise
301 _sync_close(tmp_file)
302 if isinstance(message, MaildirMessage):
303 subdir = message.get_subdir()
304 suffix = self.colon + message.get_info()
305 if suffix == self.colon:
306 suffix = ''
307 else:
308 subdir = 'new'
309 suffix = ''
310 uniq = os.path.basename(tmp_file.name).split(self.colon)[0]
311 dest = os.path.join(self._path, subdir, uniq + suffix)
312 if isinstance(message, MaildirMessage):
313 os.utime(tmp_file.name,
314 (os.path.getatime(tmp_file.name), message.get_date()))
315 # No file modification should be done after the file is moved to its
316 # final position in order to prevent race conditions with changes
317 # from other programs
318 try:
319 try:
320 os.link(tmp_file.name, dest)
321 except (AttributeError, PermissionError):
322 os.rename(tmp_file.name, dest)
323 else:
324 os.remove(tmp_file.name)
325 except OSError as e:
326 os.remove(tmp_file.name)
327 if e.errno == errno.EEXIST:
328 raise ExternalClashError('Name clash with existing message: %s'
329 % dest)
330 else:
331 raise
332 return uniq
333
334 def remove(self, key):
335 """Remove the keyed message; raise KeyError if it doesn't exist."""
336 os.remove(os.path.join(self._path, self._lookup(key)))
337
338 def discard(self, key):
339 """If the keyed message exists, remove it."""
340 # This overrides an inapplicable implementation in the superclass.
341 try:
342 self.remove(key)
343 except (KeyError, FileNotFoundError):
344 pass
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 tmp_path = os.path.join(self._path, temp_subpath)
364 new_path = os.path.join(self._path, subdir, key + suffix)
365 if isinstance(message, MaildirMessage):
366 os.utime(tmp_path,
367 (os.path.getatime(tmp_path), message.get_date()))
368 # No file modification should be done after the file is moved to its
369 # final position in order to prevent race conditions with changes
370 # from other programs
371 os.rename(tmp_path, new_path)
372
373 def get_message(self, key):
374 """Return a Message representation or raise a KeyError."""
375 subpath = self._lookup(key)
376 with open(os.path.join(self._path, subpath), 'rb') as f:
377 if self._factory:
378 msg = self._factory(f)
379 else:
380 msg = MaildirMessage(f)
381 subdir, name = os.path.split(subpath)
382 msg.set_subdir(subdir)
383 if self.colon in name:
384 msg.set_info(name.split(self.colon)[-1])
385 msg.set_date(os.path.getmtime(os.path.join(self._path, subpath)))
386 return msg
387
388 def get_bytes(self, key):
389 """Return a bytes representation or raise a KeyError."""
390 with open(os.path.join(self._path, self._lookup(key)), 'rb') as f:
391 return f.read().replace(linesep, b'\n')
392
393 def get_file(self, key):
394 """Return a file-like representation or raise a KeyError."""
395 f = open(os.path.join(self._path, self._lookup(key)), 'rb')
396 return _ProxyFile(f)
397
398 def iterkeys(self):
399 """Return an iterator over keys."""
400 self._refresh()
401 for key in self._toc:
402 try:
403 self._lookup(key)
404 except KeyError:
405 continue
406 yield key
407
408 def __contains__(self, key):
409 """Return True if the keyed message exists, False otherwise."""
410 self._refresh()
411 return key in self._toc
412
413 def __len__(self):
414 """Return a count of messages in the mailbox."""
415 self._refresh()
416 return len(self._toc)
417
418 def flush(self):
419 """Write any pending changes to disk."""
420 # Maildir changes are always written immediately, so there's nothing
421 # to do.
422 pass
423
424 def lock(self):
425 """Lock the mailbox."""
426 return
427
428 def unlock(self):
429 """Unlock the mailbox if it is locked."""
430 return
431
432 def close(self):
433 """Flush and close the mailbox."""
434 return
435
436 def list_folders(self):
437 """Return a list of folder names."""
438 result = []
439 for entry in os.listdir(self._path):
440 if len(entry) > 1 and entry[0] == '.' and \
441 os.path.isdir(os.path.join(self._path, entry)):
442 result.append(entry[1:])
443 return result
444
445 def get_folder(self, folder):
446 """Return a Maildir instance for the named folder."""
447 return Maildir(os.path.join(self._path, '.' + folder),
448 factory=self._factory,
449 create=False)
450
451 def add_folder(self, folder):
452 """Create a folder and return a Maildir instance representing it."""
453 path = os.path.join(self._path, '.' + folder)
454 result = Maildir(path, factory=self._factory)
455 maildirfolder_path = os.path.join(path, 'maildirfolder')
456 if not os.path.exists(maildirfolder_path):
457 os.close(os.open(maildirfolder_path, os.O_CREAT | os.O_WRONLY,
458 0o666))
459 return result
460
461 def remove_folder(self, folder):
462 """Delete the named folder, which must be empty."""
463 path = os.path.join(self._path, '.' + folder)
464 for entry in os.listdir(os.path.join(path, 'new')) + \
465 os.listdir(os.path.join(path, 'cur')):
466 if len(entry) < 1 or entry[0] != '.':
467 raise NotEmptyError('Folder contains message(s): %s' % folder)
468 for entry in os.listdir(path):
469 if entry != 'new' and entry != 'cur' and entry != 'tmp' and \
470 os.path.isdir(os.path.join(path, entry)):
471 raise NotEmptyError("Folder contains subdirectory '%s': %s" %
472 (folder, entry))
473 for root, dirs, files in os.walk(path, topdown=False):
474 for entry in files:
475 os.remove(os.path.join(root, entry))
476 for entry in dirs:
477 os.rmdir(os.path.join(root, entry))
478 os.rmdir(path)
479
480 def clean(self):
481 """Delete old files in "tmp"."""
482 now = time.time()
483 for entry in os.listdir(os.path.join(self._path, 'tmp')):
484 path = os.path.join(self._path, 'tmp', entry)
485 if now - os.path.getatime(path) > 129600: # 60 * 60 * 36
486 os.remove(path)
487
488 _count = 1 # This is used to generate unique file names.
489
490 def _create_tmp(self):
491 """Create a file in the tmp subdirectory and open and return it."""
492 now = time.time()
493 hostname = socket.gethostname()
494 if '/' in hostname:
495 hostname = hostname.replace('/', r'\057')
496 if ':' in hostname:
497 hostname = hostname.replace(':', r'\072')
498 uniq = "%s.M%sP%sQ%s.%s" % (int(now), int(now % 1 * 1e6), os.getpid(),
499 Maildir._count, hostname)
500 path = os.path.join(self._path, 'tmp', uniq)
501 try:
502 os.stat(path)
503 except FileNotFoundError:
504 Maildir._count += 1
505 try:
506 return _create_carefully(path)
507 except FileExistsError:
508 pass
509
510 # Fall through to here if stat succeeded or open raised EEXIST.
511 raise ExternalClashError('Name clash prevented file creation: %s' %
512 path)
513
514 def _refresh(self):
515 """Update table of contents mapping."""
516 # If it has been less than two seconds since the last _refresh() call,
517 # we have to unconditionally re-read the mailbox just in case it has
518 # been modified, because os.path.mtime() has a 2 sec resolution in the
519 # most common worst case (FAT) and a 1 sec resolution typically. This
520 # results in a few unnecessary re-reads when _refresh() is called
521 # multiple times in that interval, but once the clock ticks over, we
522 # will only re-read as needed. Because the filesystem might be being
523 # served by an independent system with its own clock, we record and
524 # compare with the mtimes from the filesystem. Because the other
525 # system's clock might be skewing relative to our clock, we add an
526 # extra delta to our wait. The default is one tenth second, but is an
527 # instance variable and so can be adjusted if dealing with a
528 # particularly skewed or irregular system.
529 if time.time() - self._last_read > 2 + self._skewfactor:
530 refresh = False
531 for subdir in self._toc_mtimes:
532 mtime = os.path.getmtime(self._paths[subdir])
533 if mtime > self._toc_mtimes[subdir]:
534 refresh = True
535 self._toc_mtimes[subdir] = mtime
536 if not refresh:
537 return
538 # Refresh toc
539 self._toc = {}
540 for subdir in self._toc_mtimes:
541 path = self._paths[subdir]
542 for entry in os.listdir(path):
543 p = os.path.join(path, entry)
544 if os.path.isdir(p):
545 continue
546 uniq = entry.split(self.colon)[0]
547 self._toc[uniq] = os.path.join(subdir, entry)
548 self._last_read = time.time()
549
550 def _lookup(self, key):
551 """Use TOC to return subpath for given key, or raise a KeyError."""
552 try:
553 if os.path.exists(os.path.join(self._path, self._toc[key])):
554 return self._toc[key]
555 except KeyError:
556 pass
557 self._refresh()
558 try:
559 return self._toc[key]
560 except KeyError:
561 raise KeyError('No message with key: %s' % key) from None
562
563 # This method is for backward compatibility only.
564 def next(self):
565 """Return the next message in a one-time iteration."""
566 if not hasattr(self, '_onetime_keys'):
567 self._onetime_keys = self.iterkeys()
568 while True:
569 try:
570 return self[next(self._onetime_keys)]
571 except StopIteration:
572 return None
573 except KeyError:
574 continue
575
576
577 class _singlefileMailbox(Mailbox):
578 """A single-file mailbox."""
579
580 def __init__(self, path, factory=None, create=True):
581 """Initialize a single-file mailbox."""
582 Mailbox.__init__(self, path, factory, create)
583 try:
584 f = open(self._path, 'rb+')
585 except OSError as e:
586 if e.errno == errno.ENOENT:
587 if create:
588 f = open(self._path, 'wb+')
589 else:
590 raise NoSuchMailboxError(self._path)
591 elif e.errno in (errno.EACCES, errno.EROFS):
592 f = open(self._path, 'rb')
593 else:
594 raise
595 self._file = f
596 self._toc = None
597 self._next_key = 0
598 self._pending = False # No changes require rewriting the file.
599 self._pending_sync = False # No need to sync the file
600 self._locked = False
601 self._file_length = None # Used to record mailbox size
602
603 def add(self, message):
604 """Add message and return assigned key."""
605 self._lookup()
606 self._toc[self._next_key] = self._append_message(message)
607 self._next_key += 1
608 # _append_message appends the message to the mailbox file. We
609 # don't need a full rewrite + rename, sync is enough.
610 self._pending_sync = True
611 return self._next_key - 1
612
613 def remove(self, key):
614 """Remove the keyed message; raise KeyError if it doesn't exist."""
615 self._lookup(key)
616 del self._toc[key]
617 self._pending = True
618
619 def __setitem__(self, key, message):
620 """Replace the keyed message; raise KeyError if it doesn't exist."""
621 self._lookup(key)
622 self._toc[key] = self._append_message(message)
623 self._pending = True
624
625 def iterkeys(self):
626 """Return an iterator over keys."""
627 self._lookup()
628 yield from self._toc.keys()
629
630 def __contains__(self, key):
631 """Return True if the keyed message exists, False otherwise."""
632 self._lookup()
633 return key in self._toc
634
635 def __len__(self):
636 """Return a count of messages in the mailbox."""
637 self._lookup()
638 return len(self._toc)
639
640 def lock(self):
641 """Lock the mailbox."""
642 if not self._locked:
643 _lock_file(self._file)
644 self._locked = True
645
646 def unlock(self):
647 """Unlock the mailbox if it is locked."""
648 if self._locked:
649 _unlock_file(self._file)
650 self._locked = False
651
652 def flush(self):
653 """Write any pending changes to disk."""
654 if not self._pending:
655 if self._pending_sync:
656 # Messages have only been added, so syncing the file
657 # is enough.
658 _sync_flush(self._file)
659 self._pending_sync = False
660 return
661
662 # In order to be writing anything out at all, self._toc must
663 # already have been generated (and presumably has been modified
664 # by adding or deleting an item).
665 assert self._toc is not None
666
667 # Check length of self._file; if it's changed, some other process
668 # has modified the mailbox since we scanned it.
669 self._file.seek(0, 2)
670 cur_len = self._file.tell()
671 if cur_len != self._file_length:
672 raise ExternalClashError('Size of mailbox file changed '
673 '(expected %i, found %i)' %
674 (self._file_length, cur_len))
675
676 new_file = _create_temporary(self._path)
677 try:
678 new_toc = {}
679 self._pre_mailbox_hook(new_file)
680 for key in sorted(self._toc.keys()):
681 start, stop = self._toc[key]
682 self._file.seek(start)
683 self._pre_message_hook(new_file)
684 new_start = new_file.tell()
685 while True:
686 buffer = self._file.read(min(4096,
687 stop - self._file.tell()))
688 if not buffer:
689 break
690 new_file.write(buffer)
691 new_toc[key] = (new_start, new_file.tell())
692 self._post_message_hook(new_file)
693 self._file_length = new_file.tell()
694 except:
695 new_file.close()
696 os.remove(new_file.name)
697 raise
698 _sync_close(new_file)
699 # self._file is about to get replaced, so no need to sync.
700 self._file.close()
701 # Make sure the new file's mode is the same as the old file's
702 mode = os.stat(self._path).st_mode
703 os.chmod(new_file.name, mode)
704 try:
705 os.rename(new_file.name, self._path)
706 except FileExistsError:
707 os.remove(self._path)
708 os.rename(new_file.name, self._path)
709 self._file = open(self._path, 'rb+')
710 self._toc = new_toc
711 self._pending = False
712 self._pending_sync = False
713 if self._locked:
714 _lock_file(self._file, dotlock=False)
715
716 def _pre_mailbox_hook(self, f):
717 """Called before writing the mailbox to file f."""
718 return
719
720 def _pre_message_hook(self, f):
721 """Called before writing each message to file f."""
722 return
723
724 def _post_message_hook(self, f):
725 """Called after writing each message to file f."""
726 return
727
728 def close(self):
729 """Flush and close the mailbox."""
730 try:
731 self.flush()
732 finally:
733 try:
734 if self._locked:
735 self.unlock()
736 finally:
737 self._file.close() # Sync has been done by self.flush() above.
738
739 def _lookup(self, key=None):
740 """Return (start, stop) or raise KeyError."""
741 if self._toc is None:
742 self._generate_toc()
743 if key is not None:
744 try:
745 return self._toc[key]
746 except KeyError:
747 raise KeyError('No message with key: %s' % key) from None
748
749 def _append_message(self, message):
750 """Append message to mailbox and return (start, stop) offsets."""
751 self._file.seek(0, 2)
752 before = self._file.tell()
753 if len(self._toc) == 0 and not self._pending:
754 # This is the first message, and the _pre_mailbox_hook
755 # hasn't yet been called. If self._pending is True,
756 # messages have been removed, so _pre_mailbox_hook must
757 # have been called already.
758 self._pre_mailbox_hook(self._file)
759 try:
760 self._pre_message_hook(self._file)
761 offsets = self._install_message(message)
762 self._post_message_hook(self._file)
763 except BaseException:
764 self._file.truncate(before)
765 raise
766 self._file.flush()
767 self._file_length = self._file.tell() # Record current length of mailbox
768 return offsets
769
770
771
772 class _mboxMMDF(_singlefileMailbox):
773 """An mbox or MMDF mailbox."""
774
775 _mangle_from_ = True
776
777 def get_message(self, key):
778 """Return a Message representation or raise a KeyError."""
779 start, stop = self._lookup(key)
780 self._file.seek(start)
781 from_line = self._file.readline().replace(linesep, b'').decode('ascii')
782 string = self._file.read(stop - self._file.tell())
783 msg = self._message_factory(string.replace(linesep, b'\n'))
784 msg.set_unixfrom(from_line)
785 msg.set_from(from_line[5:])
786 return msg
787
788 def get_string(self, key, from_=False):
789 """Return a string representation or raise a KeyError."""
790 return email.message_from_bytes(
791 self.get_bytes(key, from_)).as_string(unixfrom=from_)
792
793 def get_bytes(self, key, from_=False):
794 """Return a string representation or raise a KeyError."""
795 start, stop = self._lookup(key)
796 self._file.seek(start)
797 if not from_:
798 self._file.readline()
799 string = self._file.read(stop - self._file.tell())
800 return string.replace(linesep, b'\n')
801
802 def get_file(self, key, from_=False):
803 """Return a file-like representation or raise a KeyError."""
804 start, stop = self._lookup(key)
805 self._file.seek(start)
806 if not from_:
807 self._file.readline()
808 return _PartialFile(self._file, self._file.tell(), stop)
809
810 def _install_message(self, message):
811 """Format a message and blindly write to self._file."""
812 from_line = None
813 if isinstance(message, str):
814 message = self._string_to_bytes(message)
815 if isinstance(message, bytes) and message.startswith(b'From '):
816 newline = message.find(b'\n')
817 if newline != -1:
818 from_line = message[:newline]
819 message = message[newline + 1:]
820 else:
821 from_line = message
822 message = b''
823 elif isinstance(message, _mboxMMDFMessage):
824 author = message.get_from().encode('ascii')
825 from_line = b'From ' + author
826 elif isinstance(message, email.message.Message):
827 from_line = message.get_unixfrom() # May be None.
828 if from_line is not None:
829 from_line = from_line.encode('ascii')
830 if from_line is None:
831 from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
832 start = self._file.tell()
833 self._file.write(from_line + linesep)
834 self._dump_message(message, self._file, self._mangle_from_)
835 stop = self._file.tell()
836 return (start, stop)
837
838
839 class mbox(_mboxMMDF):
840 """A classic mbox mailbox."""
841
842 _mangle_from_ = True
843
844 # All messages must end in a newline character, and
845 # _post_message_hooks outputs an empty line between messages.
846 _append_newline = True
847
848 def __init__(self, path, factory=None, create=True):
849 """Initialize an mbox mailbox."""
850 self._message_factory = mboxMessage
851 _mboxMMDF.__init__(self, path, factory, create)
852
853 def _post_message_hook(self, f):
854 """Called after writing each message to file f."""
855 f.write(linesep)
856
857 def _generate_toc(self):
858 """Generate key-to-(start, stop) table of contents."""
859 starts, stops = [], []
860 last_was_empty = False
861 self._file.seek(0)
862 while True:
863 line_pos = self._file.tell()
864 line = self._file.readline()
865 if line.startswith(b'From '):
866 if len(stops) < len(starts):
867 if last_was_empty:
868 stops.append(line_pos - len(linesep))
869 else:
870 # The last line before the "From " line wasn't
871 # blank, but we consider it a start of a
872 # message anyway.
873 stops.append(line_pos)
874 starts.append(line_pos)
875 last_was_empty = False
876 elif not line:
877 if last_was_empty:
878 stops.append(line_pos - len(linesep))
879 else:
880 stops.append(line_pos)
881 break
882 elif line == linesep:
883 last_was_empty = True
884 else:
885 last_was_empty = False
886 self._toc = dict(enumerate(zip(starts, stops)))
887 self._next_key = len(self._toc)
888 self._file_length = self._file.tell()
889
890
891 class MMDF(_mboxMMDF):
892 """An MMDF mailbox."""
893
894 def __init__(self, path, factory=None, create=True):
895 """Initialize an MMDF mailbox."""
896 self._message_factory = MMDFMessage
897 _mboxMMDF.__init__(self, path, factory, create)
898
899 def _pre_message_hook(self, f):
900 """Called before writing each message to file f."""
901 f.write(b'\001\001\001\001' + linesep)
902
903 def _post_message_hook(self, f):
904 """Called after writing each message to file f."""
905 f.write(linesep + b'\001\001\001\001' + linesep)
906
907 def _generate_toc(self):
908 """Generate key-to-(start, stop) table of contents."""
909 starts, stops = [], []
910 self._file.seek(0)
911 next_pos = 0
912 while True:
913 line_pos = next_pos
914 line = self._file.readline()
915 next_pos = self._file.tell()
916 if line.startswith(b'\001\001\001\001' + linesep):
917 starts.append(next_pos)
918 while True:
919 line_pos = next_pos
920 line = self._file.readline()
921 next_pos = self._file.tell()
922 if line == b'\001\001\001\001' + linesep:
923 stops.append(line_pos - len(linesep))
924 break
925 elif not line:
926 stops.append(line_pos)
927 break
928 elif not line:
929 break
930 self._toc = dict(enumerate(zip(starts, stops)))
931 self._next_key = len(self._toc)
932 self._file.seek(0, 2)
933 self._file_length = self._file.tell()
934
935
936 class MH(Mailbox):
937 """An MH mailbox."""
938
939 def __init__(self, path, factory=None, create=True):
940 """Initialize an MH instance."""
941 Mailbox.__init__(self, path, factory, create)
942 if not os.path.exists(self._path):
943 if create:
944 os.mkdir(self._path, 0o700)
945 os.close(os.open(os.path.join(self._path, '.mh_sequences'),
946 os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
947 else:
948 raise NoSuchMailboxError(self._path)
949 self._locked = False
950
951 def add(self, message):
952 """Add message and return assigned key."""
953 keys = self.keys()
954 if len(keys) == 0:
955 new_key = 1
956 else:
957 new_key = max(keys) + 1
958 new_path = os.path.join(self._path, str(new_key))
959 f = _create_carefully(new_path)
960 closed = False
961 try:
962 if self._locked:
963 _lock_file(f)
964 try:
965 try:
966 self._dump_message(message, f)
967 except BaseException:
968 # Unlock and close so it can be deleted on Windows
969 if self._locked:
970 _unlock_file(f)
971 _sync_close(f)
972 closed = True
973 os.remove(new_path)
974 raise
975 if isinstance(message, MHMessage):
976 self._dump_sequences(message, new_key)
977 finally:
978 if self._locked:
979 _unlock_file(f)
980 finally:
981 if not closed:
982 _sync_close(f)
983 return new_key
984
985 def remove(self, key):
986 """Remove the keyed message; raise KeyError if it doesn't exist."""
987 path = os.path.join(self._path, str(key))
988 try:
989 f = open(path, 'rb+')
990 except OSError as e:
991 if e.errno == errno.ENOENT:
992 raise KeyError('No message with key: %s' % key)
993 else:
994 raise
995 else:
996 f.close()
997 os.remove(path)
998
999 def __setitem__(self, key, message):
1000 """Replace the keyed message; raise KeyError if it doesn't exist."""
1001 path = os.path.join(self._path, str(key))
1002 try:
1003 f = open(path, 'rb+')
1004 except OSError as e:
1005 if e.errno == errno.ENOENT:
1006 raise KeyError('No message with key: %s' % key)
1007 else:
1008 raise
1009 try:
1010 if self._locked:
1011 _lock_file(f)
1012 try:
1013 os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
1014 self._dump_message(message, f)
1015 if isinstance(message, MHMessage):
1016 self._dump_sequences(message, key)
1017 finally:
1018 if self._locked:
1019 _unlock_file(f)
1020 finally:
1021 _sync_close(f)
1022
1023 def get_message(self, key):
1024 """Return a Message representation or raise a KeyError."""
1025 try:
1026 if self._locked:
1027 f = open(os.path.join(self._path, str(key)), 'rb+')
1028 else:
1029 f = open(os.path.join(self._path, str(key)), 'rb')
1030 except OSError as e:
1031 if e.errno == errno.ENOENT:
1032 raise KeyError('No message with key: %s' % key)
1033 else:
1034 raise
1035 with f:
1036 if self._locked:
1037 _lock_file(f)
1038 try:
1039 msg = MHMessage(f)
1040 finally:
1041 if self._locked:
1042 _unlock_file(f)
1043 for name, key_list in self.get_sequences().items():
1044 if key in key_list:
1045 msg.add_sequence(name)
1046 return msg
1047
1048 def get_bytes(self, key):
1049 """Return a bytes representation or raise a KeyError."""
1050 try:
1051 if self._locked:
1052 f = open(os.path.join(self._path, str(key)), 'rb+')
1053 else:
1054 f = open(os.path.join(self._path, str(key)), 'rb')
1055 except OSError as e:
1056 if e.errno == errno.ENOENT:
1057 raise KeyError('No message with key: %s' % key)
1058 else:
1059 raise
1060 with f:
1061 if self._locked:
1062 _lock_file(f)
1063 try:
1064 return f.read().replace(linesep, b'\n')
1065 finally:
1066 if self._locked:
1067 _unlock_file(f)
1068
1069 def get_file(self, key):
1070 """Return a file-like representation or raise a KeyError."""
1071 try:
1072 f = open(os.path.join(self._path, str(key)), 'rb')
1073 except OSError as e:
1074 if e.errno == errno.ENOENT:
1075 raise KeyError('No message with key: %s' % key)
1076 else:
1077 raise
1078 return _ProxyFile(f)
1079
1080 def iterkeys(self):
1081 """Return an iterator over keys."""
1082 return iter(sorted(int(entry) for entry in os.listdir(self._path)
1083 if entry.isdigit()))
1084
1085 def __contains__(self, key):
1086 """Return True if the keyed message exists, False otherwise."""
1087 return os.path.exists(os.path.join(self._path, str(key)))
1088
1089 def __len__(self):
1090 """Return a count of messages in the mailbox."""
1091 return len(list(self.iterkeys()))
1092
1093 def lock(self):
1094 """Lock the mailbox."""
1095 if not self._locked:
1096 self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
1097 _lock_file(self._file)
1098 self._locked = True
1099
1100 def unlock(self):
1101 """Unlock the mailbox if it is locked."""
1102 if self._locked:
1103 _unlock_file(self._file)
1104 _sync_close(self._file)
1105 del self._file
1106 self._locked = False
1107
1108 def flush(self):
1109 """Write any pending changes to the disk."""
1110 return
1111
1112 def close(self):
1113 """Flush and close the mailbox."""
1114 if self._locked:
1115 self.unlock()
1116
1117 def list_folders(self):
1118 """Return a list of folder names."""
1119 result = []
1120 for entry in os.listdir(self._path):
1121 if os.path.isdir(os.path.join(self._path, entry)):
1122 result.append(entry)
1123 return result
1124
1125 def get_folder(self, folder):
1126 """Return an MH instance for the named folder."""
1127 return MH(os.path.join(self._path, folder),
1128 factory=self._factory, create=False)
1129
1130 def add_folder(self, folder):
1131 """Create a folder and return an MH instance representing it."""
1132 return MH(os.path.join(self._path, folder),
1133 factory=self._factory)
1134
1135 def remove_folder(self, folder):
1136 """Delete the named folder, which must be empty."""
1137 path = os.path.join(self._path, folder)
1138 entries = os.listdir(path)
1139 if entries == ['.mh_sequences']:
1140 os.remove(os.path.join(path, '.mh_sequences'))
1141 elif entries == []:
1142 pass
1143 else:
1144 raise NotEmptyError('Folder not empty: %s' % self._path)
1145 os.rmdir(path)
1146
1147 def get_sequences(self):
1148 """Return a name-to-key-list dictionary to define each sequence."""
1149 results = {}
1150 with open(os.path.join(self._path, '.mh_sequences'), 'r', encoding='ASCII') as f:
1151 all_keys = set(self.keys())
1152 for line in f:
1153 try:
1154 name, contents = line.split(':')
1155 keys = set()
1156 for spec in contents.split():
1157 if spec.isdigit():
1158 keys.add(int(spec))
1159 else:
1160 start, stop = (int(x) for x in spec.split('-'))
1161 keys.update(range(start, stop + 1))
1162 results[name] = [key for key in sorted(keys) \
1163 if key in all_keys]
1164 if len(results[name]) == 0:
1165 del results[name]
1166 except ValueError:
1167 raise FormatError('Invalid sequence specification: %s' %
1168 line.rstrip())
1169 return results
1170
1171 def set_sequences(self, sequences):
1172 """Set sequences using the given name-to-key-list dictionary."""
1173 f = open(os.path.join(self._path, '.mh_sequences'), 'r+', encoding='ASCII')
1174 try:
1175 os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
1176 for name, keys in sequences.items():
1177 if len(keys) == 0:
1178 continue
1179 f.write(name + ':')
1180 prev = None
1181 completing = False
1182 for key in sorted(set(keys)):
1183 if key - 1 == prev:
1184 if not completing:
1185 completing = True
1186 f.write('-')
1187 elif completing:
1188 completing = False
1189 f.write('%s %s' % (prev, key))
1190 else:
1191 f.write(' %s' % key)
1192 prev = key
1193 if completing:
1194 f.write(str(prev) + '\n')
1195 else:
1196 f.write('\n')
1197 finally:
1198 _sync_close(f)
1199
1200 def pack(self):
1201 """Re-name messages to eliminate numbering gaps. Invalidates keys."""
1202 sequences = self.get_sequences()
1203 prev = 0
1204 changes = []
1205 for key in self.iterkeys():
1206 if key - 1 != prev:
1207 changes.append((key, prev + 1))
1208 try:
1209 os.link(os.path.join(self._path, str(key)),
1210 os.path.join(self._path, str(prev + 1)))
1211 except (AttributeError, PermissionError):
1212 os.rename(os.path.join(self._path, str(key)),
1213 os.path.join(self._path, str(prev + 1)))
1214 else:
1215 os.unlink(os.path.join(self._path, str(key)))
1216 prev += 1
1217 self._next_key = prev + 1
1218 if len(changes) == 0:
1219 return
1220 for name, key_list in sequences.items():
1221 for old, new in changes:
1222 if old in key_list:
1223 key_list[key_list.index(old)] = new
1224 self.set_sequences(sequences)
1225
1226 def _dump_sequences(self, message, key):
1227 """Inspect a new MHMessage and update sequences appropriately."""
1228 pending_sequences = message.get_sequences()
1229 all_sequences = self.get_sequences()
1230 for name, key_list in all_sequences.items():
1231 if name in pending_sequences:
1232 key_list.append(key)
1233 elif key in key_list:
1234 del key_list[key_list.index(key)]
1235 for sequence in pending_sequences:
1236 if sequence not in all_sequences:
1237 all_sequences[sequence] = [key]
1238 self.set_sequences(all_sequences)
1239
1240
1241 class Babyl(_singlefileMailbox):
1242 """An Rmail-style Babyl mailbox."""
1243
1244 _special_labels = frozenset({'unseen', 'deleted', 'filed', 'answered',
1245 'forwarded', 'edited', 'resent'})
1246
1247 def __init__(self, path, factory=None, create=True):
1248 """Initialize a Babyl mailbox."""
1249 _singlefileMailbox.__init__(self, path, factory, create)
1250 self._labels = {}
1251
1252 def add(self, message):
1253 """Add message and return assigned key."""
1254 key = _singlefileMailbox.add(self, message)
1255 if isinstance(message, BabylMessage):
1256 self._labels[key] = message.get_labels()
1257 return key
1258
1259 def remove(self, key):
1260 """Remove the keyed message; raise KeyError if it doesn't exist."""
1261 _singlefileMailbox.remove(self, key)
1262 if key in self._labels:
1263 del self._labels[key]
1264
1265 def __setitem__(self, key, message):
1266 """Replace the keyed message; raise KeyError if it doesn't exist."""
1267 _singlefileMailbox.__setitem__(self, key, message)
1268 if isinstance(message, BabylMessage):
1269 self._labels[key] = message.get_labels()
1270
1271 def get_message(self, key):
1272 """Return a Message representation or raise a KeyError."""
1273 start, stop = self._lookup(key)
1274 self._file.seek(start)
1275 self._file.readline() # Skip b'1,' line specifying labels.
1276 original_headers = io.BytesIO()
1277 while True:
1278 line = self._file.readline()
1279 if line == b'*** EOOH ***' + linesep or not line:
1280 break
1281 original_headers.write(line.replace(linesep, b'\n'))
1282 visible_headers = io.BytesIO()
1283 while True:
1284 line = self._file.readline()
1285 if line == linesep or not line:
1286 break
1287 visible_headers.write(line.replace(linesep, b'\n'))
1288 # Read up to the stop, or to the end
1289 n = stop - self._file.tell()
1290 assert n >= 0
1291 body = self._file.read(n)
1292 body = body.replace(linesep, b'\n')
1293 msg = BabylMessage(original_headers.getvalue() + body)
1294 msg.set_visible(visible_headers.getvalue())
1295 if key in self._labels:
1296 msg.set_labels(self._labels[key])
1297 return msg
1298
1299 def get_bytes(self, key):
1300 """Return a string representation or raise a KeyError."""
1301 start, stop = self._lookup(key)
1302 self._file.seek(start)
1303 self._file.readline() # Skip b'1,' line specifying labels.
1304 original_headers = io.BytesIO()
1305 while True:
1306 line = self._file.readline()
1307 if line == b'*** EOOH ***' + linesep or not line:
1308 break
1309 original_headers.write(line.replace(linesep, b'\n'))
1310 while True:
1311 line = self._file.readline()
1312 if line == linesep or not line:
1313 break
1314 headers = original_headers.getvalue()
1315 n = stop - self._file.tell()
1316 assert n >= 0
1317 data = self._file.read(n)
1318 data = data.replace(linesep, b'\n')
1319 return headers + data
1320
1321 def get_file(self, key):
1322 """Return a file-like representation or raise a KeyError."""
1323 return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep))
1324
1325 def get_labels(self):
1326 """Return a list of user-defined labels in the mailbox."""
1327 self._lookup()
1328 labels = set()
1329 for label_list in self._labels.values():
1330 labels.update(label_list)
1331 labels.difference_update(self._special_labels)
1332 return list(labels)
1333
1334 def _generate_toc(self):
1335 """Generate key-to-(start, stop) table of contents."""
1336 starts, stops = [], []
1337 self._file.seek(0)
1338 next_pos = 0
1339 label_lists = []
1340 while True:
1341 line_pos = next_pos
1342 line = self._file.readline()
1343 next_pos = self._file.tell()
1344 if line == b'\037\014' + linesep:
1345 if len(stops) < len(starts):
1346 stops.append(line_pos - len(linesep))
1347 starts.append(next_pos)
1348 labels = [label.strip() for label
1349 in self._file.readline()[1:].split(b',')
1350 if label.strip()]
1351 label_lists.append(labels)
1352 elif line == b'\037' or line == b'\037' + linesep:
1353 if len(stops) < len(starts):
1354 stops.append(line_pos - len(linesep))
1355 elif not line:
1356 stops.append(line_pos - len(linesep))
1357 break
1358 self._toc = dict(enumerate(zip(starts, stops)))
1359 self._labels = dict(enumerate(label_lists))
1360 self._next_key = len(self._toc)
1361 self._file.seek(0, 2)
1362 self._file_length = self._file.tell()
1363
1364 def _pre_mailbox_hook(self, f):
1365 """Called before writing the mailbox to file f."""
1366 babyl = b'BABYL OPTIONS:' + linesep
1367 babyl += b'Version: 5' + linesep
1368 labels = self.get_labels()
1369 labels = (label.encode() for label in labels)
1370 babyl += b'Labels:' + b','.join(labels) + linesep
1371 babyl += b'\037'
1372 f.write(babyl)
1373
1374 def _pre_message_hook(self, f):
1375 """Called before writing each message to file f."""
1376 f.write(b'\014' + linesep)
1377
1378 def _post_message_hook(self, f):
1379 """Called after writing each message to file f."""
1380 f.write(linesep + b'\037')
1381
1382 def _install_message(self, message):
1383 """Write message contents and return (start, stop)."""
1384 start = self._file.tell()
1385 if isinstance(message, BabylMessage):
1386 special_labels = []
1387 labels = []
1388 for label in message.get_labels():
1389 if label in self._special_labels:
1390 special_labels.append(label)
1391 else:
1392 labels.append(label)
1393 self._file.write(b'1')
1394 for label in special_labels:
1395 self._file.write(b', ' + label.encode())
1396 self._file.write(b',,')
1397 for label in labels:
1398 self._file.write(b' ' + label.encode() + b',')
1399 self._file.write(linesep)
1400 else:
1401 self._file.write(b'1,,' + linesep)
1402 if isinstance(message, email.message.Message):
1403 orig_buffer = io.BytesIO()
1404 orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0)
1405 orig_generator.flatten(message)
1406 orig_buffer.seek(0)
1407 while True:
1408 line = orig_buffer.readline()
1409 self._file.write(line.replace(b'\n', linesep))
1410 if line == b'\n' or not line:
1411 break
1412 self._file.write(b'*** EOOH ***' + linesep)
1413 if isinstance(message, BabylMessage):
1414 vis_buffer = io.BytesIO()
1415 vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0)
1416 vis_generator.flatten(message.get_visible())
1417 while True:
1418 line = vis_buffer.readline()
1419 self._file.write(line.replace(b'\n', linesep))
1420 if line == b'\n' or not line:
1421 break
1422 else:
1423 orig_buffer.seek(0)
1424 while True:
1425 line = orig_buffer.readline()
1426 self._file.write(line.replace(b'\n', linesep))
1427 if line == b'\n' or not line:
1428 break
1429 while True:
1430 buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
1431 if not buffer:
1432 break
1433 self._file.write(buffer.replace(b'\n', linesep))
1434 elif isinstance(message, (bytes, str, io.StringIO)):
1435 if isinstance(message, io.StringIO):
1436 warnings.warn("Use of StringIO input is deprecated, "
1437 "use BytesIO instead", DeprecationWarning, 3)
1438 message = message.getvalue()
1439 if isinstance(message, str):
1440 message = self._string_to_bytes(message)
1441 body_start = message.find(b'\n\n') + 2
1442 if body_start - 2 != -1:
1443 self._file.write(message[:body_start].replace(b'\n', linesep))
1444 self._file.write(b'*** EOOH ***' + linesep)
1445 self._file.write(message[:body_start].replace(b'\n', linesep))
1446 self._file.write(message[body_start:].replace(b'\n', linesep))
1447 else:
1448 self._file.write(b'*** EOOH ***' + linesep + linesep)
1449 self._file.write(message.replace(b'\n', linesep))
1450 elif hasattr(message, 'readline'):
1451 if hasattr(message, 'buffer'):
1452 warnings.warn("Use of text mode files is deprecated, "
1453 "use a binary mode file instead", DeprecationWarning, 3)
1454 message = message.buffer
1455 original_pos = message.tell()
1456 first_pass = True
1457 while True:
1458 line = message.readline()
1459 # Universal newline support.
1460 if line.endswith(b'\r\n'):
1461 line = line[:-2] + b'\n'
1462 elif line.endswith(b'\r'):
1463 line = line[:-1] + b'\n'
1464 self._file.write(line.replace(b'\n', linesep))
1465 if line == b'\n' or not line:
1466 if first_pass:
1467 first_pass = False
1468 self._file.write(b'*** EOOH ***' + linesep)
1469 message.seek(original_pos)
1470 else:
1471 break
1472 while True:
1473 line = message.readline()
1474 if not line:
1475 break
1476 # Universal newline support.
1477 if line.endswith(b'\r\n'):
1478 line = line[:-2] + linesep
1479 elif line.endswith(b'\r'):
1480 line = line[:-1] + linesep
1481 elif line.endswith(b'\n'):
1482 line = line[:-1] + linesep
1483 self._file.write(line)
1484 else:
1485 raise TypeError('Invalid message type: %s' % type(message))
1486 stop = self._file.tell()
1487 return (start, stop)
1488
1489
1490 class Message(email.message.Message):
1491 """Message with mailbox-format-specific properties."""
1492
1493 def __init__(self, message=None):
1494 """Initialize a Message instance."""
1495 if isinstance(message, email.message.Message):
1496 self._become_message(copy.deepcopy(message))
1497 if isinstance(message, Message):
1498 message._explain_to(self)
1499 elif isinstance(message, bytes):
1500 self._become_message(email.message_from_bytes(message))
1501 elif isinstance(message, str):
1502 self._become_message(email.message_from_string(message))
1503 elif isinstance(message, io.TextIOWrapper):
1504 self._become_message(email.message_from_file(message))
1505 elif hasattr(message, "read"):
1506 self._become_message(email.message_from_binary_file(message))
1507 elif message is None:
1508 email.message.Message.__init__(self)
1509 else:
1510 raise TypeError('Invalid message type: %s' % type(message))
1511
1512 def _become_message(self, message):
1513 """Assume the non-format-specific state of message."""
1514 type_specific = getattr(message, '_type_specific_attributes', [])
1515 for name in message.__dict__:
1516 if name not in type_specific:
1517 self.__dict__[name] = message.__dict__[name]
1518
1519 def _explain_to(self, message):
1520 """Copy format-specific state to message insofar as possible."""
1521 if isinstance(message, Message):
1522 return # There's nothing format-specific to explain.
1523 else:
1524 raise TypeError('Cannot convert to specified type')
1525
1526
1527 class MaildirMessage(Message):
1528 """Message with Maildir-specific properties."""
1529
1530 _type_specific_attributes = ['_subdir', '_info', '_date']
1531
1532 def __init__(self, message=None):
1533 """Initialize a MaildirMessage instance."""
1534 self._subdir = 'new'
1535 self._info = ''
1536 self._date = time.time()
1537 Message.__init__(self, message)
1538
1539 def get_subdir(self):
1540 """Return 'new' or 'cur'."""
1541 return self._subdir
1542
1543 def set_subdir(self, subdir):
1544 """Set subdir to 'new' or 'cur'."""
1545 if subdir == 'new' or subdir == 'cur':
1546 self._subdir = subdir
1547 else:
1548 raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
1549
1550 def get_flags(self):
1551 """Return as a string the flags that are set."""
1552 if self._info.startswith('2,'):
1553 return self._info[2:]
1554 else:
1555 return ''
1556
1557 def set_flags(self, flags):
1558 """Set the given flags and unset all others."""
1559 self._info = '2,' + ''.join(sorted(flags))
1560
1561 def add_flag(self, flag):
1562 """Set the given flag(s) without changing others."""
1563 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1564
1565 def remove_flag(self, flag):
1566 """Unset the given string flag(s) without changing others."""
1567 if self.get_flags():
1568 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1569
1570 def get_date(self):
1571 """Return delivery date of message, in seconds since the epoch."""
1572 return self._date
1573
1574 def set_date(self, date):
1575 """Set delivery date of message, in seconds since the epoch."""
1576 try:
1577 self._date = float(date)
1578 except ValueError:
1579 raise TypeError("can't convert to float: %s" % date) from None
1580
1581 def get_info(self):
1582 """Get the message's "info" as a string."""
1583 return self._info
1584
1585 def set_info(self, info):
1586 """Set the message's "info" string."""
1587 if isinstance(info, str):
1588 self._info = info
1589 else:
1590 raise TypeError('info must be a string: %s' % type(info))
1591
1592 def _explain_to(self, message):
1593 """Copy Maildir-specific state to message insofar as possible."""
1594 if isinstance(message, MaildirMessage):
1595 message.set_flags(self.get_flags())
1596 message.set_subdir(self.get_subdir())
1597 message.set_date(self.get_date())
1598 elif isinstance(message, _mboxMMDFMessage):
1599 flags = set(self.get_flags())
1600 if 'S' in flags:
1601 message.add_flag('R')
1602 if self.get_subdir() == 'cur':
1603 message.add_flag('O')
1604 if 'T' in flags:
1605 message.add_flag('D')
1606 if 'F' in flags:
1607 message.add_flag('F')
1608 if 'R' in flags:
1609 message.add_flag('A')
1610 message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
1611 elif isinstance(message, MHMessage):
1612 flags = set(self.get_flags())
1613 if 'S' not in flags:
1614 message.add_sequence('unseen')
1615 if 'R' in flags:
1616 message.add_sequence('replied')
1617 if 'F' in flags:
1618 message.add_sequence('flagged')
1619 elif isinstance(message, BabylMessage):
1620 flags = set(self.get_flags())
1621 if 'S' not in flags:
1622 message.add_label('unseen')
1623 if 'T' in flags:
1624 message.add_label('deleted')
1625 if 'R' in flags:
1626 message.add_label('answered')
1627 if 'P' in flags:
1628 message.add_label('forwarded')
1629 elif isinstance(message, Message):
1630 pass
1631 else:
1632 raise TypeError('Cannot convert to specified type: %s' %
1633 type(message))
1634
1635
1636 class _mboxMMDFMessage(Message):
1637 """Message with mbox- or MMDF-specific properties."""
1638
1639 _type_specific_attributes = ['_from']
1640
1641 def __init__(self, message=None):
1642 """Initialize an mboxMMDFMessage instance."""
1643 self.set_from('MAILER-DAEMON', True)
1644 if isinstance(message, email.message.Message):
1645 unixfrom = message.get_unixfrom()
1646 if unixfrom is not None and unixfrom.startswith('From '):
1647 self.set_from(unixfrom[5:])
1648 Message.__init__(self, message)
1649
1650 def get_from(self):
1651 """Return contents of "From " line."""
1652 return self._from
1653
1654 def set_from(self, from_, time_=None):
1655 """Set "From " line, formatting and appending time_ if specified."""
1656 if time_ is not None:
1657 if time_ is True:
1658 time_ = time.gmtime()
1659 from_ += ' ' + time.asctime(time_)
1660 self._from = from_
1661
1662 def get_flags(self):
1663 """Return as a string the flags that are set."""
1664 return self.get('Status', '') + self.get('X-Status', '')
1665
1666 def set_flags(self, flags):
1667 """Set the given flags and unset all others."""
1668 flags = set(flags)
1669 status_flags, xstatus_flags = '', ''
1670 for flag in ('R', 'O'):
1671 if flag in flags:
1672 status_flags += flag
1673 flags.remove(flag)
1674 for flag in ('D', 'F', 'A'):
1675 if flag in flags:
1676 xstatus_flags += flag
1677 flags.remove(flag)
1678 xstatus_flags += ''.join(sorted(flags))
1679 try:
1680 self.replace_header('Status', status_flags)
1681 except KeyError:
1682 self.add_header('Status', status_flags)
1683 try:
1684 self.replace_header('X-Status', xstatus_flags)
1685 except KeyError:
1686 self.add_header('X-Status', xstatus_flags)
1687
1688 def add_flag(self, flag):
1689 """Set the given flag(s) without changing others."""
1690 self.set_flags(''.join(set(self.get_flags()) | set(flag)))
1691
1692 def remove_flag(self, flag):
1693 """Unset the given string flag(s) without changing others."""
1694 if 'Status' in self or 'X-Status' in self:
1695 self.set_flags(''.join(set(self.get_flags()) - set(flag)))
1696
1697 def _explain_to(self, message):
1698 """Copy mbox- or MMDF-specific state to message insofar as possible."""
1699 if isinstance(message, MaildirMessage):
1700 flags = set(self.get_flags())
1701 if 'O' in flags:
1702 message.set_subdir('cur')
1703 if 'F' in flags:
1704 message.add_flag('F')
1705 if 'A' in flags:
1706 message.add_flag('R')
1707 if 'R' in flags:
1708 message.add_flag('S')
1709 if 'D' in flags:
1710 message.add_flag('T')
1711 del message['status']
1712 del message['x-status']
1713 maybe_date = ' '.join(self.get_from().split()[-5:])
1714 try:
1715 message.set_date(calendar.timegm(time.strptime(maybe_date,
1716 '%a %b %d %H:%M:%S %Y')))
1717 except (ValueError, OverflowError):
1718 pass
1719 elif isinstance(message, _mboxMMDFMessage):
1720 message.set_flags(self.get_flags())
1721 message.set_from(self.get_from())
1722 elif isinstance(message, MHMessage):
1723 flags = set(self.get_flags())
1724 if 'R' not in flags:
1725 message.add_sequence('unseen')
1726 if 'A' in flags:
1727 message.add_sequence('replied')
1728 if 'F' in flags:
1729 message.add_sequence('flagged')
1730 del message['status']
1731 del message['x-status']
1732 elif isinstance(message, BabylMessage):
1733 flags = set(self.get_flags())
1734 if 'R' not in flags:
1735 message.add_label('unseen')
1736 if 'D' in flags:
1737 message.add_label('deleted')
1738 if 'A' in flags:
1739 message.add_label('answered')
1740 del message['status']
1741 del message['x-status']
1742 elif isinstance(message, Message):
1743 pass
1744 else:
1745 raise TypeError('Cannot convert to specified type: %s' %
1746 type(message))
1747
1748
1749 class mboxMessage(_mboxMMDFMessage):
1750 """Message with mbox-specific properties."""
1751
1752
1753 class MHMessage(Message):
1754 """Message with MH-specific properties."""
1755
1756 _type_specific_attributes = ['_sequences']
1757
1758 def __init__(self, message=None):
1759 """Initialize an MHMessage instance."""
1760 self._sequences = []
1761 Message.__init__(self, message)
1762
1763 def get_sequences(self):
1764 """Return a list of sequences that include the message."""
1765 return self._sequences[:]
1766
1767 def set_sequences(self, sequences):
1768 """Set the list of sequences that include the message."""
1769 self._sequences = list(sequences)
1770
1771 def add_sequence(self, sequence):
1772 """Add sequence to list of sequences including the message."""
1773 if isinstance(sequence, str):
1774 if not sequence in self._sequences:
1775 self._sequences.append(sequence)
1776 else:
1777 raise TypeError('sequence type must be str: %s' % type(sequence))
1778
1779 def remove_sequence(self, sequence):
1780 """Remove sequence from the list of sequences including the message."""
1781 try:
1782 self._sequences.remove(sequence)
1783 except ValueError:
1784 pass
1785
1786 def _explain_to(self, message):
1787 """Copy MH-specific state to message insofar as possible."""
1788 if isinstance(message, MaildirMessage):
1789 sequences = set(self.get_sequences())
1790 if 'unseen' in sequences:
1791 message.set_subdir('cur')
1792 else:
1793 message.set_subdir('cur')
1794 message.add_flag('S')
1795 if 'flagged' in sequences:
1796 message.add_flag('F')
1797 if 'replied' in sequences:
1798 message.add_flag('R')
1799 elif isinstance(message, _mboxMMDFMessage):
1800 sequences = set(self.get_sequences())
1801 if 'unseen' not in sequences:
1802 message.add_flag('RO')
1803 else:
1804 message.add_flag('O')
1805 if 'flagged' in sequences:
1806 message.add_flag('F')
1807 if 'replied' in sequences:
1808 message.add_flag('A')
1809 elif isinstance(message, MHMessage):
1810 for sequence in self.get_sequences():
1811 message.add_sequence(sequence)
1812 elif isinstance(message, BabylMessage):
1813 sequences = set(self.get_sequences())
1814 if 'unseen' in sequences:
1815 message.add_label('unseen')
1816 if 'replied' in sequences:
1817 message.add_label('answered')
1818 elif isinstance(message, Message):
1819 pass
1820 else:
1821 raise TypeError('Cannot convert to specified type: %s' %
1822 type(message))
1823
1824
1825 class BabylMessage(Message):
1826 """Message with Babyl-specific properties."""
1827
1828 _type_specific_attributes = ['_labels', '_visible']
1829
1830 def __init__(self, message=None):
1831 """Initialize a BabylMessage instance."""
1832 self._labels = []
1833 self._visible = Message()
1834 Message.__init__(self, message)
1835
1836 def get_labels(self):
1837 """Return a list of labels on the message."""
1838 return self._labels[:]
1839
1840 def set_labels(self, labels):
1841 """Set the list of labels on the message."""
1842 self._labels = list(labels)
1843
1844 def add_label(self, label):
1845 """Add label to list of labels on the message."""
1846 if isinstance(label, str):
1847 if label not in self._labels:
1848 self._labels.append(label)
1849 else:
1850 raise TypeError('label must be a string: %s' % type(label))
1851
1852 def remove_label(self, label):
1853 """Remove label from the list of labels on the message."""
1854 try:
1855 self._labels.remove(label)
1856 except ValueError:
1857 pass
1858
1859 def get_visible(self):
1860 """Return a Message representation of visible headers."""
1861 return Message(self._visible)
1862
1863 def set_visible(self, visible):
1864 """Set the Message representation of visible headers."""
1865 self._visible = Message(visible)
1866
1867 def update_visible(self):
1868 """Update and/or sensibly generate a set of visible headers."""
1869 for header in self._visible.keys():
1870 if header in self:
1871 self._visible.replace_header(header, self[header])
1872 else:
1873 del self._visible[header]
1874 for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
1875 if header in self and header not in self._visible:
1876 self._visible[header] = self[header]
1877
1878 def _explain_to(self, message):
1879 """Copy Babyl-specific state to message insofar as possible."""
1880 if isinstance(message, MaildirMessage):
1881 labels = set(self.get_labels())
1882 if 'unseen' in labels:
1883 message.set_subdir('cur')
1884 else:
1885 message.set_subdir('cur')
1886 message.add_flag('S')
1887 if 'forwarded' in labels or 'resent' in labels:
1888 message.add_flag('P')
1889 if 'answered' in labels:
1890 message.add_flag('R')
1891 if 'deleted' in labels:
1892 message.add_flag('T')
1893 elif isinstance(message, _mboxMMDFMessage):
1894 labels = set(self.get_labels())
1895 if 'unseen' not in labels:
1896 message.add_flag('RO')
1897 else:
1898 message.add_flag('O')
1899 if 'deleted' in labels:
1900 message.add_flag('D')
1901 if 'answered' in labels:
1902 message.add_flag('A')
1903 elif isinstance(message, MHMessage):
1904 labels = set(self.get_labels())
1905 if 'unseen' in labels:
1906 message.add_sequence('unseen')
1907 if 'answered' in labels:
1908 message.add_sequence('replied')
1909 elif isinstance(message, BabylMessage):
1910 message.set_visible(self.get_visible())
1911 for label in self.get_labels():
1912 message.add_label(label)
1913 elif isinstance(message, Message):
1914 pass
1915 else:
1916 raise TypeError('Cannot convert to specified type: %s' %
1917 type(message))
1918
1919
1920 class MMDFMessage(_mboxMMDFMessage):
1921 """Message with MMDF-specific properties."""
1922
1923
1924 class _ProxyFile:
1925 """A read-only wrapper of a file."""
1926
1927 def __init__(self, f, pos=None):
1928 """Initialize a _ProxyFile."""
1929 self._file = f
1930 if pos is None:
1931 self._pos = f.tell()
1932 else:
1933 self._pos = pos
1934
1935 def read(self, size=None):
1936 """Read bytes."""
1937 return self._read(size, self._file.read)
1938
1939 def read1(self, size=None):
1940 """Read bytes."""
1941 return self._read(size, self._file.read1)
1942
1943 def readline(self, size=None):
1944 """Read a line."""
1945 return self._read(size, self._file.readline)
1946
1947 def readlines(self, sizehint=None):
1948 """Read multiple lines."""
1949 result = []
1950 for line in self:
1951 result.append(line)
1952 if sizehint is not None:
1953 sizehint -= len(line)
1954 if sizehint <= 0:
1955 break
1956 return result
1957
1958 def __iter__(self):
1959 """Iterate over lines."""
1960 while True:
1961 line = self.readline()
1962 if not line:
1963 return
1964 yield line
1965
1966 def tell(self):
1967 """Return the position."""
1968 return self._pos
1969
1970 def seek(self, offset, whence=0):
1971 """Change position."""
1972 if whence == 1:
1973 self._file.seek(self._pos)
1974 self._file.seek(offset, whence)
1975 self._pos = self._file.tell()
1976
1977 def close(self):
1978 """Close the file."""
1979 if hasattr(self, '_file'):
1980 try:
1981 if hasattr(self._file, 'close'):
1982 self._file.close()
1983 finally:
1984 del self._file
1985
1986 def _read(self, size, read_method):
1987 """Read size bytes using read_method."""
1988 if size is None:
1989 size = -1
1990 self._file.seek(self._pos)
1991 result = read_method(size)
1992 self._pos = self._file.tell()
1993 return result
1994
1995 def __enter__(self):
1996 """Context management protocol support."""
1997 return self
1998
1999 def __exit__(self, *exc):
2000 self.close()
2001
2002 def readable(self):
2003 return self._file.readable()
2004
2005 def writable(self):
2006 return self._file.writable()
2007
2008 def seekable(self):
2009 return self._file.seekable()
2010
2011 def flush(self):
2012 return self._file.flush()
2013
2014 @property
2015 def closed(self):
2016 if not hasattr(self, '_file'):
2017 return True
2018 if not hasattr(self._file, 'closed'):
2019 return False
2020 return self._file.closed
2021
2022 __class_getitem__ = classmethod(GenericAlias)
2023
2024
2025 class _PartialFile(_ProxyFile):
2026 """A read-only wrapper of part of a file."""
2027
2028 def __init__(self, f, start=None, stop=None):
2029 """Initialize a _PartialFile."""
2030 _ProxyFile.__init__(self, f, start)
2031 self._start = start
2032 self._stop = stop
2033
2034 def tell(self):
2035 """Return the position with respect to start."""
2036 return _ProxyFile.tell(self) - self._start
2037
2038 def seek(self, offset, whence=0):
2039 """Change position, possibly with respect to start or stop."""
2040 if whence == 0:
2041 self._pos = self._start
2042 whence = 1
2043 elif whence == 2:
2044 self._pos = self._stop
2045 whence = 1
2046 _ProxyFile.seek(self, offset, whence)
2047
2048 def _read(self, size, read_method):
2049 """Read size bytes using read_method, honoring start and stop."""
2050 remaining = self._stop - self._pos
2051 if remaining <= 0:
2052 return b''
2053 if size is None or size < 0 or size > remaining:
2054 size = remaining
2055 return _ProxyFile._read(self, size, read_method)
2056
2057 def close(self):
2058 # do *not* close the underlying file object for partial files,
2059 # since it's global to the mailbox object
2060 if hasattr(self, '_file'):
2061 del self._file
2062
2063
2064 def _lock_file(f, dotlock=True):
2065 """Lock file f using lockf and dot locking."""
2066 dotlock_done = False
2067 try:
2068 if fcntl:
2069 try:
2070 fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
2071 except OSError as e:
2072 if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
2073 raise ExternalClashError('lockf: lock unavailable: %s' %
2074 f.name)
2075 else:
2076 raise
2077 if dotlock:
2078 try:
2079 pre_lock = _create_temporary(f.name + '.lock')
2080 pre_lock.close()
2081 except OSError as e:
2082 if e.errno in (errno.EACCES, errno.EROFS):
2083 return # Without write access, just skip dotlocking.
2084 else:
2085 raise
2086 try:
2087 try:
2088 os.link(pre_lock.name, f.name + '.lock')
2089 dotlock_done = True
2090 except (AttributeError, PermissionError):
2091 os.rename(pre_lock.name, f.name + '.lock')
2092 dotlock_done = True
2093 else:
2094 os.unlink(pre_lock.name)
2095 except FileExistsError:
2096 os.remove(pre_lock.name)
2097 raise ExternalClashError('dot lock unavailable: %s' %
2098 f.name)
2099 except:
2100 if fcntl:
2101 fcntl.lockf(f, fcntl.LOCK_UN)
2102 if dotlock_done:
2103 os.remove(f.name + '.lock')
2104 raise
2105
2106 def _unlock_file(f):
2107 """Unlock file f using lockf and dot locking."""
2108 if fcntl:
2109 fcntl.lockf(f, fcntl.LOCK_UN)
2110 if os.path.exists(f.name + '.lock'):
2111 os.remove(f.name + '.lock')
2112
2113 def _create_carefully(path):
2114 """Create a file if it doesn't exist and open for reading and writing."""
2115 fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
2116 try:
2117 return open(path, 'rb+')
2118 finally:
2119 os.close(fd)
2120
2121 def _create_temporary(path):
2122 """Create a temp file based on path and open for reading and writing."""
2123 return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
2124 socket.gethostname(),
2125 os.getpid()))
2126
2127 def _sync_flush(f):
2128 """Ensure changes to file f are physically on disk."""
2129 f.flush()
2130 if hasattr(os, 'fsync'):
2131 os.fsync(f.fileno())
2132
2133 def _sync_close(f):
2134 """Close file f, ensuring all changes are physically on disk."""
2135 _sync_flush(f)
2136 f.close()
2137
2138
2139 class Error(Exception):
2140 """Raised for module-specific errors."""
2141
2142 class NoSuchMailboxError(Error):
2143 """The specified mailbox does not exist and won't be created."""
2144
2145 class NotEmptyError(Error):
2146 """The specified mailbox is not empty and deletion was requested."""
2147
2148 class ExternalClashError(Error):
2149 """Another process caused an action to fail."""
2150
2151 class FormatError(Error):
2152 """A file appears to have an invalid format."""