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