mailbox.py 77 KB

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