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