bundled_imaplib2.py 94 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701
  1. #!/usr/bin/env python
  2. """Threaded IMAP4 client.
  3. Based on RFC 3501 and original imaplib module.
  4. Public classes: IMAP4
  5. IMAP4_SSL
  6. IMAP4_stream
  7. Public functions: Internaldate2Time
  8. ParseFlags
  9. Time2Internaldate
  10. """
  11. __all__ = ("IMAP4", "IMAP4_SSL", "IMAP4_stream",
  12. "Internaldate2Time", "ParseFlags", "Time2Internaldate",
  13. "Mon2num", "MonthNames", "InternalDate")
  14. __version__ = "2.57"
  15. __release__ = "2"
  16. __revision__ = "57"
  17. __credits__ = """
  18. Authentication code contributed by Donn Cave <donn@u.washington.edu> June 1998.
  19. String method conversion by ESR, February 2001.
  20. GET/SETACL contributed by Anthony Baxter <anthony@interlink.com.au> April 2001.
  21. IMAP4_SSL contributed by Tino Lange <Tino.Lange@isg.de> March 2002.
  22. GET/SETQUOTA contributed by Andreas Zeidler <az@kreativkombinat.de> June 2002.
  23. PROXYAUTH contributed by Rick Holbert <holbert.13@osu.edu> November 2002.
  24. IDLE via threads suggested by Philippe Normand <phil@respyre.org> January 2005.
  25. GET/SETANNOTATION contributed by Tomas Lindroos <skitta@abo.fi> June 2005.
  26. COMPRESS/DEFLATE contributed by Bron Gondwana <brong@brong.net> May 2009.
  27. STARTTLS from Jython's imaplib by Alan Kennedy.
  28. ID contributed by Dave Baggett <dave@baggett.org> November 2009.
  29. Improved untagged responses handling suggested by Dave Baggett <dave@baggett.org> November 2009.
  30. Improved thread naming, and 0 read detection contributed by Grant Edwards <grant.b.edwards@gmail.com> June 2010.
  31. Improved timeout handling contributed by Ivan Vovnenko <ivovnenko@gmail.com> October 2010.
  32. Timeout handling further improved by Ethan Glasser-Camp <glasse@cs.rpi.edu> December 2010.
  33. Time2Internaldate() patch to match RFC2060 specification of English month names from bugs.python.org/issue11024 March 2011.
  34. starttls() bug fixed with the help of Sebastian Spaeth <sebastian@sspaeth.de> April 2011.
  35. Threads now set the "daemon" flag (suggested by offlineimap-project) April 2011.
  36. Single quoting introduced with the help of Vladimir Marek <vladimir.marek@oracle.com> August 2011.
  37. Support for specifying SSL version by Ryan Kavanagh <rak@debian.org> July 2013.
  38. Fix for gmail "read 0" error provided by Jim Greenleaf <james.a.greenleaf@gmail.com> August 2013.
  39. Fix for offlineimap "indexerror: string index out of range" bug provided by Eygene Ryabinkin <rea@codelabs.ru> August 2013.
  40. Fix for missing idle_lock in _handler() provided by Franklin Brook <franklin@brook.se> August 2014.
  41. Conversion to Python3 provided by F. Malina <fmalina@gmail.com> February 2015.
  42. Fix for READ-ONLY error from multiple EXAMINE/SELECT calls by Pierre-Louis Bonicoli <pierre-louis.bonicoli@gmx.fr> March 2015.
  43. Fix for null strings appended to untagged responses by Pierre-Louis Bonicoli <pierre-louis.bonicoli@gmx.fr> March 2015.
  44. Fix for correct byte encoding for _CRAM_MD5_AUTH taken from python3.5 imaplib.py June 2015.
  45. Fix for correct Python 3 exception handling by Tobias Brink <tobias.brink@gmail.com> August 2015.
  46. Fix to allow interruptible IDLE command by Tim Peoples <dromedary512@users.sf.net> September 2015.
  47. Add support for TLS levels by Ben Boeckel <mathstuf@gmail.com> September 2015.
  48. Fix for shutown exception by Sebastien Gross <seb@chezwam.org> November 2015."""
  49. __author__ = "Piers Lauder <piers@janeelix.com>"
  50. __URL__ = "http://imaplib2.sourceforge.net"
  51. __license__ = "Python License"
  52. import binascii, errno, os, random, re, select, socket, sys, time, threading, zlib
  53. if bytes != str:
  54. # Python 3, but NB assumes strings in all I/O
  55. # for backwards compatibility with python 2 usage.
  56. import queue
  57. string_types = str
  58. else:
  59. import Queue as queue
  60. string_types = basestring
  61. threading.TIMEOUT_MAX = 9223372036854.0
  62. select_module = select
  63. # Globals
  64. CRLF = '\r\n'
  65. Debug = None # Backward compatibility
  66. IMAP4_PORT = 143
  67. IMAP4_SSL_PORT = 993
  68. IDLE_TIMEOUT_RESPONSE = '* IDLE TIMEOUT\r\n'
  69. IDLE_TIMEOUT = 60*29 # Don't stay in IDLE state longer
  70. READ_POLL_TIMEOUT = 30 # Without this timeout interrupted network connections can hang reader
  71. READ_SIZE = 32768 # Consume all available in socket
  72. DFLT_DEBUG_BUF_LVL = 3 # Level above which the logging output goes directly to stderr
  73. TLS_SECURE = "tls_secure" # Recognised TLS levels
  74. TLS_NO_SSL = "tls_no_ssl"
  75. TLS_COMPAT = "tls_compat"
  76. AllowedVersions = ('IMAP4REV1', 'IMAP4') # Most recent first
  77. # Commands
  78. CMD_VAL_STATES = 0
  79. CMD_VAL_ASYNC = 1
  80. NONAUTH, AUTH, SELECTED, LOGOUT = 'NONAUTH', 'AUTH', 'SELECTED', 'LOGOUT'
  81. Commands = {
  82. # name valid states asynchronous
  83. 'APPEND': ((AUTH, SELECTED), False),
  84. 'AUTHENTICATE': ((NONAUTH,), False),
  85. 'CAPABILITY': ((NONAUTH, AUTH, SELECTED), True),
  86. 'CHECK': ((SELECTED,), True),
  87. 'CLOSE': ((SELECTED,), False),
  88. 'COMPRESS': ((AUTH,), False),
  89. 'COPY': ((SELECTED,), True),
  90. 'CREATE': ((AUTH, SELECTED), True),
  91. 'DELETE': ((AUTH, SELECTED), True),
  92. 'DELETEACL': ((AUTH, SELECTED), True),
  93. 'ENABLE': ((AUTH,), False),
  94. 'EXAMINE': ((AUTH, SELECTED), False),
  95. 'EXPUNGE': ((SELECTED,), True),
  96. 'FETCH': ((SELECTED,), True),
  97. 'GETACL': ((AUTH, SELECTED), True),
  98. 'GETANNOTATION':((AUTH, SELECTED), True),
  99. 'GETQUOTA': ((AUTH, SELECTED), True),
  100. 'GETQUOTAROOT': ((AUTH, SELECTED), True),
  101. 'ID': ((NONAUTH, AUTH, LOGOUT, SELECTED), True),
  102. 'IDLE': ((SELECTED,), False),
  103. 'LIST': ((AUTH, SELECTED), True),
  104. 'LOGIN': ((NONAUTH,), False),
  105. 'LOGOUT': ((NONAUTH, AUTH, LOGOUT, SELECTED), False),
  106. 'LSUB': ((AUTH, SELECTED), True),
  107. 'MYRIGHTS': ((AUTH, SELECTED), True),
  108. 'NAMESPACE': ((AUTH, SELECTED), True),
  109. 'NOOP': ((NONAUTH, AUTH, SELECTED), True),
  110. 'PARTIAL': ((SELECTED,), True),
  111. 'PROXYAUTH': ((AUTH,), False),
  112. 'RENAME': ((AUTH, SELECTED), True),
  113. 'SEARCH': ((SELECTED,), True),
  114. 'SELECT': ((AUTH, SELECTED), False),
  115. 'SETACL': ((AUTH, SELECTED), False),
  116. 'SETANNOTATION':((AUTH, SELECTED), True),
  117. 'SETQUOTA': ((AUTH, SELECTED), False),
  118. 'SORT': ((SELECTED,), True),
  119. 'STARTTLS': ((NONAUTH,), False),
  120. 'STATUS': ((AUTH, SELECTED), True),
  121. 'STORE': ((SELECTED,), True),
  122. 'SUBSCRIBE': ((AUTH, SELECTED), False),
  123. 'THREAD': ((SELECTED,), True),
  124. 'UID': ((SELECTED,), True),
  125. 'UNSUBSCRIBE': ((AUTH, SELECTED), False),
  126. }
  127. UID_direct = ('SEARCH', 'SORT', 'THREAD')
  128. def Int2AP(num):
  129. """string = Int2AP(num)
  130. Return 'num' converted to a string using characters from the set 'A'..'P'
  131. """
  132. val, a2p = [], 'ABCDEFGHIJKLMNOP'
  133. num = int(abs(num))
  134. while num:
  135. num, mod = divmod(num, 16)
  136. val.insert(0, a2p[mod])
  137. return ''.join(val)
  138. class Request(object):
  139. """Private class to represent a request awaiting response."""
  140. def __init__(self, parent, name=None, callback=None, cb_arg=None, cb_self=False):
  141. self.parent = parent
  142. self.name = name
  143. self.callback = callback # Function called to process result
  144. if not cb_self:
  145. self.callback_arg = cb_arg # Optional arg passed to "callback"
  146. else:
  147. self.callback_arg = (self, cb_arg) # Self reference required in callback arg
  148. self.tag = '%s%s' % (parent.tagpre, parent.tagnum)
  149. parent.tagnum += 1
  150. self.ready = threading.Event()
  151. self.response = None
  152. self.aborted = None
  153. self.data = None
  154. def abort(self, typ, val):
  155. self.aborted = (typ, val)
  156. self.deliver(None)
  157. def get_response(self, exc_fmt=None):
  158. self.callback = None
  159. if __debug__: self.parent._log(3, '%s:%s.ready.wait' % (self.name, self.tag))
  160. self.ready.wait(threading.TIMEOUT_MAX)
  161. if self.aborted is not None:
  162. typ, val = self.aborted
  163. if exc_fmt is None:
  164. exc_fmt = '%s - %%s' % typ
  165. raise typ(exc_fmt % str(val))
  166. return self.response
  167. def deliver(self, response):
  168. if self.callback is not None:
  169. self.callback((response, self.callback_arg, self.aborted))
  170. return
  171. self.response = response
  172. self.ready.set()
  173. if __debug__: self.parent._log(3, '%s:%s.ready.set' % (self.name, self.tag))
  174. class IMAP4(object):
  175. """Threaded IMAP4 client class.
  176. Instantiate with:
  177. IMAP4(host=None, port=None, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None)
  178. host - host's name (default: localhost);
  179. port - port number (default: standard IMAP4 port);
  180. debug - debug level (default: 0 - no debug);
  181. debug_file - debug stream (default: sys.stderr);
  182. identifier - thread identifier prefix (default: host);
  183. timeout - timeout in seconds when expecting a command response (default: no timeout),
  184. debug_buf_lvl - debug level at which buffering is turned off.
  185. All IMAP4rev1 commands are supported by methods of the same name.
  186. Each command returns a tuple: (type, [data, ...]) where 'type'
  187. is usually 'OK' or 'NO', and 'data' is either the text from the
  188. tagged response, or untagged results from command. Each 'data' is
  189. either a string, or a tuple. If a tuple, then the first part is the
  190. header of the response, and the second part contains the data (ie:
  191. 'literal' value).
  192. Errors raise the exception class <instance>.error("<reason>").
  193. IMAP4 server errors raise <instance>.abort("<reason>"), which is
  194. a sub-class of 'error'. Mailbox status changes from READ-WRITE to
  195. READ-ONLY raise the exception class <instance>.readonly("<reason>"),
  196. which is a sub-class of 'abort'.
  197. "error" exceptions imply a program error.
  198. "abort" exceptions imply the connection should be reset, and
  199. the command re-tried.
  200. "readonly" exceptions imply the command should be re-tried.
  201. All commands take two optional named arguments:
  202. 'callback' and 'cb_arg'
  203. If 'callback' is provided then the command is asynchronous, so after
  204. the command is queued for transmission, the call returns immediately
  205. with the tuple (None, None).
  206. The result will be posted by invoking "callback" with one arg, a tuple:
  207. callback((result, cb_arg, None))
  208. or, if there was a problem:
  209. callback((None, cb_arg, (exception class, reason)))
  210. Otherwise the command is synchronous (waits for result). But note
  211. that state-changing commands will both block until previous commands
  212. have completed, and block subsequent commands until they have finished.
  213. All (non-callback) arguments to commands are converted to strings,
  214. except for AUTHENTICATE, and the last argument to APPEND which is
  215. passed as an IMAP4 literal. If necessary (the string contains any
  216. non-printing characters or white-space and isn't enclosed with
  217. either parentheses or double or single quotes) each string is
  218. quoted. However, the 'password' argument to the LOGIN command is
  219. always quoted. If you want to avoid having an argument string
  220. quoted (eg: the 'flags' argument to STORE) then enclose the string
  221. in parentheses (eg: "(\Deleted)"). If you are using "sequence sets"
  222. containing the wildcard character '*', then enclose the argument
  223. in single quotes: the quotes will be removed and the resulting
  224. string passed unquoted. Note also that you can pass in an argument
  225. with a type that doesn't evaluate to 'string_types' (eg: 'bytearray')
  226. and it will be converted to a string without quoting.
  227. There is one instance variable, 'state', that is useful for tracking
  228. whether the client needs to login to the server. If it has the
  229. value "AUTH" after instantiating the class, then the connection
  230. is pre-authenticated (otherwise it will be "NONAUTH"). Selecting a
  231. mailbox changes the state to be "SELECTED", closing a mailbox changes
  232. back to "AUTH", and once the client has logged out, the state changes
  233. to "LOGOUT" and no further commands may be issued.
  234. Note: to use this module, you must read the RFCs pertaining to the
  235. IMAP4 protocol, as the semantics of the arguments to each IMAP4
  236. command are left to the invoker, not to mention the results. Also,
  237. most IMAP servers implement a sub-set of the commands available here.
  238. Note also that you must call logout() to shut down threads before
  239. discarding an instance.
  240. """
  241. class error(Exception): pass # Logical errors - debug required
  242. class abort(error): pass # Service errors - close and retry
  243. class readonly(abort): pass # Mailbox status changed to READ-ONLY
  244. # These must be encoded according to utf8 setting in _mode_xxx():
  245. _literal = br'.*{(?P<size>\d+)}$'
  246. _untagged_status = br'\* (?P<data>\d+) (?P<type>[A-Z-]+)( (?P<data2>.*))?'
  247. continuation_cre = re.compile(r'\+( (?P<data>.*))?')
  248. mapCRLF_cre = re.compile(r'\r\n|\r|\n')
  249. # Need to quote "atom-specials" :-
  250. # "(" / ")" / "{" / SP / 0x00 - 0x1f / 0x7f / "%" / "*" / DQUOTE / "\" / "]"
  251. # so match not the inverse set
  252. mustquote_cre = re.compile(r"[^!#$&'+,./0-9:;<=>?@A-Z\[^_`a-z|}~-]")
  253. response_code_cre = re.compile(r'\[(?P<type>[A-Z-]+)( (?P<data>[^\]]*))?\]')
  254. untagged_response_cre = re.compile(r'\* (?P<type>[A-Z-]+)( (?P<data>.*))?')
  255. def __init__(self, host=None, port=None, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None):
  256. self.state = NONAUTH # IMAP4 protocol state
  257. self.literal = None # A literal argument to a command
  258. self.tagged_commands = {} # Tagged commands awaiting response
  259. self.untagged_responses = [] # [[typ: [data, ...]], ...]
  260. self.mailbox = None # Current mailbox selected
  261. self.is_readonly = False # READ-ONLY desired state
  262. self.idle_rqb = None # Server IDLE Request - see _IdleCont
  263. self.idle_timeout = None # Must prod server occasionally
  264. self._expecting_data = False # Expecting message data
  265. self._expecting_data_len = 0 # How many characters we expect
  266. self._accumulated_data = [] # Message data accumulated so far
  267. self._literal_expected = None # Message data descriptor
  268. self.compressor = None # COMPRESS/DEFLATE if not None
  269. self.decompressor = None
  270. self._tls_established = False
  271. # Create unique tag for this session,
  272. # and compile tagged response matcher.
  273. self.tagnum = 0
  274. self.tagpre = Int2AP(random.randint(4096, 65535))
  275. self.tagre = re.compile(r'(?P<tag>'
  276. + self.tagpre
  277. + r'\d+) (?P<type>[A-Z]+) (?P<data>.*)')
  278. self._mode_ascii() # Only option in py2
  279. if __debug__: self._init_debug(debug, debug_file, debug_buf_lvl)
  280. self.resp_timeout = timeout # Timeout waiting for command response
  281. if timeout is not None and timeout < READ_POLL_TIMEOUT:
  282. self.read_poll_timeout = timeout
  283. else:
  284. self.read_poll_timeout = READ_POLL_TIMEOUT
  285. self.read_size = READ_SIZE
  286. # Open socket to server.
  287. self.open(host, port)
  288. if __debug__:
  289. if debug:
  290. self._mesg('connected to %s on port %s' % (self.host, self.port))
  291. # Threading
  292. if identifier is not None:
  293. self.identifier = identifier
  294. else:
  295. self.identifier = self.host
  296. if self.identifier:
  297. self.identifier += ' '
  298. self.Terminate = self.TerminateReader = False
  299. self.state_change_free = threading.Event()
  300. self.state_change_pending = threading.Lock()
  301. self.commands_lock = threading.Lock()
  302. self.idle_lock = threading.Lock()
  303. self.ouq = queue.Queue(10)
  304. self.inq = queue.Queue()
  305. self.wrth = threading.Thread(target=self._writer)
  306. self.wrth.setDaemon(True)
  307. self.wrth.start()
  308. self.rdth = threading.Thread(target=self._reader)
  309. self.rdth.setDaemon(True)
  310. self.rdth.start()
  311. self.inth = threading.Thread(target=self._handler)
  312. self.inth.setDaemon(True)
  313. self.inth.start()
  314. # Get server welcome message,
  315. # request and store CAPABILITY response.
  316. try:
  317. self.welcome = self._request_push(name='welcome', tag='continuation').get_response('IMAP4 protocol error: %s')[1]
  318. if self._get_untagged_response('PREAUTH'):
  319. self.state = AUTH
  320. if __debug__: self._log(1, 'state => AUTH')
  321. elif self._get_untagged_response('OK'):
  322. if __debug__: self._log(1, 'state => NONAUTH')
  323. else:
  324. raise self.error('unrecognised server welcome message: %s' % repr(self.welcome))
  325. typ, dat = self.capability()
  326. if dat == [None]:
  327. raise self.error('no CAPABILITY response from server')
  328. self.capabilities = tuple(dat[-1].upper().split())
  329. if __debug__: self._log(1, 'CAPABILITY: %r' % (self.capabilities,))
  330. for version in AllowedVersions:
  331. if not version in self.capabilities:
  332. continue
  333. self.PROTOCOL_VERSION = version
  334. break
  335. else:
  336. raise self.error('server not IMAP4 compliant')
  337. except:
  338. self._close_threads()
  339. raise
  340. def __getattr__(self, attr):
  341. # Allow UPPERCASE variants of IMAP4 command methods.
  342. if attr in Commands:
  343. return getattr(self, attr.lower())
  344. raise AttributeError("Unknown IMAP4 command: '%s'" % attr)
  345. def _mode_ascii(self):
  346. self.utf8_enabled = False
  347. self._encoding = 'ascii'
  348. if bytes != str:
  349. self.literal_cre = re.compile(self._literal, re.ASCII)
  350. self.untagged_status_cre = re.compile(self._untagged_status, re.ASCII)
  351. else:
  352. self.literal_cre = re.compile(self._literal)
  353. self.untagged_status_cre = re.compile(self._untagged_status)
  354. def _mode_utf8(self):
  355. self.utf8_enabled = True
  356. self._encoding = 'utf-8'
  357. if bytes != str:
  358. self.literal_cre = re.compile(self._literal)
  359. self.untagged_status_cre = re.compile(self._untagged_status)
  360. else:
  361. self.literal_cre = re.compile(self._literal, re.UNICODE)
  362. self.untagged_status_cre = re.compile(self._untagged_status, re.UNICODE)
  363. # Overridable methods
  364. def open(self, host=None, port=None):
  365. """open(host=None, port=None)
  366. Setup connection to remote server on "host:port"
  367. (default: localhost:standard IMAP4 port).
  368. This connection will be used by the routines:
  369. read, send, shutdown, socket."""
  370. self.host = self._choose_nonull_or_dflt('', host)
  371. self.port = self._choose_nonull_or_dflt(IMAP4_PORT, port)
  372. self.sock = self.open_socket()
  373. self.read_fd = self.sock.fileno()
  374. def open_socket(self):
  375. """open_socket()
  376. Open socket choosing first address family available."""
  377. msg = (-1, 'could not open socket')
  378. for res in socket.getaddrinfo(self.host, self.port, socket.AF_UNSPEC, socket.SOCK_STREAM):
  379. af, socktype, proto, canonname, sa = res
  380. try:
  381. s = socket.socket(af, socktype, proto)
  382. except socket.error as m:
  383. msg = m
  384. continue
  385. try:
  386. for i in (0, 1):
  387. try:
  388. s.connect(sa)
  389. break
  390. except socket.error as m:
  391. msg = m
  392. if len(msg.args) < 2 or msg.args[0] != errno.EINTR:
  393. raise
  394. else:
  395. raise socket.error(msg)
  396. except socket.error as m:
  397. msg = m
  398. s.close()
  399. continue
  400. break
  401. else:
  402. raise socket.error(msg)
  403. return s
  404. def ssl_wrap_socket(self):
  405. try:
  406. import ssl
  407. TLS_MAP = {}
  408. if hasattr(ssl, "PROTOCOL_TLSv1_2"):
  409. TLS_MAP[TLS_SECURE] = {
  410. "tls1_2": ssl.PROTOCOL_TLSv1_2,
  411. "tls1_1": ssl.PROTOCOL_TLSv1_1,
  412. }
  413. else:
  414. TLS_MAP[TLS_SECURE] = {}
  415. TLS_MAP[TLS_NO_SSL] = TLS_MAP[TLS_SECURE].copy()
  416. TLS_MAP[TLS_NO_SSL].update({
  417. "tls1": ssl.PROTOCOL_TLSv1,
  418. })
  419. TLS_MAP[TLS_COMPAT] = TLS_MAP[TLS_NO_SSL].copy()
  420. TLS_MAP[TLS_COMPAT].update({
  421. "ssl23": ssl.PROTOCOL_SSLv23,
  422. None: ssl.PROTOCOL_SSLv23,
  423. })
  424. if hasattr(ssl, "PROTOCOL_SSLv3"): # Might not be available.
  425. TLS_MAP[TLS_COMPAT].update({
  426. "ssl3": ssl.PROTOCOL_SSLv3
  427. })
  428. if self.ca_certs is not None:
  429. cert_reqs = ssl.CERT_REQUIRED
  430. else:
  431. cert_reqs = ssl.CERT_NONE
  432. if self.tls_level not in TLS_MAP:
  433. raise RuntimeError("unknown tls_level: %s" % self.tls_level)
  434. if self.ssl_version not in TLS_MAP[self.tls_level]:
  435. raise socket.sslerror("Invalid SSL version '%s' requested for tls_version '%s'" % (self.ssl_version, self.tls_level))
  436. ssl_version = TLS_MAP[self.tls_level][self.ssl_version]
  437. self.sock = ssl.wrap_socket(self.sock, self.keyfile, self.certfile, ca_certs=self.ca_certs, cert_reqs=cert_reqs, ssl_version=ssl_version)
  438. ssl_exc = ssl.SSLError
  439. self.read_fd = self.sock.fileno()
  440. except ImportError:
  441. # No ssl module, and socket.ssl has no fileno(), and does not allow certificate verification
  442. raise socket.sslerror("imaplib SSL mode does not work without ssl module")
  443. if self.cert_verify_cb is not None:
  444. cert_err = self.cert_verify_cb(self.sock.getpeercert(), self.host)
  445. if cert_err:
  446. raise ssl_exc(cert_err)
  447. # Allow sending of keep-alive messages - seems to prevent some servers
  448. # from closing SSL, leading to deadlocks.
  449. self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
  450. def start_compressing(self):
  451. """start_compressing()
  452. Enable deflate compression on the socket (RFC 4978)."""
  453. # rfc 1951 - pure DEFLATE, so use -15 for both windows
  454. self.decompressor = zlib.decompressobj(-15)
  455. self.compressor = zlib.compressobj(zlib.Z_DEFAULT_COMPRESSION, zlib.DEFLATED, -15)
  456. def read(self, size):
  457. """data = read(size)
  458. Read at most 'size' bytes from remote."""
  459. if self.decompressor is None:
  460. return self.sock.recv(size)
  461. if self.decompressor.unconsumed_tail:
  462. data = self.decompressor.unconsumed_tail
  463. else:
  464. data = self.sock.recv(READ_SIZE)
  465. return self.decompressor.decompress(data, size)
  466. def send(self, data):
  467. """send(data)
  468. Send 'data' to remote."""
  469. if self.compressor is not None:
  470. data = self.compressor.compress(data)
  471. data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
  472. if bytes != str:
  473. data = bytes(data, 'ASCII')
  474. self.sock.sendall(data)
  475. def shutdown(self):
  476. """shutdown()
  477. Close I/O established in "open"."""
  478. try:
  479. self.sock.shutdown(socket.SHUT_RDWR)
  480. except Exception as e:
  481. # The server might already have closed the connection
  482. if e.errno != errno.ENOTCONN:
  483. raise
  484. finally:
  485. self.sock.close()
  486. def socket(self):
  487. """socket = socket()
  488. Return socket instance used to connect to IMAP4 server."""
  489. return self.sock
  490. # Utility methods
  491. def enable_compression(self):
  492. """enable_compression()
  493. Ask the server to start compressing the connection.
  494. Should be called from user of this class after instantiation, as in:
  495. if 'COMPRESS=DEFLATE' in imapobj.capabilities:
  496. imapobj.enable_compression()"""
  497. try:
  498. typ, dat = self._simple_command('COMPRESS', 'DEFLATE')
  499. if typ == 'OK':
  500. self.start_compressing()
  501. if __debug__: self._log(1, 'Enabled COMPRESS=DEFLATE')
  502. finally:
  503. self._release_state_change()
  504. def pop_untagged_responses(self):
  505. """ for typ,data in pop_untagged_responses(): pass
  506. Generator for any remaining untagged responses.
  507. Returns and removes untagged responses in order of reception.
  508. Use at your own risk!"""
  509. while self.untagged_responses:
  510. self.commands_lock.acquire()
  511. try:
  512. yield self.untagged_responses.pop(0)
  513. finally:
  514. self.commands_lock.release()
  515. def recent(self, **kw):
  516. """(typ, [data]) = recent()
  517. Return 'RECENT' responses if any exist,
  518. else prompt server for an update using the 'NOOP' command.
  519. 'data' is None if no new messages,
  520. else list of RECENT responses, most recent last."""
  521. name = 'RECENT'
  522. typ, dat = self._untagged_response(None, [None], name)
  523. if dat != [None]:
  524. return self._deliver_dat(typ, dat, kw)
  525. kw['untagged_response'] = name
  526. return self.noop(**kw) # Prod server for response
  527. def response(self, code, **kw):
  528. """(code, [data]) = response(code)
  529. Return data for response 'code' if received, or None.
  530. Old value for response 'code' is cleared."""
  531. typ, dat = self._untagged_response(code, [None], code.upper())
  532. return self._deliver_dat(typ, dat, kw)
  533. # IMAP4 commands
  534. def append(self, mailbox, flags, date_time, message, **kw):
  535. """(typ, [data]) = append(mailbox, flags, date_time, message)
  536. Append message to named mailbox.
  537. All args except `message' can be None."""
  538. name = 'APPEND'
  539. if not mailbox:
  540. mailbox = 'INBOX'
  541. if flags:
  542. if (flags[0],flags[-1]) != ('(',')'):
  543. flags = '(%s)' % flags
  544. else:
  545. flags = None
  546. if date_time:
  547. date_time = Time2Internaldate(date_time)
  548. else:
  549. date_time = None
  550. literal = self.mapCRLF_cre.sub(CRLF, message)
  551. if self.utf8_enabled:
  552. literal = b'UTF8 (' + literal + b')'
  553. self.literal = literal
  554. try:
  555. return self._simple_command(name, mailbox, flags, date_time, **kw)
  556. finally:
  557. self._release_state_change()
  558. def authenticate(self, mechanism, authobject, **kw):
  559. """(typ, [data]) = authenticate(mechanism, authobject)
  560. Authenticate command - requires response processing.
  561. 'mechanism' specifies which authentication mechanism is to
  562. be used - it must appear in <instance>.capabilities in the
  563. form AUTH=<mechanism>.
  564. 'authobject' must be a callable object:
  565. data = authobject(response)
  566. It will be called to process server continuation responses.
  567. It should return data that will be encoded and sent to server.
  568. It should return None if the client abort response '*' should
  569. be sent instead."""
  570. self.literal = _Authenticator(authobject).process
  571. try:
  572. typ, dat = self._simple_command('AUTHENTICATE', mechanism.upper())
  573. if typ != 'OK':
  574. self._deliver_exc(self.error, dat[-1], kw)
  575. self.state = AUTH
  576. if __debug__: self._log(1, 'state => AUTH')
  577. finally:
  578. self._release_state_change()
  579. return self._deliver_dat(typ, dat, kw)
  580. def capability(self, **kw):
  581. """(typ, [data]) = capability()
  582. Fetch capabilities list from server."""
  583. name = 'CAPABILITY'
  584. kw['untagged_response'] = name
  585. return self._simple_command(name, **kw)
  586. def check(self, **kw):
  587. """(typ, [data]) = check()
  588. Checkpoint mailbox on server."""
  589. return self._simple_command('CHECK', **kw)
  590. def close(self, **kw):
  591. """(typ, [data]) = close()
  592. Close currently selected mailbox.
  593. Deleted messages are removed from writable mailbox.
  594. This is the recommended command before 'LOGOUT'."""
  595. if self.state != 'SELECTED':
  596. raise self.error('No mailbox selected.')
  597. try:
  598. typ, dat = self._simple_command('CLOSE')
  599. finally:
  600. self.state = AUTH
  601. if __debug__: self._log(1, 'state => AUTH')
  602. self._release_state_change()
  603. return self._deliver_dat(typ, dat, kw)
  604. def copy(self, message_set, new_mailbox, **kw):
  605. """(typ, [data]) = copy(message_set, new_mailbox)
  606. Copy 'message_set' messages onto end of 'new_mailbox'."""
  607. return self._simple_command('COPY', message_set, new_mailbox, **kw)
  608. def create(self, mailbox, **kw):
  609. """(typ, [data]) = create(mailbox)
  610. Create new mailbox."""
  611. return self._simple_command('CREATE', mailbox, **kw)
  612. def delete(self, mailbox, **kw):
  613. """(typ, [data]) = delete(mailbox)
  614. Delete old mailbox."""
  615. return self._simple_command('DELETE', mailbox, **kw)
  616. def deleteacl(self, mailbox, who, **kw):
  617. """(typ, [data]) = deleteacl(mailbox, who)
  618. Delete the ACLs (remove any rights) set for who on mailbox."""
  619. return self._simple_command('DELETEACL', mailbox, who, **kw)
  620. def enable(self, capability):
  621. """Send an RFC5161 enable string to the server.
  622. (typ, [data]) = <intance>.enable(capability)
  623. """
  624. if 'ENABLE' not in self.capabilities:
  625. raise self.error("Server does not support ENABLE")
  626. typ, data = self._simple_command('ENABLE', capability)
  627. if typ == 'OK' and 'UTF8=ACCEPT' in capability.upper():
  628. self._mode_utf8()
  629. return typ, data
  630. def examine(self, mailbox='INBOX', **kw):
  631. """(typ, [data]) = examine(mailbox='INBOX')
  632. Select a mailbox for READ-ONLY access. (Flushes all untagged responses.)
  633. 'data' is count of messages in mailbox ('EXISTS' response).
  634. Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
  635. other responses should be obtained via "response('FLAGS')" etc."""
  636. return self.select(mailbox=mailbox, readonly=True, **kw)
  637. def expunge(self, **kw):
  638. """(typ, [data]) = expunge()
  639. Permanently remove deleted items from selected mailbox.
  640. Generates 'EXPUNGE' response for each deleted message.
  641. 'data' is list of 'EXPUNGE'd message numbers in order received."""
  642. name = 'EXPUNGE'
  643. kw['untagged_response'] = name
  644. return self._simple_command(name, **kw)
  645. def fetch(self, message_set, message_parts, **kw):
  646. """(typ, [data, ...]) = fetch(message_set, message_parts)
  647. Fetch (parts of) messages.
  648. 'message_parts' should be a string of selected parts
  649. enclosed in parentheses, eg: "(UID BODY[TEXT])".
  650. 'data' are tuples of message part envelope and data,
  651. followed by a string containing the trailer."""
  652. name = 'FETCH'
  653. kw['untagged_response'] = name
  654. return self._simple_command(name, message_set, message_parts, **kw)
  655. def getacl(self, mailbox, **kw):
  656. """(typ, [data]) = getacl(mailbox)
  657. Get the ACLs for a mailbox."""
  658. kw['untagged_response'] = 'ACL'
  659. return self._simple_command('GETACL', mailbox, **kw)
  660. def getannotation(self, mailbox, entry, attribute, **kw):
  661. """(typ, [data]) = getannotation(mailbox, entry, attribute)
  662. Retrieve ANNOTATIONs."""
  663. kw['untagged_response'] = 'ANNOTATION'
  664. return self._simple_command('GETANNOTATION', mailbox, entry, attribute, **kw)
  665. def getquota(self, root, **kw):
  666. """(typ, [data]) = getquota(root)
  667. Get the quota root's resource usage and limits.
  668. (Part of the IMAP4 QUOTA extension defined in rfc2087.)"""
  669. kw['untagged_response'] = 'QUOTA'
  670. return self._simple_command('GETQUOTA', root, **kw)
  671. def getquotaroot(self, mailbox, **kw):
  672. # Hmmm, this is non-std! Left for backwards-compatibility, sigh.
  673. # NB: usage should have been defined as:
  674. # (typ, [QUOTAROOT responses...]) = getquotaroot(mailbox)
  675. # (typ, [QUOTA responses...]) = response('QUOTA')
  676. """(typ, [[QUOTAROOT responses...], [QUOTA responses...]]) = getquotaroot(mailbox)
  677. Get the list of quota roots for the named mailbox."""
  678. typ, dat = self._simple_command('GETQUOTAROOT', mailbox)
  679. typ, quota = self._untagged_response(typ, dat, 'QUOTA')
  680. typ, quotaroot = self._untagged_response(typ, dat, 'QUOTAROOT')
  681. return self._deliver_dat(typ, [quotaroot, quota], kw)
  682. def id(self, *kv_pairs, **kw):
  683. """(typ, [data]) = <instance>.id(kv_pairs)
  684. 'kv_pairs' is a possibly empty list of keys and values.
  685. 'data' is a list of ID key value pairs or NIL.
  686. NB: a single argument is assumed to be correctly formatted and is passed through unchanged
  687. (for backward compatibility with earlier version).
  688. Exchange information for problem analysis and determination.
  689. The ID extension is defined in RFC 2971. """
  690. name = 'ID'
  691. kw['untagged_response'] = name
  692. if not kv_pairs:
  693. data = 'NIL'
  694. elif len(kv_pairs) == 1:
  695. data = kv_pairs[0] # Assume invoker passing correctly formatted string (back-compat)
  696. else:
  697. data = '(%s)' % ' '.join([(arg and self._quote(arg) or 'NIL') for arg in kv_pairs])
  698. return self._simple_command(name, data, **kw)
  699. def idle(self, timeout=None, **kw):
  700. """"(typ, [data]) = idle(timeout=None)
  701. Put server into IDLE mode until server notifies some change,
  702. or 'timeout' (secs) occurs (default: 29 minutes),
  703. or another IMAP4 command is scheduled."""
  704. name = 'IDLE'
  705. self.literal = _IdleCont(self, timeout).process
  706. try:
  707. return self._simple_command(name, **kw)
  708. finally:
  709. self._release_state_change()
  710. def list(self, directory='""', pattern='*', **kw):
  711. """(typ, [data]) = list(directory='""', pattern='*')
  712. List mailbox names in directory matching pattern.
  713. 'data' is list of LIST responses.
  714. NB: for 'pattern':
  715. % matches all except separator ( so LIST "" "%" returns names at root)
  716. * matches all (so LIST "" "*" returns whole directory tree from root)"""
  717. name = 'LIST'
  718. kw['untagged_response'] = name
  719. return self._simple_command(name, directory, pattern, **kw)
  720. def login(self, user, password, **kw):
  721. """(typ, [data]) = login(user, password)
  722. Identify client using plaintext password.
  723. NB: 'password' will be quoted."""
  724. try:
  725. typ, dat = self._simple_command('LOGIN', user, self._quote(password))
  726. if typ != 'OK':
  727. self._deliver_exc(self.error, dat[-1], kw)
  728. self.state = AUTH
  729. if __debug__: self._log(1, 'state => AUTH')
  730. finally:
  731. self._release_state_change()
  732. return self._deliver_dat(typ, dat, kw)
  733. def login_cram_md5(self, user, password, **kw):
  734. """(typ, [data]) = login_cram_md5(user, password)
  735. Force use of CRAM-MD5 authentication."""
  736. self.user, self.password = user, password
  737. return self.authenticate('CRAM-MD5', self._CRAM_MD5_AUTH, **kw)
  738. def _CRAM_MD5_AUTH(self, challenge):
  739. """Authobject to use with CRAM-MD5 authentication."""
  740. import hmac
  741. pwd = (self.password.encode('ASCII') if isinstance(self.password, str)
  742. else self.password)
  743. return self.user + " " + hmac.HMAC(pwd, challenge, 'md5').hexdigest()
  744. def logout(self, **kw):
  745. """(typ, [data]) = logout()
  746. Shutdown connection to server.
  747. Returns server 'BYE' response.
  748. NB: You must call this to shut down threads before discarding an instance."""
  749. self.state = LOGOUT
  750. if __debug__: self._log(1, 'state => LOGOUT')
  751. try:
  752. try:
  753. typ, dat = self._simple_command('LOGOUT')
  754. except:
  755. typ, dat = 'NO', ['%s: %s' % sys.exc_info()[:2]]
  756. if __debug__: self._log(1, dat)
  757. self._close_threads()
  758. finally:
  759. self._release_state_change()
  760. if __debug__: self._log(1, 'connection closed')
  761. bye = self._get_untagged_response('BYE', leave=True)
  762. if bye:
  763. typ, dat = 'BYE', bye
  764. return self._deliver_dat(typ, dat, kw)
  765. def lsub(self, directory='""', pattern='*', **kw):
  766. """(typ, [data, ...]) = lsub(directory='""', pattern='*')
  767. List 'subscribed' mailbox names in directory matching pattern.
  768. 'data' are tuples of message part envelope and data."""
  769. name = 'LSUB'
  770. kw['untagged_response'] = name
  771. return self._simple_command(name, directory, pattern, **kw)
  772. def myrights(self, mailbox, **kw):
  773. """(typ, [data]) = myrights(mailbox)
  774. Show my ACLs for a mailbox (i.e. the rights that I have on mailbox)."""
  775. name = 'MYRIGHTS'
  776. kw['untagged_response'] = name
  777. return self._simple_command(name, mailbox, **kw)
  778. def namespace(self, **kw):
  779. """(typ, [data, ...]) = namespace()
  780. Returns IMAP namespaces ala rfc2342."""
  781. name = 'NAMESPACE'
  782. kw['untagged_response'] = name
  783. return self._simple_command(name, **kw)
  784. def noop(self, **kw):
  785. """(typ, [data]) = noop()
  786. Send NOOP command."""
  787. if __debug__: self._dump_ur(3)
  788. return self._simple_command('NOOP', **kw)
  789. def partial(self, message_num, message_part, start, length, **kw):
  790. """(typ, [data, ...]) = partial(message_num, message_part, start, length)
  791. Fetch truncated part of a message.
  792. 'data' is tuple of message part envelope and data.
  793. NB: obsolete."""
  794. name = 'PARTIAL'
  795. kw['untagged_response'] = 'FETCH'
  796. return self._simple_command(name, message_num, message_part, start, length, **kw)
  797. def proxyauth(self, user, **kw):
  798. """(typ, [data]) = proxyauth(user)
  799. Assume authentication as 'user'.
  800. (Allows an authorised administrator to proxy into any user's mailbox.)"""
  801. try:
  802. return self._simple_command('PROXYAUTH', user, **kw)
  803. finally:
  804. self._release_state_change()
  805. def rename(self, oldmailbox, newmailbox, **kw):
  806. """(typ, [data]) = rename(oldmailbox, newmailbox)
  807. Rename old mailbox name to new."""
  808. return self._simple_command('RENAME', oldmailbox, newmailbox, **kw)
  809. def search(self, charset, *criteria, **kw):
  810. """(typ, [data]) = search(charset, criterion, ...)
  811. Search mailbox for matching messages.
  812. If UTF8 is enabled, charset MUST be None.
  813. 'data' is space separated list of matching message numbers."""
  814. name = 'SEARCH'
  815. kw['untagged_response'] = name
  816. if charset:
  817. if self.utf8_enabled:
  818. raise self.error("Non-None charset not valid in UTF8 mode")
  819. return self._simple_command(name, 'CHARSET', charset, *criteria, **kw)
  820. return self._simple_command(name, *criteria, **kw)
  821. def select(self, mailbox='INBOX', readonly=False, **kw):
  822. """(typ, [data]) = select(mailbox='INBOX', readonly=False)
  823. Select a mailbox. (Flushes all untagged responses.)
  824. 'data' is count of messages in mailbox ('EXISTS' response).
  825. Mandated responses are ('FLAGS', 'EXISTS', 'RECENT', 'UIDVALIDITY'), so
  826. other responses should be obtained via "response('FLAGS')" etc."""
  827. self.mailbox = mailbox
  828. self.is_readonly = bool(readonly)
  829. if readonly:
  830. name = 'EXAMINE'
  831. else:
  832. name = 'SELECT'
  833. try:
  834. rqb = self._command(name, mailbox)
  835. typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
  836. if typ != 'OK':
  837. if self.state == SELECTED:
  838. self.state = AUTH
  839. if __debug__: self._log(1, 'state => AUTH')
  840. if typ == 'BAD':
  841. self._deliver_exc(self.error, '%s command error: %s %s. Data: %.100s' % (name, typ, dat, mailbox), kw)
  842. return self._deliver_dat(typ, dat, kw)
  843. self.state = SELECTED
  844. if __debug__: self._log(1, 'state => SELECTED')
  845. finally:
  846. self._release_state_change()
  847. if self._get_untagged_response('READ-ONLY', leave=True) and not readonly:
  848. if __debug__: self._dump_ur(1)
  849. self._deliver_exc(self.readonly, '%s is not writable' % mailbox, kw)
  850. typ, dat = self._untagged_response(typ, [None], 'EXISTS')
  851. return self._deliver_dat(typ, dat, kw)
  852. def setacl(self, mailbox, who, what, **kw):
  853. """(typ, [data]) = setacl(mailbox, who, what)
  854. Set a mailbox acl."""
  855. try:
  856. return self._simple_command('SETACL', mailbox, who, what, **kw)
  857. finally:
  858. self._release_state_change()
  859. def setannotation(self, *args, **kw):
  860. """(typ, [data]) = setannotation(mailbox[, entry, attribute]+)
  861. Set ANNOTATIONs."""
  862. kw['untagged_response'] = 'ANNOTATION'
  863. return self._simple_command('SETANNOTATION', *args, **kw)
  864. def setquota(self, root, limits, **kw):
  865. """(typ, [data]) = setquota(root, limits)
  866. Set the quota root's resource limits."""
  867. kw['untagged_response'] = 'QUOTA'
  868. try:
  869. return self._simple_command('SETQUOTA', root, limits, **kw)
  870. finally:
  871. self._release_state_change()
  872. def sort(self, sort_criteria, charset, *search_criteria, **kw):
  873. """(typ, [data]) = sort(sort_criteria, charset, search_criteria, ...)
  874. IMAP4rev1 extension SORT command."""
  875. name = 'SORT'
  876. if (sort_criteria[0],sort_criteria[-1]) != ('(',')'):
  877. sort_criteria = '(%s)' % sort_criteria
  878. kw['untagged_response'] = name
  879. return self._simple_command(name, sort_criteria, charset, *search_criteria, **kw)
  880. def starttls(self, keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", tls_level=TLS_COMPAT, **kw):
  881. """(typ, [data]) = starttls(keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", tls_level="tls_compat")
  882. Start TLS negotiation as per RFC 2595."""
  883. name = 'STARTTLS'
  884. if name not in self.capabilities:
  885. raise self.abort('TLS not supported by server')
  886. if self._tls_established:
  887. raise self.abort('TLS session already established')
  888. # Must now shutdown reader thread after next response, and restart after changing read_fd
  889. self.read_size = 1 # Don't consume TLS handshake
  890. self.TerminateReader = True
  891. try:
  892. typ, dat = self._simple_command(name)
  893. finally:
  894. self._release_state_change()
  895. self.rdth.join()
  896. self.TerminateReader = False
  897. self.read_size = READ_SIZE
  898. if typ != 'OK':
  899. # Restart reader thread and error
  900. self.rdth = threading.Thread(target=self._reader)
  901. self.rdth.setDaemon(True)
  902. self.rdth.start()
  903. raise self.error("Couldn't establish TLS session: %s" % dat)
  904. self.keyfile = keyfile
  905. self.certfile = certfile
  906. self.ca_certs = ca_certs
  907. self.cert_verify_cb = cert_verify_cb
  908. self.ssl_version = ssl_version
  909. self.tls_level = tls_level
  910. try:
  911. self.ssl_wrap_socket()
  912. finally:
  913. # Restart reader thread
  914. self.rdth = threading.Thread(target=self._reader)
  915. self.rdth.setDaemon(True)
  916. self.rdth.start()
  917. typ, dat = self.capability()
  918. if dat == [None]:
  919. raise self.error('no CAPABILITY response from server')
  920. self.capabilities = tuple(dat[-1].upper().split())
  921. self._tls_established = True
  922. typ, dat = self._untagged_response(typ, dat, name)
  923. return self._deliver_dat(typ, dat, kw)
  924. def status(self, mailbox, names, **kw):
  925. """(typ, [data]) = status(mailbox, names)
  926. Request named status conditions for mailbox."""
  927. name = 'STATUS'
  928. kw['untagged_response'] = name
  929. return self._simple_command(name, mailbox, names, **kw)
  930. def store(self, message_set, command, flags, **kw):
  931. """(typ, [data]) = store(message_set, command, flags)
  932. Alters flag dispositions for messages in mailbox."""
  933. if (flags[0],flags[-1]) != ('(',')'):
  934. flags = '(%s)' % flags # Avoid quoting the flags
  935. kw['untagged_response'] = 'FETCH'
  936. return self._simple_command('STORE', message_set, command, flags, **kw)
  937. def subscribe(self, mailbox, **kw):
  938. """(typ, [data]) = subscribe(mailbox)
  939. Subscribe to new mailbox."""
  940. try:
  941. return self._simple_command('SUBSCRIBE', mailbox, **kw)
  942. finally:
  943. self._release_state_change()
  944. def thread(self, threading_algorithm, charset, *search_criteria, **kw):
  945. """(type, [data]) = thread(threading_alogrithm, charset, search_criteria, ...)
  946. IMAPrev1 extension THREAD command."""
  947. name = 'THREAD'
  948. kw['untagged_response'] = name
  949. return self._simple_command(name, threading_algorithm, charset, *search_criteria, **kw)
  950. def uid(self, command, *args, **kw):
  951. """(typ, [data]) = uid(command, arg, ...)
  952. Execute "command arg ..." with messages identified by UID,
  953. rather than message number.
  954. Assumes 'command' is legal in current state.
  955. Returns response appropriate to 'command'."""
  956. command = command.upper()
  957. if command in UID_direct:
  958. resp = command
  959. else:
  960. resp = 'FETCH'
  961. kw['untagged_response'] = resp
  962. return self._simple_command('UID', command, *args, **kw)
  963. def unsubscribe(self, mailbox, **kw):
  964. """(typ, [data]) = unsubscribe(mailbox)
  965. Unsubscribe from old mailbox."""
  966. try:
  967. return self._simple_command('UNSUBSCRIBE', mailbox, **kw)
  968. finally:
  969. self._release_state_change()
  970. def xatom(self, name, *args, **kw):
  971. """(typ, [data]) = xatom(name, arg, ...)
  972. Allow simple extension commands notified by server in CAPABILITY response.
  973. Assumes extension command 'name' is legal in current state.
  974. Returns response appropriate to extension command 'name'."""
  975. name = name.upper()
  976. if not name in Commands:
  977. Commands[name] = ((self.state,), False)
  978. try:
  979. return self._simple_command(name, *args, **kw)
  980. finally:
  981. self._release_state_change()
  982. # Internal methods
  983. def _append_untagged(self, typ, dat):
  984. # Append new 'dat' to end of last untagged response if same 'typ',
  985. # else append new response.
  986. if dat is None: dat = ''
  987. self.commands_lock.acquire()
  988. if self.untagged_responses:
  989. urn, urd = self.untagged_responses[-1]
  990. if urn != typ:
  991. urd = None
  992. else:
  993. urd = None
  994. if urd is None:
  995. urd = []
  996. self.untagged_responses.append([typ, urd])
  997. urd.append(dat)
  998. self.commands_lock.release()
  999. if __debug__: self._log(5, 'untagged_responses[%s] %s += ["%.80s"]' % (typ, len(urd)-1, dat))
  1000. def _check_bye(self):
  1001. bye = self._get_untagged_response('BYE', leave=True)
  1002. if bye:
  1003. if str != bytes:
  1004. raise self.abort(bye[-1].decode('ASCII', 'replace'))
  1005. else:
  1006. raise self.abort(bye[-1])
  1007. def _checkquote(self, arg):
  1008. # Must quote command args if "atom-specials" present,
  1009. # and not already quoted. NB: single quotes are removed.
  1010. if not isinstance(arg, string_types):
  1011. return arg
  1012. if len(arg) >= 2 and (arg[0],arg[-1]) in (('(',')'),('"','"')):
  1013. return arg
  1014. if len(arg) >= 2 and (arg[0],arg[-1]) in (("'","'"),):
  1015. return arg[1:-1]
  1016. if arg and self.mustquote_cre.search(arg) is None:
  1017. return arg
  1018. return self._quote(arg)
  1019. def _choose_nonull_or_dflt(self, dflt, *args):
  1020. if isinstance(dflt, string_types):
  1021. dflttyp = string_types # Allow any string type
  1022. else:
  1023. dflttyp = type(dflt)
  1024. for arg in args:
  1025. if arg is not None:
  1026. if isinstance(arg, dflttyp):
  1027. return arg
  1028. if __debug__: self._log(0, 'bad arg is %s, expecting %s' % (type(arg), dflttyp))
  1029. return dflt
  1030. def _command(self, name, *args, **kw):
  1031. if Commands[name][CMD_VAL_ASYNC]:
  1032. cmdtyp = 'async'
  1033. else:
  1034. cmdtyp = 'sync'
  1035. if __debug__: self._log(1, '[%s] %s %s' % (cmdtyp, name, args))
  1036. if __debug__: self._log(3, 'state_change_pending.acquire')
  1037. self.state_change_pending.acquire()
  1038. self._end_idle()
  1039. if cmdtyp == 'async':
  1040. self.state_change_pending.release()
  1041. if __debug__: self._log(3, 'state_change_pending.release')
  1042. else:
  1043. # Need to wait for all async commands to complete
  1044. self._check_bye()
  1045. self.commands_lock.acquire()
  1046. if self.tagged_commands:
  1047. self.state_change_free.clear()
  1048. need_event = True
  1049. else:
  1050. need_event = False
  1051. self.commands_lock.release()
  1052. if need_event:
  1053. if __debug__: self._log(3, 'sync command %s waiting for empty commands Q' % name)
  1054. self.state_change_free.wait(threading.TIMEOUT_MAX)
  1055. if __debug__: self._log(3, 'sync command %s proceeding' % name)
  1056. if self.state not in Commands[name][CMD_VAL_STATES]:
  1057. self.literal = None
  1058. raise self.error('command %s illegal in state %s, only allowed in states %s'
  1059. % (name, self.state, ', '.join(Commands[name][CMD_VAL_STATES])))
  1060. self._check_bye()
  1061. if name in ('EXAMINE', 'SELECT'):
  1062. self.commands_lock.acquire()
  1063. self.untagged_responses = [] # Flush all untagged responses
  1064. self.commands_lock.release()
  1065. else:
  1066. for typ in ('OK', 'NO', 'BAD'):
  1067. while self._get_untagged_response(typ):
  1068. continue
  1069. if not self.is_readonly and self._get_untagged_response('READ-ONLY', leave=True):
  1070. self.literal = None
  1071. raise self.readonly('mailbox status changed to READ-ONLY')
  1072. if self.Terminate:
  1073. raise self.abort('connection closed')
  1074. rqb = self._request_push(name=name, **kw)
  1075. data = '%s %s' % (rqb.tag, name)
  1076. for arg in args:
  1077. if arg is None: continue
  1078. data = '%s %s' % (data, self._checkquote(arg))
  1079. literal = self.literal
  1080. if literal is not None:
  1081. self.literal = None
  1082. if isinstance(literal, string_types):
  1083. literator = None
  1084. data = '%s {%s}' % (data, len(literal))
  1085. else:
  1086. literator = literal
  1087. if __debug__: self._log(4, 'data=%s' % data)
  1088. rqb.data = '%s%s' % (data, CRLF)
  1089. if literal is None:
  1090. self.ouq.put(rqb)
  1091. return rqb
  1092. # Must setup continuation expectancy *before* ouq.put
  1093. crqb = self._request_push(name=name, tag='continuation')
  1094. self.ouq.put(rqb)
  1095. while True:
  1096. # Wait for continuation response
  1097. ok, data = crqb.get_response('command: %s => %%s' % name)
  1098. if __debug__: self._log(4, 'continuation => %s, %s' % (ok, data))
  1099. # NO/BAD response?
  1100. if not ok:
  1101. break
  1102. if data == 'go ahead': # Apparently not uncommon broken IMAP4 server response to AUTHENTICATE command
  1103. data = ''
  1104. # Send literal
  1105. if literator is not None:
  1106. literal = literator(data, rqb)
  1107. if literal is None:
  1108. break
  1109. if literator is not None:
  1110. # Need new request for next continuation response
  1111. crqb = self._request_push(name=name, tag='continuation')
  1112. if __debug__: self._log(4, 'write literal size %s' % len(literal))
  1113. crqb.data = '%s%s' % (literal, CRLF)
  1114. self.ouq.put(crqb)
  1115. if literator is None:
  1116. break
  1117. return rqb
  1118. def _command_complete(self, rqb, kw):
  1119. # Called for non-callback commands
  1120. self._check_bye()
  1121. typ, dat = rqb.get_response('command: %s => %%s' % rqb.name)
  1122. if typ == 'BAD':
  1123. if __debug__: self._print_log()
  1124. raise self.error('%s command error: %s %s. Data: %.100s' % (rqb.name, typ, dat, rqb.data))
  1125. if 'untagged_response' in kw:
  1126. return self._untagged_response(typ, dat, kw['untagged_response'])
  1127. return typ, dat
  1128. def _command_completer(self, cb_arg_list):
  1129. # Called for callback commands
  1130. response, cb_arg, error = cb_arg_list
  1131. rqb, kw = cb_arg
  1132. rqb.callback = kw['callback']
  1133. rqb.callback_arg = kw.get('cb_arg')
  1134. if error is not None:
  1135. if __debug__: self._print_log()
  1136. typ, val = error
  1137. rqb.abort(typ, val)
  1138. return
  1139. bye = self._get_untagged_response('BYE', leave=True)
  1140. if bye:
  1141. if str != bytes:
  1142. rqb.abort(self.abort, bye[-1].decode('ASCII', 'replace'))
  1143. else:
  1144. rqb.abort(self.abort, bye[-1])
  1145. return
  1146. typ, dat = response
  1147. if typ == 'BAD':
  1148. if __debug__: self._print_log()
  1149. rqb.abort(self.error, '%s command error: %s %s. Data: %.100s' % (rqb.name, typ, dat, rqb.data))
  1150. return
  1151. if __debug__: self._log(4, '_command_completer(%s, %s, None) = %s' % (response, cb_arg, rqb.tag))
  1152. if 'untagged_response' in kw:
  1153. response = self._untagged_response(typ, dat, kw['untagged_response'])
  1154. rqb.deliver(response)
  1155. def _deliver_dat(self, typ, dat, kw):
  1156. if 'callback' in kw:
  1157. kw['callback'](((typ, dat), kw.get('cb_arg'), None))
  1158. return typ, dat
  1159. def _deliver_exc(self, exc, dat, kw):
  1160. if 'callback' in kw:
  1161. kw['callback']((None, kw.get('cb_arg'), (exc, dat)))
  1162. raise exc(dat)
  1163. def _end_idle(self):
  1164. self.idle_lock.acquire()
  1165. irqb = self.idle_rqb
  1166. if irqb is None:
  1167. self.idle_lock.release()
  1168. return
  1169. self.idle_rqb = None
  1170. self.idle_timeout = None
  1171. self.idle_lock.release()
  1172. irqb.data = 'DONE%s' % CRLF
  1173. self.ouq.put(irqb)
  1174. if __debug__: self._log(2, 'server IDLE finished')
  1175. def _get_untagged_response(self, name, leave=False):
  1176. self.commands_lock.acquire()
  1177. for i, (typ, dat) in enumerate(self.untagged_responses):
  1178. if typ == name:
  1179. if not leave:
  1180. del self.untagged_responses[i]
  1181. self.commands_lock.release()
  1182. if __debug__: self._log(5, '_get_untagged_response(%s) => %.80s' % (name, dat))
  1183. return dat
  1184. self.commands_lock.release()
  1185. return None
  1186. def _match(self, cre, s):
  1187. # Run compiled regular expression 'cre' match method on 's'.
  1188. # Save result, return success.
  1189. self.mo = cre.match(s)
  1190. return self.mo is not None
  1191. def _put_response(self, resp):
  1192. if self._expecting_data:
  1193. rlen = len(resp)
  1194. dlen = min(self._expecting_data_len, rlen)
  1195. if __debug__: self._log(5, '_put_response expecting data len %s, got %s' % (self._expecting_data_len, rlen))
  1196. self._expecting_data_len -= dlen
  1197. self._expecting_data = (self._expecting_data_len != 0)
  1198. if rlen <= dlen:
  1199. self._accumulated_data.append(resp)
  1200. return
  1201. self._accumulated_data.append(resp[:dlen])
  1202. resp = resp[dlen:]
  1203. if self._accumulated_data:
  1204. typ, dat = self._literal_expected
  1205. self._append_untagged(typ, (dat, ''.join(self._accumulated_data)))
  1206. self._accumulated_data = []
  1207. # Protocol mandates all lines terminated by CRLF
  1208. resp = resp[:-2]
  1209. if __debug__: self._log(5, '_put_response(%s)' % resp)
  1210. if 'continuation' in self.tagged_commands:
  1211. continuation_expected = True
  1212. else:
  1213. continuation_expected = False
  1214. if self._literal_expected is not None:
  1215. dat = resp
  1216. if self._match(self.literal_cre, dat):
  1217. self._literal_expected[1] = dat
  1218. self._expecting_data = True
  1219. self._expecting_data_len = int(self.mo.group('size'))
  1220. if __debug__: self._log(4, 'expecting literal size %s' % self._expecting_data_len)
  1221. return
  1222. typ = self._literal_expected[0]
  1223. self._literal_expected = None
  1224. if dat:
  1225. self._append_untagged(typ, dat) # Tail
  1226. if __debug__: self._log(4, 'literal completed')
  1227. else:
  1228. # Command completion response?
  1229. if self._match(self.tagre, resp):
  1230. tag = self.mo.group('tag')
  1231. typ = self.mo.group('type')
  1232. dat = self.mo.group('data')
  1233. if typ in ('OK', 'NO', 'BAD') and self._match(self.response_code_cre, dat):
  1234. self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  1235. if not tag in self.tagged_commands:
  1236. if __debug__: self._log(1, 'unexpected tagged response: %s' % resp)
  1237. else:
  1238. self._request_pop(tag, (typ, [dat]))
  1239. else:
  1240. dat2 = None
  1241. # '*' (untagged) responses?
  1242. if not self._match(self.untagged_response_cre, resp):
  1243. if self._match(self.untagged_status_cre, resp):
  1244. dat2 = self.mo.group('data2')
  1245. if self.mo is None:
  1246. # Only other possibility is '+' (continuation) response...
  1247. if self._match(self.continuation_cre, resp):
  1248. if not continuation_expected:
  1249. if __debug__: self._log(1, "unexpected continuation response: '%s'" % resp)
  1250. return
  1251. self._request_pop('continuation', (True, self.mo.group('data')))
  1252. return
  1253. if __debug__: self._log(1, "unexpected response: '%s'" % resp)
  1254. return
  1255. typ = self.mo.group('type')
  1256. dat = self.mo.group('data')
  1257. if dat is None: dat = '' # Null untagged response
  1258. if dat2: dat = dat + ' ' + dat2
  1259. # Is there a literal to come?
  1260. if self._match(self.literal_cre, dat):
  1261. self._expecting_data = True
  1262. self._expecting_data_len = int(self.mo.group('size'))
  1263. if __debug__: self._log(4, 'read literal size %s' % self._expecting_data_len)
  1264. self._literal_expected = [typ, dat]
  1265. return
  1266. self._append_untagged(typ, dat)
  1267. if typ in ('OK', 'NO', 'BAD') and self._match(self.response_code_cre, dat):
  1268. self._append_untagged(self.mo.group('type'), self.mo.group('data'))
  1269. if typ != 'OK': # NO, BYE, IDLE
  1270. self._end_idle()
  1271. # Command waiting for aborted continuation response?
  1272. if continuation_expected:
  1273. self._request_pop('continuation', (False, resp))
  1274. # Bad news?
  1275. if typ in ('NO', 'BAD', 'BYE'):
  1276. if typ == 'BYE':
  1277. self.Terminate = True
  1278. if __debug__: self._log(1, '%s response: %s' % (typ, dat))
  1279. def _quote(self, arg):
  1280. return '"%s"' % arg.replace('\\', '\\\\').replace('"', '\\"')
  1281. def _release_state_change(self):
  1282. if self.state_change_pending.locked():
  1283. self.state_change_pending.release()
  1284. if __debug__: self._log(3, 'state_change_pending.release')
  1285. def _request_pop(self, name, data):
  1286. self.commands_lock.acquire()
  1287. rqb = self.tagged_commands.pop(name)
  1288. if not self.tagged_commands:
  1289. need_event = True
  1290. else:
  1291. need_event = False
  1292. self.commands_lock.release()
  1293. if __debug__: self._log(4, '_request_pop(%s, %s) [%d] = %s' % (name, data, len(self.tagged_commands), rqb.tag))
  1294. rqb.deliver(data)
  1295. if need_event:
  1296. if __debug__: self._log(3, 'state_change_free.set')
  1297. self.state_change_free.set()
  1298. def _request_push(self, tag=None, name=None, **kw):
  1299. self.commands_lock.acquire()
  1300. rqb = Request(self, name=name, **kw)
  1301. if tag is None:
  1302. tag = rqb.tag
  1303. self.tagged_commands[tag] = rqb
  1304. self.commands_lock.release()
  1305. if __debug__: self._log(4, '_request_push(%s, %s, %s) = %s' % (tag, name, repr(kw), rqb.tag))
  1306. return rqb
  1307. def _simple_command(self, name, *args, **kw):
  1308. if 'callback' in kw:
  1309. # Note: old calling sequence for back-compat with python <2.6
  1310. self._command(name, callback=self._command_completer, cb_arg=kw, cb_self=True, *args)
  1311. return (None, None)
  1312. return self._command_complete(self._command(name, *args), kw)
  1313. def _untagged_response(self, typ, dat, name):
  1314. if typ == 'NO':
  1315. return typ, dat
  1316. data = self._get_untagged_response(name)
  1317. if not data:
  1318. return typ, [None]
  1319. while True:
  1320. dat = self._get_untagged_response(name)
  1321. if not dat:
  1322. break
  1323. data += dat
  1324. if __debug__: self._log(4, '_untagged_response(%s, ?, %s) => %.80s' % (typ, name, data))
  1325. return typ, data
  1326. # Threads
  1327. def _close_threads(self):
  1328. if __debug__: self._log(1, '_close_threads')
  1329. self.ouq.put(None)
  1330. self.wrth.join()
  1331. if __debug__: self._log(1, 'call shutdown')
  1332. self.shutdown()
  1333. self.rdth.join()
  1334. self.inth.join()
  1335. def _handler(self):
  1336. resp_timeout = self.resp_timeout
  1337. threading.currentThread().setName(self.identifier + 'handler')
  1338. time.sleep(0.1) # Don't start handling before main thread ready
  1339. if __debug__: self._log(1, 'starting')
  1340. typ, val = self.abort, 'connection terminated'
  1341. while not self.Terminate:
  1342. self.idle_lock.acquire()
  1343. if self.idle_timeout is not None:
  1344. timeout = self.idle_timeout - time.time()
  1345. if timeout <= 0:
  1346. timeout = 1
  1347. if __debug__:
  1348. if self.idle_rqb is not None:
  1349. self._log(5, 'server IDLING, timeout=%.2f' % timeout)
  1350. else:
  1351. timeout = resp_timeout
  1352. self.idle_lock.release()
  1353. try:
  1354. line = self.inq.get(True, timeout)
  1355. except queue.Empty:
  1356. if self.idle_rqb is None:
  1357. if resp_timeout is not None and self.tagged_commands:
  1358. if __debug__: self._log(1, 'response timeout')
  1359. typ, val = self.abort, 'no response after %s secs' % resp_timeout
  1360. break
  1361. continue
  1362. if self.idle_timeout > time.time():
  1363. continue
  1364. if __debug__: self._log(2, 'server IDLE timedout')
  1365. line = IDLE_TIMEOUT_RESPONSE
  1366. if line is None:
  1367. if __debug__: self._log(1, 'inq None - terminating')
  1368. break
  1369. if not isinstance(line, string_types):
  1370. typ, val = line
  1371. break
  1372. try:
  1373. self._put_response(line)
  1374. except:
  1375. typ, val = self.error, 'program error: %s - %s' % sys.exc_info()[:2]
  1376. break
  1377. self.Terminate = True
  1378. if __debug__: self._log(1, 'terminating: %s' % repr(val))
  1379. while not self.ouq.empty():
  1380. try:
  1381. qel = self.ouq.get_nowait()
  1382. if qel is not None:
  1383. qel.abort(typ, val)
  1384. except queue.Empty:
  1385. break
  1386. self.ouq.put(None)
  1387. self.commands_lock.acquire()
  1388. for name in list(self.tagged_commands.keys()):
  1389. rqb = self.tagged_commands.pop(name)
  1390. rqb.abort(typ, val)
  1391. self.state_change_free.set()
  1392. self.commands_lock.release()
  1393. if __debug__: self._log(3, 'state_change_free.set')
  1394. if __debug__: self._log(1, 'finished')
  1395. if hasattr(select_module, "poll"):
  1396. def _reader(self):
  1397. threading.currentThread().setName(self.identifier + 'reader')
  1398. if __debug__: self._log(1, 'starting using poll')
  1399. def poll_error(state):
  1400. PollErrors = {
  1401. select.POLLERR: 'Error',
  1402. select.POLLHUP: 'Hang up',
  1403. select.POLLNVAL: 'Invalid request: descriptor not open',
  1404. }
  1405. return ' '.join([PollErrors[s] for s in PollErrors.keys() if (s & state)])
  1406. if bytes != str:
  1407. line_part = b''
  1408. else:
  1409. line_part = ''
  1410. poll = select.poll()
  1411. poll.register(self.read_fd, select.POLLIN)
  1412. rxzero = 0
  1413. terminate = False
  1414. read_poll_timeout = self.read_poll_timeout * 1000 # poll() timeout is in millisecs
  1415. while not (terminate or self.Terminate):
  1416. if self.state == LOGOUT:
  1417. timeout = 10
  1418. else:
  1419. timeout = read_poll_timeout
  1420. try:
  1421. r = poll.poll(timeout)
  1422. if __debug__: self._log(5, 'poll => %s' % repr(r))
  1423. if not r:
  1424. continue # Timeout
  1425. fd,state = r[0]
  1426. if state & select.POLLIN:
  1427. data = self.read(self.read_size) # Drain ssl buffer if present
  1428. start = 0
  1429. dlen = len(data)
  1430. if __debug__: self._log(5, 'rcvd %s' % dlen)
  1431. if dlen == 0:
  1432. rxzero += 1
  1433. if rxzero > 5:
  1434. raise IOError("Too many read 0")
  1435. time.sleep(0.1)
  1436. continue # Try again
  1437. rxzero = 0
  1438. while True:
  1439. if bytes != str:
  1440. stop = data.find(b'\n', start)
  1441. if stop < 0:
  1442. line_part += data[start:]
  1443. break
  1444. stop += 1
  1445. line_part, start, line = \
  1446. b'', stop, (line_part + data[start:stop]).decode(errors='ignore')
  1447. else:
  1448. stop = data.find('\n', start)
  1449. if stop < 0:
  1450. line_part += data[start:]
  1451. break
  1452. stop += 1
  1453. line_part, start, line = \
  1454. '', stop, line_part + data[start:stop]
  1455. if __debug__: self._log(4, '< %s' % line)
  1456. self.inq.put(line)
  1457. if self.TerminateReader:
  1458. terminate = True
  1459. if state & ~(select.POLLIN):
  1460. raise IOError(poll_error(state))
  1461. except:
  1462. reason = 'socket error: %s - %s' % sys.exc_info()[:2]
  1463. if __debug__:
  1464. if not self.Terminate:
  1465. self._print_log()
  1466. if self.debug: self.debug += 4 # Output all
  1467. self._log(1, reason)
  1468. self.inq.put((self.abort, reason))
  1469. break
  1470. poll.unregister(self.read_fd)
  1471. if __debug__: self._log(1, 'finished')
  1472. else:
  1473. # No "poll" - use select()
  1474. def _reader(self):
  1475. threading.currentThread().setName(self.identifier + 'reader')
  1476. if __debug__: self._log(1, 'starting using select')
  1477. if bytes != str:
  1478. line_part = b''
  1479. else:
  1480. line_part = ''
  1481. rxzero = 0
  1482. terminate = False
  1483. while not (terminate or self.Terminate):
  1484. if self.state == LOGOUT:
  1485. timeout = 1
  1486. else:
  1487. timeout = self.read_poll_timeout
  1488. try:
  1489. r,w,e = select.select([self.read_fd], [], [], timeout)
  1490. if __debug__: self._log(5, 'select => %s, %s, %s' % (r,w,e))
  1491. if not r: # Timeout
  1492. continue
  1493. data = self.read(self.read_size) # Drain ssl buffer if present
  1494. start = 0
  1495. dlen = len(data)
  1496. if __debug__: self._log(5, 'rcvd %s' % dlen)
  1497. if dlen == 0:
  1498. rxzero += 1
  1499. if rxzero > 5:
  1500. raise IOError("Too many read 0")
  1501. time.sleep(0.1)
  1502. continue # Try again
  1503. rxzero = 0
  1504. while True:
  1505. if bytes != str:
  1506. stop = data.find(b'\n', start)
  1507. if stop < 0:
  1508. line_part += data[start:]
  1509. break
  1510. stop += 1
  1511. line_part, start, line = \
  1512. b'', stop, (line_part + data[start:stop]).decode(errors='ignore')
  1513. else:
  1514. stop = data.find('\n', start)
  1515. if stop < 0:
  1516. line_part += data[start:]
  1517. break
  1518. stop += 1
  1519. line_part, start, line = \
  1520. '', stop, line_part + data[start:stop]
  1521. if __debug__: self._log(4, '< %s' % line)
  1522. self.inq.put(line)
  1523. if self.TerminateReader:
  1524. terminate = True
  1525. except:
  1526. reason = 'socket error: %s - %s' % sys.exc_info()[:2]
  1527. if __debug__:
  1528. if not self.Terminate:
  1529. self._print_log()
  1530. if self.debug: self.debug += 4 # Output all
  1531. self._log(1, reason)
  1532. self.inq.put((self.abort, reason))
  1533. break
  1534. if __debug__: self._log(1, 'finished')
  1535. def _writer(self):
  1536. threading.currentThread().setName(self.identifier + 'writer')
  1537. if __debug__: self._log(1, 'starting')
  1538. reason = 'Terminated'
  1539. while not self.Terminate:
  1540. rqb = self.ouq.get()
  1541. if rqb is None:
  1542. break # Outq flushed
  1543. try:
  1544. self.send(rqb.data)
  1545. if __debug__: self._log(4, '> %s' % rqb.data)
  1546. except:
  1547. reason = 'socket error: %s - %s' % sys.exc_info()[:2]
  1548. if __debug__:
  1549. if not self.Terminate:
  1550. self._print_log()
  1551. if self.debug: self.debug += 4 # Output all
  1552. self._log(1, reason)
  1553. rqb.abort(self.abort, reason)
  1554. break
  1555. self.inq.put((self.abort, reason))
  1556. if __debug__: self._log(1, 'finished')
  1557. # Debugging
  1558. if __debug__:
  1559. def _init_debug(self, debug=None, debug_file=None, debug_buf_lvl=None):
  1560. self.debug_lock = threading.Lock()
  1561. self.debug = self._choose_nonull_or_dflt(0, debug, Debug)
  1562. self.debug_file = self._choose_nonull_or_dflt(sys.stderr, debug_file)
  1563. self.debug_buf_lvl = self._choose_nonull_or_dflt(DFLT_DEBUG_BUF_LVL, debug_buf_lvl)
  1564. self._cmd_log_len = 20
  1565. self._cmd_log_idx = 0
  1566. self._cmd_log = {} # Last `_cmd_log_len' interactions
  1567. if self.debug:
  1568. self._mesg('imaplib2 version %s' % __version__)
  1569. self._mesg('imaplib2 debug level %s, buffer level %s' % (self.debug, self.debug_buf_lvl))
  1570. def _dump_ur(self, lvl):
  1571. if lvl > self.debug:
  1572. return
  1573. l = self.untagged_responses
  1574. if not l:
  1575. return
  1576. t = '\n\t\t'
  1577. l = ['%s: "%s"' % (x[0], x[1][0] and '" "'.join(x[1]) or '') for x in l]
  1578. self.debug_lock.acquire()
  1579. self._mesg('untagged responses dump:%s%s' % (t, t.join(l)))
  1580. self.debug_lock.release()
  1581. def _log(self, lvl, line):
  1582. if lvl > self.debug:
  1583. return
  1584. if line[-2:] == CRLF:
  1585. line = line[:-2] + '\\r\\n'
  1586. tn = threading.currentThread().getName()
  1587. if lvl <= 1 or self.debug > self.debug_buf_lvl:
  1588. self.debug_lock.acquire()
  1589. self._mesg(line, tn)
  1590. self.debug_lock.release()
  1591. if lvl != 1:
  1592. return
  1593. # Keep log of last `_cmd_log_len' interactions for debugging.
  1594. self.debug_lock.acquire()
  1595. self._cmd_log[self._cmd_log_idx] = (line, tn, time.time())
  1596. self._cmd_log_idx += 1
  1597. if self._cmd_log_idx >= self._cmd_log_len:
  1598. self._cmd_log_idx = 0
  1599. self.debug_lock.release()
  1600. def _mesg(self, s, tn=None, secs=None):
  1601. if secs is None:
  1602. secs = time.time()
  1603. if tn is None:
  1604. tn = threading.currentThread().getName()
  1605. tm = time.strftime('%M:%S', time.localtime(secs))
  1606. try:
  1607. self.debug_file.write(' %s.%02d %s %s\n' % (tm, (secs*100)%100, tn, s))
  1608. self.debug_file.flush()
  1609. finally:
  1610. pass
  1611. def _print_log(self):
  1612. self.debug_lock.acquire()
  1613. i, n = self._cmd_log_idx, self._cmd_log_len
  1614. if n: self._mesg('last %d log messages:' % n)
  1615. while n:
  1616. try:
  1617. self._mesg(*self._cmd_log[i])
  1618. except:
  1619. pass
  1620. i += 1
  1621. if i >= self._cmd_log_len:
  1622. i = 0
  1623. n -= 1
  1624. self.debug_lock.release()
  1625. class IMAP4_SSL(IMAP4):
  1626. """IMAP4 client class over SSL connection
  1627. Instantiate with:
  1628. IMAP4_SSL(host=None, port=None, keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None, tls_level="tls_compat")
  1629. host - host's name (default: localhost);
  1630. port - port number (default: standard IMAP4 SSL port);
  1631. keyfile - PEM formatted file that contains your private key (default: None);
  1632. certfile - PEM formatted certificate chain file (default: None);
  1633. ca_certs - PEM formatted certificate chain file used to validate server certificates (default: None);
  1634. cert_verify_cb - function to verify authenticity of server certificates (default: None);
  1635. ssl_version - SSL version to use (default: "ssl23", choose from: "tls1","ssl3","ssl23");
  1636. debug - debug level (default: 0 - no debug);
  1637. debug_file - debug stream (default: sys.stderr);
  1638. identifier - thread identifier prefix (default: host);
  1639. timeout - timeout in seconds when expecting a command response.
  1640. debug_buf_lvl - debug level at which buffering is turned off.
  1641. tls_level - TLS security level (default: "tls_compat").
  1642. The recognized values for tls_level are:
  1643. tls_secure: accept only TLS protocols recognized as "secure"
  1644. tls_no_ssl: disable SSLv2 and SSLv3 support
  1645. tls_compat: accept all SSL/TLS versions
  1646. For more documentation see the docstring of the parent class IMAP4.
  1647. """
  1648. def __init__(self, host=None, port=None, keyfile=None, certfile=None, ca_certs=None, cert_verify_cb=None, ssl_version="ssl23", debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None, tls_level=TLS_COMPAT):
  1649. self.keyfile = keyfile
  1650. self.certfile = certfile
  1651. self.ca_certs = ca_certs
  1652. self.cert_verify_cb = cert_verify_cb
  1653. self.ssl_version = ssl_version
  1654. self.tls_level = tls_level
  1655. IMAP4.__init__(self, host, port, debug, debug_file, identifier, timeout, debug_buf_lvl)
  1656. def open(self, host=None, port=None):
  1657. """open(host=None, port=None)
  1658. Setup secure connection to remote server on "host:port"
  1659. (default: localhost:standard IMAP4 SSL port).
  1660. This connection will be used by the routines:
  1661. read, send, shutdown, socket, ssl."""
  1662. self.host = self._choose_nonull_or_dflt('', host)
  1663. self.port = self._choose_nonull_or_dflt(IMAP4_SSL_PORT, port)
  1664. self.sock = self.open_socket()
  1665. self.ssl_wrap_socket()
  1666. def read(self, size):
  1667. """data = read(size)
  1668. Read at most 'size' bytes from remote."""
  1669. if self.decompressor is None:
  1670. return self.sock.read(size)
  1671. if self.decompressor.unconsumed_tail:
  1672. data = self.decompressor.unconsumed_tail
  1673. else:
  1674. data = self.sock.read(READ_SIZE)
  1675. return self.decompressor.decompress(data, size)
  1676. def send(self, data):
  1677. """send(data)
  1678. Send 'data' to remote."""
  1679. if self.compressor is not None:
  1680. data = self.compressor.compress(data)
  1681. data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
  1682. if bytes != str:
  1683. data = bytes(data, 'utf8')
  1684. if hasattr(self.sock, "sendall"):
  1685. self.sock.sendall(data)
  1686. else:
  1687. dlen = len(data)
  1688. while dlen > 0:
  1689. sent = self.sock.write(data)
  1690. if sent == dlen:
  1691. break # avoid copy
  1692. data = data[sent:]
  1693. dlen = dlen - sent
  1694. def ssl(self):
  1695. """ssl = ssl()
  1696. Return ssl instance used to communicate with the IMAP4 server."""
  1697. return self.sock
  1698. class IMAP4_stream(IMAP4):
  1699. """IMAP4 client class over a stream
  1700. Instantiate with:
  1701. IMAP4_stream(command, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None)
  1702. command - string that can be passed to subprocess.Popen();
  1703. debug - debug level (default: 0 - no debug);
  1704. debug_file - debug stream (default: sys.stderr);
  1705. identifier - thread identifier prefix (default: host);
  1706. timeout - timeout in seconds when expecting a command response.
  1707. debug_buf_lvl - debug level at which buffering is turned off.
  1708. For more documentation see the docstring of the parent class IMAP4.
  1709. """
  1710. def __init__(self, command, debug=None, debug_file=None, identifier=None, timeout=None, debug_buf_lvl=None):
  1711. self.command = command
  1712. self.host = command
  1713. self.port = None
  1714. self.sock = None
  1715. self.writefile, self.readfile = None, None
  1716. self.read_fd = None
  1717. IMAP4.__init__(self, None, None, debug, debug_file, identifier, timeout, debug_buf_lvl)
  1718. def open(self, host=None, port=None):
  1719. """open(host=None, port=None)
  1720. Setup a stream connection via 'self.command'.
  1721. This connection will be used by the routines:
  1722. read, send, shutdown, socket."""
  1723. from subprocess import Popen, PIPE
  1724. if __debug__: self._log(0, 'opening stream from command "%s"' % self.command)
  1725. self._P = Popen(self.command, shell=True, stdin=PIPE, stdout=PIPE, close_fds=True)
  1726. self.writefile, self.readfile = self._P.stdin, self._P.stdout
  1727. self.read_fd = self.readfile.fileno()
  1728. def read(self, size):
  1729. """Read 'size' bytes from remote."""
  1730. if self.decompressor is None:
  1731. return os.read(self.read_fd, size)
  1732. if self.decompressor.unconsumed_tail:
  1733. data = self.decompressor.unconsumed_tail
  1734. else:
  1735. data = os.read(self.read_fd, READ_SIZE)
  1736. return self.decompressor.decompress(data, size)
  1737. def send(self, data):
  1738. """Send data to remote."""
  1739. if self.compressor is not None:
  1740. data = self.compressor.compress(data)
  1741. data += self.compressor.flush(zlib.Z_SYNC_FLUSH)
  1742. if bytes != str:
  1743. data = bytes(data, 'utf8')
  1744. self.writefile.write(data)
  1745. self.writefile.flush()
  1746. def shutdown(self):
  1747. """Close I/O established in "open"."""
  1748. self.readfile.close()
  1749. self.writefile.close()
  1750. class _Authenticator(object):
  1751. """Private class to provide en/de-coding
  1752. for base64 authentication conversation."""
  1753. def __init__(self, mechinst):
  1754. self.mech = mechinst # Callable object to provide/process data
  1755. def process(self, data, rqb):
  1756. ret = self.mech(self.decode(data))
  1757. if ret is None:
  1758. return '*' # Abort conversation
  1759. return self.encode(ret)
  1760. def encode(self, inp):
  1761. #
  1762. # Invoke binascii.b2a_base64 iteratively with
  1763. # short even length buffers, strip the trailing
  1764. # line feed from the result and append. "Even"
  1765. # means a number that factors to both 6 and 8,
  1766. # so when it gets to the end of the 8-bit input
  1767. # there's no partial 6-bit output.
  1768. #
  1769. if bytes != str:
  1770. oup = b''
  1771. else:
  1772. oup = ''
  1773. while inp:
  1774. if len(inp) > 48:
  1775. t = inp[:48]
  1776. inp = inp[48:]
  1777. else:
  1778. t = inp
  1779. inp = ''
  1780. e = binascii.b2a_base64(t)
  1781. if e:
  1782. oup = oup + e[:-1]
  1783. return oup
  1784. def decode(self, inp):
  1785. if not inp:
  1786. return ''
  1787. return binascii.a2b_base64(inp)
  1788. class _IdleCont(object):
  1789. """When process is called, server is in IDLE state
  1790. and will send asynchronous changes."""
  1791. def __init__(self, parent, timeout):
  1792. self.parent = parent
  1793. self.timeout = parent._choose_nonull_or_dflt(IDLE_TIMEOUT, timeout)
  1794. self.parent.idle_timeout = self.timeout + time.time()
  1795. def process(self, data, rqb):
  1796. self.parent.idle_lock.acquire()
  1797. self.parent.idle_rqb = rqb
  1798. self.parent.idle_timeout = self.timeout + time.time()
  1799. self.parent.idle_lock.release()
  1800. if __debug__: self.parent._log(2, 'server IDLE started, timeout in %.2f secs' % self.timeout)
  1801. return None
  1802. MonthNames = [None, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  1803. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  1804. Mon2num = dict(list(zip((x for x in MonthNames[1:]), list(range(1, 13)))))
  1805. InternalDate = re.compile(r'.*INTERNALDATE "'
  1806. r'(?P<day>[ 0123][0-9])-(?P<mon>[A-Z][a-z][a-z])-(?P<year>[0-9][0-9][0-9][0-9])'
  1807. r' (?P<hour>[0-9][0-9]):(?P<min>[0-9][0-9]):(?P<sec>[0-9][0-9])'
  1808. r' (?P<zonen>[-+])(?P<zoneh>[0-9][0-9])(?P<zonem>[0-9][0-9])'
  1809. r'"')
  1810. def Internaldate2Time(resp):
  1811. """time_tuple = Internaldate2Time(resp)
  1812. Convert IMAP4 INTERNALDATE to UT."""
  1813. mo = InternalDate.match(resp)
  1814. if not mo:
  1815. return None
  1816. mon = Mon2num[mo.group('mon')]
  1817. zonen = mo.group('zonen')
  1818. day = int(mo.group('day'))
  1819. year = int(mo.group('year'))
  1820. hour = int(mo.group('hour'))
  1821. min = int(mo.group('min'))
  1822. sec = int(mo.group('sec'))
  1823. zoneh = int(mo.group('zoneh'))
  1824. zonem = int(mo.group('zonem'))
  1825. # INTERNALDATE timezone must be subtracted to get UT
  1826. zone = (zoneh*60 + zonem)*60
  1827. if zonen == '-':
  1828. zone = -zone
  1829. tt = (year, mon, day, hour, min, sec, -1, -1, -1)
  1830. utc = time.mktime(tt)
  1831. # Following is necessary because the time module has no 'mkgmtime'.
  1832. # 'mktime' assumes arg in local timezone, so adds timezone/altzone.
  1833. lt = time.localtime(utc)
  1834. if time.daylight and lt[-1]:
  1835. zone = zone + time.altzone
  1836. else:
  1837. zone = zone + time.timezone
  1838. return time.localtime(utc - zone)
  1839. Internaldate2tuple = Internaldate2Time # (Backward compatible)
  1840. def Time2Internaldate(date_time):
  1841. """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time)
  1842. Convert 'date_time' to IMAP4 INTERNALDATE representation."""
  1843. if isinstance(date_time, (int, float)):
  1844. tt = time.localtime(date_time)
  1845. elif isinstance(date_time, (tuple, time.struct_time)):
  1846. tt = date_time
  1847. elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
  1848. return date_time # Assume in correct format
  1849. else:
  1850. raise ValueError("date_time not of a known type")
  1851. if time.daylight and tt[-1]:
  1852. zone = -time.altzone
  1853. else:
  1854. zone = -time.timezone
  1855. return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' %
  1856. ((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] +
  1857. divmod(zone//60, 60)))
  1858. FLAGS_cre = re.compile(r'.*FLAGS \((?P<flags>[^\)]*)\)')
  1859. def ParseFlags(resp):
  1860. """('flag', ...) = ParseFlags(line)
  1861. Convert IMAP4 flags response to python tuple."""
  1862. mo = FLAGS_cre.match(resp)
  1863. if not mo:
  1864. return ()
  1865. return tuple(mo.group('flags').split())
  1866. if __name__ == '__main__':
  1867. # To test: invoke either as 'python imaplib2.py [IMAP4_server_hostname]',
  1868. # or as 'python imaplib2.py -s "rsh IMAP4_server_hostname exec /etc/rimapd"'
  1869. # or as 'python imaplib2.py -l keyfile[:certfile]|: [IMAP4_SSL_server_hostname]'
  1870. #
  1871. # Option "-d <level>" turns on debugging (use "-d 5" for everything)
  1872. # Option "-i" tests that IDLE is interruptible
  1873. # Option "-p <port>" allows alternate ports
  1874. if not __debug__:
  1875. raise ValueError('Please run without -O')
  1876. import getopt, getpass
  1877. try:
  1878. optlist, args = getopt.getopt(sys.argv[1:], 'd:il:s:p:')
  1879. except getopt.error as val:
  1880. optlist, args = (), ()
  1881. debug, debug_buf_lvl, port, stream_command, keyfile, certfile, idle_intr = (None,)*7
  1882. for opt,val in optlist:
  1883. if opt == '-d':
  1884. debug = int(val)
  1885. debug_buf_lvl = debug - 1
  1886. elif opt == '-i':
  1887. idle_intr = 1
  1888. elif opt == '-l':
  1889. try:
  1890. keyfile,certfile = val.split(':')
  1891. except ValueError:
  1892. keyfile,certfile = val,val
  1893. elif opt == '-p':
  1894. port = int(val)
  1895. elif opt == '-s':
  1896. stream_command = val
  1897. if not args: args = (stream_command,)
  1898. if not args: args = ('',)
  1899. if not port: port = (keyfile is not None) and IMAP4_SSL_PORT or IMAP4_PORT
  1900. host = args[0]
  1901. USER = getpass.getuser()
  1902. data = open(os.path.exists("test.data") and "test.data" or __file__).read(1000)
  1903. test_mesg = 'From: %(user)s@localhost%(lf)sSubject: IMAP4 test%(lf)s%(lf)s%(data)s' \
  1904. % {'user':USER, 'lf':'\n', 'data':data}
  1905. test_seq1 = [
  1906. ('list', ('""', '""')),
  1907. ('list', ('""', '%')),
  1908. ('create', ('imaplib2_test0',)),
  1909. ('rename', ('imaplib2_test0', 'imaplib2_test1')),
  1910. ('CREATE', ('imaplib2_test2',)),
  1911. ('append', ('imaplib2_test2', None, None, test_mesg)),
  1912. ('list', ('', 'imaplib2_test%')),
  1913. ('select', ('imaplib2_test2',)),
  1914. ('search', (None, 'SUBJECT', 'IMAP4 test')),
  1915. ('fetch', ("'1:*'", '(FLAGS INTERNALDATE RFC822)')),
  1916. ('store', ('1', 'FLAGS', '(\Deleted)')),
  1917. ('namespace', ()),
  1918. ('expunge', ()),
  1919. ('recent', ()),
  1920. ('close', ()),
  1921. ]
  1922. test_seq2 = (
  1923. ('select', ()),
  1924. ('response', ('UIDVALIDITY',)),
  1925. ('response', ('EXISTS',)),
  1926. ('append', (None, None, None, test_mesg)),
  1927. ('examine', ()),
  1928. ('select', ()),
  1929. ('fetch', ("'1:*'", '(FLAGS UID)')),
  1930. ('examine', ()),
  1931. ('select', ()),
  1932. ('uid', ('SEARCH', 'SUBJECT', 'IMAP4 test')),
  1933. ('uid', ('SEARCH', 'ALL')),
  1934. ('uid', ('THREAD', 'references', 'UTF-8', '(SEEN)')),
  1935. ('recent', ()),
  1936. )
  1937. AsyncError, M = None, None
  1938. def responder(cb_arg_list):
  1939. response, cb_arg, error = cb_arg_list
  1940. global AsyncError
  1941. cmd, args = cb_arg
  1942. if error is not None:
  1943. AsyncError = error
  1944. M._log(0, '[cb] ERROR %s %.100s => %s' % (cmd, args, error))
  1945. return
  1946. typ, dat = response
  1947. M._log(0, '[cb] %s %.100s => %s %.100s' % (cmd, args, typ, dat))
  1948. if typ == 'NO':
  1949. AsyncError = (Exception, dat[0])
  1950. def run(cmd, args, cb=True):
  1951. if AsyncError:
  1952. M._log(1, 'AsyncError %s' % repr(AsyncError))
  1953. M.logout()
  1954. typ, val = AsyncError
  1955. raise typ(val)
  1956. if not M.debug: M._log(0, '%s %.100s' % (cmd, args))
  1957. try:
  1958. if cb:
  1959. typ, dat = getattr(M, cmd)(callback=responder, cb_arg=(cmd, args), *args)
  1960. M._log(1, '%s %.100s => %s %.100s' % (cmd, args, typ, dat))
  1961. else:
  1962. typ, dat = getattr(M, cmd)(*args)
  1963. M._log(1, '%s %.100s => %s %.100s' % (cmd, args, typ, dat))
  1964. except:
  1965. M._log(1, '%s - %s' % sys.exc_info()[:2])
  1966. M.logout()
  1967. raise
  1968. if typ == 'NO':
  1969. M._log(1, 'NO')
  1970. M.logout()
  1971. raise Exception(dat[0])
  1972. return dat
  1973. try:
  1974. threading.currentThread().setName('main')
  1975. if keyfile is not None:
  1976. if not keyfile: keyfile = None
  1977. if not certfile: certfile = None
  1978. M = IMAP4_SSL(host=host, port=port, keyfile=keyfile, certfile=certfile, ssl_version="tls1", debug=debug, identifier='', timeout=10, debug_buf_lvl=debug_buf_lvl, tls_level="tls_no_ssl")
  1979. elif stream_command:
  1980. M = IMAP4_stream(stream_command, debug=debug, identifier='', timeout=10, debug_buf_lvl=debug_buf_lvl)
  1981. else:
  1982. M = IMAP4(host=host, port=port, debug=debug, identifier='', timeout=10, debug_buf_lvl=debug_buf_lvl)
  1983. if M.state != 'AUTH': # Login needed
  1984. PASSWD = getpass.getpass("IMAP password for %s on %s: " % (USER, host or "localhost"))
  1985. test_seq1.insert(0, ('login', (USER, PASSWD)))
  1986. M._log(0, 'PROTOCOL_VERSION = %s' % M.PROTOCOL_VERSION)
  1987. if 'COMPRESS=DEFLATE' in M.capabilities:
  1988. M.enable_compression()
  1989. for cmd,args in test_seq1:
  1990. run(cmd, args)
  1991. for ml in run('list', ('', 'imaplib2_test%'), cb=False):
  1992. mo = re.match(r'.*"([^"]+)"$', ml)
  1993. if mo: path = mo.group(1)
  1994. else: path = ml.split()[-1]
  1995. run('delete', (path,))
  1996. if 'ID' in M.capabilities:
  1997. run('id', ())
  1998. run('id', ("(name imaplib2)",))
  1999. run('id', ("version", __version__, "os", os.uname()[0]))
  2000. for cmd,args in test_seq2:
  2001. if (cmd,args) != ('uid', ('SEARCH', 'SUBJECT', 'IMAP4 test')):
  2002. run(cmd, args)
  2003. continue
  2004. dat = run(cmd, args, cb=False)
  2005. uid = dat[-1].split()
  2006. if not uid: continue
  2007. run('uid', ('FETCH', uid[-1],
  2008. '(FLAGS INTERNALDATE RFC822.SIZE RFC822.HEADER RFC822.TEXT)'))
  2009. run('uid', ('STORE', uid[-1], 'FLAGS', '(\Deleted)'))
  2010. run('expunge', ())
  2011. if 'IDLE' in M.capabilities:
  2012. run('idle', (2,), cb=False)
  2013. run('idle', (99,)) # Asynchronous, to test interruption of 'idle' by 'noop'
  2014. time.sleep(1)
  2015. run('noop', (), cb=False)
  2016. run('append', (None, None, None, test_mesg), cb=False)
  2017. num = run('search', (None, 'ALL'), cb=False)[0].split()[0]
  2018. dat = run('fetch', (num, '(FLAGS INTERNALDATE RFC822)'), cb=False)
  2019. M._mesg('fetch %s => %s' % (num, repr(dat)))
  2020. run('idle', (2,))
  2021. run('store', (num, '-FLAGS', '(\Seen)'), cb=False),
  2022. dat = run('fetch', (num, '(FLAGS INTERNALDATE RFC822)'), cb=False)
  2023. M._mesg('fetch %s => %s' % (num, repr(dat)))
  2024. run('uid', ('STORE', num, 'FLAGS', '(\Deleted)'))
  2025. run('expunge', ())
  2026. if idle_intr:
  2027. M._mesg('HIT CTRL-C to interrupt IDLE')
  2028. try:
  2029. run('idle', (99,), cb=False) # Synchronous, to test interruption of 'idle' by INTR
  2030. except KeyboardInterrupt:
  2031. M._mesg('Thanks!')
  2032. M._mesg('')
  2033. raise
  2034. elif idle_intr:
  2035. M._mesg('chosen server does not report IDLE capability')
  2036. run('logout', (), cb=False)
  2037. if debug:
  2038. M._mesg('')
  2039. M._print_log()
  2040. M._mesg('')
  2041. M._mesg('unused untagged responses in order, most recent last:')
  2042. for typ,dat in M.pop_untagged_responses(): M._mesg('\t%s %s' % (typ, dat))
  2043. print('All tests OK.')
  2044. except:
  2045. if not idle_intr or M is None or not 'IDLE' in M.capabilities:
  2046. print('Tests failed.')
  2047. if not debug:
  2048. print('''
  2049. If you would like to see debugging output,
  2050. try: %s -d5
  2051. ''' % sys.argv[0])
  2052. raise