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