imap.el 106 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057
  1. ;;; imap.el --- imap library
  2. ;; Copyright (C) 1998-2012 Free Software Foundation, Inc.
  3. ;; Author: Simon Josefsson <simon@josefsson.org>
  4. ;; Keywords: mail
  5. ;; This file is part of GNU Emacs.
  6. ;; GNU Emacs is free software: you can redistribute it and/or modify
  7. ;; it under the terms of the GNU General Public License as published by
  8. ;; the Free Software Foundation, either version 3 of the License, or
  9. ;; (at your option) any later version.
  10. ;; GNU Emacs is distributed in the hope that it will be useful,
  11. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ;; GNU General Public License for more details.
  14. ;; You should have received a copy of the GNU General Public License
  15. ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
  16. ;;; Commentary:
  17. ;; imap.el is an elisp library providing an interface for talking to
  18. ;; IMAP servers.
  19. ;;
  20. ;; imap.el is roughly divided in two parts, one that parses IMAP
  21. ;; responses from the server and storing data into buffer-local
  22. ;; variables, and one for utility functions which send commands to
  23. ;; server, waits for an answer, and return information. The latter
  24. ;; part is layered on top of the previous.
  25. ;;
  26. ;; The imap.el API consist of the following functions, other functions
  27. ;; in this file should not be called directly and the result of doing
  28. ;; so are at best undefined.
  29. ;;
  30. ;; Global commands:
  31. ;;
  32. ;; imap-open, imap-opened, imap-authenticate, imap-close,
  33. ;; imap-capability, imap-namespace, imap-error-text
  34. ;;
  35. ;; Mailbox commands:
  36. ;;
  37. ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
  38. ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
  39. ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
  40. ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
  41. ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
  42. ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
  43. ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
  44. ;;
  45. ;; Message commands:
  46. ;;
  47. ;; imap-fetch-asynch, imap-fetch,
  48. ;; imap-current-message, imap-list-to-message-set,
  49. ;; imap-message-get, imap-message-map
  50. ;; imap-message-envelope-date, imap-message-envelope-subject,
  51. ;; imap-message-envelope-from, imap-message-envelope-sender,
  52. ;; imap-message-envelope-reply-to, imap-message-envelope-to,
  53. ;; imap-message-envelope-cc, imap-message-envelope-bcc
  54. ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
  55. ;; imap-message-body, imap-message-flag-permanent-p
  56. ;; imap-message-flags-set, imap-message-flags-del
  57. ;; imap-message-flags-add, imap-message-copyuid
  58. ;; imap-message-copy, imap-message-appenduid
  59. ;; imap-message-append, imap-envelope-from
  60. ;; imap-body-lines
  61. ;;
  62. ;; It is my hope that these commands should be pretty self
  63. ;; explanatory for someone that know IMAP. All functions have
  64. ;; additional documentation on how to invoke them.
  65. ;;
  66. ;; imap.el supports RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1). The implemented
  67. ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
  68. ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
  69. ;; LOGINDISABLED) (with use of external library starttls.el and
  70. ;; program starttls), and the GSSAPI / Kerberos V4 sections of RFC1731
  71. ;; (with use of external program `imtest'), and RFC2971 (ID). It also
  72. ;; takes advantage of the UNSELECT extension in Cyrus IMAPD.
  73. ;;
  74. ;; Without the work of John McClary Prevost and Jim Radford this library
  75. ;; would not have seen the light of day. Many thanks.
  76. ;;
  77. ;; This is a transcript of a short interactive session for demonstration
  78. ;; purposes.
  79. ;;
  80. ;; (imap-open "my.mail.server")
  81. ;; => " *imap* my.mail.server:0"
  82. ;;
  83. ;; The rest are invoked with current buffer as the buffer returned by
  84. ;; `imap-open'. It is possible to do it all without this, but it would
  85. ;; look ugly here since `buffer' is always the last argument for all
  86. ;; imap.el API functions.
  87. ;;
  88. ;; (imap-authenticate "myusername" "mypassword")
  89. ;; => auth
  90. ;;
  91. ;; (imap-mailbox-lsub "*")
  92. ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
  93. ;;
  94. ;; (imap-mailbox-list "INBOX.n%")
  95. ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
  96. ;;
  97. ;; (imap-mailbox-select "INBOX.nnimap")
  98. ;; => "INBOX.nnimap"
  99. ;;
  100. ;; (imap-mailbox-get 'exists)
  101. ;; => 166
  102. ;;
  103. ;; (imap-mailbox-get 'uidvalidity)
  104. ;; => "908992622"
  105. ;;
  106. ;; (imap-search "FLAGGED SINCE 18-DEC-98")
  107. ;; => (235 236)
  108. ;;
  109. ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
  110. ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
  111. ;;
  112. ;; Todo:
  113. ;;
  114. ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
  115. ;; Use IEEE floats (which are effectively exact)? -- fx
  116. ;; o Don't use `read' at all (important places already fixed)
  117. ;; o Accept list of articles instead of message set string in most
  118. ;; imap-message-* functions.
  119. ;; o Send strings as literal if they contain, e.g., ".
  120. ;;
  121. ;; Revision history:
  122. ;;
  123. ;; - 19991218 added starttls/digest-md5 patch,
  124. ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
  125. ;; NB! you need SLIM for starttls.el and digest-md5.el
  126. ;; - 19991023 committed to pgnus
  127. ;;
  128. ;;; Code:
  129. (eval-when-compile (require 'cl))
  130. (eval-and-compile
  131. ;; For Emacs <22.2 and XEmacs.
  132. (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
  133. (autoload 'starttls-open-stream "starttls")
  134. (autoload 'starttls-negotiate "starttls")
  135. (autoload 'sasl-find-mechanism "sasl")
  136. (autoload 'digest-md5-parse-digest-challenge "digest-md5")
  137. (autoload 'digest-md5-digest-response "digest-md5")
  138. (autoload 'digest-md5-digest-uri "digest-md5")
  139. (autoload 'digest-md5-challenge "digest-md5")
  140. (autoload 'rfc2104-hash "rfc2104")
  141. (autoload 'utf7-encode "utf7")
  142. (autoload 'utf7-decode "utf7")
  143. (autoload 'format-spec "format-spec")
  144. (autoload 'format-spec-make "format-spec")
  145. (autoload 'open-tls-stream "tls"))
  146. ;; User variables.
  147. (defgroup imap nil
  148. "Low-level IMAP issues."
  149. :version "21.1"
  150. :group 'mail)
  151. (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
  152. "imtest -kp %s %p")
  153. "List of strings containing commands for Kerberos 4 authentication.
  154. %s is replaced with server hostname, %p with port to connect to, and
  155. %l with the value of `imap-default-user'. The program should accept
  156. IMAP commands on stdin and return responses to stdout. Each entry in
  157. the list is tried until a successful connection is made."
  158. :group 'imap
  159. :type '(repeat string))
  160. (defcustom imap-gssapi-program (list
  161. (concat "gsasl %s %p "
  162. "--mechanism GSSAPI "
  163. "--authentication-id %l")
  164. "imtest -m gssapi -u %l -p %p %s")
  165. "List of strings containing commands for GSSAPI (krb5) authentication.
  166. %s is replaced with server hostname, %p with port to connect to, and
  167. %l with the value of `imap-default-user'. The program should accept
  168. IMAP commands on stdin and return responses to stdout. Each entry in
  169. the list is tried until a successful connection is made."
  170. :group 'imap
  171. :type '(repeat string))
  172. (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
  173. "openssl s_client -quiet -ssl2 -connect %s:%p"
  174. "s_client -quiet -ssl3 -connect %s:%p"
  175. "s_client -quiet -ssl2 -connect %s:%p")
  176. "A string, or list of strings, containing commands for SSL connections.
  177. Within a string, %s is replaced with the server address and %p with
  178. port number on server. The program should accept IMAP commands on
  179. stdin and return responses to stdout. Each entry in the list is tried
  180. until a successful connection is made."
  181. :group 'imap
  182. :type '(choice string
  183. (repeat string)))
  184. (defcustom imap-shell-program '("ssh %s imapd"
  185. "rsh %s imapd"
  186. "ssh %g ssh %s imapd"
  187. "rsh %g rsh %s imapd")
  188. "A list of strings, containing commands for IMAP connection.
  189. Within a string, %s is replaced with the server address, %p with port
  190. number on server, %g with `imap-shell-host', and %l with
  191. `imap-default-user'. The program should read IMAP commands from stdin
  192. and write IMAP response to stdout. Each entry in the list is tried
  193. until a successful connection is made."
  194. :group 'imap
  195. :type '(repeat string))
  196. (defcustom imap-process-connection-type nil
  197. "Value for `process-connection-type' to use for Kerberos4, GSSAPI, shell, and SSL.
  198. The `process-connection-type' variable controls the type of device
  199. used to communicate with subprocesses. Values are nil to use a
  200. pipe, or t or `pty' to use a pty. The value has no effect if the
  201. system has no ptys or if all ptys are busy: then a pipe is used
  202. in any case. The value takes effect when an IMAP server is
  203. opened; changing it after that has no effect."
  204. :version "22.1"
  205. :group 'imap
  206. :type 'boolean)
  207. (defcustom imap-use-utf7 t
  208. "If non-nil, do utf7 encoding/decoding of mailbox names.
  209. Since the UTF7 decoding currently only decodes into ISO-8859-1
  210. characters, you may disable this decoding if you need to access UTF7
  211. encoded mailboxes which doesn't translate into ISO-8859-1."
  212. :group 'imap
  213. :type 'boolean)
  214. (defcustom imap-log nil
  215. "If non-nil, an imap session trace is placed in `imap-log-buffer'.
  216. Note that username, passwords and other privacy sensitive
  217. information (such as e-mail) may be stored in the buffer.
  218. It is not written to disk, however. Do not enable this
  219. variable unless you are comfortable with that.
  220. See also `imap-debug'."
  221. :group 'imap
  222. :type 'boolean)
  223. (defcustom imap-debug nil
  224. "If non-nil, trace imap- functions into `imap-debug-buffer'.
  225. Uses `trace-function-background', so you can turn it off with,
  226. say, `untrace-all'.
  227. Note that username, passwords and other privacy sensitive
  228. information (such as e-mail) may be stored in the buffer.
  229. It is not written to disk, however. Do not enable this
  230. variable unless you are comfortable with that.
  231. This variable only takes effect when loading the `imap' library.
  232. See also `imap-log'."
  233. :group 'imap
  234. :type 'boolean)
  235. (defcustom imap-shell-host "gateway"
  236. "Hostname of rlogin proxy."
  237. :group 'imap
  238. :type 'string)
  239. (defcustom imap-default-user (user-login-name)
  240. "Default username to use."
  241. :group 'imap
  242. :type 'string)
  243. (defcustom imap-read-timeout (if (string-match
  244. "windows-nt\\|os/2\\|cygwin"
  245. (symbol-name system-type))
  246. 1.0
  247. 0.1)
  248. "How long to wait between checking for the end of output.
  249. Shorter values mean quicker response, but is more CPU intensive."
  250. :type 'number
  251. :group 'imap)
  252. (defcustom imap-store-password nil
  253. "If non-nil, store session password without prompting."
  254. :group 'imap
  255. :type 'boolean)
  256. ;; Various variables.
  257. (defvar imap-fetch-data-hook nil
  258. "Hooks called after receiving each FETCH response.")
  259. (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
  260. "Priority of streams to consider when opening connection to server.")
  261. (defvar imap-stream-alist
  262. '((gssapi imap-gssapi-stream-p imap-gssapi-open)
  263. (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
  264. (tls imap-tls-p imap-tls-open)
  265. (ssl imap-ssl-p imap-ssl-open)
  266. (network imap-network-p imap-network-open)
  267. (shell imap-shell-p imap-shell-open)
  268. (starttls imap-starttls-p imap-starttls-open))
  269. "Definition of network streams.
  270. \(NAME CHECK OPEN)
  271. NAME names the stream, CHECK is a function returning non-nil if the
  272. server support the stream and OPEN is a function for opening the
  273. stream.")
  274. (defvar imap-authenticators '(gssapi
  275. kerberos4
  276. digest-md5
  277. cram-md5
  278. ;;sasl
  279. login
  280. anonymous)
  281. "Priority of authenticators to consider when authenticating to server.")
  282. (defvar imap-authenticator-alist
  283. '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
  284. (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
  285. (sasl imap-sasl-auth-p imap-sasl-auth)
  286. (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
  287. (login imap-login-p imap-login-auth)
  288. (anonymous imap-anonymous-p imap-anonymous-auth)
  289. (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
  290. "Definition of authenticators.
  291. \(NAME CHECK AUTHENTICATE)
  292. NAME names the authenticator. CHECK is a function returning non-nil if
  293. the server support the authenticator and AUTHENTICATE is a function
  294. for doing the actual authentication.")
  295. (defvar imap-error nil
  296. "Error codes from the last command.")
  297. (defvar imap-logout-timeout nil
  298. "Close server immediately if it can't logout in this number of seconds.
  299. If it is nil, never close server until logout completes. Normally,
  300. the value of this variable will be bound to a certain value to which
  301. an application program that uses this module specifies on a per-server
  302. basis.")
  303. ;; Internal constants. Change these and die.
  304. (defconst imap-default-port 143)
  305. (defconst imap-default-ssl-port 993)
  306. (defconst imap-default-tls-port 993)
  307. (defconst imap-default-stream 'network)
  308. (defconst imap-coding-system-for-read 'binary)
  309. (defconst imap-coding-system-for-write 'binary)
  310. (defconst imap-local-variables '(imap-server
  311. imap-port
  312. imap-client-eol
  313. imap-server-eol
  314. imap-auth
  315. imap-stream
  316. imap-username
  317. imap-password
  318. imap-current-mailbox
  319. imap-current-target-mailbox
  320. imap-message-data
  321. imap-capability
  322. imap-id
  323. imap-namespace
  324. imap-state
  325. imap-reached-tag
  326. imap-failed-tags
  327. imap-tag
  328. imap-process
  329. imap-calculate-literal-size-first
  330. imap-mailbox-data))
  331. (defconst imap-log-buffer "*imap-log*")
  332. (defconst imap-debug-buffer "*imap-debug*")
  333. ;; Internal variables.
  334. (defvar imap-stream nil)
  335. (defvar imap-auth nil)
  336. (defvar imap-server nil)
  337. (defvar imap-port nil)
  338. (defvar imap-username nil)
  339. (defvar imap-password nil)
  340. (defvar imap-last-authenticator nil)
  341. (defvar imap-calculate-literal-size-first nil)
  342. (defvar imap-state 'closed
  343. "IMAP state.
  344. Valid states are `closed', `initial', `nonauth', `auth', `selected'
  345. and `examine'.")
  346. (defvar imap-server-eol "\r\n"
  347. "The EOL string sent from the server.")
  348. (defvar imap-client-eol "\r\n"
  349. "The EOL string we send to the server.")
  350. (defvar imap-current-mailbox nil
  351. "Current mailbox name.")
  352. (defvar imap-current-target-mailbox nil
  353. "Current target mailbox for COPY and APPEND commands.")
  354. (defvar imap-mailbox-data nil
  355. "Obarray with mailbox data.")
  356. (defvar imap-mailbox-prime 997
  357. "Length of `imap-mailbox-data'.")
  358. (defvar imap-current-message nil
  359. "Current message number.")
  360. (defvar imap-message-data nil
  361. "Obarray with message data.")
  362. (defvar imap-message-prime 997
  363. "Length of `imap-message-data'.")
  364. (defvar imap-capability nil
  365. "Capability for server.")
  366. (defvar imap-id nil
  367. "Identity of server.
  368. See RFC 2971.")
  369. (defvar imap-namespace nil
  370. "Namespace for current server.")
  371. (defvar imap-reached-tag 0
  372. "Lower limit on command tags that have been parsed.")
  373. (defvar imap-failed-tags nil
  374. "Alist of tags that failed.
  375. Each element is a list with four elements; tag (a integer), response
  376. state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
  377. human readable response text (a string).")
  378. (defvar imap-tag 0
  379. "Command tag number.")
  380. (defvar imap-process nil
  381. "Process.")
  382. (defvar imap-continuation nil
  383. "Non-nil indicates that the server emitted a continuation request.
  384. The actual value is really the text on the continuation line.")
  385. (defvar imap-callbacks nil
  386. "List of response tags and callbacks, on the form `(number . function)'.
  387. The function should take two arguments, the first the IMAP tag and the
  388. second the status (OK, NO, BAD etc) of the command.")
  389. (defvar imap-enable-exchange-bug-workaround nil
  390. "Send FETCH UID commands as *:* instead of *.
  391. When non-nil, use an alternative UIDS form. Enabling appears to
  392. be required for some servers (e.g., Microsoft Exchange 2007)
  393. which otherwise would trigger a response 'BAD The specified
  394. message set is invalid.'. We don't unconditionally use this
  395. form, since this is said to be significantly inefficient.
  396. This variable is set to t automatically per server if the
  397. canonical form fails.")
  398. ;; Utility functions:
  399. (defun imap-remassoc (key alist)
  400. "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
  401. The modified ALIST is returned. If the first member
  402. of ALIST has a car that is `equal' to KEY, there is no way to remove it
  403. by side effect; therefore, write `(setq foo (remassoc key foo))' to be
  404. sure of changing the value of `foo'."
  405. (when alist
  406. (if (equal key (caar alist))
  407. (cdr alist)
  408. (setcdr alist (imap-remassoc key (cdr alist)))
  409. alist)))
  410. (defmacro imap-disable-multibyte ()
  411. "Enable multibyte in the current buffer."
  412. (unless (featurep 'xemacs)
  413. '(set-buffer-multibyte nil)))
  414. (defsubst imap-utf7-encode (string)
  415. (if imap-use-utf7
  416. (and string
  417. (condition-case ()
  418. (utf7-encode string t)
  419. (error (message
  420. "imap: Could not UTF7 encode `%s', using it unencoded..."
  421. string)
  422. string)))
  423. string))
  424. (defsubst imap-utf7-decode (string)
  425. (if imap-use-utf7
  426. (and string
  427. (condition-case ()
  428. (utf7-decode string t)
  429. (error (message
  430. "imap: Could not UTF7 decode `%s', using it undecoded..."
  431. string)
  432. string)))
  433. string))
  434. (defsubst imap-ok-p (status)
  435. (if (eq status 'OK)
  436. t
  437. (setq imap-error status)
  438. nil))
  439. (defun imap-error-text (&optional buffer)
  440. (with-current-buffer (or buffer (current-buffer))
  441. (nth 3 (car imap-failed-tags))))
  442. ;; Server functions; stream stuff:
  443. (defun imap-log (string-or-buffer)
  444. (when imap-log
  445. (with-current-buffer (get-buffer-create imap-log-buffer)
  446. (imap-disable-multibyte)
  447. (buffer-disable-undo)
  448. (goto-char (point-max))
  449. (if (bufferp string-or-buffer)
  450. (insert-buffer-substring string-or-buffer)
  451. (insert string-or-buffer)))))
  452. (defun imap-kerberos4-stream-p (buffer)
  453. (imap-capability 'AUTH=KERBEROS_V4 buffer))
  454. (defun imap-kerberos4-open (name buffer server port)
  455. (let ((cmds imap-kerberos4-program)
  456. cmd done)
  457. (while (and (not done) (setq cmd (pop cmds)))
  458. (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
  459. (erase-buffer)
  460. (let* ((port (or port imap-default-port))
  461. (coding-system-for-read imap-coding-system-for-read)
  462. (coding-system-for-write imap-coding-system-for-write)
  463. (process-connection-type imap-process-connection-type)
  464. (process (start-process
  465. name buffer shell-file-name shell-command-switch
  466. (format-spec
  467. cmd
  468. (format-spec-make
  469. ?s server
  470. ?p (number-to-string port)
  471. ?l imap-default-user))))
  472. response)
  473. (when process
  474. (with-current-buffer buffer
  475. (setq imap-client-eol "\n"
  476. imap-calculate-literal-size-first t)
  477. (while (and (memq (process-status process) '(open run))
  478. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  479. (goto-char (point-min))
  480. ;; Athena IMTEST can output SSL verify errors
  481. (or (while (looking-at "^verify error:num=")
  482. (forward-line))
  483. t)
  484. (or (while (looking-at "^TLS connection established")
  485. (forward-line))
  486. t)
  487. ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
  488. (or (while (looking-at "^C:")
  489. (forward-line))
  490. t)
  491. ;; cyrus 1.6 imtest print "S: " before server greeting
  492. (or (not (looking-at "S: "))
  493. (forward-char 3)
  494. t)
  495. (not (and (imap-parse-greeting)
  496. ;; success in imtest < 1.6:
  497. (or (re-search-forward
  498. "^__\\(.*\\)__\n" nil t)
  499. ;; success in imtest 1.6:
  500. (re-search-forward
  501. "^\\(Authenticat.*\\)" nil t))
  502. (setq response (match-string 1)))))
  503. (accept-process-output process 1)
  504. (sit-for 1))
  505. (erase-buffer)
  506. (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
  507. (if response (concat "done, " response) "failed"))
  508. (if (and response (let ((case-fold-search nil))
  509. (not (string-match "failed" response))))
  510. (setq done process)
  511. (if (memq (process-status process) '(open run))
  512. (imap-logout))
  513. (delete-process process)
  514. nil)))))
  515. done))
  516. (defun imap-gssapi-stream-p (buffer)
  517. (imap-capability 'AUTH=GSSAPI buffer))
  518. (defun imap-gssapi-open (name buffer server port)
  519. (let ((cmds imap-gssapi-program)
  520. cmd done)
  521. (while (and (not done) (setq cmd (pop cmds)))
  522. (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
  523. (erase-buffer)
  524. (let* ((port (or port imap-default-port))
  525. (coding-system-for-read imap-coding-system-for-read)
  526. (coding-system-for-write imap-coding-system-for-write)
  527. (process-connection-type imap-process-connection-type)
  528. (process (start-process
  529. name buffer shell-file-name shell-command-switch
  530. (format-spec
  531. cmd
  532. (format-spec-make
  533. ?s server
  534. ?p (number-to-string port)
  535. ?l imap-default-user))))
  536. response)
  537. (when process
  538. (with-current-buffer buffer
  539. (setq imap-client-eol "\n"
  540. imap-calculate-literal-size-first t)
  541. (while (and (memq (process-status process) '(open run))
  542. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  543. (goto-char (point-min))
  544. ;; Athena IMTEST can output SSL verify errors
  545. (or (while (looking-at "^verify error:num=")
  546. (forward-line))
  547. t)
  548. (or (while (looking-at "^TLS connection established")
  549. (forward-line))
  550. t)
  551. ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
  552. (or (while (looking-at "^C:")
  553. (forward-line))
  554. t)
  555. ;; cyrus 1.6 imtest print "S: " before server greeting
  556. (or (not (looking-at "S: "))
  557. (forward-char 3)
  558. t)
  559. ;; GNU SASL may print 'Trying ...' first.
  560. (or (not (looking-at "Trying "))
  561. (forward-line)
  562. t)
  563. (not (and (imap-parse-greeting)
  564. ;; success in imtest 1.6:
  565. (re-search-forward
  566. (concat "^\\(\\(Authenticat.*\\)\\|\\("
  567. "Client authentication "
  568. "finished.*\\)\\)")
  569. nil t)
  570. (setq response (match-string 1)))))
  571. (accept-process-output process 1)
  572. (sit-for 1))
  573. (imap-log buffer)
  574. (erase-buffer)
  575. (message "GSSAPI IMAP connection: %s" (or response "failed"))
  576. (if (and response (let ((case-fold-search nil))
  577. (not (string-match "failed" response))))
  578. (setq done process)
  579. (if (memq (process-status process) '(open run))
  580. (imap-logout))
  581. (delete-process process)
  582. nil)))))
  583. done))
  584. (defun imap-ssl-p (buffer)
  585. nil)
  586. (defun imap-ssl-open (name buffer server port)
  587. "Open an SSL connection to SERVER."
  588. (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
  589. (list imap-ssl-program)))
  590. cmd done)
  591. (while (and (not done) (setq cmd (pop cmds)))
  592. (message "imap: Opening SSL connection with `%s'..." cmd)
  593. (erase-buffer)
  594. (let* ((port (or port imap-default-ssl-port))
  595. (coding-system-for-read imap-coding-system-for-read)
  596. (coding-system-for-write imap-coding-system-for-write)
  597. (process-connection-type imap-process-connection-type)
  598. (set-process-query-on-exit-flag
  599. (if (fboundp 'set-process-query-on-exit-flag)
  600. 'set-process-query-on-exit-flag
  601. 'process-kill-without-query))
  602. process)
  603. (when (progn
  604. (setq process (start-process
  605. name buffer shell-file-name
  606. shell-command-switch
  607. (format-spec cmd
  608. (format-spec-make
  609. ?s server
  610. ?p (number-to-string port)))))
  611. (funcall set-process-query-on-exit-flag process nil)
  612. process)
  613. (with-current-buffer buffer
  614. (goto-char (point-min))
  615. (while (and (memq (process-status process) '(open run))
  616. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  617. (goto-char (point-max))
  618. (forward-line -1)
  619. (not (imap-parse-greeting)))
  620. (accept-process-output process 1)
  621. (sit-for 1))
  622. (imap-log buffer)
  623. (erase-buffer)
  624. (when (memq (process-status process) '(open run))
  625. (setq done process))))))
  626. (if done
  627. (progn
  628. (message "imap: Opening SSL connection with `%s'...done" cmd)
  629. done)
  630. (message "imap: Opening SSL connection with `%s'...failed" cmd)
  631. nil)))
  632. (defun imap-tls-p (buffer)
  633. nil)
  634. (defun imap-tls-open (name buffer server port)
  635. (let* ((port (or port imap-default-tls-port))
  636. (coding-system-for-read imap-coding-system-for-read)
  637. (coding-system-for-write imap-coding-system-for-write)
  638. (process (open-tls-stream name buffer server port)))
  639. (when process
  640. (while (and (memq (process-status process) '(open run))
  641. ;; FIXME: Per the "blue moon" comment, the process/buffer
  642. ;; handling here, and elsewhere in functions which open
  643. ;; streams, looks confused. Obviously we can change buffers
  644. ;; if a different process handler kicks in from
  645. ;; `accept-process-output' or `sit-for' below, and TRT seems
  646. ;; to be to `save-buffer' around those calls. (I wonder why
  647. ;; `sit-for' is used with a non-zero wait.) -- fx
  648. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  649. (goto-char (point-max))
  650. (forward-line -1)
  651. (not (imap-parse-greeting)))
  652. (accept-process-output process 1)
  653. (sit-for 1))
  654. (imap-log buffer)
  655. (when (memq (process-status process) '(open run))
  656. process))))
  657. (defun imap-network-p (buffer)
  658. t)
  659. (defun imap-network-open (name buffer server port)
  660. (let* ((port (or port imap-default-port))
  661. (coding-system-for-read imap-coding-system-for-read)
  662. (coding-system-for-write imap-coding-system-for-write)
  663. (process (open-network-stream name buffer server port)))
  664. (when process
  665. (while (and (memq (process-status process) '(open run))
  666. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  667. (goto-char (point-min))
  668. (not (imap-parse-greeting)))
  669. (accept-process-output process 1)
  670. (sit-for 1))
  671. (imap-log buffer)
  672. (when (memq (process-status process) '(open run))
  673. process))))
  674. (defun imap-shell-p (buffer)
  675. nil)
  676. (defun imap-shell-open (name buffer server port)
  677. (let ((cmds (if (listp imap-shell-program) imap-shell-program
  678. (list imap-shell-program)))
  679. cmd done)
  680. (while (and (not done) (setq cmd (pop cmds)))
  681. (message "imap: Opening IMAP connection with `%s'..." cmd)
  682. (setq imap-client-eol "\n")
  683. (let* ((port (or port imap-default-port))
  684. (coding-system-for-read imap-coding-system-for-read)
  685. (coding-system-for-write imap-coding-system-for-write)
  686. (process-connection-type imap-process-connection-type)
  687. (process (start-process
  688. name buffer shell-file-name shell-command-switch
  689. (format-spec
  690. cmd
  691. (format-spec-make
  692. ?s server
  693. ?g imap-shell-host
  694. ?p (number-to-string port)
  695. ?l imap-default-user)))))
  696. (when process
  697. (while (and (memq (process-status process) '(open run))
  698. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  699. (goto-char (point-max))
  700. (forward-line -1)
  701. (not (imap-parse-greeting)))
  702. (accept-process-output process 1)
  703. (sit-for 1))
  704. (imap-log buffer)
  705. (erase-buffer)
  706. (when (memq (process-status process) '(open run))
  707. (setq done process)))))
  708. (if done
  709. (progn
  710. (message "imap: Opening IMAP connection with `%s'...done" cmd)
  711. done)
  712. (message "imap: Opening IMAP connection with `%s'...failed" cmd)
  713. nil)))
  714. (defun imap-starttls-p (buffer)
  715. (imap-capability 'STARTTLS buffer))
  716. (defun imap-starttls-open (name buffer server port)
  717. (let* ((port (or port imap-default-port))
  718. (coding-system-for-read imap-coding-system-for-read)
  719. (coding-system-for-write imap-coding-system-for-write)
  720. (process (starttls-open-stream name buffer server port))
  721. done tls-info)
  722. (message "imap: Connecting with STARTTLS...")
  723. (when process
  724. (while (and (memq (process-status process) '(open run))
  725. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  726. (goto-char (point-max))
  727. (forward-line -1)
  728. (not (imap-parse-greeting)))
  729. (accept-process-output process 1)
  730. (sit-for 1))
  731. (imap-send-command "STARTTLS")
  732. (while (and (memq (process-status process) '(open run))
  733. (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
  734. (goto-char (point-max))
  735. (forward-line -1)
  736. (not (re-search-forward "[0-9]+ OK.*\r?\n" nil t)))
  737. (accept-process-output process 1)
  738. (sit-for 1))
  739. (imap-log buffer)
  740. (when (and (setq tls-info (starttls-negotiate process))
  741. (memq (process-status process) '(open run)))
  742. (setq done process)))
  743. (if (stringp tls-info)
  744. (message "imap: STARTTLS info: %s" tls-info))
  745. (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
  746. done))
  747. ;; Server functions; authenticator stuff:
  748. (defun imap-interactive-login (buffer loginfunc)
  749. "Login to server in BUFFER.
  750. LOGINFUNC is passed a username and a password, it should return t if
  751. it where successful authenticating itself to the server, nil otherwise.
  752. Returns t if login was successful, nil otherwise."
  753. (with-current-buffer buffer
  754. (make-local-variable 'imap-username)
  755. (make-local-variable 'imap-password)
  756. (let (user passwd ret)
  757. ;; (condition-case ()
  758. (while (or (not user) (not passwd))
  759. (setq user (or imap-username
  760. (read-from-minibuffer
  761. (concat "imap: username for " imap-server
  762. " (using stream `" (symbol-name imap-stream)
  763. "'): ")
  764. (or user imap-default-user))))
  765. (setq passwd (or imap-password
  766. (read-passwd
  767. (concat "imap: password for " user "@"
  768. imap-server " (using authenticator `"
  769. (symbol-name imap-auth) "'): "))))
  770. (when (and user passwd)
  771. (if (funcall loginfunc user passwd)
  772. (progn
  773. (message "imap: Login successful...")
  774. (setq ret t
  775. imap-username user)
  776. (when (and (not imap-password)
  777. (or imap-store-password
  778. (y-or-n-p "imap: Store password for this IMAP session? ")))
  779. (setq imap-password passwd)))
  780. (message "imap: Login failed...")
  781. (setq passwd nil)
  782. (setq imap-password nil)
  783. (sit-for 1))))
  784. ;; (quit (with-current-buffer buffer
  785. ;; (setq user nil
  786. ;; passwd nil)))
  787. ;; (error (with-current-buffer buffer
  788. ;; (setq user nil
  789. ;; passwd nil))))
  790. ret)))
  791. (defun imap-gssapi-auth-p (buffer)
  792. (eq imap-stream 'gssapi))
  793. (defun imap-gssapi-auth (buffer)
  794. (message "imap: Authenticating using GSSAPI...%s"
  795. (if (eq imap-stream 'gssapi) "done" "failed"))
  796. (eq imap-stream 'gssapi))
  797. (defun imap-kerberos4-auth-p (buffer)
  798. (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
  799. (eq imap-stream 'kerberos4)))
  800. (defun imap-kerberos4-auth (buffer)
  801. (message "imap: Authenticating using Kerberos 4...%s"
  802. (if (eq imap-stream 'kerberos4) "done" "failed"))
  803. (eq imap-stream 'kerberos4))
  804. (defun imap-cram-md5-p (buffer)
  805. (imap-capability 'AUTH=CRAM-MD5 buffer))
  806. (defun imap-cram-md5-auth (buffer)
  807. "Login to server using the AUTH CRAM-MD5 method."
  808. (message "imap: Authenticating using CRAM-MD5...")
  809. (let ((done (imap-interactive-login
  810. buffer
  811. (lambda (user passwd)
  812. (imap-ok-p
  813. (imap-send-command-wait
  814. (list
  815. "AUTHENTICATE CRAM-MD5"
  816. (lambda (challenge)
  817. (let* ((decoded (base64-decode-string challenge))
  818. (hash (rfc2104-hash 'md5 64 16 passwd decoded))
  819. (response (concat user " " hash))
  820. (encoded (base64-encode-string response)))
  821. encoded)))))))))
  822. (if done
  823. (message "imap: Authenticating using CRAM-MD5...done")
  824. (message "imap: Authenticating using CRAM-MD5...failed"))))
  825. (defun imap-login-p (buffer)
  826. (and (not (imap-capability 'LOGINDISABLED buffer))
  827. (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
  828. (defun imap-quote-specials (string)
  829. (with-temp-buffer
  830. (insert string)
  831. (goto-char (point-min))
  832. (while (re-search-forward "[\\\"]" nil t)
  833. (forward-char -1)
  834. (insert "\\")
  835. (forward-char 1))
  836. (buffer-string)))
  837. (defun imap-login-auth (buffer)
  838. "Login to server using the LOGIN command."
  839. (message "imap: Plaintext authentication...")
  840. (imap-interactive-login buffer
  841. (lambda (user passwd)
  842. (imap-ok-p (imap-send-command-wait
  843. (concat "LOGIN \""
  844. (imap-quote-specials user)
  845. "\" \""
  846. (imap-quote-specials passwd)
  847. "\""))))))
  848. (defun imap-anonymous-p (buffer)
  849. t)
  850. (defun imap-anonymous-auth (buffer)
  851. (message "imap: Logging in anonymously...")
  852. (with-current-buffer buffer
  853. (imap-ok-p (imap-send-command-wait
  854. (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
  855. (system-name)) "\"")))))
  856. ;;; Compiler directives.
  857. (defvar imap-sasl-client)
  858. (defvar imap-sasl-step)
  859. (defun imap-sasl-make-mechanisms (buffer)
  860. (let ((mecs '()))
  861. (mapc (lambda (sym)
  862. (let ((name (symbol-name sym)))
  863. (if (and (> (length name) 5)
  864. (string-equal "AUTH=" (substring name 0 5 )))
  865. (setq mecs (cons (substring name 5) mecs)))))
  866. (imap-capability nil buffer))
  867. mecs))
  868. (declare-function sasl-find-mechanism "sasl" (mechanism))
  869. (declare-function sasl-mechanism-name "sasl" (mechanism))
  870. (declare-function sasl-make-client "sasl" (mechanism name service server))
  871. (declare-function sasl-next-step "sasl" (client step))
  872. (declare-function sasl-step-data "sasl" (step))
  873. (declare-function sasl-step-set-data "sasl" (step data))
  874. (defun imap-sasl-auth-p (buffer)
  875. (and (condition-case ()
  876. (require 'sasl)
  877. (error nil))
  878. (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
  879. (defun imap-sasl-auth (buffer)
  880. "Login to server using the SASL method."
  881. (message "imap: Authenticating using SASL...")
  882. (with-current-buffer buffer
  883. (make-local-variable 'imap-username)
  884. (make-local-variable 'imap-sasl-client)
  885. (make-local-variable 'imap-sasl-step)
  886. (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
  887. logged user)
  888. (while (not logged)
  889. (setq user (or imap-username
  890. (read-from-minibuffer
  891. (concat "IMAP username for " imap-server " using SASL "
  892. (sasl-mechanism-name mechanism) ": ")
  893. (or user imap-default-user))))
  894. (when user
  895. (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
  896. imap-sasl-step (sasl-next-step imap-sasl-client nil))
  897. (let ((tag (imap-send-command
  898. (if (sasl-step-data imap-sasl-step)
  899. (format "AUTHENTICATE %s %s"
  900. (sasl-mechanism-name mechanism)
  901. (sasl-step-data imap-sasl-step))
  902. (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
  903. buffer)))
  904. (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
  905. (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
  906. (setq imap-continuation nil
  907. imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
  908. (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
  909. (base64-encode-string (sasl-step-data imap-sasl-step) t)
  910. "")))
  911. (if (imap-ok-p (imap-wait-for-tag tag))
  912. (setq imap-username user
  913. logged t)
  914. (message "Login failed...")
  915. (sit-for 1)))))
  916. logged)))
  917. (defun imap-digest-md5-p (buffer)
  918. (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
  919. (condition-case ()
  920. (require 'digest-md5)
  921. (error nil))))
  922. (defun imap-digest-md5-auth (buffer)
  923. "Login to server using the AUTH DIGEST-MD5 method."
  924. (message "imap: Authenticating using DIGEST-MD5...")
  925. (imap-interactive-login
  926. buffer
  927. (lambda (user passwd)
  928. (let ((tag
  929. (imap-send-command
  930. (list
  931. "AUTHENTICATE DIGEST-MD5"
  932. (lambda (challenge)
  933. (digest-md5-parse-digest-challenge
  934. (base64-decode-string challenge))
  935. (let* ((digest-uri
  936. (digest-md5-digest-uri
  937. "imap" (digest-md5-challenge 'realm)))
  938. (response
  939. (digest-md5-digest-response
  940. user passwd digest-uri)))
  941. (base64-encode-string response 'no-line-break))))
  942. )))
  943. (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
  944. nil
  945. (setq imap-continuation nil)
  946. (imap-send-command-1 "")
  947. (imap-ok-p (imap-wait-for-tag tag)))))))
  948. ;; Server functions:
  949. (defun imap-open-1 (buffer)
  950. (with-current-buffer buffer
  951. (erase-buffer)
  952. (setq imap-current-mailbox nil
  953. imap-current-message nil
  954. imap-state 'initial
  955. imap-process (condition-case ()
  956. (funcall (nth 2 (assq imap-stream
  957. imap-stream-alist))
  958. "imap" buffer imap-server imap-port)
  959. ((error quit) nil)))
  960. (when imap-process
  961. (set-process-filter imap-process 'imap-arrival-filter)
  962. (set-process-sentinel imap-process 'imap-sentinel)
  963. (while (and (eq imap-state 'initial)
  964. (memq (process-status imap-process) '(open run)))
  965. (message "Waiting for response from %s..." imap-server)
  966. (accept-process-output imap-process 1))
  967. (message "Waiting for response from %s...done" imap-server)
  968. (and (memq (process-status imap-process) '(open run))
  969. imap-process))))
  970. (defun imap-open (server &optional port stream auth buffer)
  971. "Open an IMAP connection to host SERVER at PORT returning a buffer.
  972. If PORT is unspecified, a default value is used (143 except
  973. for SSL which use 993).
  974. STREAM indicates the stream to use, see `imap-streams' for available
  975. streams. If nil, it choices the best stream the server is capable of.
  976. AUTH indicates authenticator to use, see `imap-authenticators' for
  977. available authenticators. If nil, it choices the best stream the
  978. server is capable of.
  979. BUFFER can be a buffer or a name of a buffer, which is created if
  980. necessary. If nil, the buffer name is generated."
  981. (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
  982. (with-current-buffer (get-buffer-create buffer)
  983. (if (imap-opened buffer)
  984. (imap-close buffer))
  985. (mapc 'make-local-variable imap-local-variables)
  986. (imap-disable-multibyte)
  987. (buffer-disable-undo)
  988. (setq imap-server (or server imap-server))
  989. (setq imap-port (or port imap-port))
  990. (setq imap-auth (or auth imap-auth))
  991. (setq imap-stream (or stream imap-stream))
  992. (message "imap: Connecting to %s..." imap-server)
  993. (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
  994. (imap-open-1 buffer)))
  995. (progn
  996. (message "imap: Connecting to %s...failed" imap-server)
  997. nil)
  998. (when (null imap-stream)
  999. ;; Need to choose stream.
  1000. (let ((streams imap-streams))
  1001. (while (setq stream (pop streams))
  1002. ;; OK to use this stream?
  1003. (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
  1004. ;; Stream changed?
  1005. (if (not (eq imap-default-stream stream))
  1006. (with-current-buffer (get-buffer-create
  1007. (generate-new-buffer-name " *temp*"))
  1008. (mapc 'make-local-variable imap-local-variables)
  1009. (imap-disable-multibyte)
  1010. (buffer-disable-undo)
  1011. (setq imap-server (or server imap-server))
  1012. (setq imap-port (or port imap-port))
  1013. (setq imap-auth (or auth imap-auth))
  1014. (message "imap: Reconnecting with stream `%s'..." stream)
  1015. (if (null (let ((imap-stream stream))
  1016. (imap-open-1 (current-buffer))))
  1017. (progn
  1018. (kill-buffer (current-buffer))
  1019. (message
  1020. "imap: Reconnecting with stream `%s'...failed"
  1021. stream))
  1022. ;; We're done, kill the first connection
  1023. (imap-close buffer)
  1024. (let ((name (if (stringp buffer)
  1025. buffer
  1026. (buffer-name buffer))))
  1027. (kill-buffer buffer)
  1028. (rename-buffer name)
  1029. ;; set the passed buffer to the current one,
  1030. ;; so that (imap-opened buffer) later will work
  1031. (setq buffer (current-buffer)))
  1032. (message "imap: Reconnecting with stream `%s'...done"
  1033. stream)
  1034. (setq imap-stream stream)
  1035. (setq imap-capability nil)
  1036. (setq streams nil)))
  1037. ;; We're done
  1038. (message "imap: Connecting to %s...done" imap-server)
  1039. (setq imap-stream stream)
  1040. (setq imap-capability nil)
  1041. (setq streams nil))))))
  1042. (when (imap-opened buffer)
  1043. (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
  1044. ;; (debug "opened+state+auth+buffer" (imap-opened buffer) imap-state imap-auth buffer)
  1045. (when imap-stream
  1046. buffer))))
  1047. (defcustom imap-ping-server t
  1048. "If non-nil, check if IMAP is open.
  1049. See the function `imap-ping-server'."
  1050. :version "23.1" ;; No Gnus
  1051. :group 'imap
  1052. :type 'boolean)
  1053. (defun imap-opened (&optional buffer)
  1054. "Return non-nil if connection to imap server in BUFFER is open.
  1055. If BUFFER is nil then the current buffer is used."
  1056. (and (setq buffer (get-buffer (or buffer (current-buffer))))
  1057. (buffer-live-p buffer)
  1058. (with-current-buffer buffer
  1059. (and imap-process
  1060. (memq (process-status imap-process) '(open run))
  1061. (if imap-ping-server
  1062. (imap-ping-server)
  1063. t)))))
  1064. (defun imap-ping-server (&optional buffer)
  1065. "Ping the IMAP server in BUFFER with a \"NOOP\" command.
  1066. Return non-nil if the server responds, and nil if it does not
  1067. respond. If BUFFER is nil, the current buffer is used."
  1068. (condition-case ()
  1069. (imap-ok-p (imap-send-command-wait "NOOP" buffer))
  1070. (error nil)))
  1071. (defun imap-authenticate (&optional user passwd buffer)
  1072. "Authenticate to server in BUFFER, using current buffer if nil.
  1073. It uses the authenticator specified when opening the server. If the
  1074. authenticator requires username/passwords, they are queried from the
  1075. user and optionally stored in the buffer. If USER and/or PASSWD is
  1076. specified, the user will not be questioned and the username and/or
  1077. password is remembered in the buffer."
  1078. (with-current-buffer (or buffer (current-buffer))
  1079. (if (not (eq imap-state 'nonauth))
  1080. (or (eq imap-state 'auth)
  1081. (eq imap-state 'selected)
  1082. (eq imap-state 'examine))
  1083. (make-local-variable 'imap-username)
  1084. (make-local-variable 'imap-password)
  1085. (make-local-variable 'imap-last-authenticator)
  1086. (when user (setq imap-username user))
  1087. (when passwd (setq imap-password passwd))
  1088. (if imap-auth
  1089. (and (setq imap-last-authenticator
  1090. (assq imap-auth imap-authenticator-alist))
  1091. (funcall (nth 2 imap-last-authenticator) (current-buffer))
  1092. (setq imap-state 'auth))
  1093. ;; Choose authenticator.
  1094. (let ((auths imap-authenticators)
  1095. auth)
  1096. (while (setq auth (pop auths))
  1097. ;; OK to use authenticator?
  1098. (setq imap-last-authenticator
  1099. (assq auth imap-authenticator-alist))
  1100. (when (funcall (nth 1 imap-last-authenticator) (current-buffer))
  1101. (message "imap: Authenticating to `%s' using `%s'..."
  1102. imap-server auth)
  1103. (setq imap-auth auth)
  1104. (if (funcall (nth 2 imap-last-authenticator) (current-buffer))
  1105. (progn
  1106. (message "imap: Authenticating to `%s' using `%s'...done"
  1107. imap-server auth)
  1108. ;; set imap-state correctly on successful auth attempt
  1109. (setq imap-state 'auth)
  1110. ;; stop iterating through the authenticator list
  1111. (setq auths nil))
  1112. (message "imap: Authenticating to `%s' using `%s'...failed"
  1113. imap-server auth)))))
  1114. imap-state))))
  1115. (defun imap-close (&optional buffer)
  1116. "Close connection to server in BUFFER.
  1117. If BUFFER is nil, the current buffer is used."
  1118. (with-current-buffer (or buffer (current-buffer))
  1119. (when (imap-opened)
  1120. (condition-case nil
  1121. (imap-logout-wait)
  1122. (quit nil)))
  1123. (when (and imap-process
  1124. (memq (process-status imap-process) '(open run)))
  1125. (delete-process imap-process))
  1126. (setq imap-current-mailbox nil
  1127. imap-current-message nil
  1128. imap-process nil)
  1129. (erase-buffer)
  1130. t))
  1131. (defun imap-capability (&optional identifier buffer)
  1132. "Return a list of identifiers which server in BUFFER support.
  1133. If IDENTIFIER, return non-nil if it's among the servers capabilities.
  1134. If BUFFER is nil, the current buffer is assumed."
  1135. (with-current-buffer (or buffer (current-buffer))
  1136. (unless imap-capability
  1137. (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
  1138. (setq imap-capability '(IMAP2))))
  1139. (if identifier
  1140. (memq (intern (upcase (symbol-name identifier))) imap-capability)
  1141. imap-capability)))
  1142. (defun imap-id (&optional list-of-values buffer)
  1143. "Identify client to server in BUFFER, and return server identity.
  1144. LIST-OF-VALUES is nil, or a plist with identifier and value
  1145. strings to send to the server to identify the client.
  1146. Return a list of identifiers which server in BUFFER support, or
  1147. nil if it doesn't support ID or returns no information.
  1148. If BUFFER is nil, the current buffer is assumed."
  1149. (with-current-buffer (or buffer (current-buffer))
  1150. (when (and (imap-capability 'ID)
  1151. (imap-ok-p (imap-send-command-wait
  1152. (if (null list-of-values)
  1153. "ID NIL"
  1154. (concat "ID (" (mapconcat (lambda (el)
  1155. (concat "\"" el "\""))
  1156. list-of-values
  1157. " ") ")")))))
  1158. imap-id)))
  1159. (defun imap-namespace (&optional buffer)
  1160. "Return a namespace hierarchy at server in BUFFER.
  1161. If BUFFER is nil, the current buffer is assumed."
  1162. (with-current-buffer (or buffer (current-buffer))
  1163. (unless imap-namespace
  1164. (when (imap-capability 'NAMESPACE)
  1165. (imap-send-command-wait "NAMESPACE")))
  1166. imap-namespace))
  1167. (defun imap-send-command-wait (command &optional buffer)
  1168. (imap-wait-for-tag (imap-send-command command buffer) buffer))
  1169. (defun imap-logout (&optional buffer)
  1170. (or buffer (setq buffer (current-buffer)))
  1171. (if imap-logout-timeout
  1172. (with-timeout (imap-logout-timeout
  1173. (condition-case nil
  1174. (with-current-buffer buffer
  1175. (delete-process imap-process))
  1176. (error)))
  1177. (imap-send-command "LOGOUT" buffer))
  1178. (imap-send-command "LOGOUT" buffer)))
  1179. (defun imap-logout-wait (&optional buffer)
  1180. (or buffer (setq buffer (current-buffer)))
  1181. (if imap-logout-timeout
  1182. (with-timeout (imap-logout-timeout
  1183. (condition-case nil
  1184. (with-current-buffer buffer
  1185. (delete-process imap-process))
  1186. (error)))
  1187. (imap-send-command-wait "LOGOUT" buffer))
  1188. (imap-send-command-wait "LOGOUT" buffer)))
  1189. ;; Mailbox functions:
  1190. (defun imap-mailbox-put (propname value &optional mailbox buffer)
  1191. (with-current-buffer (or buffer (current-buffer))
  1192. (if imap-mailbox-data
  1193. (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
  1194. propname value)
  1195. (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
  1196. propname value mailbox (current-buffer)))
  1197. t))
  1198. (defsubst imap-mailbox-get-1 (propname &optional mailbox)
  1199. (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
  1200. propname))
  1201. (defun imap-mailbox-get (propname &optional mailbox buffer)
  1202. (let ((mailbox (imap-utf7-encode mailbox)))
  1203. (with-current-buffer (or buffer (current-buffer))
  1204. (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
  1205. (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
  1206. (with-current-buffer (or buffer (current-buffer))
  1207. (let (result)
  1208. (mapatoms
  1209. (lambda (s)
  1210. (push (funcall func (if mailbox-decoder
  1211. (funcall mailbox-decoder (symbol-name s))
  1212. (symbol-name s))) result))
  1213. imap-mailbox-data)
  1214. result)))
  1215. (defun imap-mailbox-map (func &optional buffer)
  1216. "Map a function across each mailbox in `imap-mailbox-data', returning a list.
  1217. Function should take a mailbox name (a string) as
  1218. the only argument."
  1219. (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
  1220. (defun imap-current-mailbox (&optional buffer)
  1221. (with-current-buffer (or buffer (current-buffer))
  1222. (imap-utf7-decode imap-current-mailbox)))
  1223. (defun imap-current-mailbox-p-1 (mailbox &optional examine)
  1224. (and (string= mailbox imap-current-mailbox)
  1225. (or (and examine
  1226. (eq imap-state 'examine))
  1227. (and (not examine)
  1228. (eq imap-state 'selected)))))
  1229. (defun imap-current-mailbox-p (mailbox &optional examine buffer)
  1230. (with-current-buffer (or buffer (current-buffer))
  1231. (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
  1232. (defun imap-mailbox-select-1 (mailbox &optional examine)
  1233. "Select MAILBOX on server in BUFFER.
  1234. If EXAMINE is non-nil, do a read-only select."
  1235. (if (imap-current-mailbox-p-1 mailbox examine)
  1236. imap-current-mailbox
  1237. (setq imap-current-mailbox mailbox)
  1238. (if (imap-ok-p (imap-send-command-wait
  1239. (concat (if examine "EXAMINE" "SELECT") " \""
  1240. mailbox "\"")))
  1241. (progn
  1242. (setq imap-message-data (make-vector imap-message-prime 0)
  1243. imap-state (if examine 'examine 'selected))
  1244. imap-current-mailbox)
  1245. ;; Failed SELECT/EXAMINE unselects current mailbox
  1246. (setq imap-current-mailbox nil))))
  1247. (defun imap-mailbox-select (mailbox &optional examine buffer)
  1248. (with-current-buffer (or buffer (current-buffer))
  1249. (imap-utf7-decode
  1250. (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
  1251. (defun imap-mailbox-examine-1 (mailbox &optional buffer)
  1252. (with-current-buffer (or buffer (current-buffer))
  1253. (imap-mailbox-select-1 mailbox 'examine)))
  1254. (defun imap-mailbox-examine (mailbox &optional buffer)
  1255. "Examine MAILBOX on server in BUFFER."
  1256. (imap-mailbox-select mailbox 'examine buffer))
  1257. (defun imap-mailbox-unselect (&optional buffer)
  1258. "Close current folder in BUFFER, without expunging articles."
  1259. (with-current-buffer (or buffer (current-buffer))
  1260. (when (or (eq imap-state 'auth)
  1261. (and (imap-capability 'UNSELECT)
  1262. (imap-ok-p (imap-send-command-wait "UNSELECT")))
  1263. (and (imap-ok-p
  1264. (imap-send-command-wait (concat "EXAMINE \""
  1265. imap-current-mailbox
  1266. "\"")))
  1267. (imap-ok-p (imap-send-command-wait "CLOSE"))))
  1268. (setq imap-current-mailbox nil
  1269. imap-message-data nil
  1270. imap-state 'auth)
  1271. t)))
  1272. (defun imap-mailbox-expunge (&optional asynch buffer)
  1273. "Expunge articles in current folder in BUFFER.
  1274. If ASYNCH, do not wait for successful completion of the command.
  1275. If BUFFER is nil the current buffer is assumed."
  1276. (with-current-buffer (or buffer (current-buffer))
  1277. (when (and imap-current-mailbox (not (eq imap-state 'examine)))
  1278. (if asynch
  1279. (imap-send-command "EXPUNGE")
  1280. (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
  1281. (defun imap-mailbox-close (&optional asynch buffer)
  1282. "Expunge articles and close current folder in BUFFER.
  1283. If ASYNCH, do not wait for successful completion of the command.
  1284. If BUFFER is nil the current buffer is assumed."
  1285. (with-current-buffer (or buffer (current-buffer))
  1286. (when imap-current-mailbox
  1287. (if asynch
  1288. (imap-add-callback (imap-send-command "CLOSE")
  1289. `(lambda (tag status)
  1290. (message "IMAP mailbox `%s' closed... %s"
  1291. imap-current-mailbox status)
  1292. (when (eq ,imap-current-mailbox
  1293. imap-current-mailbox)
  1294. ;; Don't wipe out data if another mailbox
  1295. ;; was selected...
  1296. (setq imap-current-mailbox nil
  1297. imap-message-data nil
  1298. imap-state 'auth))))
  1299. (when (imap-ok-p (imap-send-command-wait "CLOSE"))
  1300. (setq imap-current-mailbox nil
  1301. imap-message-data nil
  1302. imap-state 'auth)))
  1303. t)))
  1304. (defun imap-mailbox-create-1 (mailbox)
  1305. (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
  1306. (defun imap-mailbox-create (mailbox &optional buffer)
  1307. "Create MAILBOX on server in BUFFER.
  1308. If BUFFER is nil the current buffer is assumed."
  1309. (with-current-buffer (or buffer (current-buffer))
  1310. (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
  1311. (defun imap-mailbox-delete (mailbox &optional buffer)
  1312. "Delete MAILBOX on server in BUFFER.
  1313. If BUFFER is nil the current buffer is assumed."
  1314. (let ((mailbox (imap-utf7-encode mailbox)))
  1315. (with-current-buffer (or buffer (current-buffer))
  1316. (imap-ok-p
  1317. (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
  1318. (defun imap-mailbox-rename (oldname newname &optional buffer)
  1319. "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
  1320. If BUFFER is nil the current buffer is assumed."
  1321. (let ((oldname (imap-utf7-encode oldname))
  1322. (newname (imap-utf7-encode newname)))
  1323. (with-current-buffer (or buffer (current-buffer))
  1324. (imap-ok-p
  1325. (imap-send-command-wait (list "RENAME \"" oldname "\" "
  1326. "\"" newname "\""))))))
  1327. (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
  1328. "Return a list of subscribed mailboxes on server in BUFFER.
  1329. If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
  1330. non-nil, a hierarchy delimiter is added to root. REFERENCE is a
  1331. implementation-specific string that has to be passed to lsub command."
  1332. (with-current-buffer (or buffer (current-buffer))
  1333. ;; Make sure we know the hierarchy separator for root's hierarchy
  1334. (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
  1335. (imap-send-command-wait (concat "LIST \"" reference "\" \""
  1336. (imap-utf7-encode root) "\"")))
  1337. ;; clear list data (NB not delimiter and other stuff)
  1338. (imap-mailbox-map-1 (lambda (mailbox)
  1339. (imap-mailbox-put 'lsub nil mailbox)))
  1340. (when (imap-ok-p
  1341. (imap-send-command-wait
  1342. (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
  1343. (and add-delimiter (imap-mailbox-get-1 'delimiter root))
  1344. "%\"")))
  1345. (let (out)
  1346. (imap-mailbox-map-1 (lambda (mailbox)
  1347. (when (imap-mailbox-get-1 'lsub mailbox)
  1348. (push (imap-utf7-decode mailbox) out))))
  1349. (nreverse out)))))
  1350. (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
  1351. "Return a list of mailboxes matching ROOT on server in BUFFER.
  1352. If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
  1353. root. REFERENCE is a implementation-specific string that has to be
  1354. passed to list command."
  1355. (with-current-buffer (or buffer (current-buffer))
  1356. ;; Make sure we know the hierarchy separator for root's hierarchy
  1357. (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
  1358. (imap-send-command-wait (concat "LIST \"" reference "\" \""
  1359. (imap-utf7-encode root) "\"")))
  1360. ;; clear list data (NB not delimiter and other stuff)
  1361. (imap-mailbox-map-1 (lambda (mailbox)
  1362. (imap-mailbox-put 'list nil mailbox)))
  1363. (when (imap-ok-p
  1364. (imap-send-command-wait
  1365. (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
  1366. (and add-delimiter (imap-mailbox-get-1 'delimiter root))
  1367. "%\"")))
  1368. (let (out)
  1369. (imap-mailbox-map-1 (lambda (mailbox)
  1370. (when (imap-mailbox-get-1 'list mailbox)
  1371. (push (imap-utf7-decode mailbox) out))))
  1372. (nreverse out)))))
  1373. (defun imap-mailbox-subscribe (mailbox &optional buffer)
  1374. "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
  1375. Returns non-nil if successful."
  1376. (with-current-buffer (or buffer (current-buffer))
  1377. (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
  1378. (imap-utf7-encode mailbox)
  1379. "\"")))))
  1380. (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
  1381. "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
  1382. Returns non-nil if successful."
  1383. (with-current-buffer (or buffer (current-buffer))
  1384. (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
  1385. (imap-utf7-encode mailbox)
  1386. "\"")))))
  1387. (defun imap-mailbox-status (mailbox items &optional buffer)
  1388. "Get status items ITEM in MAILBOX from server in BUFFER.
  1389. ITEMS can be a symbol or a list of symbols, valid symbols are one of
  1390. the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
  1391. or `unseen'. If ITEMS is a list of symbols, a list of values is
  1392. returned, if ITEMS is a symbol only its value is returned."
  1393. (with-current-buffer (or buffer (current-buffer))
  1394. (when (imap-ok-p
  1395. (imap-send-command-wait (list "STATUS \""
  1396. (imap-utf7-encode mailbox)
  1397. "\" "
  1398. (upcase
  1399. (format "%s"
  1400. (if (listp items)
  1401. items
  1402. (list items)))))))
  1403. (if (listp items)
  1404. (mapcar (lambda (item)
  1405. (imap-mailbox-get item mailbox))
  1406. items)
  1407. (imap-mailbox-get items mailbox)))))
  1408. (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
  1409. "Send status item request ITEM on MAILBOX to server in BUFFER.
  1410. ITEMS can be a symbol or a list of symbols, valid symbols are one of
  1411. the STATUS data items -- i.e. 'messages, 'recent, 'uidnext, 'uidvalidity
  1412. or 'unseen. The IMAP command tag is returned."
  1413. (with-current-buffer (or buffer (current-buffer))
  1414. (imap-send-command (list "STATUS \""
  1415. (imap-utf7-encode mailbox)
  1416. "\" "
  1417. (upcase
  1418. (format "%s"
  1419. (if (listp items)
  1420. items
  1421. (list items))))))))
  1422. (defun imap-mailbox-acl-get (&optional mailbox buffer)
  1423. "Get ACL on MAILBOX from server in BUFFER."
  1424. (let ((mailbox (imap-utf7-encode mailbox)))
  1425. (with-current-buffer (or buffer (current-buffer))
  1426. (when (imap-ok-p
  1427. (imap-send-command-wait (list "GETACL \""
  1428. (or mailbox imap-current-mailbox)
  1429. "\"")))
  1430. (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
  1431. (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
  1432. "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
  1433. (let ((mailbox (imap-utf7-encode mailbox)))
  1434. (with-current-buffer (or buffer (current-buffer))
  1435. (imap-ok-p
  1436. (imap-send-command-wait (list "SETACL \""
  1437. (or mailbox imap-current-mailbox)
  1438. "\" "
  1439. identifier
  1440. " "
  1441. rights))))))
  1442. (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
  1443. "Remove any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
  1444. (let ((mailbox (imap-utf7-encode mailbox)))
  1445. (with-current-buffer (or buffer (current-buffer))
  1446. (imap-ok-p
  1447. (imap-send-command-wait (list "DELETEACL \""
  1448. (or mailbox imap-current-mailbox)
  1449. "\" "
  1450. identifier))))))
  1451. ;; Message functions:
  1452. (defun imap-current-message (&optional buffer)
  1453. (with-current-buffer (or buffer (current-buffer))
  1454. imap-current-message))
  1455. (defun imap-list-to-message-set (list)
  1456. (mapconcat (lambda (item)
  1457. (number-to-string item))
  1458. (if (listp list)
  1459. list
  1460. (list list))
  1461. ","))
  1462. (defun imap-range-to-message-set (range)
  1463. (mapconcat
  1464. (lambda (item)
  1465. (if (consp item)
  1466. (format "%d:%d"
  1467. (car item) (cdr item))
  1468. (format "%d" item)))
  1469. (if (and (listp range) (not (listp (cdr range))))
  1470. (list range) ;; make (1 . 2) into ((1 . 2))
  1471. range)
  1472. ","))
  1473. (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
  1474. (with-current-buffer (or buffer (current-buffer))
  1475. (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
  1476. (if (listp uids)
  1477. (imap-list-to-message-set uids)
  1478. uids)
  1479. props))))
  1480. (defun imap-fetch (uids props &optional receive nouidfetch buffer)
  1481. "Fetch properties PROPS from message set UIDS from server in BUFFER.
  1482. UIDS can be a string, number or a list of numbers. If RECEIVE
  1483. is non-nil return these properties."
  1484. (with-current-buffer (or buffer (current-buffer))
  1485. (when (imap-ok-p (imap-send-command-wait
  1486. (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
  1487. (if (listp uids)
  1488. (imap-list-to-message-set uids)
  1489. uids)
  1490. props)))
  1491. (if (or (null receive) (stringp uids))
  1492. t
  1493. (if (listp uids)
  1494. (mapcar (lambda (uid)
  1495. (if (listp receive)
  1496. (mapcar (lambda (prop)
  1497. (imap-message-get uid prop))
  1498. receive)
  1499. (imap-message-get uid receive)))
  1500. uids)
  1501. (imap-message-get uids receive))))))
  1502. (defun imap-message-put (uid propname value &optional buffer)
  1503. (with-current-buffer (or buffer (current-buffer))
  1504. (if imap-message-data
  1505. (put (intern (number-to-string uid) imap-message-data)
  1506. propname value)
  1507. (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
  1508. uid propname value (current-buffer)))
  1509. t))
  1510. (defun imap-message-get (uid propname &optional buffer)
  1511. (with-current-buffer (or buffer (current-buffer))
  1512. (get (intern-soft (number-to-string uid) imap-message-data)
  1513. propname)))
  1514. (defun imap-message-map (func propname &optional buffer)
  1515. "Map a function across each message in `imap-message-data', returning a list."
  1516. (with-current-buffer (or buffer (current-buffer))
  1517. (let (result)
  1518. (mapatoms
  1519. (lambda (s)
  1520. (push (funcall func (get s 'UID) (get s propname)) result))
  1521. imap-message-data)
  1522. result)))
  1523. (defmacro imap-message-envelope-date (uid &optional buffer)
  1524. `(with-current-buffer (or ,buffer (current-buffer))
  1525. (elt (imap-message-get ,uid 'ENVELOPE) 0)))
  1526. (defmacro imap-message-envelope-subject (uid &optional buffer)
  1527. `(with-current-buffer (or ,buffer (current-buffer))
  1528. (elt (imap-message-get ,uid 'ENVELOPE) 1)))
  1529. (defmacro imap-message-envelope-from (uid &optional buffer)
  1530. `(with-current-buffer (or ,buffer (current-buffer))
  1531. (elt (imap-message-get ,uid 'ENVELOPE) 2)))
  1532. (defmacro imap-message-envelope-sender (uid &optional buffer)
  1533. `(with-current-buffer (or ,buffer (current-buffer))
  1534. (elt (imap-message-get ,uid 'ENVELOPE) 3)))
  1535. (defmacro imap-message-envelope-reply-to (uid &optional buffer)
  1536. `(with-current-buffer (or ,buffer (current-buffer))
  1537. (elt (imap-message-get ,uid 'ENVELOPE) 4)))
  1538. (defmacro imap-message-envelope-to (uid &optional buffer)
  1539. `(with-current-buffer (or ,buffer (current-buffer))
  1540. (elt (imap-message-get ,uid 'ENVELOPE) 5)))
  1541. (defmacro imap-message-envelope-cc (uid &optional buffer)
  1542. `(with-current-buffer (or ,buffer (current-buffer))
  1543. (elt (imap-message-get ,uid 'ENVELOPE) 6)))
  1544. (defmacro imap-message-envelope-bcc (uid &optional buffer)
  1545. `(with-current-buffer (or ,buffer (current-buffer))
  1546. (elt (imap-message-get ,uid 'ENVELOPE) 7)))
  1547. (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
  1548. `(with-current-buffer (or ,buffer (current-buffer))
  1549. (elt (imap-message-get ,uid 'ENVELOPE) 8)))
  1550. (defmacro imap-message-envelope-message-id (uid &optional buffer)
  1551. `(with-current-buffer (or ,buffer (current-buffer))
  1552. (elt (imap-message-get ,uid 'ENVELOPE) 9)))
  1553. (defmacro imap-message-body (uid &optional buffer)
  1554. `(with-current-buffer (or ,buffer (current-buffer))
  1555. (imap-message-get ,uid 'BODY)))
  1556. ;; FIXME: Should this try to use CHARSET? -- fx
  1557. (defun imap-search (predicate &optional buffer)
  1558. (with-current-buffer (or buffer (current-buffer))
  1559. (imap-mailbox-put 'search 'dummy)
  1560. (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
  1561. (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
  1562. (progn
  1563. (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
  1564. nil)
  1565. (imap-mailbox-get-1 'search imap-current-mailbox)))))
  1566. (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
  1567. "Return t if FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
  1568. (with-current-buffer (or buffer (current-buffer))
  1569. (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
  1570. (member flag (imap-mailbox-get 'permanentflags mailbox)))))
  1571. (defun imap-message-flags-set (articles flags &optional silent buffer)
  1572. (when (and articles flags)
  1573. (with-current-buffer (or buffer (current-buffer))
  1574. (imap-ok-p (imap-send-command-wait
  1575. (concat "UID STORE " articles
  1576. " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
  1577. (defun imap-message-flags-del (articles flags &optional silent buffer)
  1578. (when (and articles flags)
  1579. (with-current-buffer (or buffer (current-buffer))
  1580. (imap-ok-p (imap-send-command-wait
  1581. (concat "UID STORE " articles
  1582. " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
  1583. (defun imap-message-flags-add (articles flags &optional silent buffer)
  1584. (when (and articles flags)
  1585. (with-current-buffer (or buffer (current-buffer))
  1586. (imap-ok-p (imap-send-command-wait
  1587. (concat "UID STORE " articles
  1588. " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
  1589. ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
  1590. ;; Signal an error if we'd get an integer overflow.
  1591. ;;
  1592. ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
  1593. ;; `imap-string-to-integer'.
  1594. (defun imap-string-to-integer (string &optional base)
  1595. (let ((number (string-to-number string base)))
  1596. (if (> number most-positive-fixnum)
  1597. (error
  1598. (format "String %s cannot be converted to a Lisp integer" number))
  1599. number)))
  1600. (defun imap-fetch-safe (uids props &optional receive nouidfetch buffer)
  1601. "Like `imap-fetch', but DTRT with Exchange 2007 bug.
  1602. However, UIDS here is a cons, where the car is the canonical form
  1603. of the UIDS specification, and the cdr is the one which works with
  1604. Exchange 2007 or, potentially, other buggy servers.
  1605. See `imap-enable-exchange-bug-workaround'."
  1606. ;; The first time we get here for a given, we'll try the canonical
  1607. ;; form. If we get the known error from the buggy server, set the
  1608. ;; flag buffer-locally (to account for connections to multiple
  1609. ;; servers), then re-try with the alternative UIDS spec. We don't
  1610. ;; unconditionally use the alternative form, since the
  1611. ;; currently-used alternatives are seriously inefficient with some
  1612. ;; servers (although they are valid).
  1613. ;;
  1614. ;; FIXME: Maybe it would be cleaner to have a flag to not signal
  1615. ;; the error (which otherwise gives a message), and test
  1616. ;; `imap-failed-tags'. Also, Other IMAP clients use other forms of
  1617. ;; request which work with Exchange, e.g. Claws does "UID FETCH 1:*
  1618. ;; (UID)" rather than "FETCH UID 1,*". Is there a good reason not
  1619. ;; to do the same?
  1620. (condition-case data
  1621. ;; Binding `debug-on-error' allows us to get the error from
  1622. ;; `imap-parse-response' -- it's normally caught by Emacs around
  1623. ;; execution of a process filter.
  1624. (let ((debug-on-error t))
  1625. (imap-fetch (if imap-enable-exchange-bug-workaround
  1626. (cdr uids)
  1627. (car uids))
  1628. props receive nouidfetch buffer))
  1629. (error
  1630. (if (and (not imap-enable-exchange-bug-workaround)
  1631. ;; This is the Exchange 2007 response. It may be more
  1632. ;; robust just to check for a BAD response to the
  1633. ;; attempted fetch.
  1634. (string-match "The specified message set is invalid"
  1635. (cadr data)))
  1636. (with-current-buffer (or buffer (current-buffer))
  1637. (set (make-local-variable 'imap-enable-exchange-bug-workaround)
  1638. t)
  1639. (imap-fetch (cdr uids) props receive nouidfetch))
  1640. (signal (car data) (cdr data))))))
  1641. (defun imap-message-copyuid-1 (mailbox)
  1642. (if (imap-capability 'UIDPLUS)
  1643. (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
  1644. (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
  1645. (let ((old-mailbox imap-current-mailbox)
  1646. (state imap-state)
  1647. (imap-message-data (make-vector 2 0)))
  1648. (when (imap-mailbox-examine-1 mailbox)
  1649. (prog1
  1650. (and (imap-fetch-safe '("*" . "*:*") "UID")
  1651. (list (imap-mailbox-get-1 'uidvalidity mailbox)
  1652. (apply 'max (imap-message-map
  1653. (lambda (uid prop) uid) 'UID))))
  1654. (if old-mailbox
  1655. (imap-mailbox-select old-mailbox (eq state 'examine))
  1656. (imap-mailbox-unselect)))))))
  1657. (defun imap-message-copyuid (mailbox &optional buffer)
  1658. (with-current-buffer (or buffer (current-buffer))
  1659. (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
  1660. (defun imap-message-copy (articles mailbox
  1661. &optional dont-create no-copyuid buffer)
  1662. "Copy ARTICLES to MAILBOX on server in BUFFER.
  1663. ARTICLES is a string message set. Create mailbox if it doesn't exist,
  1664. unless DONT-CREATE is non-nil. On success, return a list with
  1665. the UIDVALIDITY of the mailbox the article(s) was copied to as the
  1666. first element. The rest of list contains the saved articles' UIDs."
  1667. (when articles
  1668. (with-current-buffer (or buffer (current-buffer))
  1669. (let ((mailbox (imap-utf7-encode mailbox)))
  1670. (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
  1671. (imap-current-target-mailbox mailbox))
  1672. (if (imap-ok-p (imap-send-command-wait cmd))
  1673. t
  1674. (when (and (not dont-create)
  1675. ;; removed because of buggy Oracle server
  1676. ;; that doesn't send TRYCREATE tags (which
  1677. ;; is a MUST according to specifications):
  1678. ;;(imap-mailbox-get-1 'trycreate mailbox)
  1679. (imap-mailbox-create-1 mailbox))
  1680. (imap-ok-p (imap-send-command-wait cmd)))))
  1681. (or no-copyuid
  1682. (imap-message-copyuid-1 mailbox)))))))
  1683. ;; FIXME: Amalgamate with imap-message-copyuid-1, using an extra arg, since it
  1684. ;; shares most of the code? -- fx
  1685. (defun imap-message-appenduid-1 (mailbox)
  1686. (if (imap-capability 'UIDPLUS)
  1687. (imap-mailbox-get-1 'appenduid mailbox)
  1688. (let ((old-mailbox imap-current-mailbox)
  1689. (state imap-state)
  1690. (imap-message-data (make-vector 2 0)))
  1691. (when (imap-mailbox-examine-1 mailbox)
  1692. (prog1
  1693. (and (imap-fetch-safe '("*" . "*:*") "UID")
  1694. (list (imap-mailbox-get-1 'uidvalidity mailbox)
  1695. (apply 'max (imap-message-map
  1696. (lambda (uid prop) uid) 'UID))))
  1697. (if old-mailbox
  1698. (imap-mailbox-select old-mailbox (eq state 'examine))
  1699. (imap-mailbox-unselect)))))))
  1700. (defun imap-message-appenduid (mailbox &optional buffer)
  1701. (with-current-buffer (or buffer (current-buffer))
  1702. (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
  1703. (defun imap-message-append (mailbox article &optional flags date-time buffer)
  1704. "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
  1705. FLAGS and DATE-TIME is currently not used. Return a cons holding
  1706. uidvalidity of MAILBOX and UID the newly created article got, or nil
  1707. on failure."
  1708. (let ((mailbox (imap-utf7-encode mailbox)))
  1709. (with-current-buffer (or buffer (current-buffer))
  1710. (and (let ((imap-current-target-mailbox mailbox))
  1711. (imap-ok-p
  1712. (imap-send-command-wait
  1713. (list "APPEND \"" mailbox "\" " article))))
  1714. (imap-message-appenduid-1 mailbox)))))
  1715. (defun imap-body-lines (body)
  1716. "Return number of lines in article by looking at the mime bodystructure BODY."
  1717. (if (listp body)
  1718. (if (stringp (car body))
  1719. (cond ((and (string= (upcase (car body)) "TEXT")
  1720. (numberp (nth 7 body)))
  1721. (nth 7 body))
  1722. ((and (string= (upcase (car body)) "MESSAGE")
  1723. (numberp (nth 9 body)))
  1724. (nth 9 body))
  1725. (t 0))
  1726. (apply '+ (mapcar 'imap-body-lines body)))
  1727. 0))
  1728. (defun imap-envelope-from (from)
  1729. "Return a from string line."
  1730. (and from
  1731. (concat (aref from 0)
  1732. (if (aref from 0) " <")
  1733. (aref from 2)
  1734. "@"
  1735. (aref from 3)
  1736. (if (aref from 0) ">"))))
  1737. ;; Internal functions.
  1738. (defun imap-add-callback (tag func)
  1739. (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
  1740. (defun imap-send-command-1 (cmdstr)
  1741. (setq cmdstr (concat cmdstr imap-client-eol))
  1742. (imap-log cmdstr)
  1743. (process-send-string imap-process cmdstr))
  1744. (defun imap-send-command (command &optional buffer)
  1745. (with-current-buffer (or buffer (current-buffer))
  1746. (if (not (listp command)) (setq command (list command)))
  1747. (let ((tag (setq imap-tag (1+ imap-tag)))
  1748. cmd cmdstr)
  1749. (setq cmdstr (concat (number-to-string imap-tag) " "))
  1750. (while (setq cmd (pop command))
  1751. (cond ((stringp cmd)
  1752. (setq cmdstr (concat cmdstr cmd)))
  1753. ((bufferp cmd)
  1754. (let ((eol imap-client-eol)
  1755. (calcfirst imap-calculate-literal-size-first)
  1756. size)
  1757. (with-current-buffer cmd
  1758. (if calcfirst
  1759. (setq size (buffer-size)))
  1760. (when (not (equal eol "\r\n"))
  1761. ;; XXX modifies buffer!
  1762. (goto-char (point-min))
  1763. (while (search-forward "\r\n" nil t)
  1764. (replace-match eol)))
  1765. (if (not calcfirst)
  1766. (setq size (buffer-size))))
  1767. (setq cmdstr
  1768. (concat cmdstr (format "{%d}" size))))
  1769. (unwind-protect
  1770. (progn
  1771. (imap-send-command-1 cmdstr)
  1772. (setq cmdstr nil)
  1773. (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
  1774. (setq command nil) ;; abort command if no cont-req
  1775. (let ((process imap-process)
  1776. (stream imap-stream)
  1777. (eol imap-client-eol))
  1778. (with-current-buffer cmd
  1779. (imap-log cmd)
  1780. (process-send-region process (point-min)
  1781. (point-max)))
  1782. (process-send-string process imap-client-eol))))
  1783. (setq imap-continuation nil)))
  1784. ((functionp cmd)
  1785. (imap-send-command-1 cmdstr)
  1786. (setq cmdstr nil)
  1787. (unwind-protect
  1788. (setq command
  1789. (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
  1790. nil ;; abort command if no cont-req
  1791. (cons (funcall cmd imap-continuation)
  1792. command)))
  1793. (setq imap-continuation nil)))
  1794. (t
  1795. (error "Unknown command type"))))
  1796. (if cmdstr
  1797. (imap-send-command-1 cmdstr))
  1798. tag)))
  1799. (defun imap-wait-for-tag (tag &optional buffer)
  1800. (with-current-buffer (or buffer (current-buffer))
  1801. (let (imap-have-messaged)
  1802. (while (and (null imap-continuation)
  1803. (memq (process-status imap-process) '(open run))
  1804. (< imap-reached-tag tag))
  1805. (let ((len (/ (buffer-size) 1024))
  1806. message-log-max)
  1807. (unless (< len 10)
  1808. (setq imap-have-messaged t)
  1809. (message "imap read: %dk" len))
  1810. (accept-process-output imap-process
  1811. (truncate imap-read-timeout)
  1812. (truncate (* (- imap-read-timeout
  1813. (truncate imap-read-timeout))
  1814. 1000)))))
  1815. ;; A process can die _before_ we have processed everything it
  1816. ;; has to say. Moreover, this can happen in between the call to
  1817. ;; accept-process-output and the call to process-status in an
  1818. ;; iteration of the loop above.
  1819. (when (and (null imap-continuation)
  1820. (< imap-reached-tag tag))
  1821. (accept-process-output imap-process 0 0))
  1822. (when imap-have-messaged
  1823. (message ""))
  1824. (and (memq (process-status imap-process) '(open run))
  1825. (or (assq tag imap-failed-tags)
  1826. (if imap-continuation
  1827. 'INCOMPLETE
  1828. 'OK))))))
  1829. (defun imap-sentinel (process string)
  1830. (delete-process process))
  1831. (defun imap-find-next-line ()
  1832. "Return point at end of current line, taking into account literals.
  1833. Return nil if no complete line has arrived."
  1834. (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
  1835. imap-server-eol)
  1836. nil t)
  1837. (if (match-string 1)
  1838. (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
  1839. nil
  1840. (goto-char (+ (point) (string-to-number (match-string 1))))
  1841. (imap-find-next-line))
  1842. (point))))
  1843. (defun imap-arrival-filter (proc string)
  1844. "IMAP process filter."
  1845. ;; Sometimes, we are called even though the process has died.
  1846. ;; Better abstain from doing stuff in that case.
  1847. (when (buffer-name (process-buffer proc))
  1848. (with-current-buffer (process-buffer proc)
  1849. (goto-char (point-max))
  1850. (insert string)
  1851. (imap-log string)
  1852. (let (end)
  1853. (goto-char (point-min))
  1854. (while (setq end (imap-find-next-line))
  1855. (save-restriction
  1856. (narrow-to-region (point-min) end)
  1857. (delete-char (- (length imap-server-eol)))
  1858. (goto-char (point-min))
  1859. (unwind-protect
  1860. (cond ((eq imap-state 'initial)
  1861. (imap-parse-greeting))
  1862. ((or (eq imap-state 'auth)
  1863. (eq imap-state 'nonauth)
  1864. (eq imap-state 'selected)
  1865. (eq imap-state 'examine))
  1866. (imap-parse-response))
  1867. (t
  1868. (message "Unknown state %s in arrival filter"
  1869. imap-state)))
  1870. (delete-region (point-min) (point-max)))))))))
  1871. ;; Imap parser.
  1872. (defsubst imap-forward ()
  1873. (or (eobp) (forward-char)))
  1874. ;; number = 1*DIGIT
  1875. ;; ; Unsigned 32-bit integer
  1876. ;; ; (0 <= n < 4,294,967,296)
  1877. (defsubst imap-parse-number ()
  1878. (when (looking-at "[0-9]+")
  1879. (prog1
  1880. (string-to-number (match-string 0))
  1881. (goto-char (match-end 0)))))
  1882. ;; literal = "{" number "}" CRLF *CHAR8
  1883. ;; ; Number represents the number of CHAR8s
  1884. (defsubst imap-parse-literal ()
  1885. (when (looking-at "{\\([0-9]+\\)}\r\n")
  1886. (let ((pos (match-end 0))
  1887. (len (string-to-number (match-string 1))))
  1888. (if (< (point-max) (+ pos len))
  1889. nil
  1890. (goto-char (+ pos len))
  1891. (buffer-substring pos (+ pos len))))))
  1892. ;; string = quoted / literal
  1893. ;;
  1894. ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
  1895. ;;
  1896. ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
  1897. ;; "\" quoted-specials
  1898. ;;
  1899. ;; quoted-specials = DQUOTE / "\"
  1900. ;;
  1901. ;; TEXT-CHAR = <any CHAR except CR and LF>
  1902. (defsubst imap-parse-string ()
  1903. (cond ((eq (char-after) ?\")
  1904. (forward-char 1)
  1905. (let ((p (point)) (name ""))
  1906. (skip-chars-forward "^\"\\\\")
  1907. (setq name (buffer-substring p (point)))
  1908. (while (eq (char-after) ?\\)
  1909. (setq p (1+ (point)))
  1910. (forward-char 2)
  1911. (skip-chars-forward "^\"\\\\")
  1912. (setq name (concat name (buffer-substring p (point)))))
  1913. (forward-char 1)
  1914. name))
  1915. ((eq (char-after) ?{)
  1916. (imap-parse-literal))))
  1917. ;; nil = "NIL"
  1918. (defsubst imap-parse-nil ()
  1919. (if (looking-at "NIL")
  1920. (goto-char (match-end 0))))
  1921. ;; nstring = string / nil
  1922. (defsubst imap-parse-nstring ()
  1923. (or (imap-parse-string)
  1924. (and (imap-parse-nil)
  1925. nil)))
  1926. ;; astring = atom / string
  1927. ;;
  1928. ;; atom = 1*ATOM-CHAR
  1929. ;;
  1930. ;; ATOM-CHAR = <any CHAR except atom-specials>
  1931. ;;
  1932. ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
  1933. ;; quoted-specials
  1934. ;;
  1935. ;; list-wildcards = "%" / "*"
  1936. ;;
  1937. ;; quoted-specials = DQUOTE / "\"
  1938. (defsubst imap-parse-astring ()
  1939. (or (imap-parse-string)
  1940. (buffer-substring (point)
  1941. (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
  1942. (goto-char (1- (match-end 0)))
  1943. (end-of-line)
  1944. (point)))))
  1945. ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
  1946. ;; addr-host ")"
  1947. ;;
  1948. ;; addr-adl = nstring
  1949. ;; ; Holds route from [RFC-822] route-addr if
  1950. ;; ; non-nil
  1951. ;;
  1952. ;; addr-host = nstring
  1953. ;; ; nil indicates [RFC-822] group syntax.
  1954. ;; ; Otherwise, holds [RFC-822] domain name
  1955. ;;
  1956. ;; addr-mailbox = nstring
  1957. ;; ; nil indicates end of [RFC-822] group; if
  1958. ;; ; non-nil and addr-host is nil, holds
  1959. ;; ; [RFC-822] group name.
  1960. ;; ; Otherwise, holds [RFC-822] local-part
  1961. ;; ; after removing [RFC-822] quoting
  1962. ;;
  1963. ;; addr-name = nstring
  1964. ;; ; If non-nil, holds phrase from [RFC-822]
  1965. ;; ; mailbox after removing [RFC-822] quoting
  1966. ;;
  1967. (defsubst imap-parse-address ()
  1968. (let (address)
  1969. (when (eq (char-after) ?\()
  1970. (imap-forward)
  1971. (setq address (vector (prog1 (imap-parse-nstring)
  1972. (imap-forward))
  1973. (prog1 (imap-parse-nstring)
  1974. (imap-forward))
  1975. (prog1 (imap-parse-nstring)
  1976. (imap-forward))
  1977. (imap-parse-nstring)))
  1978. (when (eq (char-after) ?\))
  1979. (imap-forward)
  1980. address))))
  1981. ;; address-list = "(" 1*address ")" / nil
  1982. ;;
  1983. ;; nil = "NIL"
  1984. (defsubst imap-parse-address-list ()
  1985. (if (eq (char-after) ?\()
  1986. (let (address addresses)
  1987. (imap-forward)
  1988. (while (and (not (eq (char-after) ?\)))
  1989. ;; next line for MS Exchange bug
  1990. (progn (and (eq (char-after) ? ) (imap-forward)) t)
  1991. (setq address (imap-parse-address)))
  1992. (setq addresses (cons address addresses)))
  1993. (when (eq (char-after) ?\))
  1994. (imap-forward)
  1995. (nreverse addresses)))
  1996. ;; With assert, the code might not be eval'd.
  1997. ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
  1998. (imap-parse-nil)))
  1999. ;; mailbox = "INBOX" / astring
  2000. ;; ; INBOX is case-insensitive. All case variants of
  2001. ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
  2002. ;; ; not as an astring. An astring which consists of
  2003. ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
  2004. ;; ; is considered to be INBOX and not an astring.
  2005. ;; ; Refer to section 5.1 for further
  2006. ;; ; semantic details of mailbox names.
  2007. (defsubst imap-parse-mailbox ()
  2008. (let ((mailbox (imap-parse-astring)))
  2009. (if (string-equal "INBOX" (upcase mailbox))
  2010. "INBOX"
  2011. mailbox)))
  2012. ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
  2013. ;;
  2014. ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
  2015. ;; ; Authentication condition
  2016. ;;
  2017. ;; resp-cond-bye = "BYE" SP resp-text
  2018. (defun imap-parse-greeting ()
  2019. "Parse an IMAP greeting."
  2020. (cond ((looking-at "\\* OK ")
  2021. (setq imap-state 'nonauth))
  2022. ((looking-at "\\* PREAUTH ")
  2023. (setq imap-state 'auth))
  2024. ((looking-at "\\* BYE ")
  2025. (setq imap-state 'closed))))
  2026. ;; response = *(continue-req / response-data) response-done
  2027. ;;
  2028. ;; continue-req = "+" SP (resp-text / base64) CRLF
  2029. ;;
  2030. ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
  2031. ;; mailbox-data / message-data / capability-data) CRLF
  2032. ;;
  2033. ;; response-done = response-tagged / response-fatal
  2034. ;;
  2035. ;; response-fatal = "*" SP resp-cond-bye CRLF
  2036. ;; ; Server closes connection immediately
  2037. ;;
  2038. ;; response-tagged = tag SP resp-cond-state CRLF
  2039. ;;
  2040. ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
  2041. ;; ; Status condition
  2042. ;;
  2043. ;; resp-cond-bye = "BYE" SP resp-text
  2044. ;;
  2045. ;; mailbox-data = "FLAGS" SP flag-list /
  2046. ;; "LIST" SP mailbox-list /
  2047. ;; "LSUB" SP mailbox-list /
  2048. ;; "SEARCH" *(SP nz-number) /
  2049. ;; "STATUS" SP mailbox SP "("
  2050. ;; [status-att SP number *(SP status-att SP number)] ")" /
  2051. ;; number SP "EXISTS" /
  2052. ;; number SP "RECENT"
  2053. ;;
  2054. ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
  2055. ;;
  2056. ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
  2057. ;; *(SP capability)
  2058. ;; ; IMAP4rev1 servers which offer RFC 1730
  2059. ;; ; compatibility MUST list "IMAP4" as the first
  2060. ;; ; capability.
  2061. (defun imap-parse-response ()
  2062. "Parse a IMAP command response."
  2063. (let (token)
  2064. (case (setq token (read (current-buffer)))
  2065. (+ (setq imap-continuation
  2066. (or (buffer-substring (min (point-max) (1+ (point)))
  2067. (point-max))
  2068. t)))
  2069. (* (case (prog1 (setq token (read (current-buffer)))
  2070. (imap-forward))
  2071. (OK (imap-parse-resp-text))
  2072. (NO (imap-parse-resp-text))
  2073. (BAD (imap-parse-resp-text))
  2074. (BYE (imap-parse-resp-text))
  2075. (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
  2076. (LIST (imap-parse-data-list 'list))
  2077. (LSUB (imap-parse-data-list 'lsub))
  2078. (SEARCH (imap-mailbox-put
  2079. 'search
  2080. (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
  2081. (STATUS (imap-parse-status))
  2082. (CAPABILITY (setq imap-capability
  2083. (read (concat "(" (upcase (buffer-substring
  2084. (point) (point-max)))
  2085. ")"))))
  2086. (ID (setq imap-id (read (buffer-substring (point)
  2087. (point-max)))))
  2088. (ACL (imap-parse-acl))
  2089. (t (case (prog1 (read (current-buffer))
  2090. (imap-forward))
  2091. (EXISTS (imap-mailbox-put 'exists token))
  2092. (RECENT (imap-mailbox-put 'recent token))
  2093. (EXPUNGE t)
  2094. (FETCH (imap-parse-fetch token))
  2095. (t (message "Garbage: %s" (buffer-string)))))))
  2096. (t (let (status)
  2097. (if (not (integerp token))
  2098. (message "Garbage: %s" (buffer-string))
  2099. (case (prog1 (setq status (read (current-buffer)))
  2100. (imap-forward))
  2101. (OK (progn
  2102. (setq imap-reached-tag (max imap-reached-tag token))
  2103. (imap-parse-resp-text)))
  2104. (NO (progn
  2105. (setq imap-reached-tag (max imap-reached-tag token))
  2106. (save-excursion
  2107. (imap-parse-resp-text))
  2108. (let (code text)
  2109. (when (eq (char-after) ?\[)
  2110. (setq code (buffer-substring (point)
  2111. (search-forward "]")))
  2112. (imap-forward))
  2113. (setq text (buffer-substring (point) (point-max)))
  2114. (push (list token status code text)
  2115. imap-failed-tags))))
  2116. (BAD (progn
  2117. (setq imap-reached-tag (max imap-reached-tag token))
  2118. (save-excursion
  2119. (imap-parse-resp-text))
  2120. (let (code text)
  2121. (when (eq (char-after) ?\[)
  2122. (setq code (buffer-substring (point)
  2123. (search-forward "]")))
  2124. (imap-forward))
  2125. (setq text (buffer-substring (point) (point-max)))
  2126. (push (list token status code text) imap-failed-tags)
  2127. (error "Internal error, tag %s status %s code %s text %s"
  2128. token status code text))))
  2129. (t (message "Garbage: %s" (buffer-string))))
  2130. (when (assq token imap-callbacks)
  2131. (funcall (cdr (assq token imap-callbacks)) token status)
  2132. (setq imap-callbacks
  2133. (imap-remassoc token imap-callbacks)))))))))
  2134. ;; resp-text = ["[" resp-text-code "]" SP] text
  2135. ;;
  2136. ;; text = 1*TEXT-CHAR
  2137. ;;
  2138. ;; TEXT-CHAR = <any CHAR except CR and LF>
  2139. (defun imap-parse-resp-text ()
  2140. (imap-parse-resp-text-code))
  2141. ;; resp-text-code = "ALERT" /
  2142. ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
  2143. ;; "NEWNAME" SP string SP string /
  2144. ;; "PARSE" /
  2145. ;; "PERMANENTFLAGS" SP "("
  2146. ;; [flag-perm *(SP flag-perm)] ")" /
  2147. ;; "READ-ONLY" /
  2148. ;; "READ-WRITE" /
  2149. ;; "TRYCREATE" /
  2150. ;; "UIDNEXT" SP nz-number /
  2151. ;; "UIDVALIDITY" SP nz-number /
  2152. ;; "UNSEEN" SP nz-number /
  2153. ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
  2154. ;;
  2155. ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
  2156. ;;
  2157. ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
  2158. ;;
  2159. ;; set = sequence-num / (sequence-num ":" sequence-num) /
  2160. ;; (set "," set)
  2161. ;; ; Identifies a set of messages. For message
  2162. ;; ; sequence numbers, these are consecutive
  2163. ;; ; numbers from 1 to the number of messages in
  2164. ;; ; the mailbox
  2165. ;; ; Comma delimits individual numbers, colon
  2166. ;; ; delimits between two numbers inclusive.
  2167. ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
  2168. ;; ; 14,15 for a mailbox with 15 messages.
  2169. ;;
  2170. ;; sequence-num = nz-number / "*"
  2171. ;; ; * is the largest number in use. For message
  2172. ;; ; sequence numbers, it is the number of messages
  2173. ;; ; in the mailbox. For unique identifiers, it is
  2174. ;; ; the unique identifier of the last message in
  2175. ;; ; the mailbox.
  2176. ;;
  2177. ;; flag-perm = flag / "\*"
  2178. ;;
  2179. ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
  2180. ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
  2181. ;; ; Does not include "\Recent"
  2182. ;;
  2183. ;; flag-extension = "\" atom
  2184. ;; ; Future expansion. Client implementations
  2185. ;; ; MUST accept flag-extension flags. Server
  2186. ;; ; implementations MUST NOT generate
  2187. ;; ; flag-extension flags except as defined by
  2188. ;; ; future standard or standards-track
  2189. ;; ; revisions of this specification.
  2190. ;;
  2191. ;; flag-keyword = atom
  2192. ;;
  2193. ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
  2194. (defun imap-parse-resp-text-code ()
  2195. ;; xxx next line for stalker communigate pro 3.3.1 bug
  2196. (when (looking-at " \\[")
  2197. (imap-forward))
  2198. (when (eq (char-after) ?\[)
  2199. (imap-forward)
  2200. (cond ((search-forward "PERMANENTFLAGS " nil t)
  2201. (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
  2202. ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
  2203. (imap-mailbox-put 'uidnext (match-string 1)))
  2204. ((search-forward "UNSEEN " nil t)
  2205. (imap-mailbox-put 'first-unseen (read (current-buffer))))
  2206. ((looking-at "UIDVALIDITY \\([0-9]+\\)")
  2207. (imap-mailbox-put 'uidvalidity (match-string 1)))
  2208. ((search-forward "READ-ONLY" nil t)
  2209. (imap-mailbox-put 'read-only t))
  2210. ((search-forward "NEWNAME " nil t)
  2211. (let (oldname newname)
  2212. (setq oldname (imap-parse-string))
  2213. (imap-forward)
  2214. (setq newname (imap-parse-string))
  2215. (imap-mailbox-put 'newname newname oldname)))
  2216. ((search-forward "TRYCREATE" nil t)
  2217. (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
  2218. ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
  2219. (imap-mailbox-put 'appenduid
  2220. (list (match-string 1)
  2221. (string-to-number (match-string 2)))
  2222. imap-current-target-mailbox))
  2223. ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
  2224. (imap-mailbox-put 'copyuid (list (match-string 1)
  2225. (match-string 2)
  2226. (match-string 3))
  2227. imap-current-target-mailbox))
  2228. ((search-forward "ALERT] " nil t)
  2229. (message "Imap server %s information: %s" imap-server
  2230. (buffer-substring (point) (point-max)))))))
  2231. ;; mailbox-list = "(" [mbx-list-flags] ")" SP
  2232. ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
  2233. ;;
  2234. ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
  2235. ;; *(SP mbx-list-oflag) /
  2236. ;; mbx-list-oflag *(SP mbx-list-oflag)
  2237. ;;
  2238. ;; mbx-list-oflag = "\Noinferiors" / flag-extension
  2239. ;; ; Other flags; multiple possible per LIST response
  2240. ;;
  2241. ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
  2242. ;; ; Selectability flags; only one per LIST response
  2243. ;;
  2244. ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
  2245. ;; "\" quoted-specials
  2246. ;;
  2247. ;; quoted-specials = DQUOTE / "\"
  2248. (defun imap-parse-data-list (type)
  2249. (let (flags delimiter mailbox)
  2250. (setq flags (imap-parse-flag-list))
  2251. (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
  2252. (setq delimiter (match-string 1))
  2253. (goto-char (1+ (match-end 0)))
  2254. (when (setq mailbox (imap-parse-mailbox))
  2255. (imap-mailbox-put type t mailbox)
  2256. (imap-mailbox-put 'list-flags flags mailbox)
  2257. (imap-mailbox-put 'delimiter delimiter mailbox)))))
  2258. ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
  2259. ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
  2260. ;; "INTERNALDATE" SPACE date_time /
  2261. ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
  2262. ;; "RFC822.SIZE" SPACE number /
  2263. ;; "BODY" ["STRUCTURE"] SPACE body /
  2264. ;; "BODY" section ["<" number ">"] SPACE nstring /
  2265. ;; "UID" SPACE uniqueid) ")"
  2266. ;;
  2267. ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
  2268. ;; SPACE time SPACE zone <">
  2269. ;;
  2270. ;; section ::= "[" [section_text / (nz_number *["." nz_number]
  2271. ;; ["." (section_text / "MIME")])] "]"
  2272. ;;
  2273. ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
  2274. ;; SPACE header_list / "TEXT"
  2275. ;;
  2276. ;; header_fld_name ::= astring
  2277. ;;
  2278. ;; header_list ::= "(" 1#header_fld_name ")"
  2279. (defsubst imap-parse-header-list ()
  2280. (when (eq (char-after) ?\()
  2281. (let (strlist)
  2282. (while (not (eq (char-after) ?\)))
  2283. (imap-forward)
  2284. (push (imap-parse-astring) strlist))
  2285. (imap-forward)
  2286. (nreverse strlist))))
  2287. (defsubst imap-parse-fetch-body-section ()
  2288. (let ((section
  2289. (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
  2290. (if (eq (char-before) ? )
  2291. (prog1
  2292. (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
  2293. (search-forward "]" nil t))
  2294. section)))
  2295. (defun imap-parse-fetch (response)
  2296. (when (eq (char-after) ?\()
  2297. (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
  2298. rfc822size body bodydetail bodystructure flags-empty)
  2299. ;; Courier can insert spurious blank characters which will
  2300. ;; confuse `read', so skip past them.
  2301. (while (let ((moved (skip-chars-forward " \t")))
  2302. (prog1 (not (eq (char-after) ?\)))
  2303. (unless (= moved 0) (backward-char))))
  2304. (imap-forward)
  2305. (let ((token (read (current-buffer))))
  2306. (imap-forward)
  2307. (cond ((eq token 'UID)
  2308. (setq uid (condition-case ()
  2309. (read (current-buffer))
  2310. (error))))
  2311. ((eq token 'FLAGS)
  2312. (setq flags (imap-parse-flag-list))
  2313. (if (not flags)
  2314. (setq flags-empty 't)))
  2315. ((eq token 'ENVELOPE)
  2316. (setq envelope (imap-parse-envelope)))
  2317. ((eq token 'INTERNALDATE)
  2318. (setq internaldate (imap-parse-string)))
  2319. ((eq token 'RFC822)
  2320. (setq rfc822 (imap-parse-nstring)))
  2321. ((eq token 'RFC822.HEADER)
  2322. (setq rfc822header (imap-parse-nstring)))
  2323. ((eq token 'RFC822.TEXT)
  2324. (setq rfc822text (imap-parse-nstring)))
  2325. ((eq token 'RFC822.SIZE)
  2326. (setq rfc822size (read (current-buffer))))
  2327. ((eq token 'BODY)
  2328. (if (eq (char-before) ?\[)
  2329. (push (list
  2330. (upcase (imap-parse-fetch-body-section))
  2331. (and (eq (char-after) ?<)
  2332. (buffer-substring (1+ (point))
  2333. (search-forward ">" nil t)))
  2334. (progn (imap-forward)
  2335. (imap-parse-nstring)))
  2336. bodydetail)
  2337. (setq body (imap-parse-body))))
  2338. ((eq token 'BODYSTRUCTURE)
  2339. (setq bodystructure (imap-parse-body))))))
  2340. (when uid
  2341. (setq imap-current-message uid)
  2342. (imap-message-put uid 'UID uid)
  2343. (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
  2344. (and envelope (imap-message-put uid 'ENVELOPE envelope))
  2345. (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
  2346. (and rfc822 (imap-message-put uid 'RFC822 rfc822))
  2347. (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
  2348. (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
  2349. (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
  2350. (and body (imap-message-put uid 'BODY body))
  2351. (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
  2352. (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
  2353. (run-hooks 'imap-fetch-data-hook)))))
  2354. ;; mailbox-data = ...
  2355. ;; "STATUS" SP mailbox SP "("
  2356. ;; [status-att SP number
  2357. ;; *(SP status-att SP number)] ")"
  2358. ;; ...
  2359. ;;
  2360. ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
  2361. ;; "UNSEEN"
  2362. (defun imap-parse-status ()
  2363. (let ((mailbox (imap-parse-mailbox)))
  2364. (if (eq (char-after) ? )
  2365. (forward-char))
  2366. (when (and mailbox (eq (char-after) ?\())
  2367. (while (and (not (eq (char-after) ?\)))
  2368. (or (forward-char) t)
  2369. (looking-at "\\([A-Za-z]+\\) "))
  2370. (let ((token (upcase (match-string 1))))
  2371. (goto-char (match-end 0))
  2372. (cond ((string= token "MESSAGES")
  2373. (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
  2374. ((string= token "RECENT")
  2375. (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
  2376. ((string= token "UIDNEXT")
  2377. (and (looking-at "[0-9]+")
  2378. (imap-mailbox-put 'uidnext (match-string 0) mailbox)
  2379. (goto-char (match-end 0))))
  2380. ((string= token "UIDVALIDITY")
  2381. (and (looking-at "[0-9]+")
  2382. (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
  2383. (goto-char (match-end 0))))
  2384. ((string= token "UNSEEN")
  2385. (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
  2386. (t
  2387. (message "Unknown status data %s in mailbox %s ignored"
  2388. token mailbox)
  2389. (read (current-buffer)))))))))
  2390. ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
  2391. ;; rights)
  2392. ;;
  2393. ;; identifier ::= astring
  2394. ;;
  2395. ;; rights ::= astring
  2396. (defun imap-parse-acl ()
  2397. (let ((mailbox (imap-parse-mailbox))
  2398. identifier rights acl)
  2399. (while (eq (char-after) ?\ )
  2400. (imap-forward)
  2401. (setq identifier (imap-parse-astring))
  2402. (imap-forward)
  2403. (setq rights (imap-parse-astring))
  2404. (setq acl (append acl (list (cons identifier rights)))))
  2405. (imap-mailbox-put 'acl acl mailbox)))
  2406. ;; flag-list = "(" [flag *(SP flag)] ")"
  2407. ;;
  2408. ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
  2409. ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
  2410. ;; ; Does not include "\Recent"
  2411. ;;
  2412. ;; flag-keyword = atom
  2413. ;;
  2414. ;; flag-extension = "\" atom
  2415. ;; ; Future expansion. Client implementations
  2416. ;; ; MUST accept flag-extension flags. Server
  2417. ;; ; implementations MUST NOT generate
  2418. ;; ; flag-extension flags except as defined by
  2419. ;; ; future standard or standards-track
  2420. ;; ; revisions of this specification.
  2421. (defun imap-parse-flag-list ()
  2422. (let (flag-list start)
  2423. (assert (eq (char-after) ?\() nil "In imap-parse-flag-list 1")
  2424. (while (and (not (eq (char-after) ?\)))
  2425. (setq start (progn
  2426. (imap-forward)
  2427. ;; next line for Courier IMAP bug.
  2428. (skip-chars-forward " ")
  2429. (point)))
  2430. (> (skip-chars-forward "^ )" (point-at-eol)) 0))
  2431. (push (buffer-substring start (point)) flag-list))
  2432. (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list 2")
  2433. (imap-forward)
  2434. (nreverse flag-list)))
  2435. ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
  2436. ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
  2437. ;; env-in-reply-to SP env-message-id ")"
  2438. ;;
  2439. ;; env-bcc = "(" 1*address ")" / nil
  2440. ;;
  2441. ;; env-cc = "(" 1*address ")" / nil
  2442. ;;
  2443. ;; env-date = nstring
  2444. ;;
  2445. ;; env-from = "(" 1*address ")" / nil
  2446. ;;
  2447. ;; env-in-reply-to = nstring
  2448. ;;
  2449. ;; env-message-id = nstring
  2450. ;;
  2451. ;; env-reply-to = "(" 1*address ")" / nil
  2452. ;;
  2453. ;; env-sender = "(" 1*address ")" / nil
  2454. ;;
  2455. ;; env-subject = nstring
  2456. ;;
  2457. ;; env-to = "(" 1*address ")" / nil
  2458. (defun imap-parse-envelope ()
  2459. (when (eq (char-after) ?\()
  2460. (imap-forward)
  2461. (vector (prog1 (imap-parse-nstring) ;; date
  2462. (imap-forward))
  2463. (prog1 (imap-parse-nstring) ;; subject
  2464. (imap-forward))
  2465. (prog1 (imap-parse-address-list) ;; from
  2466. (imap-forward))
  2467. (prog1 (imap-parse-address-list) ;; sender
  2468. (imap-forward))
  2469. (prog1 (imap-parse-address-list) ;; reply-to
  2470. (imap-forward))
  2471. (prog1 (imap-parse-address-list) ;; to
  2472. (imap-forward))
  2473. (prog1 (imap-parse-address-list) ;; cc
  2474. (imap-forward))
  2475. (prog1 (imap-parse-address-list) ;; bcc
  2476. (imap-forward))
  2477. (prog1 (imap-parse-nstring) ;; in-reply-to
  2478. (imap-forward))
  2479. (prog1 (imap-parse-nstring) ;; message-id
  2480. (imap-forward)))))
  2481. ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
  2482. (defsubst imap-parse-string-list ()
  2483. (cond ((eq (char-after) ?\() ;; body-fld-param
  2484. (let (strlist str)
  2485. (imap-forward)
  2486. (while (setq str (imap-parse-string))
  2487. (push str strlist)
  2488. ;; buggy stalker communigate pro 3.0 doesn't print SPC
  2489. ;; between body-fld-param's sometimes
  2490. (or (eq (char-after) ?\")
  2491. (imap-forward)))
  2492. (nreverse strlist)))
  2493. ((imap-parse-nil)
  2494. nil)))
  2495. ;; body-extension = nstring / number /
  2496. ;; "(" body-extension *(SP body-extension) ")"
  2497. ;; ; Future expansion. Client implementations
  2498. ;; ; MUST accept body-extension fields. Server
  2499. ;; ; implementations MUST NOT generate
  2500. ;; ; body-extension fields except as defined by
  2501. ;; ; future standard or standards-track
  2502. ;; ; revisions of this specification.
  2503. (defun imap-parse-body-extension ()
  2504. (if (eq (char-after) ?\()
  2505. (let (b-e)
  2506. (imap-forward)
  2507. (push (imap-parse-body-extension) b-e)
  2508. (while (eq (char-after) ?\ )
  2509. (imap-forward)
  2510. (push (imap-parse-body-extension) b-e))
  2511. (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
  2512. (imap-forward)
  2513. (nreverse b-e))
  2514. (or (imap-parse-number)
  2515. (imap-parse-nstring))))
  2516. ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
  2517. ;; *(SP body-extension)]]
  2518. ;; ; MUST NOT be returned on non-extensible
  2519. ;; ; "BODY" fetch
  2520. ;;
  2521. ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
  2522. ;; *(SP body-extension)]]
  2523. ;; ; MUST NOT be returned on non-extensible
  2524. ;; ; "BODY" fetch
  2525. (defsubst imap-parse-body-ext ()
  2526. (let (ext)
  2527. (when (eq (char-after) ?\ ) ;; body-fld-dsp
  2528. (imap-forward)
  2529. (let (dsp)
  2530. (if (eq (char-after) ?\()
  2531. (progn
  2532. (imap-forward)
  2533. (push (imap-parse-string) dsp)
  2534. (imap-forward)
  2535. (push (imap-parse-string-list) dsp)
  2536. (imap-forward))
  2537. ;; With assert, the code might not be eval'd.
  2538. ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
  2539. (imap-parse-nil))
  2540. (push (nreverse dsp) ext))
  2541. (when (eq (char-after) ?\ ) ;; body-fld-lang
  2542. (imap-forward)
  2543. (if (eq (char-after) ?\()
  2544. (push (imap-parse-string-list) ext)
  2545. (push (imap-parse-nstring) ext))
  2546. (while (eq (char-after) ?\ ) ;; body-extension
  2547. (imap-forward)
  2548. (setq ext (append (imap-parse-body-extension) ext)))))
  2549. ext))
  2550. ;; body = "(" body-type-1part / body-type-mpart ")"
  2551. ;;
  2552. ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
  2553. ;; *(SP body-extension)]]
  2554. ;; ; MUST NOT be returned on non-extensible
  2555. ;; ; "BODY" fetch
  2556. ;;
  2557. ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
  2558. ;; *(SP body-extension)]]
  2559. ;; ; MUST NOT be returned on non-extensible
  2560. ;; ; "BODY" fetch
  2561. ;;
  2562. ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
  2563. ;; body-fld-enc SP body-fld-octets
  2564. ;;
  2565. ;; body-fld-desc = nstring
  2566. ;;
  2567. ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
  2568. ;;
  2569. ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
  2570. ;; "QUOTED-PRINTABLE") DQUOTE) / string
  2571. ;;
  2572. ;; body-fld-id = nstring
  2573. ;;
  2574. ;; body-fld-lang = nstring / "(" string *(SP string) ")"
  2575. ;;
  2576. ;; body-fld-lines = number
  2577. ;;
  2578. ;; body-fld-md5 = nstring
  2579. ;;
  2580. ;; body-fld-octets = number
  2581. ;;
  2582. ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
  2583. ;;
  2584. ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
  2585. ;; [SP body-ext-1part]
  2586. ;;
  2587. ;; body-type-basic = media-basic SP body-fields
  2588. ;; ; MESSAGE subtype MUST NOT be "RFC822"
  2589. ;;
  2590. ;; body-type-msg = media-message SP body-fields SP envelope
  2591. ;; SP body SP body-fld-lines
  2592. ;;
  2593. ;; body-type-text = media-text SP body-fields SP body-fld-lines
  2594. ;;
  2595. ;; body-type-mpart = 1*body SP media-subtype
  2596. ;; [SP body-ext-mpart]
  2597. ;;
  2598. ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
  2599. ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
  2600. ;; ; Defined in [MIME-IMT]
  2601. ;;
  2602. ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
  2603. ;; ; Defined in [MIME-IMT]
  2604. ;;
  2605. ;; media-subtype = string
  2606. ;; ; Defined in [MIME-IMT]
  2607. ;;
  2608. ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
  2609. ;; ; Defined in [MIME-IMT]
  2610. (defun imap-parse-body ()
  2611. (let (body)
  2612. (when (eq (char-after) ?\()
  2613. (imap-forward)
  2614. (if (eq (char-after) ?\()
  2615. (let (subbody)
  2616. (while (and (eq (char-after) ?\()
  2617. (setq subbody (imap-parse-body)))
  2618. ;; buggy stalker communigate pro 3.0 inserts a SPC between
  2619. ;; parts in multiparts
  2620. (when (and (eq (char-after) ?\ )
  2621. (eq (char-after (1+ (point))) ?\())
  2622. (imap-forward))
  2623. (push subbody body))
  2624. (imap-forward)
  2625. (push (imap-parse-string) body) ;; media-subtype
  2626. (when (eq (char-after) ?\ ) ;; body-ext-mpart:
  2627. (imap-forward)
  2628. (if (eq (char-after) ?\() ;; body-fld-param
  2629. (push (imap-parse-string-list) body)
  2630. (push (and (imap-parse-nil) nil) body))
  2631. (setq body
  2632. (append (imap-parse-body-ext) body))) ;; body-ext-...
  2633. (assert (eq (char-after) ?\)) nil "In imap-parse-body")
  2634. (imap-forward)
  2635. (nreverse body))
  2636. (push (imap-parse-string) body) ;; media-type
  2637. (imap-forward)
  2638. (push (imap-parse-string) body) ;; media-subtype
  2639. (imap-forward)
  2640. ;; next line for Sun SIMS bug
  2641. (and (eq (char-after) ? ) (imap-forward))
  2642. (if (eq (char-after) ?\() ;; body-fld-param
  2643. (push (imap-parse-string-list) body)
  2644. (push (and (imap-parse-nil) nil) body))
  2645. (imap-forward)
  2646. (push (imap-parse-nstring) body) ;; body-fld-id
  2647. (imap-forward)
  2648. (push (imap-parse-nstring) body) ;; body-fld-desc
  2649. (imap-forward)
  2650. ;; Next `or' for Sun SIMS bug. It regards body-fld-enc as a
  2651. ;; nstring and returns nil instead of defaulting back to 7BIT
  2652. ;; as the standard says.
  2653. ;; Exchange (2007, at least) does this as well.
  2654. (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
  2655. (imap-forward)
  2656. ;; Exchange 2007 can return -1, contrary to the spec...
  2657. (if (eq (char-after) ?-)
  2658. (progn
  2659. (skip-chars-forward "-0-9")
  2660. (push nil body))
  2661. (push (imap-parse-number) body)) ;; body-fld-octets
  2662. ;; Ok, we're done parsing the required parts, what comes now is one of
  2663. ;; three things:
  2664. ;;
  2665. ;; envelope (then we're parsing body-type-msg)
  2666. ;; body-fld-lines (then we're parsing body-type-text)
  2667. ;; body-ext-1part (then we're parsing body-type-basic)
  2668. ;;
  2669. ;; The problem is that the two first are in turn optionally followed
  2670. ;; by the third. So we parse the first two here (if there are any)...
  2671. (when (eq (char-after) ?\ )
  2672. (imap-forward)
  2673. (let (lines)
  2674. (cond ((eq (char-after) ?\() ;; body-type-msg:
  2675. (push (imap-parse-envelope) body) ;; envelope
  2676. (imap-forward)
  2677. (push (imap-parse-body) body) ;; body
  2678. ;; buggy stalker communigate pro 3.0 doesn't print
  2679. ;; number of lines in message/rfc822 attachment
  2680. (if (eq (char-after) ?\))
  2681. (push 0 body)
  2682. (imap-forward)
  2683. (push (imap-parse-number) body))) ;; body-fld-lines
  2684. ((setq lines (imap-parse-number)) ;; body-type-text:
  2685. (push lines body)) ;; body-fld-lines
  2686. (t
  2687. (backward-char))))) ;; no match...
  2688. ;; ...and then parse the third one here...
  2689. (when (eq (char-after) ?\ ) ;; body-ext-1part:
  2690. (imap-forward)
  2691. (push (imap-parse-nstring) body) ;; body-fld-md5
  2692. (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
  2693. (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
  2694. (imap-forward)
  2695. (nreverse body)))))
  2696. (when imap-debug ; (untrace-all)
  2697. (require 'trace)
  2698. (buffer-disable-undo (get-buffer-create imap-debug-buffer))
  2699. (mapc (lambda (f) (trace-function-background f imap-debug-buffer))
  2700. '(
  2701. imap-utf7-encode
  2702. imap-utf7-decode
  2703. imap-error-text
  2704. imap-kerberos4s-p
  2705. imap-kerberos4-open
  2706. imap-ssl-p
  2707. imap-ssl-open
  2708. imap-network-p
  2709. imap-network-open
  2710. imap-interactive-login
  2711. imap-kerberos4a-p
  2712. imap-kerberos4-auth
  2713. imap-cram-md5-p
  2714. imap-cram-md5-auth
  2715. imap-login-p
  2716. imap-login-auth
  2717. imap-anonymous-p
  2718. imap-anonymous-auth
  2719. imap-open-1
  2720. imap-open
  2721. imap-opened
  2722. imap-ping-server
  2723. imap-authenticate
  2724. imap-close
  2725. imap-capability
  2726. imap-namespace
  2727. imap-send-command-wait
  2728. imap-mailbox-put
  2729. imap-mailbox-get
  2730. imap-mailbox-map-1
  2731. imap-mailbox-map
  2732. imap-current-mailbox
  2733. imap-current-mailbox-p-1
  2734. imap-current-mailbox-p
  2735. imap-mailbox-select-1
  2736. imap-mailbox-select
  2737. imap-mailbox-examine-1
  2738. imap-mailbox-examine
  2739. imap-mailbox-unselect
  2740. imap-mailbox-expunge
  2741. imap-mailbox-close
  2742. imap-mailbox-create-1
  2743. imap-mailbox-create
  2744. imap-mailbox-delete
  2745. imap-mailbox-rename
  2746. imap-mailbox-lsub
  2747. imap-mailbox-list
  2748. imap-mailbox-subscribe
  2749. imap-mailbox-unsubscribe
  2750. imap-mailbox-status
  2751. imap-mailbox-acl-get
  2752. imap-mailbox-acl-set
  2753. imap-mailbox-acl-delete
  2754. imap-current-message
  2755. imap-list-to-message-set
  2756. imap-fetch-asynch
  2757. imap-fetch
  2758. imap-fetch-safe
  2759. imap-message-put
  2760. imap-message-get
  2761. imap-message-map
  2762. imap-search
  2763. imap-message-flag-permanent-p
  2764. imap-message-flags-set
  2765. imap-message-flags-del
  2766. imap-message-flags-add
  2767. imap-message-copyuid-1
  2768. imap-message-copyuid
  2769. imap-message-copy
  2770. imap-message-appenduid-1
  2771. imap-message-appenduid
  2772. imap-message-append
  2773. imap-body-lines
  2774. imap-envelope-from
  2775. imap-send-command-1
  2776. imap-send-command
  2777. imap-wait-for-tag
  2778. imap-sentinel
  2779. imap-find-next-line
  2780. imap-arrival-filter
  2781. imap-parse-greeting
  2782. imap-parse-response
  2783. imap-parse-resp-text
  2784. imap-parse-resp-text-code
  2785. imap-parse-data-list
  2786. imap-parse-fetch
  2787. imap-parse-status
  2788. imap-parse-acl
  2789. imap-parse-flag-list
  2790. imap-parse-envelope
  2791. imap-parse-body-extension
  2792. imap-parse-body
  2793. )))
  2794. (provide 'imap)
  2795. ;;; imap.el ends here