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