5c30a5788d83464ca47b99e91e5beeaccbdb1d41
[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)
1319   (imap-mailbox-get-1 propname (or (imap-utf7-encode mailbox)
1320                                    imap-current-mailbox)))
1321
1322 (defun imap-mailbox-map-1 (func &optional mailbox-decoder)
1323   (let (result)
1324     (mapatoms
1325      (lambda (s)
1326        (push (funcall func (if mailbox-decoder
1327                                (funcall mailbox-decoder (symbol-name s))
1328                              (symbol-name s))) result))
1329      imap-mailbox-data)
1330     result))
1331
1332 (defun imap-mailbox-map (func)
1333   "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1334 Function should take a mailbox name (a string) as
1335 the only argument."
1336   (imap-mailbox-map-1 func 'imap-utf7-decode))
1337
1338 (defun imap-current-mailbox (&optional buffer)
1339   (with-current-buffer (or buffer (current-buffer))
1340     (imap-utf7-decode imap-current-mailbox)))
1341
1342 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1343   (and (string= mailbox imap-current-mailbox)
1344        (or (and examine
1345                 (eq imap-state 'examine))
1346            (and (not examine)
1347                 (eq imap-state 'selected)))))
1348
1349 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1350   (with-current-buffer (or buffer (current-buffer))
1351     (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1352
1353 (defun imap-mailbox-select-1 (mailbox &optional examine)
1354   "Select MAILBOX on server in BUFFER.
1355 If EXAMINE is non-nil, do a read-only select."
1356   (if (imap-current-mailbox-p-1 mailbox examine)
1357       imap-current-mailbox
1358     (setq imap-current-mailbox mailbox)
1359     (if (imap-ok-p (imap-send-command-wait
1360                     (concat (if examine "EXAMINE" "SELECT") " \""
1361                             mailbox "\"")))
1362         (progn
1363           (setq imap-message-data (make-vector imap-message-prime 0)
1364                 imap-state (if examine 'examine 'selected))
1365           imap-current-mailbox)
1366       ;; Failed SELECT/EXAMINE unselects current mailbox
1367       (setq imap-current-mailbox nil))))
1368
1369 (defun imap-mailbox-select (mailbox &optional examine buffer)
1370   (with-current-buffer (or buffer (current-buffer))
1371     (imap-utf7-decode
1372      (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1373
1374 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1375   (with-current-buffer (or buffer (current-buffer))
1376     (imap-mailbox-select-1 mailbox 'examine)))
1377
1378 (defun imap-mailbox-examine (mailbox &optional buffer)
1379   "Examine MAILBOX on server in BUFFER."
1380   (imap-mailbox-select mailbox 'examine buffer))
1381
1382 (defun imap-mailbox-unselect (&optional buffer)
1383   "Close current folder in BUFFER, without expunging articles."
1384   (with-current-buffer (or buffer (current-buffer))
1385     (when (or (eq imap-state 'auth)
1386               (and (imap-capability 'UNSELECT)
1387                    (imap-ok-p (imap-send-command-wait "UNSELECT")))
1388               (and (imap-ok-p
1389                     (imap-send-command-wait (concat "EXAMINE \""
1390                                                     imap-current-mailbox
1391                                                     "\"")))
1392                    (imap-ok-p (imap-send-command-wait "CLOSE"))))
1393       (setq imap-current-mailbox nil
1394             imap-message-data nil
1395             imap-state 'auth)
1396       t)))
1397
1398 (defun imap-mailbox-expunge (&optional asynch buffer)
1399   "Expunge articles in current folder in BUFFER.
1400 If ASYNCH, do not wait for successful completion of the command.
1401 If BUFFER is nil the current buffer is assumed."
1402   (with-current-buffer (or buffer (current-buffer))
1403     (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1404       (if asynch
1405           (imap-send-command "EXPUNGE")
1406       (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1407
1408 (defun imap-mailbox-close (&optional asynch buffer)
1409   "Expunge articles and close current folder in BUFFER.
1410 If ASYNCH, do not wait for successful completion of the command.
1411 If BUFFER is nil the current buffer is assumed."
1412   (with-current-buffer (or buffer (current-buffer))
1413     (when imap-current-mailbox
1414       (if asynch
1415           (imap-add-callback (imap-send-command "CLOSE")
1416                              `(lambda (tag status)
1417                                 (message "IMAP mailbox `%s' closed... %s"
1418                                          imap-current-mailbox status)
1419                                 (when (eq ,imap-current-mailbox
1420                                           imap-current-mailbox)
1421                                   ;; Don't wipe out data if another mailbox
1422                                   ;; was selected...
1423                                   (setq imap-current-mailbox nil
1424                                         imap-message-data nil
1425                                         imap-state 'auth))))
1426         (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1427           (setq imap-current-mailbox nil
1428                 imap-message-data nil
1429                 imap-state 'auth)))
1430       t)))
1431
1432 (defun imap-mailbox-create-1 (mailbox)
1433   (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1434
1435 (defun imap-mailbox-create (mailbox &optional buffer)
1436   "Create MAILBOX on server in BUFFER.
1437 If BUFFER is nil the current buffer is assumed."
1438   (with-current-buffer (or buffer (current-buffer))
1439     (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1440
1441 (defun imap-mailbox-delete (mailbox &optional buffer)
1442   "Delete MAILBOX on server in BUFFER.
1443 If BUFFER is nil the current buffer is assumed."
1444   (let ((mailbox (imap-utf7-encode mailbox)))
1445     (with-current-buffer (or buffer (current-buffer))
1446       (imap-ok-p
1447        (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1448
1449 (defun imap-mailbox-rename (oldname newname &optional buffer)
1450   "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1451 If BUFFER is nil the current buffer is assumed."
1452   (let ((oldname (imap-utf7-encode oldname))
1453         (newname (imap-utf7-encode newname)))
1454     (with-current-buffer (or buffer (current-buffer))
1455       (imap-ok-p
1456        (imap-send-command-wait (list "RENAME \"" oldname "\" "
1457                                      "\"" newname "\""))))))
1458
1459 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1460   "Return a list of subscribed mailboxes on server in BUFFER.
1461 If ROOT is non-nil, only list matching mailboxes.  If ADD-DELIMITER is
1462 non-nil, a hierarchy delimiter is added to root.  REFERENCE is a
1463 implementation-specific string that has to be passed to lsub command."
1464   (with-current-buffer (or buffer (current-buffer))
1465     ;; Make sure we know the hierarchy separator for root's hierarchy
1466     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1467       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1468                                       (imap-utf7-encode root) "\"")))
1469     ;; clear list data (NB not delimiter and other stuff)
1470     (imap-mailbox-map-1 (lambda (mailbox)
1471                           (imap-mailbox-put 'lsub nil mailbox)))
1472     (when (imap-ok-p
1473            (imap-send-command-wait
1474             (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1475                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1476                     "%\"")))
1477       (let (out)
1478         (imap-mailbox-map-1 (lambda (mailbox)
1479                               (when (imap-mailbox-get-1 'lsub mailbox)
1480                                 (push (imap-utf7-decode mailbox) out))))
1481         (nreverse out)))))
1482
1483 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1484   "Return a list of mailboxes matching ROOT on server in BUFFER.
1485 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1486 root.  REFERENCE is a implementation-specific string that has to be
1487 passed to list command."
1488   (with-current-buffer (or buffer (current-buffer))
1489     ;; Make sure we know the hierarchy separator for root's hierarchy
1490     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1491       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1492                                       (imap-utf7-encode root) "\"")))
1493     ;; clear list data (NB not delimiter and other stuff)
1494     (imap-mailbox-map-1 (lambda (mailbox)
1495                           (imap-mailbox-put 'list nil mailbox)))
1496     (when (imap-ok-p
1497            (imap-send-command-wait
1498             (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1499                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1500                     "%\"")))
1501       (let (out)
1502         (imap-mailbox-map-1 (lambda (mailbox)
1503                               (when (imap-mailbox-get-1 'list mailbox)
1504                                 (push (imap-utf7-decode mailbox) out))))
1505         (nreverse out)))))
1506
1507 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1508   "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1509 Returns non-nil if successful."
1510   (with-current-buffer (or buffer (current-buffer))
1511     (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1512                                                (imap-utf7-encode mailbox)
1513                                                "\"")))))
1514
1515 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1516   "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1517 Returns non-nil if successful."
1518   (with-current-buffer (or buffer (current-buffer))
1519     (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1520                                                (imap-utf7-encode mailbox)
1521                                                "\"")))))
1522
1523 (defun imap-mailbox-status (mailbox items &optional buffer)
1524   "Get status items ITEM in MAILBOX from server in BUFFER.
1525 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1526 the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
1527 or `unseen'.  If ITEMS is a list of symbols, a list of values is
1528 returned, if ITEMS is a symbol only its value is returned."
1529   (with-current-buffer (or buffer (current-buffer))
1530     (when (imap-ok-p
1531            (imap-send-command-wait (list "STATUS \""
1532                                          (imap-utf7-encode mailbox)
1533                                          "\" "
1534                                          (upcase
1535                                           (format "%s"
1536                                                   (if (listp items)
1537                                                       items
1538                                                     (list items)))))))
1539       (if (listp items)
1540           (mapcar (lambda (item)
1541                     (imap-mailbox-get item mailbox))
1542                   items)
1543         (imap-mailbox-get items mailbox)))))
1544
1545 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1546   "Send status item request ITEM on MAILBOX to server in BUFFER.
1547 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1548 the STATUS data items -- i.e. 'messages, 'recent, 'uidnext, 'uidvalidity
1549 or 'unseen.  The IMAP command tag is returned."
1550   (with-current-buffer (or buffer (current-buffer))
1551     (imap-send-command (list "STATUS \""
1552                              (imap-utf7-encode mailbox)
1553                              "\" "
1554                              (upcase
1555                               (format "%s"
1556                                       (if (listp items)
1557                                           items
1558                                         (list items))))))))
1559
1560 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1561   "Get ACL on MAILBOX from server in BUFFER."
1562   (let ((mailbox (imap-utf7-encode mailbox)))
1563     (with-current-buffer (or buffer (current-buffer))
1564       (when (imap-ok-p
1565              (imap-send-command-wait (list "GETACL \""
1566                                            (or mailbox imap-current-mailbox)
1567                                            "\"")))
1568         (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1569
1570 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1571   "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1572   (let ((mailbox (imap-utf7-encode mailbox)))
1573     (with-current-buffer (or buffer (current-buffer))
1574       (imap-ok-p
1575        (imap-send-command-wait (list "SETACL \""
1576                                      (or mailbox imap-current-mailbox)
1577                                      "\" "
1578                                      identifier
1579                                      " "
1580                                      rights))))))
1581
1582 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1583   "Remove any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1584   (let ((mailbox (imap-utf7-encode mailbox)))
1585     (with-current-buffer (or buffer (current-buffer))
1586       (imap-ok-p
1587        (imap-send-command-wait (list "DELETEACL \""
1588                                      (or mailbox imap-current-mailbox)
1589                                      "\" "
1590                                      identifier))))))
1591
1592 \f
1593 ;; Message functions:
1594
1595 (defun imap-current-message (&optional buffer)
1596   (with-current-buffer (or buffer (current-buffer))
1597     imap-current-message))
1598
1599 (defun imap-list-to-message-set (list)
1600   (mapconcat (lambda (item)
1601                (number-to-string item))
1602              (if (listp list)
1603                  list
1604                (list list))
1605              ","))
1606
1607 (defun imap-range-to-message-set (range)
1608   (mapconcat
1609    (lambda (item)
1610      (if (consp item)
1611          (format "%d:%d"
1612                  (car item) (cdr item))
1613        (format "%d" item)))
1614    (if (and (listp range) (not (listp (cdr range))))
1615        (list range) ;; make (1 . 2) into ((1 . 2))
1616      range)
1617    ","))
1618
1619 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1620   (with-current-buffer (or buffer (current-buffer))
1621     (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1622                                (if (listp uids)
1623                                    (imap-list-to-message-set uids)
1624                                  uids)
1625                                props))))
1626
1627 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1628   "Fetch properties PROPS from message set UIDS from server in BUFFER.
1629 UIDS can be a string, number or a list of numbers.  If RECEIVE
1630 is non-nil return these properties."
1631   (with-current-buffer (or buffer (current-buffer))
1632     (when (imap-ok-p (imap-send-command-wait
1633                       (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1634                               (if (listp uids)
1635                                   (imap-list-to-message-set uids)
1636                                 uids)
1637                               props)))
1638       (if (or (null receive) (stringp uids))
1639           t
1640         (if (listp uids)
1641             (mapcar (lambda (uid)
1642                       (if (listp receive)
1643                           (mapcar (lambda (prop)
1644                                     (imap-message-get uid prop))
1645                                   receive)
1646                         (imap-message-get uid receive)))
1647                     uids)
1648           (imap-message-get uids receive))))))
1649
1650 (defun imap-message-put (uid propname value)
1651   (if imap-message-data
1652       (put (intern (number-to-string uid) imap-message-data)
1653            propname value)
1654     (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1655            uid propname value (current-buffer)))
1656   t)
1657
1658 (defun imap-message-get (uid propname)
1659   (get (intern-soft (number-to-string uid) imap-message-data)
1660        propname))
1661
1662 (defun imap-message-map (func propname)
1663   "Map a function across each message in `imap-message-data', returning a list."
1664   (let (result)
1665     (mapatoms
1666      (lambda (s)
1667        (push (funcall func (get s 'UID) (get s propname)) result))
1668      imap-message-data)
1669     result))
1670
1671 (defmacro imap-message-envelope-date (uid &optional buffer)
1672   `(with-current-buffer (or ,buffer (current-buffer))
1673      (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1674
1675 (defmacro imap-message-envelope-subject (uid &optional buffer)
1676   `(with-current-buffer (or ,buffer (current-buffer))
1677      (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1678
1679 (defmacro imap-message-envelope-from (uid &optional buffer)
1680   `(with-current-buffer (or ,buffer (current-buffer))
1681      (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1682
1683 (defmacro imap-message-envelope-sender (uid &optional buffer)
1684   `(with-current-buffer (or ,buffer (current-buffer))
1685      (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1686
1687 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1688   `(with-current-buffer (or ,buffer (current-buffer))
1689      (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1690
1691 (defmacro imap-message-envelope-to (uid &optional buffer)
1692   `(with-current-buffer (or ,buffer (current-buffer))
1693      (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1694
1695 (defmacro imap-message-envelope-cc (uid &optional buffer)
1696   `(with-current-buffer (or ,buffer (current-buffer))
1697      (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1698
1699 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1700   `(with-current-buffer (or ,buffer (current-buffer))
1701      (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1702
1703 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1704   `(with-current-buffer (or ,buffer (current-buffer))
1705      (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1706
1707 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1708   `(with-current-buffer (or ,buffer (current-buffer))
1709      (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1710
1711 (defmacro imap-message-body (uid &optional buffer)
1712   `(with-current-buffer (or ,buffer (current-buffer))
1713      (imap-message-get ,uid 'BODY)))
1714
1715 ;; FIXME: Should this try to use CHARSET?  -- fx
1716 (defun imap-search (predicate &optional buffer)
1717   (with-current-buffer (or buffer (current-buffer))
1718     (imap-mailbox-put 'search 'dummy)
1719     (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1720       (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1721           (progn
1722             (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1723             nil)
1724         (imap-mailbox-get-1 'search imap-current-mailbox)))))
1725
1726 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1727   "Return t if FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1728   (with-current-buffer (or buffer (current-buffer))
1729     (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1730         (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1731
1732 (defun imap-message-flags-set (articles flags &optional silent buffer)
1733   (when (and articles flags)
1734     (with-current-buffer (or buffer (current-buffer))
1735       (imap-ok-p (imap-send-command-wait
1736                   (concat "UID STORE " articles
1737                           " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1738
1739 (defun imap-message-flags-del (articles flags &optional silent buffer)
1740   (when (and articles flags)
1741     (with-current-buffer (or buffer (current-buffer))
1742       (imap-ok-p (imap-send-command-wait
1743                   (concat "UID STORE " articles
1744                           " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1745
1746 (defun imap-message-flags-add (articles flags &optional silent buffer)
1747   (when (and articles flags)
1748     (with-current-buffer (or buffer (current-buffer))
1749       (imap-ok-p (imap-send-command-wait
1750                   (concat "UID STORE " articles
1751                           " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1752
1753 ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
1754 ;; Signal an error if we'd get an integer overflow.
1755 ;;
1756 ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
1757 ;; `imap-string-to-integer'.
1758 (defun imap-string-to-integer (string &optional base)
1759   (let ((number (string-to-number string base)))
1760     (if (> number most-positive-fixnum)
1761         (error
1762          (format "String %s cannot be converted to a Lisp integer" number))
1763       number)))
1764
1765 (defun imap-message-copyuid-1 (mailbox)
1766   (if (imap-capability 'UIDPLUS)
1767       (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1768             (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1769     (let ((old-mailbox imap-current-mailbox)
1770           (state imap-state)
1771           (imap-message-data (make-vector 2 0)))
1772       (when (imap-mailbox-examine-1 mailbox)
1773         (prog1
1774             (and (imap-fetch "*:*" "UID")
1775                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1776                        (apply 'max (imap-message-map
1777                                     (lambda (uid prop) uid) 'UID))))
1778           (if old-mailbox
1779               (imap-mailbox-select old-mailbox (eq state 'examine))
1780             (imap-mailbox-unselect)))))))
1781
1782 (defun imap-message-copyuid (mailbox &optional buffer)
1783   (with-current-buffer (or buffer (current-buffer))
1784     (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1785
1786 (defun imap-message-copy (articles mailbox
1787                                    &optional dont-create no-copyuid buffer)
1788   "Copy ARTICLES to MAILBOX on server in BUFFER.
1789 ARTICLES is a string message set.  Create mailbox if it doesn't exist,
1790 unless DONT-CREATE is non-nil.  On success, return a list with
1791 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1792 first element.  The rest of list contains the saved articles' UIDs."
1793   (when articles
1794     (with-current-buffer (or buffer (current-buffer))
1795       (let ((mailbox (imap-utf7-encode mailbox)))
1796         (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1797                   (imap-current-target-mailbox mailbox))
1798               (if (imap-ok-p (imap-send-command-wait cmd))
1799                   t
1800                 (when (and (not dont-create)
1801                            ;; removed because of buggy Oracle server
1802                            ;; that doesn't send TRYCREATE tags (which
1803                            ;; is a MUST according to specifications):
1804                            ;;(imap-mailbox-get-1 'trycreate mailbox)
1805                            (imap-mailbox-create-1 mailbox))
1806                   (imap-ok-p (imap-send-command-wait cmd)))))
1807             (or no-copyuid
1808                 (imap-message-copyuid-1 mailbox)))))))
1809
1810 ;; FIXME: Amalgamate with imap-message-copyuid-1, using an extra arg, since it
1811 ;; shares most of the code?  -- fx
1812 (defun imap-message-appenduid-1 (mailbox)
1813   (if (imap-capability 'UIDPLUS)
1814       (imap-mailbox-get-1 'appenduid mailbox)
1815     (let ((old-mailbox imap-current-mailbox)
1816           (state imap-state)
1817           (imap-message-data (make-vector 2 0)))
1818       (when (imap-mailbox-examine-1 mailbox)
1819         (prog1
1820             (and (imap-fetch "*:*" "UID")
1821                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1822                        (apply 'max (imap-message-map
1823                                     (lambda (uid prop) uid) 'UID))))
1824           (if old-mailbox
1825               (imap-mailbox-select old-mailbox (eq state 'examine))
1826             (imap-mailbox-unselect)))))))
1827
1828 (defun imap-message-appenduid (mailbox &optional buffer)
1829   (with-current-buffer (or buffer (current-buffer))
1830     (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1831
1832 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1833   "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1834 FLAGS and DATE-TIME is currently not used.  Return a cons holding
1835 uidvalidity of MAILBOX and UID the newly created article got, or nil
1836 on failure."
1837   (let ((mailbox (imap-utf7-encode mailbox)))
1838     (with-current-buffer (or buffer (current-buffer))
1839       (and (let ((imap-current-target-mailbox mailbox))
1840              (imap-ok-p
1841               (imap-send-command-wait
1842                (list "APPEND \"" mailbox "\" "  article))))
1843            (imap-message-appenduid-1 mailbox)))))
1844
1845 (defun imap-body-lines (body)
1846   "Return number of lines in article by looking at the mime bodystructure BODY."
1847   (if (listp body)
1848       (if (stringp (car body))
1849           (cond ((and (string= (upcase (car body)) "TEXT")
1850                       (numberp (nth 7 body)))
1851                  (nth 7 body))
1852                 ((and (string= (upcase (car body)) "MESSAGE")
1853                       (numberp (nth 9 body)))
1854                  (nth 9 body))
1855                 (t 0))
1856         (apply '+ (mapcar 'imap-body-lines body)))
1857     0))
1858
1859 (defun imap-envelope-from (from)
1860   "Return a from string line."
1861   (and from
1862        (concat (aref from 0)
1863                (if (aref from 0) " <")
1864                (aref from 2)
1865                "@"
1866                (aref from 3)
1867                (if (aref from 0) ">"))))
1868
1869 \f
1870 ;; Internal functions.
1871
1872 (defun imap-add-callback (tag func)
1873   (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1874
1875 (defun imap-send-command-1 (cmdstr)
1876   (setq cmdstr (concat cmdstr imap-client-eol))
1877   (imap-log cmdstr)
1878   (process-send-string imap-process cmdstr))
1879
1880 (defun imap-send-command (command &optional buffer)
1881   (with-current-buffer (or buffer (current-buffer))
1882     (if (not (listp command)) (setq command (list command)))
1883     (let ((tag (setq imap-tag (1+ imap-tag)))
1884           cmd cmdstr)
1885       (setq cmdstr (concat (number-to-string imap-tag) " "))
1886       (while (setq cmd (pop command))
1887         (cond ((stringp cmd)
1888                (setq cmdstr (concat cmdstr cmd)))
1889               ((bufferp cmd)
1890                (let ((eol imap-client-eol)
1891                      (calcfirst imap-calculate-literal-size-first)
1892                      size)
1893                  (with-current-buffer cmd
1894                    (if calcfirst
1895                        (setq size (buffer-size)))
1896                    (when (not (equal eol "\r\n"))
1897                      ;; XXX modifies buffer!
1898                      (goto-char (point-min))
1899                      (while (search-forward "\r\n" nil t)
1900                        (replace-match eol)))
1901                    (if (not calcfirst)
1902                        (setq size (buffer-size))))
1903                  (setq cmdstr
1904                        (concat cmdstr (format "{%d}" size))))
1905                (unwind-protect
1906                    (progn
1907                      (imap-send-command-1 cmdstr)
1908                      (setq cmdstr nil)
1909                      (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1910                          (setq command nil) ;; abort command if no cont-req
1911                        (let ((process imap-process)
1912                              (stream imap-stream)
1913                              (eol imap-client-eol))
1914                          (with-current-buffer cmd
1915                            (imap-log cmd)
1916                            (process-send-region process (point-min)
1917                                                 (point-max)))
1918                          (process-send-string process imap-client-eol))))
1919                  (setq imap-continuation nil)))
1920               ((functionp cmd)
1921                (imap-send-command-1 cmdstr)
1922                (setq cmdstr nil)
1923                (unwind-protect
1924                    (setq command
1925                          (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1926                              nil ;; abort command if no cont-req
1927                            (cons (funcall cmd imap-continuation)
1928                                  command)))
1929                  (setq imap-continuation nil)))
1930               (t
1931                (error "Unknown command type"))))
1932       (if cmdstr
1933           (imap-send-command-1 cmdstr))
1934       tag)))
1935
1936 (defun imap-wait-for-tag (tag &optional buffer)
1937   (with-current-buffer (or buffer (current-buffer))
1938     (let (imap-have-messaged)
1939       (while (and (null imap-continuation)
1940                   (memq (process-status imap-process) '(open run))
1941                   (< imap-reached-tag tag))
1942         (let ((len (/ (buffer-size) 1024))
1943               message-log-max)
1944           (unless (< len 10)
1945             (setq imap-have-messaged t)
1946             (message "imap read: %dk" len))
1947           (accept-process-output imap-process
1948                                  (truncate imap-read-timeout)
1949                                  (truncate (* (- imap-read-timeout
1950                                                  (truncate imap-read-timeout))
1951                                               1000)))))
1952       ;; A process can die _before_ we have processed everything it
1953       ;; has to say.  Moreover, this can happen in between the call to
1954       ;; accept-process-output and the call to process-status in an
1955       ;; iteration of the loop above.
1956       (when (and (null imap-continuation)
1957                  (< imap-reached-tag tag))
1958         (accept-process-output imap-process 0 0))
1959       (when imap-have-messaged
1960         (message ""))
1961       (and (memq (process-status imap-process) '(open run))
1962            (or (assq tag imap-failed-tags)
1963                (if imap-continuation
1964                    'INCOMPLETE
1965                  'OK))))))
1966
1967 (defun imap-sentinel (process string)
1968   (delete-process process))
1969
1970 (defun imap-find-next-line ()
1971   "Return point at end of current line, taking into account literals.
1972 Return nil if no complete line has arrived."
1973   (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1974                                    imap-server-eol)
1975                            nil t)
1976     (if (match-string 1)
1977         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1978             nil
1979           (goto-char (+ (point) (string-to-number (match-string 1))))
1980           (imap-find-next-line))
1981       (point))))
1982
1983 (defun imap-arrival-filter (proc string)
1984   "IMAP process filter."
1985   ;; Sometimes, we are called even though the process has died.
1986   ;; Better abstain from doing stuff in that case.
1987   (when (buffer-name (process-buffer proc))
1988     (with-current-buffer (process-buffer proc)
1989       (goto-char (point-max))
1990       (insert string)
1991       (imap-log string)
1992       (let (end)
1993         (goto-char (point-min))
1994         (while (setq end (imap-find-next-line))
1995           (save-restriction
1996             (narrow-to-region (point-min) end)
1997             (delete-char (- (length imap-server-eol)))
1998             (goto-char (point-min))
1999             (unwind-protect
2000                 (cond ((eq imap-state 'initial)
2001                        (imap-parse-greeting))
2002                       ((or (eq imap-state 'auth)
2003                            (eq imap-state 'nonauth)
2004                            (eq imap-state 'selected)
2005                            (eq imap-state 'examine))
2006                        (imap-parse-response))
2007                       (t
2008                        (message "Unknown state %s in arrival filter"
2009                                 imap-state)))
2010               (delete-region (point-min) (point-max)))))))))
2011
2012 \f
2013 ;; Imap parser.
2014
2015 (defsubst imap-forward ()
2016   (or (eobp) (forward-char)))
2017
2018 ;;   number          = 1*DIGIT
2019 ;;                       ; Unsigned 32-bit integer
2020 ;;                       ; (0 <= n < 4,294,967,296)
2021
2022 (defsubst imap-parse-number ()
2023   (when (looking-at "[0-9]+")
2024     (prog1
2025         (string-to-number (match-string 0))
2026       (goto-char (match-end 0)))))
2027
2028 ;;   literal         = "{" number "}" CRLF *CHAR8
2029 ;;                       ; Number represents the number of CHAR8s
2030
2031 (defsubst imap-parse-literal ()
2032   (when (looking-at "{\\([0-9]+\\)}\r\n")
2033     (let ((pos (match-end 0))
2034           (len (string-to-number (match-string 1))))
2035       (if (< (point-max) (+ pos len))
2036           nil
2037         (goto-char (+ pos len))
2038         (buffer-substring pos (+ pos len))))))
2039
2040 ;;   string          = quoted / literal
2041 ;;
2042 ;;   quoted          = DQUOTE *QUOTED-CHAR DQUOTE
2043 ;;
2044 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2045 ;;                     "\" quoted-specials
2046 ;;
2047 ;;   quoted-specials = DQUOTE / "\"
2048 ;;
2049 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2050
2051 (defsubst imap-parse-string ()
2052   (cond ((eq (char-after) ?\")
2053          (forward-char 1)
2054          (let ((p (point)) (name ""))
2055            (skip-chars-forward "^\"\\\\")
2056            (setq name (buffer-substring p (point)))
2057            (while (eq (char-after) ?\\)
2058              (setq p (1+ (point)))
2059              (forward-char 2)
2060              (skip-chars-forward "^\"\\\\")
2061              (setq name (concat name (buffer-substring p (point)))))
2062            (forward-char 1)
2063            name))
2064         ((eq (char-after) ?{)
2065          (imap-parse-literal))))
2066
2067 ;;   nil             = "NIL"
2068
2069 (defsubst imap-parse-nil ()
2070   (if (looking-at "NIL")
2071       (goto-char (match-end 0))))
2072
2073 ;;   nstring         = string / nil
2074
2075 (defsubst imap-parse-nstring ()
2076   (or (imap-parse-string)
2077       (and (imap-parse-nil)
2078            nil)))
2079
2080 ;;   astring         = atom / string
2081 ;;
2082 ;;   atom            = 1*ATOM-CHAR
2083 ;;
2084 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
2085 ;;
2086 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
2087 ;;                     quoted-specials
2088 ;;
2089 ;;   list-wildcards  = "%" / "*"
2090 ;;
2091 ;;   quoted-specials = DQUOTE / "\"
2092
2093 (defsubst imap-parse-astring ()
2094   (or (imap-parse-string)
2095       (buffer-substring (point)
2096                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2097                             (goto-char (1- (match-end 0)))
2098                           (end-of-line)
2099                           (point)))))
2100
2101 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
2102 ;;                      addr-host ")"
2103 ;;
2104 ;;   addr-adl        = nstring
2105 ;;                       ; Holds route from [RFC-822] route-addr if
2106 ;;                       ; non-nil
2107 ;;
2108 ;;   addr-host       = nstring
2109 ;;                       ; nil indicates [RFC-822] group syntax.
2110 ;;                       ; Otherwise, holds [RFC-822] domain name
2111 ;;
2112 ;;   addr-mailbox    = nstring
2113 ;;                       ; nil indicates end of [RFC-822] group; if
2114 ;;                       ; non-nil and addr-host is nil, holds
2115 ;;                       ; [RFC-822] group name.
2116 ;;                       ; Otherwise, holds [RFC-822] local-part
2117 ;;                       ; after removing [RFC-822] quoting
2118 ;;
2119 ;;   addr-name       = nstring
2120 ;;                       ; If non-nil, holds phrase from [RFC-822]
2121 ;;                       ; mailbox after removing [RFC-822] quoting
2122 ;;
2123
2124 (defsubst imap-parse-address ()
2125   (let (address)
2126     (when (eq (char-after) ?\()
2127       (imap-forward)
2128       (setq address (vector (prog1 (imap-parse-nstring)
2129                               (imap-forward))
2130                             (prog1 (imap-parse-nstring)
2131                               (imap-forward))
2132                             (prog1 (imap-parse-nstring)
2133                               (imap-forward))
2134                             (imap-parse-nstring)))
2135       (when (eq (char-after) ?\))
2136         (imap-forward)
2137         address))))
2138
2139 ;;   address-list    = "(" 1*address ")" / nil
2140 ;;
2141 ;;   nil             = "NIL"
2142
2143 (defsubst imap-parse-address-list ()
2144   (if (eq (char-after) ?\()
2145       (let (address addresses)
2146         (imap-forward)
2147         (while (and (not (eq (char-after) ?\)))
2148                     ;; next line for MS Exchange bug
2149                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
2150                     (setq address (imap-parse-address)))
2151           (setq addresses (cons address addresses)))
2152         (when (eq (char-after) ?\))
2153           (imap-forward)
2154           (nreverse addresses)))
2155     ;; With assert, the code might not be eval'd.
2156     ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2157     (imap-parse-nil)))
2158
2159 ;;   mailbox         = "INBOX" / astring
2160 ;;                       ; INBOX is case-insensitive.  All case variants of
2161 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2162 ;;                       ; not as an astring.  An astring which consists of
2163 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
2164 ;;                       ; is considered to be INBOX and not an astring.
2165 ;;                       ;  Refer to section 5.1 for further
2166 ;;                       ; semantic details of mailbox names.
2167
2168 (defsubst imap-parse-mailbox ()
2169   (let ((mailbox (imap-parse-astring)))
2170     (if (string-equal "INBOX" (upcase mailbox))
2171         "INBOX"
2172       mailbox)))
2173
2174 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2175 ;;
2176 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
2177 ;;                       ; Authentication condition
2178 ;;
2179 ;;   resp-cond-bye   = "BYE" SP resp-text
2180
2181 (defun imap-parse-greeting ()
2182   "Parse an IMAP greeting."
2183   (cond ((looking-at "\\* OK ")
2184          (setq imap-state 'nonauth))
2185         ((looking-at "\\* PREAUTH ")
2186          (setq imap-state 'auth))
2187         ((looking-at "\\* BYE ")
2188          (setq imap-state 'closed))))
2189
2190 ;;   response        = *(continue-req / response-data) response-done
2191 ;;
2192 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
2193 ;;
2194 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
2195 ;;                     mailbox-data / message-data / capability-data) CRLF
2196 ;;
2197 ;;   response-done   = response-tagged / response-fatal
2198 ;;
2199 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
2200 ;;                       ; Server closes connection immediately
2201 ;;
2202 ;;   response-tagged = tag SP resp-cond-state CRLF
2203 ;;
2204 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2205 ;;                       ; Status condition
2206 ;;
2207 ;;   resp-cond-bye   = "BYE" SP resp-text
2208 ;;
2209 ;;   mailbox-data    =  "FLAGS" SP flag-list /
2210 ;;                      "LIST" SP mailbox-list /
2211 ;;                      "LSUB" SP mailbox-list /
2212 ;;                      "SEARCH" *(SP nz-number) /
2213 ;;                      "STATUS" SP mailbox SP "("
2214 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
2215 ;;                      number SP "EXISTS" /
2216 ;;                      number SP "RECENT"
2217 ;;
2218 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2219 ;;
2220 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2221 ;;                     *(SP capability)
2222 ;;                       ; IMAP4rev1 servers which offer RFC 1730
2223 ;;                       ; compatibility MUST list "IMAP4" as the first
2224 ;;                       ; capability.
2225
2226 (defun imap-parse-response ()
2227   "Parse a IMAP command response."
2228   (let (token)
2229     (case (setq token (read (current-buffer)))
2230       (+ (setq imap-continuation
2231                (or (buffer-substring (min (point-max) (1+ (point)))
2232                                      (point-max))
2233                    t)))
2234       (* (case (prog1 (setq token (read (current-buffer)))
2235                  (imap-forward))
2236            (OK         (imap-parse-resp-text))
2237            (NO         (imap-parse-resp-text))
2238            (BAD        (imap-parse-resp-text))
2239            (BYE        (imap-parse-resp-text))
2240            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
2241            (LIST       (imap-parse-data-list 'list))
2242            (LSUB       (imap-parse-data-list 'lsub))
2243            (SEARCH     (imap-mailbox-put
2244                         'search
2245                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2246            (STATUS     (imap-parse-status))
2247            (CAPABILITY (setq imap-capability
2248                                (read (concat "(" (upcase (buffer-substring
2249                                                           (point) (point-max)))
2250                                              ")"))))
2251            (ID         (setq imap-id (read (buffer-substring (point)
2252                                                              (point-max)))))
2253            (ACL        (imap-parse-acl))
2254            (t       (case (prog1 (read (current-buffer))
2255                             (imap-forward))
2256                       (EXISTS  (imap-mailbox-put 'exists token))
2257                       (RECENT  (imap-mailbox-put 'recent token))
2258                       (EXPUNGE t)
2259                       (FETCH   (imap-parse-fetch token))
2260                       (t       (message "Garbage: %s" (buffer-string)))))))
2261       (t (let (status)
2262            (if (not (integerp token))
2263                (message "Garbage: %s" (buffer-string))
2264              (case (prog1 (setq status (read (current-buffer)))
2265                      (imap-forward))
2266                (OK  (progn
2267                       (setq imap-reached-tag (max imap-reached-tag token))
2268                       (imap-parse-resp-text)))
2269                (NO  (progn
2270                       (setq imap-reached-tag (max imap-reached-tag token))
2271                       (save-excursion
2272                         (imap-parse-resp-text))
2273                       (let (code text)
2274                         (when (eq (char-after) ?\[)
2275                           (setq code (buffer-substring (point)
2276                                                        (search-forward "]")))
2277                           (imap-forward))
2278                         (setq text (buffer-substring (point) (point-max)))
2279                         (push (list token status code text)
2280                               imap-failed-tags))))
2281                (BAD (progn
2282                       (setq imap-reached-tag (max imap-reached-tag token))
2283                       (save-excursion
2284                         (imap-parse-resp-text))
2285                       (let (code text)
2286                         (when (eq (char-after) ?\[)
2287                           (setq code (buffer-substring (point)
2288                                                        (search-forward "]")))
2289                           (imap-forward))
2290                         (setq text (buffer-substring (point) (point-max)))
2291                         (push (list token status code text) imap-failed-tags)
2292                         (error "Internal error, tag %s status %s code %s text %s"
2293                                token status code text))))
2294                (t   (message "Garbage: %s" (buffer-string))))
2295              (when (assq token imap-callbacks)
2296                (funcall (cdr (assq token imap-callbacks)) token status)
2297                (setq imap-callbacks
2298                      (imap-remassoc token imap-callbacks)))))))))
2299
2300 ;;   resp-text       = ["[" resp-text-code "]" SP] text
2301 ;;
2302 ;;   text            = 1*TEXT-CHAR
2303 ;;
2304 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2305
2306 (defun imap-parse-resp-text ()
2307   (imap-parse-resp-text-code))
2308
2309 ;;   resp-text-code  = "ALERT" /
2310 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2311 ;;                     "NEWNAME" SP string SP string /
2312 ;;                     "PARSE" /
2313 ;;                     "PERMANENTFLAGS" SP "("
2314 ;;                               [flag-perm *(SP flag-perm)] ")" /
2315 ;;                     "READ-ONLY" /
2316 ;;                     "READ-WRITE" /
2317 ;;                     "TRYCREATE" /
2318 ;;                     "UIDNEXT" SP nz-number /
2319 ;;                     "UIDVALIDITY" SP nz-number /
2320 ;;                     "UNSEEN" SP nz-number /
2321 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2322 ;;
2323 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
2324 ;;
2325 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
2326 ;;
2327 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
2328 ;;                        (set "," set)
2329 ;;                          ; Identifies a set of messages.  For message
2330 ;;                          ; sequence numbers, these are consecutive
2331 ;;                          ; numbers from 1 to the number of messages in
2332 ;;                          ; the mailbox
2333 ;;                          ; Comma delimits individual numbers, colon
2334 ;;                          ; delimits between two numbers inclusive.
2335 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2336 ;;                          ; 14,15 for a mailbox with 15 messages.
2337 ;;
2338 ;;   sequence-num    = nz-number / "*"
2339 ;;                          ; * is the largest number in use.  For message
2340 ;;                          ; sequence numbers, it is the number of messages
2341 ;;                          ; in the mailbox.  For unique identifiers, it is
2342 ;;                          ; the unique identifier of the last message in
2343 ;;                          ; the mailbox.
2344 ;;
2345 ;;   flag-perm       = flag / "\*"
2346 ;;
2347 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2348 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2349 ;;                       ; Does not include "\Recent"
2350 ;;
2351 ;;   flag-extension  = "\" atom
2352 ;;                       ; Future expansion.  Client implementations
2353 ;;                       ; MUST accept flag-extension flags.  Server
2354 ;;                       ; implementations MUST NOT generate
2355 ;;                       ; flag-extension flags except as defined by
2356 ;;                       ; future standard or standards-track
2357 ;;                       ; revisions of this specification.
2358 ;;
2359 ;;   flag-keyword    = atom
2360 ;;
2361 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
2362
2363 (defun imap-parse-resp-text-code ()
2364   ;; xxx next line for stalker communigate pro 3.3.1 bug
2365   (when (looking-at " \\[")
2366     (imap-forward))
2367   (when (eq (char-after) ?\[)
2368     (imap-forward)
2369     (cond ((search-forward "PERMANENTFLAGS " nil t)
2370            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2371           ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2372            (imap-mailbox-put 'uidnext (match-string 1)))
2373           ((search-forward "UNSEEN " nil t)
2374            (imap-mailbox-put 'first-unseen (read (current-buffer))))
2375           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2376            (imap-mailbox-put 'uidvalidity (match-string 1)))
2377           ((search-forward "READ-ONLY" nil t)
2378            (imap-mailbox-put 'read-only t))
2379           ((search-forward "NEWNAME " nil t)
2380            (let (oldname newname)
2381              (setq oldname (imap-parse-string))
2382              (imap-forward)
2383              (setq newname (imap-parse-string))
2384              (imap-mailbox-put 'newname newname oldname)))
2385           ((search-forward "TRYCREATE" nil t)
2386            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2387           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2388            (imap-mailbox-put 'appenduid
2389                              (list (match-string 1)
2390                                    (string-to-number (match-string 2)))
2391                              imap-current-target-mailbox))
2392           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2393            (imap-mailbox-put 'copyuid (list (match-string 1)
2394                                             (match-string 2)
2395                                             (match-string 3))
2396                              imap-current-target-mailbox))
2397           ((search-forward "ALERT] " nil t)
2398            (message "Imap server %s information: %s" imap-server
2399                     (buffer-substring (point) (point-max)))))))
2400
2401 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
2402 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2403 ;;
2404 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
2405 ;;                     *(SP mbx-list-oflag) /
2406 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
2407 ;;
2408 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
2409 ;;                       ; Other flags; multiple possible per LIST response
2410 ;;
2411 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
2412 ;;                       ; Selectability flags; only one per LIST response
2413 ;;
2414 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2415 ;;                     "\" quoted-specials
2416 ;;
2417 ;;   quoted-specials = DQUOTE / "\"
2418
2419 (defun imap-parse-data-list (type)
2420   (let (flags delimiter mailbox)
2421     (setq flags (imap-parse-flag-list))
2422     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2423       (setq delimiter (match-string 1))
2424       (goto-char (1+ (match-end 0)))
2425       (when (setq mailbox (imap-parse-mailbox))
2426         (imap-mailbox-put type t mailbox)
2427         (imap-mailbox-put 'list-flags flags mailbox)
2428         (imap-mailbox-put 'delimiter delimiter mailbox)))))
2429
2430 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
2431 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2432 ;;                      "INTERNALDATE" SPACE date_time /
2433 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2434 ;;                      "RFC822.SIZE" SPACE number /
2435 ;;                      "BODY" ["STRUCTURE"] SPACE body /
2436 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
2437 ;;                      "UID" SPACE uniqueid) ")"
2438 ;;
2439 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
2440 ;;                      SPACE time SPACE zone <">
2441 ;;
2442 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
2443 ;;                      ["." (section_text / "MIME")])] "]"
2444 ;;
2445 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2446 ;;                      SPACE header_list / "TEXT"
2447 ;;
2448 ;;  header_fld_name ::= astring
2449 ;;
2450 ;;  header_list     ::= "(" 1#header_fld_name ")"
2451
2452 (defsubst imap-parse-header-list ()
2453   (when (eq (char-after) ?\()
2454     (let (strlist)
2455       (while (not (eq (char-after) ?\)))
2456         (imap-forward)
2457         (push (imap-parse-astring) strlist))
2458       (imap-forward)
2459       (nreverse strlist))))
2460
2461 (defsubst imap-parse-fetch-body-section ()
2462   (let ((section
2463          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2464     (if (eq (char-before) ? )
2465         (prog1
2466             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2467           (search-forward "]" nil t))
2468       section)))
2469
2470 (defun imap-parse-fetch (response)
2471   (when (eq (char-after) ?\()
2472     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2473               rfc822size body bodydetail bodystructure flags-empty)
2474       ;; Courier can insert spurious blank characters which will
2475       ;; confuse `read', so skip past them.
2476       (while (let ((moved (skip-chars-forward " \t")))
2477                (prog1 (not (eq (char-after) ?\)))
2478                  (unless (= moved 0) (backward-char))))
2479         (imap-forward)
2480         (let ((token (read (current-buffer))))
2481           (imap-forward)
2482           (cond ((eq token 'UID)
2483                  (setq uid (condition-case ()
2484                                (read (current-buffer))
2485                              (error))))
2486                 ((eq token 'FLAGS)
2487                  (setq flags (imap-parse-flag-list))
2488                  (if (not flags)
2489                      (setq flags-empty 't)))
2490                 ((eq token 'ENVELOPE)
2491                  (setq envelope (imap-parse-envelope)))
2492                 ((eq token 'INTERNALDATE)
2493                  (setq internaldate (imap-parse-string)))
2494                 ((eq token 'RFC822)
2495                  (setq rfc822 (imap-parse-nstring)))
2496                 ((eq token 'RFC822.HEADER)
2497                  (setq rfc822header (imap-parse-nstring)))
2498                 ((eq token 'RFC822.TEXT)
2499                  (setq rfc822text (imap-parse-nstring)))
2500                 ((eq token 'RFC822.SIZE)
2501                  (setq rfc822size (read (current-buffer))))
2502                 ((eq token 'BODY)
2503                  (if (eq (char-before) ?\[)
2504                      (push (list
2505                             (upcase (imap-parse-fetch-body-section))
2506                             (and (eq (char-after) ?<)
2507                                  (buffer-substring (1+ (point))
2508                                                    (search-forward ">" nil t)))
2509                             (progn (imap-forward)
2510                                    (imap-parse-nstring)))
2511                            bodydetail)
2512                    (setq body (imap-parse-body))))
2513                 ((eq token 'BODYSTRUCTURE)
2514                  (setq bodystructure (imap-parse-body))))))
2515       (when uid
2516         (setq imap-current-message uid)
2517         (imap-message-put uid 'UID uid)
2518         (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2519         (and envelope (imap-message-put uid 'ENVELOPE envelope))
2520         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2521         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2522         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2523         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2524         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2525         (and body (imap-message-put uid 'BODY body))
2526         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2527         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2528         (run-hooks 'imap-fetch-data-hook)))))
2529
2530 ;;   mailbox-data    =  ...
2531 ;;                      "STATUS" SP mailbox SP "("
2532 ;;                            [status-att SP number
2533 ;;                            *(SP status-att SP number)] ")"
2534 ;;                      ...
2535 ;;
2536 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2537 ;;                     "UNSEEN"
2538
2539 (defun imap-parse-status ()
2540   (let ((mailbox (imap-parse-mailbox)))
2541     (if (eq (char-after) ? )
2542         (forward-char))
2543     (when (and mailbox (eq (char-after) ?\())
2544       (while (and (not (eq (char-after) ?\)))
2545                   (or (forward-char) t)
2546                   (looking-at "\\([A-Za-z]+\\) "))
2547         (let ((token (upcase (match-string 1))))
2548           (goto-char (match-end 0))
2549           (cond ((string= token "MESSAGES")
2550                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2551                 ((string= token "RECENT")
2552                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2553                 ((string= token "UIDNEXT")
2554                  (and (looking-at "[0-9]+")
2555                       (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2556                       (goto-char (match-end 0))))
2557                 ((string= token "UIDVALIDITY")
2558                  (and (looking-at "[0-9]+")
2559                       (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2560                       (goto-char (match-end 0))))
2561                 ((string= token "UNSEEN")
2562                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2563                 (t
2564                  (message "Unknown status data %s in mailbox %s ignored"
2565                           token mailbox)
2566                  (read (current-buffer)))))))))
2567
2568 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2569 ;;                        rights)
2570 ;;
2571 ;;   identifier      ::= astring
2572 ;;
2573 ;;   rights          ::= astring
2574
2575 (defun imap-parse-acl ()
2576   (let ((mailbox (imap-parse-mailbox))
2577         identifier rights acl)
2578     (while (eq (char-after) ?\ )
2579       (imap-forward)
2580       (setq identifier (imap-parse-astring))
2581       (imap-forward)
2582       (setq rights (imap-parse-astring))
2583       (setq acl (append acl (list (cons identifier rights)))))
2584     (imap-mailbox-put 'acl acl mailbox)))
2585
2586 ;;   flag-list       = "(" [flag *(SP flag)] ")"
2587 ;;
2588 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2589 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2590 ;;                       ; Does not include "\Recent"
2591 ;;
2592 ;;   flag-keyword    = atom
2593 ;;
2594 ;;   flag-extension  = "\" atom
2595 ;;                       ; Future expansion.  Client implementations
2596 ;;                       ; MUST accept flag-extension flags.  Server
2597 ;;                       ; implementations MUST NOT generate
2598 ;;                       ; flag-extension flags except as defined by
2599 ;;                       ; future standard or standards-track
2600 ;;                       ; revisions of this specification.
2601
2602 (defun imap-parse-flag-list ()
2603   (let (flag-list start)
2604     (assert (eq (char-after) ?\() nil "In imap-parse-flag-list 1")
2605     (while (and (not (eq (char-after) ?\)))
2606                 (setq start (progn
2607                               (imap-forward)
2608                               ;; next line for Courier IMAP bug.
2609                               (skip-chars-forward " ")
2610                               (point)))
2611                 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2612       (push (buffer-substring start (point)) flag-list))
2613     (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list 2")
2614     (imap-forward)
2615     (nreverse flag-list)))
2616
2617 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
2618 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
2619 ;;                     env-in-reply-to SP env-message-id ")"
2620 ;;
2621 ;;   env-bcc         = "(" 1*address ")" / nil
2622 ;;
2623 ;;   env-cc          = "(" 1*address ")" / nil
2624 ;;
2625 ;;   env-date        = nstring
2626 ;;
2627 ;;   env-from        = "(" 1*address ")" / nil
2628 ;;
2629 ;;   env-in-reply-to = nstring
2630 ;;
2631 ;;   env-message-id  = nstring
2632 ;;
2633 ;;   env-reply-to    = "(" 1*address ")" / nil
2634 ;;
2635 ;;   env-sender      = "(" 1*address ")" / nil
2636 ;;
2637 ;;   env-subject     = nstring
2638 ;;
2639 ;;   env-to          = "(" 1*address ")" / nil
2640
2641 (defun imap-parse-envelope ()
2642   (when (eq (char-after) ?\()
2643     (imap-forward)
2644     (vector (prog1 (imap-parse-nstring) ;; date
2645               (imap-forward))
2646             (prog1 (imap-parse-nstring) ;; subject
2647               (imap-forward))
2648             (prog1 (imap-parse-address-list) ;; from
2649               (imap-forward))
2650             (prog1 (imap-parse-address-list) ;; sender
2651               (imap-forward))
2652             (prog1 (imap-parse-address-list) ;; reply-to
2653               (imap-forward))
2654             (prog1 (imap-parse-address-list) ;; to
2655               (imap-forward))
2656             (prog1 (imap-parse-address-list) ;; cc
2657               (imap-forward))
2658             (prog1 (imap-parse-address-list) ;; bcc
2659               (imap-forward))
2660             (prog1 (imap-parse-nstring) ;; in-reply-to
2661               (imap-forward))
2662             (prog1 (imap-parse-nstring) ;; message-id
2663               (imap-forward)))))
2664
2665 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2666
2667 (defsubst imap-parse-string-list ()
2668   (cond ((eq (char-after) ?\() ;; body-fld-param
2669          (let (strlist str)
2670            (imap-forward)
2671            (while (setq str (imap-parse-string))
2672              (push str strlist)
2673              ;; buggy stalker communigate pro 3.0 doesn't print SPC
2674              ;; between body-fld-param's sometimes
2675              (or (eq (char-after) ?\")
2676                  (imap-forward)))
2677            (nreverse strlist)))
2678         ((imap-parse-nil)
2679          nil)))
2680
2681 ;;   body-extension  = nstring / number /
2682 ;;                      "(" body-extension *(SP body-extension) ")"
2683 ;;                       ; Future expansion.  Client implementations
2684 ;;                       ; MUST accept body-extension fields.  Server
2685 ;;                       ; implementations MUST NOT generate
2686 ;;                       ; body-extension fields except as defined by
2687 ;;                       ; future standard or standards-track
2688 ;;                       ; revisions of this specification.
2689
2690 (defun imap-parse-body-extension ()
2691   (if (eq (char-after) ?\()
2692       (let (b-e)
2693         (imap-forward)
2694         (push (imap-parse-body-extension) b-e)
2695         (while (eq (char-after) ?\ )
2696           (imap-forward)
2697           (push (imap-parse-body-extension) b-e))
2698         (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2699         (imap-forward)
2700         (nreverse b-e))
2701     (or (imap-parse-number)
2702         (imap-parse-nstring))))
2703
2704 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2705 ;;                     *(SP body-extension)]]
2706 ;;                       ; MUST NOT be returned on non-extensible
2707 ;;                       ; "BODY" fetch
2708 ;;
2709 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2710 ;;                     *(SP body-extension)]]
2711 ;;                       ; MUST NOT be returned on non-extensible
2712 ;;                       ; "BODY" fetch
2713
2714 (defsubst imap-parse-body-ext ()
2715   (let (ext)
2716     (when (eq (char-after) ?\ ) ;; body-fld-dsp
2717       (imap-forward)
2718       (let (dsp)
2719         (if (eq (char-after) ?\()
2720             (progn
2721               (imap-forward)
2722               (push (imap-parse-string) dsp)
2723               (imap-forward)
2724               (push (imap-parse-string-list) dsp)
2725               (imap-forward))
2726           ;; With assert, the code might not be eval'd.
2727           ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2728           (imap-parse-nil))
2729         (push (nreverse dsp) ext))
2730       (when (eq (char-after) ?\ ) ;; body-fld-lang
2731         (imap-forward)
2732         (if (eq (char-after) ?\()
2733             (push (imap-parse-string-list) ext)
2734           (push (imap-parse-nstring) ext))
2735         (while (eq (char-after) ?\ ) ;; body-extension
2736           (imap-forward)
2737           (setq ext (append (imap-parse-body-extension) ext)))))
2738     ext))
2739
2740 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2741 ;;
2742 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2743 ;;                     *(SP body-extension)]]
2744 ;;                       ; MUST NOT be returned on non-extensible
2745 ;;                       ; "BODY" fetch
2746 ;;
2747 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2748 ;;                     *(SP body-extension)]]
2749 ;;                       ; MUST NOT be returned on non-extensible
2750 ;;                       ; "BODY" fetch
2751 ;;
2752 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2753 ;;                     body-fld-enc SP body-fld-octets
2754 ;;
2755 ;;   body-fld-desc   = nstring
2756 ;;
2757 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2758 ;;
2759 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2760 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2761 ;;
2762 ;;   body-fld-id     = nstring
2763 ;;
2764 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2765 ;;
2766 ;;   body-fld-lines  = number
2767 ;;
2768 ;;   body-fld-md5    = nstring
2769 ;;
2770 ;;   body-fld-octets = number
2771 ;;
2772 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2773 ;;
2774 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2775 ;;                     [SP body-ext-1part]
2776 ;;
2777 ;;   body-type-basic = media-basic SP body-fields
2778 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2779 ;;
2780 ;;   body-type-msg   = media-message SP body-fields SP envelope
2781 ;;                     SP body SP body-fld-lines
2782 ;;
2783 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2784 ;;
2785 ;;   body-type-mpart = 1*body SP media-subtype
2786 ;;                     [SP body-ext-mpart]
2787 ;;
2788 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2789 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2790 ;;                       ; Defined in [MIME-IMT]
2791 ;;
2792 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2793 ;;                      ; Defined in [MIME-IMT]
2794 ;;
2795 ;;   media-subtype   = string
2796 ;;                       ; Defined in [MIME-IMT]
2797 ;;
2798 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2799 ;;                       ; Defined in [MIME-IMT]
2800
2801 (defun imap-parse-body ()
2802   (let (body)
2803     (when (eq (char-after) ?\()
2804       (imap-forward)
2805       (if (eq (char-after) ?\()
2806           (let (subbody)
2807             (while (and (eq (char-after) ?\()
2808                         (setq subbody (imap-parse-body)))
2809               ;; buggy stalker communigate pro 3.0 inserts a SPC between
2810               ;; parts in multiparts
2811               (when (and (eq (char-after) ?\ )
2812                          (eq (char-after (1+ (point))) ?\())
2813                 (imap-forward))
2814               (push subbody body))
2815             (imap-forward)
2816             (push (imap-parse-string) body) ;; media-subtype
2817             (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2818               (imap-forward)
2819               (if (eq (char-after) ?\() ;; body-fld-param
2820                   (push (imap-parse-string-list) body)
2821                 (push (and (imap-parse-nil) nil) body))
2822               (setq body
2823                     (append (imap-parse-body-ext) body))) ;; body-ext-...
2824             (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2825             (imap-forward)
2826             (nreverse body))
2827
2828         (push (imap-parse-string) body) ;; media-type
2829         (imap-forward)
2830         (push (imap-parse-string) body) ;; media-subtype
2831         (imap-forward)
2832         ;; next line for Sun SIMS bug
2833         (and (eq (char-after) ? ) (imap-forward))
2834         (if (eq (char-after) ?\() ;; body-fld-param
2835             (push (imap-parse-string-list) body)
2836           (push (and (imap-parse-nil) nil) body))
2837         (imap-forward)
2838         (push (imap-parse-nstring) body) ;; body-fld-id
2839         (imap-forward)
2840         (push (imap-parse-nstring) body) ;; body-fld-desc
2841         (imap-forward)
2842         ;; Next `or' for Sun SIMS bug.  It regards body-fld-enc as a
2843         ;; nstring and returns nil instead of defaulting back to 7BIT
2844         ;; as the standard says.
2845         ;; Exchange (2007, at least) does this as well.
2846         (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2847         (imap-forward)
2848         ;; Exchange 2007 can return -1, contrary to the spec...
2849         (if (eq (char-after) ?-)
2850             (progn
2851               (skip-chars-forward "-0-9")
2852               (push nil body))
2853           (push (imap-parse-number) body)) ;; body-fld-octets
2854
2855         ;; Ok, we're done parsing the required parts, what comes now is one of
2856         ;; three things:
2857         ;;
2858         ;; envelope       (then we're parsing body-type-msg)
2859         ;; body-fld-lines (then we're parsing body-type-text)
2860         ;; body-ext-1part (then we're parsing body-type-basic)
2861         ;;
2862         ;; The problem is that the two first are in turn optionally followed
2863         ;; by the third.  So we parse the first two here (if there are any)...
2864
2865         (when (eq (char-after) ?\ )
2866           (imap-forward)
2867           (let (lines)
2868             (cond ((eq (char-after) ?\() ;; body-type-msg:
2869                    (push (imap-parse-envelope) body) ;; envelope
2870                    (imap-forward)
2871                    (push (imap-parse-body) body) ;; body
2872                    ;; buggy stalker communigate pro 3.0 doesn't print
2873                    ;; number of lines in message/rfc822 attachment
2874                    (if (eq (char-after) ?\))
2875                        (push 0 body)
2876                      (imap-forward)
2877                      (push (imap-parse-number) body))) ;; body-fld-lines
2878                   ((setq lines (imap-parse-number)) ;; body-type-text:
2879                    (push lines body)) ;; body-fld-lines
2880                   (t
2881                    (backward-char))))) ;; no match...
2882
2883         ;; ...and then parse the third one here...
2884
2885         (when (eq (char-after) ?\ ) ;; body-ext-1part:
2886           (imap-forward)
2887           (push (imap-parse-nstring) body) ;; body-fld-md5
2888           (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2889
2890         (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2891         (imap-forward)
2892         (nreverse body)))))
2893
2894 (provide 'imap)
2895
2896 ;;; imap.el ends here