mailbox.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153
  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 and owner are the same as the old file's
  619. info = os.stat(self._path)
  620. os.chmod(new_file.name, info.st_mode)
  621. try:
  622. os.chown(new_file.name, info.st_uid, info.st_gid)
  623. except (AttributeError, OSError):
  624. pass
  625. try:
  626. os.rename(new_file.name, self._path)
  627. except FileExistsError:
  628. os.remove(self._path)
  629. os.rename(new_file.name, self._path)
  630. self._file = open(self._path, 'rb+')
  631. self._toc = new_toc
  632. self._pending = False
  633. self._pending_sync = False
  634. if self._locked:
  635. _lock_file(self._file, dotlock=False)
  636. def _pre_mailbox_hook(self, f):
  637. """Called before writing the mailbox to file f."""
  638. return
  639. def _pre_message_hook(self, f):
  640. """Called before writing each message to file f."""
  641. return
  642. def _post_message_hook(self, f):
  643. """Called after writing each message to file f."""
  644. return
  645. def close(self):
  646. """Flush and close the mailbox."""
  647. try:
  648. self.flush()
  649. finally:
  650. try:
  651. if self._locked:
  652. self.unlock()
  653. finally:
  654. self._file.close() # Sync has been done by self.flush() above.
  655. def _lookup(self, key=None):
  656. """Return (start, stop) or raise KeyError."""
  657. if self._toc is None:
  658. self._generate_toc()
  659. if key is not None:
  660. try:
  661. return self._toc[key]
  662. except KeyError:
  663. raise KeyError('No message with key: %s' % key) from None
  664. def _append_message(self, message):
  665. """Append message to mailbox and return (start, stop) offsets."""
  666. self._file.seek(0, 2)
  667. before = self._file.tell()
  668. if len(self._toc) == 0 and not self._pending:
  669. # This is the first message, and the _pre_mailbox_hook
  670. # hasn't yet been called. If self._pending is True,
  671. # messages have been removed, so _pre_mailbox_hook must
  672. # have been called already.
  673. self._pre_mailbox_hook(self._file)
  674. try:
  675. self._pre_message_hook(self._file)
  676. offsets = self._install_message(message)
  677. self._post_message_hook(self._file)
  678. except BaseException:
  679. self._file.truncate(before)
  680. raise
  681. self._file.flush()
  682. self._file_length = self._file.tell() # Record current length of mailbox
  683. return offsets
  684. class _mboxMMDF(_singlefileMailbox):
  685. """An mbox or MMDF mailbox."""
  686. _mangle_from_ = True
  687. def get_message(self, key):
  688. """Return a Message representation or raise a KeyError."""
  689. start, stop = self._lookup(key)
  690. self._file.seek(start)
  691. from_line = self._file.readline().replace(linesep, b'').decode('ascii')
  692. string = self._file.read(stop - self._file.tell())
  693. msg = self._message_factory(string.replace(linesep, b'\n'))
  694. msg.set_unixfrom(from_line)
  695. msg.set_from(from_line[5:])
  696. return msg
  697. def get_string(self, key, from_=False):
  698. """Return a string representation or raise a KeyError."""
  699. return email.message_from_bytes(
  700. self.get_bytes(key, from_)).as_string(unixfrom=from_)
  701. def get_bytes(self, key, from_=False):
  702. """Return a string representation or raise a KeyError."""
  703. start, stop = self._lookup(key)
  704. self._file.seek(start)
  705. if not from_:
  706. self._file.readline()
  707. string = self._file.read(stop - self._file.tell())
  708. return string.replace(linesep, b'\n')
  709. def get_file(self, key, from_=False):
  710. """Return a file-like representation or raise a KeyError."""
  711. start, stop = self._lookup(key)
  712. self._file.seek(start)
  713. if not from_:
  714. self._file.readline()
  715. return _PartialFile(self._file, self._file.tell(), stop)
  716. def _install_message(self, message):
  717. """Format a message and blindly write to self._file."""
  718. from_line = None
  719. if isinstance(message, str):
  720. message = self._string_to_bytes(message)
  721. if isinstance(message, bytes) and message.startswith(b'From '):
  722. newline = message.find(b'\n')
  723. if newline != -1:
  724. from_line = message[:newline]
  725. message = message[newline + 1:]
  726. else:
  727. from_line = message
  728. message = b''
  729. elif isinstance(message, _mboxMMDFMessage):
  730. author = message.get_from().encode('ascii')
  731. from_line = b'From ' + author
  732. elif isinstance(message, email.message.Message):
  733. from_line = message.get_unixfrom() # May be None.
  734. if from_line is not None:
  735. from_line = from_line.encode('ascii')
  736. if from_line is None:
  737. from_line = b'From MAILER-DAEMON ' + time.asctime(time.gmtime()).encode()
  738. start = self._file.tell()
  739. self._file.write(from_line + linesep)
  740. self._dump_message(message, self._file, self._mangle_from_)
  741. stop = self._file.tell()
  742. return (start, stop)
  743. class mbox(_mboxMMDF):
  744. """A classic mbox mailbox."""
  745. _mangle_from_ = True
  746. # All messages must end in a newline character, and
  747. # _post_message_hooks outputs an empty line between messages.
  748. _append_newline = True
  749. def __init__(self, path, factory=None, create=True):
  750. """Initialize an mbox mailbox."""
  751. self._message_factory = mboxMessage
  752. _mboxMMDF.__init__(self, path, factory, create)
  753. def _post_message_hook(self, f):
  754. """Called after writing each message to file f."""
  755. f.write(linesep)
  756. def _generate_toc(self):
  757. """Generate key-to-(start, stop) table of contents."""
  758. starts, stops = [], []
  759. last_was_empty = False
  760. self._file.seek(0)
  761. while True:
  762. line_pos = self._file.tell()
  763. line = self._file.readline()
  764. if line.startswith(b'From '):
  765. if len(stops) < len(starts):
  766. if last_was_empty:
  767. stops.append(line_pos - len(linesep))
  768. else:
  769. # The last line before the "From " line wasn't
  770. # blank, but we consider it a start of a
  771. # message anyway.
  772. stops.append(line_pos)
  773. starts.append(line_pos)
  774. last_was_empty = False
  775. elif not line:
  776. if last_was_empty:
  777. stops.append(line_pos - len(linesep))
  778. else:
  779. stops.append(line_pos)
  780. break
  781. elif line == linesep:
  782. last_was_empty = True
  783. else:
  784. last_was_empty = False
  785. self._toc = dict(enumerate(zip(starts, stops)))
  786. self._next_key = len(self._toc)
  787. self._file_length = self._file.tell()
  788. class MMDF(_mboxMMDF):
  789. """An MMDF mailbox."""
  790. def __init__(self, path, factory=None, create=True):
  791. """Initialize an MMDF mailbox."""
  792. self._message_factory = MMDFMessage
  793. _mboxMMDF.__init__(self, path, factory, create)
  794. def _pre_message_hook(self, f):
  795. """Called before writing each message to file f."""
  796. f.write(b'\001\001\001\001' + linesep)
  797. def _post_message_hook(self, f):
  798. """Called after writing each message to file f."""
  799. f.write(linesep + b'\001\001\001\001' + linesep)
  800. def _generate_toc(self):
  801. """Generate key-to-(start, stop) table of contents."""
  802. starts, stops = [], []
  803. self._file.seek(0)
  804. next_pos = 0
  805. while True:
  806. line_pos = next_pos
  807. line = self._file.readline()
  808. next_pos = self._file.tell()
  809. if line.startswith(b'\001\001\001\001' + linesep):
  810. starts.append(next_pos)
  811. while True:
  812. line_pos = next_pos
  813. line = self._file.readline()
  814. next_pos = self._file.tell()
  815. if line == b'\001\001\001\001' + linesep:
  816. stops.append(line_pos - len(linesep))
  817. break
  818. elif not line:
  819. stops.append(line_pos)
  820. break
  821. elif not line:
  822. break
  823. self._toc = dict(enumerate(zip(starts, stops)))
  824. self._next_key = len(self._toc)
  825. self._file.seek(0, 2)
  826. self._file_length = self._file.tell()
  827. class MH(Mailbox):
  828. """An MH mailbox."""
  829. def __init__(self, path, factory=None, create=True):
  830. """Initialize an MH instance."""
  831. Mailbox.__init__(self, path, factory, create)
  832. if not os.path.exists(self._path):
  833. if create:
  834. os.mkdir(self._path, 0o700)
  835. os.close(os.open(os.path.join(self._path, '.mh_sequences'),
  836. os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
  837. else:
  838. raise NoSuchMailboxError(self._path)
  839. self._locked = False
  840. def add(self, message):
  841. """Add message and return assigned key."""
  842. keys = self.keys()
  843. if len(keys) == 0:
  844. new_key = 1
  845. else:
  846. new_key = max(keys) + 1
  847. new_path = os.path.join(self._path, str(new_key))
  848. f = _create_carefully(new_path)
  849. closed = False
  850. try:
  851. if self._locked:
  852. _lock_file(f)
  853. try:
  854. try:
  855. self._dump_message(message, f)
  856. except BaseException:
  857. # Unlock and close so it can be deleted on Windows
  858. if self._locked:
  859. _unlock_file(f)
  860. _sync_close(f)
  861. closed = True
  862. os.remove(new_path)
  863. raise
  864. if isinstance(message, MHMessage):
  865. self._dump_sequences(message, new_key)
  866. finally:
  867. if self._locked:
  868. _unlock_file(f)
  869. finally:
  870. if not closed:
  871. _sync_close(f)
  872. return new_key
  873. def remove(self, key):
  874. """Remove the keyed message; raise KeyError if it doesn't exist."""
  875. path = os.path.join(self._path, str(key))
  876. try:
  877. f = open(path, 'rb+')
  878. except OSError as e:
  879. if e.errno == errno.ENOENT:
  880. raise KeyError('No message with key: %s' % key)
  881. else:
  882. raise
  883. else:
  884. f.close()
  885. os.remove(path)
  886. def __setitem__(self, key, message):
  887. """Replace the keyed message; raise KeyError if it doesn't exist."""
  888. path = os.path.join(self._path, str(key))
  889. try:
  890. f = open(path, 'rb+')
  891. except OSError as e:
  892. if e.errno == errno.ENOENT:
  893. raise KeyError('No message with key: %s' % key)
  894. else:
  895. raise
  896. try:
  897. if self._locked:
  898. _lock_file(f)
  899. try:
  900. os.close(os.open(path, os.O_WRONLY | os.O_TRUNC))
  901. self._dump_message(message, f)
  902. if isinstance(message, MHMessage):
  903. self._dump_sequences(message, key)
  904. finally:
  905. if self._locked:
  906. _unlock_file(f)
  907. finally:
  908. _sync_close(f)
  909. def get_message(self, key):
  910. """Return a Message representation or raise a KeyError."""
  911. try:
  912. if self._locked:
  913. f = open(os.path.join(self._path, str(key)), 'rb+')
  914. else:
  915. f = open(os.path.join(self._path, str(key)), 'rb')
  916. except OSError as e:
  917. if e.errno == errno.ENOENT:
  918. raise KeyError('No message with key: %s' % key)
  919. else:
  920. raise
  921. with f:
  922. if self._locked:
  923. _lock_file(f)
  924. try:
  925. msg = MHMessage(f)
  926. finally:
  927. if self._locked:
  928. _unlock_file(f)
  929. for name, key_list in self.get_sequences().items():
  930. if key in key_list:
  931. msg.add_sequence(name)
  932. return msg
  933. def get_bytes(self, key):
  934. """Return a bytes representation or raise a KeyError."""
  935. try:
  936. if self._locked:
  937. f = open(os.path.join(self._path, str(key)), 'rb+')
  938. else:
  939. f = open(os.path.join(self._path, str(key)), 'rb')
  940. except OSError as e:
  941. if e.errno == errno.ENOENT:
  942. raise KeyError('No message with key: %s' % key)
  943. else:
  944. raise
  945. with f:
  946. if self._locked:
  947. _lock_file(f)
  948. try:
  949. return f.read().replace(linesep, b'\n')
  950. finally:
  951. if self._locked:
  952. _unlock_file(f)
  953. def get_file(self, key):
  954. """Return a file-like representation or raise a KeyError."""
  955. try:
  956. f = open(os.path.join(self._path, str(key)), 'rb')
  957. except OSError as e:
  958. if e.errno == errno.ENOENT:
  959. raise KeyError('No message with key: %s' % key)
  960. else:
  961. raise
  962. return _ProxyFile(f)
  963. def iterkeys(self):
  964. """Return an iterator over keys."""
  965. return iter(sorted(int(entry) for entry in os.listdir(self._path)
  966. if entry.isdigit()))
  967. def __contains__(self, key):
  968. """Return True if the keyed message exists, False otherwise."""
  969. return os.path.exists(os.path.join(self._path, str(key)))
  970. def __len__(self):
  971. """Return a count of messages in the mailbox."""
  972. return len(list(self.iterkeys()))
  973. def lock(self):
  974. """Lock the mailbox."""
  975. if not self._locked:
  976. self._file = open(os.path.join(self._path, '.mh_sequences'), 'rb+')
  977. _lock_file(self._file)
  978. self._locked = True
  979. def unlock(self):
  980. """Unlock the mailbox if it is locked."""
  981. if self._locked:
  982. _unlock_file(self._file)
  983. _sync_close(self._file)
  984. del self._file
  985. self._locked = False
  986. def flush(self):
  987. """Write any pending changes to the disk."""
  988. return
  989. def close(self):
  990. """Flush and close the mailbox."""
  991. if self._locked:
  992. self.unlock()
  993. def list_folders(self):
  994. """Return a list of folder names."""
  995. result = []
  996. for entry in os.listdir(self._path):
  997. if os.path.isdir(os.path.join(self._path, entry)):
  998. result.append(entry)
  999. return result
  1000. def get_folder(self, folder):
  1001. """Return an MH instance for the named folder."""
  1002. return MH(os.path.join(self._path, folder),
  1003. factory=self._factory, create=False)
  1004. def add_folder(self, folder):
  1005. """Create a folder and return an MH instance representing it."""
  1006. return MH(os.path.join(self._path, folder),
  1007. factory=self._factory)
  1008. def remove_folder(self, folder):
  1009. """Delete the named folder, which must be empty."""
  1010. path = os.path.join(self._path, folder)
  1011. entries = os.listdir(path)
  1012. if entries == ['.mh_sequences']:
  1013. os.remove(os.path.join(path, '.mh_sequences'))
  1014. elif entries == []:
  1015. pass
  1016. else:
  1017. raise NotEmptyError('Folder not empty: %s' % self._path)
  1018. os.rmdir(path)
  1019. def get_sequences(self):
  1020. """Return a name-to-key-list dictionary to define each sequence."""
  1021. results = {}
  1022. with open(os.path.join(self._path, '.mh_sequences'), 'r', encoding='ASCII') as f:
  1023. all_keys = set(self.keys())
  1024. for line in f:
  1025. try:
  1026. name, contents = line.split(':')
  1027. keys = set()
  1028. for spec in contents.split():
  1029. if spec.isdigit():
  1030. keys.add(int(spec))
  1031. else:
  1032. start, stop = (int(x) for x in spec.split('-'))
  1033. keys.update(range(start, stop + 1))
  1034. results[name] = [key for key in sorted(keys) \
  1035. if key in all_keys]
  1036. if len(results[name]) == 0:
  1037. del results[name]
  1038. except ValueError:
  1039. raise FormatError('Invalid sequence specification: %s' %
  1040. line.rstrip())
  1041. return results
  1042. def set_sequences(self, sequences):
  1043. """Set sequences using the given name-to-key-list dictionary."""
  1044. f = open(os.path.join(self._path, '.mh_sequences'), 'r+', encoding='ASCII')
  1045. try:
  1046. os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
  1047. for name, keys in sequences.items():
  1048. if len(keys) == 0:
  1049. continue
  1050. f.write(name + ':')
  1051. prev = None
  1052. completing = False
  1053. for key in sorted(set(keys)):
  1054. if key - 1 == prev:
  1055. if not completing:
  1056. completing = True
  1057. f.write('-')
  1058. elif completing:
  1059. completing = False
  1060. f.write('%s %s' % (prev, key))
  1061. else:
  1062. f.write(' %s' % key)
  1063. prev = key
  1064. if completing:
  1065. f.write(str(prev) + '\n')
  1066. else:
  1067. f.write('\n')
  1068. finally:
  1069. _sync_close(f)
  1070. def pack(self):
  1071. """Re-name messages to eliminate numbering gaps. Invalidates keys."""
  1072. sequences = self.get_sequences()
  1073. prev = 0
  1074. changes = []
  1075. for key in self.iterkeys():
  1076. if key - 1 != prev:
  1077. changes.append((key, prev + 1))
  1078. try:
  1079. os.link(os.path.join(self._path, str(key)),
  1080. os.path.join(self._path, str(prev + 1)))
  1081. except (AttributeError, PermissionError):
  1082. os.rename(os.path.join(self._path, str(key)),
  1083. os.path.join(self._path, str(prev + 1)))
  1084. else:
  1085. os.unlink(os.path.join(self._path, str(key)))
  1086. prev += 1
  1087. self._next_key = prev + 1
  1088. if len(changes) == 0:
  1089. return
  1090. for name, key_list in sequences.items():
  1091. for old, new in changes:
  1092. if old in key_list:
  1093. key_list[key_list.index(old)] = new
  1094. self.set_sequences(sequences)
  1095. def _dump_sequences(self, message, key):
  1096. """Inspect a new MHMessage and update sequences appropriately."""
  1097. pending_sequences = message.get_sequences()
  1098. all_sequences = self.get_sequences()
  1099. for name, key_list in all_sequences.items():
  1100. if name in pending_sequences:
  1101. key_list.append(key)
  1102. elif key in key_list:
  1103. del key_list[key_list.index(key)]
  1104. for sequence in pending_sequences:
  1105. if sequence not in all_sequences:
  1106. all_sequences[sequence] = [key]
  1107. self.set_sequences(all_sequences)
  1108. class Babyl(_singlefileMailbox):
  1109. """An Rmail-style Babyl mailbox."""
  1110. _special_labels = frozenset({'unseen', 'deleted', 'filed', 'answered',
  1111. 'forwarded', 'edited', 'resent'})
  1112. def __init__(self, path, factory=None, create=True):
  1113. """Initialize a Babyl mailbox."""
  1114. _singlefileMailbox.__init__(self, path, factory, create)
  1115. self._labels = {}
  1116. def add(self, message):
  1117. """Add message and return assigned key."""
  1118. key = _singlefileMailbox.add(self, message)
  1119. if isinstance(message, BabylMessage):
  1120. self._labels[key] = message.get_labels()
  1121. return key
  1122. def remove(self, key):
  1123. """Remove the keyed message; raise KeyError if it doesn't exist."""
  1124. _singlefileMailbox.remove(self, key)
  1125. if key in self._labels:
  1126. del self._labels[key]
  1127. def __setitem__(self, key, message):
  1128. """Replace the keyed message; raise KeyError if it doesn't exist."""
  1129. _singlefileMailbox.__setitem__(self, key, message)
  1130. if isinstance(message, BabylMessage):
  1131. self._labels[key] = message.get_labels()
  1132. def get_message(self, key):
  1133. """Return a Message representation or raise a KeyError."""
  1134. start, stop = self._lookup(key)
  1135. self._file.seek(start)
  1136. self._file.readline() # Skip b'1,' line specifying labels.
  1137. original_headers = io.BytesIO()
  1138. while True:
  1139. line = self._file.readline()
  1140. if line == b'*** EOOH ***' + linesep or not line:
  1141. break
  1142. original_headers.write(line.replace(linesep, b'\n'))
  1143. visible_headers = io.BytesIO()
  1144. while True:
  1145. line = self._file.readline()
  1146. if line == linesep or not line:
  1147. break
  1148. visible_headers.write(line.replace(linesep, b'\n'))
  1149. # Read up to the stop, or to the end
  1150. n = stop - self._file.tell()
  1151. assert n >= 0
  1152. body = self._file.read(n)
  1153. body = body.replace(linesep, b'\n')
  1154. msg = BabylMessage(original_headers.getvalue() + body)
  1155. msg.set_visible(visible_headers.getvalue())
  1156. if key in self._labels:
  1157. msg.set_labels(self._labels[key])
  1158. return msg
  1159. def get_bytes(self, key):
  1160. """Return a string representation or raise a KeyError."""
  1161. start, stop = self._lookup(key)
  1162. self._file.seek(start)
  1163. self._file.readline() # Skip b'1,' line specifying labels.
  1164. original_headers = io.BytesIO()
  1165. while True:
  1166. line = self._file.readline()
  1167. if line == b'*** EOOH ***' + linesep or not line:
  1168. break
  1169. original_headers.write(line.replace(linesep, b'\n'))
  1170. while True:
  1171. line = self._file.readline()
  1172. if line == linesep or not line:
  1173. break
  1174. headers = original_headers.getvalue()
  1175. n = stop - self._file.tell()
  1176. assert n >= 0
  1177. data = self._file.read(n)
  1178. data = data.replace(linesep, b'\n')
  1179. return headers + data
  1180. def get_file(self, key):
  1181. """Return a file-like representation or raise a KeyError."""
  1182. return io.BytesIO(self.get_bytes(key).replace(b'\n', linesep))
  1183. def get_labels(self):
  1184. """Return a list of user-defined labels in the mailbox."""
  1185. self._lookup()
  1186. labels = set()
  1187. for label_list in self._labels.values():
  1188. labels.update(label_list)
  1189. labels.difference_update(self._special_labels)
  1190. return list(labels)
  1191. def _generate_toc(self):
  1192. """Generate key-to-(start, stop) table of contents."""
  1193. starts, stops = [], []
  1194. self._file.seek(0)
  1195. next_pos = 0
  1196. label_lists = []
  1197. while True:
  1198. line_pos = next_pos
  1199. line = self._file.readline()
  1200. next_pos = self._file.tell()
  1201. if line == b'\037\014' + linesep:
  1202. if len(stops) < len(starts):
  1203. stops.append(line_pos - len(linesep))
  1204. starts.append(next_pos)
  1205. labels = [label.strip() for label
  1206. in self._file.readline()[1:].split(b',')
  1207. if label.strip()]
  1208. label_lists.append(labels)
  1209. elif line == b'\037' or line == b'\037' + linesep:
  1210. if len(stops) < len(starts):
  1211. stops.append(line_pos - len(linesep))
  1212. elif not line:
  1213. stops.append(line_pos - len(linesep))
  1214. break
  1215. self._toc = dict(enumerate(zip(starts, stops)))
  1216. self._labels = dict(enumerate(label_lists))
  1217. self._next_key = len(self._toc)
  1218. self._file.seek(0, 2)
  1219. self._file_length = self._file.tell()
  1220. def _pre_mailbox_hook(self, f):
  1221. """Called before writing the mailbox to file f."""
  1222. babyl = b'BABYL OPTIONS:' + linesep
  1223. babyl += b'Version: 5' + linesep
  1224. labels = self.get_labels()
  1225. labels = (label.encode() for label in labels)
  1226. babyl += b'Labels:' + b','.join(labels) + linesep
  1227. babyl += b'\037'
  1228. f.write(babyl)
  1229. def _pre_message_hook(self, f):
  1230. """Called before writing each message to file f."""
  1231. f.write(b'\014' + linesep)
  1232. def _post_message_hook(self, f):
  1233. """Called after writing each message to file f."""
  1234. f.write(linesep + b'\037')
  1235. def _install_message(self, message):
  1236. """Write message contents and return (start, stop)."""
  1237. start = self._file.tell()
  1238. if isinstance(message, BabylMessage):
  1239. special_labels = []
  1240. labels = []
  1241. for label in message.get_labels():
  1242. if label in self._special_labels:
  1243. special_labels.append(label)
  1244. else:
  1245. labels.append(label)
  1246. self._file.write(b'1')
  1247. for label in special_labels:
  1248. self._file.write(b', ' + label.encode())
  1249. self._file.write(b',,')
  1250. for label in labels:
  1251. self._file.write(b' ' + label.encode() + b',')
  1252. self._file.write(linesep)
  1253. else:
  1254. self._file.write(b'1,,' + linesep)
  1255. if isinstance(message, email.message.Message):
  1256. orig_buffer = io.BytesIO()
  1257. orig_generator = email.generator.BytesGenerator(orig_buffer, False, 0)
  1258. orig_generator.flatten(message)
  1259. orig_buffer.seek(0)
  1260. while True:
  1261. line = orig_buffer.readline()
  1262. self._file.write(line.replace(b'\n', linesep))
  1263. if line == b'\n' or not line:
  1264. break
  1265. self._file.write(b'*** EOOH ***' + linesep)
  1266. if isinstance(message, BabylMessage):
  1267. vis_buffer = io.BytesIO()
  1268. vis_generator = email.generator.BytesGenerator(vis_buffer, False, 0)
  1269. vis_generator.flatten(message.get_visible())
  1270. while True:
  1271. line = vis_buffer.readline()
  1272. self._file.write(line.replace(b'\n', linesep))
  1273. if line == b'\n' or not line:
  1274. break
  1275. else:
  1276. orig_buffer.seek(0)
  1277. while True:
  1278. line = orig_buffer.readline()
  1279. self._file.write(line.replace(b'\n', linesep))
  1280. if line == b'\n' or not line:
  1281. break
  1282. while True:
  1283. buffer = orig_buffer.read(4096) # Buffer size is arbitrary.
  1284. if not buffer:
  1285. break
  1286. self._file.write(buffer.replace(b'\n', linesep))
  1287. elif isinstance(message, (bytes, str, io.StringIO)):
  1288. if isinstance(message, io.StringIO):
  1289. warnings.warn("Use of StringIO input is deprecated, "
  1290. "use BytesIO instead", DeprecationWarning, 3)
  1291. message = message.getvalue()
  1292. if isinstance(message, str):
  1293. message = self._string_to_bytes(message)
  1294. body_start = message.find(b'\n\n') + 2
  1295. if body_start - 2 != -1:
  1296. self._file.write(message[:body_start].replace(b'\n', linesep))
  1297. self._file.write(b'*** EOOH ***' + linesep)
  1298. self._file.write(message[:body_start].replace(b'\n', linesep))
  1299. self._file.write(message[body_start:].replace(b'\n', linesep))
  1300. else:
  1301. self._file.write(b'*** EOOH ***' + linesep + linesep)
  1302. self._file.write(message.replace(b'\n', linesep))
  1303. elif hasattr(message, 'readline'):
  1304. if hasattr(message, 'buffer'):
  1305. warnings.warn("Use of text mode files is deprecated, "
  1306. "use a binary mode file instead", DeprecationWarning, 3)
  1307. message = message.buffer
  1308. original_pos = message.tell()
  1309. first_pass = True
  1310. while True:
  1311. line = message.readline()
  1312. # Universal newline support.
  1313. if line.endswith(b'\r\n'):
  1314. line = line[:-2] + b'\n'
  1315. elif line.endswith(b'\r'):
  1316. line = line[:-1] + b'\n'
  1317. self._file.write(line.replace(b'\n', linesep))
  1318. if line == b'\n' or not line:
  1319. if first_pass:
  1320. first_pass = False
  1321. self._file.write(b'*** EOOH ***' + linesep)
  1322. message.seek(original_pos)
  1323. else:
  1324. break
  1325. while True:
  1326. line = message.readline()
  1327. if not line:
  1328. break
  1329. # Universal newline support.
  1330. if line.endswith(b'\r\n'):
  1331. line = line[:-2] + linesep
  1332. elif line.endswith(b'\r'):
  1333. line = line[:-1] + linesep
  1334. elif line.endswith(b'\n'):
  1335. line = line[:-1] + linesep
  1336. self._file.write(line)
  1337. else:
  1338. raise TypeError('Invalid message type: %s' % type(message))
  1339. stop = self._file.tell()
  1340. return (start, stop)
  1341. class Message(email.message.Message):
  1342. """Message with mailbox-format-specific properties."""
  1343. def __init__(self, message=None):
  1344. """Initialize a Message instance."""
  1345. if isinstance(message, email.message.Message):
  1346. self._become_message(copy.deepcopy(message))
  1347. if isinstance(message, Message):
  1348. message._explain_to(self)
  1349. elif isinstance(message, bytes):
  1350. self._become_message(email.message_from_bytes(message))
  1351. elif isinstance(message, str):
  1352. self._become_message(email.message_from_string(message))
  1353. elif isinstance(message, io.TextIOWrapper):
  1354. self._become_message(email.message_from_file(message))
  1355. elif hasattr(message, "read"):
  1356. self._become_message(email.message_from_binary_file(message))
  1357. elif message is None:
  1358. email.message.Message.__init__(self)
  1359. else:
  1360. raise TypeError('Invalid message type: %s' % type(message))
  1361. def _become_message(self, message):
  1362. """Assume the non-format-specific state of message."""
  1363. type_specific = getattr(message, '_type_specific_attributes', [])
  1364. for name in message.__dict__:
  1365. if name not in type_specific:
  1366. self.__dict__[name] = message.__dict__[name]
  1367. def _explain_to(self, message):
  1368. """Copy format-specific state to message insofar as possible."""
  1369. if isinstance(message, Message):
  1370. return # There's nothing format-specific to explain.
  1371. else:
  1372. raise TypeError('Cannot convert to specified type')
  1373. class MaildirMessage(Message):
  1374. """Message with Maildir-specific properties."""
  1375. _type_specific_attributes = ['_subdir', '_info', '_date']
  1376. def __init__(self, message=None):
  1377. """Initialize a MaildirMessage instance."""
  1378. self._subdir = 'new'
  1379. self._info = ''
  1380. self._date = time.time()
  1381. Message.__init__(self, message)
  1382. def get_subdir(self):
  1383. """Return 'new' or 'cur'."""
  1384. return self._subdir
  1385. def set_subdir(self, subdir):
  1386. """Set subdir to 'new' or 'cur'."""
  1387. if subdir == 'new' or subdir == 'cur':
  1388. self._subdir = subdir
  1389. else:
  1390. raise ValueError("subdir must be 'new' or 'cur': %s" % subdir)
  1391. def get_flags(self):
  1392. """Return as a string the flags that are set."""
  1393. if self._info.startswith('2,'):
  1394. return self._info[2:]
  1395. else:
  1396. return ''
  1397. def set_flags(self, flags):
  1398. """Set the given flags and unset all others."""
  1399. self._info = '2,' + ''.join(sorted(flags))
  1400. def add_flag(self, flag):
  1401. """Set the given flag(s) without changing others."""
  1402. self.set_flags(''.join(set(self.get_flags()) | set(flag)))
  1403. def remove_flag(self, flag):
  1404. """Unset the given string flag(s) without changing others."""
  1405. if self.get_flags():
  1406. self.set_flags(''.join(set(self.get_flags()) - set(flag)))
  1407. def get_date(self):
  1408. """Return delivery date of message, in seconds since the epoch."""
  1409. return self._date
  1410. def set_date(self, date):
  1411. """Set delivery date of message, in seconds since the epoch."""
  1412. try:
  1413. self._date = float(date)
  1414. except ValueError:
  1415. raise TypeError("can't convert to float: %s" % date) from None
  1416. def get_info(self):
  1417. """Get the message's "info" as a string."""
  1418. return self._info
  1419. def set_info(self, info):
  1420. """Set the message's "info" string."""
  1421. if isinstance(info, str):
  1422. self._info = info
  1423. else:
  1424. raise TypeError('info must be a string: %s' % type(info))
  1425. def _explain_to(self, message):
  1426. """Copy Maildir-specific state to message insofar as possible."""
  1427. if isinstance(message, MaildirMessage):
  1428. message.set_flags(self.get_flags())
  1429. message.set_subdir(self.get_subdir())
  1430. message.set_date(self.get_date())
  1431. elif isinstance(message, _mboxMMDFMessage):
  1432. flags = set(self.get_flags())
  1433. if 'S' in flags:
  1434. message.add_flag('R')
  1435. if self.get_subdir() == 'cur':
  1436. message.add_flag('O')
  1437. if 'T' in flags:
  1438. message.add_flag('D')
  1439. if 'F' in flags:
  1440. message.add_flag('F')
  1441. if 'R' in flags:
  1442. message.add_flag('A')
  1443. message.set_from('MAILER-DAEMON', time.gmtime(self.get_date()))
  1444. elif isinstance(message, MHMessage):
  1445. flags = set(self.get_flags())
  1446. if 'S' not in flags:
  1447. message.add_sequence('unseen')
  1448. if 'R' in flags:
  1449. message.add_sequence('replied')
  1450. if 'F' in flags:
  1451. message.add_sequence('flagged')
  1452. elif isinstance(message, BabylMessage):
  1453. flags = set(self.get_flags())
  1454. if 'S' not in flags:
  1455. message.add_label('unseen')
  1456. if 'T' in flags:
  1457. message.add_label('deleted')
  1458. if 'R' in flags:
  1459. message.add_label('answered')
  1460. if 'P' in flags:
  1461. message.add_label('forwarded')
  1462. elif isinstance(message, Message):
  1463. pass
  1464. else:
  1465. raise TypeError('Cannot convert to specified type: %s' %
  1466. type(message))
  1467. class _mboxMMDFMessage(Message):
  1468. """Message with mbox- or MMDF-specific properties."""
  1469. _type_specific_attributes = ['_from']
  1470. def __init__(self, message=None):
  1471. """Initialize an mboxMMDFMessage instance."""
  1472. self.set_from('MAILER-DAEMON', True)
  1473. if isinstance(message, email.message.Message):
  1474. unixfrom = message.get_unixfrom()
  1475. if unixfrom is not None and unixfrom.startswith('From '):
  1476. self.set_from(unixfrom[5:])
  1477. Message.__init__(self, message)
  1478. def get_from(self):
  1479. """Return contents of "From " line."""
  1480. return self._from
  1481. def set_from(self, from_, time_=None):
  1482. """Set "From " line, formatting and appending time_ if specified."""
  1483. if time_ is not None:
  1484. if time_ is True:
  1485. time_ = time.gmtime()
  1486. from_ += ' ' + time.asctime(time_)
  1487. self._from = from_
  1488. def get_flags(self):
  1489. """Return as a string the flags that are set."""
  1490. return self.get('Status', '') + self.get('X-Status', '')
  1491. def set_flags(self, flags):
  1492. """Set the given flags and unset all others."""
  1493. flags = set(flags)
  1494. status_flags, xstatus_flags = '', ''
  1495. for flag in ('R', 'O'):
  1496. if flag in flags:
  1497. status_flags += flag
  1498. flags.remove(flag)
  1499. for flag in ('D', 'F', 'A'):
  1500. if flag in flags:
  1501. xstatus_flags += flag
  1502. flags.remove(flag)
  1503. xstatus_flags += ''.join(sorted(flags))
  1504. try:
  1505. self.replace_header('Status', status_flags)
  1506. except KeyError:
  1507. self.add_header('Status', status_flags)
  1508. try:
  1509. self.replace_header('X-Status', xstatus_flags)
  1510. except KeyError:
  1511. self.add_header('X-Status', xstatus_flags)
  1512. def add_flag(self, flag):
  1513. """Set the given flag(s) without changing others."""
  1514. self.set_flags(''.join(set(self.get_flags()) | set(flag)))
  1515. def remove_flag(self, flag):
  1516. """Unset the given string flag(s) without changing others."""
  1517. if 'Status' in self or 'X-Status' in self:
  1518. self.set_flags(''.join(set(self.get_flags()) - set(flag)))
  1519. def _explain_to(self, message):
  1520. """Copy mbox- or MMDF-specific state to message insofar as possible."""
  1521. if isinstance(message, MaildirMessage):
  1522. flags = set(self.get_flags())
  1523. if 'O' in flags:
  1524. message.set_subdir('cur')
  1525. if 'F' in flags:
  1526. message.add_flag('F')
  1527. if 'A' in flags:
  1528. message.add_flag('R')
  1529. if 'R' in flags:
  1530. message.add_flag('S')
  1531. if 'D' in flags:
  1532. message.add_flag('T')
  1533. del message['status']
  1534. del message['x-status']
  1535. maybe_date = ' '.join(self.get_from().split()[-5:])
  1536. try:
  1537. message.set_date(calendar.timegm(time.strptime(maybe_date,
  1538. '%a %b %d %H:%M:%S %Y')))
  1539. except (ValueError, OverflowError):
  1540. pass
  1541. elif isinstance(message, _mboxMMDFMessage):
  1542. message.set_flags(self.get_flags())
  1543. message.set_from(self.get_from())
  1544. elif isinstance(message, MHMessage):
  1545. flags = set(self.get_flags())
  1546. if 'R' not in flags:
  1547. message.add_sequence('unseen')
  1548. if 'A' in flags:
  1549. message.add_sequence('replied')
  1550. if 'F' in flags:
  1551. message.add_sequence('flagged')
  1552. del message['status']
  1553. del message['x-status']
  1554. elif isinstance(message, BabylMessage):
  1555. flags = set(self.get_flags())
  1556. if 'R' not in flags:
  1557. message.add_label('unseen')
  1558. if 'D' in flags:
  1559. message.add_label('deleted')
  1560. if 'A' in flags:
  1561. message.add_label('answered')
  1562. del message['status']
  1563. del message['x-status']
  1564. elif isinstance(message, Message):
  1565. pass
  1566. else:
  1567. raise TypeError('Cannot convert to specified type: %s' %
  1568. type(message))
  1569. class mboxMessage(_mboxMMDFMessage):
  1570. """Message with mbox-specific properties."""
  1571. class MHMessage(Message):
  1572. """Message with MH-specific properties."""
  1573. _type_specific_attributes = ['_sequences']
  1574. def __init__(self, message=None):
  1575. """Initialize an MHMessage instance."""
  1576. self._sequences = []
  1577. Message.__init__(self, message)
  1578. def get_sequences(self):
  1579. """Return a list of sequences that include the message."""
  1580. return self._sequences[:]
  1581. def set_sequences(self, sequences):
  1582. """Set the list of sequences that include the message."""
  1583. self._sequences = list(sequences)
  1584. def add_sequence(self, sequence):
  1585. """Add sequence to list of sequences including the message."""
  1586. if isinstance(sequence, str):
  1587. if not sequence in self._sequences:
  1588. self._sequences.append(sequence)
  1589. else:
  1590. raise TypeError('sequence type must be str: %s' % type(sequence))
  1591. def remove_sequence(self, sequence):
  1592. """Remove sequence from the list of sequences including the message."""
  1593. try:
  1594. self._sequences.remove(sequence)
  1595. except ValueError:
  1596. pass
  1597. def _explain_to(self, message):
  1598. """Copy MH-specific state to message insofar as possible."""
  1599. if isinstance(message, MaildirMessage):
  1600. sequences = set(self.get_sequences())
  1601. if 'unseen' in sequences:
  1602. message.set_subdir('cur')
  1603. else:
  1604. message.set_subdir('cur')
  1605. message.add_flag('S')
  1606. if 'flagged' in sequences:
  1607. message.add_flag('F')
  1608. if 'replied' in sequences:
  1609. message.add_flag('R')
  1610. elif isinstance(message, _mboxMMDFMessage):
  1611. sequences = set(self.get_sequences())
  1612. if 'unseen' not in sequences:
  1613. message.add_flag('RO')
  1614. else:
  1615. message.add_flag('O')
  1616. if 'flagged' in sequences:
  1617. message.add_flag('F')
  1618. if 'replied' in sequences:
  1619. message.add_flag('A')
  1620. elif isinstance(message, MHMessage):
  1621. for sequence in self.get_sequences():
  1622. message.add_sequence(sequence)
  1623. elif isinstance(message, BabylMessage):
  1624. sequences = set(self.get_sequences())
  1625. if 'unseen' in sequences:
  1626. message.add_label('unseen')
  1627. if 'replied' in sequences:
  1628. message.add_label('answered')
  1629. elif isinstance(message, Message):
  1630. pass
  1631. else:
  1632. raise TypeError('Cannot convert to specified type: %s' %
  1633. type(message))
  1634. class BabylMessage(Message):
  1635. """Message with Babyl-specific properties."""
  1636. _type_specific_attributes = ['_labels', '_visible']
  1637. def __init__(self, message=None):
  1638. """Initialize a BabylMessage instance."""
  1639. self._labels = []
  1640. self._visible = Message()
  1641. Message.__init__(self, message)
  1642. def get_labels(self):
  1643. """Return a list of labels on the message."""
  1644. return self._labels[:]
  1645. def set_labels(self, labels):
  1646. """Set the list of labels on the message."""
  1647. self._labels = list(labels)
  1648. def add_label(self, label):
  1649. """Add label to list of labels on the message."""
  1650. if isinstance(label, str):
  1651. if label not in self._labels:
  1652. self._labels.append(label)
  1653. else:
  1654. raise TypeError('label must be a string: %s' % type(label))
  1655. def remove_label(self, label):
  1656. """Remove label from the list of labels on the message."""
  1657. try:
  1658. self._labels.remove(label)
  1659. except ValueError:
  1660. pass
  1661. def get_visible(self):
  1662. """Return a Message representation of visible headers."""
  1663. return Message(self._visible)
  1664. def set_visible(self, visible):
  1665. """Set the Message representation of visible headers."""
  1666. self._visible = Message(visible)
  1667. def update_visible(self):
  1668. """Update and/or sensibly generate a set of visible headers."""
  1669. for header in self._visible.keys():
  1670. if header in self:
  1671. self._visible.replace_header(header, self[header])
  1672. else:
  1673. del self._visible[header]
  1674. for header in ('Date', 'From', 'Reply-To', 'To', 'CC', 'Subject'):
  1675. if header in self and header not in self._visible:
  1676. self._visible[header] = self[header]
  1677. def _explain_to(self, message):
  1678. """Copy Babyl-specific state to message insofar as possible."""
  1679. if isinstance(message, MaildirMessage):
  1680. labels = set(self.get_labels())
  1681. if 'unseen' in labels:
  1682. message.set_subdir('cur')
  1683. else:
  1684. message.set_subdir('cur')
  1685. message.add_flag('S')
  1686. if 'forwarded' in labels or 'resent' in labels:
  1687. message.add_flag('P')
  1688. if 'answered' in labels:
  1689. message.add_flag('R')
  1690. if 'deleted' in labels:
  1691. message.add_flag('T')
  1692. elif isinstance(message, _mboxMMDFMessage):
  1693. labels = set(self.get_labels())
  1694. if 'unseen' not in labels:
  1695. message.add_flag('RO')
  1696. else:
  1697. message.add_flag('O')
  1698. if 'deleted' in labels:
  1699. message.add_flag('D')
  1700. if 'answered' in labels:
  1701. message.add_flag('A')
  1702. elif isinstance(message, MHMessage):
  1703. labels = set(self.get_labels())
  1704. if 'unseen' in labels:
  1705. message.add_sequence('unseen')
  1706. if 'answered' in labels:
  1707. message.add_sequence('replied')
  1708. elif isinstance(message, BabylMessage):
  1709. message.set_visible(self.get_visible())
  1710. for label in self.get_labels():
  1711. message.add_label(label)
  1712. elif isinstance(message, Message):
  1713. pass
  1714. else:
  1715. raise TypeError('Cannot convert to specified type: %s' %
  1716. type(message))
  1717. class MMDFMessage(_mboxMMDFMessage):
  1718. """Message with MMDF-specific properties."""
  1719. class _ProxyFile:
  1720. """A read-only wrapper of a file."""
  1721. def __init__(self, f, pos=None):
  1722. """Initialize a _ProxyFile."""
  1723. self._file = f
  1724. if pos is None:
  1725. self._pos = f.tell()
  1726. else:
  1727. self._pos = pos
  1728. def read(self, size=None):
  1729. """Read bytes."""
  1730. return self._read(size, self._file.read)
  1731. def read1(self, size=None):
  1732. """Read bytes."""
  1733. return self._read(size, self._file.read1)
  1734. def readline(self, size=None):
  1735. """Read a line."""
  1736. return self._read(size, self._file.readline)
  1737. def readlines(self, sizehint=None):
  1738. """Read multiple lines."""
  1739. result = []
  1740. for line in self:
  1741. result.append(line)
  1742. if sizehint is not None:
  1743. sizehint -= len(line)
  1744. if sizehint <= 0:
  1745. break
  1746. return result
  1747. def __iter__(self):
  1748. """Iterate over lines."""
  1749. while line := self.readline():
  1750. yield line
  1751. def tell(self):
  1752. """Return the position."""
  1753. return self._pos
  1754. def seek(self, offset, whence=0):
  1755. """Change position."""
  1756. if whence == 1:
  1757. self._file.seek(self._pos)
  1758. self._file.seek(offset, whence)
  1759. self._pos = self._file.tell()
  1760. def close(self):
  1761. """Close the file."""
  1762. if hasattr(self, '_file'):
  1763. try:
  1764. if hasattr(self._file, 'close'):
  1765. self._file.close()
  1766. finally:
  1767. del self._file
  1768. def _read(self, size, read_method):
  1769. """Read size bytes using read_method."""
  1770. if size is None:
  1771. size = -1
  1772. self._file.seek(self._pos)
  1773. result = read_method(size)
  1774. self._pos = self._file.tell()
  1775. return result
  1776. def __enter__(self):
  1777. """Context management protocol support."""
  1778. return self
  1779. def __exit__(self, *exc):
  1780. self.close()
  1781. def readable(self):
  1782. return self._file.readable()
  1783. def writable(self):
  1784. return self._file.writable()
  1785. def seekable(self):
  1786. return self._file.seekable()
  1787. def flush(self):
  1788. return self._file.flush()
  1789. @property
  1790. def closed(self):
  1791. if not hasattr(self, '_file'):
  1792. return True
  1793. if not hasattr(self._file, 'closed'):
  1794. return False
  1795. return self._file.closed
  1796. __class_getitem__ = classmethod(GenericAlias)
  1797. class _PartialFile(_ProxyFile):
  1798. """A read-only wrapper of part of a file."""
  1799. def __init__(self, f, start=None, stop=None):
  1800. """Initialize a _PartialFile."""
  1801. _ProxyFile.__init__(self, f, start)
  1802. self._start = start
  1803. self._stop = stop
  1804. def tell(self):
  1805. """Return the position with respect to start."""
  1806. return _ProxyFile.tell(self) - self._start
  1807. def seek(self, offset, whence=0):
  1808. """Change position, possibly with respect to start or stop."""
  1809. if whence == 0:
  1810. self._pos = self._start
  1811. whence = 1
  1812. elif whence == 2:
  1813. self._pos = self._stop
  1814. whence = 1
  1815. _ProxyFile.seek(self, offset, whence)
  1816. def _read(self, size, read_method):
  1817. """Read size bytes using read_method, honoring start and stop."""
  1818. remaining = self._stop - self._pos
  1819. if remaining <= 0:
  1820. return b''
  1821. if size is None or size < 0 or size > remaining:
  1822. size = remaining
  1823. return _ProxyFile._read(self, size, read_method)
  1824. def close(self):
  1825. # do *not* close the underlying file object for partial files,
  1826. # since it's global to the mailbox object
  1827. if hasattr(self, '_file'):
  1828. del self._file
  1829. def _lock_file(f, dotlock=True):
  1830. """Lock file f using lockf and dot locking."""
  1831. dotlock_done = False
  1832. try:
  1833. if fcntl:
  1834. try:
  1835. fcntl.lockf(f, fcntl.LOCK_EX | fcntl.LOCK_NB)
  1836. except OSError as e:
  1837. if e.errno in (errno.EAGAIN, errno.EACCES, errno.EROFS):
  1838. raise ExternalClashError('lockf: lock unavailable: %s' %
  1839. f.name)
  1840. else:
  1841. raise
  1842. if dotlock:
  1843. try:
  1844. pre_lock = _create_temporary(f.name + '.lock')
  1845. pre_lock.close()
  1846. except OSError as e:
  1847. if e.errno in (errno.EACCES, errno.EROFS):
  1848. return # Without write access, just skip dotlocking.
  1849. else:
  1850. raise
  1851. try:
  1852. try:
  1853. os.link(pre_lock.name, f.name + '.lock')
  1854. dotlock_done = True
  1855. except (AttributeError, PermissionError):
  1856. os.rename(pre_lock.name, f.name + '.lock')
  1857. dotlock_done = True
  1858. else:
  1859. os.unlink(pre_lock.name)
  1860. except FileExistsError:
  1861. os.remove(pre_lock.name)
  1862. raise ExternalClashError('dot lock unavailable: %s' %
  1863. f.name)
  1864. except:
  1865. if fcntl:
  1866. fcntl.lockf(f, fcntl.LOCK_UN)
  1867. if dotlock_done:
  1868. os.remove(f.name + '.lock')
  1869. raise
  1870. def _unlock_file(f):
  1871. """Unlock file f using lockf and dot locking."""
  1872. if fcntl:
  1873. fcntl.lockf(f, fcntl.LOCK_UN)
  1874. if os.path.exists(f.name + '.lock'):
  1875. os.remove(f.name + '.lock')
  1876. def _create_carefully(path):
  1877. """Create a file if it doesn't exist and open for reading and writing."""
  1878. fd = os.open(path, os.O_CREAT | os.O_EXCL | os.O_RDWR, 0o666)
  1879. try:
  1880. return open(path, 'rb+')
  1881. finally:
  1882. os.close(fd)
  1883. def _create_temporary(path):
  1884. """Create a temp file based on path and open for reading and writing."""
  1885. return _create_carefully('%s.%s.%s.%s' % (path, int(time.time()),
  1886. socket.gethostname(),
  1887. os.getpid()))
  1888. def _sync_flush(f):
  1889. """Ensure changes to file f are physically on disk."""
  1890. f.flush()
  1891. if hasattr(os, 'fsync'):
  1892. os.fsync(f.fileno())
  1893. def _sync_close(f):
  1894. """Close file f, ensuring all changes are physically on disk."""
  1895. _sync_flush(f)
  1896. f.close()
  1897. class Error(Exception):
  1898. """Raised for module-specific errors."""
  1899. class NoSuchMailboxError(Error):
  1900. """The specified mailbox does not exist and won't be created."""
  1901. class NotEmptyError(Error):
  1902. """The specified mailbox is not empty and deletion was requested."""
  1903. class ExternalClashError(Error):
  1904. """Another process caused an action to fail."""
  1905. class FormatError(Error):
  1906. """A file appears to have an invalid format."""