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