1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
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)
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.
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.
27 ;; imap.el is a elisp library providing an interface for talking to
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.
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.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
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
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
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; 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'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
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.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
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.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
141 (autoload 'base64-decode-string "base64")
142 (autoload 'base64-encode-string "base64")
143 (autoload 'starttls-open-stream "starttls")
144 (autoload 'starttls-negotiate "starttls")
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 'md5 "md5")
151 (autoload 'utf7-encode "utf7")
152 (autoload 'utf7-decode "utf7")
153 (autoload 'format-spec "format-spec")
154 (autoload 'format-spec-make "format-spec")
155 (autoload 'open-tls-stream "tls")
156 ;; Avoid use gnus-point-at-eol so we're independent of Gnus. These
157 ;; days we have point-at-eol anyhow.
158 (if (fboundp 'point-at-eol)
159 (defalias 'imap-point-at-eol 'point-at-eol)
160 (defun imap-point-at-eol ()
168 "Low-level IMAP issues."
172 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
174 "List of strings containing commands for Kerberos 4 authentication.
175 %s is replaced with server hostname, %p with port to connect to, and
176 %l with the value of `imap-default-user'. The program should accept
177 IMAP commands on stdin and return responses to stdout. Each entry in
178 the list is tried until a successful connection is made."
180 :type '(repeat string))
182 (defcustom imap-gssapi-program (list
183 (concat "gsasl --client --connect %s:%p "
184 "--imap --application-data "
185 "--mechanism GSSAPI "
186 "--authentication-id %l")
187 "imtest -m gssapi -u %l -p %p %s")
188 "List of strings containing commands for GSSAPI (krb5) authentication.
189 %s is replaced with server hostname, %p with port to connect to, and
190 %l with the value of `imap-default-user'. The program should accept
191 IMAP commands on stdin and return responses to stdout. Each entry in
192 the list is tried until a successful connection is made."
194 :type '(repeat string))
196 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
197 "openssl s_client -quiet -ssl2 -connect %s:%p"
198 "s_client -quiet -ssl3 -connect %s:%p"
199 "s_client -quiet -ssl2 -connect %s:%p")
200 "A string, or list of strings, containing commands for SSL connections.
201 Within a string, %s is replaced with the server address and %p with
202 port number on server. The program should accept IMAP commands on
203 stdin and return responses to stdout. Each entry in the list is tried
204 until a successful connection is made."
206 :type '(choice string
209 (defcustom imap-shell-program '("ssh %s imapd"
211 "ssh %g ssh %s imapd"
212 "rsh %g rsh %s imapd")
213 "A list of strings, containing commands for IMAP connection.
214 Within a string, %s is replaced with the server address, %p with port
215 number on server, %g with `imap-shell-host', and %l with
216 `imap-default-user'. The program should read IMAP commands from stdin
217 and write IMAP response to stdout. Each entry in the list is tried
218 until a successful connection is made."
220 :type '(repeat string))
222 (defcustom imap-process-connection-type nil
223 "*Value for `process-connection-type' to use for Kerberos4 and GSSAPI."
227 (defcustom imap-use-utf7 t
228 "If non-nil, do utf7 encoding/decoding of mailbox names.
229 Since the UTF7 decoding currently only decodes into ISO-8859-1
230 characters, you may disable this decoding if you need to access UTF7
231 encoded mailboxes which doesn't translate into ISO-8859-1."
235 (defcustom imap-log nil
236 "If non-nil, a imap session trace is placed in *imap-log* buffer."
240 (defcustom imap-debug nil
241 "If non-nil, random debug spews are placed in *imap-debug* buffer."
245 (defcustom imap-shell-host "gateway"
246 "Hostname of rlogin proxy."
250 (defcustom imap-default-user (user-login-name)
251 "Default username to use."
255 ;; Various variables.
257 (defvar imap-fetch-data-hook nil
258 "Hooks called after receiving each FETCH response.")
260 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
261 "Priority of streams to consider when opening connection to server.")
263 (defvar imap-stream-alist
264 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
265 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
266 (tls imap-tls-p imap-tls-open)
267 (ssl imap-ssl-p imap-ssl-open)
268 (network imap-network-p imap-network-open)
269 (shell imap-shell-p imap-shell-open)
270 (starttls imap-starttls-p imap-starttls-open))
271 "Definition of network streams.
275 NAME names the stream, CHECK is a function returning non-nil if the
276 server support the stream and OPEN is a function for opening the
279 (defvar imap-authenticators '(gssapi
285 "Priority of authenticators to consider when authenticating to server.")
287 (defvar imap-authenticator-alist
288 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
289 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
290 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
291 (login imap-login-p imap-login-auth)
292 (anonymous imap-anonymous-p imap-anonymous-auth)
293 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
294 "Definition of authenticators.
296 \(NAME CHECK AUTHENTICATE)
298 NAME names the authenticator. CHECK is a function returning non-nil if
299 the server support the authenticator and AUTHENTICATE is a function
300 for doing the actual authentication.")
302 (defvar imap-error nil
303 "Error codes from the last command.")
305 ;; Internal constants. Change theese and die.
307 (defconst imap-default-port 143)
308 (defconst imap-default-ssl-port 993)
309 (defconst imap-default-tls-port 993)
310 (defconst imap-default-stream 'network)
311 (defconst imap-coding-system-for-read 'binary)
312 (defconst imap-coding-system-for-write 'binary)
313 (defconst imap-local-variables '(imap-server
322 imap-current-target-mailbox
331 imap-calculate-literal-size-first
333 (defconst imap-log-buffer "*imap-log*")
334 (defconst imap-debug-buffer "*imap-debug*")
336 ;; Internal variables.
338 (defvar imap-stream nil)
339 (defvar imap-auth nil)
340 (defvar imap-server nil)
341 (defvar imap-port nil)
342 (defvar imap-username nil)
343 (defvar imap-password nil)
344 (defvar imap-calculate-literal-size-first nil)
345 (defvar imap-state 'closed
347 Valid states are `closed', `initial', `nonauth', `auth', `selected'
350 (defvar imap-server-eol "\r\n"
351 "The EOL string sent from the server.")
353 (defvar imap-client-eol "\r\n"
354 "The EOL string we send to the server.")
356 (defvar imap-current-mailbox nil
357 "Current mailbox name.")
359 (defvar imap-current-target-mailbox nil
360 "Current target mailbox for COPY and APPEND commands.")
362 (defvar imap-mailbox-data nil
363 "Obarray with mailbox data.")
365 (defvar imap-mailbox-prime 997
366 "Length of imap-mailbox-data.")
368 (defvar imap-current-message nil
369 "Current message number.")
371 (defvar imap-message-data nil
372 "Obarray with message data.")
374 (defvar imap-message-prime 997
375 "Length of imap-message-data.")
377 (defvar imap-capability nil
378 "Capability for server.")
380 (defvar imap-namespace nil
381 "Namespace for current server.")
383 (defvar imap-reached-tag 0
384 "Lower limit on command tags that have been parsed.")
386 (defvar imap-failed-tags nil
387 "Alist of tags that failed.
388 Each element is a list with four elements; tag (a integer), response
389 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
390 human readable response text (a string).")
393 "Command tag number.")
395 (defvar imap-process nil
398 (defvar imap-continuation nil
399 "Non-nil indicates that the server emitted a continuation request.
400 The actual value is really the text on the continuation line.")
402 (defvar imap-callbacks nil
403 "List of response tags and callbacks, on the form `(number . function)'.
404 The function should take two arguments, the first the IMAP tag and the
405 second the status (OK, NO, BAD etc) of the command.")
408 ;; Utility functions:
410 (defun imap-remassoc (key alist)
411 "Delete by side effect any elements of LIST whose car is `equal' to KEY.
412 The modified LIST is returned. If the first member
413 of LIST has a car that is `equal' to KEY, there is no way to remove it
414 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
415 sure of changing the value of `foo'."
417 (if (equal key (caar alist))
419 (setcdr alist (imap-remassoc key (cdr alist)))
422 (defsubst imap-disable-multibyte ()
423 "Enable multibyte in the current buffer."
424 (when (fboundp 'set-buffer-multibyte)
425 (set-buffer-multibyte nil)))
427 (defsubst imap-utf7-encode (string)
431 (utf7-encode string t)
433 "imap: Could not UTF7 encode `%s', using it unencoded..."
438 (defsubst imap-utf7-decode (string)
442 (utf7-decode string t)
444 "imap: Could not UTF7 decode `%s', using it undecoded..."
449 (defsubst imap-ok-p (status)
452 (setq imap-error status)
455 (defun imap-error-text (&optional buffer)
456 (with-current-buffer (or buffer (current-buffer))
457 (nth 3 (car imap-failed-tags))))
460 ;; Server functions; stream stuff:
462 (defun imap-kerberos4-stream-p (buffer)
463 (imap-capability 'AUTH=KERBEROS_V4 buffer))
465 (defun imap-kerberos4-open (name buffer server port)
466 (let ((cmds imap-kerberos4-program)
468 (while (and (not done) (setq cmd (pop cmds)))
469 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
471 (let* ((port (or port imap-default-port))
472 (coding-system-for-read imap-coding-system-for-read)
473 (coding-system-for-write imap-coding-system-for-write)
474 (process-connection-type imap-process-connection-type)
475 (process (start-process
476 name buffer shell-file-name shell-command-switch
481 ?p (number-to-string port)
482 ?l imap-default-user))))
485 (with-current-buffer buffer
486 (setq imap-client-eol "\n"
487 imap-calculate-literal-size-first t)
488 (while (and (memq (process-status process) '(open run))
489 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
490 (goto-char (point-min))
491 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
492 (or (while (looking-at "^C:")
495 ;; cyrus 1.6 imtest print "S: " before server greeting
496 (or (not (looking-at "S: "))
499 (not (and (imap-parse-greeting)
500 ;; success in imtest < 1.6:
501 (or (re-search-forward
502 "^__\\(.*\\)__\n" nil t)
503 ;; success in imtest 1.6:
505 "^\\(Authenticat.*\\)" nil t))
506 (setq response (match-string 1)))))
507 (accept-process-output process 1)
510 (with-current-buffer (get-buffer-create imap-log-buffer)
511 (imap-disable-multibyte)
512 (buffer-disable-undo)
513 (goto-char (point-max))
514 (insert-buffer-substring buffer)))
516 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
517 (if response (concat "done, " response) "failed"))
518 (if (and response (let ((case-fold-search nil))
519 (not (string-match "failed" response))))
521 (if (memq (process-status process) '(open run))
522 (imap-send-command "LOGOUT"))
523 (delete-process process)
527 (defun imap-gssapi-stream-p (buffer)
528 (imap-capability 'AUTH=GSSAPI buffer))
530 (defun imap-gssapi-open (name buffer server port)
531 (let ((cmds imap-gssapi-program)
533 (while (and (not done) (setq cmd (pop cmds)))
534 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
535 (let* ((port (or port imap-default-port))
536 (coding-system-for-read imap-coding-system-for-read)
537 (coding-system-for-write imap-coding-system-for-write)
538 (process-connection-type imap-process-connection-type)
539 (process (start-process
540 name buffer shell-file-name shell-command-switch
545 ?p (number-to-string port)
546 ?l imap-default-user))))
549 (with-current-buffer buffer
550 (setq imap-client-eol "\n"
551 imap-calculate-literal-size-first t)
552 (while (and (memq (process-status process) '(open run))
553 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
554 (goto-char (point-min))
555 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
556 (or (while (looking-at "^C:")
559 ;; cyrus 1.6 imtest print "S: " before server greeting
560 (or (not (looking-at "S: "))
563 (not (and (imap-parse-greeting)
564 ;; success in imtest 1.6:
566 (concat "^\\(\\(Authenticat.*\\)\\|\\("
567 "Client authentication "
570 (setq response (match-string 1)))))
571 (accept-process-output process 1)
574 (with-current-buffer (get-buffer-create imap-log-buffer)
575 (imap-disable-multibyte)
576 (buffer-disable-undo)
577 (goto-char (point-max))
578 (insert-buffer-substring buffer)))
580 (message "GSSAPI IMAP connection: %s" (or response "failed"))
581 (if (and response (let ((case-fold-search nil))
582 (not (string-match "failed" response))))
584 (if (memq (process-status process) '(open run))
585 (imap-send-command "LOGOUT"))
586 (delete-process process)
590 (defun imap-ssl-p (buffer)
593 (defun imap-ssl-open (name buffer server port)
594 "Open a SSL connection to server."
595 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
596 (list imap-ssl-program)))
598 (while (and (not done) (setq cmd (pop cmds)))
599 (message "imap: Opening SSL connection with `%s'..." cmd)
600 (let* ((port (or port imap-default-ssl-port))
601 (coding-system-for-read imap-coding-system-for-read)
602 (coding-system-for-write imap-coding-system-for-write)
603 (process-connection-type nil)
606 (setq process (start-process
607 name buffer shell-file-name
612 ?p (number-to-string port)))))
613 (process-kill-without-query process)
615 (with-current-buffer buffer
616 (goto-char (point-min))
617 (while (and (memq (process-status process) '(open run))
618 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
619 (goto-char (point-max))
621 (not (imap-parse-greeting)))
622 (accept-process-output process 1)
625 (with-current-buffer (get-buffer-create imap-log-buffer)
626 (imap-disable-multibyte)
627 (buffer-disable-undo)
628 (goto-char (point-max))
629 (insert-buffer-substring buffer)))
631 (when (memq (process-status process) '(open run))
632 (setq done process))))))
635 (message "imap: Opening SSL connection with `%s'...done" cmd)
637 (message "imap: Opening SSL connection with `%s'...failed" cmd)
640 (defun imap-tls-p (buffer)
643 (defun imap-tls-open (name buffer server port)
644 (let* ((port (or port imap-default-tls-port))
645 (coding-system-for-read imap-coding-system-for-read)
646 (coding-system-for-write imap-coding-system-for-write)
647 (process (open-tls-stream name buffer server port)))
649 (while (and (memq (process-status process) '(open run))
650 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
651 (goto-char (point-max))
653 (not (imap-parse-greeting)))
654 (accept-process-output process 1)
657 (with-current-buffer (get-buffer-create imap-log-buffer)
658 (imap-disable-multibyte)
659 (buffer-disable-undo)
660 (goto-char (point-max))
661 (insert-buffer-substring buffer)))
662 (when (memq (process-status process) '(open run))
665 (defun imap-network-p (buffer)
668 (defun imap-network-open (name buffer server port)
669 (let* ((port (or port imap-default-port))
670 (coding-system-for-read imap-coding-system-for-read)
671 (coding-system-for-write imap-coding-system-for-write)
672 (process (open-network-stream name buffer server port)))
674 (while (and (memq (process-status process) '(open run))
675 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
676 (goto-char (point-min))
677 (not (imap-parse-greeting)))
678 (accept-process-output process 1)
681 (with-current-buffer (get-buffer-create imap-log-buffer)
682 (imap-disable-multibyte)
683 (buffer-disable-undo)
684 (goto-char (point-max))
685 (insert-buffer-substring buffer)))
686 (when (memq (process-status process) '(open run))
689 (defun imap-shell-p (buffer)
692 (defun imap-shell-open (name buffer server port)
693 (let ((cmds (if (listp imap-shell-program) imap-shell-program
694 (list imap-shell-program)))
696 (while (and (not done) (setq cmd (pop cmds)))
697 (message "imap: Opening IMAP connection with `%s'..." cmd)
698 (setq imap-client-eol "\n")
699 (let* ((port (or port imap-default-port))
700 (coding-system-for-read imap-coding-system-for-read)
701 (coding-system-for-write imap-coding-system-for-write)
702 (process (start-process
703 name buffer shell-file-name shell-command-switch
709 ?p (number-to-string port)
710 ?l imap-default-user)))))
712 (while (and (memq (process-status process) '(open run))
713 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
714 (goto-char (point-max))
716 (not (imap-parse-greeting)))
717 (accept-process-output process 1)
720 (with-current-buffer (get-buffer-create imap-log-buffer)
721 (imap-disable-multibyte)
722 (buffer-disable-undo)
723 (goto-char (point-max))
724 (insert-buffer-substring buffer)))
726 (when (memq (process-status process) '(open run))
727 (setq done process)))))
730 (message "imap: Opening IMAP connection with `%s'...done" cmd)
732 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
735 (defun imap-starttls-p (buffer)
736 (imap-capability 'STARTTLS buffer))
738 (defun imap-starttls-open (name buffer server port)
739 (let* ((port (or port imap-default-port))
740 (coding-system-for-read imap-coding-system-for-read)
741 (coding-system-for-write imap-coding-system-for-write)
742 (process (starttls-open-stream name buffer server port))
744 (message "imap: Connecting with STARTTLS...")
746 (while (and (memq (process-status process) '(open run))
747 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
748 (goto-char (point-min))
749 (not (imap-parse-greeting)))
750 (accept-process-output process 1)
753 (with-current-buffer (get-buffer-create imap-log-buffer)
754 (buffer-disable-undo)
755 (goto-char (point-max))
756 (insert-buffer-substring buffer)))
757 (let ((imap-process process))
760 (set-process-filter imap-process 'imap-arrival-filter)
761 (when (and (eq imap-stream 'starttls)
762 (imap-ok-p (imap-send-command-wait "STARTTLS")))
763 (starttls-negotiate imap-process)))
764 (set-process-filter imap-process nil)))
765 (when (memq (process-status process) '(open run))
766 (setq done process)))
769 (message "imap: Connecting with STARTTLS...done")
771 (message "imap: Connecting with STARTTLS...failed")
774 ;; Server functions; authenticator stuff:
776 (defun imap-interactive-login (buffer loginfunc)
777 "Login to server in BUFFER.
778 LOGINFUNC is passed a username and a password, it should return t if
779 it where successful authenticating itself to the server, nil otherwise.
780 Returns t if login was successful, nil otherwise."
781 (with-current-buffer buffer
782 (make-local-variable 'imap-username)
783 (make-local-variable 'imap-password)
784 (let (user passwd ret)
785 ;; (condition-case ()
786 (while (or (not user) (not passwd))
787 (setq user (or imap-username
788 (read-from-minibuffer
789 (concat "IMAP username for " imap-server
790 " (using stream `" (symbol-name imap-stream)
792 (or user imap-default-user))))
793 (setq passwd (or imap-password
795 (concat "IMAP password for " user "@"
796 imap-server " (using authenticator `"
797 (symbol-name imap-auth) "'): "))))
798 (when (and user passwd)
799 (if (funcall loginfunc user passwd)
803 (if (and (not imap-password)
804 (y-or-n-p "Store password for this session? "))
805 (setq imap-password passwd)))
806 (message "Login failed...")
809 ;; (quit (with-current-buffer buffer
812 ;; (error (with-current-buffer buffer
817 (defun imap-gssapi-auth-p (buffer)
818 (and (imap-capability 'AUTH=GSSAPI buffer)
819 (eq imap-stream 'gssapi)))
821 (defun imap-gssapi-auth (buffer)
822 (message "imap: Authenticating using GSSAPI...%s"
823 (if (eq imap-stream 'gssapi) "done" "failed"))
824 (eq imap-stream 'gssapi))
826 (defun imap-kerberos4-auth-p (buffer)
827 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
828 (eq imap-stream 'kerberos4)))
830 (defun imap-kerberos4-auth (buffer)
831 (message "imap: Authenticating using Kerberos 4...%s"
832 (if (eq imap-stream 'kerberos4) "done" "failed"))
833 (eq imap-stream 'kerberos4))
835 (defun imap-cram-md5-p (buffer)
836 (imap-capability 'AUTH=CRAM-MD5 buffer))
838 (defun imap-cram-md5-auth (buffer)
839 "Login to server using the AUTH CRAM-MD5 method."
840 (message "imap: Authenticating using CRAM-MD5...")
841 (let ((done (imap-interactive-login
843 (lambda (user passwd)
845 (imap-send-command-wait
847 "AUTHENTICATE CRAM-MD5"
849 (let* ((decoded (base64-decode-string challenge))
850 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
851 (response (concat user " " hash))
852 (encoded (base64-encode-string response)))
855 (message "imap: Authenticating using CRAM-MD5...done")
856 (message "imap: Authenticating using CRAM-MD5...failed"))))
858 (defun imap-login-p (buffer)
859 (and (not (imap-capability 'LOGINDISABLED buffer))
860 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
862 (defun imap-login-auth (buffer)
863 "Login to server using the LOGIN command."
864 (message "imap: Plaintext authentication...")
865 (imap-interactive-login buffer
866 (lambda (user passwd)
867 (imap-ok-p (imap-send-command-wait
868 (concat "LOGIN \"" user "\" \""
871 (defun imap-anonymous-p (buffer)
874 (defun imap-anonymous-auth (buffer)
875 (message "imap: Logging in anonymously...")
876 (with-current-buffer buffer
877 (imap-ok-p (imap-send-command-wait
878 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
879 (system-name)) "\"")))))
881 (defun imap-digest-md5-p (buffer)
882 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
884 (require 'digest-md5)
887 (defun imap-digest-md5-auth (buffer)
888 "Login to server using the AUTH DIGEST-MD5 method."
889 (message "imap: Authenticating using DIGEST-MD5...")
890 (imap-interactive-login
892 (lambda (user passwd)
896 "AUTHENTICATE DIGEST-MD5"
898 (digest-md5-parse-digest-challenge
899 (base64-decode-string challenge))
901 (digest-md5-digest-uri
902 "imap" (digest-md5-challenge 'realm)))
904 (digest-md5-digest-response
905 user passwd digest-uri)))
906 (base64-encode-string response 'no-line-break))))
908 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
910 (setq imap-continuation nil)
911 (imap-send-command-1 "")
912 (imap-ok-p (imap-wait-for-tag tag)))))))
916 (defun imap-open-1 (buffer)
917 (with-current-buffer buffer
919 (setq imap-current-mailbox nil
920 imap-current-message nil
922 imap-process (condition-case ()
923 (funcall (nth 2 (assq imap-stream
925 "imap" buffer imap-server imap-port)
928 (set-process-filter imap-process 'imap-arrival-filter)
929 (set-process-sentinel imap-process 'imap-sentinel)
930 (while (and (eq imap-state 'initial)
931 (memq (process-status imap-process) '(open run)))
932 (message "Waiting for response from %s..." imap-server)
933 (accept-process-output imap-process 1))
934 (message "Waiting for response from %s...done" imap-server)
935 (and (memq (process-status imap-process) '(open run))
938 (defun imap-open (server &optional port stream auth buffer)
939 "Open a IMAP connection to host SERVER at PORT returning a buffer.
940 If PORT is unspecified, a default value is used (143 except
941 for SSL which use 993).
942 STREAM indicates the stream to use, see `imap-streams' for available
943 streams. If nil, it choices the best stream the server is capable of.
944 AUTH indicates authenticator to use, see `imap-authenticators' for
945 available authenticators. If nil, it choices the best stream the
946 server is capable of.
947 BUFFER can be a buffer or a name of a buffer, which is created if
948 necessary. If nil, the buffer name is generated."
949 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
950 (with-current-buffer (get-buffer-create buffer)
951 (if (imap-opened buffer)
953 (mapcar 'make-local-variable imap-local-variables)
954 (imap-disable-multibyte)
955 (buffer-disable-undo)
956 (setq imap-server (or server imap-server))
957 (setq imap-port (or port imap-port))
958 (setq imap-auth (or auth imap-auth))
959 (setq imap-stream (or stream imap-stream))
960 (message "imap: Connecting to %s..." imap-server)
961 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
962 (imap-open-1 buffer)))
964 (message "imap: Connecting to %s...failed" imap-server)
966 (when (null imap-stream)
967 ;; Need to choose stream.
968 (let ((streams imap-streams))
969 (while (setq stream (pop streams))
970 ;; OK to use this stream?
971 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
973 (if (not (eq imap-default-stream stream))
974 (with-current-buffer (get-buffer-create
975 (generate-new-buffer-name " *temp*"))
976 (mapcar 'make-local-variable imap-local-variables)
977 (imap-disable-multibyte)
978 (buffer-disable-undo)
979 (setq imap-server (or server imap-server))
980 (setq imap-port (or port imap-port))
981 (setq imap-auth (or auth imap-auth))
982 (message "imap: Reconnecting with stream `%s'..." stream)
983 (if (null (let ((imap-stream stream))
984 (imap-open-1 (current-buffer))))
986 (kill-buffer (current-buffer))
988 "imap: Reconnecting with stream `%s'...failed"
990 ;; We're done, kill the first connection
993 (rename-buffer buffer)
994 (message "imap: Reconnecting with stream `%s'...done"
996 (setq imap-stream stream)
997 (setq imap-capability nil)
1000 (message "imap: Connecting to %s...done" imap-server)
1001 (setq imap-stream stream)
1002 (setq imap-capability nil)
1003 (setq streams nil))))))
1004 (when (imap-opened buffer)
1005 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1009 (defun imap-opened (&optional buffer)
1010 "Return non-nil if connection to imap server in BUFFER is open.
1011 If BUFFER is nil then the current buffer is used."
1012 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1013 (buffer-live-p buffer)
1014 (with-current-buffer buffer
1016 (memq (process-status imap-process) '(open run))))))
1018 (defun imap-authenticate (&optional user passwd buffer)
1019 "Authenticate to server in BUFFER, using current buffer if nil.
1020 It uses the authenticator specified when opening the server. If the
1021 authenticator requires username/passwords, they are queried from the
1022 user and optionally stored in the buffer. If USER and/or PASSWD is
1023 specified, the user will not be questioned and the username and/or
1024 password is remembered in the buffer."
1025 (with-current-buffer (or buffer (current-buffer))
1026 (if (not (eq imap-state 'nonauth))
1027 (or (eq imap-state 'auth)
1028 (eq imap-state 'select)
1029 (eq imap-state 'examine))
1030 (make-local-variable 'imap-username)
1031 (make-local-variable 'imap-password)
1032 (if user (setq imap-username user))
1033 (if passwd (setq imap-password passwd))
1035 (and (funcall (nth 2 (assq imap-auth
1036 imap-authenticator-alist)) buffer)
1037 (setq imap-state 'auth))
1038 ;; Choose authenticator.
1039 (let ((auths imap-authenticators)
1041 (while (setq auth (pop auths))
1042 ;; OK to use authenticator?
1043 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1044 (message "imap: Authenticating to `%s' using `%s'..."
1046 (setq imap-auth auth)
1047 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1049 (message "imap: Authenticating to `%s' using `%s'...done"
1052 (message "imap: Authenticating to `%s' using `%s'...failed"
1053 imap-server auth)))))
1056 (defun imap-close (&optional buffer)
1057 "Close connection to server in BUFFER.
1058 If BUFFER is nil, the current buffer is used."
1059 (with-current-buffer (or buffer (current-buffer))
1062 (imap-send-command-wait "LOGOUT")
1064 (when (and imap-process
1065 (memq (process-status imap-process) '(open run)))
1066 (delete-process imap-process))
1067 (setq imap-current-mailbox nil
1068 imap-current-message nil
1073 (defun imap-capability (&optional identifier buffer)
1074 "Return a list of identifiers which server in BUFFER support.
1075 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1076 If BUFFER is nil, the current buffer is assumed."
1077 (with-current-buffer (or buffer (current-buffer))
1078 (unless imap-capability
1079 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1080 (setq imap-capability '(IMAP2))))
1082 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1085 (defun imap-namespace (&optional buffer)
1086 "Return a namespace hierarchy at server in BUFFER.
1087 If BUFFER is nil, the current buffer is assumed."
1088 (with-current-buffer (or buffer (current-buffer))
1089 (unless imap-namespace
1090 (when (imap-capability 'NAMESPACE)
1091 (imap-send-command-wait "NAMESPACE")))
1094 (defun imap-send-command-wait (command &optional buffer)
1095 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1098 ;; Mailbox functions:
1100 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1101 (with-current-buffer (or buffer (current-buffer))
1102 (if imap-mailbox-data
1103 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1105 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1106 propname value mailbox (current-buffer)))
1109 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1110 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1113 (defun imap-mailbox-get (propname &optional mailbox buffer)
1114 (let ((mailbox (imap-utf7-encode mailbox)))
1115 (with-current-buffer (or buffer (current-buffer))
1116 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1118 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1119 (with-current-buffer (or buffer (current-buffer))
1123 (push (funcall func (if mailbox-decoder
1124 (funcall mailbox-decoder (symbol-name s))
1125 (symbol-name s))) result))
1129 (defun imap-mailbox-map (func &optional buffer)
1130 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1131 Function should take a mailbox name (a string) as
1133 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1135 (defun imap-current-mailbox (&optional buffer)
1136 (with-current-buffer (or buffer (current-buffer))
1137 (imap-utf7-decode imap-current-mailbox)))
1139 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1140 (and (string= mailbox imap-current-mailbox)
1142 (eq imap-state 'examine))
1144 (eq imap-state 'selected)))))
1146 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1147 (with-current-buffer (or buffer (current-buffer))
1148 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1150 (defun imap-mailbox-select-1 (mailbox &optional examine)
1151 "Select MAILBOX on server in BUFFER.
1152 If EXAMINE is non-nil, do a read-only select."
1153 (if (imap-current-mailbox-p-1 mailbox examine)
1154 imap-current-mailbox
1155 (setq imap-current-mailbox mailbox)
1156 (if (imap-ok-p (imap-send-command-wait
1157 (concat (if examine "EXAMINE" "SELECT") " \""
1160 (setq imap-message-data (make-vector imap-message-prime 0)
1161 imap-state (if examine 'examine 'selected))
1162 imap-current-mailbox)
1163 ;; Failed SELECT/EXAMINE unselects current mailbox
1164 (setq imap-current-mailbox nil))))
1166 (defun imap-mailbox-select (mailbox &optional examine buffer)
1167 (with-current-buffer (or buffer (current-buffer))
1169 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1171 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1172 (with-current-buffer (or buffer (current-buffer))
1173 (imap-mailbox-select-1 mailbox 'examine)))
1175 (defun imap-mailbox-examine (mailbox &optional buffer)
1176 "Examine MAILBOX on server in BUFFER."
1177 (imap-mailbox-select mailbox 'examine buffer))
1179 (defun imap-mailbox-unselect (&optional buffer)
1180 "Close current folder in BUFFER, without expunging articles."
1181 (with-current-buffer (or buffer (current-buffer))
1182 (when (or (eq imap-state 'auth)
1183 (and (imap-capability 'UNSELECT)
1184 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1186 (imap-send-command-wait (concat "EXAMINE \""
1187 imap-current-mailbox
1189 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1190 (setq imap-current-mailbox nil
1191 imap-message-data nil
1195 (defun imap-mailbox-expunge (&optional asynch buffer)
1196 "Expunge articles in current folder in BUFFER.
1197 If ASYNCH, do not wait for succesful completion of the command.
1198 If BUFFER is nil the current buffer is assumed."
1199 (with-current-buffer (or buffer (current-buffer))
1200 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1202 (imap-send-command "EXPUNGE")
1203 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1205 (defun imap-mailbox-close (&optional asynch buffer)
1206 "Expunge articles and close current folder in BUFFER.
1207 If ASYNCH, do not wait for succesful completion of the command.
1208 If BUFFER is nil the current buffer is assumed."
1209 (with-current-buffer (or buffer (current-buffer))
1210 (when imap-current-mailbox
1212 (imap-add-callback (imap-send-command "CLOSE")
1213 `(lambda (tag status)
1214 (message "IMAP mailbox `%s' closed... %s"
1215 imap-current-mailbox status)
1216 (when (eq ,imap-current-mailbox
1217 imap-current-mailbox)
1218 ;; Don't wipe out data if another mailbox
1220 (setq imap-current-mailbox nil
1221 imap-message-data nil
1222 imap-state 'auth))))
1223 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1224 (setq imap-current-mailbox nil
1225 imap-message-data nil
1229 (defun imap-mailbox-create-1 (mailbox)
1230 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1232 (defun imap-mailbox-create (mailbox &optional buffer)
1233 "Create MAILBOX on server in BUFFER.
1234 If BUFFER is nil the current buffer is assumed."
1235 (with-current-buffer (or buffer (current-buffer))
1236 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1238 (defun imap-mailbox-delete (mailbox &optional buffer)
1239 "Delete MAILBOX on server in BUFFER.
1240 If BUFFER is nil the current buffer is assumed."
1241 (let ((mailbox (imap-utf7-encode mailbox)))
1242 (with-current-buffer (or buffer (current-buffer))
1244 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1246 (defun imap-mailbox-rename (oldname newname &optional buffer)
1247 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1248 If BUFFER is nil the current buffer is assumed."
1249 (let ((oldname (imap-utf7-encode oldname))
1250 (newname (imap-utf7-encode newname)))
1251 (with-current-buffer (or buffer (current-buffer))
1253 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1254 "\"" newname "\""))))))
1256 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1257 "Return a list of subscribed mailboxes on server in BUFFER.
1258 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1259 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1260 implementation-specific string that has to be passed to lsub command."
1261 (with-current-buffer (or buffer (current-buffer))
1262 ;; Make sure we know the hierarchy separator for root's hierarchy
1263 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1264 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1265 (imap-utf7-encode root) "\"")))
1266 ;; clear list data (NB not delimiter and other stuff)
1267 (imap-mailbox-map-1 (lambda (mailbox)
1268 (imap-mailbox-put 'lsub nil mailbox)))
1270 (imap-send-command-wait
1271 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1272 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1275 (imap-mailbox-map-1 (lambda (mailbox)
1276 (when (imap-mailbox-get-1 'lsub mailbox)
1277 (push (imap-utf7-decode mailbox) out))))
1280 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1281 "Return a list of mailboxes matching ROOT on server in BUFFER.
1282 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1283 root. REFERENCE is a implementation-specific string that has to be
1284 passed to list command."
1285 (with-current-buffer (or buffer (current-buffer))
1286 ;; Make sure we know the hierarchy separator for root's hierarchy
1287 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1288 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1289 (imap-utf7-encode root) "\"")))
1290 ;; clear list data (NB not delimiter and other stuff)
1291 (imap-mailbox-map-1 (lambda (mailbox)
1292 (imap-mailbox-put 'list nil mailbox)))
1294 (imap-send-command-wait
1295 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1296 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1299 (imap-mailbox-map-1 (lambda (mailbox)
1300 (when (imap-mailbox-get-1 'list mailbox)
1301 (push (imap-utf7-decode mailbox) out))))
1304 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1305 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1306 Returns non-nil if successful."
1307 (with-current-buffer (or buffer (current-buffer))
1308 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1309 (imap-utf7-encode mailbox)
1312 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1313 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1314 Returns non-nil if successful."
1315 (with-current-buffer (or buffer (current-buffer))
1316 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1317 (imap-utf7-encode mailbox)
1320 (defun imap-mailbox-status (mailbox items &optional buffer)
1321 "Get status items ITEM in MAILBOX from server in BUFFER.
1322 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1323 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1324 or 'unseen. If ITEMS is a list of symbols, a list of values is
1325 returned, if ITEMS is a symbol only its value is returned."
1326 (with-current-buffer (or buffer (current-buffer))
1328 (imap-send-command-wait (list "STATUS \""
1329 (imap-utf7-encode mailbox)
1336 (mapcar (lambda (item)
1337 (imap-mailbox-get item mailbox))
1339 (imap-mailbox-get items mailbox)))))
1341 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1342 "Send status item request ITEM on MAILBOX to server in BUFFER.
1343 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1344 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1345 or 'unseen. The IMAP command tag is returned."
1346 (with-current-buffer (or buffer (current-buffer))
1347 (imap-send-command (list "STATUS \""
1348 (imap-utf7-encode mailbox)
1355 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1356 "Get ACL on mailbox from server in BUFFER."
1357 (let ((mailbox (imap-utf7-encode mailbox)))
1358 (with-current-buffer (or buffer (current-buffer))
1360 (imap-send-command-wait (list "GETACL \""
1361 (or mailbox imap-current-mailbox)
1363 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1365 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1366 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1367 (let ((mailbox (imap-utf7-encode mailbox)))
1368 (with-current-buffer (or buffer (current-buffer))
1370 (imap-send-command-wait (list "SETACL \""
1371 (or mailbox imap-current-mailbox)
1377 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1378 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1379 (let ((mailbox (imap-utf7-encode mailbox)))
1380 (with-current-buffer (or buffer (current-buffer))
1382 (imap-send-command-wait (list "DELETEACL \""
1383 (or mailbox imap-current-mailbox)
1388 ;; Message functions:
1390 (defun imap-current-message (&optional buffer)
1391 (with-current-buffer (or buffer (current-buffer))
1392 imap-current-message))
1394 (defun imap-list-to-message-set (list)
1395 (mapconcat (lambda (item)
1396 (number-to-string item))
1402 (defun imap-range-to-message-set (range)
1407 (car item) (cdr item))
1408 (format "%d" item)))
1409 (if (and (listp range) (not (listp (cdr range))))
1410 (list range) ;; make (1 . 2) into ((1 . 2))
1414 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1415 (with-current-buffer (or buffer (current-buffer))
1416 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1418 (imap-list-to-message-set uids)
1422 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1423 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1424 UIDS can be a string, number or a list of numbers. If RECEIVE
1425 is non-nil return theese properties."
1426 (with-current-buffer (or buffer (current-buffer))
1427 (when (imap-ok-p (imap-send-command-wait
1428 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1430 (imap-list-to-message-set uids)
1433 (if (or (null receive) (stringp uids))
1436 (mapcar (lambda (uid)
1438 (mapcar (lambda (prop)
1439 (imap-message-get uid prop))
1441 (imap-message-get uid receive)))
1443 (imap-message-get uids receive))))))
1445 (defun imap-message-put (uid propname value &optional buffer)
1446 (with-current-buffer (or buffer (current-buffer))
1447 (if imap-message-data
1448 (put (intern (number-to-string uid) imap-message-data)
1450 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1451 uid propname value (current-buffer)))
1454 (defun imap-message-get (uid propname &optional buffer)
1455 (with-current-buffer (or buffer (current-buffer))
1456 (get (intern-soft (number-to-string uid) imap-message-data)
1459 (defun imap-message-map (func propname &optional buffer)
1460 "Map a function across each mailbox in `imap-message-data', returning a list."
1461 (with-current-buffer (or buffer (current-buffer))
1465 (push (funcall func (get s 'UID) (get s propname)) result))
1469 (defmacro imap-message-envelope-date (uid &optional buffer)
1470 `(with-current-buffer (or ,buffer (current-buffer))
1471 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1473 (defmacro imap-message-envelope-subject (uid &optional buffer)
1474 `(with-current-buffer (or ,buffer (current-buffer))
1475 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1477 (defmacro imap-message-envelope-from (uid &optional buffer)
1478 `(with-current-buffer (or ,buffer (current-buffer))
1479 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1481 (defmacro imap-message-envelope-sender (uid &optional buffer)
1482 `(with-current-buffer (or ,buffer (current-buffer))
1483 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1485 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1486 `(with-current-buffer (or ,buffer (current-buffer))
1487 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1489 (defmacro imap-message-envelope-to (uid &optional buffer)
1490 `(with-current-buffer (or ,buffer (current-buffer))
1491 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1493 (defmacro imap-message-envelope-cc (uid &optional buffer)
1494 `(with-current-buffer (or ,buffer (current-buffer))
1495 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1497 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1498 `(with-current-buffer (or ,buffer (current-buffer))
1499 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1501 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1502 `(with-current-buffer (or ,buffer (current-buffer))
1503 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1505 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1506 `(with-current-buffer (or ,buffer (current-buffer))
1507 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1509 (defmacro imap-message-body (uid &optional buffer)
1510 `(with-current-buffer (or ,buffer (current-buffer))
1511 (imap-message-get ,uid 'BODY)))
1513 (defun imap-search (predicate &optional buffer)
1514 (with-current-buffer (or buffer (current-buffer))
1515 (imap-mailbox-put 'search 'dummy)
1516 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1517 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1519 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1521 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1523 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1524 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1525 (with-current-buffer (or buffer (current-buffer))
1526 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1527 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1529 (defun imap-message-flags-set (articles flags &optional silent buffer)
1530 (when (and articles flags)
1531 (with-current-buffer (or buffer (current-buffer))
1532 (imap-ok-p (imap-send-command-wait
1533 (concat "UID STORE " articles
1534 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1536 (defun imap-message-flags-del (articles flags &optional silent buffer)
1537 (when (and articles flags)
1538 (with-current-buffer (or buffer (current-buffer))
1539 (imap-ok-p (imap-send-command-wait
1540 (concat "UID STORE " articles
1541 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1543 (defun imap-message-flags-add (articles flags &optional silent buffer)
1544 (when (and articles flags)
1545 (with-current-buffer (or buffer (current-buffer))
1546 (imap-ok-p (imap-send-command-wait
1547 (concat "UID STORE " articles
1548 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1550 (defun imap-message-copyuid-1 (mailbox)
1551 (if (imap-capability 'UIDPLUS)
1552 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1553 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1554 (let ((old-mailbox imap-current-mailbox)
1556 (imap-message-data (make-vector 2 0)))
1557 (when (imap-mailbox-examine-1 mailbox)
1559 (and (imap-fetch "*" "UID")
1560 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1561 (apply 'max (imap-message-map
1562 (lambda (uid prop) uid) 'UID))))
1564 (imap-mailbox-select old-mailbox (eq state 'examine))
1565 (imap-mailbox-unselect)))))))
1567 (defun imap-message-copyuid (mailbox &optional buffer)
1568 (with-current-buffer (or buffer (current-buffer))
1569 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1571 (defun imap-message-copy (articles mailbox
1572 &optional dont-create no-copyuid buffer)
1573 "Copy ARTICLES (a string message set) to MAILBOX on server in
1574 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1575 non-nil, it will not create a mailbox. On success, return a list with
1576 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1577 first element, rest of list contain the saved articles' UIDs."
1579 (with-current-buffer (or buffer (current-buffer))
1580 (let ((mailbox (imap-utf7-encode mailbox)))
1581 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1582 (imap-current-target-mailbox mailbox))
1583 (if (imap-ok-p (imap-send-command-wait cmd))
1585 (when (and (not dont-create)
1586 ;; removed because of buggy Oracle server
1587 ;; that doesn't send TRYCREATE tags (which
1588 ;; is a MUST according to specifications):
1589 ;;(imap-mailbox-get-1 'trycreate mailbox)
1590 (imap-mailbox-create-1 mailbox))
1591 (imap-ok-p (imap-send-command-wait cmd)))))
1593 (imap-message-copyuid-1 mailbox)))))))
1595 (defun imap-message-appenduid-1 (mailbox)
1596 (if (imap-capability 'UIDPLUS)
1597 (imap-mailbox-get-1 'appenduid mailbox)
1598 (let ((old-mailbox imap-current-mailbox)
1600 (imap-message-data (make-vector 2 0)))
1601 (when (imap-mailbox-examine-1 mailbox)
1603 (and (imap-fetch "*" "UID")
1604 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1605 (apply 'max (imap-message-map
1606 (lambda (uid prop) uid) 'UID))))
1608 (imap-mailbox-select old-mailbox (eq state 'examine))
1609 (imap-mailbox-unselect)))))))
1611 (defun imap-message-appenduid (mailbox &optional buffer)
1612 (with-current-buffer (or buffer (current-buffer))
1613 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1615 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1616 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1617 FLAGS and DATE-TIME is currently not used. Return a cons holding
1618 uidvalidity of MAILBOX and UID the newly created article got, or nil
1620 (let ((mailbox (imap-utf7-encode mailbox)))
1621 (with-current-buffer (or buffer (current-buffer))
1622 (and (let ((imap-current-target-mailbox mailbox))
1624 (imap-send-command-wait
1625 (list "APPEND \"" mailbox "\" " article))))
1626 (imap-message-appenduid-1 mailbox)))))
1628 (defun imap-body-lines (body)
1629 "Return number of lines in article by looking at the mime bodystructure BODY."
1631 (if (stringp (car body))
1632 (cond ((and (string= (upcase (car body)) "TEXT")
1633 (numberp (nth 7 body)))
1635 ((and (string= (upcase (car body)) "MESSAGE")
1636 (numberp (nth 9 body)))
1639 (apply '+ (mapcar 'imap-body-lines body)))
1642 (defun imap-envelope-from (from)
1643 "Return a from string line."
1645 (concat (aref from 0)
1646 (if (aref from 0) " <")
1650 (if (aref from 0) ">"))))
1653 ;; Internal functions.
1655 (defun imap-add-callback (tag func)
1656 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1658 (defun imap-send-command-1 (cmdstr)
1659 (setq cmdstr (concat cmdstr imap-client-eol))
1661 (with-current-buffer (get-buffer-create imap-log-buffer)
1662 (imap-disable-multibyte)
1663 (buffer-disable-undo)
1664 (goto-char (point-max))
1666 (process-send-string imap-process cmdstr))
1668 (defun imap-send-command (command &optional buffer)
1669 (with-current-buffer (or buffer (current-buffer))
1670 (if (not (listp command)) (setq command (list command)))
1671 (let ((tag (setq imap-tag (1+ imap-tag)))
1673 (setq cmdstr (concat (number-to-string imap-tag) " "))
1674 (while (setq cmd (pop command))
1675 (cond ((stringp cmd)
1676 (setq cmdstr (concat cmdstr cmd)))
1678 (let ((eol imap-client-eol)
1679 (calcfirst imap-calculate-literal-size-first)
1681 (with-current-buffer cmd
1683 (setq size (buffer-size)))
1684 (when (not (equal eol "\r\n"))
1685 ;; XXX modifies buffer!
1686 (goto-char (point-min))
1687 (while (search-forward "\r\n" nil t)
1688 (replace-match eol)))
1690 (setq size (buffer-size))))
1692 (concat cmdstr (format "{%d}" size))))
1695 (imap-send-command-1 cmdstr)
1697 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1698 (setq command nil) ;; abort command if no cont-req
1699 (let ((process imap-process)
1700 (stream imap-stream)
1701 (eol imap-client-eol))
1702 (with-current-buffer cmd
1704 (with-current-buffer (get-buffer-create
1706 (imap-disable-multibyte)
1707 (buffer-disable-undo)
1708 (goto-char (point-max))
1709 (insert-buffer-substring cmd)))
1710 (process-send-region process (point-min)
1712 (process-send-string process imap-client-eol))))
1713 (setq imap-continuation nil)))
1715 (imap-send-command-1 cmdstr)
1718 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1719 (setq command nil) ;; abort command if no cont-req
1720 (setq command (cons (funcall cmd imap-continuation)
1722 (setq imap-continuation nil)))
1724 (error "Unknown command type"))))
1726 (imap-send-command-1 cmdstr))
1729 (defun imap-wait-for-tag (tag &optional buffer)
1730 (with-current-buffer (or buffer (current-buffer))
1731 (let (imap-have-messaged)
1732 (while (and (null imap-continuation)
1733 (memq (process-status imap-process) '(open run))
1734 (< imap-reached-tag tag))
1735 (let ((len (/ (point-max) 1024))
1738 (setq imap-have-messaged t)
1739 (message "imap read: %dk" len))
1740 (accept-process-output imap-process 1)))
1741 (when imap-have-messaged
1743 (and (memq (process-status imap-process) '(open run))
1744 (or (assq tag imap-failed-tags)
1745 (if imap-continuation
1749 (defun imap-sentinel (process string)
1750 (delete-process process))
1752 (defun imap-find-next-line ()
1753 "Return point at end of current line, taking into account literals.
1754 Return nil if no complete line has arrived."
1755 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1758 (if (match-string 1)
1759 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1761 (goto-char (+ (point) (string-to-number (match-string 1))))
1762 (imap-find-next-line))
1765 (defun imap-arrival-filter (proc string)
1766 "IMAP process filter."
1767 (with-current-buffer (process-buffer proc)
1768 (goto-char (point-max))
1771 (with-current-buffer (get-buffer-create imap-log-buffer)
1772 (imap-disable-multibyte)
1773 (buffer-disable-undo)
1774 (goto-char (point-max))
1777 (goto-char (point-min))
1778 (while (setq end (imap-find-next-line))
1780 (narrow-to-region (point-min) end)
1781 (delete-backward-char (length imap-server-eol))
1782 (goto-char (point-min))
1784 (cond ((eq imap-state 'initial)
1785 (imap-parse-greeting))
1786 ((or (eq imap-state 'auth)
1787 (eq imap-state 'nonauth)
1788 (eq imap-state 'selected)
1789 (eq imap-state 'examine))
1790 (imap-parse-response))
1792 (message "Unknown state %s in arrival filter"
1794 (delete-region (point-min) (point-max))))))))
1799 (defsubst imap-forward ()
1800 (or (eobp) (forward-char)))
1803 ;; ; Unsigned 32-bit integer
1804 ;; ; (0 <= n < 4,294,967,296)
1806 (defsubst imap-parse-number ()
1807 (when (looking-at "[0-9]+")
1809 (string-to-number (match-string 0))
1810 (goto-char (match-end 0)))))
1812 ;; literal = "{" number "}" CRLF *CHAR8
1813 ;; ; Number represents the number of CHAR8s
1815 (defsubst imap-parse-literal ()
1816 (when (looking-at "{\\([0-9]+\\)}\r\n")
1817 (let ((pos (match-end 0))
1818 (len (string-to-number (match-string 1))))
1819 (if (< (point-max) (+ pos len))
1821 (goto-char (+ pos len))
1822 (buffer-substring pos (+ pos len))))))
1824 ;; string = quoted / literal
1826 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1828 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1829 ;; "\" quoted-specials
1831 ;; quoted-specials = DQUOTE / "\"
1833 ;; TEXT-CHAR = <any CHAR except CR and LF>
1835 (defsubst imap-parse-string ()
1836 (cond ((eq (char-after) ?\")
1838 (let ((p (point)) (name ""))
1839 (skip-chars-forward "^\"\\\\")
1840 (setq name (buffer-substring p (point)))
1841 (while (eq (char-after) ?\\)
1842 (setq p (1+ (point)))
1844 (skip-chars-forward "^\"\\\\")
1845 (setq name (concat name (buffer-substring p (point)))))
1848 ((eq (char-after) ?{)
1849 (imap-parse-literal))))
1853 (defsubst imap-parse-nil ()
1854 (if (looking-at "NIL")
1855 (goto-char (match-end 0))))
1857 ;; nstring = string / nil
1859 (defsubst imap-parse-nstring ()
1860 (or (imap-parse-string)
1861 (and (imap-parse-nil)
1864 ;; astring = atom / string
1866 ;; atom = 1*ATOM-CHAR
1868 ;; ATOM-CHAR = <any CHAR except atom-specials>
1870 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1873 ;; list-wildcards = "%" / "*"
1875 ;; quoted-specials = DQUOTE / "\"
1877 (defsubst imap-parse-astring ()
1878 (or (imap-parse-string)
1879 (buffer-substring (point)
1880 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1881 (goto-char (1- (match-end 0)))
1885 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1888 ;; addr-adl = nstring
1889 ;; ; Holds route from [RFC-822] route-addr if
1892 ;; addr-host = nstring
1893 ;; ; nil indicates [RFC-822] group syntax.
1894 ;; ; Otherwise, holds [RFC-822] domain name
1896 ;; addr-mailbox = nstring
1897 ;; ; nil indicates end of [RFC-822] group; if
1898 ;; ; non-nil and addr-host is nil, holds
1899 ;; ; [RFC-822] group name.
1900 ;; ; Otherwise, holds [RFC-822] local-part
1901 ;; ; after removing [RFC-822] quoting
1903 ;; addr-name = nstring
1904 ;; ; If non-nil, holds phrase from [RFC-822]
1905 ;; ; mailbox after removing [RFC-822] quoting
1908 (defsubst imap-parse-address ()
1910 (when (eq (char-after) ?\()
1912 (setq address (vector (prog1 (imap-parse-nstring)
1914 (prog1 (imap-parse-nstring)
1916 (prog1 (imap-parse-nstring)
1918 (imap-parse-nstring)))
1919 (when (eq (char-after) ?\))
1923 ;; address-list = "(" 1*address ")" / nil
1927 (defsubst imap-parse-address-list ()
1928 (if (eq (char-after) ?\()
1929 (let (address addresses)
1931 (while (and (not (eq (char-after) ?\)))
1932 ;; next line for MS Exchange bug
1933 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1934 (setq address (imap-parse-address)))
1935 (setq addresses (cons address addresses)))
1936 (when (eq (char-after) ?\))
1938 (nreverse addresses)))
1939 (assert (imap-parse-nil) t "In imap-parse-address-list")))
1941 ;; mailbox = "INBOX" / astring
1942 ;; ; INBOX is case-insensitive. All case variants of
1943 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1944 ;; ; not as an astring. An astring which consists of
1945 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1946 ;; ; is considered to be INBOX and not an astring.
1947 ;; ; Refer to section 5.1 for further
1948 ;; ; semantic details of mailbox names.
1950 (defsubst imap-parse-mailbox ()
1951 (let ((mailbox (imap-parse-astring)))
1952 (if (string-equal "INBOX" (upcase mailbox))
1956 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1958 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1959 ;; ; Authentication condition
1961 ;; resp-cond-bye = "BYE" SP resp-text
1963 (defun imap-parse-greeting ()
1964 "Parse a IMAP greeting."
1965 (cond ((looking-at "\\* OK ")
1966 (setq imap-state 'nonauth))
1967 ((looking-at "\\* PREAUTH ")
1968 (setq imap-state 'auth))
1969 ((looking-at "\\* BYE ")
1970 (setq imap-state 'closed))))
1972 ;; response = *(continue-req / response-data) response-done
1974 ;; continue-req = "+" SP (resp-text / base64) CRLF
1976 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1977 ;; mailbox-data / message-data / capability-data) CRLF
1979 ;; response-done = response-tagged / response-fatal
1981 ;; response-fatal = "*" SP resp-cond-bye CRLF
1982 ;; ; Server closes connection immediately
1984 ;; response-tagged = tag SP resp-cond-state CRLF
1986 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1987 ;; ; Status condition
1989 ;; resp-cond-bye = "BYE" SP resp-text
1991 ;; mailbox-data = "FLAGS" SP flag-list /
1992 ;; "LIST" SP mailbox-list /
1993 ;; "LSUB" SP mailbox-list /
1994 ;; "SEARCH" *(SP nz-number) /
1995 ;; "STATUS" SP mailbox SP "("
1996 ;; [status-att SP number *(SP status-att SP number)] ")" /
1997 ;; number SP "EXISTS" /
1998 ;; number SP "RECENT"
2000 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2002 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2004 ;; ; IMAP4rev1 servers which offer RFC 1730
2005 ;; ; compatibility MUST list "IMAP4" as the first
2008 (defun imap-parse-response ()
2009 "Parse a IMAP command response."
2011 (case (setq token (read (current-buffer)))
2012 (+ (setq imap-continuation
2013 (or (buffer-substring (min (point-max) (1+ (point)))
2016 (* (case (prog1 (setq token (read (current-buffer)))
2018 (OK (imap-parse-resp-text))
2019 (NO (imap-parse-resp-text))
2020 (BAD (imap-parse-resp-text))
2021 (BYE (imap-parse-resp-text))
2022 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
2023 (LIST (imap-parse-data-list 'list))
2024 (LSUB (imap-parse-data-list 'lsub))
2025 (SEARCH (imap-mailbox-put
2027 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2028 (STATUS (imap-parse-status))
2029 (CAPABILITY (setq imap-capability
2030 (read (concat "(" (upcase (buffer-substring
2031 (point) (point-max)))
2033 (ACL (imap-parse-acl))
2034 (t (case (prog1 (read (current-buffer))
2036 (EXISTS (imap-mailbox-put 'exists token))
2037 (RECENT (imap-mailbox-put 'recent token))
2039 (FETCH (imap-parse-fetch token))
2040 (t (message "Garbage: %s" (buffer-string)))))))
2042 (if (not (integerp token))
2043 (message "Garbage: %s" (buffer-string))
2044 (case (prog1 (setq status (read (current-buffer)))
2047 (setq imap-reached-tag (max imap-reached-tag token))
2048 (imap-parse-resp-text)))
2050 (setq imap-reached-tag (max imap-reached-tag token))
2052 (imap-parse-resp-text))
2054 (when (eq (char-after) ?\[)
2055 (setq code (buffer-substring (point)
2056 (search-forward "]")))
2058 (setq text (buffer-substring (point) (point-max)))
2059 (push (list token status code text)
2060 imap-failed-tags))))
2062 (setq imap-reached-tag (max imap-reached-tag token))
2064 (imap-parse-resp-text))
2066 (when (eq (char-after) ?\[)
2067 (setq code (buffer-substring (point)
2068 (search-forward "]")))
2070 (setq text (buffer-substring (point) (point-max)))
2071 (push (list token status code text) imap-failed-tags)
2072 (error "Internal error, tag %s status %s code %s text %s"
2073 token status code text))))
2074 (t (message "Garbage: %s" (buffer-string))))
2075 (when (assq token imap-callbacks)
2076 (funcall (cdr (assq token imap-callbacks)) token status)
2077 (setq imap-callbacks
2078 (imap-remassoc token imap-callbacks)))))))))
2080 ;; resp-text = ["[" resp-text-code "]" SP] text
2082 ;; text = 1*TEXT-CHAR
2084 ;; TEXT-CHAR = <any CHAR except CR and LF>
2086 (defun imap-parse-resp-text ()
2087 (imap-parse-resp-text-code))
2089 ;; resp-text-code = "ALERT" /
2090 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2091 ;; "NEWNAME" SP string SP string /
2093 ;; "PERMANENTFLAGS" SP "("
2094 ;; [flag-perm *(SP flag-perm)] ")" /
2098 ;; "UIDNEXT" SP nz-number /
2099 ;; "UIDVALIDITY" SP nz-number /
2100 ;; "UNSEEN" SP nz-number /
2101 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2103 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2105 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2107 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2109 ;; ; Identifies a set of messages. For message
2110 ;; ; sequence numbers, these are consecutive
2111 ;; ; numbers from 1 to the number of messages in
2113 ;; ; Comma delimits individual numbers, colon
2114 ;; ; delimits between two numbers inclusive.
2115 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2116 ;; ; 14,15 for a mailbox with 15 messages.
2118 ;; sequence-num = nz-number / "*"
2119 ;; ; * is the largest number in use. For message
2120 ;; ; sequence numbers, it is the number of messages
2121 ;; ; in the mailbox. For unique identifiers, it is
2122 ;; ; the unique identifier of the last message in
2125 ;; flag-perm = flag / "\*"
2127 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2128 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2129 ;; ; Does not include "\Recent"
2131 ;; flag-extension = "\" atom
2132 ;; ; Future expansion. Client implementations
2133 ;; ; MUST accept flag-extension flags. Server
2134 ;; ; implementations MUST NOT generate
2135 ;; ; flag-extension flags except as defined by
2136 ;; ; future standard or standards-track
2137 ;; ; revisions of this specification.
2139 ;; flag-keyword = atom
2141 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2143 (defun imap-parse-resp-text-code ()
2144 ;; xxx next line for stalker communigate pro 3.3.1 bug
2145 (when (looking-at " \\[")
2147 (when (eq (char-after) ?\[)
2149 (cond ((search-forward "PERMANENTFLAGS " nil t)
2150 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2151 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2152 (imap-mailbox-put 'uidnext (match-string 1)))
2153 ((search-forward "UNSEEN " nil t)
2154 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2155 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2156 (imap-mailbox-put 'uidvalidity (match-string 1)))
2157 ((search-forward "READ-ONLY" nil t)
2158 (imap-mailbox-put 'read-only t))
2159 ((search-forward "NEWNAME " nil t)
2160 (let (oldname newname)
2161 (setq oldname (imap-parse-string))
2163 (setq newname (imap-parse-string))
2164 (imap-mailbox-put 'newname newname oldname)))
2165 ((search-forward "TRYCREATE" nil t)
2166 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2167 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2168 (imap-mailbox-put 'appenduid
2169 (list (match-string 1)
2170 (string-to-number (match-string 2)))
2171 imap-current-target-mailbox))
2172 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2173 (imap-mailbox-put 'copyuid (list (match-string 1)
2176 imap-current-target-mailbox))
2177 ((search-forward "ALERT] " nil t)
2178 (message "Imap server %s information: %s" imap-server
2179 (buffer-substring (point) (point-max)))))))
2181 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2182 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2184 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2185 ;; *(SP mbx-list-oflag) /
2186 ;; mbx-list-oflag *(SP mbx-list-oflag)
2188 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2189 ;; ; Other flags; multiple possible per LIST response
2191 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2192 ;; ; Selectability flags; only one per LIST response
2194 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2195 ;; "\" quoted-specials
2197 ;; quoted-specials = DQUOTE / "\"
2199 (defun imap-parse-data-list (type)
2200 (let (flags delimiter mailbox)
2201 (setq flags (imap-parse-flag-list))
2202 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2203 (setq delimiter (match-string 1))
2204 (goto-char (1+ (match-end 0)))
2205 (when (setq mailbox (imap-parse-mailbox))
2206 (imap-mailbox-put type t mailbox)
2207 (imap-mailbox-put 'list-flags flags mailbox)
2208 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2210 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2211 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2212 ;; "INTERNALDATE" SPACE date_time /
2213 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2214 ;; "RFC822.SIZE" SPACE number /
2215 ;; "BODY" ["STRUCTURE"] SPACE body /
2216 ;; "BODY" section ["<" number ">"] SPACE nstring /
2217 ;; "UID" SPACE uniqueid) ")"
2219 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2220 ;; SPACE time SPACE zone <">
2222 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2223 ;; ["." (section_text / "MIME")])] "]"
2225 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2226 ;; SPACE header_list / "TEXT"
2228 ;; header_fld_name ::= astring
2230 ;; header_list ::= "(" 1#header_fld_name ")"
2232 (defsubst imap-parse-header-list ()
2233 (when (eq (char-after) ?\()
2235 (while (not (eq (char-after) ?\)))
2237 (push (imap-parse-astring) strlist))
2239 (nreverse strlist))))
2241 (defsubst imap-parse-fetch-body-section ()
2243 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2244 (if (eq (char-before) ? )
2246 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2247 (search-forward "]" nil t))
2250 (defun imap-parse-fetch (response)
2251 (when (eq (char-after) ?\()
2252 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2253 rfc822size body bodydetail bodystructure flags-empty)
2254 (while (not (eq (char-after) ?\)))
2256 (let ((token (read (current-buffer))))
2258 (cond ((eq token 'UID)
2259 (setq uid (condition-case ()
2260 (read (current-buffer))
2263 (setq flags (imap-parse-flag-list))
2265 (setq flags-empty 't)))
2266 ((eq token 'ENVELOPE)
2267 (setq envelope (imap-parse-envelope)))
2268 ((eq token 'INTERNALDATE)
2269 (setq internaldate (imap-parse-string)))
2271 (setq rfc822 (imap-parse-nstring)))
2272 ((eq token 'RFC822.HEADER)
2273 (setq rfc822header (imap-parse-nstring)))
2274 ((eq token 'RFC822.TEXT)
2275 (setq rfc822text (imap-parse-nstring)))
2276 ((eq token 'RFC822.SIZE)
2277 (setq rfc822size (read (current-buffer))))
2279 (if (eq (char-before) ?\[)
2281 (upcase (imap-parse-fetch-body-section))
2282 (and (eq (char-after) ?<)
2283 (buffer-substring (1+ (point))
2284 (search-forward ">" nil t)))
2285 (progn (imap-forward)
2286 (imap-parse-nstring)))
2288 (setq body (imap-parse-body))))
2289 ((eq token 'BODYSTRUCTURE)
2290 (setq bodystructure (imap-parse-body))))))
2292 (setq imap-current-message uid)
2293 (imap-message-put uid 'UID uid)
2294 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2295 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2296 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2297 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2298 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2299 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2300 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2301 (and body (imap-message-put uid 'BODY body))
2302 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2303 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2304 (run-hooks 'imap-fetch-data-hook)))))
2306 ;; mailbox-data = ...
2307 ;; "STATUS" SP mailbox SP "("
2308 ;; [status-att SP number
2309 ;; *(SP status-att SP number)] ")"
2312 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2315 (defun imap-parse-status ()
2316 (let ((mailbox (imap-parse-mailbox)))
2317 (if (eq (char-after) ? )
2319 (when (and mailbox (eq (char-after) ?\())
2320 (while (and (not (eq (char-after) ?\)))
2321 (or (forward-char) t)
2322 (looking-at "\\([A-Za-z]+\\) "))
2323 (let ((token (match-string 1)))
2324 (goto-char (match-end 0))
2325 (cond ((string= token "MESSAGES")
2326 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2327 ((string= token "RECENT")
2328 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2329 ((string= token "UIDNEXT")
2330 (and (looking-at "[0-9]+")
2331 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2332 (goto-char (match-end 0))))
2333 ((string= token "UIDVALIDITY")
2334 (and (looking-at "[0-9]+")
2335 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2336 (goto-char (match-end 0))))
2337 ((string= token "UNSEEN")
2338 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2340 (message "Unknown status data %s in mailbox %s ignored"
2342 (read (current-buffer)))))))))
2344 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2347 ;; identifier ::= astring
2349 ;; rights ::= astring
2351 (defun imap-parse-acl ()
2352 (let ((mailbox (imap-parse-mailbox))
2353 identifier rights acl)
2354 (while (eq (char-after) ?\ )
2356 (setq identifier (imap-parse-astring))
2358 (setq rights (imap-parse-astring))
2359 (setq acl (append acl (list (cons identifier rights)))))
2360 (imap-mailbox-put 'acl acl mailbox)))
2362 ;; flag-list = "(" [flag *(SP flag)] ")"
2364 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2365 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2366 ;; ; Does not include "\Recent"
2368 ;; flag-keyword = atom
2370 ;; flag-extension = "\" atom
2371 ;; ; Future expansion. Client implementations
2372 ;; ; MUST accept flag-extension flags. Server
2373 ;; ; implementations MUST NOT generate
2374 ;; ; flag-extension flags except as defined by
2375 ;; ; future standard or standards-track
2376 ;; ; revisions of this specification.
2378 (defun imap-parse-flag-list ()
2379 (let (flag-list start)
2380 (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2381 (while (and (not (eq (char-after) ?\)))
2384 ;; next line for Courier IMAP bug.
2385 (skip-chars-forward " ")
2387 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2388 (push (buffer-substring start (point)) flag-list))
2389 (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2391 (nreverse flag-list)))
2393 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2394 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2395 ;; env-in-reply-to SP env-message-id ")"
2397 ;; env-bcc = "(" 1*address ")" / nil
2399 ;; env-cc = "(" 1*address ")" / nil
2401 ;; env-date = nstring
2403 ;; env-from = "(" 1*address ")" / nil
2405 ;; env-in-reply-to = nstring
2407 ;; env-message-id = nstring
2409 ;; env-reply-to = "(" 1*address ")" / nil
2411 ;; env-sender = "(" 1*address ")" / nil
2413 ;; env-subject = nstring
2415 ;; env-to = "(" 1*address ")" / nil
2417 (defun imap-parse-envelope ()
2418 (when (eq (char-after) ?\()
2420 (vector (prog1 (imap-parse-nstring) ;; date
2422 (prog1 (imap-parse-nstring) ;; subject
2424 (prog1 (imap-parse-address-list) ;; from
2426 (prog1 (imap-parse-address-list) ;; sender
2428 (prog1 (imap-parse-address-list) ;; reply-to
2430 (prog1 (imap-parse-address-list) ;; to
2432 (prog1 (imap-parse-address-list) ;; cc
2434 (prog1 (imap-parse-address-list) ;; bcc
2436 (prog1 (imap-parse-nstring) ;; in-reply-to
2438 (prog1 (imap-parse-nstring) ;; message-id
2441 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2443 (defsubst imap-parse-string-list ()
2444 (cond ((eq (char-after) ?\() ;; body-fld-param
2447 (while (setq str (imap-parse-string))
2449 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2450 ;; between body-fld-param's sometimes
2451 (or (eq (char-after) ?\")
2453 (nreverse strlist)))
2457 ;; body-extension = nstring / number /
2458 ;; "(" body-extension *(SP body-extension) ")"
2459 ;; ; Future expansion. Client implementations
2460 ;; ; MUST accept body-extension fields. Server
2461 ;; ; implementations MUST NOT generate
2462 ;; ; body-extension fields except as defined by
2463 ;; ; future standard or standards-track
2464 ;; ; revisions of this specification.
2466 (defun imap-parse-body-extension ()
2467 (if (eq (char-after) ?\()
2470 (push (imap-parse-body-extension) b-e)
2471 (while (eq (char-after) ?\ )
2473 (push (imap-parse-body-extension) b-e))
2474 (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2477 (or (imap-parse-number)
2478 (imap-parse-nstring))))
2480 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2481 ;; *(SP body-extension)]]
2482 ;; ; MUST NOT be returned on non-extensible
2485 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2486 ;; *(SP body-extension)]]
2487 ;; ; MUST NOT be returned on non-extensible
2490 (defsubst imap-parse-body-ext ()
2492 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2495 (if (eq (char-after) ?\()
2498 (push (imap-parse-string) dsp)
2500 (push (imap-parse-string-list) dsp)
2502 (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2503 (push (nreverse dsp) ext))
2504 (when (eq (char-after) ?\ ) ;; body-fld-lang
2506 (if (eq (char-after) ?\()
2507 (push (imap-parse-string-list) ext)
2508 (push (imap-parse-nstring) ext))
2509 (while (eq (char-after) ?\ ) ;; body-extension
2511 (setq ext (append (imap-parse-body-extension) ext)))))
2514 ;; body = "(" body-type-1part / body-type-mpart ")"
2516 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2517 ;; *(SP body-extension)]]
2518 ;; ; MUST NOT be returned on non-extensible
2521 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2522 ;; *(SP body-extension)]]
2523 ;; ; MUST NOT be returned on non-extensible
2526 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2527 ;; body-fld-enc SP body-fld-octets
2529 ;; body-fld-desc = nstring
2531 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2533 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2534 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2536 ;; body-fld-id = nstring
2538 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2540 ;; body-fld-lines = number
2542 ;; body-fld-md5 = nstring
2544 ;; body-fld-octets = number
2546 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2548 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2549 ;; [SP body-ext-1part]
2551 ;; body-type-basic = media-basic SP body-fields
2552 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2554 ;; body-type-msg = media-message SP body-fields SP envelope
2555 ;; SP body SP body-fld-lines
2557 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2559 ;; body-type-mpart = 1*body SP media-subtype
2560 ;; [SP body-ext-mpart]
2562 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2563 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2564 ;; ; Defined in [MIME-IMT]
2566 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2567 ;; ; Defined in [MIME-IMT]
2569 ;; media-subtype = string
2570 ;; ; Defined in [MIME-IMT]
2572 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2573 ;; ; Defined in [MIME-IMT]
2575 (defun imap-parse-body ()
2577 (when (eq (char-after) ?\()
2579 (if (eq (char-after) ?\()
2581 (while (and (eq (char-after) ?\()
2582 (setq subbody (imap-parse-body)))
2583 ;; buggy stalker communigate pro 3.0 insert a SPC between
2584 ;; parts in multiparts
2585 (when (and (eq (char-after) ?\ )
2586 (eq (char-after (1+ (point))) ?\())
2588 (push subbody body))
2590 (push (imap-parse-string) body) ;; media-subtype
2591 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2593 (if (eq (char-after) ?\() ;; body-fld-param
2594 (push (imap-parse-string-list) body)
2595 (push (and (imap-parse-nil) nil) body))
2597 (append (imap-parse-body-ext) body))) ;; body-ext-...
2598 (assert (eq (char-after) ?\)) t "In imap-parse-body")
2602 (push (imap-parse-string) body) ;; media-type
2604 (push (imap-parse-string) body) ;; media-subtype
2606 ;; next line for Sun SIMS bug
2607 (and (eq (char-after) ? ) (imap-forward))
2608 (if (eq (char-after) ?\() ;; body-fld-param
2609 (push (imap-parse-string-list) body)
2610 (push (and (imap-parse-nil) nil) body))
2612 (push (imap-parse-nstring) body) ;; body-fld-id
2614 (push (imap-parse-nstring) body) ;; body-fld-desc
2616 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2617 ;; nstring and return nil instead of defaulting back to 7BIT
2618 ;; as the standard says.
2619 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2621 (push (imap-parse-number) body) ;; body-fld-octets
2623 ;; ok, we're done parsing the required parts, what comes now is one
2626 ;; envelope (then we're parsing body-type-msg)
2627 ;; body-fld-lines (then we're parsing body-type-text)
2628 ;; body-ext-1part (then we're parsing body-type-basic)
2630 ;; the problem is that the two first are in turn optionally followed
2631 ;; by the third. So we parse the first two here (if there are any)...
2633 (when (eq (char-after) ?\ )
2636 (cond ((eq (char-after) ?\() ;; body-type-msg:
2637 (push (imap-parse-envelope) body) ;; envelope
2639 (push (imap-parse-body) body) ;; body
2640 ;; buggy stalker communigate pro 3.0 doesn't print
2641 ;; number of lines in message/rfc822 attachment
2642 (if (eq (char-after) ?\))
2645 (push (imap-parse-number) body))) ;; body-fld-lines
2646 ((setq lines (imap-parse-number)) ;; body-type-text:
2647 (push lines body)) ;; body-fld-lines
2649 (backward-char))))) ;; no match...
2651 ;; ...and then parse the third one here...
2653 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2655 (push (imap-parse-nstring) body) ;; body-fld-md5
2656 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2658 (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2662 (when imap-debug ; (untrace-all)
2664 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2665 (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2676 imap-interactive-login
2692 imap-send-command-wait
2697 imap-current-mailbox
2698 imap-current-mailbox-p-1
2699 imap-current-mailbox-p
2700 imap-mailbox-select-1
2702 imap-mailbox-examine-1
2703 imap-mailbox-examine
2704 imap-mailbox-unselect
2705 imap-mailbox-expunge
2707 imap-mailbox-create-1
2713 imap-mailbox-subscribe
2714 imap-mailbox-unsubscribe
2716 imap-mailbox-acl-get
2717 imap-mailbox-acl-set
2718 imap-mailbox-acl-delete
2719 imap-current-message
2720 imap-list-to-message-set
2727 imap-message-flag-permanent-p
2728 imap-message-flags-set
2729 imap-message-flags-del
2730 imap-message-flags-add
2731 imap-message-copyuid-1
2732 imap-message-copyuid
2734 imap-message-appenduid-1
2735 imap-message-appenduid
2747 imap-parse-resp-text
2748 imap-parse-resp-text-code
2749 imap-parse-data-list
2753 imap-parse-flag-list
2755 imap-parse-body-extension
2761 ;;; imap.el ends here