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