1 ;;; imap.el --- imap library
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
6 ;; Author: Simon Josefsson <simon@josefsson.org>
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; imap.el is an elisp library providing an interface for talking to
29 ;; imap.el is roughly divided in two parts, one that parses IMAP
30 ;; responses from the server and storing data into buffer-local
31 ;; variables, and one for utility functions which send commands to
32 ;; server, waits for an answer, and return information. The latter
33 ;; part is layered on top of the previous.
35 ;; The imap.el API consist of the following functions, other functions
36 ;; in this file should not be called directly and the result of doing
37 ;; so are at best undefined.
41 ;; imap-open, imap-opened, imap-authenticate, imap-close,
42 ;; imap-capability, imap-namespace, imap-error-text
46 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
47 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
48 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
49 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
50 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
51 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
52 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
56 ;; imap-fetch-asynch, imap-fetch,
57 ;; imap-current-message, imap-list-to-message-set,
58 ;; imap-message-get, imap-message-map
59 ;; imap-message-envelope-date, imap-message-envelope-subject,
60 ;; imap-message-envelope-from, imap-message-envelope-sender,
61 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
62 ;; imap-message-envelope-cc, imap-message-envelope-bcc
63 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
64 ;; imap-message-body, imap-message-flag-permanent-p
65 ;; imap-message-flags-set, imap-message-flags-del
66 ;; imap-message-flags-add, imap-message-copyuid
67 ;; imap-message-copy, imap-message-appenduid
68 ;; imap-message-append, imap-envelope-from
71 ;; It is my hope that these commands should be pretty self
72 ;; explanatory for someone that know IMAP. All functions have
73 ;; additional documentation on how to invoke them.
75 ;; imap.el supports RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1). The implemented
76 ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
77 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
78 ;; LOGINDISABLED) (with use of external library starttls.el and
79 ;; program starttls), and the GSSAPI / Kerberos V4 sections of RFC1731
80 ;; (with use of external program `imtest'), and RFC2971 (ID). It also
81 ;; takes advantage of the UNSELECT extension in Cyrus IMAPD.
83 ;; Without the work of John McClary Prevost and Jim Radford this library
84 ;; would not have seen the light of day. Many thanks.
86 ;; This is a transcript of a short interactive session for demonstration
89 ;; (imap-open "my.mail.server")
90 ;; => " *imap* my.mail.server:0"
92 ;; The rest are invoked with current buffer as the buffer returned by
93 ;; `imap-open'. It is possible to do it all without this, but it would
94 ;; look ugly here since `buffer' is always the last argument for all
95 ;; imap.el API functions.
97 ;; (imap-authenticate "myusername" "mypassword")
100 ;; (imap-mailbox-lsub "*")
101 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
103 ;; (imap-mailbox-list "INBOX.n%")
104 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
106 ;; (imap-mailbox-select "INBOX.nnimap")
109 ;; (imap-mailbox-get 'exists)
112 ;; (imap-mailbox-get 'uidvalidity)
115 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
118 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
119 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
123 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
124 ;; Use IEEE floats (which are effectively exact)? -- fx
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., ".
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 committed to pgnus
140 (eval-when-compile (require 'cl))
142 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
143 (autoload 'starttls-open-stream "starttls")
144 (autoload 'starttls-negotiate "starttls")
145 (autoload 'sasl-find-mechanism "sasl")
146 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
147 (autoload 'digest-md5-digest-response "digest-md5")
148 (autoload 'digest-md5-digest-uri "digest-md5")
149 (autoload 'digest-md5-challenge "digest-md5")
150 (autoload 'rfc2104-hash "rfc2104")
151 (autoload 'utf7-encode "utf7")
152 (autoload 'utf7-decode "utf7")
153 (autoload 'format-spec "format-spec")
154 (autoload 'format-spec-make "format-spec")
155 (autoload 'open-tls-stream "tls"))
160 "Low-level IMAP issues."
164 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
166 "List of strings containing commands for Kerberos 4 authentication.
167 %s is replaced with server hostname, %p with port to connect to, and
168 %l with the value of `imap-default-user'. The program should accept
169 IMAP commands on stdin and return responses to stdout. Each entry in
170 the list is tried until a successful connection is made."
172 :type '(repeat string))
174 (defcustom imap-gssapi-program (list
175 (concat "gsasl %s %p "
176 "--mechanism GSSAPI "
177 "--authentication-id %l")
178 "imtest -m gssapi -u %l -p %p %s")
179 "List of strings containing commands for GSSAPI (krb5) authentication.
180 %s is replaced with server hostname, %p with port to connect to, and
181 %l with the value of `imap-default-user'. The program should accept
182 IMAP commands on stdin and return responses to stdout. Each entry in
183 the list is tried until a successful connection is made."
185 :type '(repeat string))
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."
197 :type '(choice string
200 (defcustom imap-shell-program '("ssh %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."
211 :type '(repeat string))
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 controls the 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 an IMAP server is
220 opened; changing it after that has no effect."
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."
233 (defcustom imap-log nil
234 "If non-nil, an imap session trace is placed in `imap-log-buffer'.
235 Note that username, passwords and other privacy sensitive
236 information (such as e-mail) may be stored in the buffer.
237 It is not written to disk, however. Do not enable this
238 variable unless you are comfortable with that.
240 See also `imap-debug'."
244 (defcustom imap-debug nil
245 "If non-nil, trace imap- functions into `imap-debug-buffer'.
246 Uses `trace-function-background', so you can turn it off with,
249 Note that username, passwords and other privacy sensitive
250 information (such as e-mail) may be stored in the buffer.
251 It is not written to disk, however. Do not enable this
252 variable unless you are comfortable with that.
254 This variable only takes effect when loading the `imap' library.
255 See also `imap-log'."
259 (defcustom imap-shell-host "gateway"
260 "Hostname of rlogin proxy."
264 (defcustom imap-default-user (user-login-name)
265 "Default username to use."
269 (defcustom imap-read-timeout (if (string-match
270 "windows-nt\\|os/2\\|emx\\|cygwin"
271 (symbol-name system-type))
274 "*How long to wait between checking for the end of output.
275 Shorter values mean quicker response, but is more CPU intensive."
279 (defcustom imap-store-password nil
280 "If non-nil, store session password without prompting."
284 ;; Various variables.
286 (defvar imap-fetch-data-hook nil
287 "Hooks called after receiving each FETCH response.")
289 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
290 "Priority of streams to consider when opening connection to server.")
292 (defvar imap-stream-alist
293 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
294 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
295 (tls imap-tls-p imap-tls-open)
296 (ssl imap-ssl-p imap-ssl-open)
297 (network imap-network-p imap-network-open)
298 (shell imap-shell-p imap-shell-open)
299 (starttls imap-starttls-p imap-starttls-open))
300 "Definition of network streams.
304 NAME names the stream, CHECK is a function returning non-nil if the
305 server support the stream and OPEN is a function for opening the
308 (defvar imap-authenticators '(gssapi
315 "Priority of authenticators to consider when authenticating to server.")
317 (defvar imap-authenticator-alist
318 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
319 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
320 (sasl imap-sasl-auth-p imap-sasl-auth)
321 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
322 (login imap-login-p imap-login-auth)
323 (anonymous imap-anonymous-p imap-anonymous-auth)
324 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
325 "Definition of authenticators.
327 \(NAME CHECK AUTHENTICATE)
329 NAME names the authenticator. CHECK is a function returning non-nil if
330 the server support the authenticator and AUTHENTICATE is a function
331 for doing the actual authentication.")
333 (defvar imap-error nil
334 "Error codes from the last command.")
336 (defvar imap-logout-timeout nil
337 "Close server immediately if it can't logout in this number of seconds.
338 If it is nil, never close server until logout completes. Normally,
339 the value of this variable will be bound to a certain value to which
340 an application program that uses this module specifies on a per-server
343 ;; Internal constants. Change these and die.
345 (defconst imap-default-port 143)
346 (defconst imap-default-ssl-port 993)
347 (defconst imap-default-tls-port 993)
348 (defconst imap-default-stream 'network)
349 (defconst imap-coding-system-for-read 'binary)
350 (defconst imap-coding-system-for-write 'binary)
351 (defconst imap-local-variables '(imap-server
360 imap-current-target-mailbox
370 imap-calculate-literal-size-first
372 (defconst imap-log-buffer "*imap-log*")
373 (defconst imap-debug-buffer "*imap-debug*")
375 ;; Internal variables.
377 (defvar imap-stream nil)
378 (defvar imap-auth nil)
379 (defvar imap-server nil)
380 (defvar imap-port nil)
381 (defvar imap-username nil)
382 (defvar imap-password nil)
383 (defvar imap-calculate-literal-size-first nil)
384 (defvar imap-state 'closed
386 Valid states are `closed', `initial', `nonauth', `auth', `selected'
389 (defvar imap-server-eol "\r\n"
390 "The EOL string sent from the server.")
392 (defvar imap-client-eol "\r\n"
393 "The EOL string we send to the server.")
395 (defvar imap-current-mailbox nil
396 "Current mailbox name.")
398 (defvar imap-current-target-mailbox nil
399 "Current target mailbox for COPY and APPEND commands.")
401 (defvar imap-mailbox-data nil
402 "Obarray with mailbox data.")
404 (defvar imap-mailbox-prime 997
405 "Length of `imap-mailbox-data'.")
407 (defvar imap-current-message nil
408 "Current message number.")
410 (defvar imap-message-data nil
411 "Obarray with message data.")
413 (defvar imap-message-prime 997
414 "Length of `imap-message-data'.")
416 (defvar imap-capability nil
417 "Capability for server.")
423 (defvar imap-namespace nil
424 "Namespace for current server.")
426 (defvar imap-reached-tag 0
427 "Lower limit on command tags that have been parsed.")
429 (defvar imap-failed-tags nil
430 "Alist of tags that failed.
431 Each element is a list with four elements; tag (a integer), response
432 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
433 human readable response text (a string).")
436 "Command tag number.")
438 (defvar imap-process nil
441 (defvar imap-continuation nil
442 "Non-nil indicates that the server emitted a continuation request.
443 The actual value is really the text on the continuation line.")
445 (defvar imap-callbacks nil
446 "List of response tags and callbacks, on the form `(number . function)'.
447 The function should take two arguments, the first the IMAP tag and the
448 second the status (OK, NO, BAD etc) of the command.")
450 (defvar imap-enable-exchange-bug-workaround nil
451 "Send FETCH UID commands as *:* instead of *.
452 Enabling this appears to be required for some servers (e.g.,
453 Microsoft Exchange) which otherwise would trigger a response 'BAD
454 The specified message set is invalid.'.")
457 ;; Utility functions:
459 (defun imap-remassoc (key alist)
460 "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
461 The modified ALIST is returned. If the first member
462 of ALIST has a car that is `equal' to KEY, there is no way to remove it
463 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
464 sure of changing the value of `foo'."
466 (if (equal key (caar alist))
468 (setcdr alist (imap-remassoc key (cdr alist)))
471 (defsubst imap-disable-multibyte ()
472 "Enable multibyte in the current buffer."
473 (when (fboundp 'set-buffer-multibyte)
474 (set-buffer-multibyte nil)))
476 (defsubst imap-utf7-encode (string)
480 (utf7-encode string t)
482 "imap: Could not UTF7 encode `%s', using it unencoded..."
487 (defsubst imap-utf7-decode (string)
491 (utf7-decode string t)
493 "imap: Could not UTF7 decode `%s', using it undecoded..."
498 (defsubst imap-ok-p (status)
501 (setq imap-error status)
504 (defun imap-error-text (&optional buffer)
505 (with-current-buffer (or buffer (current-buffer))
506 (nth 3 (car imap-failed-tags))))
509 ;; Server functions; stream stuff:
511 (defun imap-kerberos4-stream-p (buffer)
512 (imap-capability 'AUTH=KERBEROS_V4 buffer))
514 (defun imap-kerberos4-open (name buffer server port)
515 (let ((cmds imap-kerberos4-program)
517 (while (and (not done) (setq cmd (pop cmds)))
518 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
520 (let* ((port (or port imap-default-port))
521 (coding-system-for-read imap-coding-system-for-read)
522 (coding-system-for-write imap-coding-system-for-write)
523 (process-connection-type imap-process-connection-type)
524 (process (start-process
525 name buffer shell-file-name shell-command-switch
530 ?p (number-to-string port)
531 ?l imap-default-user))))
534 (with-current-buffer buffer
535 (setq imap-client-eol "\n"
536 imap-calculate-literal-size-first t)
537 (while (and (memq (process-status process) '(open run))
538 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
539 (goto-char (point-min))
540 ;; Athena IMTEST can output SSL verify errors
541 (or (while (looking-at "^verify error:num=")
544 (or (while (looking-at "^TLS connection established")
547 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
548 (or (while (looking-at "^C:")
551 ;; cyrus 1.6 imtest print "S: " before server greeting
552 (or (not (looking-at "S: "))
555 (not (and (imap-parse-greeting)
556 ;; success in imtest < 1.6:
557 (or (re-search-forward
558 "^__\\(.*\\)__\n" nil t)
559 ;; success in imtest 1.6:
561 "^\\(Authenticat.*\\)" nil t))
562 (setq response (match-string 1)))))
563 (accept-process-output process 1)
566 (with-current-buffer (get-buffer-create imap-log-buffer)
567 (imap-disable-multibyte)
568 (buffer-disable-undo)
569 (goto-char (point-max))
570 (insert-buffer-substring buffer)))
572 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
573 (if response (concat "done, " response) "failed"))
574 (if (and response (let ((case-fold-search nil))
575 (not (string-match "failed" response))))
577 (if (memq (process-status process) '(open run))
579 (delete-process process)
583 (defun imap-gssapi-stream-p (buffer)
584 (imap-capability 'AUTH=GSSAPI buffer))
586 (defun imap-gssapi-open (name buffer server port)
587 (let ((cmds imap-gssapi-program)
589 (while (and (not done) (setq cmd (pop cmds)))
590 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
592 (let* ((port (or port imap-default-port))
593 (coding-system-for-read imap-coding-system-for-read)
594 (coding-system-for-write imap-coding-system-for-write)
595 (process-connection-type imap-process-connection-type)
596 (process (start-process
597 name buffer shell-file-name shell-command-switch
602 ?p (number-to-string port)
603 ?l imap-default-user))))
606 (with-current-buffer buffer
607 (setq imap-client-eol "\n"
608 imap-calculate-literal-size-first t)
609 (while (and (memq (process-status process) '(open run))
610 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
611 (goto-char (point-min))
612 ;; Athena IMTEST can output SSL verify errors
613 (or (while (looking-at "^verify error:num=")
616 (or (while (looking-at "^TLS connection established")
619 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
620 (or (while (looking-at "^C:")
623 ;; cyrus 1.6 imtest print "S: " before server greeting
624 (or (not (looking-at "S: "))
627 ;; GNU SASL may print 'Trying ...' first.
628 (or (not (looking-at "Trying "))
631 (not (and (imap-parse-greeting)
632 ;; success in imtest 1.6:
634 (concat "^\\(\\(Authenticat.*\\)\\|\\("
635 "Client authentication "
638 (setq response (match-string 1)))))
639 (accept-process-output process 1)
642 (with-current-buffer (get-buffer-create imap-log-buffer)
643 (imap-disable-multibyte)
644 (buffer-disable-undo)
645 (goto-char (point-max))
646 (insert-buffer-substring buffer)))
648 (message "GSSAPI IMAP connection: %s" (or response "failed"))
649 (if (and response (let ((case-fold-search nil))
650 (not (string-match "failed" response))))
652 (if (memq (process-status process) '(open run))
654 (delete-process process)
658 (defun imap-ssl-p (buffer)
661 (defun imap-ssl-open (name buffer server port)
662 "Open an SSL connection to SERVER."
663 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
664 (list imap-ssl-program)))
666 (while (and (not done) (setq cmd (pop cmds)))
667 (message "imap: Opening SSL connection with `%s'..." cmd)
669 (let* ((port (or port imap-default-ssl-port))
670 (coding-system-for-read imap-coding-system-for-read)
671 (coding-system-for-write imap-coding-system-for-write)
672 (process-connection-type imap-process-connection-type)
673 (set-process-query-on-exit-flag
674 (if (fboundp 'set-process-query-on-exit-flag)
675 'set-process-query-on-exit-flag
676 'process-kill-without-query))
679 (setq process (start-process
680 name buffer shell-file-name
685 ?p (number-to-string port)))))
686 (funcall set-process-query-on-exit-flag process nil)
688 (with-current-buffer buffer
689 (goto-char (point-min))
690 (while (and (memq (process-status process) '(open run))
691 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
692 (goto-char (point-max))
694 (not (imap-parse-greeting)))
695 (accept-process-output process 1)
698 (with-current-buffer (get-buffer-create imap-log-buffer)
699 (imap-disable-multibyte)
700 (buffer-disable-undo)
701 (goto-char (point-max))
702 (insert-buffer-substring buffer)))
704 (when (memq (process-status process) '(open run))
705 (setq done process))))))
708 (message "imap: Opening SSL connection with `%s'...done" cmd)
710 (message "imap: Opening SSL connection with `%s'...failed" cmd)
713 (defun imap-tls-p (buffer)
716 (defun imap-tls-open (name buffer server port)
717 (let* ((port (or port imap-default-tls-port))
718 (coding-system-for-read imap-coding-system-for-read)
719 (coding-system-for-write imap-coding-system-for-write)
720 (process (open-tls-stream name buffer server port)))
722 (while (and (memq (process-status process) '(open run))
723 ;; FIXME: Per the "blue moon" comment, the process/buffer
724 ;; handling here, and elsewhere in functions which open
725 ;; streams, looks confused. Obviously we can change buffers
726 ;; if a different process handler kicks in from
727 ;; `accept-process-output' or `sit-for' below, and TRT seems
728 ;; to be to `save-buffer' around those calls. (I wonder why
729 ;; `sit-for' is used with a non-zero wait.) -- fx
730 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
731 (goto-char (point-max))
733 (not (imap-parse-greeting)))
734 (accept-process-output process 1)
737 (with-current-buffer (get-buffer-create imap-log-buffer)
738 (imap-disable-multibyte)
739 (buffer-disable-undo)
740 (goto-char (point-max))
741 (insert-buffer-substring buffer)))
742 (when (memq (process-status process) '(open run))
745 (defun imap-network-p (buffer)
748 (defun imap-network-open (name buffer server port)
749 (let* ((port (or port imap-default-port))
750 (coding-system-for-read imap-coding-system-for-read)
751 (coding-system-for-write imap-coding-system-for-write)
752 (process (open-network-stream name buffer server port)))
754 (while (and (memq (process-status process) '(open run))
755 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
756 (goto-char (point-min))
757 (not (imap-parse-greeting)))
758 (accept-process-output process 1)
761 (with-current-buffer (get-buffer-create imap-log-buffer)
762 (imap-disable-multibyte)
763 (buffer-disable-undo)
764 (goto-char (point-max))
765 (insert-buffer-substring buffer)))
766 (when (memq (process-status process) '(open run))
769 (defun imap-shell-p (buffer)
772 (defun imap-shell-open (name buffer server port)
773 (let ((cmds (if (listp imap-shell-program) imap-shell-program
774 (list imap-shell-program)))
776 (while (and (not done) (setq cmd (pop cmds)))
777 (message "imap: Opening IMAP connection with `%s'..." cmd)
778 (setq imap-client-eol "\n")
779 (let* ((port (or port imap-default-port))
780 (coding-system-for-read imap-coding-system-for-read)
781 (coding-system-for-write imap-coding-system-for-write)
782 (process (start-process
783 name buffer shell-file-name shell-command-switch
789 ?p (number-to-string port)
790 ?l imap-default-user)))))
792 (while (and (memq (process-status process) '(open run))
793 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
794 (goto-char (point-max))
796 (not (imap-parse-greeting)))
797 (accept-process-output process 1)
800 (with-current-buffer (get-buffer-create imap-log-buffer)
801 (imap-disable-multibyte)
802 (buffer-disable-undo)
803 (goto-char (point-max))
804 (insert-buffer-substring buffer)))
806 (when (memq (process-status process) '(open run))
807 (setq done process)))))
810 (message "imap: Opening IMAP connection with `%s'...done" cmd)
812 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
815 (defun imap-starttls-p (buffer)
816 (imap-capability 'STARTTLS buffer))
818 (defun imap-starttls-open (name buffer server port)
819 (let* ((port (or port imap-default-port))
820 (coding-system-for-read imap-coding-system-for-read)
821 (coding-system-for-write imap-coding-system-for-write)
822 (process (starttls-open-stream name buffer server port))
824 (message "imap: Connecting with STARTTLS...")
826 (while (and (memq (process-status process) '(open run))
827 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
828 (goto-char (point-max))
830 (not (imap-parse-greeting)))
831 (accept-process-output process 1)
833 (imap-send-command "STARTTLS")
834 (while (and (memq (process-status process) '(open run))
835 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
836 (goto-char (point-max))
838 (not (re-search-forward "[0-9]+ OK.*\r?\n" nil t)))
839 (accept-process-output process 1)
842 (with-current-buffer (get-buffer-create imap-log-buffer)
843 (buffer-disable-undo)
844 (goto-char (point-max))
845 (insert-buffer-substring buffer)))
846 (when (and (setq tls-info (starttls-negotiate process))
847 (memq (process-status process) '(open run)))
848 (setq done process)))
849 (if (stringp tls-info)
850 (message "imap: STARTTLS info: %s" tls-info))
851 (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
854 ;; Server functions; authenticator stuff:
856 (defun imap-interactive-login (buffer loginfunc)
857 "Login to server in BUFFER.
858 LOGINFUNC is passed a username and a password, it should return t if
859 it where successful authenticating itself to the server, nil otherwise.
860 Returns t if login was successful, nil otherwise."
861 (with-current-buffer buffer
862 (make-local-variable 'imap-username)
863 (make-local-variable 'imap-password)
864 (let (user passwd ret)
865 ;; (condition-case ()
866 (while (or (not user) (not passwd))
867 (setq user (or imap-username
868 (read-from-minibuffer
869 (concat "IMAP username for " imap-server
870 " (using stream `" (symbol-name imap-stream)
872 (or user imap-default-user))))
873 (setq passwd (or imap-password
875 (concat "IMAP password for " user "@"
876 imap-server " (using authenticator `"
877 (symbol-name imap-auth) "'): "))))
878 (when (and user passwd)
879 (if (funcall loginfunc user passwd)
883 (when (and (not imap-password)
884 (or imap-store-password
885 (y-or-n-p "Store password for this session? ")))
886 (setq imap-password passwd)))
887 (message "Login failed...")
889 (setq imap-password nil)
891 ;; (quit (with-current-buffer buffer
894 ;; (error (with-current-buffer buffer
899 (defun imap-gssapi-auth-p (buffer)
900 (eq imap-stream 'gssapi))
902 (defun imap-gssapi-auth (buffer)
903 (message "imap: Authenticating using GSSAPI...%s"
904 (if (eq imap-stream 'gssapi) "done" "failed"))
905 (eq imap-stream 'gssapi))
907 (defun imap-kerberos4-auth-p (buffer)
908 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
909 (eq imap-stream 'kerberos4)))
911 (defun imap-kerberos4-auth (buffer)
912 (message "imap: Authenticating using Kerberos 4...%s"
913 (if (eq imap-stream 'kerberos4) "done" "failed"))
914 (eq imap-stream 'kerberos4))
916 (defun imap-cram-md5-p (buffer)
917 (imap-capability 'AUTH=CRAM-MD5 buffer))
919 (defun imap-cram-md5-auth (buffer)
920 "Login to server using the AUTH CRAM-MD5 method."
921 (message "imap: Authenticating using CRAM-MD5...")
922 (let ((done (imap-interactive-login
924 (lambda (user passwd)
926 (imap-send-command-wait
928 "AUTHENTICATE CRAM-MD5"
930 (let* ((decoded (base64-decode-string challenge))
931 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
932 (response (concat user " " hash))
933 (encoded (base64-encode-string response)))
936 (message "imap: Authenticating using CRAM-MD5...done")
937 (message "imap: Authenticating using CRAM-MD5...failed"))))
939 (defun imap-login-p (buffer)
940 (and (not (imap-capability 'LOGINDISABLED buffer))
941 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
943 (defun imap-quote-specials (string)
946 (goto-char (point-min))
947 (while (re-search-forward "[\\\"]" nil t)
953 (defun imap-login-auth (buffer)
954 "Login to server using the LOGIN command."
955 (message "imap: Plaintext authentication...")
956 (imap-interactive-login buffer
957 (lambda (user passwd)
958 (imap-ok-p (imap-send-command-wait
960 (imap-quote-specials user)
962 (imap-quote-specials passwd)
965 (defun imap-anonymous-p (buffer)
968 (defun imap-anonymous-auth (buffer)
969 (message "imap: Logging in anonymously...")
970 (with-current-buffer buffer
971 (imap-ok-p (imap-send-command-wait
972 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
973 (system-name)) "\"")))))
975 ;;; Compiler directives.
977 (defvar imap-sasl-client)
978 (defvar imap-sasl-step)
980 (defun imap-sasl-make-mechanisms (buffer)
983 (let ((name (symbol-name sym)))
984 (if (and (> (length name) 5)
985 (string-equal "AUTH=" (substring name 0 5 )))
986 (setq mecs (cons (substring name 5) mecs)))))
987 (imap-capability nil buffer))
990 (declare-function sasl-find-mechanism "sasl" (mechanism))
991 (declare-function sasl-mechanism-name "sasl" (mechanism))
992 (declare-function sasl-make-client "sasl" (mechanism name service server))
993 (declare-function sasl-next-step "sasl" (client step))
994 (declare-function sasl-step-data "sasl" (step))
995 (declare-function sasl-step-set-data "sasl" (step data))
997 (defun imap-sasl-auth-p (buffer)
998 (and (condition-case ()
1001 (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
1003 (defun imap-sasl-auth (buffer)
1004 "Login to server using the SASL method."
1005 (message "imap: Authenticating using SASL...")
1006 (with-current-buffer buffer
1007 (make-local-variable 'imap-username)
1008 (make-local-variable 'imap-sasl-client)
1009 (make-local-variable 'imap-sasl-step)
1010 (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
1013 (setq user (or imap-username
1014 (read-from-minibuffer
1015 (concat "IMAP username for " imap-server " using SASL "
1016 (sasl-mechanism-name mechanism) ": ")
1017 (or user imap-default-user))))
1019 (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
1020 imap-sasl-step (sasl-next-step imap-sasl-client nil))
1021 (let ((tag (imap-send-command
1022 (if (sasl-step-data imap-sasl-step)
1023 (format "AUTHENTICATE %s %s"
1024 (sasl-mechanism-name mechanism)
1025 (sasl-step-data imap-sasl-step))
1026 (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
1028 (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
1029 (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
1030 (setq imap-continuation nil
1031 imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
1032 (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
1033 (base64-encode-string (sasl-step-data imap-sasl-step) t)
1035 (if (imap-ok-p (imap-wait-for-tag tag))
1036 (setq imap-username user
1038 (message "Login failed...")
1042 (defun imap-digest-md5-p (buffer)
1043 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
1045 (require 'digest-md5)
1048 (defun imap-digest-md5-auth (buffer)
1049 "Login to server using the AUTH DIGEST-MD5 method."
1050 (message "imap: Authenticating using DIGEST-MD5...")
1051 (imap-interactive-login
1053 (lambda (user passwd)
1057 "AUTHENTICATE DIGEST-MD5"
1059 (digest-md5-parse-digest-challenge
1060 (base64-decode-string challenge))
1062 (digest-md5-digest-uri
1063 "imap" (digest-md5-challenge 'realm)))
1065 (digest-md5-digest-response
1066 user passwd digest-uri)))
1067 (base64-encode-string response 'no-line-break))))
1069 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1071 (setq imap-continuation nil)
1072 (imap-send-command-1 "")
1073 (imap-ok-p (imap-wait-for-tag tag)))))))
1075 ;; Server functions:
1077 (defun imap-open-1 (buffer)
1078 (with-current-buffer buffer
1080 (setq imap-current-mailbox nil
1081 imap-current-message nil
1083 imap-process (condition-case ()
1084 (funcall (nth 2 (assq imap-stream
1086 "imap" buffer imap-server imap-port)
1087 ((error quit) nil)))
1089 (set-process-filter imap-process 'imap-arrival-filter)
1090 (set-process-sentinel imap-process 'imap-sentinel)
1091 (while (and (eq imap-state 'initial)
1092 (memq (process-status imap-process) '(open run)))
1093 (message "Waiting for response from %s..." imap-server)
1094 (accept-process-output imap-process 1))
1095 (message "Waiting for response from %s...done" imap-server)
1096 (and (memq (process-status imap-process) '(open run))
1099 (defun imap-open (server &optional port stream auth buffer)
1100 "Open an IMAP connection to host SERVER at PORT returning a buffer.
1101 If PORT is unspecified, a default value is used (143 except
1102 for SSL which use 993).
1103 STREAM indicates the stream to use, see `imap-streams' for available
1104 streams. If nil, it choices the best stream the server is capable of.
1105 AUTH indicates authenticator to use, see `imap-authenticators' for
1106 available authenticators. If nil, it choices the best stream the
1107 server is capable of.
1108 BUFFER can be a buffer or a name of a buffer, which is created if
1109 necessary. If nil, the buffer name is generated."
1110 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1111 (with-current-buffer (get-buffer-create buffer)
1112 (if (imap-opened buffer)
1113 (imap-close buffer))
1114 (mapc 'make-local-variable imap-local-variables)
1115 (imap-disable-multibyte)
1116 (buffer-disable-undo)
1117 (setq imap-server (or server imap-server))
1118 (setq imap-port (or port imap-port))
1119 (setq imap-auth (or auth imap-auth))
1120 (setq imap-stream (or stream imap-stream))
1121 (message "imap: Connecting to %s..." imap-server)
1122 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1123 (imap-open-1 buffer)))
1125 (message "imap: Connecting to %s...failed" imap-server)
1127 (when (null imap-stream)
1128 ;; Need to choose stream.
1129 (let ((streams imap-streams))
1130 (while (setq stream (pop streams))
1131 ;; OK to use this stream?
1132 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1134 (if (not (eq imap-default-stream stream))
1135 (with-current-buffer (get-buffer-create
1136 (generate-new-buffer-name " *temp*"))
1137 (mapc 'make-local-variable imap-local-variables)
1138 (imap-disable-multibyte)
1139 (buffer-disable-undo)
1140 (setq imap-server (or server imap-server))
1141 (setq imap-port (or port imap-port))
1142 (setq imap-auth (or auth imap-auth))
1143 (message "imap: Reconnecting with stream `%s'..." stream)
1144 (if (null (let ((imap-stream stream))
1145 (imap-open-1 (current-buffer))))
1147 (kill-buffer (current-buffer))
1149 "imap: Reconnecting with stream `%s'...failed"
1151 ;; We're done, kill the first connection
1153 (let ((name (if (stringp buffer)
1155 (buffer-name buffer))))
1156 (kill-buffer buffer)
1157 (rename-buffer name))
1158 (message "imap: Reconnecting with stream `%s'...done"
1160 (setq imap-stream stream)
1161 (setq imap-capability nil)
1162 (setq streams nil)))
1164 (message "imap: Connecting to %s...done" imap-server)
1165 (setq imap-stream stream)
1166 (setq imap-capability nil)
1167 (setq streams nil))))))
1168 (when (imap-opened buffer)
1169 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1173 (defcustom imap-ping-server t
1174 "If non-nil, check if IMAP is open.
1175 See the function `imap-ping-server'."
1176 :version "23.1" ;; No Gnus
1180 (defun imap-opened (&optional buffer)
1181 "Return non-nil if connection to imap server in BUFFER is open.
1182 If BUFFER is nil then the current buffer is used."
1183 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1184 (buffer-live-p buffer)
1185 (with-current-buffer buffer
1187 (memq (process-status imap-process) '(open run))
1188 (if imap-ping-server
1192 (defun imap-ping-server (&optional buffer)
1193 "Ping the IMAP server in BUFFER with a \"NOOP\" command.
1194 Return non-nil if the server responds, and nil if it does not
1195 respond. If BUFFER is nil, the current buffer is used."
1197 (imap-ok-p (imap-send-command-wait "NOOP" buffer))
1200 (defun imap-authenticate (&optional user passwd buffer)
1201 "Authenticate to server in BUFFER, using current buffer if nil.
1202 It uses the authenticator specified when opening the server. If the
1203 authenticator requires username/passwords, they are queried from the
1204 user and optionally stored in the buffer. If USER and/or PASSWD is
1205 specified, the user will not be questioned and the username and/or
1206 password is remembered in the buffer."
1207 (with-current-buffer (or buffer (current-buffer))
1208 (if (not (eq imap-state 'nonauth))
1209 (or (eq imap-state 'auth)
1210 (eq imap-state 'selected)
1211 (eq imap-state 'examine))
1212 (make-local-variable 'imap-username)
1213 (make-local-variable 'imap-password)
1214 (if user (setq imap-username user))
1215 (if passwd (setq imap-password passwd))
1217 (and (funcall (nth 2 (assq imap-auth
1218 imap-authenticator-alist)) (current-buffer))
1219 (setq imap-state 'auth))
1220 ;; Choose authenticator.
1221 (let ((auths imap-authenticators)
1223 (while (setq auth (pop auths))
1224 ;; OK to use authenticator?
1225 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) (current-buffer))
1226 (message "imap: Authenticating to `%s' using `%s'..."
1228 (setq imap-auth auth)
1229 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) (current-buffer))
1231 (message "imap: Authenticating to `%s' using `%s'...done"
1234 (message "imap: Authenticating to `%s' using `%s'...failed"
1235 imap-server auth)))))
1238 (defun imap-close (&optional buffer)
1239 "Close connection to server in BUFFER.
1240 If BUFFER is nil, the current buffer is used."
1241 (with-current-buffer (or buffer (current-buffer))
1246 (when (and imap-process
1247 (memq (process-status imap-process) '(open run)))
1248 (delete-process imap-process))
1249 (setq imap-current-mailbox nil
1250 imap-current-message nil
1255 (defun imap-capability (&optional identifier buffer)
1256 "Return a list of identifiers which server in BUFFER support.
1257 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1258 If BUFFER is nil, the current buffer is assumed."
1259 (with-current-buffer (or buffer (current-buffer))
1260 (unless imap-capability
1261 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1262 (setq imap-capability '(IMAP2))))
1264 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1267 (defun imap-id (&optional list-of-values buffer)
1268 "Identify client to server in BUFFER, and return server identity.
1269 LIST-OF-VALUES is nil, or a plist with identifier and value
1270 strings to send to the server to identify the client.
1272 Return a list of identifiers which server in BUFFER support, or
1273 nil if it doesn't support ID or returns no information.
1275 If BUFFER is nil, the current buffer is assumed."
1276 (with-current-buffer (or buffer (current-buffer))
1277 (when (and (imap-capability 'ID)
1278 (imap-ok-p (imap-send-command-wait
1279 (if (null list-of-values)
1281 (concat "ID (" (mapconcat (lambda (el)
1282 (concat "\"" el "\""))
1287 (defun imap-namespace (&optional buffer)
1288 "Return a namespace hierarchy at server in BUFFER.
1289 If BUFFER is nil, the current buffer is assumed."
1290 (with-current-buffer (or buffer (current-buffer))
1291 (unless imap-namespace
1292 (when (imap-capability 'NAMESPACE)
1293 (imap-send-command-wait "NAMESPACE")))
1296 (defun imap-send-command-wait (command &optional buffer)
1297 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1299 (defun imap-logout (&optional buffer)
1300 (or buffer (setq buffer (current-buffer)))
1301 (if imap-logout-timeout
1302 (with-timeout (imap-logout-timeout
1304 (with-current-buffer buffer
1305 (delete-process imap-process))
1307 (imap-send-command "LOGOUT" buffer))
1308 (imap-send-command "LOGOUT" buffer)))
1310 (defun imap-logout-wait (&optional buffer)
1311 (or buffer (setq buffer (current-buffer)))
1312 (if imap-logout-timeout
1313 (with-timeout (imap-logout-timeout
1315 (with-current-buffer buffer
1316 (delete-process imap-process))
1318 (imap-send-command-wait "LOGOUT" buffer))
1319 (imap-send-command-wait "LOGOUT" buffer)))
1322 ;; Mailbox functions:
1324 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1325 (with-current-buffer (or buffer (current-buffer))
1326 (if imap-mailbox-data
1327 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1329 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1330 propname value mailbox (current-buffer)))
1333 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1334 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1337 (defun imap-mailbox-get (propname &optional mailbox buffer)
1338 (let ((mailbox (imap-utf7-encode mailbox)))
1339 (with-current-buffer (or buffer (current-buffer))
1340 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1342 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1343 (with-current-buffer (or buffer (current-buffer))
1347 (push (funcall func (if mailbox-decoder
1348 (funcall mailbox-decoder (symbol-name s))
1349 (symbol-name s))) result))
1353 (defun imap-mailbox-map (func &optional buffer)
1354 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1355 Function should take a mailbox name (a string) as
1357 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1359 (defun imap-current-mailbox (&optional buffer)
1360 (with-current-buffer (or buffer (current-buffer))
1361 (imap-utf7-decode imap-current-mailbox)))
1363 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1364 (and (string= mailbox imap-current-mailbox)
1366 (eq imap-state 'examine))
1368 (eq imap-state 'selected)))))
1370 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1371 (with-current-buffer (or buffer (current-buffer))
1372 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1374 (defun imap-mailbox-select-1 (mailbox &optional examine)
1375 "Select MAILBOX on server in BUFFER.
1376 If EXAMINE is non-nil, do a read-only select."
1377 (if (imap-current-mailbox-p-1 mailbox examine)
1378 imap-current-mailbox
1379 (setq imap-current-mailbox mailbox)
1380 (if (imap-ok-p (imap-send-command-wait
1381 (concat (if examine "EXAMINE" "SELECT") " \""
1384 (setq imap-message-data (make-vector imap-message-prime 0)
1385 imap-state (if examine 'examine 'selected))
1386 imap-current-mailbox)
1387 ;; Failed SELECT/EXAMINE unselects current mailbox
1388 (setq imap-current-mailbox nil))))
1390 (defun imap-mailbox-select (mailbox &optional examine buffer)
1391 (with-current-buffer (or buffer (current-buffer))
1393 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1395 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1396 (with-current-buffer (or buffer (current-buffer))
1397 (imap-mailbox-select-1 mailbox 'examine)))
1399 (defun imap-mailbox-examine (mailbox &optional buffer)
1400 "Examine MAILBOX on server in BUFFER."
1401 (imap-mailbox-select mailbox 'examine buffer))
1403 (defun imap-mailbox-unselect (&optional buffer)
1404 "Close current folder in BUFFER, without expunging articles."
1405 (with-current-buffer (or buffer (current-buffer))
1406 (when (or (eq imap-state 'auth)
1407 (and (imap-capability 'UNSELECT)
1408 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1410 (imap-send-command-wait (concat "EXAMINE \""
1411 imap-current-mailbox
1413 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1414 (setq imap-current-mailbox nil
1415 imap-message-data nil
1419 (defun imap-mailbox-expunge (&optional asynch buffer)
1420 "Expunge articles in current folder in BUFFER.
1421 If ASYNCH, do not wait for successful completion of the command.
1422 If BUFFER is nil the current buffer is assumed."
1423 (with-current-buffer (or buffer (current-buffer))
1424 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1426 (imap-send-command "EXPUNGE")
1427 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1429 (defun imap-mailbox-close (&optional asynch buffer)
1430 "Expunge articles and close current folder in BUFFER.
1431 If ASYNCH, do not wait for successful completion of the command.
1432 If BUFFER is nil the current buffer is assumed."
1433 (with-current-buffer (or buffer (current-buffer))
1434 (when imap-current-mailbox
1436 (imap-add-callback (imap-send-command "CLOSE")
1437 `(lambda (tag status)
1438 (message "IMAP mailbox `%s' closed... %s"
1439 imap-current-mailbox status)
1440 (when (eq ,imap-current-mailbox
1441 imap-current-mailbox)
1442 ;; Don't wipe out data if another mailbox
1444 (setq imap-current-mailbox nil
1445 imap-message-data nil
1446 imap-state 'auth))))
1447 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1448 (setq imap-current-mailbox nil
1449 imap-message-data nil
1453 (defun imap-mailbox-create-1 (mailbox)
1454 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1456 (defun imap-mailbox-create (mailbox &optional buffer)
1457 "Create MAILBOX on server in BUFFER.
1458 If BUFFER is nil the current buffer is assumed."
1459 (with-current-buffer (or buffer (current-buffer))
1460 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1462 (defun imap-mailbox-delete (mailbox &optional buffer)
1463 "Delete MAILBOX on server in BUFFER.
1464 If BUFFER is nil the current buffer is assumed."
1465 (let ((mailbox (imap-utf7-encode mailbox)))
1466 (with-current-buffer (or buffer (current-buffer))
1468 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1470 (defun imap-mailbox-rename (oldname newname &optional buffer)
1471 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1472 If BUFFER is nil the current buffer is assumed."
1473 (let ((oldname (imap-utf7-encode oldname))
1474 (newname (imap-utf7-encode newname)))
1475 (with-current-buffer (or buffer (current-buffer))
1477 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1478 "\"" newname "\""))))))
1480 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1481 "Return a list of subscribed mailboxes on server in BUFFER.
1482 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1483 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1484 implementation-specific string that has to be passed to lsub command."
1485 (with-current-buffer (or buffer (current-buffer))
1486 ;; Make sure we know the hierarchy separator for root's hierarchy
1487 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1488 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1489 (imap-utf7-encode root) "\"")))
1490 ;; clear list data (NB not delimiter and other stuff)
1491 (imap-mailbox-map-1 (lambda (mailbox)
1492 (imap-mailbox-put 'lsub nil mailbox)))
1494 (imap-send-command-wait
1495 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1496 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1499 (imap-mailbox-map-1 (lambda (mailbox)
1500 (when (imap-mailbox-get-1 'lsub mailbox)
1501 (push (imap-utf7-decode mailbox) out))))
1504 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1505 "Return a list of mailboxes matching ROOT on server in BUFFER.
1506 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1507 root. REFERENCE is a implementation-specific string that has to be
1508 passed to list command."
1509 (with-current-buffer (or buffer (current-buffer))
1510 ;; Make sure we know the hierarchy separator for root's hierarchy
1511 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1512 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1513 (imap-utf7-encode root) "\"")))
1514 ;; clear list data (NB not delimiter and other stuff)
1515 (imap-mailbox-map-1 (lambda (mailbox)
1516 (imap-mailbox-put 'list nil mailbox)))
1518 (imap-send-command-wait
1519 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1520 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1523 (imap-mailbox-map-1 (lambda (mailbox)
1524 (when (imap-mailbox-get-1 'list mailbox)
1525 (push (imap-utf7-decode mailbox) out))))
1528 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1529 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1530 Returns non-nil if successful."
1531 (with-current-buffer (or buffer (current-buffer))
1532 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1533 (imap-utf7-encode mailbox)
1536 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1537 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1538 Returns non-nil if successful."
1539 (with-current-buffer (or buffer (current-buffer))
1540 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1541 (imap-utf7-encode mailbox)
1544 (defun imap-mailbox-status (mailbox items &optional buffer)
1545 "Get status items ITEM in MAILBOX from server in BUFFER.
1546 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1547 the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
1548 or `unseen'. If ITEMS is a list of symbols, a list of values is
1549 returned, if ITEMS is a symbol only its value is returned."
1550 (with-current-buffer (or buffer (current-buffer))
1552 (imap-send-command-wait (list "STATUS \""
1553 (imap-utf7-encode mailbox)
1561 (mapcar (lambda (item)
1562 (imap-mailbox-get item mailbox))
1564 (imap-mailbox-get items mailbox)))))
1566 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1567 "Send status item request ITEM on MAILBOX to server in BUFFER.
1568 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1569 the STATUS data items -- i.e. 'messages, 'recent, 'uidnext, 'uidvalidity
1570 or 'unseen. The IMAP command tag is returned."
1571 (with-current-buffer (or buffer (current-buffer))
1572 (imap-send-command (list "STATUS \""
1573 (imap-utf7-encode mailbox)
1581 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1582 "Get ACL on MAILBOX from server in BUFFER."
1583 (let ((mailbox (imap-utf7-encode mailbox)))
1584 (with-current-buffer (or buffer (current-buffer))
1586 (imap-send-command-wait (list "GETACL \""
1587 (or mailbox imap-current-mailbox)
1589 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1591 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1592 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1593 (let ((mailbox (imap-utf7-encode mailbox)))
1594 (with-current-buffer (or buffer (current-buffer))
1596 (imap-send-command-wait (list "SETACL \""
1597 (or mailbox imap-current-mailbox)
1603 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1604 "Remove any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1605 (let ((mailbox (imap-utf7-encode mailbox)))
1606 (with-current-buffer (or buffer (current-buffer))
1608 (imap-send-command-wait (list "DELETEACL \""
1609 (or mailbox imap-current-mailbox)
1614 ;; Message functions:
1616 (defun imap-current-message (&optional buffer)
1617 (with-current-buffer (or buffer (current-buffer))
1618 imap-current-message))
1620 (defun imap-list-to-message-set (list)
1621 (mapconcat (lambda (item)
1622 (number-to-string item))
1628 (defun imap-range-to-message-set (range)
1633 (car item) (cdr item))
1634 (format "%d" item)))
1635 (if (and (listp range) (not (listp (cdr range))))
1636 (list range) ;; make (1 . 2) into ((1 . 2))
1640 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1641 (with-current-buffer (or buffer (current-buffer))
1642 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1644 (imap-list-to-message-set uids)
1648 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1649 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1650 UIDS can be a string, number or a list of numbers. If RECEIVE
1651 is non-nil return these properties."
1652 (with-current-buffer (or buffer (current-buffer))
1653 (when (imap-ok-p (imap-send-command-wait
1654 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1656 (imap-list-to-message-set uids)
1659 (if (or (null receive) (stringp uids))
1662 (mapcar (lambda (uid)
1664 (mapcar (lambda (prop)
1665 (imap-message-get uid prop))
1667 (imap-message-get uid receive)))
1669 (imap-message-get uids receive))))))
1671 (defun imap-message-put (uid propname value &optional buffer)
1672 (with-current-buffer (or buffer (current-buffer))
1673 (if imap-message-data
1674 (put (intern (number-to-string uid) imap-message-data)
1676 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1677 uid propname value (current-buffer)))
1680 (defun imap-message-get (uid propname &optional buffer)
1681 (with-current-buffer (or buffer (current-buffer))
1682 (get (intern-soft (number-to-string uid) imap-message-data)
1685 (defun imap-message-map (func propname &optional buffer)
1686 "Map a function across each mailbox in `imap-message-data', returning a list."
1687 (with-current-buffer (or buffer (current-buffer))
1691 (push (funcall func (get s 'UID) (get s propname)) result))
1695 (defmacro imap-message-envelope-date (uid &optional buffer)
1696 `(with-current-buffer (or ,buffer (current-buffer))
1697 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1699 (defmacro imap-message-envelope-subject (uid &optional buffer)
1700 `(with-current-buffer (or ,buffer (current-buffer))
1701 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1703 (defmacro imap-message-envelope-from (uid &optional buffer)
1704 `(with-current-buffer (or ,buffer (current-buffer))
1705 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1707 (defmacro imap-message-envelope-sender (uid &optional buffer)
1708 `(with-current-buffer (or ,buffer (current-buffer))
1709 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1711 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1712 `(with-current-buffer (or ,buffer (current-buffer))
1713 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1715 (defmacro imap-message-envelope-to (uid &optional buffer)
1716 `(with-current-buffer (or ,buffer (current-buffer))
1717 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1719 (defmacro imap-message-envelope-cc (uid &optional buffer)
1720 `(with-current-buffer (or ,buffer (current-buffer))
1721 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1723 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1724 `(with-current-buffer (or ,buffer (current-buffer))
1725 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1727 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1728 `(with-current-buffer (or ,buffer (current-buffer))
1729 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1731 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1732 `(with-current-buffer (or ,buffer (current-buffer))
1733 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1735 (defmacro imap-message-body (uid &optional buffer)
1736 `(with-current-buffer (or ,buffer (current-buffer))
1737 (imap-message-get ,uid 'BODY)))
1739 ;; FIXME: Should this try to use CHARSET? -- fx
1740 (defun imap-search (predicate &optional buffer)
1741 (with-current-buffer (or buffer (current-buffer))
1742 (imap-mailbox-put 'search 'dummy)
1743 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1744 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1746 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1748 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1750 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1751 "Return t if FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1752 (with-current-buffer (or buffer (current-buffer))
1753 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1754 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1756 (defun imap-message-flags-set (articles flags &optional silent buffer)
1757 (when (and articles flags)
1758 (with-current-buffer (or buffer (current-buffer))
1759 (imap-ok-p (imap-send-command-wait
1760 (concat "UID STORE " articles
1761 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1763 (defun imap-message-flags-del (articles flags &optional silent buffer)
1764 (when (and articles flags)
1765 (with-current-buffer (or buffer (current-buffer))
1766 (imap-ok-p (imap-send-command-wait
1767 (concat "UID STORE " articles
1768 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1770 (defun imap-message-flags-add (articles flags &optional silent buffer)
1771 (when (and articles flags)
1772 (with-current-buffer (or buffer (current-buffer))
1773 (imap-ok-p (imap-send-command-wait
1774 (concat "UID STORE " articles
1775 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1777 ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
1778 ;; Signal an error if we'd get an integer overflow.
1780 ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
1781 ;; `imap-string-to-integer'.
1782 (defun imap-string-to-integer (string &optional base)
1783 (let ((number (string-to-number string base)))
1784 (if (> number most-positive-fixnum)
1786 (format "String %s cannot be converted to a Lisp integer" number))
1789 (defun imap-fetch-safe (uids props &optional receive nouidfetch buffer)
1790 "Like `imap-fetch', but DTRT with Exchange 2007 bug.
1791 However, UIDS here is a cons, where the car is the canonical form
1792 of the UIDS specification, and the cdr is the one which works with
1793 Exchange 2007 or, potentially, other buggy servers.
1794 See `imap-enable-exchange-bug-workaround'."
1795 ;; We don't unconditionally use the alternative (valid) form, since
1796 ;; this is said to be significantly inefficient. The first time we
1797 ;; get here for a given, we'll try the canonical form. If we get
1798 ;; the known error from the buggy server, set the flag
1799 ;; buffer-locally (to account for connexions to multiple servers),
1800 ;; then re-try with the alternative UIDS spec.
1801 (condition-case data
1802 (imap-fetch (if imap-enable-exchange-bug-workaround
1805 props receive nouidfetch buffer)
1807 (if (and (not imap-enable-exchange-bug-workaround)
1809 "The specified message set is invalid"
1811 (with-current-buffer (or buffer (current-buffer))
1812 (set (make-local-variable
1813 'imap-enable-exchange-bug-workaround)
1815 (imap-fetch (cdr uids) props receive nouidfetch))
1816 (signal (car data) (cdr data))))))
1818 (defun imap-message-copyuid-1 (mailbox)
1819 (if (imap-capability 'UIDPLUS)
1820 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1821 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1822 (let ((old-mailbox imap-current-mailbox)
1824 (imap-message-data (make-vector 2 0)))
1825 (when (imap-mailbox-examine-1 mailbox)
1827 (and (imap-fetch-safe '("*" . "*:*") "UID")
1828 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1829 (apply 'max (imap-message-map
1830 (lambda (uid prop) uid) 'UID))))
1832 (imap-mailbox-select old-mailbox (eq state 'examine))
1833 (imap-mailbox-unselect)))))))
1835 (defun imap-message-copyuid (mailbox &optional buffer)
1836 (with-current-buffer (or buffer (current-buffer))
1837 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1839 (defun imap-message-copy (articles mailbox
1840 &optional dont-create no-copyuid buffer)
1841 "Copy ARTICLES to MAILBOX on server in BUFFER.
1842 ARTICLES is a string message set. Create mailbox if it doesn't exist,
1843 unless DONT-CREATE is non-nil. On success, return a list with
1844 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1845 first element. The rest of list contains the saved articles' UIDs."
1847 (with-current-buffer (or buffer (current-buffer))
1848 (let ((mailbox (imap-utf7-encode mailbox)))
1849 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1850 (imap-current-target-mailbox mailbox))
1851 (if (imap-ok-p (imap-send-command-wait cmd))
1853 (when (and (not dont-create)
1854 ;; removed because of buggy Oracle server
1855 ;; that doesn't send TRYCREATE tags (which
1856 ;; is a MUST according to specifications):
1857 ;;(imap-mailbox-get-1 'trycreate mailbox)
1858 (imap-mailbox-create-1 mailbox))
1859 (imap-ok-p (imap-send-command-wait cmd)))))
1861 (imap-message-copyuid-1 mailbox)))))))
1863 ;; FIXME: Amalgamate with imap-message-copyuid-1, using an extra arg, since it
1864 ;; shares most of the code? -- fx
1865 (defun imap-message-appenduid-1 (mailbox)
1866 (if (imap-capability 'UIDPLUS)
1867 (imap-mailbox-get-1 'appenduid mailbox)
1868 (let ((old-mailbox imap-current-mailbox)
1870 (imap-message-data (make-vector 2 0)))
1871 (when (imap-mailbox-examine-1 mailbox)
1873 (and (imap-fetch-safe '("*" "*:*") "UID")
1874 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1875 (apply 'max (imap-message-map
1876 (lambda (uid prop) uid) 'UID))))
1878 (imap-mailbox-select old-mailbox (eq state 'examine))
1879 (imap-mailbox-unselect)))))))
1881 (defun imap-message-appenduid (mailbox &optional buffer)
1882 (with-current-buffer (or buffer (current-buffer))
1883 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1885 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1886 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1887 FLAGS and DATE-TIME is currently not used. Return a cons holding
1888 uidvalidity of MAILBOX and UID the newly created article got, or nil
1890 (let ((mailbox (imap-utf7-encode mailbox)))
1891 (with-current-buffer (or buffer (current-buffer))
1892 (and (let ((imap-current-target-mailbox mailbox))
1894 (imap-send-command-wait
1895 (list "APPEND \"" mailbox "\" " article))))
1896 (imap-message-appenduid-1 mailbox)))))
1898 (defun imap-body-lines (body)
1899 "Return number of lines in article by looking at the mime bodystructure BODY."
1901 (if (stringp (car body))
1902 (cond ((and (string= (upcase (car body)) "TEXT")
1903 (numberp (nth 7 body)))
1905 ((and (string= (upcase (car body)) "MESSAGE")
1906 (numberp (nth 9 body)))
1909 (apply '+ (mapcar 'imap-body-lines body)))
1912 (defun imap-envelope-from (from)
1913 "Return a from string line."
1915 (concat (aref from 0)
1916 (if (aref from 0) " <")
1920 (if (aref from 0) ">"))))
1923 ;; Internal functions.
1925 (defun imap-add-callback (tag func)
1926 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1928 (defun imap-send-command-1 (cmdstr)
1929 (setq cmdstr (concat cmdstr imap-client-eol))
1931 (with-current-buffer (get-buffer-create imap-log-buffer)
1932 (imap-disable-multibyte)
1933 (buffer-disable-undo)
1934 (goto-char (point-max))
1936 (process-send-string imap-process cmdstr))
1938 (defun imap-send-command (command &optional buffer)
1939 (with-current-buffer (or buffer (current-buffer))
1940 (if (not (listp command)) (setq command (list command)))
1941 (let ((tag (setq imap-tag (1+ imap-tag)))
1943 (setq cmdstr (concat (number-to-string imap-tag) " "))
1944 (while (setq cmd (pop command))
1945 (cond ((stringp cmd)
1946 (setq cmdstr (concat cmdstr cmd)))
1948 (let ((eol imap-client-eol)
1949 (calcfirst imap-calculate-literal-size-first)
1951 (with-current-buffer cmd
1953 (setq size (buffer-size)))
1954 (when (not (equal eol "\r\n"))
1955 ;; XXX modifies buffer!
1956 (goto-char (point-min))
1957 (while (search-forward "\r\n" nil t)
1958 (replace-match eol)))
1960 (setq size (buffer-size))))
1962 (concat cmdstr (format "{%d}" size))))
1965 (imap-send-command-1 cmdstr)
1967 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1968 (setq command nil) ;; abort command if no cont-req
1969 (let ((process imap-process)
1970 (stream imap-stream)
1971 (eol imap-client-eol))
1972 (with-current-buffer cmd
1974 (with-current-buffer (get-buffer-create
1976 (imap-disable-multibyte)
1977 (buffer-disable-undo)
1978 (goto-char (point-max))
1979 (insert-buffer-substring cmd)))
1980 (process-send-region process (point-min)
1982 (process-send-string process imap-client-eol))))
1983 (setq imap-continuation nil)))
1985 (imap-send-command-1 cmdstr)
1988 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1989 (setq command nil) ;; abort command if no cont-req
1990 (setq command (cons (funcall cmd imap-continuation)
1992 (setq imap-continuation nil)))
1994 (error "Unknown command type"))))
1996 (imap-send-command-1 cmdstr))
1999 (defun imap-wait-for-tag (tag &optional buffer)
2000 (with-current-buffer (or buffer (current-buffer))
2001 (let (imap-have-messaged)
2002 (while (and (null imap-continuation)
2003 (memq (process-status imap-process) '(open run))
2004 (< imap-reached-tag tag))
2005 (let ((len (/ (point-max) 1024))
2008 (setq imap-have-messaged t)
2009 (message "imap read: %dk" len))
2010 (accept-process-output imap-process
2011 (truncate imap-read-timeout)
2012 (truncate (* (- imap-read-timeout
2013 (truncate imap-read-timeout))
2015 ;; A process can die _before_ we have processed everything it
2016 ;; has to say. Moreover, this can happen in between the call to
2017 ;; accept-process-output and the call to process-status in an
2018 ;; iteration of the loop above.
2019 (when (and (null imap-continuation)
2020 (< imap-reached-tag tag))
2021 (accept-process-output imap-process 0 0))
2022 (when imap-have-messaged
2024 (and (memq (process-status imap-process) '(open run))
2025 (or (assq tag imap-failed-tags)
2026 (if imap-continuation
2030 (defun imap-sentinel (process string)
2031 (delete-process process))
2033 (defun imap-find-next-line ()
2034 "Return point at end of current line, taking into account literals.
2035 Return nil if no complete line has arrived."
2036 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
2039 (if (match-string 1)
2040 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
2042 (goto-char (+ (point) (string-to-number (match-string 1))))
2043 (imap-find-next-line))
2046 (defun imap-arrival-filter (proc string)
2047 "IMAP process filter."
2048 ;; Sometimes, we are called even though the process has died.
2049 ;; Better abstain from doing stuff in that case.
2050 (when (buffer-name (process-buffer proc))
2051 (with-current-buffer (process-buffer proc)
2052 (goto-char (point-max))
2055 (with-current-buffer (get-buffer-create imap-log-buffer)
2056 (imap-disable-multibyte)
2057 (buffer-disable-undo)
2058 (goto-char (point-max))
2061 (goto-char (point-min))
2062 (while (setq end (imap-find-next-line))
2064 (narrow-to-region (point-min) end)
2065 (delete-backward-char (length imap-server-eol))
2066 (goto-char (point-min))
2068 (cond ((eq imap-state 'initial)
2069 (imap-parse-greeting))
2070 ((or (eq imap-state 'auth)
2071 (eq imap-state 'nonauth)
2072 (eq imap-state 'selected)
2073 (eq imap-state 'examine))
2074 (imap-parse-response))
2076 (message "Unknown state %s in arrival filter"
2078 (delete-region (point-min) (point-max)))))))))
2083 (defsubst imap-forward ()
2084 (or (eobp) (forward-char)))
2087 ;; ; Unsigned 32-bit integer
2088 ;; ; (0 <= n < 4,294,967,296)
2090 (defsubst imap-parse-number ()
2091 (when (looking-at "[0-9]+")
2093 (string-to-number (match-string 0))
2094 (goto-char (match-end 0)))))
2096 ;; literal = "{" number "}" CRLF *CHAR8
2097 ;; ; Number represents the number of CHAR8s
2099 (defsubst imap-parse-literal ()
2100 (when (looking-at "{\\([0-9]+\\)}\r\n")
2101 (let ((pos (match-end 0))
2102 (len (string-to-number (match-string 1))))
2103 (if (< (point-max) (+ pos len))
2105 (goto-char (+ pos len))
2106 (buffer-substring pos (+ pos len))))))
2108 ;; string = quoted / literal
2110 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
2112 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2113 ;; "\" quoted-specials
2115 ;; quoted-specials = DQUOTE / "\"
2117 ;; TEXT-CHAR = <any CHAR except CR and LF>
2119 (defsubst imap-parse-string ()
2120 (cond ((eq (char-after) ?\")
2122 (let ((p (point)) (name ""))
2123 (skip-chars-forward "^\"\\\\")
2124 (setq name (buffer-substring p (point)))
2125 (while (eq (char-after) ?\\)
2126 (setq p (1+ (point)))
2128 (skip-chars-forward "^\"\\\\")
2129 (setq name (concat name (buffer-substring p (point)))))
2132 ((eq (char-after) ?{)
2133 (imap-parse-literal))))
2137 (defsubst imap-parse-nil ()
2138 (if (looking-at "NIL")
2139 (goto-char (match-end 0))))
2141 ;; nstring = string / nil
2143 (defsubst imap-parse-nstring ()
2144 (or (imap-parse-string)
2145 (and (imap-parse-nil)
2148 ;; astring = atom / string
2150 ;; atom = 1*ATOM-CHAR
2152 ;; ATOM-CHAR = <any CHAR except atom-specials>
2154 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
2157 ;; list-wildcards = "%" / "*"
2159 ;; quoted-specials = DQUOTE / "\"
2161 (defsubst imap-parse-astring ()
2162 (or (imap-parse-string)
2163 (buffer-substring (point)
2164 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2165 (goto-char (1- (match-end 0)))
2169 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
2172 ;; addr-adl = nstring
2173 ;; ; Holds route from [RFC-822] route-addr if
2176 ;; addr-host = nstring
2177 ;; ; nil indicates [RFC-822] group syntax.
2178 ;; ; Otherwise, holds [RFC-822] domain name
2180 ;; addr-mailbox = nstring
2181 ;; ; nil indicates end of [RFC-822] group; if
2182 ;; ; non-nil and addr-host is nil, holds
2183 ;; ; [RFC-822] group name.
2184 ;; ; Otherwise, holds [RFC-822] local-part
2185 ;; ; after removing [RFC-822] quoting
2187 ;; addr-name = nstring
2188 ;; ; If non-nil, holds phrase from [RFC-822]
2189 ;; ; mailbox after removing [RFC-822] quoting
2192 (defsubst imap-parse-address ()
2194 (when (eq (char-after) ?\()
2196 (setq address (vector (prog1 (imap-parse-nstring)
2198 (prog1 (imap-parse-nstring)
2200 (prog1 (imap-parse-nstring)
2202 (imap-parse-nstring)))
2203 (when (eq (char-after) ?\))
2207 ;; address-list = "(" 1*address ")" / nil
2211 (defsubst imap-parse-address-list ()
2212 (if (eq (char-after) ?\()
2213 (let (address addresses)
2215 (while (and (not (eq (char-after) ?\)))
2216 ;; next line for MS Exchange bug
2217 (progn (and (eq (char-after) ? ) (imap-forward)) t)
2218 (setq address (imap-parse-address)))
2219 (setq addresses (cons address addresses)))
2220 (when (eq (char-after) ?\))
2222 (nreverse addresses)))
2223 ;; With assert, the code might not be eval'd.
2224 ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2227 ;; mailbox = "INBOX" / astring
2228 ;; ; INBOX is case-insensitive. All case variants of
2229 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2230 ;; ; not as an astring. An astring which consists of
2231 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
2232 ;; ; is considered to be INBOX and not an astring.
2233 ;; ; Refer to section 5.1 for further
2234 ;; ; semantic details of mailbox names.
2236 (defsubst imap-parse-mailbox ()
2237 (let ((mailbox (imap-parse-astring)))
2238 (if (string-equal "INBOX" (upcase mailbox))
2242 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2244 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
2245 ;; ; Authentication condition
2247 ;; resp-cond-bye = "BYE" SP resp-text
2249 (defun imap-parse-greeting ()
2250 "Parse an IMAP greeting."
2251 (cond ((looking-at "\\* OK ")
2252 (setq imap-state 'nonauth))
2253 ((looking-at "\\* PREAUTH ")
2254 (setq imap-state 'auth))
2255 ((looking-at "\\* BYE ")
2256 (setq imap-state 'closed))))
2258 ;; response = *(continue-req / response-data) response-done
2260 ;; continue-req = "+" SP (resp-text / base64) CRLF
2262 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
2263 ;; mailbox-data / message-data / capability-data) CRLF
2265 ;; response-done = response-tagged / response-fatal
2267 ;; response-fatal = "*" SP resp-cond-bye CRLF
2268 ;; ; Server closes connection immediately
2270 ;; response-tagged = tag SP resp-cond-state CRLF
2272 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2273 ;; ; Status condition
2275 ;; resp-cond-bye = "BYE" SP resp-text
2277 ;; mailbox-data = "FLAGS" SP flag-list /
2278 ;; "LIST" SP mailbox-list /
2279 ;; "LSUB" SP mailbox-list /
2280 ;; "SEARCH" *(SP nz-number) /
2281 ;; "STATUS" SP mailbox SP "("
2282 ;; [status-att SP number *(SP status-att SP number)] ")" /
2283 ;; number SP "EXISTS" /
2284 ;; number SP "RECENT"
2286 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2288 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2290 ;; ; IMAP4rev1 servers which offer RFC 1730
2291 ;; ; compatibility MUST list "IMAP4" as the first
2294 (defun imap-parse-response ()
2295 "Parse a IMAP command response."
2297 (case (setq token (read (current-buffer)))
2298 (+ (setq imap-continuation
2299 (or (buffer-substring (min (point-max) (1+ (point)))
2302 (* (case (prog1 (setq token (read (current-buffer)))
2304 (OK (imap-parse-resp-text))
2305 (NO (imap-parse-resp-text))
2306 (BAD (imap-parse-resp-text))
2307 (BYE (imap-parse-resp-text))
2308 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
2309 (LIST (imap-parse-data-list 'list))
2310 (LSUB (imap-parse-data-list 'lsub))
2311 (SEARCH (imap-mailbox-put
2313 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2314 (STATUS (imap-parse-status))
2315 (CAPABILITY (setq imap-capability
2316 (read (concat "(" (upcase (buffer-substring
2317 (point) (point-max)))
2319 (ID (setq imap-id (read (buffer-substring (point)
2321 (ACL (imap-parse-acl))
2322 (t (case (prog1 (read (current-buffer))
2324 (EXISTS (imap-mailbox-put 'exists token))
2325 (RECENT (imap-mailbox-put 'recent token))
2327 (FETCH (imap-parse-fetch token))
2328 (t (message "Garbage: %s" (buffer-string)))))))
2330 (if (not (integerp token))
2331 (message "Garbage: %s" (buffer-string))
2332 (case (prog1 (setq status (read (current-buffer)))
2335 (setq imap-reached-tag (max imap-reached-tag token))
2336 (imap-parse-resp-text)))
2338 (setq imap-reached-tag (max imap-reached-tag token))
2340 (imap-parse-resp-text))
2342 (when (eq (char-after) ?\[)
2343 (setq code (buffer-substring (point)
2344 (search-forward "]")))
2346 (setq text (buffer-substring (point) (point-max)))
2347 (push (list token status code text)
2348 imap-failed-tags))))
2350 (setq imap-reached-tag (max imap-reached-tag token))
2352 (imap-parse-resp-text))
2354 (when (eq (char-after) ?\[)
2355 (setq code (buffer-substring (point)
2356 (search-forward "]")))
2358 (setq text (buffer-substring (point) (point-max)))
2359 (push (list token status code text) imap-failed-tags)
2360 (error "Internal error, tag %s status %s code %s text %s"
2361 token status code text))))
2362 (t (message "Garbage: %s" (buffer-string))))
2363 (when (assq token imap-callbacks)
2364 (funcall (cdr (assq token imap-callbacks)) token status)
2365 (setq imap-callbacks
2366 (imap-remassoc token imap-callbacks)))))))))
2368 ;; resp-text = ["[" resp-text-code "]" SP] text
2370 ;; text = 1*TEXT-CHAR
2372 ;; TEXT-CHAR = <any CHAR except CR and LF>
2374 (defun imap-parse-resp-text ()
2375 (imap-parse-resp-text-code))
2377 ;; resp-text-code = "ALERT" /
2378 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2379 ;; "NEWNAME" SP string SP string /
2381 ;; "PERMANENTFLAGS" SP "("
2382 ;; [flag-perm *(SP flag-perm)] ")" /
2386 ;; "UIDNEXT" SP nz-number /
2387 ;; "UIDVALIDITY" SP nz-number /
2388 ;; "UNSEEN" SP nz-number /
2389 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2391 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2393 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2395 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2397 ;; ; Identifies a set of messages. For message
2398 ;; ; sequence numbers, these are consecutive
2399 ;; ; numbers from 1 to the number of messages in
2401 ;; ; Comma delimits individual numbers, colon
2402 ;; ; delimits between two numbers inclusive.
2403 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2404 ;; ; 14,15 for a mailbox with 15 messages.
2406 ;; sequence-num = nz-number / "*"
2407 ;; ; * is the largest number in use. For message
2408 ;; ; sequence numbers, it is the number of messages
2409 ;; ; in the mailbox. For unique identifiers, it is
2410 ;; ; the unique identifier of the last message in
2413 ;; flag-perm = flag / "\*"
2415 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2416 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2417 ;; ; Does not include "\Recent"
2419 ;; flag-extension = "\" atom
2420 ;; ; Future expansion. Client implementations
2421 ;; ; MUST accept flag-extension flags. Server
2422 ;; ; implementations MUST NOT generate
2423 ;; ; flag-extension flags except as defined by
2424 ;; ; future standard or standards-track
2425 ;; ; revisions of this specification.
2427 ;; flag-keyword = atom
2429 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2431 (defun imap-parse-resp-text-code ()
2432 ;; xxx next line for stalker communigate pro 3.3.1 bug
2433 (when (looking-at " \\[")
2435 (when (eq (char-after) ?\[)
2437 (cond ((search-forward "PERMANENTFLAGS " nil t)
2438 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2439 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2440 (imap-mailbox-put 'uidnext (match-string 1)))
2441 ((search-forward "UNSEEN " nil t)
2442 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2443 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2444 (imap-mailbox-put 'uidvalidity (match-string 1)))
2445 ((search-forward "READ-ONLY" nil t)
2446 (imap-mailbox-put 'read-only t))
2447 ((search-forward "NEWNAME " nil t)
2448 (let (oldname newname)
2449 (setq oldname (imap-parse-string))
2451 (setq newname (imap-parse-string))
2452 (imap-mailbox-put 'newname newname oldname)))
2453 ((search-forward "TRYCREATE" nil t)
2454 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2455 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2456 (imap-mailbox-put 'appenduid
2457 (list (match-string 1)
2458 (string-to-number (match-string 2)))
2459 imap-current-target-mailbox))
2460 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2461 (imap-mailbox-put 'copyuid (list (match-string 1)
2464 imap-current-target-mailbox))
2465 ((search-forward "ALERT] " nil t)
2466 (message "Imap server %s information: %s" imap-server
2467 (buffer-substring (point) (point-max)))))))
2469 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2470 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2472 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2473 ;; *(SP mbx-list-oflag) /
2474 ;; mbx-list-oflag *(SP mbx-list-oflag)
2476 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2477 ;; ; Other flags; multiple possible per LIST response
2479 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2480 ;; ; Selectability flags; only one per LIST response
2482 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2483 ;; "\" quoted-specials
2485 ;; quoted-specials = DQUOTE / "\"
2487 (defun imap-parse-data-list (type)
2488 (let (flags delimiter mailbox)
2489 (setq flags (imap-parse-flag-list))
2490 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2491 (setq delimiter (match-string 1))
2492 (goto-char (1+ (match-end 0)))
2493 (when (setq mailbox (imap-parse-mailbox))
2494 (imap-mailbox-put type t mailbox)
2495 (imap-mailbox-put 'list-flags flags mailbox)
2496 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2498 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2499 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2500 ;; "INTERNALDATE" SPACE date_time /
2501 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2502 ;; "RFC822.SIZE" SPACE number /
2503 ;; "BODY" ["STRUCTURE"] SPACE body /
2504 ;; "BODY" section ["<" number ">"] SPACE nstring /
2505 ;; "UID" SPACE uniqueid) ")"
2507 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2508 ;; SPACE time SPACE zone <">
2510 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2511 ;; ["." (section_text / "MIME")])] "]"
2513 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2514 ;; SPACE header_list / "TEXT"
2516 ;; header_fld_name ::= astring
2518 ;; header_list ::= "(" 1#header_fld_name ")"
2520 (defsubst imap-parse-header-list ()
2521 (when (eq (char-after) ?\()
2523 (while (not (eq (char-after) ?\)))
2525 (push (imap-parse-astring) strlist))
2527 (nreverse strlist))))
2529 (defsubst imap-parse-fetch-body-section ()
2531 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2532 (if (eq (char-before) ? )
2534 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2535 (search-forward "]" nil t))
2538 (defun imap-parse-fetch (response)
2539 (when (eq (char-after) ?\()
2540 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2541 rfc822size body bodydetail bodystructure flags-empty)
2542 (while (not (eq (char-after) ?\)))
2544 (let ((token (read (current-buffer))))
2546 (cond ((eq token 'UID)
2547 (setq uid (condition-case ()
2548 (read (current-buffer))
2551 (setq flags (imap-parse-flag-list))
2553 (setq flags-empty 't)))
2554 ((eq token 'ENVELOPE)
2555 (setq envelope (imap-parse-envelope)))
2556 ((eq token 'INTERNALDATE)
2557 (setq internaldate (imap-parse-string)))
2559 (setq rfc822 (imap-parse-nstring)))
2560 ((eq token 'RFC822.HEADER)
2561 (setq rfc822header (imap-parse-nstring)))
2562 ((eq token 'RFC822.TEXT)
2563 (setq rfc822text (imap-parse-nstring)))
2564 ((eq token 'RFC822.SIZE)
2565 (setq rfc822size (read (current-buffer))))
2567 (if (eq (char-before) ?\[)
2569 (upcase (imap-parse-fetch-body-section))
2570 (and (eq (char-after) ?<)
2571 (buffer-substring (1+ (point))
2572 (search-forward ">" nil t)))
2573 (progn (imap-forward)
2574 (imap-parse-nstring)))
2576 (setq body (imap-parse-body))))
2577 ((eq token 'BODYSTRUCTURE)
2578 (setq bodystructure (imap-parse-body))))))
2580 (setq imap-current-message uid)
2581 (imap-message-put uid 'UID uid)
2582 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2583 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2584 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2585 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2586 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2587 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2588 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2589 (and body (imap-message-put uid 'BODY body))
2590 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2591 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2592 (run-hooks 'imap-fetch-data-hook)))))
2594 ;; mailbox-data = ...
2595 ;; "STATUS" SP mailbox SP "("
2596 ;; [status-att SP number
2597 ;; *(SP status-att SP number)] ")"
2600 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2603 (defun imap-parse-status ()
2604 (let ((mailbox (imap-parse-mailbox)))
2605 (if (eq (char-after) ? )
2607 (when (and mailbox (eq (char-after) ?\())
2608 (while (and (not (eq (char-after) ?\)))
2609 (or (forward-char) t)
2610 (looking-at "\\([A-Za-z]+\\) "))
2611 (let ((token (upcase (match-string 1))))
2612 (goto-char (match-end 0))
2613 (cond ((string= token "MESSAGES")
2614 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2615 ((string= token "RECENT")
2616 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2617 ((string= token "UIDNEXT")
2618 (and (looking-at "[0-9]+")
2619 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2620 (goto-char (match-end 0))))
2621 ((string= token "UIDVALIDITY")
2622 (and (looking-at "[0-9]+")
2623 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2624 (goto-char (match-end 0))))
2625 ((string= token "UNSEEN")
2626 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2628 (message "Unknown status data %s in mailbox %s ignored"
2630 (read (current-buffer)))))))))
2632 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2635 ;; identifier ::= astring
2637 ;; rights ::= astring
2639 (defun imap-parse-acl ()
2640 (let ((mailbox (imap-parse-mailbox))
2641 identifier rights acl)
2642 (while (eq (char-after) ?\ )
2644 (setq identifier (imap-parse-astring))
2646 (setq rights (imap-parse-astring))
2647 (setq acl (append acl (list (cons identifier rights)))))
2648 (imap-mailbox-put 'acl acl mailbox)))
2650 ;; flag-list = "(" [flag *(SP flag)] ")"
2652 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2653 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2654 ;; ; Does not include "\Recent"
2656 ;; flag-keyword = atom
2658 ;; flag-extension = "\" atom
2659 ;; ; Future expansion. Client implementations
2660 ;; ; MUST accept flag-extension flags. Server
2661 ;; ; implementations MUST NOT generate
2662 ;; ; flag-extension flags except as defined by
2663 ;; ; future standard or standards-track
2664 ;; ; revisions of this specification.
2666 (defun imap-parse-flag-list ()
2667 (let (flag-list start)
2668 (assert (eq (char-after) ?\() nil "In imap-parse-flag-list 1")
2669 (while (and (not (eq (char-after) ?\)))
2672 ;; next line for Courier IMAP bug.
2673 (skip-chars-forward " ")
2675 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2676 (push (buffer-substring start (point)) flag-list))
2677 (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list 2")
2679 (nreverse flag-list)))
2681 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2682 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2683 ;; env-in-reply-to SP env-message-id ")"
2685 ;; env-bcc = "(" 1*address ")" / nil
2687 ;; env-cc = "(" 1*address ")" / nil
2689 ;; env-date = nstring
2691 ;; env-from = "(" 1*address ")" / nil
2693 ;; env-in-reply-to = nstring
2695 ;; env-message-id = nstring
2697 ;; env-reply-to = "(" 1*address ")" / nil
2699 ;; env-sender = "(" 1*address ")" / nil
2701 ;; env-subject = nstring
2703 ;; env-to = "(" 1*address ")" / nil
2705 (defun imap-parse-envelope ()
2706 (when (eq (char-after) ?\()
2708 (vector (prog1 (imap-parse-nstring) ;; date
2710 (prog1 (imap-parse-nstring) ;; subject
2712 (prog1 (imap-parse-address-list) ;; from
2714 (prog1 (imap-parse-address-list) ;; sender
2716 (prog1 (imap-parse-address-list) ;; reply-to
2718 (prog1 (imap-parse-address-list) ;; to
2720 (prog1 (imap-parse-address-list) ;; cc
2722 (prog1 (imap-parse-address-list) ;; bcc
2724 (prog1 (imap-parse-nstring) ;; in-reply-to
2726 (prog1 (imap-parse-nstring) ;; message-id
2729 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2731 (defsubst imap-parse-string-list ()
2732 (cond ((eq (char-after) ?\() ;; body-fld-param
2735 (while (setq str (imap-parse-string))
2737 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2738 ;; between body-fld-param's sometimes
2739 (or (eq (char-after) ?\")
2741 (nreverse strlist)))
2745 ;; body-extension = nstring / number /
2746 ;; "(" body-extension *(SP body-extension) ")"
2747 ;; ; Future expansion. Client implementations
2748 ;; ; MUST accept body-extension fields. Server
2749 ;; ; implementations MUST NOT generate
2750 ;; ; body-extension fields except as defined by
2751 ;; ; future standard or standards-track
2752 ;; ; revisions of this specification.
2754 (defun imap-parse-body-extension ()
2755 (if (eq (char-after) ?\()
2758 (push (imap-parse-body-extension) b-e)
2759 (while (eq (char-after) ?\ )
2761 (push (imap-parse-body-extension) b-e))
2762 (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2765 (or (imap-parse-number)
2766 (imap-parse-nstring))))
2768 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2769 ;; *(SP body-extension)]]
2770 ;; ; MUST NOT be returned on non-extensible
2773 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2774 ;; *(SP body-extension)]]
2775 ;; ; MUST NOT be returned on non-extensible
2778 (defsubst imap-parse-body-ext ()
2780 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2783 (if (eq (char-after) ?\()
2786 (push (imap-parse-string) dsp)
2788 (push (imap-parse-string-list) dsp)
2790 ;; With assert, the code might not be eval'd.
2791 ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2793 (push (nreverse dsp) ext))
2794 (when (eq (char-after) ?\ ) ;; body-fld-lang
2796 (if (eq (char-after) ?\()
2797 (push (imap-parse-string-list) ext)
2798 (push (imap-parse-nstring) ext))
2799 (while (eq (char-after) ?\ ) ;; body-extension
2801 (setq ext (append (imap-parse-body-extension) ext)))))
2804 ;; body = "(" body-type-1part / body-type-mpart ")"
2806 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2807 ;; *(SP body-extension)]]
2808 ;; ; MUST NOT be returned on non-extensible
2811 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2812 ;; *(SP body-extension)]]
2813 ;; ; MUST NOT be returned on non-extensible
2816 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2817 ;; body-fld-enc SP body-fld-octets
2819 ;; body-fld-desc = nstring
2821 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2823 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2824 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2826 ;; body-fld-id = nstring
2828 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2830 ;; body-fld-lines = number
2832 ;; body-fld-md5 = nstring
2834 ;; body-fld-octets = number
2836 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2838 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2839 ;; [SP body-ext-1part]
2841 ;; body-type-basic = media-basic SP body-fields
2842 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2844 ;; body-type-msg = media-message SP body-fields SP envelope
2845 ;; SP body SP body-fld-lines
2847 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2849 ;; body-type-mpart = 1*body SP media-subtype
2850 ;; [SP body-ext-mpart]
2852 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2853 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2854 ;; ; Defined in [MIME-IMT]
2856 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2857 ;; ; Defined in [MIME-IMT]
2859 ;; media-subtype = string
2860 ;; ; Defined in [MIME-IMT]
2862 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2863 ;; ; Defined in [MIME-IMT]
2865 (defun imap-parse-body ()
2867 (when (eq (char-after) ?\()
2869 (if (eq (char-after) ?\()
2871 (while (and (eq (char-after) ?\()
2872 (setq subbody (imap-parse-body)))
2873 ;; buggy stalker communigate pro 3.0 inserts a SPC between
2874 ;; parts in multiparts
2875 (when (and (eq (char-after) ?\ )
2876 (eq (char-after (1+ (point))) ?\())
2878 (push subbody body))
2880 (push (imap-parse-string) body) ;; media-subtype
2881 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2883 (if (eq (char-after) ?\() ;; body-fld-param
2884 (push (imap-parse-string-list) body)
2885 (push (and (imap-parse-nil) nil) body))
2887 (append (imap-parse-body-ext) body))) ;; body-ext-...
2888 (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2892 (push (imap-parse-string) body) ;; media-type
2894 (push (imap-parse-string) body) ;; media-subtype
2896 ;; next line for Sun SIMS bug
2897 (and (eq (char-after) ? ) (imap-forward))
2898 (if (eq (char-after) ?\() ;; body-fld-param
2899 (push (imap-parse-string-list) body)
2900 (push (and (imap-parse-nil) nil) body))
2902 (push (imap-parse-nstring) body) ;; body-fld-id
2904 (push (imap-parse-nstring) body) ;; body-fld-desc
2906 ;; Next `or' for Sun SIMS bug. It regards body-fld-enc as a
2907 ;; nstring and returns nil instead of defaulting back to 7BIT
2908 ;; as the standard says.
2909 ;; Exchange (2007, at least) does this as well.
2910 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2912 ;; Exchange 2007 can return -1, contrary to the spec...
2913 (if (eq (char-after) ?-)
2915 (skip-chars-forward "-0-9")
2917 (push (imap-parse-number) body)) ;; body-fld-octets
2919 ;; Ok, we're done parsing the required parts, what comes now is one of
2922 ;; envelope (then we're parsing body-type-msg)
2923 ;; body-fld-lines (then we're parsing body-type-text)
2924 ;; body-ext-1part (then we're parsing body-type-basic)
2926 ;; The problem is that the two first are in turn optionally followed
2927 ;; by the third. So we parse the first two here (if there are any)...
2929 (when (eq (char-after) ?\ )
2932 (cond ((eq (char-after) ?\() ;; body-type-msg:
2933 (push (imap-parse-envelope) body) ;; envelope
2935 (push (imap-parse-body) body) ;; body
2936 ;; buggy stalker communigate pro 3.0 doesn't print
2937 ;; number of lines in message/rfc822 attachment
2938 (if (eq (char-after) ?\))
2941 (push (imap-parse-number) body))) ;; body-fld-lines
2942 ((setq lines (imap-parse-number)) ;; body-type-text:
2943 (push lines body)) ;; body-fld-lines
2945 (backward-char))))) ;; no match...
2947 ;; ...and then parse the third one here...
2949 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2951 (push (imap-parse-nstring) body) ;; body-fld-md5
2952 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2954 (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2958 (when imap-debug ; (untrace-all)
2960 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2961 (mapc (lambda (f) (trace-function-background f imap-debug-buffer))
2972 imap-interactive-login
2989 imap-send-command-wait
2994 imap-current-mailbox
2995 imap-current-mailbox-p-1
2996 imap-current-mailbox-p
2997 imap-mailbox-select-1
2999 imap-mailbox-examine-1
3000 imap-mailbox-examine
3001 imap-mailbox-unselect
3002 imap-mailbox-expunge
3004 imap-mailbox-create-1
3010 imap-mailbox-subscribe
3011 imap-mailbox-unsubscribe
3013 imap-mailbox-acl-get
3014 imap-mailbox-acl-set
3015 imap-mailbox-acl-delete
3016 imap-current-message
3017 imap-list-to-message-set
3024 imap-message-flag-permanent-p
3025 imap-message-flags-set
3026 imap-message-flags-del
3027 imap-message-flags-add
3028 imap-message-copyuid-1
3029 imap-message-copyuid
3031 imap-message-appenduid-1
3032 imap-message-appenduid
3044 imap-parse-resp-text
3045 imap-parse-resp-text-code
3046 imap-parse-data-list
3050 imap-parse-flag-list
3052 imap-parse-body-extension
3058 ;; arch-tag: 27369ed6-33e4-482f-96f1-8bb906ba70f7
3059 ;;; imap.el ends here