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