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