mailbox.py 77 KB

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