pop3client.py 45 KB

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