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