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