pop3.py 52 KB

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