maildir.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  1. # -*- test-case-name: twisted.mail.test.test_mail -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Maildir-style mailbox support.
  6. """
  7. import os
  8. import stat
  9. import socket
  10. from hashlib import md5
  11. from zope.interface import implementer
  12. try:
  13. import cStringIO as StringIO
  14. except ImportError:
  15. import StringIO
  16. from twisted.mail import pop3
  17. from twisted.mail import smtp
  18. from twisted.protocols import basic
  19. from twisted.persisted import dirdbm
  20. from twisted.python import log, failure
  21. from twisted.mail import mail
  22. from twisted.internet import interfaces, defer, reactor
  23. from twisted.cred import portal, credentials, checkers
  24. from twisted.cred.error import UnauthorizedLogin
  25. INTERNAL_ERROR = '''\
  26. From: Twisted.mail Internals
  27. Subject: An Error Occurred
  28. An internal server error has occurred. Please contact the
  29. server administrator.
  30. '''
  31. class _MaildirNameGenerator:
  32. """
  33. A utility class to generate a unique maildir name.
  34. @type n: L{int}
  35. @ivar n: A counter used to generate unique integers.
  36. @type p: L{int}
  37. @ivar p: The ID of the current process.
  38. @type s: L{bytes}
  39. @ivar s: A representation of the hostname.
  40. @ivar _clock: See C{clock} parameter of L{__init__}.
  41. """
  42. n = 0
  43. p = os.getpid()
  44. s = socket.gethostname().replace('/', r'\057').replace(':', r'\072')
  45. def __init__(self, clock):
  46. """
  47. @type clock: L{IReactorTime <interfaces.IReactorTime>} provider
  48. @param clock: A reactor which will be used to learn the current time.
  49. """
  50. self._clock = clock
  51. def generate(self):
  52. """
  53. Generate a string which is intended to be unique across all calls to
  54. this function (across all processes, reboots, etc).
  55. Strings returned by earlier calls to this method will compare less
  56. than strings returned by later calls as long as the clock provided
  57. doesn't go backwards.
  58. @rtype: L{bytes}
  59. @return: A unique string.
  60. """
  61. self.n = self.n + 1
  62. t = self._clock.seconds()
  63. seconds = str(int(t))
  64. microseconds = '%07d' % (int((t - int(t)) * 10e6),)
  65. return '%s.M%sP%sQ%s.%s' % (seconds, microseconds,
  66. self.p, self.n, self.s)
  67. _generateMaildirName = _MaildirNameGenerator(reactor).generate
  68. def initializeMaildir(dir):
  69. """
  70. Create a maildir user directory if it doesn't already exist.
  71. @type dir: L{bytes}
  72. @param dir: The path name for a user directory.
  73. """
  74. if not os.path.isdir(dir):
  75. os.mkdir(dir, 0o700)
  76. for subdir in ['new', 'cur', 'tmp', '.Trash']:
  77. os.mkdir(os.path.join(dir, subdir), 0o700)
  78. for subdir in ['new', 'cur', 'tmp']:
  79. os.mkdir(os.path.join(dir, '.Trash', subdir), 0o700)
  80. # touch
  81. open(os.path.join(dir, '.Trash', 'maildirfolder'), 'w').close()
  82. class MaildirMessage(mail.FileMessage):
  83. """
  84. A message receiver which adds a header and delivers a message to a file
  85. whose name includes the size of the message.
  86. @type size: L{int}
  87. @ivar size: The number of octets in the message.
  88. """
  89. size = None
  90. def __init__(self, address, fp, *a, **kw):
  91. """
  92. @type address: L{bytes}
  93. @param address: The address of the message recipient.
  94. @type fp: file-like object
  95. @param fp: The file in which to store the message while it is being
  96. received.
  97. @type a: 2-L{tuple} of (0) L{bytes}, (1) L{bytes}
  98. @param a: Positional arguments for L{FileMessage.__init__}.
  99. @type kw: L{dict}
  100. @param kw: Keyword arguments for L{FileMessage.__init__}.
  101. """
  102. header = "Delivered-To: %s\n" % address
  103. fp.write(header)
  104. self.size = len(header)
  105. mail.FileMessage.__init__(self, fp, *a, **kw)
  106. def lineReceived(self, line):
  107. """
  108. Write a line to the file.
  109. @type line: L{bytes}
  110. @param line: A received line.
  111. """
  112. mail.FileMessage.lineReceived(self, line)
  113. self.size += len(line)+1
  114. def eomReceived(self):
  115. """
  116. At the end of message, rename the file holding the message to its final
  117. name concatenated with the size of the file.
  118. @rtype: L{Deferred <defer.Deferred>} which successfully results in
  119. L{bytes}
  120. @return: A deferred which returns the name of the file holding the
  121. message.
  122. """
  123. self.finalName = self.finalName+',S=%d' % self.size
  124. return mail.FileMessage.eomReceived(self)
  125. @implementer(mail.IAliasableDomain)
  126. class AbstractMaildirDomain:
  127. """
  128. An abstract maildir-backed domain.
  129. @type alias: L{None} or L{dict} mapping
  130. L{bytes} to L{AliasBase}
  131. @ivar alias: A mapping of username to alias.
  132. @ivar root: See L{__init__}.
  133. """
  134. alias = None
  135. root = None
  136. def __init__(self, service, root):
  137. """
  138. @type service: L{MailService}
  139. @param service: An email service.
  140. @type root: L{bytes}
  141. @param root: The maildir root directory.
  142. """
  143. self.root = root
  144. def userDirectory(self, user):
  145. """
  146. Return the maildir directory for a user.
  147. @type user: L{bytes}
  148. @param user: A username.
  149. @rtype: L{bytes} or L{None}
  150. @return: The user's mail directory for a valid user. Otherwise,
  151. L{None}.
  152. """
  153. return None
  154. def setAliasGroup(self, alias):
  155. """
  156. Set the group of defined aliases for this domain.
  157. @type alias: L{dict} mapping L{bytes} to L{IAlias} provider.
  158. @param alias: A mapping of domain name to alias.
  159. """
  160. self.alias = alias
  161. def exists(self, user, memo=None):
  162. """
  163. Check whether a user exists in this domain or an alias of it.
  164. @type user: L{User}
  165. @param user: A user.
  166. @type memo: L{None} or L{dict} of L{AliasBase}
  167. @param memo: A record of the addresses already considered while
  168. resolving aliases. The default value should be used by all
  169. external code.
  170. @rtype: no-argument callable which returns L{IMessage <smtp.IMessage>}
  171. provider.
  172. @return: A function which takes no arguments and returns a message
  173. receiver for the user.
  174. @raises SMTPBadRcpt: When the given user does not exist in this domain
  175. or an alias of it.
  176. """
  177. if self.userDirectory(user.dest.local) is not None:
  178. return lambda: self.startMessage(user)
  179. try:
  180. a = self.alias[user.dest.local]
  181. except:
  182. raise smtp.SMTPBadRcpt(user)
  183. else:
  184. aliases = a.resolve(self.alias, memo)
  185. if aliases:
  186. return lambda: aliases
  187. log.err("Bad alias configuration: " + str(user))
  188. raise smtp.SMTPBadRcpt(user)
  189. def startMessage(self, user):
  190. """
  191. Create a maildir message for a user.
  192. @type user: L{bytes}
  193. @param user: A username.
  194. @rtype: L{MaildirMessage}
  195. @return: A message receiver for this user.
  196. """
  197. if isinstance(user, str):
  198. name, domain = user.split('@', 1)
  199. else:
  200. name, domain = user.dest.local, user.dest.domain
  201. dir = self.userDirectory(name)
  202. fname = _generateMaildirName()
  203. filename = os.path.join(dir, 'tmp', fname)
  204. fp = open(filename, 'w')
  205. return MaildirMessage('%s@%s' % (name, domain), fp, filename,
  206. os.path.join(dir, 'new', fname))
  207. def willRelay(self, user, protocol):
  208. """
  209. Check whether this domain will relay.
  210. @type user: L{Address}
  211. @param user: The destination address.
  212. @type protocol: L{SMTP}
  213. @param protocol: The protocol over which the message to be relayed is
  214. being received.
  215. @rtype: L{bool}
  216. @return: An indication of whether this domain will relay the message to
  217. the destination.
  218. """
  219. return False
  220. def addUser(self, user, password):
  221. """
  222. Add a user to this domain.
  223. Subclasses should override this method.
  224. @type user: L{bytes}
  225. @param user: A username.
  226. @type password: L{bytes}
  227. @param password: A password.
  228. """
  229. raise NotImplementedError
  230. def getCredentialsCheckers(self):
  231. """
  232. Return credentials checkers for this domain.
  233. Subclasses should override this method.
  234. @rtype: L{list} of L{ICredentialsChecker
  235. <checkers.ICredentialsChecker>} provider
  236. @return: Credentials checkers for this domain.
  237. """
  238. raise NotImplementedError
  239. @implementer(interfaces.IConsumer)
  240. class _MaildirMailboxAppendMessageTask:
  241. """
  242. A task which adds a message to a maildir mailbox.
  243. @ivar mbox: See L{__init__}.
  244. @type defer: L{Deferred <defer.Deferred>} which successfully returns
  245. L{None}
  246. @ivar defer: A deferred which fires when the task has completed.
  247. @type opencall: L{IDelayedCall <interfaces.IDelayedCall>} provider or
  248. L{None}
  249. @ivar opencall: A scheduled call to L{prodProducer}.
  250. @type msg: file-like object
  251. @ivar msg: The message to add.
  252. @type tmpname: L{bytes}
  253. @ivar tmpname: The pathname of the temporary file holding the message while
  254. it is being transferred.
  255. @type fh: file
  256. @ivar fh: The new maildir file.
  257. @type filesender: L{FileSender <basic.FileSender>}
  258. @ivar filesender: A file sender which sends the message.
  259. @type myproducer: L{IProducer <interfaces.IProducer>}
  260. @ivar myproducer: The registered producer.
  261. @type streaming: L{bool}
  262. @ivar streaming: Indicates whether the registered producer provides a
  263. streaming interface.
  264. """
  265. osopen = staticmethod(os.open)
  266. oswrite = staticmethod(os.write)
  267. osclose = staticmethod(os.close)
  268. osrename = staticmethod(os.rename)
  269. def __init__(self, mbox, msg):
  270. """
  271. @type mbox: L{MaildirMailbox}
  272. @param mbox: A maildir mailbox.
  273. @type msg: L{bytes} or file-like object
  274. @param msg: The message to add.
  275. """
  276. self.mbox = mbox
  277. self.defer = defer.Deferred()
  278. self.openCall = None
  279. if not hasattr(msg, "read"):
  280. msg = StringIO.StringIO(msg)
  281. self.msg = msg
  282. def startUp(self):
  283. """
  284. Start transferring the message to the mailbox.
  285. """
  286. self.createTempFile()
  287. if self.fh != -1:
  288. self.filesender = basic.FileSender()
  289. self.filesender.beginFileTransfer(self.msg, self)
  290. def registerProducer(self, producer, streaming):
  291. """
  292. Register a producer and start asking it for data if it is
  293. non-streaming.
  294. @type producer: L{IProducer <interfaces.IProducer>}
  295. @param producer: A producer.
  296. @type streaming: L{bool}
  297. @param streaming: A flag indicating whether the producer provides a
  298. streaming interface.
  299. """
  300. self.myproducer = producer
  301. self.streaming = streaming
  302. if not streaming:
  303. self.prodProducer()
  304. def prodProducer(self):
  305. """
  306. Repeatedly prod a non-streaming producer to produce data.
  307. """
  308. self.openCall = None
  309. if self.myproducer is not None:
  310. self.openCall = reactor.callLater(0, self.prodProducer)
  311. self.myproducer.resumeProducing()
  312. def unregisterProducer(self):
  313. """
  314. Finish transferring the message to the mailbox.
  315. """
  316. self.myproducer = None
  317. self.streaming = None
  318. self.osclose(self.fh)
  319. self.moveFileToNew()
  320. def write(self, data):
  321. """
  322. Write data to the maildir file.
  323. @type data: L{bytes}
  324. @param data: Data to be written to the file.
  325. """
  326. try:
  327. self.oswrite(self.fh, data)
  328. except:
  329. self.fail()
  330. def fail(self, err=None):
  331. """
  332. Fire the deferred to indicate the task completed with a failure.
  333. @type err: L{Failure <failure.Failure>}
  334. @param err: The error that occurred.
  335. """
  336. if err is None:
  337. err = failure.Failure()
  338. if self.openCall is not None:
  339. self.openCall.cancel()
  340. self.defer.errback(err)
  341. self.defer = None
  342. def moveFileToNew(self):
  343. """
  344. Place the message in the I{new/} directory, add it to the mailbox and
  345. fire the deferred to indicate that the task has completed
  346. successfully.
  347. """
  348. while True:
  349. newname = os.path.join(self.mbox.path, "new", _generateMaildirName())
  350. try:
  351. self.osrename(self.tmpname, newname)
  352. break
  353. except OSError as e:
  354. (err, estr) = e.args
  355. import errno
  356. # if the newname exists, retry with a new newname.
  357. if err != errno.EEXIST:
  358. self.fail()
  359. newname = None
  360. break
  361. if newname is not None:
  362. self.mbox.list.append(newname)
  363. self.defer.callback(None)
  364. self.defer = None
  365. def createTempFile(self):
  366. """
  367. Create a temporary file to hold the message as it is being transferred.
  368. """
  369. attr = (os.O_RDWR | os.O_CREAT | os.O_EXCL
  370. | getattr(os, "O_NOINHERIT", 0)
  371. | getattr(os, "O_NOFOLLOW", 0))
  372. tries = 0
  373. self.fh = -1
  374. while True:
  375. self.tmpname = os.path.join(self.mbox.path, "tmp", _generateMaildirName())
  376. try:
  377. self.fh = self.osopen(self.tmpname, attr, 0o600)
  378. return None
  379. except OSError:
  380. tries += 1
  381. if tries > 500:
  382. self.defer.errback(RuntimeError("Could not create tmp file for %s" % self.mbox.path))
  383. self.defer = None
  384. return None
  385. class MaildirMailbox(pop3.Mailbox):
  386. """
  387. A maildir-backed mailbox.
  388. @ivar path: See L{__init__}.
  389. @type list: L{list} of L{int} or 2-L{tuple} of (0) file-like object,
  390. (1) L{bytes}
  391. @ivar list: Information about the messages in the mailbox. For undeleted
  392. messages, the file containing the message and the
  393. full path name of the file are stored. Deleted messages are indicated
  394. by 0.
  395. @type deleted: L{dict} mapping 2-L{tuple} of (0) file-like object,
  396. (1) L{bytes} to L{bytes}
  397. @type deleted: A mapping of the information about a file before it was
  398. deleted to the full path name of the deleted file in the I{.Trash/}
  399. subfolder.
  400. """
  401. AppendFactory = _MaildirMailboxAppendMessageTask
  402. def __init__(self, path):
  403. """
  404. @type path: L{bytes}
  405. @param path: The directory name for a maildir mailbox.
  406. """
  407. self.path = path
  408. self.list = []
  409. self.deleted = {}
  410. initializeMaildir(path)
  411. for name in ('cur', 'new'):
  412. for file in os.listdir(os.path.join(path, name)):
  413. self.list.append((file, os.path.join(path, name, file)))
  414. self.list.sort()
  415. self.list = [e[1] for e in self.list]
  416. def listMessages(self, i=None):
  417. """
  418. Retrieve the size of a message, or, if none is specified, the size of
  419. each message in the mailbox.
  420. @type i: L{int} or L{None}
  421. @param i: The 0-based index of a message.
  422. @rtype: L{int} or L{list} of L{int}
  423. @return: The number of octets in the specified message, or, if an index
  424. is not specified, a list of the number of octets for all messages
  425. in the mailbox. Any value which corresponds to a deleted message
  426. is set to 0.
  427. @raise IndexError: When the index does not correspond to a message in
  428. the mailbox.
  429. """
  430. if i is None:
  431. ret = []
  432. for mess in self.list:
  433. if mess:
  434. ret.append(os.stat(mess)[stat.ST_SIZE])
  435. else:
  436. ret.append(0)
  437. return ret
  438. return self.list[i] and os.stat(self.list[i])[stat.ST_SIZE] or 0
  439. def getMessage(self, i):
  440. """
  441. Retrieve a file-like object with the contents of a message.
  442. @type i: L{int}
  443. @param i: The 0-based index of a message.
  444. @rtype: file-like object
  445. @return: A file containing the message.
  446. @raise IndexError: When the index does not correspond to a message in
  447. the mailbox.
  448. """
  449. return open(self.list[i])
  450. def getUidl(self, i):
  451. """
  452. Get a unique identifier for a message.
  453. @type i: L{int}
  454. @param i: The 0-based index of a message.
  455. @rtype: L{bytes}
  456. @return: A string of printable characters uniquely identifying the
  457. message for all time.
  458. @raise IndexError: When the index does not correspond to a message in
  459. the mailbox.
  460. """
  461. # Returning the actual filename is a mistake. Hash it.
  462. base = os.path.basename(self.list[i])
  463. return md5(base).hexdigest()
  464. def deleteMessage(self, i):
  465. """
  466. Mark a message for deletion.
  467. Move the message to the I{.Trash/} subfolder so it can be undeleted
  468. by an administrator.
  469. @type i: L{int}
  470. @param i: The 0-based index of a message.
  471. @raise IndexError: When the index does not correspond to a message in
  472. the mailbox.
  473. """
  474. trashFile = os.path.join(
  475. self.path, '.Trash', 'cur', os.path.basename(self.list[i])
  476. )
  477. os.rename(self.list[i], trashFile)
  478. self.deleted[self.list[i]] = trashFile
  479. self.list[i] = 0
  480. def undeleteMessages(self):
  481. """
  482. Undelete all messages marked for deletion.
  483. Move each message marked for deletion from the I{.Trash/} subfolder back
  484. to its original position.
  485. """
  486. for (real, trash) in self.deleted.items():
  487. try:
  488. os.rename(trash, real)
  489. except OSError as e:
  490. (err, estr) = e.args
  491. import errno
  492. # If the file has been deleted from disk, oh well!
  493. if err != errno.ENOENT:
  494. raise
  495. # This is a pass
  496. else:
  497. try:
  498. self.list[self.list.index(0)] = real
  499. except ValueError:
  500. self.list.append(real)
  501. self.deleted.clear()
  502. def appendMessage(self, txt):
  503. """
  504. Add a message to the mailbox.
  505. @type txt: L{bytes} or file-like object
  506. @param txt: A message to add.
  507. @rtype: L{Deferred <defer.Deferred>}
  508. @return: A deferred which fires when the message has been added to
  509. the mailbox.
  510. """
  511. task = self.AppendFactory(self, txt)
  512. result = task.defer
  513. task.startUp()
  514. return result
  515. @implementer(pop3.IMailbox)
  516. class StringListMailbox:
  517. """
  518. An in-memory mailbox.
  519. @ivar msgs: See L{__init__}.
  520. @type _delete: L{set} of L{int}
  521. @ivar _delete: The indices of messages which have been marked for deletion.
  522. """
  523. def __init__(self, msgs):
  524. """
  525. @type msgs: L{list} of L{bytes}
  526. @param msgs: The contents of each message in the mailbox.
  527. """
  528. self.msgs = msgs
  529. self._delete = set()
  530. def listMessages(self, i=None):
  531. """
  532. Retrieve the size of a message, or, if none is specified, the size of
  533. each message in the mailbox.
  534. @type i: L{int} or L{None}
  535. @param i: The 0-based index of a message.
  536. @rtype: L{int} or L{list} of L{int}
  537. @return: The number of octets in the specified message, or, if an index
  538. is not specified, a list of the number of octets in each message in
  539. the mailbox. Any value which corresponds to a deleted message is
  540. set to 0.
  541. @raise IndexError: When the index does not correspond to a message in
  542. the mailbox.
  543. """
  544. if i is None:
  545. return [self.listMessages(msg) for msg in range(len(self.msgs))]
  546. if i in self._delete:
  547. return 0
  548. return len(self.msgs[i])
  549. def getMessage(self, i):
  550. """
  551. Return an in-memory file-like object with the contents of a message.
  552. @type i: L{int}
  553. @param i: The 0-based index of a message.
  554. @rtype: L{StringIO <cStringIO.StringIO>}
  555. @return: An in-memory file-like object containing the message.
  556. @raise IndexError: When the index does not correspond to a message in
  557. the mailbox.
  558. """
  559. return StringIO.StringIO(self.msgs[i])
  560. def getUidl(self, i):
  561. """
  562. Get a unique identifier for a message.
  563. @type i: L{int}
  564. @param i: The 0-based index of a message.
  565. @rtype: L{bytes}
  566. @return: A hash of the contents of the message at the given index.
  567. @raise IndexError: When the index does not correspond to a message in
  568. the mailbox.
  569. """
  570. return md5(self.msgs[i]).hexdigest()
  571. def deleteMessage(self, i):
  572. """
  573. Mark a message for deletion.
  574. @type i: L{int}
  575. @param i: The 0-based index of a message to delete.
  576. @raise IndexError: When the index does not correspond to a message in
  577. the mailbox.
  578. """
  579. self._delete.add(i)
  580. def undeleteMessages(self):
  581. """
  582. Undelete any messages which have been marked for deletion.
  583. """
  584. self._delete = set()
  585. def sync(self):
  586. """
  587. Discard the contents of any messages marked for deletion.
  588. """
  589. for index in self._delete:
  590. self.msgs[index] = ""
  591. self._delete = set()
  592. @implementer(portal.IRealm)
  593. class MaildirDirdbmDomain(AbstractMaildirDomain):
  594. """
  595. A maildir-backed domain where membership is checked with a
  596. L{DirDBM <dirdbm.DirDBM>} database.
  597. The directory structure of a MaildirDirdbmDomain is:
  598. /passwd <-- a DirDBM directory
  599. /USER/{cur, new, del} <-- each user has these three directories
  600. @ivar postmaster: See L{__init__}.
  601. @type dbm: L{DirDBM <dirdbm.DirDBM>}
  602. @ivar dbm: The authentication database for the domain.
  603. """
  604. portal = None
  605. _credcheckers = None
  606. def __init__(self, service, root, postmaster=0):
  607. """
  608. @type service: L{MailService}
  609. @param service: An email service.
  610. @type root: L{bytes}
  611. @param root: The maildir root directory.
  612. @type postmaster: L{bool}
  613. @param postmaster: A flag indicating whether non-existent addresses
  614. should be forwarded to the postmaster (C{True}) or
  615. bounced (C{False}).
  616. """
  617. AbstractMaildirDomain.__init__(self, service, root)
  618. dbm = os.path.join(root, 'passwd')
  619. if not os.path.exists(dbm):
  620. os.makedirs(dbm)
  621. self.dbm = dirdbm.open(dbm)
  622. self.postmaster = postmaster
  623. def userDirectory(self, name):
  624. """
  625. Return the path to a user's mail directory.
  626. @type name: L{bytes}
  627. @param name: A username.
  628. @rtype: L{bytes} or L{None}
  629. @return: The path to the user's mail directory for a valid user. For
  630. an invalid user, the path to the postmaster's mailbox if bounces
  631. are redirected there. Otherwise, L{None}.
  632. """
  633. if name not in self.dbm:
  634. if not self.postmaster:
  635. return None
  636. name = 'postmaster'
  637. dir = os.path.join(self.root, name)
  638. if not os.path.exists(dir):
  639. initializeMaildir(dir)
  640. return dir
  641. def addUser(self, user, password):
  642. """
  643. Add a user to this domain by adding an entry in the authentication
  644. database and initializing the user's mail directory.
  645. @type user: L{bytes}
  646. @param user: A username.
  647. @type password: L{bytes}
  648. @param password: A password.
  649. """
  650. self.dbm[user] = password
  651. # Ensure it is initialized
  652. self.userDirectory(user)
  653. def getCredentialsCheckers(self):
  654. """
  655. Return credentials checkers for this domain.
  656. @rtype: L{list} of L{ICredentialsChecker
  657. <checkers.ICredentialsChecker>} provider
  658. @return: Credentials checkers for this domain.
  659. """
  660. if self._credcheckers is None:
  661. self._credcheckers = [DirdbmDatabase(self.dbm)]
  662. return self._credcheckers
  663. def requestAvatar(self, avatarId, mind, *interfaces):
  664. """
  665. Get the mailbox for an authenticated user.
  666. The mailbox for the authenticated user will be returned only if the
  667. given interfaces include L{IMailbox <pop3.IMailbox>}. Requests for
  668. anonymous access will be met with a mailbox containing a message
  669. indicating that an internal error has occurred.
  670. @type avatarId: L{bytes} or C{twisted.cred.checkers.ANONYMOUS}
  671. @param avatarId: A string which identifies a user or an object which
  672. signals a request for anonymous access.
  673. @type mind: L{None}
  674. @param mind: Unused.
  675. @type interfaces: n-L{tuple} of C{zope.interface.Interface}
  676. @param interfaces: A group of interfaces, one of which the avatar
  677. must support.
  678. @rtype: 3-L{tuple} of (0) L{IMailbox <pop3.IMailbox>},
  679. (1) L{IMailbox <pop3.IMailbox>} provider, (2) no-argument
  680. callable
  681. @return: A tuple of the supported interface, a mailbox, and a
  682. logout function.
  683. @raise NotImplementedError: When the given interfaces do not include
  684. L{IMailbox <pop3.IMailbox>}.
  685. """
  686. if pop3.IMailbox not in interfaces:
  687. raise NotImplementedError("No interface")
  688. if avatarId == checkers.ANONYMOUS:
  689. mbox = StringListMailbox([INTERNAL_ERROR])
  690. else:
  691. mbox = MaildirMailbox(os.path.join(self.root, avatarId))
  692. return (
  693. pop3.IMailbox,
  694. mbox,
  695. lambda: None
  696. )
  697. @implementer(checkers.ICredentialsChecker)
  698. class DirdbmDatabase:
  699. """
  700. A credentials checker which authenticates users out of a
  701. L{DirDBM <dirdbm.DirDBM>} database.
  702. @type dirdbm: L{DirDBM <dirdbm.DirDBM>}
  703. @ivar dirdbm: An authentication database.
  704. """
  705. # credentialInterfaces is not used by the class
  706. credentialInterfaces = (
  707. credentials.IUsernamePassword,
  708. credentials.IUsernameHashedPassword
  709. )
  710. def __init__(self, dbm):
  711. """
  712. @type dbm: L{DirDBM <dirdbm.DirDBM>}
  713. @param dbm: An authentication database.
  714. """
  715. self.dirdbm = dbm
  716. def requestAvatarId(self, c):
  717. """
  718. Authenticate a user and, if successful, return their username.
  719. @type c: L{IUsernamePassword <credentials.IUsernamePassword>} or
  720. L{IUsernameHashedPassword <credentials.IUsernameHashedPassword>}
  721. provider.
  722. @param c: Credentials.
  723. @rtype: L{bytes}
  724. @return: A string which identifies an user.
  725. @raise UnauthorizedLogin: When the credentials check fails.
  726. """
  727. if c.username in self.dirdbm:
  728. if c.checkPassword(self.dirdbm[c.username]):
  729. return c.username
  730. raise UnauthorizedLogin()