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