1 ;;; imap.el --- imap library
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008 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 control type of device
216 used to communicate with subprocesses. Values are nil to use a
217 pipe, or t or `pty' to use a pty. The value has no effect if the
218 system has no ptys or if all ptys are busy: then a pipe is used
219 in any case. The value takes effect when a IMAP server is
220 opened, changing it after that has no effect."
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, random debug spews are placed in *imap-debug* buffer.
246 Note that username, passwords and other privacy sensitive
247 information (such as e-mail) may be stored in the *imap-debug*
248 buffer. It is not written to disk, however. Do not enable this
249 variable unless you are comfortable with that.
251 This variable only takes effect when loading the `imap' library.
252 See also `imap-log'."
256 (defcustom imap-shell-host "gateway"
257 "Hostname of rlogin proxy."
261 (defcustom imap-default-user (user-login-name)
262 "Default username to use."
266 (defcustom imap-read-timeout (if (string-match
267 "windows-nt\\|os/2\\|emx\\|cygwin"
268 (symbol-name system-type))
271 "*How long to wait between checking for the end of output.
272 Shorter values mean quicker response, but is more CPU intensive."
276 (defcustom imap-store-password nil
277 "If non-nil, store session password without prompting."
281 ;; Various variables.
283 (defvar imap-fetch-data-hook nil
284 "Hooks called after receiving each FETCH response.")
286 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
287 "Priority of streams to consider when opening connection to server.")
289 (defvar imap-stream-alist
290 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
291 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
292 (tls imap-tls-p imap-tls-open)
293 (ssl imap-ssl-p imap-ssl-open)
294 (network imap-network-p imap-network-open)
295 (shell imap-shell-p imap-shell-open)
296 (starttls imap-starttls-p imap-starttls-open))
297 "Definition of network streams.
301 NAME names the stream, CHECK is a function returning non-nil if the
302 server support the stream and OPEN is a function for opening the
305 (defvar imap-authenticators '(gssapi
312 "Priority of authenticators to consider when authenticating to server.")
314 (defvar imap-authenticator-alist
315 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
316 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
317 (sasl imap-sasl-auth-p imap-sasl-auth)
318 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
319 (login imap-login-p imap-login-auth)
320 (anonymous imap-anonymous-p imap-anonymous-auth)
321 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
322 "Definition of authenticators.
324 \(NAME CHECK AUTHENTICATE)
326 NAME names the authenticator. CHECK is a function returning non-nil if
327 the server support the authenticator and AUTHENTICATE is a function
328 for doing the actual authentication.")
330 (defvar imap-error nil
331 "Error codes from the last command.")
333 (defvar imap-logout-timeout nil
334 "Close server immediately if it can't logout in this number of seconds.
335 If it is nil, never close server until logout completes. Normally,
336 the value of this variable will be bound to a certain value to which
337 an application program that uses this module specifies on a per-server
340 ;; Internal constants. Change these and die.
342 (defconst imap-default-port 143)
343 (defconst imap-default-ssl-port 993)
344 (defconst imap-default-tls-port 993)
345 (defconst imap-default-stream 'network)
346 (defconst imap-coding-system-for-read 'binary)
347 (defconst imap-coding-system-for-write 'binary)
348 (defconst imap-local-variables '(imap-server
357 imap-current-target-mailbox
367 imap-calculate-literal-size-first
369 (defconst imap-log-buffer "*imap-log*")
370 (defconst imap-debug-buffer "*imap-debug*")
372 ;; Internal variables.
374 (defvar imap-stream nil)
375 (defvar imap-auth nil)
376 (defvar imap-server nil)
377 (defvar imap-port nil)
378 (defvar imap-username nil)
379 (defvar imap-password nil)
380 (defvar imap-calculate-literal-size-first nil)
381 (defvar imap-state 'closed
383 Valid states are `closed', `initial', `nonauth', `auth', `selected'
386 (defvar imap-server-eol "\r\n"
387 "The EOL string sent from the server.")
389 (defvar imap-client-eol "\r\n"
390 "The EOL string we send to the server.")
392 (defvar imap-current-mailbox nil
393 "Current mailbox name.")
395 (defvar imap-current-target-mailbox nil
396 "Current target mailbox for COPY and APPEND commands.")
398 (defvar imap-mailbox-data nil
399 "Obarray with mailbox data.")
401 (defvar imap-mailbox-prime 997
402 "Length of `imap-mailbox-data'.")
404 (defvar imap-current-message nil
405 "Current message number.")
407 (defvar imap-message-data nil
408 "Obarray with message data.")
410 (defvar imap-message-prime 997
411 "Length of `imap-message-data'.")
413 (defvar imap-capability nil
414 "Capability for server.")
420 (defvar imap-namespace nil
421 "Namespace for current server.")
423 (defvar imap-reached-tag 0
424 "Lower limit on command tags that have been parsed.")
426 (defvar imap-failed-tags nil
427 "Alist of tags that failed.
428 Each element is a list with four elements; tag (a integer), response
429 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
430 human readable response text (a string).")
433 "Command tag number.")
435 (defvar imap-process nil
438 (defvar imap-continuation nil
439 "Non-nil indicates that the server emitted a continuation request.
440 The actual value is really the text on the continuation line.")
442 (defvar imap-callbacks nil
443 "List of response tags and callbacks, on the form `(number . function)'.
444 The function should take two arguments, the first the IMAP tag and the
445 second the status (OK, NO, BAD etc) of the command.")
447 (defvar imap-enable-exchange-bug-workaround nil
448 "Send FETCH UID commands as *:* instead of *.
449 Enabling this appears to be required for some servers (e.g.,
450 Microsoft Exchange) which otherwise would trigger a response 'BAD
451 The specified message set is invalid.'.")
454 ;; Utility functions:
456 (defun imap-remassoc (key alist)
457 "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
458 The modified ALIST is returned. If the first member
459 of ALIST has a car that is `equal' to KEY, there is no way to remove it
460 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
461 sure of changing the value of `foo'."
463 (if (equal key (caar alist))
465 (setcdr alist (imap-remassoc key (cdr alist)))
468 (defsubst imap-disable-multibyte ()
469 "Enable multibyte in the current buffer."
470 (when (fboundp 'set-buffer-multibyte)
471 (set-buffer-multibyte nil)))
473 (defsubst imap-utf7-encode (string)
477 (utf7-encode string t)
479 "imap: Could not UTF7 encode `%s', using it unencoded..."
484 (defsubst imap-utf7-decode (string)
488 (utf7-decode string t)
490 "imap: Could not UTF7 decode `%s', using it undecoded..."
495 (defsubst imap-ok-p (status)
498 (setq imap-error status)
501 (defun imap-error-text (&optional buffer)
502 (with-current-buffer (or buffer (current-buffer))
503 (nth 3 (car imap-failed-tags))))
506 ;; Server functions; stream stuff:
508 (defun imap-kerberos4-stream-p (buffer)
509 (imap-capability 'AUTH=KERBEROS_V4 buffer))
511 (defun imap-kerberos4-open (name buffer server port)
512 (let ((cmds imap-kerberos4-program)
514 (while (and (not done) (setq cmd (pop cmds)))
515 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
517 (let* ((port (or port imap-default-port))
518 (coding-system-for-read imap-coding-system-for-read)
519 (coding-system-for-write imap-coding-system-for-write)
520 (process-connection-type imap-process-connection-type)
521 (process (start-process
522 name buffer shell-file-name shell-command-switch
527 ?p (number-to-string port)
528 ?l imap-default-user))))
531 (with-current-buffer buffer
532 (setq imap-client-eol "\n"
533 imap-calculate-literal-size-first t)
534 (while (and (memq (process-status process) '(open run))
535 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
536 (goto-char (point-min))
537 ;; Athena IMTEST can output SSL verify errors
538 (or (while (looking-at "^verify error:num=")
541 (or (while (looking-at "^TLS connection established")
544 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
545 (or (while (looking-at "^C:")
548 ;; cyrus 1.6 imtest print "S: " before server greeting
549 (or (not (looking-at "S: "))
552 (not (and (imap-parse-greeting)
553 ;; success in imtest < 1.6:
554 (or (re-search-forward
555 "^__\\(.*\\)__\n" nil t)
556 ;; success in imtest 1.6:
558 "^\\(Authenticat.*\\)" nil t))
559 (setq response (match-string 1)))))
560 (accept-process-output process 1)
563 (with-current-buffer (get-buffer-create imap-log-buffer)
564 (imap-disable-multibyte)
565 (buffer-disable-undo)
566 (goto-char (point-max))
567 (insert-buffer-substring buffer)))
569 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
570 (if response (concat "done, " response) "failed"))
571 (if (and response (let ((case-fold-search nil))
572 (not (string-match "failed" response))))
574 (if (memq (process-status process) '(open run))
576 (delete-process process)
580 (defun imap-gssapi-stream-p (buffer)
581 (imap-capability 'AUTH=GSSAPI buffer))
583 (defun imap-gssapi-open (name buffer server port)
584 (let ((cmds imap-gssapi-program)
586 (while (and (not done) (setq cmd (pop cmds)))
587 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
589 (let* ((port (or port imap-default-port))
590 (coding-system-for-read imap-coding-system-for-read)
591 (coding-system-for-write imap-coding-system-for-write)
592 (process-connection-type imap-process-connection-type)
593 (process (start-process
594 name buffer shell-file-name shell-command-switch
599 ?p (number-to-string port)
600 ?l imap-default-user))))
603 (with-current-buffer buffer
604 (setq imap-client-eol "\n"
605 imap-calculate-literal-size-first t)
606 (while (and (memq (process-status process) '(open run))
607 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
608 (goto-char (point-min))
609 ;; Athena IMTEST can output SSL verify errors
610 (or (while (looking-at "^verify error:num=")
613 (or (while (looking-at "^TLS connection established")
616 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
617 (or (while (looking-at "^C:")
620 ;; cyrus 1.6 imtest print "S: " before server greeting
621 (or (not (looking-at "S: "))
624 ;; GNU SASL may print 'Trying ...' first.
625 (or (not (looking-at "Trying "))
628 (not (and (imap-parse-greeting)
629 ;; success in imtest 1.6:
631 (concat "^\\(\\(Authenticat.*\\)\\|\\("
632 "Client authentication "
635 (setq response (match-string 1)))))
636 (accept-process-output process 1)
639 (with-current-buffer (get-buffer-create imap-log-buffer)
640 (imap-disable-multibyte)
641 (buffer-disable-undo)
642 (goto-char (point-max))
643 (insert-buffer-substring buffer)))
645 (message "GSSAPI IMAP connection: %s" (or response "failed"))
646 (if (and response (let ((case-fold-search nil))
647 (not (string-match "failed" response))))
649 (if (memq (process-status process) '(open run))
651 (delete-process process)
655 (defun imap-ssl-p (buffer)
658 (defun imap-ssl-open (name buffer server port)
659 "Open an SSL connection to SERVER."
660 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
661 (list imap-ssl-program)))
663 (while (and (not done) (setq cmd (pop cmds)))
664 (message "imap: Opening SSL connection with `%s'..." cmd)
666 (let* ((port (or port imap-default-ssl-port))
667 (coding-system-for-read imap-coding-system-for-read)
668 (coding-system-for-write imap-coding-system-for-write)
669 (process-connection-type imap-process-connection-type)
670 (set-process-query-on-exit-flag
671 (if (fboundp 'set-process-query-on-exit-flag)
672 'set-process-query-on-exit-flag
673 'process-kill-without-query))
676 (setq process (start-process
677 name buffer shell-file-name
682 ?p (number-to-string port)))))
683 (funcall set-process-query-on-exit-flag process nil)
685 (with-current-buffer buffer
686 (goto-char (point-min))
687 (while (and (memq (process-status process) '(open run))
688 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
689 (goto-char (point-max))
691 (not (imap-parse-greeting)))
692 (accept-process-output process 1)
695 (with-current-buffer (get-buffer-create imap-log-buffer)
696 (imap-disable-multibyte)
697 (buffer-disable-undo)
698 (goto-char (point-max))
699 (insert-buffer-substring buffer)))
701 (when (memq (process-status process) '(open run))
702 (setq done process))))))
705 (message "imap: Opening SSL connection with `%s'...done" cmd)
707 (message "imap: Opening SSL connection with `%s'...failed" cmd)
710 (defun imap-tls-p (buffer)
713 (defun imap-tls-open (name buffer server port)
714 (let* ((port (or port imap-default-tls-port))
715 (coding-system-for-read imap-coding-system-for-read)
716 (coding-system-for-write imap-coding-system-for-write)
717 (process (open-tls-stream name buffer server port)))
719 (while (and (memq (process-status process) '(open run))
720 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
721 (goto-char (point-max))
723 (not (imap-parse-greeting)))
724 (accept-process-output process 1)
727 (with-current-buffer (get-buffer-create imap-log-buffer)
728 (imap-disable-multibyte)
729 (buffer-disable-undo)
730 (goto-char (point-max))
731 (insert-buffer-substring buffer)))
732 (when (memq (process-status process) '(open run))
735 (defun imap-network-p (buffer)
738 (defun imap-network-open (name buffer server port)
739 (let* ((port (or port imap-default-port))
740 (coding-system-for-read imap-coding-system-for-read)
741 (coding-system-for-write imap-coding-system-for-write)
742 (process (open-network-stream name buffer server port)))
744 (while (and (memq (process-status process) '(open run))
745 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
746 (goto-char (point-min))
747 (not (imap-parse-greeting)))
748 (accept-process-output process 1)
751 (with-current-buffer (get-buffer-create imap-log-buffer)
752 (imap-disable-multibyte)
753 (buffer-disable-undo)
754 (goto-char (point-max))
755 (insert-buffer-substring buffer)))
756 (when (memq (process-status process) '(open run))
759 (defun imap-shell-p (buffer)
762 (defun imap-shell-open (name buffer server port)
763 (let ((cmds (if (listp imap-shell-program) imap-shell-program
764 (list imap-shell-program)))
766 (while (and (not done) (setq cmd (pop cmds)))
767 (message "imap: Opening IMAP connection with `%s'..." cmd)
768 (setq imap-client-eol "\n")
769 (let* ((port (or port imap-default-port))
770 (coding-system-for-read imap-coding-system-for-read)
771 (coding-system-for-write imap-coding-system-for-write)
772 (process (start-process
773 name buffer shell-file-name shell-command-switch
779 ?p (number-to-string port)
780 ?l imap-default-user)))))
782 (while (and (memq (process-status process) '(open run))
783 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
784 (goto-char (point-max))
786 (not (imap-parse-greeting)))
787 (accept-process-output process 1)
790 (with-current-buffer (get-buffer-create imap-log-buffer)
791 (imap-disable-multibyte)
792 (buffer-disable-undo)
793 (goto-char (point-max))
794 (insert-buffer-substring buffer)))
796 (when (memq (process-status process) '(open run))
797 (setq done process)))))
800 (message "imap: Opening IMAP connection with `%s'...done" cmd)
802 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
805 (defun imap-starttls-p (buffer)
806 (imap-capability 'STARTTLS buffer))
808 (defun imap-starttls-open (name buffer server port)
809 (let* ((port (or port imap-default-port))
810 (coding-system-for-read imap-coding-system-for-read)
811 (coding-system-for-write imap-coding-system-for-write)
812 (process (starttls-open-stream name buffer server port))
814 (message "imap: Connecting with STARTTLS...")
816 (while (and (memq (process-status process) '(open run))
817 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
818 (goto-char (point-max))
820 (not (imap-parse-greeting)))
821 (accept-process-output process 1)
823 (imap-send-command "STARTTLS")
824 (while (and (memq (process-status process) '(open run))
825 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
826 (goto-char (point-max))
828 (not (re-search-forward "[0-9]+ OK.*\r?\n" nil t)))
829 (accept-process-output process 1)
832 (with-current-buffer (get-buffer-create imap-log-buffer)
833 (buffer-disable-undo)
834 (goto-char (point-max))
835 (insert-buffer-substring buffer)))
836 (when (and (setq tls-info (starttls-negotiate process))
837 (memq (process-status process) '(open run)))
838 (setq done process)))
839 (if (stringp tls-info)
840 (message "imap: STARTTLS info: %s" tls-info))
841 (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
844 ;; Server functions; authenticator stuff:
846 (defun imap-interactive-login (buffer loginfunc)
847 "Login to server in BUFFER.
848 LOGINFUNC is passed a username and a password, it should return t if
849 it where successful authenticating itself to the server, nil otherwise.
850 Returns t if login was successful, nil otherwise."
851 (with-current-buffer buffer
852 (make-local-variable 'imap-username)
853 (make-local-variable 'imap-password)
854 (let (user passwd ret)
855 ;; (condition-case ()
856 (while (or (not user) (not passwd))
857 (setq user (or imap-username
858 (read-from-minibuffer
859 (concat "IMAP username for " imap-server
860 " (using stream `" (symbol-name imap-stream)
862 (or user imap-default-user))))
863 (setq passwd (or imap-password
865 (concat "IMAP password for " user "@"
866 imap-server " (using authenticator `"
867 (symbol-name imap-auth) "'): "))))
868 (when (and user passwd)
869 (if (funcall loginfunc user passwd)
873 (when (and (not imap-password)
874 (or imap-store-password
875 (y-or-n-p "Store password for this session? ")))
876 (setq imap-password passwd)))
877 (message "Login failed...")
879 (setq imap-password nil)
881 ;; (quit (with-current-buffer buffer
884 ;; (error (with-current-buffer buffer
889 (defun imap-gssapi-auth-p (buffer)
890 (eq imap-stream 'gssapi))
892 (defun imap-gssapi-auth (buffer)
893 (message "imap: Authenticating using GSSAPI...%s"
894 (if (eq imap-stream 'gssapi) "done" "failed"))
895 (eq imap-stream 'gssapi))
897 (defun imap-kerberos4-auth-p (buffer)
898 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
899 (eq imap-stream 'kerberos4)))
901 (defun imap-kerberos4-auth (buffer)
902 (message "imap: Authenticating using Kerberos 4...%s"
903 (if (eq imap-stream 'kerberos4) "done" "failed"))
904 (eq imap-stream 'kerberos4))
906 (defun imap-cram-md5-p (buffer)
907 (imap-capability 'AUTH=CRAM-MD5 buffer))
909 (defun imap-cram-md5-auth (buffer)
910 "Login to server using the AUTH CRAM-MD5 method."
911 (message "imap: Authenticating using CRAM-MD5...")
912 (let ((done (imap-interactive-login
914 (lambda (user passwd)
916 (imap-send-command-wait
918 "AUTHENTICATE CRAM-MD5"
920 (let* ((decoded (base64-decode-string challenge))
921 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
922 (response (concat user " " hash))
923 (encoded (base64-encode-string response)))
926 (message "imap: Authenticating using CRAM-MD5...done")
927 (message "imap: Authenticating using CRAM-MD5...failed"))))
929 (defun imap-login-p (buffer)
930 (and (not (imap-capability 'LOGINDISABLED buffer))
931 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
933 (defun imap-quote-specials (string)
936 (goto-char (point-min))
937 (while (re-search-forward "[\\\"]" nil t)
943 (defun imap-login-auth (buffer)
944 "Login to server using the LOGIN command."
945 (message "imap: Plaintext authentication...")
946 (imap-interactive-login buffer
947 (lambda (user passwd)
948 (imap-ok-p (imap-send-command-wait
950 (imap-quote-specials user)
952 (imap-quote-specials passwd)
955 (defun imap-anonymous-p (buffer)
958 (defun imap-anonymous-auth (buffer)
959 (message "imap: Logging in anonymously...")
960 (with-current-buffer buffer
961 (imap-ok-p (imap-send-command-wait
962 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
963 (system-name)) "\"")))))
965 ;;; Compiler directives.
967 (defvar imap-sasl-client)
968 (defvar imap-sasl-step)
970 (defun imap-sasl-make-mechanisms (buffer)
973 (let ((name (symbol-name sym)))
974 (if (and (> (length name) 5)
975 (string-equal "AUTH=" (substring name 0 5 )))
976 (setq mecs (cons (substring name 5) mecs)))))
977 (imap-capability nil buffer))
980 (declare-function sasl-find-mechanism "sasl" (mechanism))
981 (declare-function sasl-mechanism-name "sasl" (mechanism))
982 (declare-function sasl-make-client "sasl" (mechanism name service server))
983 (declare-function sasl-next-step "sasl" (client step))
984 (declare-function sasl-step-data "sasl" (step))
985 (declare-function sasl-step-set-data "sasl" (step data))
987 (defun imap-sasl-auth-p (buffer)
988 (and (condition-case ()
991 (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
993 (defun imap-sasl-auth (buffer)
994 "Login to server using the SASL method."
995 (message "imap: Authenticating using SASL...")
996 (with-current-buffer buffer
997 (make-local-variable 'imap-username)
998 (make-local-variable 'imap-sasl-client)
999 (make-local-variable 'imap-sasl-step)
1000 (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
1003 (setq user (or imap-username
1004 (read-from-minibuffer
1005 (concat "IMAP username for " imap-server " using SASL "
1006 (sasl-mechanism-name mechanism) ": ")
1007 (or user imap-default-user))))
1009 (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
1010 imap-sasl-step (sasl-next-step imap-sasl-client nil))
1011 (let ((tag (imap-send-command
1012 (if (sasl-step-data imap-sasl-step)
1013 (format "AUTHENTICATE %s %s"
1014 (sasl-mechanism-name mechanism)
1015 (sasl-step-data imap-sasl-step))
1016 (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
1018 (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
1019 (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
1020 (setq imap-continuation nil
1021 imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
1022 (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
1023 (base64-encode-string (sasl-step-data imap-sasl-step) t)
1025 (if (imap-ok-p (imap-wait-for-tag tag))
1026 (setq imap-username user
1028 (message "Login failed...")
1032 (defun imap-digest-md5-p (buffer)
1033 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
1035 (require 'digest-md5)
1038 (defun imap-digest-md5-auth (buffer)
1039 "Login to server using the AUTH DIGEST-MD5 method."
1040 (message "imap: Authenticating using DIGEST-MD5...")
1041 (imap-interactive-login
1043 (lambda (user passwd)
1047 "AUTHENTICATE DIGEST-MD5"
1049 (digest-md5-parse-digest-challenge
1050 (base64-decode-string challenge))
1052 (digest-md5-digest-uri
1053 "imap" (digest-md5-challenge 'realm)))
1055 (digest-md5-digest-response
1056 user passwd digest-uri)))
1057 (base64-encode-string response 'no-line-break))))
1059 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1061 (setq imap-continuation nil)
1062 (imap-send-command-1 "")
1063 (imap-ok-p (imap-wait-for-tag tag)))))))
1065 ;; Server functions:
1067 (defun imap-open-1 (buffer)
1068 (with-current-buffer buffer
1070 (setq imap-current-mailbox nil
1071 imap-current-message nil
1073 imap-process (condition-case ()
1074 (funcall (nth 2 (assq imap-stream
1076 "imap" buffer imap-server imap-port)
1077 ((error quit) nil)))
1079 (set-process-filter imap-process 'imap-arrival-filter)
1080 (set-process-sentinel imap-process 'imap-sentinel)
1081 (while (and (eq imap-state 'initial)
1082 (memq (process-status imap-process) '(open run)))
1083 (message "Waiting for response from %s..." imap-server)
1084 (accept-process-output imap-process 1))
1085 (message "Waiting for response from %s...done" imap-server)
1086 (and (memq (process-status imap-process) '(open run))
1089 (defun imap-open (server &optional port stream auth buffer)
1090 "Open a IMAP connection to host SERVER at PORT returning a buffer.
1091 If PORT is unspecified, a default value is used (143 except
1092 for SSL which use 993).
1093 STREAM indicates the stream to use, see `imap-streams' for available
1094 streams. If nil, it choices the best stream the server is capable of.
1095 AUTH indicates authenticator to use, see `imap-authenticators' for
1096 available authenticators. If nil, it choices the best stream the
1097 server is capable of.
1098 BUFFER can be a buffer or a name of a buffer, which is created if
1099 necessary. If nil, the buffer name is generated."
1100 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1101 (with-current-buffer (get-buffer-create buffer)
1102 (if (imap-opened buffer)
1103 (imap-close buffer))
1104 (mapc 'make-local-variable imap-local-variables)
1105 (imap-disable-multibyte)
1106 (buffer-disable-undo)
1107 (setq imap-server (or server imap-server))
1108 (setq imap-port (or port imap-port))
1109 (setq imap-auth (or auth imap-auth))
1110 (setq imap-stream (or stream imap-stream))
1111 (message "imap: Connecting to %s..." imap-server)
1112 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1113 (imap-open-1 buffer)))
1115 (message "imap: Connecting to %s...failed" imap-server)
1117 (when (null imap-stream)
1118 ;; Need to choose stream.
1119 (let ((streams imap-streams))
1120 (while (setq stream (pop streams))
1121 ;; OK to use this stream?
1122 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1124 (if (not (eq imap-default-stream stream))
1125 (with-current-buffer (get-buffer-create
1126 (generate-new-buffer-name " *temp*"))
1127 (mapc 'make-local-variable imap-local-variables)
1128 (imap-disable-multibyte)
1129 (buffer-disable-undo)
1130 (setq imap-server (or server imap-server))
1131 (setq imap-port (or port imap-port))
1132 (setq imap-auth (or auth imap-auth))
1133 (message "imap: Reconnecting with stream `%s'..." stream)
1134 (if (null (let ((imap-stream stream))
1135 (imap-open-1 (current-buffer))))
1137 (kill-buffer (current-buffer))
1139 "imap: Reconnecting with stream `%s'...failed"
1141 ;; We're done, kill the first connection
1143 (let ((name (if (stringp buffer)
1145 (buffer-name buffer))))
1146 (kill-buffer buffer)
1147 (rename-buffer name))
1148 (message "imap: Reconnecting with stream `%s'...done"
1150 (setq imap-stream stream)
1151 (setq imap-capability nil)
1152 (setq streams nil)))
1154 (message "imap: Connecting to %s...done" imap-server)
1155 (setq imap-stream stream)
1156 (setq imap-capability nil)
1157 (setq streams nil))))))
1158 (when (imap-opened buffer)
1159 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1163 (defcustom imap-ping-server t
1164 "If non-nil, check if IMAP is open.
1165 See the function `imap-ping-server'."
1166 :version "23.1" ;; No Gnus
1170 (defun imap-opened (&optional buffer)
1171 "Return non-nil if connection to imap server in BUFFER is open.
1172 If BUFFER is nil then the current buffer is used."
1173 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1174 (buffer-live-p buffer)
1175 (with-current-buffer buffer
1177 (memq (process-status imap-process) '(open run))
1178 (if imap-ping-server
1182 (defun imap-ping-server (&optional buffer)
1183 "Ping the IMAP server in BUFFER with a \"NOOP\" command.
1184 Return non-nil if the server responds, and nil if it does not
1185 respond. If BUFFER is nil, the current buffer is used."
1187 (imap-ok-p (imap-send-command-wait "NOOP" buffer))
1190 (defun imap-authenticate (&optional user passwd buffer)
1191 "Authenticate to server in BUFFER, using current buffer if nil.
1192 It uses the authenticator specified when opening the server. If the
1193 authenticator requires username/passwords, they are queried from the
1194 user and optionally stored in the buffer. If USER and/or PASSWD is
1195 specified, the user will not be questioned and the username and/or
1196 password is remembered in the buffer."
1197 (with-current-buffer (or buffer (current-buffer))
1198 (if (not (eq imap-state 'nonauth))
1199 (or (eq imap-state 'auth)
1200 (eq imap-state 'selected)
1201 (eq imap-state 'examine))
1202 (make-local-variable 'imap-username)
1203 (make-local-variable 'imap-password)
1204 (if user (setq imap-username user))
1205 (if passwd (setq imap-password passwd))
1207 (and (funcall (nth 2 (assq imap-auth
1208 imap-authenticator-alist)) (current-buffer))
1209 (setq imap-state 'auth))
1210 ;; Choose authenticator.
1211 (let ((auths imap-authenticators)
1213 (while (setq auth (pop auths))
1214 ;; OK to use authenticator?
1215 (when (funcall (nth 1 (assq auth imap-authenticator-alist)) (current-buffer))
1216 (message "imap: Authenticating to `%s' using `%s'..."
1218 (setq imap-auth auth)
1219 (if (funcall (nth 2 (assq auth imap-authenticator-alist)) (current-buffer))
1221 (message "imap: Authenticating to `%s' using `%s'...done"
1224 (message "imap: Authenticating to `%s' using `%s'...failed"
1225 imap-server auth)))))
1228 (defun imap-close (&optional buffer)
1229 "Close connection to server in BUFFER.
1230 If BUFFER is nil, the current buffer is used."
1231 (with-current-buffer (or buffer (current-buffer))
1236 (when (and imap-process
1237 (memq (process-status imap-process) '(open run)))
1238 (delete-process imap-process))
1239 (setq imap-current-mailbox nil
1240 imap-current-message nil
1245 (defun imap-capability (&optional identifier buffer)
1246 "Return a list of identifiers which server in BUFFER support.
1247 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1248 If BUFFER is nil, the current buffer is assumed."
1249 (with-current-buffer (or buffer (current-buffer))
1250 (unless imap-capability
1251 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1252 (setq imap-capability '(IMAP2))))
1254 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1257 (defun imap-id (&optional list-of-values buffer)
1258 "Identify client to server in BUFFER, and return server identity.
1259 LIST-OF-VALUES is nil, or a plist with identifier and value
1260 strings to send to the server to identify the client.
1262 Return a list of identifiers which server in BUFFER support, or
1263 nil if it doesn't support ID or returns no information.
1265 If BUFFER is nil, the current buffer is assumed."
1266 (with-current-buffer (or buffer (current-buffer))
1267 (when (and (imap-capability 'ID)
1268 (imap-ok-p (imap-send-command-wait
1269 (if (null list-of-values)
1271 (concat "ID (" (mapconcat (lambda (el)
1272 (concat "\"" el "\""))
1277 (defun imap-namespace (&optional buffer)
1278 "Return a namespace hierarchy at server in BUFFER.
1279 If BUFFER is nil, the current buffer is assumed."
1280 (with-current-buffer (or buffer (current-buffer))
1281 (unless imap-namespace
1282 (when (imap-capability 'NAMESPACE)
1283 (imap-send-command-wait "NAMESPACE")))
1286 (defun imap-send-command-wait (command &optional buffer)
1287 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1289 (defun imap-logout (&optional buffer)
1290 (or buffer (setq buffer (current-buffer)))
1291 (if imap-logout-timeout
1292 (with-timeout (imap-logout-timeout
1294 (with-current-buffer buffer
1295 (delete-process imap-process))
1297 (imap-send-command "LOGOUT" buffer))
1298 (imap-send-command "LOGOUT" buffer)))
1300 (defun imap-logout-wait (&optional buffer)
1301 (or buffer (setq buffer (current-buffer)))
1302 (if imap-logout-timeout
1303 (with-timeout (imap-logout-timeout
1305 (with-current-buffer buffer
1306 (delete-process imap-process))
1308 (imap-send-command-wait "LOGOUT" buffer))
1309 (imap-send-command-wait "LOGOUT" buffer)))
1312 ;; Mailbox functions:
1314 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1315 (with-current-buffer (or buffer (current-buffer))
1316 (if imap-mailbox-data
1317 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1319 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1320 propname value mailbox (current-buffer)))
1323 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1324 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1327 (defun imap-mailbox-get (propname &optional mailbox buffer)
1328 (let ((mailbox (imap-utf7-encode mailbox)))
1329 (with-current-buffer (or buffer (current-buffer))
1330 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1332 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1333 (with-current-buffer (or buffer (current-buffer))
1337 (push (funcall func (if mailbox-decoder
1338 (funcall mailbox-decoder (symbol-name s))
1339 (symbol-name s))) result))
1343 (defun imap-mailbox-map (func &optional buffer)
1344 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1345 Function should take a mailbox name (a string) as
1347 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1349 (defun imap-current-mailbox (&optional buffer)
1350 (with-current-buffer (or buffer (current-buffer))
1351 (imap-utf7-decode imap-current-mailbox)))
1353 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1354 (and (string= mailbox imap-current-mailbox)
1356 (eq imap-state 'examine))
1358 (eq imap-state 'selected)))))
1360 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1361 (with-current-buffer (or buffer (current-buffer))
1362 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1364 (defun imap-mailbox-select-1 (mailbox &optional examine)
1365 "Select MAILBOX on server in BUFFER.
1366 If EXAMINE is non-nil, do a read-only select."
1367 (if (imap-current-mailbox-p-1 mailbox examine)
1368 imap-current-mailbox
1369 (setq imap-current-mailbox mailbox)
1370 (if (imap-ok-p (imap-send-command-wait
1371 (concat (if examine "EXAMINE" "SELECT") " \""
1374 (setq imap-message-data (make-vector imap-message-prime 0)
1375 imap-state (if examine 'examine 'selected))
1376 imap-current-mailbox)
1377 ;; Failed SELECT/EXAMINE unselects current mailbox
1378 (setq imap-current-mailbox nil))))
1380 (defun imap-mailbox-select (mailbox &optional examine buffer)
1381 (with-current-buffer (or buffer (current-buffer))
1383 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1385 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1386 (with-current-buffer (or buffer (current-buffer))
1387 (imap-mailbox-select-1 mailbox 'examine)))
1389 (defun imap-mailbox-examine (mailbox &optional buffer)
1390 "Examine MAILBOX on server in BUFFER."
1391 (imap-mailbox-select mailbox 'examine buffer))
1393 (defun imap-mailbox-unselect (&optional buffer)
1394 "Close current folder in BUFFER, without expunging articles."
1395 (with-current-buffer (or buffer (current-buffer))
1396 (when (or (eq imap-state 'auth)
1397 (and (imap-capability 'UNSELECT)
1398 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1400 (imap-send-command-wait (concat "EXAMINE \""
1401 imap-current-mailbox
1403 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1404 (setq imap-current-mailbox nil
1405 imap-message-data nil
1409 (defun imap-mailbox-expunge (&optional asynch buffer)
1410 "Expunge articles in current folder in BUFFER.
1411 If ASYNCH, do not wait for successful completion of the command.
1412 If BUFFER is nil the current buffer is assumed."
1413 (with-current-buffer (or buffer (current-buffer))
1414 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1416 (imap-send-command "EXPUNGE")
1417 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1419 (defun imap-mailbox-close (&optional asynch buffer)
1420 "Expunge articles and close 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 imap-current-mailbox
1426 (imap-add-callback (imap-send-command "CLOSE")
1427 `(lambda (tag status)
1428 (message "IMAP mailbox `%s' closed... %s"
1429 imap-current-mailbox status)
1430 (when (eq ,imap-current-mailbox
1431 imap-current-mailbox)
1432 ;; Don't wipe out data if another mailbox
1434 (setq imap-current-mailbox nil
1435 imap-message-data nil
1436 imap-state 'auth))))
1437 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1438 (setq imap-current-mailbox nil
1439 imap-message-data nil
1443 (defun imap-mailbox-create-1 (mailbox)
1444 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1446 (defun imap-mailbox-create (mailbox &optional buffer)
1447 "Create MAILBOX on server in BUFFER.
1448 If BUFFER is nil the current buffer is assumed."
1449 (with-current-buffer (or buffer (current-buffer))
1450 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1452 (defun imap-mailbox-delete (mailbox &optional buffer)
1453 "Delete MAILBOX on server in BUFFER.
1454 If BUFFER is nil the current buffer is assumed."
1455 (let ((mailbox (imap-utf7-encode mailbox)))
1456 (with-current-buffer (or buffer (current-buffer))
1458 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1460 (defun imap-mailbox-rename (oldname newname &optional buffer)
1461 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1462 If BUFFER is nil the current buffer is assumed."
1463 (let ((oldname (imap-utf7-encode oldname))
1464 (newname (imap-utf7-encode newname)))
1465 (with-current-buffer (or buffer (current-buffer))
1467 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1468 "\"" newname "\""))))))
1470 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1471 "Return a list of subscribed mailboxes on server in BUFFER.
1472 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1473 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1474 implementation-specific string that has to be passed to lsub command."
1475 (with-current-buffer (or buffer (current-buffer))
1476 ;; Make sure we know the hierarchy separator for root's hierarchy
1477 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1478 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1479 (imap-utf7-encode root) "\"")))
1480 ;; clear list data (NB not delimiter and other stuff)
1481 (imap-mailbox-map-1 (lambda (mailbox)
1482 (imap-mailbox-put 'lsub nil mailbox)))
1484 (imap-send-command-wait
1485 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1486 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1489 (imap-mailbox-map-1 (lambda (mailbox)
1490 (when (imap-mailbox-get-1 'lsub mailbox)
1491 (push (imap-utf7-decode mailbox) out))))
1494 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1495 "Return a list of mailboxes matching ROOT on server in BUFFER.
1496 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1497 root. REFERENCE is a implementation-specific string that has to be
1498 passed to list command."
1499 (with-current-buffer (or buffer (current-buffer))
1500 ;; Make sure we know the hierarchy separator for root's hierarchy
1501 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1502 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1503 (imap-utf7-encode root) "\"")))
1504 ;; clear list data (NB not delimiter and other stuff)
1505 (imap-mailbox-map-1 (lambda (mailbox)
1506 (imap-mailbox-put 'list nil mailbox)))
1508 (imap-send-command-wait
1509 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1510 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1513 (imap-mailbox-map-1 (lambda (mailbox)
1514 (when (imap-mailbox-get-1 'list mailbox)
1515 (push (imap-utf7-decode mailbox) out))))
1518 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1519 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1520 Returns non-nil if successful."
1521 (with-current-buffer (or buffer (current-buffer))
1522 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1523 (imap-utf7-encode mailbox)
1526 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1527 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1528 Returns non-nil if successful."
1529 (with-current-buffer (or buffer (current-buffer))
1530 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1531 (imap-utf7-encode mailbox)
1534 (defun imap-mailbox-status (mailbox items &optional buffer)
1535 "Get status items ITEM in MAILBOX from server in BUFFER.
1536 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1537 the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
1538 or `unseen'. If ITEMS is a list of symbols, a list of values is
1539 returned, if ITEMS is a symbol only its value is returned."
1540 (with-current-buffer (or buffer (current-buffer))
1542 (imap-send-command-wait (list "STATUS \""
1543 (imap-utf7-encode mailbox)
1551 (mapcar (lambda (item)
1552 (imap-mailbox-get item mailbox))
1554 (imap-mailbox-get items mailbox)))))
1556 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1557 "Send status item request ITEM on MAILBOX to server in BUFFER.
1558 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1559 the STATUS data items -- i.e. 'messages, 'recent, 'uidnext, 'uidvalidity
1560 or 'unseen. The IMAP command tag is returned."
1561 (with-current-buffer (or buffer (current-buffer))
1562 (imap-send-command (list "STATUS \""
1563 (imap-utf7-encode mailbox)
1571 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1572 "Get ACL on MAILBOX from server in BUFFER."
1573 (let ((mailbox (imap-utf7-encode mailbox)))
1574 (with-current-buffer (or buffer (current-buffer))
1576 (imap-send-command-wait (list "GETACL \""
1577 (or mailbox imap-current-mailbox)
1579 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1581 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1582 "Change/set ACL for IDENTIFIER to RIGHTS in 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 "SETACL \""
1587 (or mailbox imap-current-mailbox)
1593 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1594 "Remove any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1595 (let ((mailbox (imap-utf7-encode mailbox)))
1596 (with-current-buffer (or buffer (current-buffer))
1598 (imap-send-command-wait (list "DELETEACL \""
1599 (or mailbox imap-current-mailbox)
1604 ;; Message functions:
1606 (defun imap-current-message (&optional buffer)
1607 (with-current-buffer (or buffer (current-buffer))
1608 imap-current-message))
1610 (defun imap-list-to-message-set (list)
1611 (mapconcat (lambda (item)
1612 (number-to-string item))
1618 (defun imap-range-to-message-set (range)
1623 (car item) (cdr item))
1624 (format "%d" item)))
1625 (if (and (listp range) (not (listp (cdr range))))
1626 (list range) ;; make (1 . 2) into ((1 . 2))
1630 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1631 (with-current-buffer (or buffer (current-buffer))
1632 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1634 (imap-list-to-message-set uids)
1638 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1639 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1640 UIDS can be a string, number or a list of numbers. If RECEIVE
1641 is non-nil return these properties."
1642 (with-current-buffer (or buffer (current-buffer))
1643 (when (imap-ok-p (imap-send-command-wait
1644 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1646 (imap-list-to-message-set uids)
1649 (if (or (null receive) (stringp uids))
1652 (mapcar (lambda (uid)
1654 (mapcar (lambda (prop)
1655 (imap-message-get uid prop))
1657 (imap-message-get uid receive)))
1659 (imap-message-get uids receive))))))
1661 (defun imap-message-put (uid propname value &optional buffer)
1662 (with-current-buffer (or buffer (current-buffer))
1663 (if imap-message-data
1664 (put (intern (number-to-string uid) imap-message-data)
1666 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1667 uid propname value (current-buffer)))
1670 (defun imap-message-get (uid propname &optional buffer)
1671 (with-current-buffer (or buffer (current-buffer))
1672 (get (intern-soft (number-to-string uid) imap-message-data)
1675 (defun imap-message-map (func propname &optional buffer)
1676 "Map a function across each mailbox in `imap-message-data', returning a list."
1677 (with-current-buffer (or buffer (current-buffer))
1681 (push (funcall func (get s 'UID) (get s propname)) result))
1685 (defmacro imap-message-envelope-date (uid &optional buffer)
1686 `(with-current-buffer (or ,buffer (current-buffer))
1687 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1689 (defmacro imap-message-envelope-subject (uid &optional buffer)
1690 `(with-current-buffer (or ,buffer (current-buffer))
1691 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1693 (defmacro imap-message-envelope-from (uid &optional buffer)
1694 `(with-current-buffer (or ,buffer (current-buffer))
1695 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1697 (defmacro imap-message-envelope-sender (uid &optional buffer)
1698 `(with-current-buffer (or ,buffer (current-buffer))
1699 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1701 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1702 `(with-current-buffer (or ,buffer (current-buffer))
1703 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1705 (defmacro imap-message-envelope-to (uid &optional buffer)
1706 `(with-current-buffer (or ,buffer (current-buffer))
1707 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1709 (defmacro imap-message-envelope-cc (uid &optional buffer)
1710 `(with-current-buffer (or ,buffer (current-buffer))
1711 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1713 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1714 `(with-current-buffer (or ,buffer (current-buffer))
1715 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1717 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1718 `(with-current-buffer (or ,buffer (current-buffer))
1719 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1721 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1722 `(with-current-buffer (or ,buffer (current-buffer))
1723 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1725 (defmacro imap-message-body (uid &optional buffer)
1726 `(with-current-buffer (or ,buffer (current-buffer))
1727 (imap-message-get ,uid 'BODY)))
1729 (defun imap-search (predicate &optional buffer)
1730 (with-current-buffer (or buffer (current-buffer))
1731 (imap-mailbox-put 'search 'dummy)
1732 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1733 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1735 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1737 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1739 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1740 "Return t if FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1741 (with-current-buffer (or buffer (current-buffer))
1742 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1743 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1745 (defun imap-message-flags-set (articles flags &optional silent buffer)
1746 (when (and articles flags)
1747 (with-current-buffer (or buffer (current-buffer))
1748 (imap-ok-p (imap-send-command-wait
1749 (concat "UID STORE " articles
1750 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1752 (defun imap-message-flags-del (articles flags &optional silent buffer)
1753 (when (and articles flags)
1754 (with-current-buffer (or buffer (current-buffer))
1755 (imap-ok-p (imap-send-command-wait
1756 (concat "UID STORE " articles
1757 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1759 (defun imap-message-flags-add (articles flags &optional silent buffer)
1760 (when (and articles flags)
1761 (with-current-buffer (or buffer (current-buffer))
1762 (imap-ok-p (imap-send-command-wait
1763 (concat "UID STORE " articles
1764 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1766 ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
1767 ;; Signal an error if we'd get an integer overflow.
1769 ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
1770 ;; `imap-string-to-integer'.
1771 (defun imap-string-to-integer (string &optional base)
1772 (let ((number (string-to-number string base)))
1773 (if (> number most-positive-fixnum)
1775 (format "String %s cannot be converted to a lisp integer" number))
1778 (defun imap-message-copyuid-1 (mailbox)
1779 (if (imap-capability 'UIDPLUS)
1780 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1781 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1782 (let ((old-mailbox imap-current-mailbox)
1784 (imap-message-data (make-vector 2 0)))
1785 (when (imap-mailbox-examine-1 mailbox)
1788 ;; why the switch here, since they seem to be
1789 ;; equivalent, and ~ no-one is going to find this
1791 (if imap-enable-exchange-bug-workaround "*:*" "*") "UID")
1792 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1793 (apply 'max (imap-message-map
1794 (lambda (uid prop) uid) 'UID))))
1796 (imap-mailbox-select old-mailbox (eq state 'examine))
1797 (imap-mailbox-unselect)))))))
1799 (defun imap-message-copyuid (mailbox &optional buffer)
1800 (with-current-buffer (or buffer (current-buffer))
1801 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1803 (defun imap-message-copy (articles mailbox
1804 &optional dont-create no-copyuid buffer)
1805 "Copy ARTICLES to MAILBOX on server in BUFFER.
1806 ARTICLES is a string message set. Create mailbox if it doesn't exist,
1807 unless DONT-CREATE is non-nil. On success, return a list with
1808 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1809 first element. The rest of list contains the saved articles' UIDs."
1811 (with-current-buffer (or buffer (current-buffer))
1812 (let ((mailbox (imap-utf7-encode mailbox)))
1813 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1814 (imap-current-target-mailbox mailbox))
1815 (if (imap-ok-p (imap-send-command-wait cmd))
1817 (when (and (not dont-create)
1818 ;; removed because of buggy Oracle server
1819 ;; that doesn't send TRYCREATE tags (which
1820 ;; is a MUST according to specifications):
1821 ;;(imap-mailbox-get-1 'trycreate mailbox)
1822 (imap-mailbox-create-1 mailbox))
1823 (imap-ok-p (imap-send-command-wait cmd)))))
1825 (imap-message-copyuid-1 mailbox)))))))
1827 (defun imap-message-appenduid-1 (mailbox)
1828 (if (imap-capability 'UIDPLUS)
1829 (imap-mailbox-get-1 'appenduid mailbox)
1830 (let ((old-mailbox imap-current-mailbox)
1832 (imap-message-data (make-vector 2 0)))
1833 (when (imap-mailbox-examine-1 mailbox)
1836 (if imap-enable-exchange-bug-workaround "*:*" "*") "UID")
1837 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1838 (apply 'max (imap-message-map
1839 (lambda (uid prop) uid) 'UID))))
1841 (imap-mailbox-select old-mailbox (eq state 'examine))
1842 (imap-mailbox-unselect)))))))
1844 (defun imap-message-appenduid (mailbox &optional buffer)
1845 (with-current-buffer (or buffer (current-buffer))
1846 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1848 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1849 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1850 FLAGS and DATE-TIME is currently not used. Return a cons holding
1851 uidvalidity of MAILBOX and UID the newly created article got, or nil
1853 (let ((mailbox (imap-utf7-encode mailbox)))
1854 (with-current-buffer (or buffer (current-buffer))
1855 (and (let ((imap-current-target-mailbox mailbox))
1857 (imap-send-command-wait
1858 (list "APPEND \"" mailbox "\" " article))))
1859 (imap-message-appenduid-1 mailbox)))))
1861 (defun imap-body-lines (body)
1862 "Return number of lines in article by looking at the mime bodystructure BODY."
1864 (if (stringp (car body))
1865 (cond ((and (string= (upcase (car body)) "TEXT")
1866 (numberp (nth 7 body)))
1868 ((and (string= (upcase (car body)) "MESSAGE")
1869 (numberp (nth 9 body)))
1872 (apply '+ (mapcar 'imap-body-lines body)))
1875 (defun imap-envelope-from (from)
1876 "Return a from string line."
1878 (concat (aref from 0)
1879 (if (aref from 0) " <")
1883 (if (aref from 0) ">"))))
1886 ;; Internal functions.
1888 (defun imap-add-callback (tag func)
1889 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1891 (defun imap-send-command-1 (cmdstr)
1892 (setq cmdstr (concat cmdstr imap-client-eol))
1894 (with-current-buffer (get-buffer-create imap-log-buffer)
1895 (imap-disable-multibyte)
1896 (buffer-disable-undo)
1897 (goto-char (point-max))
1899 (process-send-string imap-process cmdstr))
1901 (defun imap-send-command (command &optional buffer)
1902 (with-current-buffer (or buffer (current-buffer))
1903 (if (not (listp command)) (setq command (list command)))
1904 (let ((tag (setq imap-tag (1+ imap-tag)))
1906 (setq cmdstr (concat (number-to-string imap-tag) " "))
1907 (while (setq cmd (pop command))
1908 (cond ((stringp cmd)
1909 (setq cmdstr (concat cmdstr cmd)))
1911 (let ((eol imap-client-eol)
1912 (calcfirst imap-calculate-literal-size-first)
1914 (with-current-buffer cmd
1916 (setq size (buffer-size)))
1917 (when (not (equal eol "\r\n"))
1918 ;; XXX modifies buffer!
1919 (goto-char (point-min))
1920 (while (search-forward "\r\n" nil t)
1921 (replace-match eol)))
1923 (setq size (buffer-size))))
1925 (concat cmdstr (format "{%d}" size))))
1928 (imap-send-command-1 cmdstr)
1930 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1931 (setq command nil) ;; abort command if no cont-req
1932 (let ((process imap-process)
1933 (stream imap-stream)
1934 (eol imap-client-eol))
1935 (with-current-buffer cmd
1937 (with-current-buffer (get-buffer-create
1939 (imap-disable-multibyte)
1940 (buffer-disable-undo)
1941 (goto-char (point-max))
1942 (insert-buffer-substring cmd)))
1943 (process-send-region process (point-min)
1945 (process-send-string process imap-client-eol))))
1946 (setq imap-continuation nil)))
1948 (imap-send-command-1 cmdstr)
1951 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1952 (setq command nil) ;; abort command if no cont-req
1953 (setq command (cons (funcall cmd imap-continuation)
1955 (setq imap-continuation nil)))
1957 (error "Unknown command type"))))
1959 (imap-send-command-1 cmdstr))
1962 (defun imap-wait-for-tag (tag &optional buffer)
1963 (with-current-buffer (or buffer (current-buffer))
1964 (let (imap-have-messaged)
1965 (while (and (null imap-continuation)
1966 (memq (process-status imap-process) '(open run))
1967 (< imap-reached-tag tag))
1968 (let ((len (/ (point-max) 1024))
1971 (setq imap-have-messaged t)
1972 (message "imap read: %dk" len))
1973 (accept-process-output imap-process
1974 (truncate imap-read-timeout)
1975 (truncate (* (- imap-read-timeout
1976 (truncate imap-read-timeout))
1978 ;; A process can die _before_ we have processed everything it
1979 ;; has to say. Moreover, this can happen in between the call to
1980 ;; accept-process-output and the call to process-status in an
1981 ;; iteration of the loop above.
1982 (when (and (null imap-continuation)
1983 (< imap-reached-tag tag))
1984 (accept-process-output imap-process 0 0))
1985 (when imap-have-messaged
1987 (and (memq (process-status imap-process) '(open run))
1988 (or (assq tag imap-failed-tags)
1989 (if imap-continuation
1993 (defun imap-sentinel (process string)
1994 (delete-process process))
1996 (defun imap-find-next-line ()
1997 "Return point at end of current line, taking into account literals.
1998 Return nil if no complete line has arrived."
1999 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
2002 (if (match-string 1)
2003 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
2005 (goto-char (+ (point) (string-to-number (match-string 1))))
2006 (imap-find-next-line))
2009 (defun imap-arrival-filter (proc string)
2010 "IMAP process filter."
2011 ;; Sometimes, we are called even though the process has died.
2012 ;; Better abstain from doing stuff in that case.
2013 (when (buffer-name (process-buffer proc))
2014 (with-current-buffer (process-buffer proc)
2015 (goto-char (point-max))
2018 (with-current-buffer (get-buffer-create imap-log-buffer)
2019 (imap-disable-multibyte)
2020 (buffer-disable-undo)
2021 (goto-char (point-max))
2024 (goto-char (point-min))
2025 (while (setq end (imap-find-next-line))
2027 (narrow-to-region (point-min) end)
2028 (delete-backward-char (length imap-server-eol))
2029 (goto-char (point-min))
2031 (cond ((eq imap-state 'initial)
2032 (imap-parse-greeting))
2033 ((or (eq imap-state 'auth)
2034 (eq imap-state 'nonauth)
2035 (eq imap-state 'selected)
2036 (eq imap-state 'examine))
2037 (imap-parse-response))
2039 (message "Unknown state %s in arrival filter"
2041 (delete-region (point-min) (point-max)))))))))
2046 (defsubst imap-forward ()
2047 (or (eobp) (forward-char)))
2050 ;; ; Unsigned 32-bit integer
2051 ;; ; (0 <= n < 4,294,967,296)
2053 (defsubst imap-parse-number ()
2054 (when (looking-at "[0-9]+")
2056 (string-to-number (match-string 0))
2057 (goto-char (match-end 0)))))
2059 ;; literal = "{" number "}" CRLF *CHAR8
2060 ;; ; Number represents the number of CHAR8s
2062 (defsubst imap-parse-literal ()
2063 (when (looking-at "{\\([0-9]+\\)}\r\n")
2064 (let ((pos (match-end 0))
2065 (len (string-to-number (match-string 1))))
2066 (if (< (point-max) (+ pos len))
2068 (goto-char (+ pos len))
2069 (buffer-substring pos (+ pos len))))))
2071 ;; string = quoted / literal
2073 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
2075 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2076 ;; "\" quoted-specials
2078 ;; quoted-specials = DQUOTE / "\"
2080 ;; TEXT-CHAR = <any CHAR except CR and LF>
2082 (defsubst imap-parse-string ()
2083 (cond ((eq (char-after) ?\")
2085 (let ((p (point)) (name ""))
2086 (skip-chars-forward "^\"\\\\")
2087 (setq name (buffer-substring p (point)))
2088 (while (eq (char-after) ?\\)
2089 (setq p (1+ (point)))
2091 (skip-chars-forward "^\"\\\\")
2092 (setq name (concat name (buffer-substring p (point)))))
2095 ((eq (char-after) ?{)
2096 (imap-parse-literal))))
2100 (defsubst imap-parse-nil ()
2101 (if (looking-at "NIL")
2102 (goto-char (match-end 0))))
2104 ;; nstring = string / nil
2106 (defsubst imap-parse-nstring ()
2107 (or (imap-parse-string)
2108 (and (imap-parse-nil)
2111 ;; astring = atom / string
2113 ;; atom = 1*ATOM-CHAR
2115 ;; ATOM-CHAR = <any CHAR except atom-specials>
2117 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
2120 ;; list-wildcards = "%" / "*"
2122 ;; quoted-specials = DQUOTE / "\"
2124 (defsubst imap-parse-astring ()
2125 (or (imap-parse-string)
2126 (buffer-substring (point)
2127 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2128 (goto-char (1- (match-end 0)))
2132 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
2135 ;; addr-adl = nstring
2136 ;; ; Holds route from [RFC-822] route-addr if
2139 ;; addr-host = nstring
2140 ;; ; nil indicates [RFC-822] group syntax.
2141 ;; ; Otherwise, holds [RFC-822] domain name
2143 ;; addr-mailbox = nstring
2144 ;; ; nil indicates end of [RFC-822] group; if
2145 ;; ; non-nil and addr-host is nil, holds
2146 ;; ; [RFC-822] group name.
2147 ;; ; Otherwise, holds [RFC-822] local-part
2148 ;; ; after removing [RFC-822] quoting
2150 ;; addr-name = nstring
2151 ;; ; If non-nil, holds phrase from [RFC-822]
2152 ;; ; mailbox after removing [RFC-822] quoting
2155 (defsubst imap-parse-address ()
2157 (when (eq (char-after) ?\()
2159 (setq address (vector (prog1 (imap-parse-nstring)
2161 (prog1 (imap-parse-nstring)
2163 (prog1 (imap-parse-nstring)
2165 (imap-parse-nstring)))
2166 (when (eq (char-after) ?\))
2170 ;; address-list = "(" 1*address ")" / nil
2174 (defsubst imap-parse-address-list ()
2175 (if (eq (char-after) ?\()
2176 (let (address addresses)
2178 (while (and (not (eq (char-after) ?\)))
2179 ;; next line for MS Exchange bug
2180 (progn (and (eq (char-after) ? ) (imap-forward)) t)
2181 (setq address (imap-parse-address)))
2182 (setq addresses (cons address addresses)))
2183 (when (eq (char-after) ?\))
2185 (nreverse addresses)))
2186 ;; With assert, the code might not be eval'd.
2187 ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2190 ;; mailbox = "INBOX" / astring
2191 ;; ; INBOX is case-insensitive. All case variants of
2192 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2193 ;; ; not as an astring. An astring which consists of
2194 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
2195 ;; ; is considered to be INBOX and not an astring.
2196 ;; ; Refer to section 5.1 for further
2197 ;; ; semantic details of mailbox names.
2199 (defsubst imap-parse-mailbox ()
2200 (let ((mailbox (imap-parse-astring)))
2201 (if (string-equal "INBOX" (upcase mailbox))
2205 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2207 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
2208 ;; ; Authentication condition
2210 ;; resp-cond-bye = "BYE" SP resp-text
2212 (defun imap-parse-greeting ()
2213 "Parse a IMAP greeting."
2214 (cond ((looking-at "\\* OK ")
2215 (setq imap-state 'nonauth))
2216 ((looking-at "\\* PREAUTH ")
2217 (setq imap-state 'auth))
2218 ((looking-at "\\* BYE ")
2219 (setq imap-state 'closed))))
2221 ;; response = *(continue-req / response-data) response-done
2223 ;; continue-req = "+" SP (resp-text / base64) CRLF
2225 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
2226 ;; mailbox-data / message-data / capability-data) CRLF
2228 ;; response-done = response-tagged / response-fatal
2230 ;; response-fatal = "*" SP resp-cond-bye CRLF
2231 ;; ; Server closes connection immediately
2233 ;; response-tagged = tag SP resp-cond-state CRLF
2235 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2236 ;; ; Status condition
2238 ;; resp-cond-bye = "BYE" SP resp-text
2240 ;; mailbox-data = "FLAGS" SP flag-list /
2241 ;; "LIST" SP mailbox-list /
2242 ;; "LSUB" SP mailbox-list /
2243 ;; "SEARCH" *(SP nz-number) /
2244 ;; "STATUS" SP mailbox SP "("
2245 ;; [status-att SP number *(SP status-att SP number)] ")" /
2246 ;; number SP "EXISTS" /
2247 ;; number SP "RECENT"
2249 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2251 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2253 ;; ; IMAP4rev1 servers which offer RFC 1730
2254 ;; ; compatibility MUST list "IMAP4" as the first
2257 (defun imap-parse-response ()
2258 "Parse a IMAP command response."
2260 (case (setq token (read (current-buffer)))
2261 (+ (setq imap-continuation
2262 (or (buffer-substring (min (point-max) (1+ (point)))
2265 (* (case (prog1 (setq token (read (current-buffer)))
2267 (OK (imap-parse-resp-text))
2268 (NO (imap-parse-resp-text))
2269 (BAD (imap-parse-resp-text))
2270 (BYE (imap-parse-resp-text))
2271 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
2272 (LIST (imap-parse-data-list 'list))
2273 (LSUB (imap-parse-data-list 'lsub))
2274 (SEARCH (imap-mailbox-put
2276 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2277 (STATUS (imap-parse-status))
2278 (CAPABILITY (setq imap-capability
2279 (read (concat "(" (upcase (buffer-substring
2280 (point) (point-max)))
2282 (ID (setq imap-id (read (buffer-substring (point)
2284 (ACL (imap-parse-acl))
2285 (t (case (prog1 (read (current-buffer))
2287 (EXISTS (imap-mailbox-put 'exists token))
2288 (RECENT (imap-mailbox-put 'recent token))
2290 (FETCH (imap-parse-fetch token))
2291 (t (message "Garbage: %s" (buffer-string)))))))
2293 (if (not (integerp token))
2294 (message "Garbage: %s" (buffer-string))
2295 (case (prog1 (setq status (read (current-buffer)))
2298 (setq imap-reached-tag (max imap-reached-tag token))
2299 (imap-parse-resp-text)))
2301 (setq imap-reached-tag (max imap-reached-tag token))
2303 (imap-parse-resp-text))
2305 (when (eq (char-after) ?\[)
2306 (setq code (buffer-substring (point)
2307 (search-forward "]")))
2309 (setq text (buffer-substring (point) (point-max)))
2310 (push (list token status code text)
2311 imap-failed-tags))))
2313 (setq imap-reached-tag (max imap-reached-tag token))
2315 (imap-parse-resp-text))
2317 (when (eq (char-after) ?\[)
2318 (setq code (buffer-substring (point)
2319 (search-forward "]")))
2321 (setq text (buffer-substring (point) (point-max)))
2322 (push (list token status code text) imap-failed-tags)
2323 (error "Internal error, tag %s status %s code %s text %s"
2324 token status code text))))
2325 (t (message "Garbage: %s" (buffer-string))))
2326 (when (assq token imap-callbacks)
2327 (funcall (cdr (assq token imap-callbacks)) token status)
2328 (setq imap-callbacks
2329 (imap-remassoc token imap-callbacks)))))))))
2331 ;; resp-text = ["[" resp-text-code "]" SP] text
2333 ;; text = 1*TEXT-CHAR
2335 ;; TEXT-CHAR = <any CHAR except CR and LF>
2337 (defun imap-parse-resp-text ()
2338 (imap-parse-resp-text-code))
2340 ;; resp-text-code = "ALERT" /
2341 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2342 ;; "NEWNAME" SP string SP string /
2344 ;; "PERMANENTFLAGS" SP "("
2345 ;; [flag-perm *(SP flag-perm)] ")" /
2349 ;; "UIDNEXT" SP nz-number /
2350 ;; "UIDVALIDITY" SP nz-number /
2351 ;; "UNSEEN" SP nz-number /
2352 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2354 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2356 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2358 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2360 ;; ; Identifies a set of messages. For message
2361 ;; ; sequence numbers, these are consecutive
2362 ;; ; numbers from 1 to the number of messages in
2364 ;; ; Comma delimits individual numbers, colon
2365 ;; ; delimits between two numbers inclusive.
2366 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2367 ;; ; 14,15 for a mailbox with 15 messages.
2369 ;; sequence-num = nz-number / "*"
2370 ;; ; * is the largest number in use. For message
2371 ;; ; sequence numbers, it is the number of messages
2372 ;; ; in the mailbox. For unique identifiers, it is
2373 ;; ; the unique identifier of the last message in
2376 ;; flag-perm = flag / "\*"
2378 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2379 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2380 ;; ; Does not include "\Recent"
2382 ;; flag-extension = "\" atom
2383 ;; ; Future expansion. Client implementations
2384 ;; ; MUST accept flag-extension flags. Server
2385 ;; ; implementations MUST NOT generate
2386 ;; ; flag-extension flags except as defined by
2387 ;; ; future standard or standards-track
2388 ;; ; revisions of this specification.
2390 ;; flag-keyword = atom
2392 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2394 (defun imap-parse-resp-text-code ()
2395 ;; xxx next line for stalker communigate pro 3.3.1 bug
2396 (when (looking-at " \\[")
2398 (when (eq (char-after) ?\[)
2400 (cond ((search-forward "PERMANENTFLAGS " nil t)
2401 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2402 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2403 (imap-mailbox-put 'uidnext (match-string 1)))
2404 ((search-forward "UNSEEN " nil t)
2405 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2406 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2407 (imap-mailbox-put 'uidvalidity (match-string 1)))
2408 ((search-forward "READ-ONLY" nil t)
2409 (imap-mailbox-put 'read-only t))
2410 ((search-forward "NEWNAME " nil t)
2411 (let (oldname newname)
2412 (setq oldname (imap-parse-string))
2414 (setq newname (imap-parse-string))
2415 (imap-mailbox-put 'newname newname oldname)))
2416 ((search-forward "TRYCREATE" nil t)
2417 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2418 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2419 (imap-mailbox-put 'appenduid
2420 (list (match-string 1)
2421 (string-to-number (match-string 2)))
2422 imap-current-target-mailbox))
2423 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2424 (imap-mailbox-put 'copyuid (list (match-string 1)
2427 imap-current-target-mailbox))
2428 ((search-forward "ALERT] " nil t)
2429 (message "Imap server %s information: %s" imap-server
2430 (buffer-substring (point) (point-max)))))))
2432 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2433 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2435 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2436 ;; *(SP mbx-list-oflag) /
2437 ;; mbx-list-oflag *(SP mbx-list-oflag)
2439 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2440 ;; ; Other flags; multiple possible per LIST response
2442 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2443 ;; ; Selectability flags; only one per LIST response
2445 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2446 ;; "\" quoted-specials
2448 ;; quoted-specials = DQUOTE / "\"
2450 (defun imap-parse-data-list (type)
2451 (let (flags delimiter mailbox)
2452 (setq flags (imap-parse-flag-list))
2453 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2454 (setq delimiter (match-string 1))
2455 (goto-char (1+ (match-end 0)))
2456 (when (setq mailbox (imap-parse-mailbox))
2457 (imap-mailbox-put type t mailbox)
2458 (imap-mailbox-put 'list-flags flags mailbox)
2459 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2461 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2462 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2463 ;; "INTERNALDATE" SPACE date_time /
2464 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2465 ;; "RFC822.SIZE" SPACE number /
2466 ;; "BODY" ["STRUCTURE"] SPACE body /
2467 ;; "BODY" section ["<" number ">"] SPACE nstring /
2468 ;; "UID" SPACE uniqueid) ")"
2470 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2471 ;; SPACE time SPACE zone <">
2473 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2474 ;; ["." (section_text / "MIME")])] "]"
2476 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2477 ;; SPACE header_list / "TEXT"
2479 ;; header_fld_name ::= astring
2481 ;; header_list ::= "(" 1#header_fld_name ")"
2483 (defsubst imap-parse-header-list ()
2484 (when (eq (char-after) ?\()
2486 (while (not (eq (char-after) ?\)))
2488 (push (imap-parse-astring) strlist))
2490 (nreverse strlist))))
2492 (defsubst imap-parse-fetch-body-section ()
2494 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2495 (if (eq (char-before) ? )
2497 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2498 (search-forward "]" nil t))
2501 (defun imap-parse-fetch (response)
2502 (when (eq (char-after) ?\()
2503 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2504 rfc822size body bodydetail bodystructure flags-empty)
2505 (while (not (eq (char-after) ?\)))
2507 (let ((token (read (current-buffer))))
2509 (cond ((eq token 'UID)
2510 (setq uid (condition-case ()
2511 (read (current-buffer))
2514 (setq flags (imap-parse-flag-list))
2516 (setq flags-empty 't)))
2517 ((eq token 'ENVELOPE)
2518 (setq envelope (imap-parse-envelope)))
2519 ((eq token 'INTERNALDATE)
2520 (setq internaldate (imap-parse-string)))
2522 (setq rfc822 (imap-parse-nstring)))
2523 ((eq token 'RFC822.HEADER)
2524 (setq rfc822header (imap-parse-nstring)))
2525 ((eq token 'RFC822.TEXT)
2526 (setq rfc822text (imap-parse-nstring)))
2527 ((eq token 'RFC822.SIZE)
2528 (setq rfc822size (read (current-buffer))))
2530 (if (eq (char-before) ?\[)
2532 (upcase (imap-parse-fetch-body-section))
2533 (and (eq (char-after) ?<)
2534 (buffer-substring (1+ (point))
2535 (search-forward ">" nil t)))
2536 (progn (imap-forward)
2537 (imap-parse-nstring)))
2539 (setq body (imap-parse-body))))
2540 ((eq token 'BODYSTRUCTURE)
2541 (setq bodystructure (imap-parse-body))))))
2543 (setq imap-current-message uid)
2544 (imap-message-put uid 'UID uid)
2545 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2546 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2547 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2548 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2549 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2550 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2551 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2552 (and body (imap-message-put uid 'BODY body))
2553 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2554 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2555 (run-hooks 'imap-fetch-data-hook)))))
2557 ;; mailbox-data = ...
2558 ;; "STATUS" SP mailbox SP "("
2559 ;; [status-att SP number
2560 ;; *(SP status-att SP number)] ")"
2563 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2566 (defun imap-parse-status ()
2567 (let ((mailbox (imap-parse-mailbox)))
2568 (if (eq (char-after) ? )
2570 (when (and mailbox (eq (char-after) ?\())
2571 (while (and (not (eq (char-after) ?\)))
2572 (or (forward-char) t)
2573 (looking-at "\\([A-Za-z]+\\) "))
2574 (let ((token (upcase (match-string 1))))
2575 (goto-char (match-end 0))
2576 (cond ((string= token "MESSAGES")
2577 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2578 ((string= token "RECENT")
2579 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2580 ((string= token "UIDNEXT")
2581 (and (looking-at "[0-9]+")
2582 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2583 (goto-char (match-end 0))))
2584 ((string= token "UIDVALIDITY")
2585 (and (looking-at "[0-9]+")
2586 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2587 (goto-char (match-end 0))))
2588 ((string= token "UNSEEN")
2589 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2591 (message "Unknown status data %s in mailbox %s ignored"
2593 (read (current-buffer)))))))))
2595 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2598 ;; identifier ::= astring
2600 ;; rights ::= astring
2602 (defun imap-parse-acl ()
2603 (let ((mailbox (imap-parse-mailbox))
2604 identifier rights acl)
2605 (while (eq (char-after) ?\ )
2607 (setq identifier (imap-parse-astring))
2609 (setq rights (imap-parse-astring))
2610 (setq acl (append acl (list (cons identifier rights)))))
2611 (imap-mailbox-put 'acl acl mailbox)))
2613 ;; flag-list = "(" [flag *(SP flag)] ")"
2615 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2616 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2617 ;; ; Does not include "\Recent"
2619 ;; flag-keyword = atom
2621 ;; flag-extension = "\" atom
2622 ;; ; Future expansion. Client implementations
2623 ;; ; MUST accept flag-extension flags. Server
2624 ;; ; implementations MUST NOT generate
2625 ;; ; flag-extension flags except as defined by
2626 ;; ; future standard or standards-track
2627 ;; ; revisions of this specification.
2629 (defun imap-parse-flag-list ()
2630 (let (flag-list start)
2631 (assert (eq (char-after) ?\() nil "In imap-parse-flag-list")
2632 (while (and (not (eq (char-after) ?\)))
2635 ;; next line for Courier IMAP bug.
2636 (skip-chars-forward " ")
2638 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2639 (push (buffer-substring start (point)) flag-list))
2640 (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list")
2642 (nreverse flag-list)))
2644 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2645 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2646 ;; env-in-reply-to SP env-message-id ")"
2648 ;; env-bcc = "(" 1*address ")" / nil
2650 ;; env-cc = "(" 1*address ")" / nil
2652 ;; env-date = nstring
2654 ;; env-from = "(" 1*address ")" / nil
2656 ;; env-in-reply-to = nstring
2658 ;; env-message-id = nstring
2660 ;; env-reply-to = "(" 1*address ")" / nil
2662 ;; env-sender = "(" 1*address ")" / nil
2664 ;; env-subject = nstring
2666 ;; env-to = "(" 1*address ")" / nil
2668 (defun imap-parse-envelope ()
2669 (when (eq (char-after) ?\()
2671 (vector (prog1 (imap-parse-nstring) ;; date
2673 (prog1 (imap-parse-nstring) ;; subject
2675 (prog1 (imap-parse-address-list) ;; from
2677 (prog1 (imap-parse-address-list) ;; sender
2679 (prog1 (imap-parse-address-list) ;; reply-to
2681 (prog1 (imap-parse-address-list) ;; to
2683 (prog1 (imap-parse-address-list) ;; cc
2685 (prog1 (imap-parse-address-list) ;; bcc
2687 (prog1 (imap-parse-nstring) ;; in-reply-to
2689 (prog1 (imap-parse-nstring) ;; message-id
2692 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2694 (defsubst imap-parse-string-list ()
2695 (cond ((eq (char-after) ?\() ;; body-fld-param
2698 (while (setq str (imap-parse-string))
2700 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2701 ;; between body-fld-param's sometimes
2702 (or (eq (char-after) ?\")
2704 (nreverse strlist)))
2708 ;; body-extension = nstring / number /
2709 ;; "(" body-extension *(SP body-extension) ")"
2710 ;; ; Future expansion. Client implementations
2711 ;; ; MUST accept body-extension fields. Server
2712 ;; ; implementations MUST NOT generate
2713 ;; ; body-extension fields except as defined by
2714 ;; ; future standard or standards-track
2715 ;; ; revisions of this specification.
2717 (defun imap-parse-body-extension ()
2718 (if (eq (char-after) ?\()
2721 (push (imap-parse-body-extension) b-e)
2722 (while (eq (char-after) ?\ )
2724 (push (imap-parse-body-extension) b-e))
2725 (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2728 (or (imap-parse-number)
2729 (imap-parse-nstring))))
2731 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2732 ;; *(SP body-extension)]]
2733 ;; ; MUST NOT be returned on non-extensible
2736 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2737 ;; *(SP body-extension)]]
2738 ;; ; MUST NOT be returned on non-extensible
2741 (defsubst imap-parse-body-ext ()
2743 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2746 (if (eq (char-after) ?\()
2749 (push (imap-parse-string) dsp)
2751 (push (imap-parse-string-list) dsp)
2753 ;; With assert, the code might not be eval'd.
2754 ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2756 (push (nreverse dsp) ext))
2757 (when (eq (char-after) ?\ ) ;; body-fld-lang
2759 (if (eq (char-after) ?\()
2760 (push (imap-parse-string-list) ext)
2761 (push (imap-parse-nstring) ext))
2762 (while (eq (char-after) ?\ ) ;; body-extension
2764 (setq ext (append (imap-parse-body-extension) ext)))))
2767 ;; body = "(" body-type-1part / body-type-mpart ")"
2769 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2770 ;; *(SP body-extension)]]
2771 ;; ; MUST NOT be returned on non-extensible
2774 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2775 ;; *(SP body-extension)]]
2776 ;; ; MUST NOT be returned on non-extensible
2779 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2780 ;; body-fld-enc SP body-fld-octets
2782 ;; body-fld-desc = nstring
2784 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2786 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2787 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2789 ;; body-fld-id = nstring
2791 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2793 ;; body-fld-lines = number
2795 ;; body-fld-md5 = nstring
2797 ;; body-fld-octets = number
2799 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2801 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2802 ;; [SP body-ext-1part]
2804 ;; body-type-basic = media-basic SP body-fields
2805 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2807 ;; body-type-msg = media-message SP body-fields SP envelope
2808 ;; SP body SP body-fld-lines
2810 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2812 ;; body-type-mpart = 1*body SP media-subtype
2813 ;; [SP body-ext-mpart]
2815 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2816 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2817 ;; ; Defined in [MIME-IMT]
2819 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2820 ;; ; Defined in [MIME-IMT]
2822 ;; media-subtype = string
2823 ;; ; Defined in [MIME-IMT]
2825 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2826 ;; ; Defined in [MIME-IMT]
2828 (defun imap-parse-body ()
2830 (when (eq (char-after) ?\()
2832 (if (eq (char-after) ?\()
2834 (while (and (eq (char-after) ?\()
2835 (setq subbody (imap-parse-body)))
2836 ;; buggy stalker communigate pro 3.0 inserts a SPC between
2837 ;; parts in multiparts
2838 (when (and (eq (char-after) ?\ )
2839 (eq (char-after (1+ (point))) ?\())
2841 (push subbody body))
2843 (push (imap-parse-string) body) ;; media-subtype
2844 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2846 (if (eq (char-after) ?\() ;; body-fld-param
2847 (push (imap-parse-string-list) body)
2848 (push (and (imap-parse-nil) nil) body))
2850 (append (imap-parse-body-ext) body))) ;; body-ext-...
2851 (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2855 (push (imap-parse-string) body) ;; media-type
2857 (push (imap-parse-string) body) ;; media-subtype
2859 ;; next line for Sun SIMS bug
2860 (and (eq (char-after) ? ) (imap-forward))
2861 (if (eq (char-after) ?\() ;; body-fld-param
2862 (push (imap-parse-string-list) body)
2863 (push (and (imap-parse-nil) nil) body))
2865 (push (imap-parse-nstring) body) ;; body-fld-id
2867 (push (imap-parse-nstring) body) ;; body-fld-desc
2869 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2870 ;; nstring and return nil instead of defaulting back to 7BIT
2871 ;; as the standard says.
2872 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2874 ;; Exchange 2007 can return -1, contrary to the spec...
2875 (if (eq (char-after) ?-)
2877 (skip-chars-forward "-0-9")
2879 (push (imap-parse-number) body)) ;; body-fld-octets
2881 ;; ok, we're done parsing the required parts, what comes now is one
2884 ;; envelope (then we're parsing body-type-msg)
2885 ;; body-fld-lines (then we're parsing body-type-text)
2886 ;; body-ext-1part (then we're parsing body-type-basic)
2888 ;; the problem is that the two first are in turn optionally followed
2889 ;; by the third. So we parse the first two here (if there are any)...
2891 (when (eq (char-after) ?\ )
2894 (cond ((eq (char-after) ?\() ;; body-type-msg:
2895 (push (imap-parse-envelope) body) ;; envelope
2897 (push (imap-parse-body) body) ;; body
2898 ;; buggy stalker communigate pro 3.0 doesn't print
2899 ;; number of lines in message/rfc822 attachment
2900 (if (eq (char-after) ?\))
2903 (push (imap-parse-number) body))) ;; body-fld-lines
2904 ((setq lines (imap-parse-number)) ;; body-type-text:
2905 (push lines body)) ;; body-fld-lines
2907 (backward-char))))) ;; no match...
2909 ;; ...and then parse the third one here...
2911 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2913 (push (imap-parse-nstring) body) ;; body-fld-md5
2914 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2916 (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2920 (when imap-debug ; (untrace-all)
2922 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2923 (mapc (lambda (f) (trace-function-background f imap-debug-buffer))
2934 imap-interactive-login
2951 imap-send-command-wait
2956 imap-current-mailbox
2957 imap-current-mailbox-p-1
2958 imap-current-mailbox-p
2959 imap-mailbox-select-1
2961 imap-mailbox-examine-1
2962 imap-mailbox-examine
2963 imap-mailbox-unselect
2964 imap-mailbox-expunge
2966 imap-mailbox-create-1
2972 imap-mailbox-subscribe
2973 imap-mailbox-unsubscribe
2975 imap-mailbox-acl-get
2976 imap-mailbox-acl-set
2977 imap-mailbox-acl-delete
2978 imap-current-message
2979 imap-list-to-message-set
2986 imap-message-flag-permanent-p
2987 imap-message-flags-set
2988 imap-message-flags-del
2989 imap-message-flags-add
2990 imap-message-copyuid-1
2991 imap-message-copyuid
2993 imap-message-appenduid-1
2994 imap-message-appenduid
3006 imap-parse-resp-text
3007 imap-parse-resp-text-code
3008 imap-parse-data-list
3012 imap-parse-flag-list
3014 imap-parse-body-extension
3020 ;; arch-tag: 27369ed6-33e4-482f-96f1-8bb906ba70f7
3021 ;;; imap.el ends here