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