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