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