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