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