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