pop3client.py 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264
  1. # -*- test-case-name: twisted.mail.test.test_pop3client -*-
  2. # Copyright (c) 2001-2004 Divmod Inc.
  3. # Copyright (c) Twisted Matrix Laboratories.
  4. # See LICENSE for details.
  5. """
  6. A POP3 client protocol implementation.
  7. Don't use this module directly. Use twisted.mail.pop3 instead.
  8. @author: Jp Calderone
  9. """
  10. import re
  11. from hashlib import md5
  12. from twisted.python import log
  13. from twisted.python.compat import intToBytes
  14. from twisted.internet import defer
  15. from twisted.protocols import basic
  16. from twisted.protocols import policies
  17. from twisted.internet import error
  18. from twisted.internet import interfaces
  19. from twisted.mail._except import (
  20. InsecureAuthenticationDisallowed, TLSError,
  21. TLSNotSupportedError, ServerErrorResponse, LineTooLong)
  22. OK = b'+OK'
  23. ERR = b'-ERR'
  24. class _ListSetter:
  25. """
  26. A utility class to construct a list from a multi-line response accounting
  27. for deleted messages.
  28. POP3 responses sometimes occur in the form of a list of lines containing
  29. two pieces of data, a message index and a value of some sort. When a
  30. message is deleted, it is omitted from these responses. The L{setitem}
  31. method of this class is meant to be called with these two values. In the
  32. cases where indices are skipped, it takes care of padding out the missing
  33. values with L{None}.
  34. @ivar L: See L{__init__}
  35. """
  36. def __init__(self, L):
  37. """
  38. @type L: L{list} of L{object}
  39. @param L: The list being constructed. An empty list should be
  40. passed in.
  41. """
  42. self.L = L
  43. def setitem(self, itemAndValue):
  44. """
  45. Add the value at the specified position, padding out missing entries.
  46. @type itemAndValue: C{tuple}
  47. @param item: A tuple of (item, value). The I{item} is the 0-based
  48. index in the list at which the value should be placed. The value is
  49. is an L{object} to put in the list.
  50. """
  51. (item, value) = itemAndValue
  52. diff = item - len(self.L) + 1
  53. if diff > 0:
  54. self.L.extend([None] * diff)
  55. self.L[item] = value
  56. def _statXform(line):
  57. """
  58. Parse the response to a STAT command.
  59. @type line: L{bytes}
  60. @param line: The response from the server to a STAT command minus the
  61. status indicator.
  62. @rtype: 2-L{tuple} of (0) L{int}, (1) L{int}
  63. @return: The number of messages in the mailbox and the size of the mailbox.
  64. """
  65. numMsgs, totalSize = line.split(None, 1)
  66. return int(numMsgs), int(totalSize)
  67. def _listXform(line):
  68. """
  69. Parse a line of the response to a LIST command.
  70. The line from the LIST response consists of a 1-based message number
  71. followed by a size.
  72. @type line: L{bytes}
  73. @param line: A non-initial line from the multi-line response to a LIST
  74. command.
  75. @rtype: 2-L{tuple} of (0) L{int}, (1) L{int}
  76. @return: The 0-based index of the message and the size of the message.
  77. """
  78. index, size = line.split(None, 1)
  79. return int(index) - 1, int(size)
  80. def _uidXform(line):
  81. """
  82. Parse a line of the response to a UIDL command.
  83. The line from the UIDL response consists of a 1-based message number
  84. followed by a unique id.
  85. @type line: L{bytes}
  86. @param line: A non-initial line from the multi-line response to a UIDL
  87. command.
  88. @rtype: 2-L{tuple} of (0) L{int}, (1) L{bytes}
  89. @return: The 0-based index of the message and the unique identifier
  90. for the message.
  91. """
  92. index, uid = line.split(None, 1)
  93. return int(index) - 1, uid
  94. def _codeStatusSplit(line):
  95. """
  96. Parse the first line of a multi-line server response.
  97. @type line: L{bytes}
  98. @param line: The first line of a multi-line server response.
  99. @rtype: 2-tuple of (0) L{bytes}, (1) L{bytes}
  100. @return: The status indicator and the rest of the server response.
  101. """
  102. parts = line.split(b' ', 1)
  103. if len(parts) == 1:
  104. return parts[0], b''
  105. return parts
  106. def _dotUnquoter(line):
  107. """
  108. Remove a byte-stuffed termination character at the beginning of a line if
  109. present.
  110. When the termination character (C{'.'}) appears at the beginning of a line,
  111. the server byte-stuffs it by adding another termination character to
  112. avoid confusion with the terminating sequence (C{'.\\r\\n'}).
  113. @type line: L{bytes}
  114. @param line: A received line.
  115. @rtype: L{bytes}
  116. @return: The line without the byte-stuffed termination character at the
  117. beginning if it was present. Otherwise, the line unchanged.
  118. """
  119. if line.startswith(b'..'):
  120. return line[1:]
  121. return line
  122. class POP3Client(basic.LineOnlyReceiver, policies.TimeoutMixin):
  123. """
  124. A POP3 client protocol.
  125. Instances of this class provide a convenient, efficient API for
  126. retrieving and deleting messages from a POP3 server.
  127. This API provides a pipelining interface but POP3 pipelining
  128. on the network is not yet supported.
  129. @type startedTLS: L{bool}
  130. @ivar startedTLS: An indication of whether TLS has been negotiated
  131. successfully.
  132. @type allowInsecureLogin: L{bool}
  133. @ivar allowInsecureLogin: An indication of whether plaintext login should
  134. be allowed when the server offers no authentication challenge and the
  135. transport does not offer any protection via encryption.
  136. @type serverChallenge: L{bytes} or L{None}
  137. @ivar serverChallenge: The challenge received in the server greeting.
  138. @type timeout: L{int}
  139. @ivar timeout: The number of seconds to wait on a response from the server
  140. before timing out a connection. If the number is <= 0, no timeout
  141. checking will be performed.
  142. @type _capCache: L{None} or L{dict} mapping L{bytes}
  143. to L{list} of L{bytes} and/or L{bytes} to L{None}
  144. @ivar _capCache: The cached server capabilities. Capabilities are not
  145. allowed to change during the session (except when TLS is negotiated),
  146. so the first response to a capabilities command can be used for
  147. later lookups.
  148. @type _challengeMagicRe: L{RegexObject <re.RegexObject>}
  149. @ivar _challengeMagicRe: A regular expression which matches the
  150. challenge in the server greeting.
  151. @type _blockedQueue: L{None} or L{list} of 3-L{tuple}
  152. of (0) L{Deferred <defer.Deferred>}, (1) callable which results
  153. in a L{Deferred <defer.Deferred>}, (2) L{tuple}
  154. @ivar _blockedQueue: A list of blocked commands. While a command is
  155. awaiting a response from the server, other commands are blocked. When
  156. no command is outstanding, C{_blockedQueue} is set to L{None}.
  157. Otherwise, it contains a list of information about blocked commands.
  158. Each list entry provides the following information about a blocked
  159. command: the deferred that should be called when the response to the
  160. command is received, the function that sends the command, and the
  161. arguments to the function.
  162. @type _waiting: L{Deferred <defer.Deferred>} or
  163. L{None}
  164. @ivar _waiting: A deferred which fires when the response to the
  165. outstanding command is received from the server.
  166. @type _timedOut: L{bool}
  167. @ivar _timedOut: An indication of whether the connection was dropped
  168. because of a timeout.
  169. @type _greetingError: L{bytes} or L{None}
  170. @ivar _greetingError: The server greeting minus the status indicator, when
  171. the connection was dropped because of an error in the server greeting.
  172. Otherwise, L{None}.
  173. @type state: L{bytes}
  174. @ivar state: The state which indicates what type of response is expected
  175. from the server. Valid states are: 'WELCOME', 'WAITING', 'SHORT',
  176. 'LONG_INITIAL', 'LONG'.
  177. @type _xform: L{None} or callable that takes L{bytes}
  178. and returns L{object}
  179. @ivar _xform: The transform function which is used to convert each
  180. line of a multi-line response into usable values for use by the
  181. consumer function. If L{None}, each line of the multi-line response
  182. is sent directly to the consumer function.
  183. @type _consumer: callable that takes L{object}
  184. @ivar _consumer: The consumer function which is used to store the
  185. values derived by the transform function from each line of a
  186. multi-line response into a list.
  187. """
  188. startedTLS = False
  189. allowInsecureLogin = False
  190. timeout = 0
  191. serverChallenge = None
  192. _capCache = None
  193. _challengeMagicRe = re.compile(b'(<[^>]+>)')
  194. _blockedQueue = None
  195. _waiting = None
  196. _timedOut = False
  197. _greetingError = None
  198. def _blocked(self, f, *a):
  199. """
  200. Block a command, if necessary.
  201. If commands are being blocked, append information about the function
  202. which sends the command to a list and return a deferred that will be
  203. chained with the return value of the function when it eventually runs.
  204. Otherwise, set up for subsequent commands to be blocked and return
  205. L{None}.
  206. @type f: callable
  207. @param f: A function which sends a command.
  208. @type a: L{tuple}
  209. @param a: Arguments to the function.
  210. @rtype: L{None} or L{Deferred <defer.Deferred>}
  211. @return: L{None} if the command can run immediately. Otherwise,
  212. a deferred that will eventually trigger with the return value of
  213. the function.
  214. """
  215. if self._blockedQueue is not None:
  216. d = defer.Deferred()
  217. self._blockedQueue.append((d, f, a))
  218. return d
  219. self._blockedQueue = []
  220. return None
  221. def _unblock(self):
  222. """
  223. Send the next blocked command.
  224. If there are no more commands in the blocked queue, set up for the next
  225. command to be sent immediately.
  226. """
  227. if self._blockedQueue == []:
  228. self._blockedQueue = None
  229. elif self._blockedQueue is not None:
  230. _blockedQueue = self._blockedQueue
  231. self._blockedQueue = None
  232. d, f, a = _blockedQueue.pop(0)
  233. d2 = f(*a)
  234. d2.chainDeferred(d)
  235. # f is a function which uses _blocked (otherwise it wouldn't
  236. # have gotten into the blocked queue), which means it will have
  237. # re-set _blockedQueue to an empty list, so we can put the rest
  238. # of the blocked queue back into it now.
  239. self._blockedQueue.extend(_blockedQueue)
  240. def sendShort(self, cmd, args):
  241. """
  242. Send a POP3 command to which a short response is expected.
  243. Block all further commands from being sent until the response is
  244. received. Transition the state to SHORT.
  245. @type cmd: L{bytes}
  246. @param cmd: A POP3 command.
  247. @type args: L{bytes}
  248. @param args: The command arguments.
  249. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  250. L{bytes} or fails with L{ServerErrorResponse}
  251. @return: A deferred which fires when the entire response is received.
  252. On an OK response, it returns the response from the server minus
  253. the status indicator. On an ERR response, it issues a server
  254. error response failure with the response from the server minus the
  255. status indicator.
  256. """
  257. d = self._blocked(self.sendShort, cmd, args)
  258. if d is not None:
  259. return d
  260. if args:
  261. self.sendLine(cmd + b' ' + args)
  262. else:
  263. self.sendLine(cmd)
  264. self.state = 'SHORT'
  265. self._waiting = defer.Deferred()
  266. return self._waiting
  267. def sendLong(self, cmd, args, consumer, xform):
  268. """
  269. Send a POP3 command to which a multi-line response is expected.
  270. Block all further commands from being sent until the entire response is
  271. received. Transition the state to LONG_INITIAL.
  272. @type cmd: L{bytes}
  273. @param cmd: A POP3 command.
  274. @type args: L{bytes}
  275. @param args: The command arguments.
  276. @type consumer: callable that takes L{object}
  277. @param consumer: A consumer function which should be used to put
  278. the values derived by a transform function from each line of the
  279. multi-line response into a list.
  280. @type xform: L{None} or callable that takes
  281. L{bytes} and returns L{object}
  282. @param xform: A transform function which should be used to transform
  283. each line of the multi-line response into usable values for use by
  284. a consumer function. If L{None}, each line of the multi-line
  285. response should be sent directly to the consumer function.
  286. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  287. callable that takes L{object} and fails with L{ServerErrorResponse}
  288. @return: A deferred which fires when the entire response is received.
  289. On an OK response, it returns the consumer function. On an ERR
  290. response, it issues a server error response failure with the
  291. response from the server minus the status indicator and the
  292. consumer function.
  293. """
  294. d = self._blocked(self.sendLong, cmd, args, consumer, xform)
  295. if d is not None:
  296. return d
  297. if args:
  298. self.sendLine(cmd + b' ' + args)
  299. else:
  300. self.sendLine(cmd)
  301. self.state = 'LONG_INITIAL'
  302. self._xform = xform
  303. self._consumer = consumer
  304. self._waiting = defer.Deferred()
  305. return self._waiting
  306. # Twisted protocol callback
  307. def connectionMade(self):
  308. """
  309. Wait for a greeting from the server after the connection has been made.
  310. Start the connection in the WELCOME state.
  311. """
  312. if self.timeout > 0:
  313. self.setTimeout(self.timeout)
  314. self.state = 'WELCOME'
  315. self._blockedQueue = []
  316. def timeoutConnection(self):
  317. """
  318. Drop the connection when the server does not respond in time.
  319. """
  320. self._timedOut = True
  321. self.transport.loseConnection()
  322. def connectionLost(self, reason):
  323. """
  324. Clean up when the connection has been lost.
  325. When the loss of connection was initiated by the client due to a
  326. timeout, the L{_timedOut} flag will be set. When it was initiated by
  327. the client due to an error in the server greeting, L{_greetingError}
  328. will be set to the server response minus the status indicator.
  329. @type reason: L{Failure <twisted.python.failure.Failure>}
  330. @param reason: The reason the connection was terminated.
  331. """
  332. if self.timeout > 0:
  333. self.setTimeout(None)
  334. if self._timedOut:
  335. reason = error.TimeoutError()
  336. elif self._greetingError:
  337. reason = ServerErrorResponse(self._greetingError)
  338. d = []
  339. if self._waiting is not None:
  340. d.append(self._waiting)
  341. self._waiting = None
  342. if self._blockedQueue is not None:
  343. d.extend([deferred for (deferred, f, a) in self._blockedQueue])
  344. self._blockedQueue = None
  345. for w in d:
  346. w.errback(reason)
  347. def lineReceived(self, line):
  348. """
  349. Pass a received line to a state machine function and
  350. transition to the next state.
  351. @type line: L{bytes}
  352. @param line: A received line.
  353. """
  354. if self.timeout > 0:
  355. self.resetTimeout()
  356. state = self.state
  357. self.state = None
  358. state = getattr(self, 'state_' + state)(line) or state
  359. if self.state is None:
  360. self.state = state
  361. def lineLengthExceeded(self, buffer):
  362. """
  363. Drop the connection when a server response exceeds the maximum line
  364. length (L{LineOnlyReceiver.MAX_LENGTH}).
  365. @type buffer: L{bytes}
  366. @param buffer: A received line which exceeds the maximum line length.
  367. """
  368. # XXX - We need to be smarter about this
  369. if self._waiting is not None:
  370. waiting, self._waiting = self._waiting, None
  371. waiting.errback(LineTooLong())
  372. self.transport.loseConnection()
  373. # POP3 Client state logic - don't touch this.
  374. def state_WELCOME(self, line):
  375. """
  376. Handle server responses for the WELCOME state in which the server
  377. greeting is expected.
  378. WELCOME is the first state. The server should send one line of text
  379. with a greeting and possibly an APOP challenge. Transition the state
  380. to WAITING.
  381. @type line: L{bytes}
  382. @param line: A line received from the server.
  383. @rtype: L{bytes}
  384. @return: The next state.
  385. """
  386. code, status = _codeStatusSplit(line)
  387. if code != OK:
  388. self._greetingError = status
  389. self.transport.loseConnection()
  390. else:
  391. m = self._challengeMagicRe.search(status)
  392. if m is not None:
  393. self.serverChallenge = m.group(1)
  394. self.serverGreeting(status)
  395. self._unblock()
  396. return 'WAITING'
  397. def state_WAITING(self, line):
  398. """
  399. Log an error for server responses received in the WAITING state during
  400. which the server is not expected to send anything.
  401. @type line: L{bytes}
  402. @param line: A line received from the server.
  403. """
  404. log.msg("Illegal line from server: " + repr(line))
  405. def state_SHORT(self, line):
  406. """
  407. Handle server responses for the SHORT state in which the server is
  408. expected to send a single line response.
  409. Parse the response and fire the deferred which is waiting on receipt of
  410. a complete response. Transition the state back to WAITING.
  411. @type line: L{bytes}
  412. @param line: A line received from the server.
  413. @rtype: L{bytes}
  414. @return: The next state.
  415. """
  416. deferred, self._waiting = self._waiting, None
  417. self._unblock()
  418. code, status = _codeStatusSplit(line)
  419. if code == OK:
  420. deferred.callback(status)
  421. else:
  422. deferred.errback(ServerErrorResponse(status))
  423. return 'WAITING'
  424. def state_LONG_INITIAL(self, line):
  425. """
  426. Handle server responses for the LONG_INITIAL state in which the server
  427. is expected to send the first line of a multi-line response.
  428. Parse the response. On an OK response, transition the state to
  429. LONG. On an ERR response, cleanup and transition the state to
  430. WAITING.
  431. @type line: L{bytes}
  432. @param line: A line received from the server.
  433. @rtype: L{bytes}
  434. @return: The next state.
  435. """
  436. code, status = _codeStatusSplit(line)
  437. if code == OK:
  438. return 'LONG'
  439. consumer = self._consumer
  440. deferred = self._waiting
  441. self._consumer = self._waiting = self._xform = None
  442. self._unblock()
  443. deferred.errback(ServerErrorResponse(status, consumer))
  444. return 'WAITING'
  445. def state_LONG(self, line):
  446. """
  447. Handle server responses for the LONG state in which the server is
  448. expected to send a non-initial line of a multi-line response.
  449. On receipt of the last line of the response, clean up, fire the
  450. deferred which is waiting on receipt of a complete response, and
  451. transition the state to WAITING. Otherwise, pass the line to the
  452. transform function, if provided, and then the consumer function.
  453. @type line: L{bytes}
  454. @param line: A line received from the server.
  455. @rtype: L{bytes}
  456. @return: The next state.
  457. """
  458. # This is the state for each line of a long response.
  459. if line == b'.':
  460. consumer = self._consumer
  461. deferred = self._waiting
  462. self._consumer = self._waiting = self._xform = None
  463. self._unblock()
  464. deferred.callback(consumer)
  465. return 'WAITING'
  466. else:
  467. if self._xform is not None:
  468. self._consumer(self._xform(line))
  469. else:
  470. self._consumer(line)
  471. return 'LONG'
  472. # Callbacks - override these
  473. def serverGreeting(self, greeting):
  474. """
  475. Handle the server greeting.
  476. @type greeting: L{bytes}
  477. @param greeting: The server greeting minus the status indicator.
  478. For servers implementing APOP authentication, this will contain a
  479. challenge string.
  480. """
  481. # External API - call these (most of 'em anyway)
  482. def startTLS(self, contextFactory=None):
  483. """
  484. Switch to encrypted communication using TLS.
  485. The first step of switching to encrypted communication is obtaining
  486. the server's capabilities. When that is complete, the L{_startTLS}
  487. callback function continues the switching process.
  488. @type contextFactory: L{None} or
  489. L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}
  490. @param contextFactory: The context factory with which to negotiate TLS.
  491. If not provided, try to create a new one.
  492. @rtype: L{Deferred <defer.Deferred>} which successfully results in
  493. L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes} to
  494. L{None} or fails with L{TLSError}
  495. @return: A deferred which fires when the transport has been
  496. secured according to the given context factory with the server
  497. capabilities, or which fails with a TLS error if the transport
  498. cannot be secured.
  499. """
  500. tls = interfaces.ITLSTransport(self.transport, None)
  501. if tls is None:
  502. return defer.fail(TLSError(
  503. "POP3Client transport does not implement "
  504. "interfaces.ITLSTransport"))
  505. if contextFactory is None:
  506. contextFactory = self._getContextFactory()
  507. if contextFactory is None:
  508. return defer.fail(TLSError(
  509. "POP3Client requires a TLS context to "
  510. "initiate the STLS handshake"))
  511. d = self.capabilities()
  512. d.addCallback(self._startTLS, contextFactory, tls)
  513. return d
  514. def _startTLS(self, caps, contextFactory, tls):
  515. """
  516. Continue the process of switching to encrypted communication.
  517. This callback function runs after the server capabilities are received.
  518. The next step is sending the server an STLS command to request a
  519. switch to encrypted communication. When an OK response is received,
  520. the L{_startedTLS} callback function completes the switch to encrypted
  521. communication. Then, the new server capabilities are requested.
  522. @type caps: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or
  523. L{bytes} to L{None}
  524. @param caps: The server capabilities.
  525. @type contextFactory: L{ClientContextFactory
  526. <twisted.internet.ssl.ClientContextFactory>}
  527. @param contextFactory: A context factory with which to negotiate TLS.
  528. @type tls: L{ITLSTransport <interfaces.ITLSTransport>}
  529. @param tls: A TCP transport that supports switching to TLS midstream.
  530. @rtype: L{Deferred <defer.Deferred>} which successfully triggers with
  531. L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes} to
  532. L{None} or fails with L{TLSNotSupportedError}
  533. @return: A deferred which successfully fires when the response from
  534. the server to the request to start TLS has been received and the
  535. new server capabilities have been received or fails when the server
  536. does not support TLS.
  537. """
  538. assert not self.startedTLS, "Client and Server are currently communicating via TLS"
  539. if b'STLS' not in caps:
  540. return defer.fail(TLSNotSupportedError(
  541. "Server does not support secure communication "
  542. "via TLS / SSL"))
  543. d = self.sendShort(b'STLS', None)
  544. d.addCallback(self._startedTLS, contextFactory, tls)
  545. d.addCallback(lambda _: self.capabilities())
  546. return d
  547. def _startedTLS(self, result, context, tls):
  548. """
  549. Complete the process of switching to encrypted communication.
  550. This callback function runs after the response to the STLS command has
  551. been received.
  552. The final steps are discarding the cached capabilities and initiating
  553. TLS negotiation on the transport.
  554. @type result: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or
  555. L{bytes} to L{None}
  556. @param result: The server capabilities.
  557. @type context: L{ClientContextFactory
  558. <twisted.internet.ssl.ClientContextFactory>}
  559. @param context: A context factory with which to negotiate TLS.
  560. @type tls: L{ITLSTransport <interfaces.ITLSTransport>}
  561. @param tls: A TCP transport that supports switching to TLS midstream.
  562. @rtype: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes}
  563. to L{None}
  564. @return: The server capabilities.
  565. """
  566. self.transport = tls
  567. self.transport.startTLS(context)
  568. self._capCache = None
  569. self.startedTLS = True
  570. return result
  571. def _getContextFactory(self):
  572. """
  573. Get a context factory with which to negotiate TLS.
  574. @rtype: L{None} or
  575. L{ClientContextFactory <twisted.internet.ssl.ClientContextFactory>}
  576. @return: A context factory or L{None} if TLS is not supported on the
  577. client.
  578. """
  579. try:
  580. from twisted.internet import ssl
  581. except ImportError:
  582. return None
  583. else:
  584. context = ssl.ClientContextFactory()
  585. context.method = ssl.SSL.TLSv1_METHOD
  586. return context
  587. def login(self, username, password):
  588. """
  589. Log in to the server.
  590. If APOP is available it will be used. Otherwise, if TLS is
  591. available, an encrypted session will be started and plaintext
  592. login will proceed. Otherwise, if L{allowInsecureLogin} is set,
  593. insecure plaintext login will proceed. Otherwise,
  594. L{InsecureAuthenticationDisallowed} will be raised.
  595. The first step of logging into the server is obtaining the server's
  596. capabilities. When that is complete, the L{_login} callback function
  597. continues the login process.
  598. @type username: L{bytes}
  599. @param username: The username with which to log in.
  600. @type password: L{bytes}
  601. @param password: The password with which to log in.
  602. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  603. L{bytes}
  604. @return: A deferred which fires when the login process is complete.
  605. On a successful login, it returns the server's response minus the
  606. status indicator.
  607. """
  608. d = self.capabilities()
  609. d.addCallback(self._login, username, password)
  610. return d
  611. def _login(self, caps, username, password):
  612. """
  613. Continue the process of logging in to the server.
  614. This callback function runs after the server capabilities are received.
  615. If the server provided a challenge in the greeting, proceed with an
  616. APOP login. Otherwise, if the server and the transport support
  617. encrypted communication, try to switch to TLS and then complete
  618. the login process with the L{_loginTLS} callback function. Otherwise,
  619. if insecure authentication is allowed, do a plaintext login.
  620. Otherwise, fail with an L{InsecureAuthenticationDisallowed} error.
  621. @type caps: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or
  622. L{bytes} to L{None}
  623. @param caps: The server capabilities.
  624. @type username: L{bytes}
  625. @param username: The username with which to log in.
  626. @type password: L{bytes}
  627. @param password: The password with which to log in.
  628. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  629. L{bytes}
  630. @return: A deferred which fires when the login process is complete.
  631. On a successful login, it returns the server's response minus the
  632. status indicator.
  633. """
  634. if self.serverChallenge is not None:
  635. return self._apop(username, password, self.serverChallenge)
  636. tryTLS = b'STLS' in caps
  637. # If our transport supports switching to TLS, we might want to
  638. # try to switch to TLS.
  639. tlsableTransport = interfaces.ITLSTransport(self.transport, None) is not None
  640. # If our transport is not already using TLS, we might want to
  641. # try to switch to TLS.
  642. nontlsTransport = interfaces.ISSLTransport(self.transport, None) is None
  643. if not self.startedTLS and tryTLS and tlsableTransport and nontlsTransport:
  644. d = self.startTLS()
  645. d.addCallback(self._loginTLS, username, password)
  646. return d
  647. elif self.startedTLS or not nontlsTransport or self.allowInsecureLogin:
  648. return self._plaintext(username, password)
  649. else:
  650. return defer.fail(InsecureAuthenticationDisallowed())
  651. def _loginTLS(self, res, username, password):
  652. """
  653. Do a plaintext login over an encrypted transport.
  654. This callback function runs after the transport switches to encrypted
  655. communication.
  656. @type res: L{dict} mapping L{bytes} to L{list} of L{bytes} and/or
  657. L{bytes} to L{None}
  658. @param res: The server capabilities.
  659. @type username: L{bytes}
  660. @param username: The username with which to log in.
  661. @type password: L{bytes}
  662. @param password: The password with which to log in.
  663. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  664. L{bytes} or fails with L{ServerErrorResponse}
  665. @return: A deferred which fires when the server accepts the username
  666. and password or fails when the server rejects either. On a
  667. successful login, it returns the server's response minus the
  668. status indicator.
  669. """
  670. return self._plaintext(username, password)
  671. def _plaintext(self, username, password):
  672. """
  673. Perform a plaintext login.
  674. @type username: L{bytes}
  675. @param username: The username with which to log in.
  676. @type password: L{bytes}
  677. @param password: The password with which to log in.
  678. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  679. L{bytes} or fails with L{ServerErrorResponse}
  680. @return: A deferred which fires when the server accepts the username
  681. and password or fails when the server rejects either. On a
  682. successful login, it returns the server's response minus the
  683. status indicator.
  684. """
  685. return self.user(username).addCallback(lambda r: self.password(password))
  686. def _apop(self, username, password, challenge):
  687. """
  688. Perform an APOP login.
  689. @type username: L{bytes}
  690. @param username: The username with which to log in.
  691. @type password: L{bytes}
  692. @param password: The password with which to log in.
  693. @type challenge: L{bytes}
  694. @param challenge: A challenge string.
  695. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  696. L{bytes} or fails with L{ServerErrorResponse}
  697. @return: A deferred which fires when the server response is received.
  698. On a successful login, it returns the server response minus
  699. the status indicator.
  700. """
  701. digest = md5(challenge + password).hexdigest().encode("ascii")
  702. return self.apop(username, digest)
  703. def apop(self, username, digest):
  704. """
  705. Send an APOP command to perform authenticated login.
  706. This should be used in special circumstances only, when it is
  707. known that the server supports APOP authentication, and APOP
  708. authentication is absolutely required. For the common case,
  709. use L{login} instead.
  710. @type username: L{bytes}
  711. @param username: The username with which to log in.
  712. @type digest: L{bytes}
  713. @param digest: The challenge response to authenticate with.
  714. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  715. L{bytes} or fails with L{ServerErrorResponse}
  716. @return: A deferred which fires when the server response is received.
  717. On an OK response, the deferred succeeds with the server
  718. response minus the status indicator. On an ERR response, the
  719. deferred fails with a server error response failure.
  720. """
  721. return self.sendShort(b'APOP', username + b' ' + digest)
  722. def user(self, username):
  723. """
  724. Send a USER command to perform the first half of plaintext login.
  725. Unless this is absolutely required, use the L{login} method instead.
  726. @type username: L{bytes}
  727. @param username: The username with which to log in.
  728. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  729. L{bytes} or fails with L{ServerErrorResponse}
  730. @return: A deferred which fires when the server response is received.
  731. On an OK response, the deferred succeeds with the server
  732. response minus the status indicator. On an ERR response, the
  733. deferred fails with a server error response failure.
  734. """
  735. return self.sendShort(b'USER', username)
  736. def password(self, password):
  737. """
  738. Send a PASS command to perform the second half of plaintext login.
  739. Unless this is absolutely required, use the L{login} method instead.
  740. @type password: L{bytes}
  741. @param password: The plaintext password with which to authenticate.
  742. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  743. L{bytes} or fails with L{ServerErrorResponse}
  744. @return: A deferred which fires when the server response is received.
  745. On an OK response, the deferred succeeds with the server
  746. response minus the status indicator. On an ERR response, the
  747. deferred fails with a server error response failure.
  748. """
  749. return self.sendShort(b'PASS', password)
  750. def delete(self, index):
  751. """
  752. Send a DELE command to delete a message from the server.
  753. @type index: L{int}
  754. @param index: The 0-based index of the message to delete.
  755. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  756. L{bytes} or fails with L{ServerErrorResponse}
  757. @return: A deferred which fires when the server response is received.
  758. On an OK response, the deferred succeeds with the server
  759. response minus the status indicator. On an ERR response, the
  760. deferred fails with a server error response failure.
  761. """
  762. return self.sendShort(b'DELE', intToBytes(index + 1))
  763. def _consumeOrSetItem(self, cmd, args, consumer, xform):
  764. """
  765. Send a command to which a long response is expected and process the
  766. multi-line response into a list accounting for deleted messages.
  767. @type cmd: L{bytes}
  768. @param cmd: A POP3 command to which a long response is expected.
  769. @type args: L{bytes}
  770. @param args: The command arguments.
  771. @type consumer: L{None} or callable that takes
  772. L{object}
  773. @param consumer: L{None} or a function that consumes the output from
  774. the transform function.
  775. @type xform: L{None}, callable that takes
  776. L{bytes} and returns 2-L{tuple} of (0) L{int}, (1) L{object},
  777. or callable that takes L{bytes} and returns L{object}
  778. @param xform: A function that parses a line from a multi-line response
  779. and transforms the values into usable form for input to the
  780. consumer function. If no consumer function is specified, the
  781. output must be a message index and corresponding value. If no
  782. transform function is specified, the line is used as is.
  783. @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of
  784. L{object} or callable that takes L{list} of L{object}
  785. @return: A deferred which fires when the entire response has been
  786. received. When a consumer is not provided, the return value is a
  787. list of the value for each message or L{None} for deleted messages.
  788. Otherwise, it returns the consumer itself.
  789. """
  790. if consumer is None:
  791. L = []
  792. consumer = _ListSetter(L).setitem
  793. return self.sendLong(cmd, args, consumer, xform).addCallback(lambda r: L)
  794. return self.sendLong(cmd, args, consumer, xform)
  795. def _consumeOrAppend(self, cmd, args, consumer, xform):
  796. """
  797. Send a command to which a long response is expected and process the
  798. multi-line response into a list.
  799. @type cmd: L{bytes}
  800. @param cmd: A POP3 command which expects a long response.
  801. @type args: L{bytes}
  802. @param args: The command arguments.
  803. @type consumer: L{None} or callable that takes
  804. L{object}
  805. @param consumer: L{None} or a function that consumes the output from the
  806. transform function.
  807. @type xform: L{None} or callable that takes
  808. L{bytes} and returns L{object}
  809. @param xform: A function that transforms a line from a multi-line
  810. response into usable form for input to the consumer function. If
  811. no transform function is specified, the line is used as is.
  812. @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of
  813. 2-L{tuple} of (0) L{int}, (1) L{object} or callable that
  814. takes 2-L{tuple} of (0) L{int}, (1) L{object}
  815. @return: A deferred which fires when the entire response has been
  816. received. When a consumer is not provided, the return value is a
  817. list of the transformed lines. Otherwise, it returns the consumer
  818. itself.
  819. """
  820. if consumer is None:
  821. L = []
  822. consumer = L.append
  823. return self.sendLong(cmd, args, consumer, xform).addCallback(lambda r: L)
  824. return self.sendLong(cmd, args, consumer, xform)
  825. def capabilities(self, useCache=True):
  826. """
  827. Send a CAPA command to retrieve the capabilities supported by
  828. the server.
  829. Not all servers support this command. If the server does not
  830. support this, it is treated as though it returned a successful
  831. response listing no capabilities. At some future time, this may be
  832. changed to instead seek out information about a server's
  833. capabilities in some other fashion (only if it proves useful to do
  834. so, and only if there are servers still in use which do not support
  835. CAPA but which do support POP3 extensions that are useful).
  836. @type useCache: L{bool}
  837. @param useCache: A flag that determines whether previously retrieved
  838. results should be used if available.
  839. @rtype: L{Deferred <defer.Deferred>} which successfully results in
  840. L{dict} mapping L{bytes} to L{list} of L{bytes} and/or L{bytes} to
  841. L{None}
  842. @return: A deferred which fires with a mapping of capability name to
  843. parameters. For example::
  844. C: CAPA
  845. S: +OK Capability list follows
  846. S: TOP
  847. S: USER
  848. S: SASL CRAM-MD5 KERBEROS_V4
  849. S: RESP-CODES
  850. S: LOGIN-DELAY 900
  851. S: PIPELINING
  852. S: EXPIRE 60
  853. S: UIDL
  854. S: IMPLEMENTATION Shlemazle-Plotz-v302
  855. S: .
  856. will be lead to a result of::
  857. | {'TOP': None,
  858. | 'USER': None,
  859. | 'SASL': ['CRAM-MD5', 'KERBEROS_V4'],
  860. | 'RESP-CODES': None,
  861. | 'LOGIN-DELAY': ['900'],
  862. | 'PIPELINING': None,
  863. | 'EXPIRE': ['60'],
  864. | 'UIDL': None,
  865. | 'IMPLEMENTATION': ['Shlemazle-Plotz-v302']}
  866. """
  867. if useCache and self._capCache is not None:
  868. return defer.succeed(self._capCache)
  869. cache = {}
  870. def consume(line):
  871. tmp = line.split()
  872. if len(tmp) == 1:
  873. cache[tmp[0]] = None
  874. elif len(tmp) > 1:
  875. cache[tmp[0]] = tmp[1:]
  876. def capaNotSupported(err):
  877. err.trap(ServerErrorResponse)
  878. return None
  879. def gotCapabilities(result):
  880. self._capCache = cache
  881. return cache
  882. d = self._consumeOrAppend(b'CAPA', None, consume, None)
  883. d.addErrback(capaNotSupported).addCallback(gotCapabilities)
  884. return d
  885. def noop(self):
  886. """
  887. Send a NOOP command asking the server to do nothing but respond.
  888. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  889. L{bytes} or fails with L{ServerErrorResponse}
  890. @return: A deferred which fires when the server response is received.
  891. On an OK response, the deferred succeeds with the server
  892. response minus the status indicator. On an ERR response, the
  893. deferred fails with a server error response failure.
  894. """
  895. return self.sendShort(b"NOOP", None)
  896. def reset(self):
  897. """
  898. Send a RSET command to unmark any messages that have been flagged
  899. for deletion on the server.
  900. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  901. L{bytes} or fails with L{ServerErrorResponse}
  902. @return: A deferred which fires when the server response is received.
  903. On an OK response, the deferred succeeds with the server
  904. response minus the status indicator. On an ERR response, the
  905. deferred fails with a server error response failure.
  906. """
  907. return self.sendShort(b"RSET", None)
  908. def retrieve(self, index, consumer=None, lines=None):
  909. """
  910. Send a RETR or TOP command to retrieve all or part of a message from
  911. the server.
  912. @type index: L{int}
  913. @param index: A 0-based message index.
  914. @type consumer: L{None} or callable that takes
  915. L{bytes}
  916. @param consumer: A function which consumes each transformed line from a
  917. multi-line response as it is received.
  918. @type lines: L{None} or L{int}
  919. @param lines: If specified, the number of lines of the message to be
  920. retrieved. Otherwise, the entire message is retrieved.
  921. @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of
  922. L{bytes}, or callable that takes 2-L{tuple} of (0) L{int},
  923. (1) L{object}
  924. @return: A deferred which fires when the entire response has been
  925. received. When a consumer is not provided, the return value is a
  926. list of the transformed lines. Otherwise, it returns the consumer
  927. itself.
  928. """
  929. idx = intToBytes(index + 1)
  930. if lines is None:
  931. return self._consumeOrAppend(b'RETR', idx, consumer, _dotUnquoter)
  932. return self._consumeOrAppend(b'TOP', idx + b' ' + intToBytes(lines),
  933. consumer, _dotUnquoter)
  934. def stat(self):
  935. """
  936. Send a STAT command to get information about the size of the mailbox.
  937. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  938. a 2-tuple of (0) L{int}, (1) L{int} or fails with
  939. L{ServerErrorResponse}
  940. @return: A deferred which fires when the server response is received.
  941. On an OK response, the deferred succeeds with the number of
  942. messages in the mailbox and the size of the mailbox in octets.
  943. On an ERR response, the deferred fails with a server error
  944. response failure.
  945. """
  946. return self.sendShort(b'STAT', None).addCallback(_statXform)
  947. def listSize(self, consumer=None):
  948. """
  949. Send a LIST command to retrieve the sizes of all messages on the
  950. server.
  951. @type consumer: L{None} or callable that takes
  952. 2-L{tuple} of (0) L{int}, (1) L{int}
  953. @param consumer: A function which consumes the 0-based message index
  954. and message size derived from the server response.
  955. @rtype: L{Deferred <defer.Deferred>} which fires L{list} of L{int} or
  956. callable that takes 2-L{tuple} of (0) L{int}, (1) L{int}
  957. @return: A deferred which fires when the entire response has been
  958. received. When a consumer is not provided, the return value is a
  959. list of message sizes. Otherwise, it returns the consumer itself.
  960. """
  961. return self._consumeOrSetItem(b'LIST', None, consumer, _listXform)
  962. def listUID(self, consumer=None):
  963. """
  964. Send a UIDL command to retrieve the UIDs of all messages on the server.
  965. @type consumer: L{None} or callable that takes
  966. 2-L{tuple} of (0) L{int}, (1) L{bytes}
  967. @param consumer: A function which consumes the 0-based message index
  968. and UID derived from the server response.
  969. @rtype: L{Deferred <defer.Deferred>} which fires with L{list} of
  970. L{object} or callable that takes 2-L{tuple} of (0) L{int},
  971. (1) L{bytes}
  972. @return: A deferred which fires when the entire response has been
  973. received. When a consumer is not provided, the return value is a
  974. list of message sizes. Otherwise, it returns the consumer itself.
  975. """
  976. return self._consumeOrSetItem(b'UIDL', None, consumer, _uidXform)
  977. def quit(self):
  978. """
  979. Send a QUIT command to disconnect from the server.
  980. @rtype: L{Deferred <defer.Deferred>} which successfully fires with
  981. L{bytes} or fails with L{ServerErrorResponse}
  982. @return: A deferred which fires when the server response is received.
  983. On an OK response, the deferred succeeds with the server
  984. response minus the status indicator. On an ERR response, the
  985. deferred fails with a server error response failure.
  986. """
  987. return self.sendShort(b'QUIT', None)
  988. __all__ = []