pop3.py 54 KB

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