Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

maildir.py 27KB

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