You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

imaplib.py 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125
  1. """IMAP4 client.
  2. Based on RFC 2060.
  3. Public class: IMAP4
  4. Public variable: Debug
  5. Public functions: Internaldate2tuple
  6. Int2AP
  7. ParseFlags
  8. Time2Internaldate
  9. """
  10. # Author: Piers Lauder <piers@cs.su.oz.au> December 1997.
  11. #
  12. # Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
  13. # String method conversion by ESR, February 2001.
  14. __version__ = "2.40"
  15. import binascii, re, socket, time, random, sys
  16. __all__ = ["IMAP4", "Internaldate2tuple",
  17. "Int2AP", "ParseFlags", "Time2Internaldate"]
  18. # Globals
  19. CRLF = '\r\n'
  20. Debug = 0
  21. IMAP4_PORT = 143
  22. AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
  23. # Commands
  24. Commands = {
  25. # name valid states
  26. 'APPEND': ('AUTH', 'SELECTED'),
  27. 'AUTHENTICATE': ('NONAUTH',),
  28. 'CAPABILITY': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  29. 'CHECK': ('SELECTED',),
  30. 'CLOSE': ('SELECTED',),
  31. 'COPY': ('SELECTED',),
  32. 'CREATE': ('AUTH', 'SELECTED'),
  33. 'DELETE': ('AUTH', 'SELECTED'),
  34. 'EXAMINE': ('AUTH', 'SELECTED'),
  35. 'EXPUNGE': ('SELECTED',),
  36. 'FETCH': ('SELECTED',),
  37. 'LIST': ('AUTH', 'SELECTED'),
  38. 'LOGIN': ('NONAUTH',),
  39. 'LOGOUT': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  40. 'LSUB': ('AUTH', 'SELECTED'),
  41. 'NOOP': ('NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'),
  42. 'PARTIAL': ('SELECTED',),
  43. 'RENAME': ('AUTH', 'SELECTED'),
  44. 'SEARCH': ('SELECTED',),
  45. 'SELECT': ('AUTH', 'SELECTED'),
  46. 'STATUS': ('AUTH', 'SELECTED'),
  47. 'STORE': ('SELECTED',),
  48. 'SUBSCRIBE': ('AUTH', 'SELECTED'),
  49. 'UID': ('SELECTED',),
  50. 'UNSUBSCRIBE': ('AUTH', 'SELECTED'),
  51. }
  52. # Patterns to match server responses
  53. Continuation = re.compile(r'\+( (?P<data>.*))?')
  54. Flags = re.compile(r'.*FLAGS \((?P<flags>[^\)]*)\)')
  55. InternalDate = re.compile(r'.*INTERNALDATE "'
  56. r'(?P<day>[ 123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
  57. r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
  58. r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
  59. r'"')
  60. Literal = re.compile(r'.*{(?P<size>\d+)}$')
  61. Response_code = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
  62. Untagged_response = re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  63. Untagged_status = re.compile(r'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?')
  64. class IMAP4:
  65. """IMAP4 client class.
  66. Instantiate with: IMAP4([host[, port]])
  67. host - host's name (default: localhost);
  68. port - port number (default: standard IMAP4 port).
  69. All IMAP4rev1 commands are supported by methods of the same
  70. name (in lower-case).
  71. All arguments to commands are converted to strings, except for
  72. AUTHENTICATE, and the last argument to APPEND which is passed as
  73. an IMAP4 literal. If necessary (the string contains any
  74. non-printing characters or white-space and isn't enclosed with
  75. either parentheses or double quotes) each string is quoted.
  76. However, the 'password' argument to the LOGIN command is always
  77. quoted. If you want to avoid having an argument string quoted
  78. (eg: the 'flags' argument to STORE) then enclose the string in
  79. parentheses (eg: "(\Deleted)").
  80. Each command returns a tuple: (type, [data, ...]) where 'type'
  81. is usually 'OK' or 'NO', and 'data' is either the text from the
  82. tagged response, or untagged results from command.
  83. Errors raise the exception class <instance>.error("<reason>").
  84. IMAP4 server errors raise <instance>.abort("<reason>"),
  85. which is a sub-class of 'error'. Mailbox status changes
  86. from READ-WRITE to READ-ONLY raise the exception class
  87. <instance>.readonly("<reason>"), which is a sub-class of 'abort'.
  88. "error" exceptions imply a program error.
  89. "abort" exceptions imply the connection should be reset, and
  90. the command re-tried.
  91. "readonly" exceptions imply the command should be re-tried.
  92. Note: to use this module, you must read the RFCs pertaining
  93. to the IMAP4 protocol, as the semantics of the arguments to
  94. each IMAP4 command are left to the invoker, not to mention
  95. the results.
  96. """
  97. class error(Exception): pass # Logical errors - debug required
  98. class abort(error): pass # Service errors - close and retry
  99. class readonly(abort): pass # Mailbox status changed to READ-ONLY
  100. mustquote = re.compile(r"[^\w!#$%&'*+,.:;<=>?^`|~-]")
  101. def __init__(self, host = '', port = IMAP4_PORT):
  102. self.host = host
  103. self.port = port
  104. self.debug = Debug
  105. self.state = 'LOGOUT'
  106. self.literal = None # A literal argument to a command
  107. self.tagged_commands = {} # Tagged commands awaiting response
  108. self.untagged_responses = {} # {typ: [data, ...], ...}
  109. self.continuation_response = '' # Last continuation response
  110. self.is_readonly = None # READ-ONLY desired state
  111. self.tagnum = 0
  112. # Open socket to server.
  113. self.open(host, port)
  114. # Create unique tag for this session,
  115. # and compile tagged response matcher.
  116. self.tagpre = Int2AP(random.randint(0, 31999))
  117. self.tagre = re.compile(r'(?P<tag>'
  118. + self.tagpre
  119. + r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
  120. # Get server welcome message,
  121. # request and store CAPABILITY response.
  122. if __debug__:
  123. if self.debug >= 1:
  124. _mesg('new IMAP4 connection, tag=%s' % self.tagpre)
  125. self.welcome = self._get_response()
  126. if self.untagged_responses.has_key('PREAUTH'):
  127. self.state = 'AUTH'
  128. elif self.untagged_responses.has_key('OK'):
  129. self.state = 'NONAUTH'
  130. else:
  131. raise self.error(self.welcome)
  132. cap = 'CAPABILITY'
  133. self._simple_command(cap)
  134. if not self.untagged_responses.has_key(cap):
  135. raise self.error('no CAPABILITY response from server')
  136. self.capabilities = tuple(self.untagged_responses[cap][-1].upper().split())
  137. if __debug__:
  138. if self.debug >= 3:
  139. _mesg('CAPABILITIES: %s' % `self.capabilities`)
  140. for version in AllowedVersions:
  141. if not version in self.capabilities:
  142. continue
  143. self.PROTOCOL_VERSION = version
  144. return
  145. raise self.error('server not IMAP4 compliant')
  146. def __getattr__(self, attr):
  147. # Allow UPPERCASE variants of IMAP4 command methods.
  148. if Commands.has_key(attr):
  149. return eval("self.%s" % attr.lower())
  150. raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  151. # Public methods
  152. def open(self, host, port):
  153. """Setup 'self.sock' and 'self.file'."""
  154. self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  155. self.sock.connect((self.host, self.port))
  156. self.file = self.sock.makefile('rb')
  157. def recent(self):
  158. """Return most recent 'RECENT' responses if any exist,
  159. else prompt server for an update using the 'NOOP' command.
  160. (typ, [data]) = <instance>.recent()
  161. 'data' is None if no new messages,
  162. else list of RECENT responses, most recent last.
  163. """
  164. name = 'RECENT'
  165. typ, dat = self._untagged_response('OK', [None], name)
  166. if dat[-1]:
  167. return typ, dat
  168. typ, dat = self.noop() # Prod server for response
  169. return self._untagged_response(typ, dat, name)
  170. def response(self, code):
  171. """Return data for response 'code' if received, or None.
  172. Old value for response 'code' is cleared.
  173. (code, [data]) = <instance>.response(code)
  174. """
  175. return self._untagged_response(code, [None], code.upper())
  176. def socket(self):
  177. """Return socket instance used to connect to IMAP4 server.
  178. socket = <instance>.socket()
  179. """
  180. return self.sock
  181. # IMAP4 commands
  182. def append(self, mailbox, flags, date_time, message):
  183. """Append message to named mailbox.
  184. (typ, [data]) = <instance>.append(mailbox, flags, date_time, message)
  185. All args except `message' can be None.
  186. """
  187. name = 'APPEND'
  188. if not mailbox:
  189. mailbox = 'INBOX'
  190. if flags:
  191. if (flags[0],flags[-1]) != ('(',')'):
  192. flags = '(%s)' % flags
  193. else:
  194. flags = None
  195. if date_time:
  196. date_time = Time2Internaldate(date_time)
  197. else:
  198. date_time = None
  199. self.literal = message
  200. return self._simple_command(name, mailbox, flags, date_time)
  201. def authenticate(self, mechanism, authobject):
  202. """Authenticate command - requires response processing.
  203. 'mechanism' specifies which authentication mechanism is to
  204. be used - it must appear in <instance>.capabilities in the
  205. form AUTH=<mechanism>.
  206. 'authobject' must be a callable object:
  207. data = authobject(response)
  208. It will be called to process server continuation responses.
  209. It should return data that will be encoded and sent to server.
  210. It should return None if the client abort response '*' should
  211. be sent instead.
  212. """
  213. mech = mechanism.upper()
  214. cap = 'AUTH=%s' % mech
  215. if not cap in self.capabilities:
  216. raise self.error("Server doesn't allow %s authentication." % mech)
  217. self.literal = _Authenticator(authobject).process
  218. typ, dat = self._simple_command('AUTHENTICATE', mech)
  219. if typ != 'OK':
  220. raise self.error(dat[-1])
  221. self.state = 'AUTH'
  222. return typ, dat
  223. def check(self):
  224. """Checkpoint mailbox on server.
  225. (typ, [data]) = <instance>.check()
  226. """
  227. return self._simple_command('CHECK')
  228. def close(self):
  229. """Close currently selected mailbox.
  230. Deleted messages are removed from writable mailbox.
  231. This is the recommended command before 'LOGOUT'.
  232. (typ, [data]) = <instance>.close()
  233. """
  234. try:
  235. typ, dat = self._simple_command('CLOSE')
  236. finally:
  237. self.state = 'AUTH'
  238. return typ, dat
  239. def copy(self, message_set, new_mailbox):
  240. """Copy 'message_set' messages onto end of 'new_mailbox'.
  241. (typ, [data]) = <instance>.copy(message_set, new_mailbox)
  242. """
  243. return self._simple_command('COPY', message_set, new_mailbox)
  244. def create(self, mailbox):
  245. """Create new mailbox.
  246. (typ, [data]) = <instance>.create(mailbox)
  247. """
  248. return self._simple_command('CREATE', mailbox)
  249. def delete(self, mailbox):
  250. """Delete old mailbox.
  251. (typ, [data]) = <instance>.delete(mailbox)
  252. """
  253. return self._simple_command('DELETE', mailbox)
  254. def expunge(self):
  255. """Permanently remove deleted items from selected mailbox.
  256. Generates 'EXPUNGE' response for each deleted message.
  257. (typ, [data]) = <instance>.expunge()
  258. 'data' is list of 'EXPUNGE'd message numbers in order received.
  259. """
  260. name = 'EXPUNGE'
  261. typ, dat = self._simple_command(name)
  262. return self._untagged_response(typ, dat, name)
  263. def fetch(self, message_set, message_parts):
  264. """Fetch (parts of) messages.
  265. (typ, [data, ...]) = <instance>.fetch(message_set, message_parts)
  266. 'message_parts' should be a string of selected parts
  267. enclosed in parentheses, eg: "(UID BODY[TEXT])".
  268. 'data' are tuples of message part envelope and data.
  269. """
  270. name = 'FETCH'
  271. typ, dat = self._simple_command(name, message_set, message_parts)
  272. return self._untagged_response(typ, dat, name)
  273. def list(self, directory='""', pattern='*'):
  274. """List mailbox names in directory matching pattern.
  275. (typ, [data]) = <instance>.list(directory='""', pattern='*')
  276. 'data' is list of LIST responses.
  277. """
  278. name = 'LIST'
  279. typ, dat = self._simple_command(name, directory, pattern)
  280. return self._untagged_response(typ, dat, name)
  281. def login(self, user, password):
  282. """Identify client using plaintext password.
  283. (typ, [data]) = <instance>.login(user, password)
  284. NB: 'password' will be quoted.
  285. """
  286. #if not 'AUTH=LOGIN' in self.capabilities:
  287. # raise self.error("Server doesn't allow LOGIN authentication." % mech)
  288. typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  289. if typ != 'OK':
  290. raise self.error(dat[-1])
  291. self.state = 'AUTH'
  292. return typ, dat
  293. def logout(self):
  294. """Shutdown connection to server.
  295. (typ, [data]) = <instance>.logout()
  296. Returns server 'BYE' response.
  297. """
  298. self.state = 'LOGOUT'
  299. try: typ, dat = self._simple_command('LOGOUT')
  300. except: typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
  301. self.file.close()
  302. self.sock.close()
  303. if self.untagged_responses.has_key('BYE'):
  304. return 'BYE', self.untagged_responses['BYE']
  305. return typ, dat
  306. def lsub(self, directory='""', pattern='*'):
  307. """List 'subscribed' mailbox names in directory matching pattern.
  308. (typ, [data, ...]) = <instance>.lsub(directory='""', pattern='*')
  309. 'data' are tuples of message part envelope and data.
  310. """
  311. name = 'LSUB'
  312. typ, dat = self._simple_command(name, directory, pattern)
  313. return self._untagged_response(typ, dat, name)
  314. def noop(self):
  315. """Send NOOP command.
  316. (typ, data) = <instance>.noop()
  317. """
  318. if __debug__:
  319. if self.debug >= 3:
  320. _dump_ur(self.untagged_responses)
  321. return self._simple_command('NOOP')
  322. def partial(self, message_num, message_part, start, length):
  323. """Fetch truncated part of a message.
  324. (typ, [data, ...]) = <instance>.partial(message_num, message_part, start, length)
  325. 'data' is tuple of message part envelope and data.
  326. """
  327. name = 'PARTIAL'
  328. typ, dat = self._simple_command(name, message_num, message_part, start, length)
  329. return self._untagged_response(typ, dat, 'FETCH')
  330. def rename(self, oldmailbox, newmailbox):
  331. """Rename old mailbox name to new.
  332. (typ, data) = <instance>.rename(oldmailbox, newmailbox)
  333. """
  334. return self._simple_command('RENAME', oldmailbox, newmailbox)
  335. def search(self, charset, *criteria):
  336. """Search mailbox for matching messages.
  337. (typ, [data]) = <instance>.search(charset, criterium, ...)
  338. 'data' is space separated list of matching message numbers.
  339. """
  340. name = 'SEARCH'
  341. if charset:
  342. charset = 'CHARSET ' + charset
  343. typ, dat = apply(self._simple_command, (name, charset) + criteria)
  344. return self._untagged_response(typ, dat, name)
  345. def select(self, mailbox='INBOX', readonly=None):
  346. """Select a mailbox.
  347. Flush all untagged responses.
  348. (typ, [data]) = <instance>.select(mailbox='INBOX', readonly=None)
  349. 'data' is count of messages in mailbox ('EXISTS' response).
  350. """
  351. # Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY')
  352. self.untagged_responses = {} # Flush old responses.
  353. self.is_readonly = readonly
  354. if readonly:
  355. name = 'EXAMINE'
  356. else:
  357. name = 'SELECT'
  358. typ, dat = self._simple_command(name, mailbox)
  359. if typ != 'OK':
  360. self.state = 'AUTH' # Might have been 'SELECTED'
  361. return typ, dat
  362. self.state = 'SELECTED'
  363. if self.untagged_responses.has_key('READ-ONLY') \
  364. and not readonly:
  365. if __debug__:
  366. if self.debug >= 1:
  367. _dump_ur(self.untagged_responses)
  368. raise self.readonly('%s is not writable' % mailbox)
  369. return typ, self.untagged_responses.get('EXISTS', [None])
  370. def status(self, mailbox, names):
  371. """Request named status conditions for mailbox.
  372. (typ, [data]) = <instance>.status(mailbox, names)
  373. """
  374. name = 'STATUS'
  375. if self.PROTOCOL_VERSION == 'IMAP4':
  376. raise self.error('%s unimplemented in IMAP4 (obtain IMAP4rev1 server, or re-code)' % name)
  377. typ, dat = self._simple_command(name, mailbox, names)
  378. return self._untagged_response(typ, dat, name)
  379. def store(self, message_set, command, flags):
  380. """Alters flag dispositions for messages in mailbox.
  381. (typ, [data]) = <instance>.store(message_set, command, flags)
  382. """
  383. if (flags[0],flags[-1]) != ('(',')'):
  384. flags = '(%s)' % flags # Avoid quoting the flags
  385. typ, dat = self._simple_command('STORE', message_set, command, flags)
  386. return self._untagged_response(typ, dat, 'FETCH')
  387. def subscribe(self, mailbox):
  388. """Subscribe to new mailbox.
  389. (typ, [data]) = <instance>.subscribe(mailbox)
  390. """
  391. return self._simple_command('SUBSCRIBE', mailbox)
  392. def uid(self, command, *args):
  393. """Execute "command arg ..." with messages identified by UID,
  394. rather than message number.
  395. (typ, [data]) = <instance>.uid(command, arg1, arg2, ...)
  396. Returns response appropriate to 'command'.
  397. """
  398. command = command.upper()
  399. if not Commands.has_key(command):
  400. raise self.error("Unknown IMAP4 UID command: %s" % command)
  401. if self.state not in Commands[command]:
  402. raise self.error('command %s illegal in state %s'
  403. % (command, self.state))
  404. name = 'UID'
  405. typ, dat = apply(self._simple_command, (name, command) + args)
  406. if command == 'SEARCH':
  407. name = 'SEARCH'
  408. else:
  409. name = 'FETCH'
  410. return self._untagged_response(typ, dat, name)
  411. def unsubscribe(self, mailbox):
  412. """Unsubscribe from old mailbox.
  413. (typ, [data]) = <instance>.unsubscribe(mailbox)
  414. """
  415. return self._simple_command('UNSUBSCRIBE', mailbox)
  416. def xatom(self, name, *args):
  417. """Allow simple extension commands
  418. notified by server in CAPABILITY response.
  419. (typ, [data]) = <instance>.xatom(name, arg, ...)
  420. """
  421. if name[0] != 'X' or not name in self.capabilities:
  422. raise self.error('unknown extension command: %s' % name)
  423. return apply(self._simple_command, (name,) + args)
  424. # Private methods
  425. def _append_untagged(self, typ, dat):
  426. if dat is None: dat = ''
  427. ur = self.untagged_responses
  428. if __debug__:
  429. if self.debug >= 5:
  430. _mesg('untagged_responses[%s] %s += ["%s"]' %
  431. (typ, len(ur.get(typ,'')), dat))
  432. if ur.has_key(typ):
  433. ur[typ].append(dat)
  434. else:
  435. ur[typ] = [dat]
  436. def _check_bye(self):
  437. bye = self.untagged_responses.get('BYE')
  438. if bye:
  439. raise self.abort(bye[-1])
  440. def _command(self, name, *args):
  441. if self.state not in Commands[name]:
  442. self.literal = None
  443. raise self.error(
  444. 'command %s illegal in state %s' % (name, self.state))
  445. for typ in ('OK', 'NO', 'BAD'):
  446. if self.untagged_responses.has_key(typ):
  447. del self.untagged_responses[typ]
  448. if self.untagged_responses.has_key('READ-ONLY') \
  449. and not self.is_readonly:
  450. raise self.readonly('mailbox status changed to READ-ONLY')
  451. tag = self._new_tag()
  452. data = '%s %s' % (tag, name)
  453. for arg in args:
  454. if arg is None: continue
  455. data = '%s %s' % (data, self._checkquote(arg))
  456. literal = self.literal
  457. if literal is not None:
  458. self.literal = None
  459. if type(literal) is type(self._command):
  460. literator = literal
  461. else:
  462. literator = None
  463. data = '%s {%s}' % (data, len(literal))
  464. if __debug__:
  465. if self.debug >= 4:
  466. _mesg('> %s' % data)
  467. else:
  468. _log('> %s' % data)
  469. try:
  470. self.sock.send('%s%s' % (data, CRLF))
  471. except socket.error, val:
  472. raise self.abort('socket error: %s' % val)
  473. if literal is None:
  474. return tag
  475. while 1:
  476. # Wait for continuation response
  477. while self._get_response():
  478. if self.tagged_commands[tag]: # BAD/NO?
  479. return tag
  480. # Send literal
  481. if literator:
  482. literal = literator(self.continuation_response)
  483. if __debug__:
  484. if self.debug >= 4:
  485. _mesg('write literal size %s' % len(literal))
  486. try:
  487. self.sock.send(literal)
  488. self.sock.send(CRLF)
  489. except socket.error, val:
  490. raise self.abort('socket error: %s' % val)
  491. if not literator:
  492. break
  493. return tag
  494. def _command_complete(self, name, tag):
  495. self._check_bye()
  496. try:
  497. typ, data = self._get_tagged_response(tag)
  498. except self.abort, val:
  499. raise self.abort('command: %s => %s' % (name, val))
  500. except self.error, val:
  501. raise self.error('command: %s => %s' % (name, val))
  502. self._check_bye()
  503. if typ == 'BAD':
  504. raise self.error('%s command error: %s %s' % (name, typ, data))
  505. return typ, data
  506. def _get_response(self):
  507. # Read response and store.
  508. #
  509. # Returns None for continuation responses,
  510. # otherwise first response line received.
  511. resp = self._get_line()
  512. # Command completion response?
  513. if self._match(self.tagre, resp):
  514. tag = self.mo.group('tag')
  515. if not self.tagged_commands.has_key(tag):
  516. raise self.abort('unexpected tagged response: %s' % resp)
  517. typ = self.mo.group('type')
  518. dat = self.mo.group('data')
  519. self.tagged_commands[tag] = (typ, [dat])
  520. else:
  521. dat2 = None
  522. # '*' (untagged) responses?
  523. if not self._match(Untagged_response, resp):
  524. if self._match(Untagged_status, resp):
  525. dat2 = self.mo.group('data2')
  526. if self.mo is None:
  527. # Only other possibility is '+' (continuation) response...
  528. if self._match(Continuation, resp):
  529. self.continuation_response = self.mo.group('data')
  530. return None # NB: indicates continuation
  531. raise self.abort("unexpected response: '%s'" % resp)
  532. typ = self.mo.group('type')
  533. dat = self.mo.group('data')
  534. if dat is None: dat = '' # Null untagged response
  535. if dat2: dat = dat + ' ' + dat2
  536. # Is there a literal to come?
  537. while self._match(Literal, dat):
  538. # Read literal direct from connection.
  539. size = int(self.mo.group('size'))
  540. if __debug__:
  541. if self.debug >= 4:
  542. _mesg('read literal size %s' % size)
  543. data = self.file.read(size)
  544. # Store response with literal as tuple
  545. self._append_untagged(typ, (dat, data))
  546. # Read trailer - possibly containing another literal
  547. dat = self._get_line()
  548. self._append_untagged(typ, dat)
  549. # Bracketed response information?
  550. if typ in ('OK', 'NO', 'BAD') and self._match(Response_code, dat):
  551. self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  552. if __debug__:
  553. if self.debug >= 1 and typ in ('NO', 'BAD', 'BYE'):
  554. _mesg('%s response: %s' % (typ, dat))
  555. return resp
  556. def _get_tagged_response(self, tag):
  557. while 1:
  558. result = self.tagged_commands[tag]
  559. if result is not None:
  560. del self.tagged_commands[tag]
  561. return result
  562. # Some have reported "unexpected response" exceptions.
  563. # Note that ignoring them here causes loops.
  564. # Instead, send me details of the unexpected response and
  565. # I'll update the code in `_get_response()'.
  566. try:
  567. self._get_response()
  568. except self.abort, val:
  569. if __debug__:
  570. if self.debug >= 1:
  571. print_log()
  572. raise
  573. def _get_line(self):
  574. line = self.file.readline()
  575. if not line:
  576. raise self.abort('socket error: EOF')
  577. # Protocol mandates all lines terminated by CRLF
  578. line = line[:-2]
  579. if __debug__:
  580. if self.debug >= 4:
  581. _mesg('< %s' % line)
  582. else:
  583. _log('< %s' % line)
  584. return line
  585. def _match(self, cre, s):
  586. # Run compiled regular expression match method on 's'.
  587. # Save result, return success.
  588. self.mo = cre.match(s)
  589. if __debug__:
  590. if self.mo is not None and self.debug >= 5:
  591. _mesg("\tmatched r'%s' => %s" % (cre.pattern, `self.mo.groups()`))
  592. return self.mo is not None
  593. def _new_tag(self):
  594. tag = '%s%s' % (self.tagpre, self.tagnum)
  595. self.tagnum = self.tagnum + 1
  596. self.tagged_commands[tag] = None
  597. return tag
  598. def _checkquote(self, arg):
  599. # Must quote command args if non-alphanumeric chars present,
  600. # and not already quoted.
  601. if type(arg) is not type(''):
  602. return arg
  603. if (arg[0],arg[-1]) in (('(',')'),('"','"')):
  604. return arg
  605. if self.mustquote.search(arg) is None:
  606. return arg
  607. return self._quote(arg)
  608. def _quote(self, arg):
  609. arg = arg.replace('\\', '\\\\')
  610. arg = arg.replace('"', '\\"')
  611. return '"%s"' % arg
  612. def _simple_command(self, name, *args):
  613. return self._command_complete(name, apply(self._command, (name,) + args))
  614. def _untagged_response(self, typ, dat, name):
  615. if typ == 'NO':
  616. return typ, dat
  617. if not self.untagged_responses.has_key(name):
  618. return typ, [None]
  619. data = self.untagged_responses[name]
  620. if __debug__:
  621. if self.debug >= 5:
  622. _mesg('untagged_responses[%s] => %s' % (name, data))
  623. del self.untagged_responses[name]
  624. return typ, data
  625. class _Authenticator:
  626. """Private class to provide en/decoding
  627. for base64-based authentication conversation.
  628. """
  629. def __init__(self, mechinst):
  630. self.mech = mechinst # Callable object to provide/process data
  631. def process(self, data):
  632. ret = self.mech(self.decode(data))
  633. if ret is None:
  634. return '*' # Abort conversation
  635. return self.encode(ret)
  636. def encode(self, inp):
  637. #
  638. # Invoke binascii.b2a_base64 iteratively with
  639. # short even length buffers, strip the trailing
  640. # line feed from the result and append. "Even"
  641. # means a number that factors to both 6 and 8,
  642. # so when it gets to the end of the 8-bit input
  643. # there's no partial 6-bit output.
  644. #
  645. oup = ''
  646. while inp:
  647. if len(inp) > 48:
  648. t = inp[:48]
  649. inp = inp[48:]
  650. else:
  651. t = inp
  652. inp = ''
  653. e = binascii.b2a_base64(t)
  654. if e:
  655. oup = oup + e[:-1]
  656. return oup
  657. def decode(self, inp):
  658. if not inp:
  659. return ''
  660. return binascii.a2b_base64(inp)
  661. Mon2num = {'Jan': 1, 'Feb': 2, 'Mar': 3, 'Apr': 4, 'May': 5, 'Jun': 6,
  662. 'Jul': 7, 'Aug': 8, 'Sep': 9, 'Oct': 10, 'Nov': 11, 'Dec': 12}
  663. def Internaldate2tuple(resp):
  664. """Convert IMAP4 INTERNALDATE to UT.
  665. Returns Python time module tuple.
  666. """
  667. mo = InternalDate.match(resp)
  668. if not mo:
  669. return None
  670. mon = Mon2num[mo.group('mon')]
  671. zonen = mo.group('zonen')
  672. day = int(mo.group('day'))
  673. year = int(mo.group('year'))
  674. hour = int(mo.group('hour'))
  675. min = int(mo.group('min'))
  676. sec = int(mo.group('sec'))
  677. zoneh = int(mo.group('zoneh'))
  678. zonem = int(mo.group('zonem'))
  679. # INTERNALDATE timezone must be subtracted to get UT
  680. zone = (zoneh*60 + zonem)*60
  681. if zonen == '-':
  682. zone = -zone
  683. tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  684. utc = time.mktime(tt)
  685. # Following is necessary because the time module has no 'mkgmtime'.
  686. # 'mktime' assumes arg in local timezone, so adds timezone/altzone.
  687. lt = time.localtime(utc)
  688. if time.daylight and lt[-1]:
  689. zone = zone + time.altzone
  690. else:
  691. zone = zone + time.timezone
  692. return time.localtime(utc - zone)
  693. def Int2AP(num):
  694. """Convert integer to A-P string representation."""
  695. val = ''; AP = 'ABCDEFGHIJKLMNOP'
  696. num = int(abs(num))
  697. while num:
  698. num, mod = divmod(num, 16)
  699. val = AP[mod] + val
  700. return val
  701. def ParseFlags(resp):
  702. """Convert IMAP4 flags response to python tuple."""
  703. mo = Flags.match(resp)
  704. if not mo:
  705. return ()
  706. return tuple(mo.group('flags').split())
  707. def Time2Internaldate(date_time):
  708. """Convert 'date_time' to IMAP4 INTERNALDATE representation.
  709. Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'
  710. """
  711. dttype = type(date_time)
  712. if dttype is type(1) or dttype is type(1.1):
  713. tt = time.localtime(date_time)
  714. elif dttype is type(()):
  715. tt = date_time
  716. elif dttype is type(""):
  717. return date_time # Assume in correct format
  718. else: raise ValueError
  719. dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
  720. if dt[0] == '0':
  721. dt = ' ' + dt[1:]
  722. if time.daylight and tt[-1]:
  723. zone = -time.altzone
  724. else:
  725. zone = -time.timezone
  726. return '"' + dt + " %+02d%02d" % divmod(zone/60, 60) + '"'
  727. if __debug__:
  728. def _mesg(s, secs=None):
  729. if secs is None:
  730. secs = time.time()
  731. tm = time.strftime('%M:%S', time.localtime(secs))
  732. sys.stderr.write(' %s.%02d %s\n' % (tm, (secs*100)%100, s))
  733. sys.stderr.flush()
  734. def _dump_ur(dict):
  735. # Dump untagged responses (in `dict').
  736. l = dict.items()
  737. if not l: return
  738. t = '\n\t\t'
  739. l = map(lambda x:'%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or ''), l)
  740. _mesg('untagged responses dump:%s%s' % (t, t.join(l)))
  741. _cmd_log = [] # Last `_cmd_log_len' interactions
  742. _cmd_log_len = 10
  743. def _log(line):
  744. # Keep log of last `_cmd_log_len' interactions for debugging.
  745. if len(_cmd_log) == _cmd_log_len:
  746. del _cmd_log[0]
  747. _cmd_log.append((time.time(), line))
  748. def print_log():
  749. _mesg('last %d IMAP4 interactions:' % len(_cmd_log))
  750. for secs,line in _cmd_log:
  751. _mesg(line, secs)
  752. if __name__ == '__main__':
  753. import getopt, getpass, sys
  754. try:
  755. optlist, args = getopt.getopt(sys.argv[1:], 'd:')
  756. except getopt.error, val:
  757. pass
  758. for opt,val in optlist:
  759. if opt == '-d':
  760. Debug = int(val)
  761. if not args: args = ('',)
  762. host = args[0]
  763. USER = getpass.getuser()
  764. PASSWD = getpass.getpass("IMAP password for %s on %s:" % (USER, host or "localhost"))
  765. test_mesg = 'From: %s@localhost\nSubject: IMAP4 test\n\ndata...\n' % USER
  766. test_seq1 = (
  767. ('login', (USER, PASSWD)),
  768. ('create', ('/tmp/xxx 1',)),
  769. ('rename', ('/tmp/xxx 1', '/tmp/yyy')),
  770. ('CREATE', ('/tmp/yyz 2',)),
  771. ('append', ('/tmp/yyz 2', None, None, test_mesg)),
  772. ('list', ('/tmp', 'yy*')),
  773. ('select', ('/tmp/yyz 2',)),
  774. ('search', (None, 'SUBJECT', 'test')),
  775. ('partial', ('1', 'RFC822', 1, 1024)),
  776. ('store', ('1', 'FLAGS', '(\Deleted)')),
  777. ('expunge', ()),
  778. ('recent', ()),
  779. ('close', ()),
  780. )
  781. test_seq2 = (
  782. ('select', ()),
  783. ('response',('UIDVALIDITY',)),
  784. ('uid', ('SEARCH', 'ALL')),
  785. ('response', ('EXISTS',)),
  786. ('append', (None, None, None, test_mesg)),
  787. ('recent', ()),
  788. ('logout', ()),
  789. )
  790. def run(cmd, args):
  791. _mesg('%s %s' % (cmd, args))
  792. typ, dat = apply(eval('M.%s' % cmd), args)
  793. _mesg('%s => %s %s' % (cmd, typ, dat))
  794. return dat
  795. try:
  796. M = IMAP4(host)
  797. _mesg('PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  798. for cmd,args in test_seq1:
  799. run(cmd, args)
  800. for ml in run('list', ('/tmp/', 'yy%')):
  801. mo = re.match(r'.*"([^"]+)"$', ml)
  802. if mo: path = mo.group(1)
  803. else: path = ml.split()[-1]
  804. run('delete', (path,))
  805. for cmd,args in test_seq2:
  806. dat = run(cmd, args)
  807. if (cmd,args) != ('uid', ('SEARCH', 'ALL')):
  808. continue
  809. uid = dat[-1].split()
  810. if not uid: continue
  811. run('uid', ('FETCH', '%s' % uid[-1],
  812. '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  813. print '\nAll tests OK.'
  814. except:
  815. print '\nTests failed.'
  816. if not Debug:
  817. print '''
  818. If you would like to see debugging output,
  819. try: %s -d5
  820. ''' % sys.argv[0]
  821. raise