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