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.

pop3.py 54KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704
  1. # -*- test-case-name: twisted.mail.test.test_pop3 -*-
  2. #
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. Post-office Protocol version 3.
  7. @author: Glyph Lefkowitz
  8. @author: Jp Calderone
  9. """
  10. import base64
  11. import binascii
  12. import warnings
  13. from hashlib import md5
  14. from typing import Optional
  15. from zope.interface import implementer
  16. from twisted import cred
  17. from twisted.internet import defer, interfaces, task
  18. from twisted.mail import smtp
  19. from twisted.mail._except import POP3ClientError, POP3Error, _POP3MessageDeleted
  20. from twisted.mail.interfaces import (
  21. IMailboxPOP3 as IMailbox,
  22. IServerFactoryPOP3 as IServerFactory,
  23. )
  24. from twisted.protocols import basic, policies
  25. from twisted.python import log
  26. # Authentication
  27. @implementer(cred.credentials.IUsernameHashedPassword)
  28. class APOPCredentials:
  29. """
  30. Credentials for use in APOP authentication.
  31. @ivar magic: See L{__init__}
  32. @ivar username: See L{__init__}
  33. @ivar digest: See L{__init__}
  34. """
  35. def __init__(self, magic, username, digest):
  36. """
  37. @type magic: L{bytes}
  38. @param magic: The challenge string used to encrypt the password.
  39. @type username: L{bytes}
  40. @param username: The username associated with these credentials.
  41. @type digest: L{bytes}
  42. @param digest: An encrypted version of the user's password. Should be
  43. generated as an MD5 hash of the challenge string concatenated with
  44. the plaintext password.
  45. """
  46. self.magic = magic
  47. self.username = username
  48. self.digest = digest
  49. def checkPassword(self, password):
  50. """
  51. Validate a plaintext password against the credentials.
  52. @type password: L{bytes}
  53. @param password: A plaintext password.
  54. @rtype: L{bool}
  55. @return: C{True} if the credentials represented by this object match
  56. the given password, C{False} if they do not.
  57. """
  58. seed = self.magic + password
  59. myDigest = md5(seed).hexdigest()
  60. return myDigest == self.digest
  61. class _HeadersPlusNLines:
  62. """
  63. A utility class to retrieve the header and some lines of the body of a mail
  64. message.
  65. @ivar _file: See L{__init__}
  66. @ivar _extraLines: See L{__init__}
  67. @type linecount: L{int}
  68. @ivar linecount: The number of full lines of the message body scanned.
  69. @type headers: L{bool}
  70. @ivar headers: An indication of which part of the message is being scanned.
  71. C{True} for the header and C{False} for the body.
  72. @type done: L{bool}
  73. @ivar done: A flag indicating when the desired part of the message has been
  74. scanned.
  75. @type buf: L{bytes}
  76. @ivar buf: The portion of the message body that has been scanned, up to
  77. C{n} lines.
  78. """
  79. def __init__(self, file, extraLines):
  80. """
  81. @type file: file-like object
  82. @param file: A file containing a mail message.
  83. @type extraLines: L{int}
  84. @param extraLines: The number of lines of the message body to retrieve.
  85. """
  86. self._file = file
  87. self._extraLines = extraLines
  88. self.linecount = 0
  89. self.headers = 1
  90. self.done = 0
  91. self.buf = b""
  92. def read(self, bytes):
  93. """
  94. Scan bytes from the file.
  95. @type bytes: L{int}
  96. @param bytes: The number of bytes to read from the file.
  97. @rtype: L{bytes}
  98. @return: Each portion of the header as it is scanned. Then, full lines
  99. of the message body as they are scanned. When more than one line
  100. of the header and/or body has been scanned, the result is the
  101. concatenation of the lines. When the scan results in no full
  102. lines, the empty string is returned.
  103. """
  104. if self.done:
  105. return b""
  106. data = self._file.read(bytes)
  107. if not data:
  108. return data
  109. if self.headers:
  110. df, sz = data.find(b"\r\n\r\n"), 4
  111. if df == -1:
  112. df, sz = data.find(b"\n\n"), 2
  113. if df != -1:
  114. df += sz
  115. val = data[:df]
  116. data = data[df:]
  117. self.linecount = 1
  118. self.headers = 0
  119. else:
  120. val = b""
  121. if self.linecount > 0:
  122. dsplit = (self.buf + data).split(b"\n")
  123. self.buf = dsplit[-1]
  124. for ln in dsplit[:-1]:
  125. if self.linecount > self._extraLines:
  126. self.done = 1
  127. return val
  128. val += ln + b"\n"
  129. self.linecount += 1
  130. return val
  131. else:
  132. return data
  133. class _IteratorBuffer:
  134. """
  135. An iterator which buffers the elements of a container and periodically
  136. passes them as input to a writer.
  137. @ivar write: See L{__init__}.
  138. @ivar memoryBufferSize: See L{__init__}.
  139. @type bufSize: L{int}
  140. @ivar bufSize: The number of bytes currently in the buffer.
  141. @type lines: L{list} of L{bytes}
  142. @ivar lines: The buffer, which is a list of strings.
  143. @type iterator: iterator which yields L{bytes}
  144. @ivar iterator: An iterator over a container of strings.
  145. """
  146. bufSize = 0
  147. def __init__(self, write, iterable, memoryBufferSize=None):
  148. """
  149. @type write: callable that takes L{list} of L{bytes}
  150. @param write: A writer which is a callable that takes a list of
  151. strings.
  152. @type iterable: iterable which yields L{bytes}
  153. @param iterable: An iterable container of strings.
  154. @type memoryBufferSize: L{int} or L{None}
  155. @param memoryBufferSize: The number of bytes to buffer before flushing
  156. the buffer to the writer.
  157. """
  158. self.lines = []
  159. self.write = write
  160. self.iterator = iter(iterable)
  161. if memoryBufferSize is None:
  162. memoryBufferSize = 2 ** 16
  163. self.memoryBufferSize = memoryBufferSize
  164. def __iter__(self):
  165. """
  166. Return an iterator.
  167. @rtype: iterator which yields L{bytes}
  168. @return: An iterator over strings.
  169. """
  170. return self
  171. def __next__(self):
  172. """
  173. Get the next string from the container, buffer it, and possibly send
  174. the buffer to the writer.
  175. The contents of the buffer are written when it is full or when no
  176. further values are available from the container.
  177. @raise StopIteration: When no further values are available from the
  178. container.
  179. """
  180. try:
  181. v = next(self.iterator)
  182. except StopIteration:
  183. if self.lines:
  184. self.write(self.lines)
  185. # Drop some references, in case they're edges in a cycle.
  186. del self.iterator, self.lines, self.write
  187. raise
  188. else:
  189. if v is not None:
  190. self.lines.append(v)
  191. self.bufSize += len(v)
  192. if self.bufSize > self.memoryBufferSize:
  193. self.write(self.lines)
  194. self.lines = []
  195. self.bufSize = 0
  196. next = __next__
  197. def iterateLineGenerator(proto, gen):
  198. """
  199. Direct the output of an iterator to the transport of a protocol and arrange
  200. for iteration to take place.
  201. @type proto: L{POP3}
  202. @param proto: A POP3 server protocol.
  203. @type gen: iterator which yields L{bytes}
  204. @param gen: An iterator over strings.
  205. @rtype: L{Deferred <defer.Deferred>}
  206. @return: A deferred which fires when the iterator finishes.
  207. """
  208. coll = _IteratorBuffer(proto.transport.writeSequence, gen)
  209. return proto.schedule(coll)
  210. def successResponse(response):
  211. """
  212. Format an object as a positive response.
  213. @type response: stringifyable L{object}
  214. @param response: An object with a string representation.
  215. @rtype: L{bytes}
  216. @return: A positive POP3 response string.
  217. """
  218. if not isinstance(response, bytes):
  219. response = str(response).encode("utf-8")
  220. return b"+OK " + response + b"\r\n"
  221. def formatStatResponse(msgs):
  222. """
  223. Format a list of message sizes into a STAT response.
  224. This generator function is intended to be used with
  225. L{Cooperator <twisted.internet.task.Cooperator>}.
  226. @type msgs: L{list} of L{int}
  227. @param msgs: A list of message sizes.
  228. @rtype: L{None} or L{bytes}
  229. @return: Yields none until a result is available, then a string that is
  230. suitable for use in a STAT response. The string consists of the number
  231. of messages and the total size of the messages in octets.
  232. """
  233. i = 0
  234. bytes = 0
  235. for size in msgs:
  236. i += 1
  237. bytes += size
  238. yield None
  239. yield successResponse(b"%d %d" % (i, bytes))
  240. def formatListLines(msgs):
  241. """
  242. Format a list of message sizes for use in a LIST response.
  243. @type msgs: L{list} of L{int}
  244. @param msgs: A list of message sizes.
  245. @rtype: L{bytes}
  246. @return: Yields a series of strings that are suitable for use as scan
  247. listings in a LIST response. Each string consists of a message number
  248. and its size in octets.
  249. """
  250. i = 0
  251. for size in msgs:
  252. i += 1
  253. yield b"%d %d\r\n" % (i, size)
  254. def formatListResponse(msgs):
  255. """
  256. Format a list of message sizes into a complete LIST response.
  257. This generator function is intended to be used with
  258. L{Cooperator <twisted.internet.task.Cooperator>}.
  259. @type msgs: L{list} of L{int}
  260. @param msgs: A list of message sizes.
  261. @rtype: L{bytes}
  262. @return: Yields a series of strings which make up a complete LIST response.
  263. """
  264. yield successResponse(b"%d" % (len(msgs),))
  265. yield from formatListLines(msgs)
  266. yield b".\r\n"
  267. def formatUIDListLines(msgs, getUidl):
  268. """
  269. Format a list of message sizes for use in a UIDL response.
  270. @param msgs: See L{formatUIDListResponse}
  271. @param getUidl: See L{formatUIDListResponse}
  272. @rtype: L{bytes}
  273. @return: Yields a series of strings that are suitable for use as unique-id
  274. listings in a UIDL response. Each string consists of a message number
  275. and its unique id.
  276. """
  277. for i, m in enumerate(msgs):
  278. if m is not None:
  279. uid = getUidl(i)
  280. if not isinstance(uid, bytes):
  281. uid = str(uid).encode("utf-8")
  282. yield b"%d %b\r\n" % (i + 1, uid)
  283. def formatUIDListResponse(msgs, getUidl):
  284. """
  285. Format a list of message sizes into a complete UIDL response.
  286. This generator function is intended to be used with
  287. L{Cooperator <twisted.internet.task.Cooperator>}.
  288. @type msgs: L{list} of L{int}
  289. @param msgs: A list of message sizes.
  290. @type getUidl: one-argument callable returning bytes
  291. @param getUidl: A callable which takes a message index number and returns
  292. the UID of the corresponding message in the mailbox.
  293. @rtype: L{bytes}
  294. @return: Yields a series of strings which make up a complete UIDL response.
  295. """
  296. yield successResponse("")
  297. yield from formatUIDListLines(msgs, getUidl)
  298. yield b".\r\n"
  299. @implementer(interfaces.IProducer)
  300. class POP3(basic.LineOnlyReceiver, policies.TimeoutMixin):
  301. """
  302. A POP3 server protocol.
  303. @type portal: L{Portal}
  304. @ivar portal: A portal for authentication.
  305. @type factory: L{IServerFactory} provider
  306. @ivar factory: A server factory which provides an interface for querying
  307. capabilities of the server.
  308. @type timeOut: L{int}
  309. @ivar timeOut: The number of seconds to wait for a command from the client
  310. before disconnecting.
  311. @type schedule: callable that takes interator and returns
  312. L{Deferred <defer.Deferred>}
  313. @ivar schedule: A callable that arranges for an iterator to be
  314. cooperatively iterated over along with all other iterators which have
  315. been passed to it such that runtime is divided between all of them. It
  316. returns a deferred which fires when the iterator finishes.
  317. @type magic: L{bytes} or L{None}
  318. @ivar magic: An APOP challenge. If not set, an APOP challenge string
  319. will be generated when a connection is made.
  320. @type _userIs: L{bytes} or L{None}
  321. @ivar _userIs: The username sent with the USER command.
  322. @type _onLogout: no-argument callable or L{None}
  323. @ivar _onLogout: The function to be executed when the connection is
  324. lost.
  325. @type mbox: L{IMailbox} provider
  326. @ivar mbox: The mailbox for the authenticated user.
  327. @type state: L{bytes}
  328. @ivar state: The state which indicates what type of messages are expected
  329. from the client. Valid states are 'COMMAND' and 'AUTH'
  330. @type blocked: L{None} or L{list} of 2-L{tuple} of
  331. (E{1}) L{bytes} (E{2}) L{tuple} of L{bytes}
  332. @ivar blocked: A list of blocked commands. While a response to a command
  333. is being generated by the server, other commands are blocked. When
  334. no command is outstanding, C{blocked} is set to none. Otherwise, it
  335. contains a list of information about blocked commands. Each list
  336. entry consists of the command and the arguments to the command.
  337. @type _highest: L{int}
  338. @ivar _highest: The 1-based index of the highest message retrieved.
  339. @type _auth: L{IUsernameHashedPassword
  340. <cred.credentials.IUsernameHashedPassword>} provider
  341. @ivar _auth: Authorization credentials.
  342. """
  343. magic: Optional[bytes] = None
  344. _userIs = None
  345. _onLogout = None
  346. AUTH_CMDS = [b"CAPA", b"USER", b"PASS", b"APOP", b"AUTH", b"RPOP", b"QUIT"]
  347. portal = None
  348. factory = None
  349. # The mailbox we're serving
  350. mbox = None
  351. # Set this pretty low -- POP3 clients are expected to log in, download
  352. # everything, and log out.
  353. timeOut = 300
  354. state = "COMMAND"
  355. # PIPELINE
  356. blocked = None
  357. # Cooperate and suchlike.
  358. schedule = staticmethod(task.coiterate)
  359. _highest = 0
  360. def connectionMade(self):
  361. """
  362. Send a greeting to the client after the connection has been made.
  363. """
  364. if self.magic is None:
  365. self.magic = self.generateMagic()
  366. self.successResponse(self.magic)
  367. self.setTimeout(self.timeOut)
  368. if getattr(self.factory, "noisy", True):
  369. log.msg("New connection from " + str(self.transport.getPeer()))
  370. def connectionLost(self, reason):
  371. """
  372. Clean up when the connection has been lost.
  373. @type reason: L{Failure}
  374. @param reason: The reason the connection was terminated.
  375. """
  376. if self._onLogout is not None:
  377. self._onLogout()
  378. self._onLogout = None
  379. self.setTimeout(None)
  380. def generateMagic(self):
  381. """
  382. Generate an APOP challenge.
  383. @rtype: L{bytes}
  384. @return: An RFC 822 message id format string.
  385. """
  386. return smtp.messageid()
  387. def successResponse(self, message=""):
  388. """
  389. Send a response indicating success.
  390. @type message: stringifyable L{object}
  391. @param message: An object whose string representation should be
  392. included in the response.
  393. """
  394. self.transport.write(successResponse(message))
  395. def failResponse(self, message=b""):
  396. """
  397. Send a response indicating failure.
  398. @type message: stringifyable L{object}
  399. @param message: An object whose string representation should be
  400. included in the response.
  401. """
  402. if not isinstance(message, bytes):
  403. message = str(message).encode("utf-8")
  404. self.sendLine(b"-ERR " + message)
  405. def lineReceived(self, line):
  406. """
  407. Pass a received line to a state machine function.
  408. @type line: L{bytes}
  409. @param line: A received line.
  410. """
  411. self.resetTimeout()
  412. getattr(self, "state_" + self.state)(line)
  413. def _unblock(self, _):
  414. """
  415. Process as many blocked commands as possible.
  416. If there are no more blocked commands, set up for the next command to
  417. be sent immediately.
  418. @type _: L{object}
  419. @param _: Ignored.
  420. """
  421. commands = self.blocked
  422. self.blocked = None
  423. while commands and self.blocked is None:
  424. cmd, args = commands.pop(0)
  425. self.processCommand(cmd, *args)
  426. if self.blocked is not None:
  427. self.blocked.extend(commands)
  428. def state_COMMAND(self, line):
  429. """
  430. Handle received lines for the COMMAND state in which commands from the
  431. client are expected.
  432. @type line: L{bytes}
  433. @param line: A received command.
  434. """
  435. try:
  436. return self.processCommand(*line.split(b" "))
  437. except (ValueError, AttributeError, POP3Error, TypeError) as e:
  438. log.err()
  439. self.failResponse(
  440. b": ".join(
  441. [
  442. b"bad protocol or server",
  443. e.__class__.__name__.encode("utf-8"),
  444. b"".join(e.args),
  445. ]
  446. )
  447. )
  448. def processCommand(self, command, *args):
  449. """
  450. Dispatch a command from the client for handling.
  451. @type command: L{bytes}
  452. @param command: A POP3 command.
  453. @type args: L{tuple} of L{bytes}
  454. @param args: Arguments to the command.
  455. @raise POP3Error: When the command is invalid or the command requires
  456. prior authentication which hasn't been performed.
  457. """
  458. if self.blocked is not None:
  459. self.blocked.append((command, args))
  460. return
  461. command = command.upper()
  462. authCmd = command in self.AUTH_CMDS
  463. if not self.mbox and not authCmd:
  464. raise POP3Error(b"not authenticated yet: cannot do " + command)
  465. f = getattr(self, "do_" + command.decode("utf-8"), None)
  466. if f:
  467. return f(*args)
  468. raise POP3Error(b"Unknown protocol command: " + command)
  469. def listCapabilities(self):
  470. """
  471. Return a list of server capabilities suitable for use in a CAPA
  472. response.
  473. @rtype: L{list} of L{bytes}
  474. @return: A list of server capabilities.
  475. """
  476. baseCaps = [
  477. b"TOP",
  478. b"USER",
  479. b"UIDL",
  480. b"PIPELINE",
  481. b"CELERITY",
  482. b"AUSPEX",
  483. b"POTENCE",
  484. ]
  485. if IServerFactory.providedBy(self.factory):
  486. # Oh my god. We can't just loop over a list of these because
  487. # each has spectacularly different return value semantics!
  488. try:
  489. v = self.factory.cap_IMPLEMENTATION()
  490. if v and not isinstance(v, bytes):
  491. v = str(v).encode("utf-8")
  492. except NotImplementedError:
  493. pass
  494. except BaseException:
  495. log.err()
  496. else:
  497. baseCaps.append(b"IMPLEMENTATION " + v)
  498. try:
  499. v = self.factory.cap_EXPIRE()
  500. if v and not isinstance(v, bytes):
  501. v = str(v).encode("utf-8")
  502. except NotImplementedError:
  503. pass
  504. except BaseException:
  505. log.err()
  506. else:
  507. if v is None:
  508. v = b"NEVER"
  509. if self.factory.perUserExpiration():
  510. if self.mbox:
  511. v = str(self.mbox.messageExpiration).encode("utf-8")
  512. else:
  513. v = v + b" USER"
  514. baseCaps.append(b"EXPIRE " + v)
  515. try:
  516. v = self.factory.cap_LOGIN_DELAY()
  517. if v and not isinstance(v, bytes):
  518. v = str(v).encode("utf-8")
  519. except NotImplementedError:
  520. pass
  521. except BaseException:
  522. log.err()
  523. else:
  524. if self.factory.perUserLoginDelay():
  525. if self.mbox:
  526. v = str(self.mbox.loginDelay).encode("utf-8")
  527. else:
  528. v = v + b" USER"
  529. baseCaps.append(b"LOGIN-DELAY " + v)
  530. try:
  531. v = self.factory.challengers
  532. except AttributeError:
  533. pass
  534. except BaseException:
  535. log.err()
  536. else:
  537. baseCaps.append(b"SASL " + b" ".join(v.keys()))
  538. return baseCaps
  539. def do_CAPA(self):
  540. """
  541. Handle a CAPA command.
  542. Respond with the server capabilities.
  543. """
  544. self.successResponse(b"I can do the following:")
  545. for cap in self.listCapabilities():
  546. self.sendLine(cap)
  547. self.sendLine(b".")
  548. def do_AUTH(self, args=None):
  549. """
  550. Handle an AUTH command.
  551. If the AUTH extension is not supported, send an error response. If an
  552. authentication mechanism was not specified in the command, send a list
  553. of all supported authentication methods. Otherwise, send an
  554. authentication challenge to the client and transition to the
  555. AUTH state.
  556. @type args: L{bytes} or L{None}
  557. @param args: The name of an authentication mechanism.
  558. """
  559. if not getattr(self.factory, "challengers", None):
  560. self.failResponse(b"AUTH extension unsupported")
  561. return
  562. if args is None:
  563. self.successResponse("Supported authentication methods:")
  564. for a in self.factory.challengers:
  565. self.sendLine(a.upper())
  566. self.sendLine(b".")
  567. return
  568. auth = self.factory.challengers.get(args.strip().upper())
  569. if not self.portal or not auth:
  570. self.failResponse(b"Unsupported SASL selected")
  571. return
  572. self._auth = auth()
  573. chal = self._auth.getChallenge()
  574. self.sendLine(b"+ " + base64.b64encode(chal))
  575. self.state = "AUTH"
  576. def state_AUTH(self, line):
  577. """
  578. Handle received lines for the AUTH state in which an authentication
  579. challenge response from the client is expected.
  580. Transition back to the COMMAND state. Check the credentials and
  581. complete the authorization process with the L{_cbMailbox}
  582. callback function on success or the L{_ebMailbox} and L{_ebUnexpected}
  583. errback functions on failure.
  584. @type line: L{bytes}
  585. @param line: The challenge response.
  586. """
  587. self.state = "COMMAND"
  588. try:
  589. parts = base64.b64decode(line).split(None, 1)
  590. except binascii.Error:
  591. self.failResponse(b"Invalid BASE64 encoding")
  592. else:
  593. if len(parts) != 2:
  594. self.failResponse(b"Invalid AUTH response")
  595. return
  596. self._auth.username = parts[0]
  597. self._auth.response = parts[1]
  598. d = self.portal.login(self._auth, None, IMailbox)
  599. d.addCallback(self._cbMailbox, parts[0])
  600. d.addErrback(self._ebMailbox)
  601. d.addErrback(self._ebUnexpected)
  602. def do_APOP(self, user, digest):
  603. """
  604. Handle an APOP command.
  605. Perform APOP authentication and complete the authorization process with
  606. the L{_cbMailbox} callback function on success or the L{_ebMailbox}
  607. and L{_ebUnexpected} errback functions on failure.
  608. @type user: L{bytes}
  609. @param user: A username.
  610. @type digest: L{bytes}
  611. @param digest: An MD5 digest string.
  612. """
  613. d = defer.maybeDeferred(self.authenticateUserAPOP, user, digest)
  614. d.addCallbacks(
  615. self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
  616. ).addErrback(self._ebUnexpected)
  617. def _cbMailbox(self, result, user):
  618. """
  619. Complete successful authentication.
  620. Save the mailbox and logout function for the authenticated user and
  621. send a successful response to the client.
  622. @type result: C{tuple}
  623. @param result: The first item of the tuple is a
  624. C{zope.interface.Interface} which is the interface
  625. supported by the avatar. The second item of the tuple is a
  626. L{IMailbox} provider which is the mailbox for the
  627. authenticated user. The third item of the tuple is a no-argument
  628. callable which is a function to be invoked when the session is
  629. terminated.
  630. @type user: L{bytes}
  631. @param user: The user being authenticated.
  632. """
  633. (interface, avatar, logout) = result
  634. if interface is not IMailbox:
  635. self.failResponse(b"Authentication failed")
  636. log.err("_cbMailbox() called with an interface other than IMailbox")
  637. return
  638. self.mbox = avatar
  639. self._onLogout = logout
  640. self.successResponse("Authentication succeeded")
  641. if getattr(self.factory, "noisy", True):
  642. log.msg(b"Authenticated login for " + user)
  643. def _ebMailbox(self, failure):
  644. """
  645. Handle an expected authentication failure.
  646. Send an appropriate error response for a L{LoginDenied} or
  647. L{LoginFailed} authentication failure.
  648. @type failure: L{Failure}
  649. @param failure: The authentication error.
  650. """
  651. failure = failure.trap(cred.error.LoginDenied, cred.error.LoginFailed)
  652. if issubclass(failure, cred.error.LoginDenied):
  653. self.failResponse("Access denied: " + str(failure))
  654. elif issubclass(failure, cred.error.LoginFailed):
  655. self.failResponse(b"Authentication failed")
  656. if getattr(self.factory, "noisy", True):
  657. log.msg("Denied login attempt from " + str(self.transport.getPeer()))
  658. def _ebUnexpected(self, failure):
  659. """
  660. Handle an unexpected authentication failure.
  661. Send an error response for an unexpected authentication failure.
  662. @type failure: L{Failure}
  663. @param failure: The authentication error.
  664. """
  665. self.failResponse("Server error: " + failure.getErrorMessage())
  666. log.err(failure)
  667. def do_USER(self, user):
  668. """
  669. Handle a USER command.
  670. Save the username and send a successful response prompting the client
  671. for the password.
  672. @type user: L{bytes}
  673. @param user: A username.
  674. """
  675. self._userIs = user
  676. self.successResponse(b"USER accepted, send PASS")
  677. def do_PASS(self, password, *words):
  678. """
  679. Handle a PASS command.
  680. If a USER command was previously received, authenticate the user and
  681. complete the authorization process with the L{_cbMailbox} callback
  682. function on success or the L{_ebMailbox} and L{_ebUnexpected} errback
  683. functions on failure. If a USER command was not previously received,
  684. send an error response.
  685. @type password: L{bytes}
  686. @param password: A password.
  687. @type words: L{tuple} of L{bytes}
  688. @param words: Other parts of the password split by spaces.
  689. """
  690. if self._userIs is None:
  691. self.failResponse(b"USER required before PASS")
  692. return
  693. user = self._userIs
  694. self._userIs = None
  695. password = b" ".join((password,) + words)
  696. d = defer.maybeDeferred(self.authenticateUserPASS, user, password)
  697. d.addCallbacks(
  698. self._cbMailbox, self._ebMailbox, callbackArgs=(user,)
  699. ).addErrback(self._ebUnexpected)
  700. def _longOperation(self, d):
  701. """
  702. Stop timeouts and block further command processing while a long
  703. operation completes.
  704. @type d: L{Deferred <defer.Deferred>}
  705. @param d: A deferred which triggers at the completion of a long
  706. operation.
  707. @rtype: L{Deferred <defer.Deferred>}
  708. @return: A deferred which triggers after command processing resumes and
  709. timeouts restart after the completion of a long operation.
  710. """
  711. timeOut = self.timeOut
  712. self.setTimeout(None)
  713. self.blocked = []
  714. d.addCallback(self._unblock)
  715. d.addCallback(lambda ign: self.setTimeout(timeOut))
  716. return d
  717. def _coiterate(self, gen):
  718. """
  719. Direct the output of an iterator to the transport and arrange for
  720. iteration to take place.
  721. @type gen: iterable which yields L{bytes}
  722. @param gen: An iterator over strings.
  723. @rtype: L{Deferred <defer.Deferred>}
  724. @return: A deferred which fires when the iterator finishes.
  725. """
  726. return self.schedule(_IteratorBuffer(self.transport.writeSequence, gen))
  727. def do_STAT(self):
  728. """
  729. Handle a STAT command.
  730. @rtype: L{Deferred <defer.Deferred>}
  731. @return: A deferred which triggers after the response to the STAT
  732. command has been issued.
  733. """
  734. d = defer.maybeDeferred(self.mbox.listMessages)
  735. def cbMessages(msgs):
  736. return self._coiterate(formatStatResponse(msgs))
  737. def ebMessages(err):
  738. self.failResponse(err.getErrorMessage())
  739. log.msg("Unexpected do_STAT failure:")
  740. log.err(err)
  741. return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
  742. def do_LIST(self, i=None):
  743. """
  744. Handle a LIST command.
  745. @type i: L{bytes} or L{None}
  746. @param i: A 1-based message index.
  747. @rtype: L{Deferred <defer.Deferred>}
  748. @return: A deferred which triggers after the response to the LIST
  749. command has been issued.
  750. """
  751. if i is None:
  752. d = defer.maybeDeferred(self.mbox.listMessages)
  753. def cbMessages(msgs):
  754. return self._coiterate(formatListResponse(msgs))
  755. def ebMessages(err):
  756. self.failResponse(err.getErrorMessage())
  757. log.msg("Unexpected do_LIST failure:")
  758. log.err(err)
  759. return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
  760. else:
  761. try:
  762. i = int(i)
  763. if i < 1:
  764. raise ValueError()
  765. except ValueError:
  766. if not isinstance(i, bytes):
  767. i = str(i).encode("utf-8")
  768. self.failResponse(b"Invalid message-number: " + i)
  769. else:
  770. d = defer.maybeDeferred(self.mbox.listMessages, i - 1)
  771. def cbMessage(msg):
  772. self.successResponse(b"%d %d" % (i, msg))
  773. def ebMessage(err):
  774. errcls = err.check(ValueError, IndexError)
  775. if errcls is not None:
  776. if errcls is IndexError:
  777. # IndexError was supported for a while, but really
  778. # shouldn't be. One error condition, one exception
  779. # type. See ticket #6669.
  780. warnings.warn(
  781. "twisted.mail.pop3.IMailbox.listMessages may "
  782. "not raise IndexError for out-of-bounds "
  783. "message numbers: raise ValueError instead.",
  784. PendingDeprecationWarning,
  785. )
  786. invalidNum = i
  787. if invalidNum and not isinstance(invalidNum, bytes):
  788. invalidNum = str(invalidNum).encode("utf-8")
  789. self.failResponse(b"Invalid message-number: " + invalidNum)
  790. else:
  791. self.failResponse(err.getErrorMessage())
  792. log.msg("Unexpected do_LIST failure:")
  793. log.err(err)
  794. d.addCallbacks(cbMessage, ebMessage)
  795. return self._longOperation(d)
  796. def do_UIDL(self, i=None):
  797. """
  798. Handle a UIDL command.
  799. @type i: L{bytes} or L{None}
  800. @param i: A 1-based message index.
  801. @rtype: L{Deferred <defer.Deferred>}
  802. @return: A deferred which triggers after the response to the UIDL
  803. command has been issued.
  804. """
  805. if i is None:
  806. d = defer.maybeDeferred(self.mbox.listMessages)
  807. def cbMessages(msgs):
  808. return self._coiterate(
  809. formatUIDListResponse(msgs, self.mbox.getUidl),
  810. )
  811. def ebMessages(err):
  812. self.failResponse(err.getErrorMessage())
  813. log.msg("Unexpected do_UIDL failure:")
  814. log.err(err)
  815. return self._longOperation(d.addCallbacks(cbMessages, ebMessages))
  816. else:
  817. try:
  818. i = int(i)
  819. if i < 1:
  820. raise ValueError()
  821. except ValueError:
  822. self.failResponse("Bad message number argument")
  823. else:
  824. try:
  825. msg = self.mbox.getUidl(i - 1)
  826. except IndexError:
  827. # XXX TODO See above comment regarding IndexError.
  828. warnings.warn(
  829. "twisted.mail.pop3.IMailbox.getUidl may not "
  830. "raise IndexError for out-of-bounds message numbers: "
  831. "raise ValueError instead.",
  832. PendingDeprecationWarning,
  833. )
  834. self.failResponse("Bad message number argument")
  835. except ValueError:
  836. self.failResponse("Bad message number argument")
  837. else:
  838. if not isinstance(msg, bytes):
  839. msg = str(msg).encode("utf-8")
  840. self.successResponse(msg)
  841. def _getMessageFile(self, i):
  842. """
  843. Retrieve the size and contents of a message.
  844. @type i: L{bytes}
  845. @param i: A 1-based message index.
  846. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  847. 2-L{tuple} of (E{1}) L{int}, (E{2}) file-like object
  848. @return: A deferred which successfully fires with the size of the
  849. message and a file containing the contents of the message.
  850. """
  851. try:
  852. msg = int(i) - 1
  853. if msg < 0:
  854. raise ValueError()
  855. except ValueError:
  856. self.failResponse("Bad message number argument")
  857. return defer.succeed(None)
  858. sizeDeferred = defer.maybeDeferred(self.mbox.listMessages, msg)
  859. def cbMessageSize(size):
  860. if not size:
  861. return defer.fail(_POP3MessageDeleted())
  862. fileDeferred = defer.maybeDeferred(self.mbox.getMessage, msg)
  863. fileDeferred.addCallback(lambda fObj: (size, fObj))
  864. return fileDeferred
  865. def ebMessageSomething(err):
  866. errcls = err.check(_POP3MessageDeleted, ValueError, IndexError)
  867. if errcls is _POP3MessageDeleted:
  868. self.failResponse("message deleted")
  869. elif errcls in (ValueError, IndexError):
  870. if errcls is IndexError:
  871. # XXX TODO See above comment regarding IndexError.
  872. warnings.warn(
  873. "twisted.mail.pop3.IMailbox.listMessages may not "
  874. "raise IndexError for out-of-bounds message numbers: "
  875. "raise ValueError instead.",
  876. PendingDeprecationWarning,
  877. )
  878. self.failResponse("Bad message number argument")
  879. else:
  880. log.msg("Unexpected _getMessageFile failure:")
  881. log.err(err)
  882. return None
  883. sizeDeferred.addCallback(cbMessageSize)
  884. sizeDeferred.addErrback(ebMessageSomething)
  885. return sizeDeferred
  886. def _sendMessageContent(self, i, fpWrapper, successResponse):
  887. """
  888. Send the contents of a message.
  889. @type i: L{bytes}
  890. @param i: A 1-based message index.
  891. @type fpWrapper: callable that takes a file-like object and returns
  892. a file-like object
  893. @param fpWrapper:
  894. @type successResponse: callable that takes L{int} and returns
  895. L{bytes}
  896. @param successResponse:
  897. @rtype: L{Deferred}
  898. @return: A deferred which triggers after the message has been sent.
  899. """
  900. d = self._getMessageFile(i)
  901. def cbMessageFile(info):
  902. if info is None:
  903. # Some error occurred - a failure response has been sent
  904. # already, just give up.
  905. return
  906. self._highest = max(self._highest, int(i))
  907. resp, fp = info
  908. fp = fpWrapper(fp)
  909. self.successResponse(successResponse(resp))
  910. s = basic.FileSender()
  911. d = s.beginFileTransfer(fp, self.transport, self.transformChunk)
  912. def cbFileTransfer(lastsent):
  913. if lastsent != b"\n":
  914. line = b"\r\n."
  915. else:
  916. line = b"."
  917. self.sendLine(line)
  918. def ebFileTransfer(err):
  919. self.transport.loseConnection()
  920. log.msg("Unexpected error in _sendMessageContent:")
  921. log.err(err)
  922. d.addCallback(cbFileTransfer)
  923. d.addErrback(ebFileTransfer)
  924. return d
  925. return self._longOperation(d.addCallback(cbMessageFile))
  926. def do_TOP(self, i, size):
  927. """
  928. Handle a TOP command.
  929. @type i: L{bytes}
  930. @param i: A 1-based message index.
  931. @type size: L{bytes}
  932. @param size: The number of lines of the message to retrieve.
  933. @rtype: L{Deferred}
  934. @return: A deferred which triggers after the response to the TOP
  935. command has been issued.
  936. """
  937. try:
  938. size = int(size)
  939. if size < 0:
  940. raise ValueError
  941. except ValueError:
  942. self.failResponse("Bad line count argument")
  943. else:
  944. return self._sendMessageContent(
  945. i,
  946. lambda fp: _HeadersPlusNLines(fp, size),
  947. lambda size: "Top of message follows",
  948. )
  949. def do_RETR(self, i):
  950. """
  951. Handle a RETR command.
  952. @type i: L{bytes}
  953. @param i: A 1-based message index.
  954. @rtype: L{Deferred}
  955. @return: A deferred which triggers after the response to the RETR
  956. command has been issued.
  957. """
  958. return self._sendMessageContent(i, lambda fp: fp, lambda size: "%d" % (size,))
  959. def transformChunk(self, chunk):
  960. """
  961. Transform a chunk of a message to POP3 message format.
  962. Make sure each line ends with C{'\\r\\n'} and byte-stuff the
  963. termination character (C{'.'}) by adding an extra one when one appears
  964. at the beginning of a line.
  965. @type chunk: L{bytes}
  966. @param chunk: A string to transform.
  967. @rtype: L{bytes}
  968. @return: The transformed string.
  969. """
  970. return chunk.replace(b"\n", b"\r\n").replace(b"\r\n.", b"\r\n..")
  971. def finishedFileTransfer(self, lastsent):
  972. """
  973. Send the termination sequence.
  974. @type lastsent: L{bytes}
  975. @param lastsent: The last character of the file.
  976. """
  977. if lastsent != b"\n":
  978. line = b"\r\n."
  979. else:
  980. line = b"."
  981. self.sendLine(line)
  982. def do_DELE(self, i):
  983. """
  984. Handle a DELE command.
  985. Mark a message for deletion and issue a successful response.
  986. @type i: L{int}
  987. @param i: A 1-based message index.
  988. """
  989. i = int(i) - 1
  990. self.mbox.deleteMessage(i)
  991. self.successResponse()
  992. def do_NOOP(self):
  993. """
  994. Handle a NOOP command.
  995. Do nothing but issue a successful response.
  996. """
  997. self.successResponse()
  998. def do_RSET(self):
  999. """
  1000. Handle a RSET command.
  1001. Unmark any messages that have been flagged for deletion.
  1002. """
  1003. try:
  1004. self.mbox.undeleteMessages()
  1005. except BaseException:
  1006. log.err()
  1007. self.failResponse()
  1008. else:
  1009. self._highest = 0
  1010. self.successResponse()
  1011. def do_LAST(self):
  1012. """
  1013. Handle a LAST command.
  1014. Respond with the 1-based index of the highest retrieved message.
  1015. """
  1016. self.successResponse(self._highest)
  1017. def do_RPOP(self, user):
  1018. """
  1019. Handle an RPOP command.
  1020. RPOP is not supported. Send an error response.
  1021. @type user: L{bytes}
  1022. @param user: A username.
  1023. """
  1024. self.failResponse("permission denied, sucker")
  1025. def do_QUIT(self):
  1026. """
  1027. Handle a QUIT command.
  1028. Remove any messages marked for deletion, issue a successful response,
  1029. and drop the connection.
  1030. """
  1031. if self.mbox:
  1032. self.mbox.sync()
  1033. self.successResponse()
  1034. self.transport.loseConnection()
  1035. def authenticateUserAPOP(self, user, digest):
  1036. """
  1037. Perform APOP authentication.
  1038. @type user: L{bytes}
  1039. @param user: The name of the user attempting to log in.
  1040. @type digest: L{bytes}
  1041. @param digest: The challenge response.
  1042. @rtype: L{Deferred <defer.Deferred>} which successfully results in
  1043. 3-L{tuple} of (E{1}) L{IMailbox <pop3.IMailbox>}, (E{2})
  1044. L{IMailbox <pop3.IMailbox>} provider, (E{3}) no-argument callable
  1045. @return: A deferred which fires when authentication is complete. If
  1046. successful, it returns an L{IMailbox <pop3.IMailbox>} interface, a
  1047. mailbox, and a function to be invoked with the session is
  1048. terminated. If authentication fails, the deferred fails with an
  1049. L{UnathorizedLogin <cred.error.UnauthorizedLogin>} error.
  1050. @raise cred.error.UnauthorizedLogin: When authentication fails.
  1051. """
  1052. if self.portal is not None:
  1053. return self.portal.login(
  1054. APOPCredentials(self.magic, user, digest), None, IMailbox
  1055. )
  1056. raise cred.error.UnauthorizedLogin()
  1057. def authenticateUserPASS(self, user, password):
  1058. """
  1059. Perform authentication for a username/password login.
  1060. @type user: L{bytes}
  1061. @param user: The name of the user attempting to log in.
  1062. @type password: L{bytes}
  1063. @param password: The password to authenticate with.
  1064. @rtype: L{Deferred <defer.Deferred>} which successfully results in
  1065. 3-L{tuple} of (E{1}) L{IMailbox <pop3.IMailbox>}, (E{2}) L{IMailbox
  1066. <pop3.IMailbox>} provider, (E{3}) no-argument callable
  1067. @return: A deferred which fires when authentication is complete. If
  1068. successful, it returns a L{pop3.IMailbox} interface, a mailbox,
  1069. and a function to be invoked with the session is terminated.
  1070. If authentication fails, the deferred fails with an
  1071. L{UnathorizedLogin <cred.error.UnauthorizedLogin>} error.
  1072. @raise cred.error.UnauthorizedLogin: When authentication fails.
  1073. """
  1074. if self.portal is not None:
  1075. return self.portal.login(
  1076. cred.credentials.UsernamePassword(user, password), None, IMailbox
  1077. )
  1078. raise cred.error.UnauthorizedLogin()
  1079. def stopProducing(self):
  1080. # IProducer.stopProducing
  1081. raise NotImplementedError()
  1082. @implementer(IMailbox)
  1083. class Mailbox:
  1084. """
  1085. A base class for mailboxes.
  1086. """
  1087. def listMessages(self, i=None):
  1088. """
  1089. Retrieve the size of a message, or, if none is specified, the size of
  1090. each message in the mailbox.
  1091. @type i: L{int} or L{None}
  1092. @param i: The 0-based index of the message.
  1093. @rtype: L{int}, sequence of L{int}, or L{Deferred <defer.Deferred>}
  1094. @return: The number of octets in the specified message, or, if an
  1095. index is not specified, a sequence of the number of octets for
  1096. all messages in the mailbox or a deferred which fires with
  1097. one of those. Any value which corresponds to a deleted message
  1098. is set to 0.
  1099. @raise ValueError or IndexError: When the index does not correspond to
  1100. a message in the mailbox. The use of ValueError is preferred.
  1101. """
  1102. return []
  1103. def getMessage(self, i):
  1104. """
  1105. Retrieve a file containing the contents of a message.
  1106. @type i: L{int}
  1107. @param i: The 0-based index of a message.
  1108. @rtype: file-like object
  1109. @return: A file containing the message.
  1110. @raise ValueError or IndexError: When the index does not correspond to
  1111. a message in the mailbox. The use of ValueError is preferred.
  1112. """
  1113. raise ValueError
  1114. def getUidl(self, i):
  1115. """
  1116. Get a unique identifier for a message.
  1117. @type i: L{int}
  1118. @param i: The 0-based index of a message.
  1119. @rtype: L{bytes}
  1120. @return: A string of printable characters uniquely identifying the
  1121. message for all time.
  1122. @raise ValueError or IndexError: When the index does not correspond to
  1123. a message in the mailbox. The use of ValueError is preferred.
  1124. """
  1125. raise ValueError
  1126. def deleteMessage(self, i):
  1127. """
  1128. Mark a message for deletion.
  1129. This must not change the number of messages in this mailbox. Further
  1130. requests for the size of the deleted message should return 0. Further
  1131. requests for the message itself may raise an exception.
  1132. @type i: L{int}
  1133. @param i: The 0-based index of a message.
  1134. @raise ValueError or IndexError: When the index does not correspond to
  1135. a message in the mailbox. The use of ValueError is preferred.
  1136. """
  1137. raise ValueError
  1138. def undeleteMessages(self):
  1139. """
  1140. Undelete all messages marked for deletion.
  1141. Any message which can be undeleted should be returned to its original
  1142. position in the message sequence and retain its original UID.
  1143. """
  1144. pass
  1145. def sync(self):
  1146. """
  1147. Discard the contents of any message marked for deletion.
  1148. """
  1149. pass
  1150. NONE, SHORT, FIRST_LONG, LONG = range(4)
  1151. NEXT = {}
  1152. NEXT[NONE] = NONE
  1153. NEXT[SHORT] = NONE
  1154. NEXT[FIRST_LONG] = LONG
  1155. NEXT[LONG] = NONE
  1156. class POP3Client(basic.LineOnlyReceiver):
  1157. """
  1158. A POP3 client protocol.
  1159. @type mode: L{int}
  1160. @ivar mode: The type of response expected from the server. Choices include
  1161. none (0), a one line response (1), the first line of a multi-line
  1162. response (2), and subsequent lines of a multi-line response (3).
  1163. @type command: L{bytes}
  1164. @ivar command: The command most recently sent to the server.
  1165. @type welcomeRe: L{Pattern <re.Pattern.search>}
  1166. @ivar welcomeRe: A regular expression which matches the APOP challenge in
  1167. the server greeting.
  1168. @type welcomeCode: L{bytes}
  1169. @ivar welcomeCode: The APOP challenge passed in the server greeting.
  1170. """
  1171. mode = SHORT
  1172. command = b"WELCOME"
  1173. import re
  1174. welcomeRe = re.compile(b"<(.*)>")
  1175. def __init__(self):
  1176. """
  1177. Issue deprecation warning.
  1178. """
  1179. import warnings
  1180. warnings.warn(
  1181. "twisted.mail.pop3.POP3Client is deprecated, "
  1182. "please use twisted.mail.pop3.AdvancedPOP3Client "
  1183. "instead.",
  1184. DeprecationWarning,
  1185. stacklevel=3,
  1186. )
  1187. def sendShort(self, command, params=None):
  1188. """
  1189. Send a POP3 command to which a short response is expected.
  1190. @type command: L{bytes}
  1191. @param command: A POP3 command.
  1192. @type params: stringifyable L{object} or L{None}
  1193. @param params: Command arguments.
  1194. """
  1195. if params is not None:
  1196. if not isinstance(params, bytes):
  1197. params = str(params).encode("utf-8")
  1198. self.sendLine(command + b" " + params)
  1199. else:
  1200. self.sendLine(command)
  1201. self.command = command
  1202. self.mode = SHORT
  1203. def sendLong(self, command, params):
  1204. """
  1205. Send a POP3 command to which a long response is expected.
  1206. @type command: L{bytes}
  1207. @param command: A POP3 command.
  1208. @type params: stringifyable L{object}
  1209. @param params: Command arguments.
  1210. """
  1211. if params:
  1212. if not isinstance(params, bytes):
  1213. params = str(params).encode("utf-8")
  1214. self.sendLine(command + b" " + params)
  1215. else:
  1216. self.sendLine(command)
  1217. self.command = command
  1218. self.mode = FIRST_LONG
  1219. def handle_default(self, line):
  1220. """
  1221. Handle responses from the server for which no other handler exists.
  1222. @type line: L{bytes}
  1223. @param line: A received line.
  1224. """
  1225. if line[:-4] == b"-ERR":
  1226. self.mode = NONE
  1227. def handle_WELCOME(self, line):
  1228. """
  1229. Handle a server response which is expected to be a server greeting.
  1230. @type line: L{bytes}
  1231. @param line: A received line.
  1232. """
  1233. code, data = line.split(b" ", 1)
  1234. if code != b"+OK":
  1235. self.transport.loseConnection()
  1236. else:
  1237. m = self.welcomeRe.match(line)
  1238. if m:
  1239. self.welcomeCode = m.group(1)
  1240. def _dispatch(self, command, default, *args):
  1241. """
  1242. Dispatch a response from the server for handling.
  1243. Command X is dispatched to handle_X() if it exists. If not, it is
  1244. dispatched to the default handler.
  1245. @type command: L{bytes}
  1246. @param command: The command.
  1247. @type default: callable that takes L{bytes} or
  1248. L{None}
  1249. @param default: The default handler.
  1250. @type args: L{tuple} or L{None}
  1251. @param args: Arguments to the handler function.
  1252. """
  1253. try:
  1254. method = getattr(self, "handle_" + command.decode("utf-8"), default)
  1255. if method is not None:
  1256. method(*args)
  1257. except BaseException:
  1258. log.err()
  1259. def lineReceived(self, line):
  1260. """
  1261. Dispatch a received line for processing.
  1262. The choice of function to handle the received line is based on the
  1263. type of response expected to the command sent to the server and how
  1264. much of that response has been received.
  1265. An expected one line response to command X is handled by handle_X().
  1266. The first line of a multi-line response to command X is also handled by
  1267. handle_X(). Subsequent lines of the multi-line response are handled by
  1268. handle_X_continue() except for the last line which is handled by
  1269. handle_X_end().
  1270. @type line: L{bytes}
  1271. @param line: A received line.
  1272. """
  1273. if self.mode == SHORT or self.mode == FIRST_LONG:
  1274. self.mode = NEXT[self.mode]
  1275. self._dispatch(self.command, self.handle_default, line)
  1276. elif self.mode == LONG:
  1277. if line == b".":
  1278. self.mode = NEXT[self.mode]
  1279. self._dispatch(self.command + b"_end", None)
  1280. return
  1281. if line[:1] == b".":
  1282. line = line[1:]
  1283. self._dispatch(self.command + b"_continue", None, line)
  1284. def apopAuthenticate(self, user, password, magic):
  1285. """
  1286. Perform an authenticated login.
  1287. @type user: L{bytes}
  1288. @param user: The username with which to log in.
  1289. @type password: L{bytes}
  1290. @param password: The password with which to log in.
  1291. @type magic: L{bytes}
  1292. @param magic: The challenge provided by the server.
  1293. """
  1294. digest = md5(magic + password).hexdigest().encode("ascii")
  1295. self.apop(user, digest)
  1296. def apop(self, user, digest):
  1297. """
  1298. Send an APOP command to perform authenticated login.
  1299. @type user: L{bytes}
  1300. @param user: The username with which to log in.
  1301. @type digest: L{bytes}
  1302. @param digest: The challenge response with which to authenticate.
  1303. """
  1304. self.sendLong(b"APOP", b" ".join((user, digest)))
  1305. def retr(self, i):
  1306. """
  1307. Send a RETR command to retrieve a message from the server.
  1308. @type i: L{int} or L{bytes}
  1309. @param i: A 0-based message index.
  1310. """
  1311. self.sendLong(b"RETR", i)
  1312. def dele(self, i):
  1313. """
  1314. Send a DELE command to delete a message from the server.
  1315. @type i: L{int} or L{bytes}
  1316. @param i: A 0-based message index.
  1317. """
  1318. self.sendShort(b"DELE", i)
  1319. def list(self, i=""):
  1320. """
  1321. Send a LIST command to retrieve the size of a message or, if no message
  1322. is specified, the sizes of all messages.
  1323. @type i: L{int} or L{bytes}
  1324. @param i: A 0-based message index or the empty string to specify all
  1325. messages.
  1326. """
  1327. self.sendLong(b"LIST", i)
  1328. def uidl(self, i=""):
  1329. """
  1330. Send a UIDL command to retrieve the unique identifier of a message or,
  1331. if no message is specified, the unique identifiers of all messages.
  1332. @type i: L{int} or L{bytes}
  1333. @param i: A 0-based message index or the empty string to specify all
  1334. messages.
  1335. """
  1336. self.sendLong(b"UIDL", i)
  1337. def user(self, name):
  1338. """
  1339. Send a USER command to perform the first half of a plaintext login.
  1340. @type name: L{bytes}
  1341. @param name: The username with which to log in.
  1342. """
  1343. self.sendShort(b"USER", name)
  1344. def password(self, password):
  1345. """
  1346. Perform the second half of a plaintext login.
  1347. @type password: L{bytes}
  1348. @param password: The plaintext password with which to authenticate.
  1349. """
  1350. self.sendShort(b"PASS", password)
  1351. pass_ = password
  1352. def quit(self):
  1353. """
  1354. Send a QUIT command to disconnect from the server.
  1355. """
  1356. self.sendShort(b"QUIT")
  1357. from twisted.mail._except import (
  1358. InsecureAuthenticationDisallowed,
  1359. LineTooLong,
  1360. ServerErrorResponse,
  1361. TLSError,
  1362. TLSNotSupportedError,
  1363. )
  1364. from twisted.mail._pop3client import POP3Client as AdvancedPOP3Client
  1365. __all__ = [
  1366. # Interfaces
  1367. "IMailbox",
  1368. "IServerFactory",
  1369. # Exceptions
  1370. "POP3Error",
  1371. "POP3ClientError",
  1372. "InsecureAuthenticationDisallowed",
  1373. "ServerErrorResponse",
  1374. "LineTooLong",
  1375. "TLSError",
  1376. "TLSNotSupportedError",
  1377. # Protocol classes
  1378. "POP3",
  1379. "POP3Client",
  1380. "AdvancedPOP3Client",
  1381. # Misc
  1382. "APOPCredentials",
  1383. "Mailbox",
  1384. ]