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