* imap.el (imap-string-to-integer): Fix typo.
[gnus] / lisp / imap.el
1 ;;; imap.el --- imap library
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;;   2005, 2006, 2007, 2008, 2009 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-fetch-safe (uids props &optional receive nouidfetch buffer)
1779   "Like `imap-fetch', but DTRT with Exchange 2007 bug.
1780 However, UIDS here is a cons, where the car is the canonical form
1781 of the UIDS specification, and the cdr is the one which works with
1782 Exchange 2007 or, potentially, other buggy servers.
1783 See `imap-enable-exchange-bug-workaround'."
1784   ;; We don't unconditionally use the alternative (valid) form, since
1785   ;; this is said to be significantly inefficient.  The first time we
1786   ;; get here for a given, we'll try the canonical form.  If we get
1787   ;; the known error from the buggy server, set the flag
1788   ;; buffer-locally (to account for connexions to multiple servers),
1789   ;; then re-try with the alternative UIDS spec.
1790   (condition-case data
1791       (imap-fetch (if imap-enable-exchange-bug-workaround
1792                       (cdr uids)
1793                     (car uids))
1794                   props receive nouidfetch buffer)
1795     (error
1796      (if (and (not imap-enable-exchange-bug-workaround)
1797               (string-match
1798                "The specified message set is invalid"
1799                (cadr data)))
1800          (with-current-buffer (or buffer (current-buffer))
1801            (set (make-local-variable
1802                  'imap-enable-exchange-bug-workaround)
1803                 t)
1804            (imap-fetch (cdr uids) props receive nouidfetch))
1805        (signal (car data) (cdr data))))))
1806
1807 (defun imap-message-copyuid-1 (mailbox)
1808   (if (imap-capability 'UIDPLUS)
1809       (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1810             (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1811     (let ((old-mailbox imap-current-mailbox)
1812           (state imap-state)
1813           (imap-message-data (make-vector 2 0)))
1814       (when (imap-mailbox-examine-1 mailbox)
1815         (prog1
1816             (and (imap-fetch-safe '("*" . "*:*") "UID")
1817                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1818                        (apply 'max (imap-message-map
1819                                     (lambda (uid prop) uid) 'UID))))
1820           (if old-mailbox
1821               (imap-mailbox-select old-mailbox (eq state 'examine))
1822             (imap-mailbox-unselect)))))))
1823
1824 (defun imap-message-copyuid (mailbox &optional buffer)
1825   (with-current-buffer (or buffer (current-buffer))
1826     (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1827
1828 (defun imap-message-copy (articles mailbox
1829                                    &optional dont-create no-copyuid buffer)
1830   "Copy ARTICLES to MAILBOX on server in BUFFER.
1831 ARTICLES is a string message set.  Create mailbox if it doesn't exist,
1832 unless DONT-CREATE is non-nil.  On success, return a list with
1833 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1834 first element.  The rest of list contains the saved articles' UIDs."
1835   (when articles
1836     (with-current-buffer (or buffer (current-buffer))
1837       (let ((mailbox (imap-utf7-encode mailbox)))
1838         (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1839                   (imap-current-target-mailbox mailbox))
1840               (if (imap-ok-p (imap-send-command-wait cmd))
1841                   t
1842                 (when (and (not dont-create)
1843                            ;; removed because of buggy Oracle server
1844                            ;; that doesn't send TRYCREATE tags (which
1845                            ;; is a MUST according to specifications):
1846                            ;;(imap-mailbox-get-1 'trycreate mailbox)
1847                            (imap-mailbox-create-1 mailbox))
1848                   (imap-ok-p (imap-send-command-wait cmd)))))
1849             (or no-copyuid
1850                 (imap-message-copyuid-1 mailbox)))))))
1851
1852 (defun imap-message-appenduid-1 (mailbox)
1853   (if (imap-capability 'UIDPLUS)
1854       (imap-mailbox-get-1 'appenduid mailbox)
1855     (let ((old-mailbox imap-current-mailbox)
1856           (state imap-state)
1857           (imap-message-data (make-vector 2 0)))
1858       (when (imap-mailbox-examine-1 mailbox)
1859         (prog1
1860             (and (imap-fetch-safe '("*" "*:*") "UID")
1861                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1862                        (apply 'max (imap-message-map
1863                                     (lambda (uid prop) uid) 'UID))))
1864           (if old-mailbox
1865               (imap-mailbox-select old-mailbox (eq state 'examine))
1866             (imap-mailbox-unselect)))))))
1867
1868 (defun imap-message-appenduid (mailbox &optional buffer)
1869   (with-current-buffer (or buffer (current-buffer))
1870     (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1871
1872 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1873   "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1874 FLAGS and DATE-TIME is currently not used.  Return a cons holding
1875 uidvalidity of MAILBOX and UID the newly created article got, or nil
1876 on failure."
1877   (let ((mailbox (imap-utf7-encode mailbox)))
1878     (with-current-buffer (or buffer (current-buffer))
1879       (and (let ((imap-current-target-mailbox mailbox))
1880              (imap-ok-p
1881               (imap-send-command-wait
1882                (list "APPEND \"" mailbox "\" "  article))))
1883            (imap-message-appenduid-1 mailbox)))))
1884
1885 (defun imap-body-lines (body)
1886   "Return number of lines in article by looking at the mime bodystructure BODY."
1887   (if (listp body)
1888       (if (stringp (car body))
1889           (cond ((and (string= (upcase (car body)) "TEXT")
1890                       (numberp (nth 7 body)))
1891                  (nth 7 body))
1892                 ((and (string= (upcase (car body)) "MESSAGE")
1893                       (numberp (nth 9 body)))
1894                  (nth 9 body))
1895                 (t 0))
1896         (apply '+ (mapcar 'imap-body-lines body)))
1897     0))
1898
1899 (defun imap-envelope-from (from)
1900   "Return a from string line."
1901   (and from
1902        (concat (aref from 0)
1903                (if (aref from 0) " <")
1904                (aref from 2)
1905                "@"
1906                (aref from 3)
1907                (if (aref from 0) ">"))))
1908
1909 \f
1910 ;; Internal functions.
1911
1912 (defun imap-add-callback (tag func)
1913   (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1914
1915 (defun imap-send-command-1 (cmdstr)
1916   (setq cmdstr (concat cmdstr imap-client-eol))
1917   (and imap-log
1918        (with-current-buffer (get-buffer-create imap-log-buffer)
1919          (imap-disable-multibyte)
1920          (buffer-disable-undo)
1921          (goto-char (point-max))
1922          (insert cmdstr)))
1923   (process-send-string imap-process cmdstr))
1924
1925 (defun imap-send-command (command &optional buffer)
1926   (with-current-buffer (or buffer (current-buffer))
1927     (if (not (listp command)) (setq command (list command)))
1928     (let ((tag (setq imap-tag (1+ imap-tag)))
1929           cmd cmdstr)
1930       (setq cmdstr (concat (number-to-string imap-tag) " "))
1931       (while (setq cmd (pop command))
1932         (cond ((stringp cmd)
1933                (setq cmdstr (concat cmdstr cmd)))
1934               ((bufferp cmd)
1935                (let ((eol imap-client-eol)
1936                      (calcfirst imap-calculate-literal-size-first)
1937                      size)
1938                  (with-current-buffer cmd
1939                    (if calcfirst
1940                        (setq size (buffer-size)))
1941                    (when (not (equal eol "\r\n"))
1942                      ;; XXX modifies buffer!
1943                      (goto-char (point-min))
1944                      (while (search-forward "\r\n" nil t)
1945                        (replace-match eol)))
1946                    (if (not calcfirst)
1947                        (setq size (buffer-size))))
1948                  (setq cmdstr
1949                        (concat cmdstr (format "{%d}" size))))
1950                (unwind-protect
1951                    (progn
1952                      (imap-send-command-1 cmdstr)
1953                      (setq cmdstr nil)
1954                      (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1955                          (setq command nil) ;; abort command if no cont-req
1956                        (let ((process imap-process)
1957                              (stream imap-stream)
1958                              (eol imap-client-eol))
1959                          (with-current-buffer cmd
1960                            (and imap-log
1961                                 (with-current-buffer (get-buffer-create
1962                                                       imap-log-buffer)
1963                                   (imap-disable-multibyte)
1964                                   (buffer-disable-undo)
1965                                   (goto-char (point-max))
1966                                   (insert-buffer-substring cmd)))
1967                            (process-send-region process (point-min)
1968                                                 (point-max)))
1969                          (process-send-string process imap-client-eol))))
1970                  (setq imap-continuation nil)))
1971               ((functionp cmd)
1972                (imap-send-command-1 cmdstr)
1973                (setq cmdstr nil)
1974                (unwind-protect
1975                    (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1976                        (setq command nil) ;; abort command if no cont-req
1977                      (setq command (cons (funcall cmd imap-continuation)
1978                                          command)))
1979                  (setq imap-continuation nil)))
1980               (t
1981                (error "Unknown command type"))))
1982       (if cmdstr
1983           (imap-send-command-1 cmdstr))
1984       tag)))
1985
1986 (defun imap-wait-for-tag (tag &optional buffer)
1987   (with-current-buffer (or buffer (current-buffer))
1988     (let (imap-have-messaged)
1989       (while (and (null imap-continuation)
1990                   (memq (process-status imap-process) '(open run))
1991                   (< imap-reached-tag tag))
1992         (let ((len (/ (point-max) 1024))
1993               message-log-max)
1994           (unless (< len 10)
1995             (setq imap-have-messaged t)
1996             (message "imap read: %dk" len))
1997           (accept-process-output imap-process
1998                                  (truncate imap-read-timeout)
1999                                  (truncate (* (- imap-read-timeout
2000                                                  (truncate imap-read-timeout))
2001                                               1000)))))
2002       ;; A process can die _before_ we have processed everything it
2003       ;; has to say.  Moreover, this can happen in between the call to
2004       ;; accept-process-output and the call to process-status in an
2005       ;; iteration of the loop above.
2006       (when (and (null imap-continuation)
2007                  (< imap-reached-tag tag))
2008         (accept-process-output imap-process 0 0))
2009       (when imap-have-messaged
2010         (message ""))
2011       (and (memq (process-status imap-process) '(open run))
2012            (or (assq tag imap-failed-tags)
2013                (if imap-continuation
2014                    'INCOMPLETE
2015                  'OK))))))
2016
2017 (defun imap-sentinel (process string)
2018   (delete-process process))
2019
2020 (defun imap-find-next-line ()
2021   "Return point at end of current line, taking into account literals.
2022 Return nil if no complete line has arrived."
2023   (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
2024                                    imap-server-eol)
2025                            nil t)
2026     (if (match-string 1)
2027         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
2028             nil
2029           (goto-char (+ (point) (string-to-number (match-string 1))))
2030           (imap-find-next-line))
2031       (point))))
2032
2033 (defun imap-arrival-filter (proc string)
2034   "IMAP process filter."
2035   ;; Sometimes, we are called even though the process has died.
2036   ;; Better abstain from doing stuff in that case.
2037   (when (buffer-name (process-buffer proc))
2038     (with-current-buffer (process-buffer proc)
2039       (goto-char (point-max))
2040       (insert string)
2041       (and imap-log
2042            (with-current-buffer (get-buffer-create imap-log-buffer)
2043              (imap-disable-multibyte)
2044              (buffer-disable-undo)
2045              (goto-char (point-max))
2046              (insert string)))
2047       (let (end)
2048         (goto-char (point-min))
2049         (while (setq end (imap-find-next-line))
2050           (save-restriction
2051             (narrow-to-region (point-min) end)
2052             (delete-backward-char (length imap-server-eol))
2053             (goto-char (point-min))
2054             (unwind-protect
2055                 (cond ((eq imap-state 'initial)
2056                        (imap-parse-greeting))
2057                       ((or (eq imap-state 'auth)
2058                            (eq imap-state 'nonauth)
2059                            (eq imap-state 'selected)
2060                            (eq imap-state 'examine))
2061                        (imap-parse-response))
2062                       (t
2063                        (message "Unknown state %s in arrival filter"
2064                                 imap-state)))
2065               (delete-region (point-min) (point-max)))))))))
2066
2067 \f
2068 ;; Imap parser.
2069
2070 (defsubst imap-forward ()
2071   (or (eobp) (forward-char)))
2072
2073 ;;   number          = 1*DIGIT
2074 ;;                       ; Unsigned 32-bit integer
2075 ;;                       ; (0 <= n < 4,294,967,296)
2076
2077 (defsubst imap-parse-number ()
2078   (when (looking-at "[0-9]+")
2079     (prog1
2080         (string-to-number (match-string 0))
2081       (goto-char (match-end 0)))))
2082
2083 ;;   literal         = "{" number "}" CRLF *CHAR8
2084 ;;                       ; Number represents the number of CHAR8s
2085
2086 (defsubst imap-parse-literal ()
2087   (when (looking-at "{\\([0-9]+\\)}\r\n")
2088     (let ((pos (match-end 0))
2089           (len (string-to-number (match-string 1))))
2090       (if (< (point-max) (+ pos len))
2091           nil
2092         (goto-char (+ pos len))
2093         (buffer-substring pos (+ pos len))))))
2094
2095 ;;   string          = quoted / literal
2096 ;;
2097 ;;   quoted          = DQUOTE *QUOTED-CHAR DQUOTE
2098 ;;
2099 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2100 ;;                     "\" quoted-specials
2101 ;;
2102 ;;   quoted-specials = DQUOTE / "\"
2103 ;;
2104 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2105
2106 (defsubst imap-parse-string ()
2107   (cond ((eq (char-after) ?\")
2108          (forward-char 1)
2109          (let ((p (point)) (name ""))
2110            (skip-chars-forward "^\"\\\\")
2111            (setq name (buffer-substring p (point)))
2112            (while (eq (char-after) ?\\)
2113              (setq p (1+ (point)))
2114              (forward-char 2)
2115              (skip-chars-forward "^\"\\\\")
2116              (setq name (concat name (buffer-substring p (point)))))
2117            (forward-char 1)
2118            name))
2119         ((eq (char-after) ?{)
2120          (imap-parse-literal))))
2121
2122 ;;   nil             = "NIL"
2123
2124 (defsubst imap-parse-nil ()
2125   (if (looking-at "NIL")
2126       (goto-char (match-end 0))))
2127
2128 ;;   nstring         = string / nil
2129
2130 (defsubst imap-parse-nstring ()
2131   (or (imap-parse-string)
2132       (and (imap-parse-nil)
2133            nil)))
2134
2135 ;;   astring         = atom / string
2136 ;;
2137 ;;   atom            = 1*ATOM-CHAR
2138 ;;
2139 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
2140 ;;
2141 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
2142 ;;                     quoted-specials
2143 ;;
2144 ;;   list-wildcards  = "%" / "*"
2145 ;;
2146 ;;   quoted-specials = DQUOTE / "\"
2147
2148 (defsubst imap-parse-astring ()
2149   (or (imap-parse-string)
2150       (buffer-substring (point)
2151                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2152                             (goto-char (1- (match-end 0)))
2153                           (end-of-line)
2154                           (point)))))
2155
2156 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
2157 ;;                      addr-host ")"
2158 ;;
2159 ;;   addr-adl        = nstring
2160 ;;                       ; Holds route from [RFC-822] route-addr if
2161 ;;                       ; non-nil
2162 ;;
2163 ;;   addr-host       = nstring
2164 ;;                       ; nil indicates [RFC-822] group syntax.
2165 ;;                       ; Otherwise, holds [RFC-822] domain name
2166 ;;
2167 ;;   addr-mailbox    = nstring
2168 ;;                       ; nil indicates end of [RFC-822] group; if
2169 ;;                       ; non-nil and addr-host is nil, holds
2170 ;;                       ; [RFC-822] group name.
2171 ;;                       ; Otherwise, holds [RFC-822] local-part
2172 ;;                       ; after removing [RFC-822] quoting
2173 ;;
2174 ;;   addr-name       = nstring
2175 ;;                       ; If non-nil, holds phrase from [RFC-822]
2176 ;;                       ; mailbox after removing [RFC-822] quoting
2177 ;;
2178
2179 (defsubst imap-parse-address ()
2180   (let (address)
2181     (when (eq (char-after) ?\()
2182       (imap-forward)
2183       (setq address (vector (prog1 (imap-parse-nstring)
2184                               (imap-forward))
2185                             (prog1 (imap-parse-nstring)
2186                               (imap-forward))
2187                             (prog1 (imap-parse-nstring)
2188                               (imap-forward))
2189                             (imap-parse-nstring)))
2190       (when (eq (char-after) ?\))
2191         (imap-forward)
2192         address))))
2193
2194 ;;   address-list    = "(" 1*address ")" / nil
2195 ;;
2196 ;;   nil             = "NIL"
2197
2198 (defsubst imap-parse-address-list ()
2199   (if (eq (char-after) ?\()
2200       (let (address addresses)
2201         (imap-forward)
2202         (while (and (not (eq (char-after) ?\)))
2203                     ;; next line for MS Exchange bug
2204                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
2205                     (setq address (imap-parse-address)))
2206           (setq addresses (cons address addresses)))
2207         (when (eq (char-after) ?\))
2208           (imap-forward)
2209           (nreverse addresses)))
2210     ;; With assert, the code might not be eval'd.
2211     ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2212     (imap-parse-nil)))
2213
2214 ;;   mailbox         = "INBOX" / astring
2215 ;;                       ; INBOX is case-insensitive.  All case variants of
2216 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2217 ;;                       ; not as an astring.  An astring which consists of
2218 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
2219 ;;                       ; is considered to be INBOX and not an astring.
2220 ;;                       ;  Refer to section 5.1 for further
2221 ;;                       ; semantic details of mailbox names.
2222
2223 (defsubst imap-parse-mailbox ()
2224   (let ((mailbox (imap-parse-astring)))
2225     (if (string-equal "INBOX" (upcase mailbox))
2226         "INBOX"
2227       mailbox)))
2228
2229 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2230 ;;
2231 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
2232 ;;                       ; Authentication condition
2233 ;;
2234 ;;   resp-cond-bye   = "BYE" SP resp-text
2235
2236 (defun imap-parse-greeting ()
2237   "Parse a IMAP greeting."
2238   (cond ((looking-at "\\* OK ")
2239          (setq imap-state 'nonauth))
2240         ((looking-at "\\* PREAUTH ")
2241          (setq imap-state 'auth))
2242         ((looking-at "\\* BYE ")
2243          (setq imap-state 'closed))))
2244
2245 ;;   response        = *(continue-req / response-data) response-done
2246 ;;
2247 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
2248 ;;
2249 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
2250 ;;                     mailbox-data / message-data / capability-data) CRLF
2251 ;;
2252 ;;   response-done   = response-tagged / response-fatal
2253 ;;
2254 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
2255 ;;                       ; Server closes connection immediately
2256 ;;
2257 ;;   response-tagged = tag SP resp-cond-state CRLF
2258 ;;
2259 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2260 ;;                       ; Status condition
2261 ;;
2262 ;;   resp-cond-bye   = "BYE" SP resp-text
2263 ;;
2264 ;;   mailbox-data    =  "FLAGS" SP flag-list /
2265 ;;                      "LIST" SP mailbox-list /
2266 ;;                      "LSUB" SP mailbox-list /
2267 ;;                      "SEARCH" *(SP nz-number) /
2268 ;;                      "STATUS" SP mailbox SP "("
2269 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
2270 ;;                      number SP "EXISTS" /
2271 ;;                      number SP "RECENT"
2272 ;;
2273 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2274 ;;
2275 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2276 ;;                     *(SP capability)
2277 ;;                       ; IMAP4rev1 servers which offer RFC 1730
2278 ;;                       ; compatibility MUST list "IMAP4" as the first
2279 ;;                       ; capability.
2280
2281 (defun imap-parse-response ()
2282   "Parse a IMAP command response."
2283   (let (token)
2284     (case (setq token (read (current-buffer)))
2285       (+ (setq imap-continuation
2286                (or (buffer-substring (min (point-max) (1+ (point)))
2287                                      (point-max))
2288                    t)))
2289       (* (case (prog1 (setq token (read (current-buffer)))
2290                  (imap-forward))
2291            (OK         (imap-parse-resp-text))
2292            (NO         (imap-parse-resp-text))
2293            (BAD        (imap-parse-resp-text))
2294            (BYE        (imap-parse-resp-text))
2295            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
2296            (LIST       (imap-parse-data-list 'list))
2297            (LSUB       (imap-parse-data-list 'lsub))
2298            (SEARCH     (imap-mailbox-put
2299                         'search
2300                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2301            (STATUS     (imap-parse-status))
2302            (CAPABILITY (setq imap-capability
2303                                (read (concat "(" (upcase (buffer-substring
2304                                                           (point) (point-max)))
2305                                              ")"))))
2306            (ID         (setq imap-id (read (buffer-substring (point)
2307                                                              (point-max)))))
2308            (ACL        (imap-parse-acl))
2309            (t       (case (prog1 (read (current-buffer))
2310                             (imap-forward))
2311                       (EXISTS  (imap-mailbox-put 'exists token))
2312                       (RECENT  (imap-mailbox-put 'recent token))
2313                       (EXPUNGE t)
2314                       (FETCH   (imap-parse-fetch token))
2315                       (t       (message "Garbage: %s" (buffer-string)))))))
2316       (t (let (status)
2317            (if (not (integerp token))
2318                (message "Garbage: %s" (buffer-string))
2319              (case (prog1 (setq status (read (current-buffer)))
2320                      (imap-forward))
2321                (OK  (progn
2322                       (setq imap-reached-tag (max imap-reached-tag token))
2323                       (imap-parse-resp-text)))
2324                (NO  (progn
2325                       (setq imap-reached-tag (max imap-reached-tag token))
2326                       (save-excursion
2327                         (imap-parse-resp-text))
2328                       (let (code text)
2329                         (when (eq (char-after) ?\[)
2330                           (setq code (buffer-substring (point)
2331                                                        (search-forward "]")))
2332                           (imap-forward))
2333                         (setq text (buffer-substring (point) (point-max)))
2334                         (push (list token status code text)
2335                               imap-failed-tags))))
2336                (BAD (progn
2337                       (setq imap-reached-tag (max imap-reached-tag token))
2338                       (save-excursion
2339                         (imap-parse-resp-text))
2340                       (let (code text)
2341                         (when (eq (char-after) ?\[)
2342                           (setq code (buffer-substring (point)
2343                                                        (search-forward "]")))
2344                           (imap-forward))
2345                         (setq text (buffer-substring (point) (point-max)))
2346                         (push (list token status code text) imap-failed-tags)
2347                         (error "Internal error, tag %s status %s code %s text %s"
2348                                token status code text))))
2349                (t   (message "Garbage: %s" (buffer-string))))
2350              (when (assq token imap-callbacks)
2351                (funcall (cdr (assq token imap-callbacks)) token status)
2352                (setq imap-callbacks
2353                      (imap-remassoc token imap-callbacks)))))))))
2354
2355 ;;   resp-text       = ["[" resp-text-code "]" SP] text
2356 ;;
2357 ;;   text            = 1*TEXT-CHAR
2358 ;;
2359 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2360
2361 (defun imap-parse-resp-text ()
2362   (imap-parse-resp-text-code))
2363
2364 ;;   resp-text-code  = "ALERT" /
2365 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2366 ;;                     "NEWNAME" SP string SP string /
2367 ;;                     "PARSE" /
2368 ;;                     "PERMANENTFLAGS" SP "("
2369 ;;                               [flag-perm *(SP flag-perm)] ")" /
2370 ;;                     "READ-ONLY" /
2371 ;;                     "READ-WRITE" /
2372 ;;                     "TRYCREATE" /
2373 ;;                     "UIDNEXT" SP nz-number /
2374 ;;                     "UIDVALIDITY" SP nz-number /
2375 ;;                     "UNSEEN" SP nz-number /
2376 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2377 ;;
2378 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
2379 ;;
2380 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
2381 ;;
2382 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
2383 ;;                        (set "," set)
2384 ;;                          ; Identifies a set of messages.  For message
2385 ;;                          ; sequence numbers, these are consecutive
2386 ;;                          ; numbers from 1 to the number of messages in
2387 ;;                          ; the mailbox
2388 ;;                          ; Comma delimits individual numbers, colon
2389 ;;                          ; delimits between two numbers inclusive.
2390 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2391 ;;                          ; 14,15 for a mailbox with 15 messages.
2392 ;;
2393 ;;   sequence-num    = nz-number / "*"
2394 ;;                          ; * is the largest number in use.  For message
2395 ;;                          ; sequence numbers, it is the number of messages
2396 ;;                          ; in the mailbox.  For unique identifiers, it is
2397 ;;                          ; the unique identifier of the last message in
2398 ;;                          ; the mailbox.
2399 ;;
2400 ;;   flag-perm       = flag / "\*"
2401 ;;
2402 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2403 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2404 ;;                       ; Does not include "\Recent"
2405 ;;
2406 ;;   flag-extension  = "\" atom
2407 ;;                       ; Future expansion.  Client implementations
2408 ;;                       ; MUST accept flag-extension flags.  Server
2409 ;;                       ; implementations MUST NOT generate
2410 ;;                       ; flag-extension flags except as defined by
2411 ;;                       ; future standard or standards-track
2412 ;;                       ; revisions of this specification.
2413 ;;
2414 ;;   flag-keyword    = atom
2415 ;;
2416 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
2417
2418 (defun imap-parse-resp-text-code ()
2419   ;; xxx next line for stalker communigate pro 3.3.1 bug
2420   (when (looking-at " \\[")
2421     (imap-forward))
2422   (when (eq (char-after) ?\[)
2423     (imap-forward)
2424     (cond ((search-forward "PERMANENTFLAGS " nil t)
2425            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2426           ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2427            (imap-mailbox-put 'uidnext (match-string 1)))
2428           ((search-forward "UNSEEN " nil t)
2429            (imap-mailbox-put 'first-unseen (read (current-buffer))))
2430           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2431            (imap-mailbox-put 'uidvalidity (match-string 1)))
2432           ((search-forward "READ-ONLY" nil t)
2433            (imap-mailbox-put 'read-only t))
2434           ((search-forward "NEWNAME " nil t)
2435            (let (oldname newname)
2436              (setq oldname (imap-parse-string))
2437              (imap-forward)
2438              (setq newname (imap-parse-string))
2439              (imap-mailbox-put 'newname newname oldname)))
2440           ((search-forward "TRYCREATE" nil t)
2441            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2442           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2443            (imap-mailbox-put 'appenduid
2444                              (list (match-string 1)
2445                                    (string-to-number (match-string 2)))
2446                              imap-current-target-mailbox))
2447           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2448            (imap-mailbox-put 'copyuid (list (match-string 1)
2449                                             (match-string 2)
2450                                             (match-string 3))
2451                              imap-current-target-mailbox))
2452           ((search-forward "ALERT] " nil t)
2453            (message "Imap server %s information: %s" imap-server
2454                     (buffer-substring (point) (point-max)))))))
2455
2456 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
2457 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2458 ;;
2459 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
2460 ;;                     *(SP mbx-list-oflag) /
2461 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
2462 ;;
2463 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
2464 ;;                       ; Other flags; multiple possible per LIST response
2465 ;;
2466 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
2467 ;;                       ; Selectability flags; only one per LIST response
2468 ;;
2469 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2470 ;;                     "\" quoted-specials
2471 ;;
2472 ;;   quoted-specials = DQUOTE / "\"
2473
2474 (defun imap-parse-data-list (type)
2475   (let (flags delimiter mailbox)
2476     (setq flags (imap-parse-flag-list))
2477     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2478       (setq delimiter (match-string 1))
2479       (goto-char (1+ (match-end 0)))
2480       (when (setq mailbox (imap-parse-mailbox))
2481         (imap-mailbox-put type t mailbox)
2482         (imap-mailbox-put 'list-flags flags mailbox)
2483         (imap-mailbox-put 'delimiter delimiter mailbox)))))
2484
2485 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
2486 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2487 ;;                      "INTERNALDATE" SPACE date_time /
2488 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2489 ;;                      "RFC822.SIZE" SPACE number /
2490 ;;                      "BODY" ["STRUCTURE"] SPACE body /
2491 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
2492 ;;                      "UID" SPACE uniqueid) ")"
2493 ;;
2494 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
2495 ;;                      SPACE time SPACE zone <">
2496 ;;
2497 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
2498 ;;                      ["." (section_text / "MIME")])] "]"
2499 ;;
2500 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2501 ;;                      SPACE header_list / "TEXT"
2502 ;;
2503 ;;  header_fld_name ::= astring
2504 ;;
2505 ;;  header_list     ::= "(" 1#header_fld_name ")"
2506
2507 (defsubst imap-parse-header-list ()
2508   (when (eq (char-after) ?\()
2509     (let (strlist)
2510       (while (not (eq (char-after) ?\)))
2511         (imap-forward)
2512         (push (imap-parse-astring) strlist))
2513       (imap-forward)
2514       (nreverse strlist))))
2515
2516 (defsubst imap-parse-fetch-body-section ()
2517   (let ((section
2518          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2519     (if (eq (char-before) ? )
2520         (prog1
2521             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2522           (search-forward "]" nil t))
2523       section)))
2524
2525 (defun imap-parse-fetch (response)
2526   (when (eq (char-after) ?\()
2527     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2528               rfc822size body bodydetail bodystructure flags-empty)
2529       (while (not (eq (char-after) ?\)))
2530         (imap-forward)
2531         (let ((token (read (current-buffer))))
2532           (imap-forward)
2533           (cond ((eq token 'UID)
2534                  (setq uid (condition-case ()
2535                                (read (current-buffer))
2536                              (error))))
2537                 ((eq token 'FLAGS)
2538                  (setq flags (imap-parse-flag-list))
2539                  (if (not flags)
2540                      (setq flags-empty 't)))
2541                 ((eq token 'ENVELOPE)
2542                  (setq envelope (imap-parse-envelope)))
2543                 ((eq token 'INTERNALDATE)
2544                  (setq internaldate (imap-parse-string)))
2545                 ((eq token 'RFC822)
2546                  (setq rfc822 (imap-parse-nstring)))
2547                 ((eq token 'RFC822.HEADER)
2548                  (setq rfc822header (imap-parse-nstring)))
2549                 ((eq token 'RFC822.TEXT)
2550                  (setq rfc822text (imap-parse-nstring)))
2551                 ((eq token 'RFC822.SIZE)
2552                  (setq rfc822size (read (current-buffer))))
2553                 ((eq token 'BODY)
2554                  (if (eq (char-before) ?\[)
2555                      (push (list
2556                             (upcase (imap-parse-fetch-body-section))
2557                             (and (eq (char-after) ?<)
2558                                  (buffer-substring (1+ (point))
2559                                                    (search-forward ">" nil t)))
2560                             (progn (imap-forward)
2561                                    (imap-parse-nstring)))
2562                            bodydetail)
2563                    (setq body (imap-parse-body))))
2564                 ((eq token 'BODYSTRUCTURE)
2565                  (setq bodystructure (imap-parse-body))))))
2566       (when uid
2567         (setq imap-current-message uid)
2568         (imap-message-put uid 'UID uid)
2569         (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2570         (and envelope (imap-message-put uid 'ENVELOPE envelope))
2571         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2572         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2573         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2574         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2575         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2576         (and body (imap-message-put uid 'BODY body))
2577         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2578         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2579         (run-hooks 'imap-fetch-data-hook)))))
2580
2581 ;;   mailbox-data    =  ...
2582 ;;                      "STATUS" SP mailbox SP "("
2583 ;;                            [status-att SP number
2584 ;;                            *(SP status-att SP number)] ")"
2585 ;;                      ...
2586 ;;
2587 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2588 ;;                     "UNSEEN"
2589
2590 (defun imap-parse-status ()
2591   (let ((mailbox (imap-parse-mailbox)))
2592     (if (eq (char-after) ? )
2593         (forward-char))
2594     (when (and mailbox (eq (char-after) ?\())
2595       (while (and (not (eq (char-after) ?\)))
2596                   (or (forward-char) t)
2597                   (looking-at "\\([A-Za-z]+\\) "))
2598         (let ((token (upcase (match-string 1))))
2599           (goto-char (match-end 0))
2600           (cond ((string= token "MESSAGES")
2601                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2602                 ((string= token "RECENT")
2603                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2604                 ((string= token "UIDNEXT")
2605                  (and (looking-at "[0-9]+")
2606                       (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2607                       (goto-char (match-end 0))))
2608                 ((string= token "UIDVALIDITY")
2609                  (and (looking-at "[0-9]+")
2610                       (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2611                       (goto-char (match-end 0))))
2612                 ((string= token "UNSEEN")
2613                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2614                 (t
2615                  (message "Unknown status data %s in mailbox %s ignored"
2616                           token mailbox)
2617                  (read (current-buffer)))))))))
2618
2619 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2620 ;;                        rights)
2621 ;;
2622 ;;   identifier      ::= astring
2623 ;;
2624 ;;   rights          ::= astring
2625
2626 (defun imap-parse-acl ()
2627   (let ((mailbox (imap-parse-mailbox))
2628         identifier rights acl)
2629     (while (eq (char-after) ?\ )
2630       (imap-forward)
2631       (setq identifier (imap-parse-astring))
2632       (imap-forward)
2633       (setq rights (imap-parse-astring))
2634       (setq acl (append acl (list (cons identifier rights)))))
2635     (imap-mailbox-put 'acl acl mailbox)))
2636
2637 ;;   flag-list       = "(" [flag *(SP flag)] ")"
2638 ;;
2639 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2640 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2641 ;;                       ; Does not include "\Recent"
2642 ;;
2643 ;;   flag-keyword    = atom
2644 ;;
2645 ;;   flag-extension  = "\" atom
2646 ;;                       ; Future expansion.  Client implementations
2647 ;;                       ; MUST accept flag-extension flags.  Server
2648 ;;                       ; implementations MUST NOT generate
2649 ;;                       ; flag-extension flags except as defined by
2650 ;;                       ; future standard or standards-track
2651 ;;                       ; revisions of this specification.
2652
2653 (defun imap-parse-flag-list ()
2654   (let (flag-list start)
2655     (assert (eq (char-after) ?\() nil "In imap-parse-flag-list")
2656     (while (and (not (eq (char-after) ?\)))
2657                 (setq start (progn
2658                               (imap-forward)
2659                               ;; next line for Courier IMAP bug.
2660                               (skip-chars-forward " ")
2661                               (point)))
2662                 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2663       (push (buffer-substring start (point)) flag-list))
2664     (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list")
2665     (imap-forward)
2666     (nreverse flag-list)))
2667
2668 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
2669 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
2670 ;;                     env-in-reply-to SP env-message-id ")"
2671 ;;
2672 ;;   env-bcc         = "(" 1*address ")" / nil
2673 ;;
2674 ;;   env-cc          = "(" 1*address ")" / nil
2675 ;;
2676 ;;   env-date        = nstring
2677 ;;
2678 ;;   env-from        = "(" 1*address ")" / nil
2679 ;;
2680 ;;   env-in-reply-to = nstring
2681 ;;
2682 ;;   env-message-id  = nstring
2683 ;;
2684 ;;   env-reply-to    = "(" 1*address ")" / nil
2685 ;;
2686 ;;   env-sender      = "(" 1*address ")" / nil
2687 ;;
2688 ;;   env-subject     = nstring
2689 ;;
2690 ;;   env-to          = "(" 1*address ")" / nil
2691
2692 (defun imap-parse-envelope ()
2693   (when (eq (char-after) ?\()
2694     (imap-forward)
2695     (vector (prog1 (imap-parse-nstring) ;; date
2696               (imap-forward))
2697             (prog1 (imap-parse-nstring) ;; subject
2698               (imap-forward))
2699             (prog1 (imap-parse-address-list) ;; from
2700               (imap-forward))
2701             (prog1 (imap-parse-address-list) ;; sender
2702               (imap-forward))
2703             (prog1 (imap-parse-address-list) ;; reply-to
2704               (imap-forward))
2705             (prog1 (imap-parse-address-list) ;; to
2706               (imap-forward))
2707             (prog1 (imap-parse-address-list) ;; cc
2708               (imap-forward))
2709             (prog1 (imap-parse-address-list) ;; bcc
2710               (imap-forward))
2711             (prog1 (imap-parse-nstring) ;; in-reply-to
2712               (imap-forward))
2713             (prog1 (imap-parse-nstring) ;; message-id
2714               (imap-forward)))))
2715
2716 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2717
2718 (defsubst imap-parse-string-list ()
2719   (cond ((eq (char-after) ?\() ;; body-fld-param
2720          (let (strlist str)
2721            (imap-forward)
2722            (while (setq str (imap-parse-string))
2723              (push str strlist)
2724              ;; buggy stalker communigate pro 3.0 doesn't print SPC
2725              ;; between body-fld-param's sometimes
2726              (or (eq (char-after) ?\")
2727                  (imap-forward)))
2728            (nreverse strlist)))
2729         ((imap-parse-nil)
2730          nil)))
2731
2732 ;;   body-extension  = nstring / number /
2733 ;;                      "(" body-extension *(SP body-extension) ")"
2734 ;;                       ; Future expansion.  Client implementations
2735 ;;                       ; MUST accept body-extension fields.  Server
2736 ;;                       ; implementations MUST NOT generate
2737 ;;                       ; body-extension fields except as defined by
2738 ;;                       ; future standard or standards-track
2739 ;;                       ; revisions of this specification.
2740
2741 (defun imap-parse-body-extension ()
2742   (if (eq (char-after) ?\()
2743       (let (b-e)
2744         (imap-forward)
2745         (push (imap-parse-body-extension) b-e)
2746         (while (eq (char-after) ?\ )
2747           (imap-forward)
2748           (push (imap-parse-body-extension) b-e))
2749         (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2750         (imap-forward)
2751         (nreverse b-e))
2752     (or (imap-parse-number)
2753         (imap-parse-nstring))))
2754
2755 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2756 ;;                     *(SP body-extension)]]
2757 ;;                       ; MUST NOT be returned on non-extensible
2758 ;;                       ; "BODY" fetch
2759 ;;
2760 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2761 ;;                     *(SP body-extension)]]
2762 ;;                       ; MUST NOT be returned on non-extensible
2763 ;;                       ; "BODY" fetch
2764
2765 (defsubst imap-parse-body-ext ()
2766   (let (ext)
2767     (when (eq (char-after) ?\ ) ;; body-fld-dsp
2768       (imap-forward)
2769       (let (dsp)
2770         (if (eq (char-after) ?\()
2771             (progn
2772               (imap-forward)
2773               (push (imap-parse-string) dsp)
2774               (imap-forward)
2775               (push (imap-parse-string-list) dsp)
2776               (imap-forward))
2777           ;; With assert, the code might not be eval'd.
2778           ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2779           (imap-parse-nil))
2780         (push (nreverse dsp) ext))
2781       (when (eq (char-after) ?\ ) ;; body-fld-lang
2782         (imap-forward)
2783         (if (eq (char-after) ?\()
2784             (push (imap-parse-string-list) ext)
2785           (push (imap-parse-nstring) ext))
2786         (while (eq (char-after) ?\ ) ;; body-extension
2787           (imap-forward)
2788           (setq ext (append (imap-parse-body-extension) ext)))))
2789     ext))
2790
2791 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2792 ;;
2793 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2794 ;;                     *(SP body-extension)]]
2795 ;;                       ; MUST NOT be returned on non-extensible
2796 ;;                       ; "BODY" fetch
2797 ;;
2798 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2799 ;;                     *(SP body-extension)]]
2800 ;;                       ; MUST NOT be returned on non-extensible
2801 ;;                       ; "BODY" fetch
2802 ;;
2803 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2804 ;;                     body-fld-enc SP body-fld-octets
2805 ;;
2806 ;;   body-fld-desc   = nstring
2807 ;;
2808 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2809 ;;
2810 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2811 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2812 ;;
2813 ;;   body-fld-id     = nstring
2814 ;;
2815 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2816 ;;
2817 ;;   body-fld-lines  = number
2818 ;;
2819 ;;   body-fld-md5    = nstring
2820 ;;
2821 ;;   body-fld-octets = number
2822 ;;
2823 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2824 ;;
2825 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2826 ;;                     [SP body-ext-1part]
2827 ;;
2828 ;;   body-type-basic = media-basic SP body-fields
2829 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2830 ;;
2831 ;;   body-type-msg   = media-message SP body-fields SP envelope
2832 ;;                     SP body SP body-fld-lines
2833 ;;
2834 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2835 ;;
2836 ;;   body-type-mpart = 1*body SP media-subtype
2837 ;;                     [SP body-ext-mpart]
2838 ;;
2839 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2840 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2841 ;;                       ; Defined in [MIME-IMT]
2842 ;;
2843 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2844 ;;                      ; Defined in [MIME-IMT]
2845 ;;
2846 ;;   media-subtype   = string
2847 ;;                       ; Defined in [MIME-IMT]
2848 ;;
2849 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2850 ;;                       ; Defined in [MIME-IMT]
2851
2852 (defun imap-parse-body ()
2853   (let (body)
2854     (when (eq (char-after) ?\()
2855       (imap-forward)
2856       (if (eq (char-after) ?\()
2857           (let (subbody)
2858             (while (and (eq (char-after) ?\()
2859                         (setq subbody (imap-parse-body)))
2860               ;; buggy stalker communigate pro 3.0 inserts a SPC between
2861               ;; parts in multiparts
2862               (when (and (eq (char-after) ?\ )
2863                          (eq (char-after (1+ (point))) ?\())
2864                 (imap-forward))
2865               (push subbody body))
2866             (imap-forward)
2867             (push (imap-parse-string) body) ;; media-subtype
2868             (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2869               (imap-forward)
2870               (if (eq (char-after) ?\() ;; body-fld-param
2871                   (push (imap-parse-string-list) body)
2872                 (push (and (imap-parse-nil) nil) body))
2873               (setq body
2874                     (append (imap-parse-body-ext) body))) ;; body-ext-...
2875             (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2876             (imap-forward)
2877             (nreverse body))
2878
2879         (push (imap-parse-string) body) ;; media-type
2880         (imap-forward)
2881         (push (imap-parse-string) body) ;; media-subtype
2882         (imap-forward)
2883         ;; next line for Sun SIMS bug
2884         (and (eq (char-after) ? ) (imap-forward))
2885         (if (eq (char-after) ?\() ;; body-fld-param
2886             (push (imap-parse-string-list) body)
2887           (push (and (imap-parse-nil) nil) body))
2888         (imap-forward)
2889         (push (imap-parse-nstring) body) ;; body-fld-id
2890         (imap-forward)
2891         (push (imap-parse-nstring) body) ;; body-fld-desc
2892         (imap-forward)
2893         ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2894         ;; nstring and return nil instead of defaulting back to 7BIT
2895         ;; as the standard says.
2896         (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2897         (imap-forward)
2898         ;; Exchange 2007 can return -1, contrary to the spec...
2899         (if (eq (char-after) ?-)
2900             (progn
2901               (skip-chars-forward "-0-9")
2902               (push nil body))
2903           (push (imap-parse-number) body)) ;; body-fld-octets
2904
2905    ;; ok, we're done parsing the required parts, what comes now is one
2906         ;; of three things:
2907         ;;
2908         ;; envelope       (then we're parsing body-type-msg)
2909         ;; body-fld-lines (then we're parsing body-type-text)
2910         ;; body-ext-1part (then we're parsing body-type-basic)
2911         ;;
2912   ;; the problem is that the two first are in turn optionally followed
2913 ;; by the third.  So we parse the first two here (if there are any)...
2914
2915         (when (eq (char-after) ?\ )
2916           (imap-forward)
2917           (let (lines)
2918             (cond ((eq (char-after) ?\() ;; body-type-msg:
2919                    (push (imap-parse-envelope) body) ;; envelope
2920                    (imap-forward)
2921                    (push (imap-parse-body) body) ;; body
2922                    ;; buggy stalker communigate pro 3.0 doesn't print
2923                    ;; number of lines in message/rfc822 attachment
2924                    (if (eq (char-after) ?\))
2925                        (push 0 body)
2926                      (imap-forward)
2927                      (push (imap-parse-number) body))) ;; body-fld-lines
2928                   ((setq lines (imap-parse-number)) ;; body-type-text:
2929                    (push lines body)) ;; body-fld-lines
2930                   (t
2931                    (backward-char))))) ;; no match...
2932
2933         ;; ...and then parse the third one here...
2934
2935         (when (eq (char-after) ?\ ) ;; body-ext-1part:
2936           (imap-forward)
2937           (push (imap-parse-nstring) body) ;; body-fld-md5
2938           (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2939
2940         (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2941         (imap-forward)
2942         (nreverse body)))))
2943
2944 (when imap-debug                        ; (untrace-all)
2945   (require 'trace)
2946   (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2947   (mapc (lambda (f) (trace-function-background f imap-debug-buffer))
2948         '(
2949           imap-utf7-encode
2950           imap-utf7-decode
2951           imap-error-text
2952           imap-kerberos4s-p
2953           imap-kerberos4-open
2954           imap-ssl-p
2955           imap-ssl-open
2956           imap-network-p
2957           imap-network-open
2958           imap-interactive-login
2959           imap-kerberos4a-p
2960           imap-kerberos4-auth
2961           imap-cram-md5-p
2962           imap-cram-md5-auth
2963           imap-login-p
2964           imap-login-auth
2965           imap-anonymous-p
2966           imap-anonymous-auth
2967           imap-open-1
2968           imap-open
2969           imap-opened
2970           imap-ping-server
2971           imap-authenticate
2972           imap-close
2973           imap-capability
2974           imap-namespace
2975           imap-send-command-wait
2976           imap-mailbox-put
2977           imap-mailbox-get
2978           imap-mailbox-map-1
2979           imap-mailbox-map
2980           imap-current-mailbox
2981           imap-current-mailbox-p-1
2982           imap-current-mailbox-p
2983           imap-mailbox-select-1
2984           imap-mailbox-select
2985           imap-mailbox-examine-1
2986           imap-mailbox-examine
2987           imap-mailbox-unselect
2988           imap-mailbox-expunge
2989           imap-mailbox-close
2990           imap-mailbox-create-1
2991           imap-mailbox-create
2992           imap-mailbox-delete
2993           imap-mailbox-rename
2994           imap-mailbox-lsub
2995           imap-mailbox-list
2996           imap-mailbox-subscribe
2997           imap-mailbox-unsubscribe
2998           imap-mailbox-status
2999           imap-mailbox-acl-get
3000           imap-mailbox-acl-set
3001           imap-mailbox-acl-delete
3002           imap-current-message
3003           imap-list-to-message-set
3004           imap-fetch-asynch
3005           imap-fetch
3006           imap-message-put
3007           imap-message-get
3008           imap-message-map
3009           imap-search
3010           imap-message-flag-permanent-p
3011           imap-message-flags-set
3012           imap-message-flags-del
3013           imap-message-flags-add
3014           imap-message-copyuid-1
3015           imap-message-copyuid
3016           imap-message-copy
3017           imap-message-appenduid-1
3018           imap-message-appenduid
3019           imap-message-append
3020           imap-body-lines
3021           imap-envelope-from
3022           imap-send-command-1
3023           imap-send-command
3024           imap-wait-for-tag
3025           imap-sentinel
3026           imap-find-next-line
3027           imap-arrival-filter
3028           imap-parse-greeting
3029           imap-parse-response
3030           imap-parse-resp-text
3031           imap-parse-resp-text-code
3032           imap-parse-data-list
3033           imap-parse-fetch
3034           imap-parse-status
3035           imap-parse-acl
3036           imap-parse-flag-list
3037           imap-parse-envelope
3038           imap-parse-body-extension
3039           imap-parse-body
3040           )))
3041
3042 (provide 'imap)
3043
3044 ;; arch-tag: 27369ed6-33e4-482f-96f1-8bb906ba70f7
3045 ;;; imap.el ends here