(imap-gssapi-program): Also try GNU SASL.
[gnus] / 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-and-compile
141   (autoload 'base64-decode-string "base64")
142   (autoload 'base64-encode-string "base64")
143   (autoload 'starttls-open-stream "starttls")
144   (autoload 'starttls-negotiate "starttls")
145   (autoload 'digest-md5-parse-digest-challenge "digest-md5")
146   (autoload 'digest-md5-digest-response "digest-md5")
147   (autoload 'digest-md5-digest-uri "digest-md5")
148   (autoload 'digest-md5-challenge "digest-md5")
149   (autoload 'rfc2104-hash "rfc2104")
150   (autoload 'md5 "md5")
151   (autoload 'utf7-encode "utf7")
152   (autoload 'utf7-decode "utf7")
153   (autoload 'format-spec "format-spec")
154   (autoload 'format-spec-make "format-spec")
155   (autoload 'open-tls-stream "tls")
156   ;; Avoid use gnus-point-at-eol so we're independent of Gnus.  These
157   ;; days we have point-at-eol anyhow.
158   (if (fboundp 'point-at-eol)
159       (defalias 'imap-point-at-eol 'point-at-eol)
160     (defun imap-point-at-eol ()
161       (save-excursion
162         (end-of-line)
163         (point)))))
164
165 ;; User variables.
166
167 (defgroup imap nil
168   "Low-level IMAP issues."
169   :version "21.1"
170   :group 'mail)
171
172 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
173                                     "imtest -kp %s %p")
174   "List of strings containing commands for Kerberos 4 authentication.
175 %s is replaced with server hostname, %p with port to connect to, and
176 %l with the value of `imap-default-user'.  The program should accept
177 IMAP commands on stdin and return responses to stdout.  Each entry in
178 the list is tried until a successful connection is made."
179   :group 'imap
180   :type '(repeat string))
181
182 (defcustom imap-gssapi-program (list
183                                 (concat "gsasl --client --connect %s:%p "
184                                         "--imap --application-data "
185                                         "--mechanism GSSAPI "
186                                         "--authentication-id %l")
187                                 "imtest -m gssapi -u %l -p %p %s")
188   "List of strings containing commands for GSSAPI (krb5) authentication.
189 %s is replaced with server hostname, %p with port to connect to, and
190 %l with the value of `imap-default-user'.  The program should accept
191 IMAP commands on stdin and return responses to stdout.  Each entry in
192 the list is tried until a successful connection is made."
193   :group 'imap
194   :type '(repeat string))
195
196 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
197                               "openssl s_client -quiet -ssl2 -connect %s:%p"
198                               "s_client -quiet -ssl3 -connect %s:%p"
199                               "s_client -quiet -ssl2 -connect %s:%p")
200   "A string, or list of strings, containing commands for SSL connections.
201 Within a string, %s is replaced with the server address and %p with
202 port number on server.  The program should accept IMAP commands on
203 stdin and return responses to stdout.  Each entry in the list is tried
204 until a successful connection is made."
205   :group 'imap
206   :type '(choice string
207                  (repeat string)))
208
209 (defcustom imap-shell-program '("ssh %s imapd"
210                                 "rsh %s imapd"
211                                 "ssh %g ssh %s imapd"
212                                 "rsh %g rsh %s imapd")
213   "A list of strings, containing commands for IMAP connection.
214 Within a string, %s is replaced with the server address, %p with port
215 number on server, %g with `imap-shell-host', and %l with
216 `imap-default-user'.  The program should read IMAP commands from stdin
217 and write IMAP response to stdout. Each entry in the list is tried
218 until a successful connection is made."
219   :group 'imap
220   :type '(repeat string))
221
222 (defcustom imap-process-connection-type nil
223   "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
224   :group 'imap
225   :type 'boolean)
226
227 (defcustom imap-use-utf7 t
228   "If non-nil, do utf7 encoding/decoding of mailbox names.
229 Since the UTF7 decoding currently only decodes into ISO-8859-1
230 characters, you may disable this decoding if you need to access UTF7
231 encoded mailboxes which doesn't translate into ISO-8859-1."
232   :group 'imap
233   :type 'boolean)
234
235 (defcustom imap-log nil
236   "If non-nil, a imap session trace is placed in *imap-log* buffer."
237   :group 'imap
238   :type 'boolean)
239
240 (defcustom imap-debug nil
241   "If non-nil, random debug spews are placed in *imap-debug* buffer."
242   :group 'imap
243   :type 'boolean)
244
245 (defcustom imap-shell-host "gateway"
246   "Hostname of rlogin proxy."
247   :group 'imap
248   :type 'string)
249
250 (defcustom imap-default-user (user-login-name)
251   "Default username to use."
252   :group 'imap
253   :type 'string)
254
255 ;; Various variables.
256
257 (defvar imap-fetch-data-hook nil
258   "Hooks called after receiving each FETCH response.")
259
260 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
261   "Priority of streams to consider when opening connection to server.")
262
263 (defvar imap-stream-alist
264   '((gssapi    imap-gssapi-stream-p    imap-gssapi-open)
265     (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
266     (tls       imap-tls-p              imap-tls-open)
267     (ssl       imap-ssl-p              imap-ssl-open)
268     (network   imap-network-p          imap-network-open)
269     (shell     imap-shell-p            imap-shell-open)
270     (starttls  imap-starttls-p         imap-starttls-open))
271   "Definition of network streams.
272
273 \(NAME CHECK OPEN)
274
275 NAME names the stream, CHECK is a function returning non-nil if the
276 server support the stream and OPEN is a function for opening the
277 stream.")
278
279 (defvar imap-authenticators '(gssapi
280                               kerberos4
281                               digest-md5
282                               cram-md5
283                               login
284                               anonymous)
285   "Priority of authenticators to consider when authenticating to server.")
286
287 (defvar imap-authenticator-alist
288   '((gssapi     imap-gssapi-auth-p    imap-gssapi-auth)
289     (kerberos4  imap-kerberos4-auth-p imap-kerberos4-auth)
290     (cram-md5   imap-cram-md5-p       imap-cram-md5-auth)
291     (login      imap-login-p          imap-login-auth)
292     (anonymous  imap-anonymous-p      imap-anonymous-auth)
293     (digest-md5 imap-digest-md5-p     imap-digest-md5-auth))
294   "Definition of authenticators.
295
296 \(NAME CHECK AUTHENTICATE)
297
298 NAME names the authenticator.  CHECK is a function returning non-nil if
299 the server support the authenticator and AUTHENTICATE is a function
300 for doing the actual authentication.")
301
302 (defvar imap-error nil
303   "Error codes from the last command.")
304
305 ;; Internal constants.  Change theese and die.
306
307 (defconst imap-default-port 143)
308 (defconst imap-default-ssl-port 993)
309 (defconst imap-default-tls-port 993)
310 (defconst imap-default-stream 'network)
311 (defconst imap-coding-system-for-read 'binary)
312 (defconst imap-coding-system-for-write 'binary)
313 (defconst imap-local-variables '(imap-server
314                                  imap-port
315                                  imap-client-eol
316                                  imap-server-eol
317                                  imap-auth
318                                  imap-stream
319                                  imap-username
320                                  imap-password
321                                  imap-current-mailbox
322                                  imap-current-target-mailbox
323                                  imap-message-data
324                                  imap-capability
325                                  imap-namespace
326                                  imap-state
327                                  imap-reached-tag
328                                  imap-failed-tags
329                                  imap-tag
330                                  imap-process
331                                  imap-calculate-literal-size-first
332                                  imap-mailbox-data))
333 (defconst imap-log-buffer "*imap-log*")
334 (defconst imap-debug-buffer "*imap-debug*")
335
336 ;; Internal variables.
337
338 (defvar imap-stream nil)
339 (defvar imap-auth nil)
340 (defvar imap-server nil)
341 (defvar imap-port nil)
342 (defvar imap-username nil)
343 (defvar imap-password nil)
344 (defvar imap-calculate-literal-size-first nil)
345 (defvar imap-state 'closed
346   "IMAP state.
347 Valid states are `closed', `initial', `nonauth', `auth', `selected'
348 and `examine'.")
349
350 (defvar imap-server-eol "\r\n"
351   "The EOL string sent from the server.")
352
353 (defvar imap-client-eol "\r\n"
354   "The EOL string we send to the server.")
355
356 (defvar imap-current-mailbox nil
357   "Current mailbox name.")
358
359 (defvar imap-current-target-mailbox nil
360   "Current target mailbox for COPY and APPEND commands.")
361
362 (defvar imap-mailbox-data nil
363   "Obarray with mailbox data.")
364
365 (defvar imap-mailbox-prime 997
366   "Length of imap-mailbox-data.")
367
368 (defvar imap-current-message nil
369   "Current message number.")
370
371 (defvar imap-message-data nil
372   "Obarray with message data.")
373
374 (defvar imap-message-prime 997
375   "Length of imap-message-data.")
376
377 (defvar imap-capability nil
378   "Capability for server.")
379
380 (defvar imap-namespace nil
381   "Namespace for current server.")
382
383 (defvar imap-reached-tag 0
384   "Lower limit on command tags that have been parsed.")
385
386 (defvar imap-failed-tags nil
387   "Alist of tags that failed.
388 Each element is a list with four elements; tag (a integer), response
389 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
390 human readable response text (a string).")
391
392 (defvar imap-tag 0
393   "Command tag number.")
394
395 (defvar imap-process nil
396   "Process.")
397
398 (defvar imap-continuation nil
399   "Non-nil indicates that the server emitted a continuation request.
400 The actual value is really the text on the continuation line.")
401
402 (defvar imap-callbacks nil
403   "List of response tags and callbacks, on the form `(number . function)'.
404 The function should take two arguments, the first the IMAP tag and the
405 second the status (OK, NO, BAD etc) of the command.")
406
407 \f
408 ;; Utility functions:
409
410 (defun imap-remassoc (key alist)
411   "Delete by side effect any elements of LIST whose car is `equal' to KEY.
412 The modified LIST is returned.  If the first member
413 of LIST has a car that is `equal' to KEY, there is no way to remove it
414 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
415 sure of changing the value of `foo'."
416   (when alist
417     (if (equal key (caar alist))
418         (cdr alist)
419       (setcdr alist (imap-remassoc key (cdr alist)))
420       alist)))
421
422 (defsubst imap-disable-multibyte ()
423   "Enable multibyte in the current buffer."
424   (when (fboundp 'set-buffer-multibyte)
425     (set-buffer-multibyte nil)))
426
427 (defsubst imap-utf7-encode (string)
428   (if imap-use-utf7
429       (and string
430            (condition-case ()
431                (utf7-encode string t)
432              (error (message
433                      "imap: Could not UTF7 encode `%s', using it unencoded..."
434                      string)
435                     string)))
436     string))
437
438 (defsubst imap-utf7-decode (string)
439   (if imap-use-utf7
440       (and string
441            (condition-case ()
442                (utf7-decode string t)
443              (error (message
444                      "imap: Could not UTF7 decode `%s', using it undecoded..."
445                      string)
446                     string)))
447     string))
448
449 (defsubst imap-ok-p (status)
450   (if (eq status 'OK)
451       t
452     (setq imap-error status)
453     nil))
454
455 (defun imap-error-text (&optional buffer)
456   (with-current-buffer (or buffer (current-buffer))
457     (nth 3 (car imap-failed-tags))))
458
459 \f
460 ;; Server functions; stream stuff:
461
462 (defun imap-kerberos4-stream-p (buffer)
463   (imap-capability 'AUTH=KERBEROS_V4 buffer))
464
465 (defun imap-kerberos4-open (name buffer server port)
466   (let ((cmds imap-kerberos4-program)
467         cmd done)
468     (while (and (not done) (setq cmd (pop cmds)))
469       (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
470       (erase-buffer)
471       (let* ((port (or port imap-default-port))
472              (coding-system-for-read imap-coding-system-for-read)
473              (coding-system-for-write imap-coding-system-for-write)
474              (process-connection-type imap-process-connection-type)
475              (process (start-process
476                        name buffer shell-file-name shell-command-switch
477                        (format-spec
478                         cmd
479                         (format-spec-make
480                          ?s server
481                          ?p (number-to-string port)
482                          ?l imap-default-user))))
483              response)
484         (when process
485           (with-current-buffer buffer
486             (setq imap-client-eol "\n"
487                   imap-calculate-literal-size-first t)
488             (while (and (memq (process-status process) '(open run))
489                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
490                         (goto-char (point-min))
491                         ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
492                         (or (while (looking-at "^C:")
493                               (forward-line))
494                             t)
495                         ;; cyrus 1.6 imtest print "S: " before server greeting
496                         (or (not (looking-at "S: "))
497                             (forward-char 3)
498                             t)
499                         (not (and (imap-parse-greeting)
500                                   ;; success in imtest < 1.6:
501                                   (or (re-search-forward
502                                        "^__\\(.*\\)__\n" nil t)
503                                       ;; success in imtest 1.6:
504                                       (re-search-forward
505                                        "^\\(Authenticat.*\\)" nil t))
506                                   (setq response (match-string 1)))))
507               (accept-process-output process 1)
508               (sit-for 1))
509             (and imap-log
510                  (with-current-buffer (get-buffer-create imap-log-buffer)
511                    (imap-disable-multibyte)
512                    (buffer-disable-undo)
513                    (goto-char (point-max))
514                    (insert-buffer-substring buffer)))
515             (erase-buffer)
516             (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
517                      (if response (concat "done, " response) "failed"))
518             (if (and response (let ((case-fold-search nil))
519                                 (not (string-match "failed" response))))
520                 (setq done process)
521               (if (memq (process-status process) '(open run))
522                   (imap-send-command "LOGOUT"))
523               (delete-process process)
524               nil)))))
525     done))
526
527 (defun imap-gssapi-stream-p (buffer)
528   (imap-capability 'AUTH=GSSAPI buffer))
529
530 (defun imap-gssapi-open (name buffer server port)
531   (let ((cmds imap-gssapi-program)
532         cmd done)
533     (while (and (not done) (setq cmd (pop cmds)))
534       (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
535       (let* ((port (or port imap-default-port))
536              (coding-system-for-read imap-coding-system-for-read)
537              (coding-system-for-write imap-coding-system-for-write)
538              (process-connection-type imap-process-connection-type)
539              (process (start-process
540                        name buffer shell-file-name shell-command-switch
541                        (format-spec
542                         cmd
543                         (format-spec-make
544                          ?s server
545                          ?p (number-to-string port)
546                          ?l imap-default-user))))
547              response)
548         (when process
549           (with-current-buffer buffer
550             (setq imap-client-eol "\n"
551                   imap-calculate-literal-size-first t)
552             (while (and (memq (process-status process) '(open run))
553                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
554                         (goto-char (point-min))
555                         ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
556                         (or (while (looking-at "^C:")
557                               (forward-line))
558                             t)
559                         ;; cyrus 1.6 imtest print "S: " before server greeting
560                         (or (not (looking-at "S: "))
561                             (forward-char 3)
562                             t)
563                         (not (and (imap-parse-greeting)
564                                   ;; success in imtest 1.6:
565                                   (re-search-forward
566                                    (concat "^\\(\\(Authenticat.*\\)\\|\\("
567                                            "Client authentication "
568                                            "finished.*\\)\\)")
569                                    nil t)
570                                   (setq response (match-string 1)))))
571               (accept-process-output process 1)
572               (sit-for 1))
573             (and imap-log
574                  (with-current-buffer (get-buffer-create imap-log-buffer)
575                    (imap-disable-multibyte)
576                    (buffer-disable-undo)
577                    (goto-char (point-max))
578                    (insert-buffer-substring buffer)))
579             (erase-buffer)
580             (message "GSSAPI IMAP connection: %s" (or response "failed"))
581             (if (and response (let ((case-fold-search nil))
582                                 (not (string-match "failed" response))))
583                 (setq done process)
584               (if (memq (process-status process) '(open run))
585                   (imap-send-command "LOGOUT"))
586               (delete-process process)
587               nil)))))
588     done))
589
590 (defun imap-ssl-p (buffer)
591   nil)
592
593 (defun imap-ssl-open (name buffer server port)
594   "Open a SSL connection to server."
595   (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
596                 (list imap-ssl-program)))
597         cmd done)
598     (while (and (not done) (setq cmd (pop cmds)))
599       (message "imap: Opening SSL connection with `%s'..." cmd)
600       (let* ((port (or port imap-default-ssl-port))
601              (coding-system-for-read imap-coding-system-for-read)
602              (coding-system-for-write imap-coding-system-for-write)
603              (process-connection-type nil)
604              process)
605         (when (progn
606                 (setq process (start-process 
607                                name buffer shell-file-name
608                                shell-command-switch
609                                (format-spec cmd 
610                                             (format-spec-make
611                                              ?s server
612                                              ?p (number-to-string port)))))
613                 (process-kill-without-query process)
614                 process)
615           (with-current-buffer buffer
616             (goto-char (point-min))
617             (while (and (memq (process-status process) '(open run))
618                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
619                         (goto-char (point-max))
620                         (forward-line -1)
621                         (not (imap-parse-greeting)))
622               (accept-process-output process 1)
623               (sit-for 1))
624             (and imap-log
625                  (with-current-buffer (get-buffer-create imap-log-buffer)
626                    (imap-disable-multibyte)
627                    (buffer-disable-undo)
628                    (goto-char (point-max))
629                    (insert-buffer-substring buffer)))
630             (erase-buffer)
631             (when (memq (process-status process) '(open run))
632               (setq done process))))))
633     (if done
634         (progn
635           (message "imap: Opening SSL connection with `%s'...done" cmd)
636           done)
637       (message "imap: Opening SSL connection with `%s'...failed" cmd)
638       nil)))
639
640 (defun imap-tls-p (buffer)
641   nil)
642
643 (defun imap-tls-open (name buffer server port)
644   (let* ((port (or port imap-default-tls-port))
645          (coding-system-for-read imap-coding-system-for-read)
646          (coding-system-for-write imap-coding-system-for-write)
647          (process (open-tls-stream name buffer server port)))
648     (when process
649       (while (and (memq (process-status process) '(open run))
650                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
651                   (goto-char (point-max))
652                   (forward-line -1)
653                   (not (imap-parse-greeting)))
654         (accept-process-output process 1)
655         (sit-for 1))
656       (and imap-log
657            (with-current-buffer (get-buffer-create imap-log-buffer)
658              (imap-disable-multibyte)
659              (buffer-disable-undo)
660              (goto-char (point-max))
661              (insert-buffer-substring buffer)))
662       (when (memq (process-status process) '(open run))
663         process))))
664
665 (defun imap-network-p (buffer)
666   t)
667
668 (defun imap-network-open (name buffer server port)
669   (let* ((port (or port imap-default-port))
670          (coding-system-for-read imap-coding-system-for-read)
671          (coding-system-for-write imap-coding-system-for-write)
672          (process (open-network-stream 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              (coding-system-for-read imap-coding-system-for-read)
701              (coding-system-for-write imap-coding-system-for-write)
702              (process (start-process
703                        name buffer shell-file-name shell-command-switch
704                        (format-spec
705                         cmd
706                         (format-spec-make
707                          ?s server
708                          ?g imap-shell-host
709                          ?p (number-to-string port)
710                          ?l imap-default-user)))))
711         (when process
712           (while (and (memq (process-status process) '(open run))
713                       (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
714                       (goto-char (point-max))
715                       (forward-line -1)
716                       (not (imap-parse-greeting)))
717             (accept-process-output process 1)
718             (sit-for 1))
719           (and imap-log
720                (with-current-buffer (get-buffer-create imap-log-buffer)
721                  (imap-disable-multibyte)
722                  (buffer-disable-undo)
723                  (goto-char (point-max))
724                  (insert-buffer-substring buffer)))
725           (erase-buffer)
726           (when (memq (process-status process) '(open run))
727             (setq done process)))))
728     (if done
729         (progn
730           (message "imap: Opening IMAP connection with `%s'...done" cmd)
731           done)
732       (message "imap: Opening IMAP connection with `%s'...failed" cmd)
733       nil)))
734
735 (defun imap-starttls-p (buffer)
736   (imap-capability 'STARTTLS buffer))
737
738 (defun imap-starttls-open (name buffer server port)
739   (let* ((port (or port imap-default-port))
740          (coding-system-for-read imap-coding-system-for-read)
741          (coding-system-for-write imap-coding-system-for-write)
742          (process (starttls-open-stream name buffer server port))
743          done)
744     (message "imap: Connecting with STARTTLS...")
745     (when process
746       (while (and (memq (process-status process) '(open run))
747                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
748                   (goto-char (point-min))
749                   (not (imap-parse-greeting)))
750         (accept-process-output process 1)
751         (sit-for 1))
752       (and imap-log
753            (with-current-buffer (get-buffer-create imap-log-buffer)
754              (buffer-disable-undo)
755              (goto-char (point-max))
756              (insert-buffer-substring buffer)))
757       (let ((imap-process process))
758         (unwind-protect
759             (progn
760               (set-process-filter imap-process 'imap-arrival-filter)
761               (when (and (eq imap-stream 'starttls)
762                          (imap-ok-p (imap-send-command-wait "STARTTLS")))
763                 (starttls-negotiate imap-process)))
764           (set-process-filter imap-process nil)))
765       (when (memq (process-status process) '(open run))
766         (setq done process)))
767     (if done
768         (progn
769           (message "imap: Connecting with STARTTLS...done")
770           done)
771       (message "imap: Connecting with STARTTLS...failed")
772       nil)))
773
774 ;; Server functions; authenticator stuff:
775
776 (defun imap-interactive-login (buffer loginfunc)
777   "Login to server in BUFFER.
778 LOGINFUNC is passed a username and a password, it should return t if
779 it where successful authenticating itself to the server, nil otherwise.
780 Returns t if login was successful, nil otherwise."
781   (with-current-buffer buffer
782     (make-local-variable 'imap-username)
783     (make-local-variable 'imap-password)
784     (let (user passwd ret)
785       ;;      (condition-case ()
786       (while (or (not user) (not passwd))
787         (setq user (or imap-username
788                        (read-from-minibuffer
789                         (concat "IMAP username for " imap-server
790                                 " (using stream `" (symbol-name imap-stream)
791                                 "'): ")
792                         (or user imap-default-user))))
793         (setq passwd (or imap-password
794                          (read-passwd
795                           (concat "IMAP password for " user "@"
796                                   imap-server " (using authenticator `"
797                                   (symbol-name imap-auth) "'): "))))
798         (when (and user passwd)
799           (if (funcall loginfunc user passwd)
800               (progn
801                 (setq ret t
802                       imap-username user)
803                 (if (and (not imap-password)
804                          (y-or-n-p "Store password for this session? "))
805                     (setq imap-password passwd)))
806             (message "Login failed...")
807             (setq passwd nil)
808             (sit-for 1))))
809       ;;        (quit (with-current-buffer buffer
810       ;;                (setq user nil
811       ;;                      passwd nil)))
812       ;;        (error (with-current-buffer buffer
813       ;;                 (setq user nil
814       ;;                       passwd nil))))
815       ret)))
816
817 (defun imap-gssapi-auth-p (buffer)
818   (and (imap-capability 'AUTH=GSSAPI buffer)
819        (eq imap-stream 'gssapi)))
820
821 (defun imap-gssapi-auth (buffer)
822   (message "imap: Authenticating using GSSAPI...%s"
823            (if (eq imap-stream 'gssapi) "done" "failed"))
824   (eq imap-stream 'gssapi))
825
826 (defun imap-kerberos4-auth-p (buffer)
827   (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
828        (eq imap-stream 'kerberos4)))
829
830 (defun imap-kerberos4-auth (buffer)
831   (message "imap: Authenticating using Kerberos 4...%s"
832            (if (eq imap-stream 'kerberos4) "done" "failed"))
833   (eq imap-stream 'kerberos4))
834
835 (defun imap-cram-md5-p (buffer)
836   (imap-capability 'AUTH=CRAM-MD5 buffer))
837
838 (defun imap-cram-md5-auth (buffer)
839   "Login to server using the AUTH CRAM-MD5 method."
840   (message "imap: Authenticating using CRAM-MD5...")
841   (let ((done (imap-interactive-login
842                buffer
843                (lambda (user passwd)
844                  (imap-ok-p
845                   (imap-send-command-wait
846                    (list
847                     "AUTHENTICATE CRAM-MD5"
848                     (lambda (challenge)
849                       (let* ((decoded (base64-decode-string challenge))
850                              (hash (rfc2104-hash 'md5 64 16 passwd decoded))
851                              (response (concat user " " hash))
852                              (encoded (base64-encode-string response)))
853                         encoded)))))))))
854     (if done
855         (message "imap: Authenticating using CRAM-MD5...done")
856       (message "imap: Authenticating using CRAM-MD5...failed"))))
857
858 (defun imap-login-p (buffer)
859   (and (not (imap-capability 'LOGINDISABLED buffer))
860        (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
861
862 (defun imap-login-auth (buffer)
863   "Login to server using the LOGIN command."
864   (message "imap: Plaintext authentication...")
865   (imap-interactive-login buffer
866                           (lambda (user passwd)
867                             (imap-ok-p (imap-send-command-wait
868                                         (concat "LOGIN \"" user "\" \""
869                                                 passwd "\""))))))
870
871 (defun imap-anonymous-p (buffer)
872   t)
873
874 (defun imap-anonymous-auth (buffer)
875   (message "imap: Logging in anonymously...")
876   (with-current-buffer buffer
877     (imap-ok-p (imap-send-command-wait
878                 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
879                                                      (system-name)) "\"")))))
880
881 (defun imap-digest-md5-p (buffer)
882   (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
883        (condition-case ()
884            (require 'digest-md5)
885          (error nil))))
886
887 (defun imap-digest-md5-auth (buffer)
888   "Login to server using the AUTH DIGEST-MD5 method."
889   (message "imap: Authenticating using DIGEST-MD5...")
890   (imap-interactive-login
891    buffer
892    (lambda (user passwd)
893      (let ((tag
894             (imap-send-command
895              (list
896               "AUTHENTICATE DIGEST-MD5"
897               (lambda (challenge)
898                 (digest-md5-parse-digest-challenge
899                  (base64-decode-string challenge))
900                 (let* ((digest-uri
901                         (digest-md5-digest-uri
902                          "imap" (digest-md5-challenge 'realm)))
903                        (response
904                         (digest-md5-digest-response
905                          user passwd digest-uri)))
906                   (base64-encode-string response 'no-line-break))))
907              )))
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 1)))
1741       (when imap-have-messaged
1742         (message ""))
1743       (and (memq (process-status imap-process) '(open run))
1744            (or (assq tag imap-failed-tags)
1745                (if imap-continuation
1746                    'INCOMPLETE
1747                  'OK))))))
1748
1749 (defun imap-sentinel (process string)
1750   (delete-process process))
1751
1752 (defun imap-find-next-line ()
1753   "Return point at end of current line, taking into account literals.
1754 Return nil if no complete line has arrived."
1755   (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1756                                    imap-server-eol)
1757                            nil t)
1758     (if (match-string 1)
1759         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1760             nil
1761           (goto-char (+ (point) (string-to-number (match-string 1))))
1762           (imap-find-next-line))
1763       (point))))
1764
1765 (defun imap-arrival-filter (proc string)
1766   "IMAP process filter."
1767   (with-current-buffer (process-buffer proc)
1768     (goto-char (point-max))
1769     (insert string)
1770     (and imap-log
1771          (with-current-buffer (get-buffer-create imap-log-buffer)
1772            (imap-disable-multibyte)
1773            (buffer-disable-undo)
1774            (goto-char (point-max))
1775            (insert string)))
1776     (let (end)
1777       (goto-char (point-min))
1778       (while (setq end (imap-find-next-line))
1779         (save-restriction
1780           (narrow-to-region (point-min) end)
1781           (delete-backward-char (length imap-server-eol))
1782           (goto-char (point-min))
1783           (unwind-protect
1784               (cond ((eq imap-state 'initial)
1785                      (imap-parse-greeting))
1786                     ((or (eq imap-state 'auth)
1787                          (eq imap-state 'nonauth)
1788                          (eq imap-state 'selected)
1789                          (eq imap-state 'examine))
1790                      (imap-parse-response))
1791                     (t
1792                      (message "Unknown state %s in arrival filter"
1793                               imap-state)))
1794             (delete-region (point-min) (point-max))))))))
1795
1796 \f
1797 ;; Imap parser.
1798
1799 (defsubst imap-forward ()
1800   (or (eobp) (forward-char)))
1801
1802 ;;   number          = 1*DIGIT
1803 ;;                       ; Unsigned 32-bit integer
1804 ;;                       ; (0 <= n < 4,294,967,296)
1805
1806 (defsubst imap-parse-number ()
1807   (when (looking-at "[0-9]+")
1808     (prog1
1809         (string-to-number (match-string 0))
1810       (goto-char (match-end 0)))))
1811
1812 ;;   literal         = "{" number "}" CRLF *CHAR8
1813 ;;                       ; Number represents the number of CHAR8s
1814
1815 (defsubst imap-parse-literal ()
1816   (when (looking-at "{\\([0-9]+\\)}\r\n")
1817     (let ((pos (match-end 0))
1818           (len (string-to-number (match-string 1))))
1819       (if (< (point-max) (+ pos len))
1820           nil
1821         (goto-char (+ pos len))
1822         (buffer-substring pos (+ pos len))))))
1823
1824 ;;   string          = quoted / literal
1825 ;;
1826 ;;   quoted          = DQUOTE *QUOTED-CHAR DQUOTE
1827 ;;
1828 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
1829 ;;                     "\" quoted-specials
1830 ;;
1831 ;;   quoted-specials = DQUOTE / "\"
1832 ;;
1833 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
1834
1835 (defsubst imap-parse-string ()
1836   (cond ((eq (char-after) ?\")
1837          (forward-char 1)
1838          (let ((p (point)) (name ""))
1839            (skip-chars-forward "^\"\\\\")
1840            (setq name (buffer-substring p (point)))
1841            (while (eq (char-after) ?\\)
1842              (setq p (1+ (point)))
1843              (forward-char 2)
1844              (skip-chars-forward "^\"\\\\")
1845              (setq name (concat name (buffer-substring p (point)))))
1846            (forward-char 1)
1847            name))
1848         ((eq (char-after) ?{)
1849          (imap-parse-literal))))
1850
1851 ;;   nil             = "NIL"
1852
1853 (defsubst imap-parse-nil ()
1854   (if (looking-at "NIL")
1855       (goto-char (match-end 0))))
1856
1857 ;;   nstring         = string / nil
1858
1859 (defsubst imap-parse-nstring ()
1860   (or (imap-parse-string)
1861       (and (imap-parse-nil)
1862            nil)))
1863
1864 ;;   astring         = atom / string
1865 ;;
1866 ;;   atom            = 1*ATOM-CHAR
1867 ;;
1868 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
1869 ;;
1870 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
1871 ;;                     quoted-specials
1872 ;;
1873 ;;   list-wildcards  = "%" / "*"
1874 ;;
1875 ;;   quoted-specials = DQUOTE / "\"
1876
1877 (defsubst imap-parse-astring ()
1878   (or (imap-parse-string)
1879       (buffer-substring (point)
1880                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1881                             (goto-char (1- (match-end 0)))
1882                           (end-of-line)
1883                           (point)))))
1884
1885 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
1886 ;;                      addr-host ")"
1887 ;;
1888 ;;   addr-adl        = nstring
1889 ;;                       ; Holds route from [RFC-822] route-addr if
1890 ;;                       ; non-nil
1891 ;;
1892 ;;   addr-host       = nstring
1893 ;;                       ; nil indicates [RFC-822] group syntax.
1894 ;;                       ; Otherwise, holds [RFC-822] domain name
1895 ;;
1896 ;;   addr-mailbox    = nstring
1897 ;;                       ; nil indicates end of [RFC-822] group; if
1898 ;;                       ; non-nil and addr-host is nil, holds
1899 ;;                       ; [RFC-822] group name.
1900 ;;                       ; Otherwise, holds [RFC-822] local-part
1901 ;;                       ; after removing [RFC-822] quoting
1902 ;;
1903 ;;   addr-name       = nstring
1904 ;;                       ; If non-nil, holds phrase from [RFC-822]
1905 ;;                       ; mailbox after removing [RFC-822] quoting
1906 ;;
1907
1908 (defsubst imap-parse-address ()
1909   (let (address)
1910     (when (eq (char-after) ?\()
1911       (imap-forward)
1912       (setq address (vector (prog1 (imap-parse-nstring)
1913                               (imap-forward))
1914                             (prog1 (imap-parse-nstring)
1915                               (imap-forward))
1916                             (prog1 (imap-parse-nstring)
1917                               (imap-forward))
1918                             (imap-parse-nstring)))
1919       (when (eq (char-after) ?\))
1920         (imap-forward)
1921         address))))
1922
1923 ;;   address-list    = "(" 1*address ")" / nil
1924 ;;
1925 ;;   nil             = "NIL"
1926
1927 (defsubst imap-parse-address-list ()
1928   (if (eq (char-after) ?\()
1929       (let (address addresses)
1930         (imap-forward)
1931         (while (and (not (eq (char-after) ?\)))
1932                     ;; next line for MS Exchange bug
1933                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
1934                     (setq address (imap-parse-address)))
1935           (setq addresses (cons address addresses)))
1936         (when (eq (char-after) ?\))
1937           (imap-forward)
1938           (nreverse addresses)))
1939     (assert (imap-parse-nil) t "In imap-parse-address-list")))
1940
1941 ;;   mailbox         = "INBOX" / astring
1942 ;;                       ; INBOX is case-insensitive.  All case variants of
1943 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1944 ;;                       ; not as an astring.  An astring which consists of
1945 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
1946 ;;                       ; is considered to be INBOX and not an astring.
1947 ;;                       ;  Refer to section 5.1 for further
1948 ;;                       ; semantic details of mailbox names.
1949
1950 (defsubst imap-parse-mailbox ()
1951   (let ((mailbox (imap-parse-astring)))
1952     (if (string-equal "INBOX" (upcase mailbox))
1953         "INBOX"
1954       mailbox)))
1955
1956 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1957 ;;
1958 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
1959 ;;                       ; Authentication condition
1960 ;;
1961 ;;   resp-cond-bye   = "BYE" SP resp-text
1962
1963 (defun imap-parse-greeting ()
1964   "Parse a IMAP greeting."
1965   (cond ((looking-at "\\* OK ")
1966          (setq imap-state 'nonauth))
1967         ((looking-at "\\* PREAUTH ")
1968          (setq imap-state 'auth))
1969         ((looking-at "\\* BYE ")
1970          (setq imap-state 'closed))))
1971
1972 ;;   response        = *(continue-req / response-data) response-done
1973 ;;
1974 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
1975 ;;
1976 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
1977 ;;                     mailbox-data / message-data / capability-data) CRLF
1978 ;;
1979 ;;   response-done   = response-tagged / response-fatal
1980 ;;
1981 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
1982 ;;                       ; Server closes connection immediately
1983 ;;
1984 ;;   response-tagged = tag SP resp-cond-state CRLF
1985 ;;
1986 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1987 ;;                       ; Status condition
1988 ;;
1989 ;;   resp-cond-bye   = "BYE" SP resp-text
1990 ;;
1991 ;;   mailbox-data    =  "FLAGS" SP flag-list /
1992 ;;                      "LIST" SP mailbox-list /
1993 ;;                      "LSUB" SP mailbox-list /
1994 ;;                      "SEARCH" *(SP nz-number) /
1995 ;;                      "STATUS" SP mailbox SP "("
1996 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
1997 ;;                      number SP "EXISTS" /
1998 ;;                      number SP "RECENT"
1999 ;;
2000 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2001 ;;
2002 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2003 ;;                     *(SP capability)
2004 ;;                       ; IMAP4rev1 servers which offer RFC 1730
2005 ;;                       ; compatibility MUST list "IMAP4" as the first
2006 ;;                       ; capability.
2007
2008 (defun imap-parse-response ()
2009   "Parse a IMAP command response."
2010   (let (token)
2011     (case (setq token (read (current-buffer)))
2012       (+ (setq imap-continuation
2013                (or (buffer-substring (min (point-max) (1+ (point)))
2014                                      (point-max))
2015                    t)))
2016       (* (case (prog1 (setq token (read (current-buffer)))
2017                  (imap-forward))
2018            (OK         (imap-parse-resp-text))
2019            (NO         (imap-parse-resp-text))
2020            (BAD        (imap-parse-resp-text))
2021            (BYE        (imap-parse-resp-text))
2022            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
2023            (LIST       (imap-parse-data-list 'list))
2024            (LSUB       (imap-parse-data-list 'lsub))
2025            (SEARCH     (imap-mailbox-put
2026                         'search
2027                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2028            (STATUS     (imap-parse-status))
2029            (CAPABILITY (setq imap-capability
2030                                (read (concat "(" (upcase (buffer-substring
2031                                                           (point) (point-max)))
2032                                              ")"))))
2033            (ACL        (imap-parse-acl))
2034            (t       (case (prog1 (read (current-buffer))
2035                             (imap-forward))
2036                       (EXISTS  (imap-mailbox-put 'exists token))
2037                       (RECENT  (imap-mailbox-put 'recent token))
2038                       (EXPUNGE t)
2039                       (FETCH   (imap-parse-fetch token))
2040                       (t       (message "Garbage: %s" (buffer-string)))))))
2041       (t (let (status)
2042            (if (not (integerp token))
2043                (message "Garbage: %s" (buffer-string))
2044              (case (prog1 (setq status (read (current-buffer)))
2045                      (imap-forward))
2046                (OK  (progn
2047                       (setq imap-reached-tag (max imap-reached-tag token))
2048                       (imap-parse-resp-text)))
2049                (NO  (progn
2050                       (setq imap-reached-tag (max imap-reached-tag token))
2051                       (save-excursion
2052                         (imap-parse-resp-text))
2053                       (let (code text)
2054                         (when (eq (char-after) ?\[)
2055                           (setq code (buffer-substring (point)
2056                                                        (search-forward "]")))
2057                           (imap-forward))
2058                         (setq text (buffer-substring (point) (point-max)))
2059                         (push (list token status code text)
2060                               imap-failed-tags))))
2061                (BAD (progn
2062                       (setq imap-reached-tag (max imap-reached-tag token))
2063                       (save-excursion
2064                         (imap-parse-resp-text))
2065                       (let (code text)
2066                         (when (eq (char-after) ?\[)
2067                           (setq code (buffer-substring (point)
2068                                                        (search-forward "]")))
2069                           (imap-forward))
2070                         (setq text (buffer-substring (point) (point-max)))
2071                         (push (list token status code text) imap-failed-tags)
2072                         (error "Internal error, tag %s status %s code %s text %s"
2073                                token status code text))))
2074                (t   (message "Garbage: %s" (buffer-string))))
2075              (when (assq token imap-callbacks)
2076                (funcall (cdr (assq token imap-callbacks)) token status)
2077                (setq imap-callbacks
2078                      (imap-remassoc token imap-callbacks)))))))))
2079
2080 ;;   resp-text       = ["[" resp-text-code "]" SP] text
2081 ;;
2082 ;;   text            = 1*TEXT-CHAR
2083 ;;
2084 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2085
2086 (defun imap-parse-resp-text ()
2087   (imap-parse-resp-text-code))
2088
2089 ;;   resp-text-code  = "ALERT" /
2090 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2091 ;;                     "NEWNAME" SP string SP string /
2092 ;;                     "PARSE" /
2093 ;;                     "PERMANENTFLAGS" SP "("
2094 ;;                               [flag-perm *(SP flag-perm)] ")" /
2095 ;;                     "READ-ONLY" /
2096 ;;                     "READ-WRITE" /
2097 ;;                     "TRYCREATE" /
2098 ;;                     "UIDNEXT" SP nz-number /
2099 ;;                     "UIDVALIDITY" SP nz-number /
2100 ;;                     "UNSEEN" SP nz-number /
2101 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2102 ;;
2103 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
2104 ;;
2105 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
2106 ;;
2107 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
2108 ;;                        (set "," set)
2109 ;;                          ; Identifies a set of messages.  For message
2110 ;;                          ; sequence numbers, these are consecutive
2111 ;;                          ; numbers from 1 to the number of messages in
2112 ;;                          ; the mailbox
2113 ;;                          ; Comma delimits individual numbers, colon
2114 ;;                          ; delimits between two numbers inclusive.
2115 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2116 ;;                          ; 14,15 for a mailbox with 15 messages.
2117 ;;
2118 ;;   sequence-num    = nz-number / "*"
2119 ;;                          ; * is the largest number in use.  For message
2120 ;;                          ; sequence numbers, it is the number of messages
2121 ;;                          ; in the mailbox.  For unique identifiers, it is
2122 ;;                          ; the unique identifier of the last message in
2123 ;;                          ; the mailbox.
2124 ;;
2125 ;;   flag-perm       = flag / "\*"
2126 ;;
2127 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2128 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2129 ;;                       ; Does not include "\Recent"
2130 ;;
2131 ;;   flag-extension  = "\" atom
2132 ;;                       ; Future expansion.  Client implementations
2133 ;;                       ; MUST accept flag-extension flags.  Server
2134 ;;                       ; implementations MUST NOT generate
2135 ;;                       ; flag-extension flags except as defined by
2136 ;;                       ; future standard or standards-track
2137 ;;                       ; revisions of this specification.
2138 ;;
2139 ;;   flag-keyword    = atom
2140 ;;
2141 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
2142
2143 (defun imap-parse-resp-text-code ()
2144   ;; xxx next line for stalker communigate pro 3.3.1 bug
2145   (when (looking-at " \\[")
2146     (imap-forward))
2147   (when (eq (char-after) ?\[)
2148     (imap-forward)
2149     (cond ((search-forward "PERMANENTFLAGS " nil t)
2150            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2151           ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2152            (imap-mailbox-put 'uidnext (match-string 1)))
2153           ((search-forward "UNSEEN " nil t)
2154            (imap-mailbox-put 'first-unseen (read (current-buffer))))
2155           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2156            (imap-mailbox-put 'uidvalidity (match-string 1)))
2157           ((search-forward "READ-ONLY" nil t)
2158            (imap-mailbox-put 'read-only t))
2159           ((search-forward "NEWNAME " nil t)
2160            (let (oldname newname)
2161              (setq oldname (imap-parse-string))
2162              (imap-forward)
2163              (setq newname (imap-parse-string))
2164              (imap-mailbox-put 'newname newname oldname)))
2165           ((search-forward "TRYCREATE" nil t)
2166            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2167           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2168            (imap-mailbox-put 'appenduid
2169                              (list (match-string 1)
2170                                    (string-to-number (match-string 2)))
2171                              imap-current-target-mailbox))
2172           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2173            (imap-mailbox-put 'copyuid (list (match-string 1)
2174                                             (match-string 2)
2175                                             (match-string 3))
2176                              imap-current-target-mailbox))
2177           ((search-forward "ALERT] " nil t)
2178            (message "Imap server %s information: %s" imap-server
2179                     (buffer-substring (point) (point-max)))))))
2180
2181 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
2182 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2183 ;;
2184 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
2185 ;;                     *(SP mbx-list-oflag) /
2186 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
2187 ;;
2188 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
2189 ;;                       ; Other flags; multiple possible per LIST response
2190 ;;
2191 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
2192 ;;                       ; Selectability flags; only one per LIST response
2193 ;;
2194 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2195 ;;                     "\" quoted-specials
2196 ;;
2197 ;;   quoted-specials = DQUOTE / "\"
2198
2199 (defun imap-parse-data-list (type)
2200   (let (flags delimiter mailbox)
2201     (setq flags (imap-parse-flag-list))
2202     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2203       (setq delimiter (match-string 1))
2204       (goto-char (1+ (match-end 0)))
2205       (when (setq mailbox (imap-parse-mailbox))
2206         (imap-mailbox-put type t mailbox)
2207         (imap-mailbox-put 'list-flags flags mailbox)
2208         (imap-mailbox-put 'delimiter delimiter mailbox)))))
2209
2210 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
2211 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2212 ;;                      "INTERNALDATE" SPACE date_time /
2213 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2214 ;;                      "RFC822.SIZE" SPACE number /
2215 ;;                      "BODY" ["STRUCTURE"] SPACE body /
2216 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
2217 ;;                      "UID" SPACE uniqueid) ")"
2218 ;;
2219 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
2220 ;;                      SPACE time SPACE zone <">
2221 ;;
2222 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
2223 ;;                      ["." (section_text / "MIME")])] "]"
2224 ;;
2225 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2226 ;;                      SPACE header_list / "TEXT"
2227 ;;
2228 ;;  header_fld_name ::= astring
2229 ;;
2230 ;;  header_list     ::= "(" 1#header_fld_name ")"
2231
2232 (defsubst imap-parse-header-list ()
2233   (when (eq (char-after) ?\()
2234     (let (strlist)
2235       (while (not (eq (char-after) ?\)))
2236         (imap-forward)
2237         (push (imap-parse-astring) strlist))
2238       (imap-forward)
2239       (nreverse strlist))))
2240
2241 (defsubst imap-parse-fetch-body-section ()
2242   (let ((section
2243          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2244     (if (eq (char-before) ? )
2245         (prog1
2246             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2247           (search-forward "]" nil t))
2248       section)))
2249
2250 (defun imap-parse-fetch (response)
2251   (when (eq (char-after) ?\()
2252     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2253               rfc822size body bodydetail bodystructure flags-empty)
2254       (while (not (eq (char-after) ?\)))
2255         (imap-forward)
2256         (let ((token (read (current-buffer))))
2257           (imap-forward)
2258           (cond ((eq token 'UID)
2259                  (setq uid (condition-case ()
2260                                (read (current-buffer))
2261                              (error))))
2262                 ((eq token 'FLAGS)
2263                  (setq flags (imap-parse-flag-list))
2264                  (if (not flags)
2265                      (setq flags-empty 't)))
2266                 ((eq token 'ENVELOPE)
2267                  (setq envelope (imap-parse-envelope)))
2268                 ((eq token 'INTERNALDATE)
2269                  (setq internaldate (imap-parse-string)))
2270                 ((eq token 'RFC822)
2271                  (setq rfc822 (imap-parse-nstring)))
2272                 ((eq token 'RFC822.HEADER)
2273                  (setq rfc822header (imap-parse-nstring)))
2274                 ((eq token 'RFC822.TEXT)
2275                  (setq rfc822text (imap-parse-nstring)))
2276                 ((eq token 'RFC822.SIZE)
2277                  (setq rfc822size (read (current-buffer))))
2278                 ((eq token 'BODY)
2279                  (if (eq (char-before) ?\[)
2280                      (push (list
2281                             (upcase (imap-parse-fetch-body-section))
2282                             (and (eq (char-after) ?<)
2283                                  (buffer-substring (1+ (point))
2284                                                    (search-forward ">" nil t)))
2285                             (progn (imap-forward)
2286                                    (imap-parse-nstring)))
2287                            bodydetail)
2288                    (setq body (imap-parse-body))))
2289                 ((eq token 'BODYSTRUCTURE)
2290                  (setq bodystructure (imap-parse-body))))))
2291       (when uid
2292         (setq imap-current-message uid)
2293         (imap-message-put uid 'UID uid)
2294         (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2295         (and envelope (imap-message-put uid 'ENVELOPE envelope))
2296         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2297         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2298         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2299         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2300         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2301         (and body (imap-message-put uid 'BODY body))
2302         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2303         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2304         (run-hooks 'imap-fetch-data-hook)))))
2305
2306 ;;   mailbox-data    =  ...
2307 ;;                      "STATUS" SP mailbox SP "("
2308 ;;                            [status-att SP number
2309 ;;                            *(SP status-att SP number)] ")"
2310 ;;                      ...
2311 ;;
2312 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2313 ;;                     "UNSEEN"
2314
2315 (defun imap-parse-status ()
2316   (let ((mailbox (imap-parse-mailbox)))
2317     (if (eq (char-after) ? )
2318         (forward-char))
2319     (when (and mailbox (eq (char-after) ?\())
2320       (while (and (not (eq (char-after) ?\)))
2321                   (or (forward-char) t)
2322                   (looking-at "\\([A-Za-z]+\\) "))
2323         (let ((token (match-string 1)))
2324           (goto-char (match-end 0))
2325           (cond ((string= token "MESSAGES")
2326                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2327                 ((string= token "RECENT")
2328                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2329                 ((string= token "UIDNEXT")
2330                  (and (looking-at "[0-9]+")
2331                       (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2332                       (goto-char (match-end 0))))
2333                 ((string= token "UIDVALIDITY")
2334                  (and (looking-at "[0-9]+")
2335                       (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2336                       (goto-char (match-end 0))))
2337                 ((string= token "UNSEEN")
2338                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2339                 (t
2340                  (message "Unknown status data %s in mailbox %s ignored"
2341                           token mailbox)
2342                  (read (current-buffer)))))))))
2343
2344 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2345 ;;                        rights)
2346 ;;
2347 ;;   identifier      ::= astring
2348 ;;
2349 ;;   rights          ::= astring
2350
2351 (defun imap-parse-acl ()
2352   (let ((mailbox (imap-parse-mailbox))
2353         identifier rights acl)
2354     (while (eq (char-after) ?\ )
2355       (imap-forward)
2356       (setq identifier (imap-parse-astring))
2357       (imap-forward)
2358       (setq rights (imap-parse-astring))
2359       (setq acl (append acl (list (cons identifier rights)))))
2360     (imap-mailbox-put 'acl acl mailbox)))
2361
2362 ;;   flag-list       = "(" [flag *(SP flag)] ")"
2363 ;;
2364 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2365 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2366 ;;                       ; Does not include "\Recent"
2367 ;;
2368 ;;   flag-keyword    = atom
2369 ;;
2370 ;;   flag-extension  = "\" atom
2371 ;;                       ; Future expansion.  Client implementations
2372 ;;                       ; MUST accept flag-extension flags.  Server
2373 ;;                       ; implementations MUST NOT generate
2374 ;;                       ; flag-extension flags except as defined by
2375 ;;                       ; future standard or standards-track
2376 ;;                       ; revisions of this specification.
2377
2378 (defun imap-parse-flag-list ()
2379   (let (flag-list start)
2380     (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2381     (while (and (not (eq (char-after) ?\)))
2382                 (setq start (progn
2383                               (imap-forward)
2384                               ;; next line for Courier IMAP bug.
2385                               (skip-chars-forward " ")
2386                               (point)))
2387                 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2388       (push (buffer-substring start (point)) flag-list))
2389     (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2390     (imap-forward)
2391     (nreverse flag-list)))
2392
2393 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
2394 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
2395 ;;                     env-in-reply-to SP env-message-id ")"
2396 ;;
2397 ;;   env-bcc         = "(" 1*address ")" / nil
2398 ;;
2399 ;;   env-cc          = "(" 1*address ")" / nil
2400 ;;
2401 ;;   env-date        = nstring
2402 ;;
2403 ;;   env-from        = "(" 1*address ")" / nil
2404 ;;
2405 ;;   env-in-reply-to = nstring
2406 ;;
2407 ;;   env-message-id  = nstring
2408 ;;
2409 ;;   env-reply-to    = "(" 1*address ")" / nil
2410 ;;
2411 ;;   env-sender      = "(" 1*address ")" / nil
2412 ;;
2413 ;;   env-subject     = nstring
2414 ;;
2415 ;;   env-to          = "(" 1*address ")" / nil
2416
2417 (defun imap-parse-envelope ()
2418   (when (eq (char-after) ?\()
2419     (imap-forward)
2420     (vector (prog1 (imap-parse-nstring) ;; date
2421               (imap-forward))
2422             (prog1 (imap-parse-nstring) ;; subject
2423               (imap-forward))
2424             (prog1 (imap-parse-address-list) ;; from
2425               (imap-forward))
2426             (prog1 (imap-parse-address-list) ;; sender
2427               (imap-forward))
2428             (prog1 (imap-parse-address-list) ;; reply-to
2429               (imap-forward))
2430             (prog1 (imap-parse-address-list) ;; to
2431               (imap-forward))
2432             (prog1 (imap-parse-address-list) ;; cc
2433               (imap-forward))
2434             (prog1 (imap-parse-address-list) ;; bcc
2435               (imap-forward))
2436             (prog1 (imap-parse-nstring) ;; in-reply-to
2437               (imap-forward))
2438             (prog1 (imap-parse-nstring) ;; message-id
2439               (imap-forward)))))
2440
2441 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2442
2443 (defsubst imap-parse-string-list ()
2444   (cond ((eq (char-after) ?\() ;; body-fld-param
2445          (let (strlist str)
2446            (imap-forward)
2447            (while (setq str (imap-parse-string))
2448              (push str strlist)
2449              ;; buggy stalker communigate pro 3.0 doesn't print SPC
2450              ;; between body-fld-param's sometimes
2451              (or (eq (char-after) ?\")
2452                  (imap-forward)))
2453            (nreverse strlist)))
2454         ((imap-parse-nil)
2455          nil)))
2456
2457 ;;   body-extension  = nstring / number /
2458 ;;                      "(" body-extension *(SP body-extension) ")"
2459 ;;                       ; Future expansion.  Client implementations
2460 ;;                       ; MUST accept body-extension fields.  Server
2461 ;;                       ; implementations MUST NOT generate
2462 ;;                       ; body-extension fields except as defined by
2463 ;;                       ; future standard or standards-track
2464 ;;                       ; revisions of this specification.
2465
2466 (defun imap-parse-body-extension ()
2467   (if (eq (char-after) ?\()
2468       (let (b-e)
2469         (imap-forward)
2470         (push (imap-parse-body-extension) b-e)
2471         (while (eq (char-after) ?\ )
2472           (imap-forward)
2473           (push (imap-parse-body-extension) b-e))
2474         (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2475         (imap-forward)
2476         (nreverse b-e))
2477     (or (imap-parse-number)
2478         (imap-parse-nstring))))
2479
2480 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2481 ;;                     *(SP body-extension)]]
2482 ;;                       ; MUST NOT be returned on non-extensible
2483 ;;                       ; "BODY" fetch
2484 ;;
2485 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2486 ;;                     *(SP body-extension)]]
2487 ;;                       ; MUST NOT be returned on non-extensible
2488 ;;                       ; "BODY" fetch
2489
2490 (defsubst imap-parse-body-ext ()
2491   (let (ext)
2492     (when (eq (char-after) ?\ ) ;; body-fld-dsp
2493       (imap-forward)
2494       (let (dsp)
2495         (if (eq (char-after) ?\()
2496             (progn
2497               (imap-forward)
2498               (push (imap-parse-string) dsp)
2499               (imap-forward)
2500               (push (imap-parse-string-list) dsp)
2501               (imap-forward))
2502           (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2503         (push (nreverse dsp) ext))
2504       (when (eq (char-after) ?\ ) ;; body-fld-lang
2505         (imap-forward)
2506         (if (eq (char-after) ?\()
2507             (push (imap-parse-string-list) ext)
2508           (push (imap-parse-nstring) ext))
2509         (while (eq (char-after) ?\ ) ;; body-extension
2510           (imap-forward)
2511           (setq ext (append (imap-parse-body-extension) ext)))))
2512     ext))
2513
2514 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2515 ;;
2516 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2517 ;;                     *(SP body-extension)]]
2518 ;;                       ; MUST NOT be returned on non-extensible
2519 ;;                       ; "BODY" fetch
2520 ;;
2521 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2522 ;;                     *(SP body-extension)]]
2523 ;;                       ; MUST NOT be returned on non-extensible
2524 ;;                       ; "BODY" fetch
2525 ;;
2526 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2527 ;;                     body-fld-enc SP body-fld-octets
2528 ;;
2529 ;;   body-fld-desc   = nstring
2530 ;;
2531 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2532 ;;
2533 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2534 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2535 ;;
2536 ;;   body-fld-id     = nstring
2537 ;;
2538 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2539 ;;
2540 ;;   body-fld-lines  = number
2541 ;;
2542 ;;   body-fld-md5    = nstring
2543 ;;
2544 ;;   body-fld-octets = number
2545 ;;
2546 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2547 ;;
2548 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2549 ;;                     [SP body-ext-1part]
2550 ;;
2551 ;;   body-type-basic = media-basic SP body-fields
2552 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2553 ;;
2554 ;;   body-type-msg   = media-message SP body-fields SP envelope
2555 ;;                     SP body SP body-fld-lines
2556 ;;
2557 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2558 ;;
2559 ;;   body-type-mpart = 1*body SP media-subtype
2560 ;;                     [SP body-ext-mpart]
2561 ;;
2562 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2563 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2564 ;;                       ; Defined in [MIME-IMT]
2565 ;;
2566 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2567 ;;                      ; Defined in [MIME-IMT]
2568 ;;
2569 ;;   media-subtype   = string
2570 ;;                       ; Defined in [MIME-IMT]
2571 ;;
2572 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2573 ;;                       ; Defined in [MIME-IMT]
2574
2575 (defun imap-parse-body ()
2576   (let (body)
2577     (when (eq (char-after) ?\()
2578       (imap-forward)
2579       (if (eq (char-after) ?\()
2580           (let (subbody)
2581             (while (and (eq (char-after) ?\()
2582                         (setq subbody (imap-parse-body)))
2583              ;; buggy stalker communigate pro 3.0 insert a SPC between
2584               ;; parts in multiparts
2585               (when (and (eq (char-after) ?\ )
2586                          (eq (char-after (1+ (point))) ?\())
2587                 (imap-forward))
2588               (push subbody body))
2589             (imap-forward)
2590             (push (imap-parse-string) body) ;; media-subtype
2591             (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2592               (imap-forward)
2593               (if (eq (char-after) ?\() ;; body-fld-param
2594                   (push (imap-parse-string-list) body)
2595                 (push (and (imap-parse-nil) nil) body))
2596               (setq body
2597                     (append (imap-parse-body-ext) body))) ;; body-ext-...
2598             (assert (eq (char-after) ?\)) t "In imap-parse-body")
2599             (imap-forward)
2600             (nreverse body))
2601
2602         (push (imap-parse-string) body) ;; media-type
2603         (imap-forward)
2604         (push (imap-parse-string) body) ;; media-subtype
2605         (imap-forward)
2606         ;; next line for Sun SIMS bug
2607         (and (eq (char-after) ? ) (imap-forward))
2608         (if (eq (char-after) ?\() ;; body-fld-param
2609             (push (imap-parse-string-list) body)
2610           (push (and (imap-parse-nil) nil) body))
2611         (imap-forward)
2612         (push (imap-parse-nstring) body) ;; body-fld-id
2613         (imap-forward)
2614         (push (imap-parse-nstring) body) ;; body-fld-desc
2615         (imap-forward)
2616         ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2617         ;; nstring and return nil instead of defaulting back to 7BIT
2618         ;; as the standard says.
2619         (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2620         (imap-forward)
2621         (push (imap-parse-number) body) ;; body-fld-octets
2622
2623    ;; ok, we're done parsing the required parts, what comes now is one
2624         ;; of three things:
2625         ;;
2626         ;; envelope       (then we're parsing body-type-msg)
2627         ;; body-fld-lines (then we're parsing body-type-text)
2628         ;; body-ext-1part (then we're parsing body-type-basic)
2629         ;;
2630   ;; the problem is that the two first are in turn optionally followed
2631 ;; by the third.  So we parse the first two here (if there are any)...
2632
2633         (when (eq (char-after) ?\ )
2634           (imap-forward)
2635           (let (lines)
2636             (cond ((eq (char-after) ?\() ;; body-type-msg:
2637                    (push (imap-parse-envelope) body) ;; envelope
2638                    (imap-forward)
2639                    (push (imap-parse-body) body) ;; body
2640                    ;; buggy stalker communigate pro 3.0 doesn't print
2641                    ;; number of lines in message/rfc822 attachment
2642                    (if (eq (char-after) ?\))
2643                        (push 0 body)
2644                      (imap-forward)
2645                      (push (imap-parse-number) body))) ;; body-fld-lines
2646                   ((setq lines (imap-parse-number)) ;; body-type-text:
2647                    (push lines body)) ;; body-fld-lines
2648                   (t
2649                    (backward-char))))) ;; no match...
2650
2651         ;; ...and then parse the third one here...
2652
2653         (when (eq (char-after) ?\ ) ;; body-ext-1part:
2654           (imap-forward)
2655           (push (imap-parse-nstring) body) ;; body-fld-md5
2656           (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2657
2658         (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2659         (imap-forward)
2660         (nreverse body)))))
2661
2662 (when imap-debug                        ; (untrace-all)
2663   (require 'trace)
2664   (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2665   (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2666           '(
2667             imap-utf7-encode
2668             imap-utf7-decode
2669             imap-error-text
2670             imap-kerberos4s-p
2671             imap-kerberos4-open
2672             imap-ssl-p
2673             imap-ssl-open
2674             imap-network-p
2675             imap-network-open
2676             imap-interactive-login
2677             imap-kerberos4a-p
2678             imap-kerberos4-auth
2679             imap-cram-md5-p
2680             imap-cram-md5-auth
2681             imap-login-p
2682             imap-login-auth
2683             imap-anonymous-p
2684             imap-anonymous-auth
2685             imap-open-1
2686             imap-open
2687             imap-opened
2688             imap-authenticate
2689             imap-close
2690             imap-capability
2691             imap-namespace
2692             imap-send-command-wait
2693             imap-mailbox-put
2694             imap-mailbox-get
2695             imap-mailbox-map-1
2696             imap-mailbox-map
2697             imap-current-mailbox
2698             imap-current-mailbox-p-1
2699             imap-current-mailbox-p
2700             imap-mailbox-select-1
2701             imap-mailbox-select
2702             imap-mailbox-examine-1
2703             imap-mailbox-examine
2704             imap-mailbox-unselect
2705             imap-mailbox-expunge
2706             imap-mailbox-close
2707             imap-mailbox-create-1
2708             imap-mailbox-create
2709             imap-mailbox-delete
2710             imap-mailbox-rename
2711             imap-mailbox-lsub
2712             imap-mailbox-list
2713             imap-mailbox-subscribe
2714             imap-mailbox-unsubscribe
2715             imap-mailbox-status
2716             imap-mailbox-acl-get
2717             imap-mailbox-acl-set
2718             imap-mailbox-acl-delete
2719             imap-current-message
2720             imap-list-to-message-set
2721             imap-fetch-asynch
2722             imap-fetch
2723             imap-message-put
2724             imap-message-get
2725             imap-message-map
2726             imap-search
2727             imap-message-flag-permanent-p
2728             imap-message-flags-set
2729             imap-message-flags-del
2730             imap-message-flags-add
2731             imap-message-copyuid-1
2732             imap-message-copyuid
2733             imap-message-copy
2734             imap-message-appenduid-1
2735             imap-message-appenduid
2736             imap-message-append
2737             imap-body-lines
2738             imap-envelope-from
2739             imap-send-command-1
2740             imap-send-command
2741             imap-wait-for-tag
2742             imap-sentinel
2743             imap-find-next-line
2744             imap-arrival-filter
2745             imap-parse-greeting
2746             imap-parse-response
2747             imap-parse-resp-text
2748             imap-parse-resp-text-code
2749             imap-parse-data-list
2750             imap-parse-fetch
2751             imap-parse-status
2752             imap-parse-acl
2753             imap-parse-flag-list
2754             imap-parse-envelope
2755             imap-parse-body-extension
2756             imap-parse-body
2757             )))
2758
2759 (provide 'imap)
2760
2761 ;;; imap.el ends here