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