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