1 ;;; imap.el --- imap library
3 ;; Copyright (C) 1998-2016 Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <simon@josefsson.org>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;; imap.el is an elisp library providing an interface for talking to
28 ;; imap.el is roughly divided in two parts, one that parses IMAP
29 ;; responses from the server and storing data into buffer-local
30 ;; variables, and one for utility functions which send commands to
31 ;; server, waits for an answer, and return information. The latter
32 ;; part is layered on top of the previous.
34 ;; The imap.el API consist of the following functions, other functions
35 ;; in this file should not be called directly and the result of doing
36 ;; so are at best undefined.
40 ;; imap-open, imap-opened, imap-authenticate, imap-close,
41 ;; imap-capability, imap-namespace, imap-error-text
45 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
46 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
47 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
48 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
49 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
50 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
51 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
55 ;; imap-fetch-asynch, imap-fetch,
56 ;; imap-current-message, imap-list-to-message-set,
57 ;; imap-message-get, imap-message-map
58 ;; imap-message-envelope-date, imap-message-envelope-subject,
59 ;; imap-message-envelope-from, imap-message-envelope-sender,
60 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
61 ;; imap-message-envelope-cc, imap-message-envelope-bcc
62 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
63 ;; imap-message-body, imap-message-flag-permanent-p
64 ;; imap-message-flags-set, imap-message-flags-del
65 ;; imap-message-flags-add, imap-message-copyuid
66 ;; imap-message-copy, imap-message-appenduid
67 ;; imap-message-append, imap-envelope-from
70 ;; It is my hope that these commands should be pretty self
71 ;; explanatory for someone who knows IMAP. All functions have
72 ;; additional documentation on how to invoke them.
74 ;; imap.el supports RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1). The implemented
75 ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
76 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
77 ;; LOGINDISABLED), and the GSSAPI / Kerberos V4 sections of RFC1731
78 ;; (with use of external program `imtest'), and RFC2971 (ID). It also
79 ;; takes advantage of the UNSELECT extension in Cyrus IMAPD.
81 ;; Without the work of John McClary Prevost and Jim Radford this library
82 ;; would not have seen the light of day. Many thanks.
84 ;; This is a transcript of a short interactive session for demonstration
87 ;; (imap-open "my.mail.server")
88 ;; => " *imap* my.mail.server:0"
90 ;; The rest are invoked with current buffer as the buffer returned by
91 ;; `imap-open'. It is possible to do it all without this, but it would
92 ;; look ugly here since `buffer' is always the last argument for all
93 ;; imap.el API functions.
95 ;; (imap-authenticate "myusername" "mypassword")
98 ;; (imap-mailbox-lsub "*")
99 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
101 ;; (imap-mailbox-list "INBOX.n%")
102 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
104 ;; (imap-mailbox-select "INBOX.nnimap")
107 ;; (imap-mailbox-get 'exists)
110 ;; (imap-mailbox-get 'uidvalidity)
113 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
116 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
117 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
121 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
122 ;; Use IEEE floats (which are effectively exact)? -- fx
123 ;; o Don't use `read' at all (important places already fixed)
124 ;; o Accept list of articles instead of message set string in most
125 ;; imap-message-* functions.
126 ;; o Send strings as literal if they contain, e.g., ".
130 ;; - 19991218 added starttls/digest-md5 patch,
131 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
132 ;; NB! you need SLIM for starttls.el and digest-md5.el
133 ;; - 19991023 committed to pgnus
138 (eval-when-compile (require 'cl))
140 ;; For Emacs <22.2 and XEmacs.
141 (unless (fboundp 'declare-function) (defmacro declare-function (&rest _r)))
142 (autoload 'sasl-find-mechanism "sasl")
143 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
144 (autoload 'digest-md5-digest-response "digest-md5")
145 (autoload 'digest-md5-digest-uri "digest-md5")
146 (autoload 'digest-md5-challenge "digest-md5")
147 (autoload 'rfc2104-hash "rfc2104")
148 (autoload 'utf7-encode "utf7")
149 (autoload 'utf7-decode "utf7")
150 (autoload 'format-spec "format-spec")
151 (autoload 'format-spec-make "format-spec"))
156 "Low-level IMAP issues."
160 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
162 "List of strings containing commands for Kerberos 4 authentication.
163 %s is replaced with server hostname, %p with port to connect to, and
164 %l with the value of `imap-default-user'. The program should accept
165 IMAP commands on stdin and return responses to stdout. Each entry in
166 the list is tried until a successful connection is made."
168 :type '(repeat string))
170 (defcustom imap-gssapi-program (list
171 (concat "gsasl %s %p "
172 "--mechanism GSSAPI "
173 "--authentication-id %l")
174 "imtest -m gssapi -u %l -p %p %s")
175 "List of strings containing commands for GSSAPI (krb5) authentication.
176 %s is replaced with server hostname, %p with port to connect to, and
177 %l with the value of `imap-default-user'. The program should accept
178 IMAP commands on stdin and return responses to stdout. Each entry in
179 the list is tried until a successful connection is made."
181 :type '(repeat string))
183 (defcustom imap-shell-program '("ssh %s imapd"
185 "ssh %g ssh %s imapd"
186 "rsh %g rsh %s imapd")
187 "A list of strings, containing commands for IMAP connection.
188 Within a string, %s is replaced with the server address, %p with port
189 number on server, %g with `imap-shell-host', and %l with
190 `imap-default-user'. The program should read IMAP commands from stdin
191 and write IMAP response to stdout. Each entry in the list is tried
192 until a successful connection is made."
194 :type '(repeat string))
196 (defcustom imap-process-connection-type nil
197 "Value for `process-connection-type' to use for Kerberos4, GSSAPI, shell, and SSL.
198 The `process-connection-type' variable controls the type of device
199 used to communicate with subprocesses. Values are nil to use a
200 pipe, or t or `pty' to use a pty. The value has no effect if the
201 system has no ptys or if all ptys are busy: then a pipe is used
202 in any case. The value takes effect when an IMAP server is
203 opened; changing it after that has no effect."
208 (defcustom imap-use-utf7 t
209 "If non-nil, do utf7 encoding/decoding of mailbox names.
210 Since the UTF7 decoding currently only decodes into ISO-8859-1
211 characters, you may disable this decoding if you need to access UTF7
212 encoded mailboxes which doesn't translate into ISO-8859-1."
216 (defcustom imap-log nil
217 "If non-nil, an imap session trace is placed in `imap-log-buffer'.
218 Note that username, passwords and other privacy sensitive
219 information (such as e-mail) may be stored in the buffer.
220 It is not written to disk, however. Do not enable this
221 variable unless you are comfortable with that.
223 See also `imap-debug'."
227 (defcustom imap-debug nil
228 "If non-nil, trace imap- functions into `imap-debug-buffer'.
229 Uses `trace-function-background', so you can turn it off with,
232 Note that username, passwords and other privacy sensitive
233 information (such as e-mail) may be stored in the buffer.
234 It is not written to disk, however. Do not enable this
235 variable unless you are comfortable with that.
237 This variable only takes effect when loading the `imap' library.
238 See also `imap-log'."
242 (defcustom imap-shell-host "gateway"
243 "Hostname of rlogin proxy."
247 (defcustom imap-default-user (user-login-name)
248 "Default username to use."
252 (defcustom imap-read-timeout (if (string-match
253 "windows-nt\\|os/2\\|cygwin"
254 (symbol-name system-type))
257 "How long to wait between checking for the end of output.
258 Shorter values mean quicker response, but is more CPU intensive."
262 (defcustom imap-store-password nil
263 "If non-nil, store session password without prompting."
267 ;; Various variables.
269 (defvar imap-fetch-data-hook nil
270 "Hooks called after receiving each FETCH response.")
272 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
273 "Priority of streams to consider when opening connection to server.")
275 (defvar imap-stream-alist
276 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
277 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
278 (tls imap-tls-p imap-tls-open)
279 (ssl imap-tls-p imap-tls-open)
280 (network imap-network-p imap-network-open)
281 (shell imap-shell-p imap-shell-open)
282 (starttls imap-starttls-p imap-starttls-open))
283 "Definition of network streams.
287 NAME names the stream, CHECK is a function returning non-nil if the
288 server support the stream and OPEN is a function for opening the
291 (defvar imap-authenticators '(gssapi
298 "Priority of authenticators to consider when authenticating to server.")
300 (defvar imap-authenticator-alist
301 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
302 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
303 (sasl imap-sasl-auth-p imap-sasl-auth)
304 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
305 (login imap-login-p imap-login-auth)
306 (anonymous imap-anonymous-p imap-anonymous-auth)
307 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
308 "Definition of authenticators.
310 \(NAME CHECK AUTHENTICATE)
312 NAME names the authenticator. CHECK is a function returning non-nil if
313 the server support the authenticator and AUTHENTICATE is a function
314 for doing the actual authentication.")
316 (defvar imap-error nil
317 "Error codes from the last command.")
319 (defvar imap-logout-timeout nil
320 "Close server immediately if it can't logout in this number of seconds.
321 If it is nil, never close server until logout completes. Normally,
322 the value of this variable will be bound to a certain value to which
323 an application program that uses this module specifies on a per-server
326 ;; Internal constants. Change these and die.
328 (defconst imap-default-port 143)
329 (defconst imap-default-ssl-port 993)
330 (defconst imap-default-tls-port 993)
331 (defconst imap-default-stream 'network)
332 (defconst imap-coding-system-for-read 'binary)
333 (defconst imap-coding-system-for-write 'binary)
334 (defconst imap-local-variables '(imap-server
343 imap-current-target-mailbox
353 imap-calculate-literal-size-first
355 (defconst imap-log-buffer "*imap-log*")
356 (defconst imap-debug-buffer "*imap-debug*")
358 ;; Internal variables.
360 (defvar imap-stream nil)
361 (defvar imap-auth nil)
362 (defvar imap-server nil)
363 (defvar imap-port nil)
364 (defvar imap-username nil)
365 (defvar imap-password nil)
366 (defvar imap-last-authenticator nil)
367 (defvar imap-calculate-literal-size-first nil)
368 (defvar imap-state 'closed
370 Valid states are `closed', `initial', `nonauth', `auth', `selected'
373 (defvar imap-server-eol "\r\n"
374 "The EOL string sent from the server.")
376 (defvar imap-client-eol "\r\n"
377 "The EOL string we send to the server.")
379 (defvar imap-current-mailbox nil
380 "Current mailbox name.")
382 (defvar imap-current-target-mailbox nil
383 "Current target mailbox for COPY and APPEND commands.")
385 (defvar imap-mailbox-data nil
386 "Obarray with mailbox data.")
388 (defvar imap-mailbox-prime 997
389 "Length of `imap-mailbox-data'.")
391 (defvar imap-current-message nil
392 "Current message number.")
394 (defvar imap-message-data nil
395 "Obarray with message data.")
397 (defvar imap-message-prime 997
398 "Length of `imap-message-data'.")
400 (defvar imap-capability nil
401 "Capability for server.")
407 (defvar imap-namespace nil
408 "Namespace for current server.")
410 (defvar imap-reached-tag 0
411 "Lower limit on command tags that have been parsed.")
413 (defvar imap-failed-tags nil
414 "Alist of tags that failed.
415 Each element is a list with four elements; tag (a integer), response
416 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
417 human readable response text (a string).")
420 "Command tag number.")
422 (defvar imap-process nil
425 (defvar imap-continuation nil
426 "Non-nil indicates that the server emitted a continuation request.
427 The actual value is really the text on the continuation line.")
429 (defvar imap-callbacks nil
430 "List of response tags and callbacks, on the form `(number . function)'.
431 The function should take two arguments, the first the IMAP tag and the
432 second the status (OK, NO, BAD etc) of the command.")
434 (defvar imap-enable-exchange-bug-workaround nil
435 "Send FETCH UID commands as *:* instead of *.
437 When non-nil, use an alternative UIDS form. Enabling appears to
438 be required for some servers (e.g., Microsoft Exchange 2007)
439 which otherwise would trigger a response `BAD The specified
440 message set is invalid.'. We don't unconditionally use this
441 form, since this is said to be significantly inefficient.
443 This variable is set to t automatically per server if the
444 canonical form fails.")
447 ;; Utility functions:
449 (defun imap-remassoc (key alist)
450 "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
451 The modified ALIST is returned. If the first member
452 of ALIST has a car that is `equal' to KEY, there is no way to remove it
453 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
454 sure of changing the value of `foo'."
456 (if (equal key (caar alist))
458 (setcdr alist (imap-remassoc key (cdr alist)))
461 (defmacro imap-disable-multibyte ()
462 "Enable multibyte in the current buffer."
463 (unless (featurep 'xemacs)
464 '(set-buffer-multibyte nil)))
466 (defsubst imap-utf7-encode (string)
470 (utf7-encode string t)
472 "imap: Could not UTF7 encode `%s', using it unencoded..."
477 (defsubst imap-utf7-decode (string)
481 (utf7-decode string t)
483 "imap: Could not UTF7 decode `%s', using it undecoded..."
488 (defsubst imap-ok-p (status)
491 (setq imap-error status)
494 (defun imap-error-text (&optional buffer)
495 (with-current-buffer (or buffer (current-buffer))
496 (nth 3 (car imap-failed-tags))))
499 ;; Server functions; stream stuff:
501 (defun imap-log (string-or-buffer)
503 (with-current-buffer (get-buffer-create imap-log-buffer)
504 (imap-disable-multibyte)
505 (buffer-disable-undo)
506 (goto-char (point-max))
507 (if (bufferp string-or-buffer)
508 (insert-buffer-substring string-or-buffer)
509 (insert string-or-buffer)))))
511 (defun imap-kerberos4-stream-p (buffer)
512 (imap-capability 'AUTH=KERBEROS_V4 buffer))
514 (defun imap-kerberos4-open (name buffer server port)
515 (let ((cmds imap-kerberos4-program)
517 (while (and (not done) (setq cmd (pop cmds)))
518 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
520 (let* ((port (or port imap-default-port))
521 (coding-system-for-read imap-coding-system-for-read)
522 (coding-system-for-write imap-coding-system-for-write)
523 (process-connection-type imap-process-connection-type)
524 (process (start-process
525 name buffer shell-file-name shell-command-switch
530 ?p (number-to-string port)
531 ?l imap-default-user))))
534 (with-current-buffer buffer
535 (setq imap-client-eol "\n"
536 imap-calculate-literal-size-first t)
537 (while (and (memq (process-status process) '(open run))
538 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
539 (goto-char (point-min))
540 ;; Athena IMTEST can output SSL verify errors
541 (or (while (looking-at "^verify error:num=")
544 (or (while (looking-at "^TLS connection established")
547 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
548 (or (while (looking-at "^C:")
551 ;; cyrus 1.6 imtest print "S: " before server greeting
552 (or (not (looking-at "S: "))
555 (not (and (imap-parse-greeting)
556 ;; success in imtest < 1.6:
557 (or (re-search-forward
558 "^__\\(.*\\)__\n" nil t)
559 ;; success in imtest 1.6:
561 "^\\(Authenticat.*\\)" nil t))
562 (setq response (match-string 1)))))
563 (accept-process-output process 1)
566 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
567 (if response (concat "done, " response) "failed"))
568 (if (and response (let ((case-fold-search nil))
569 (not (string-match "failed" response))))
571 (if (memq (process-status process) '(open run))
573 (delete-process process)
577 (defun imap-gssapi-stream-p (buffer)
578 (imap-capability 'AUTH=GSSAPI buffer))
580 (defun imap-gssapi-open (name buffer server port)
581 (let ((cmds imap-gssapi-program)
583 (while (and (not done) (setq cmd (pop cmds)))
584 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
586 (let* ((port (or port imap-default-port))
587 (coding-system-for-read imap-coding-system-for-read)
588 (coding-system-for-write imap-coding-system-for-write)
589 (process-connection-type imap-process-connection-type)
590 (process (start-process
591 name buffer shell-file-name shell-command-switch
596 ?p (number-to-string port)
597 ?l imap-default-user))))
600 (with-current-buffer buffer
601 (setq imap-client-eol "\n"
602 imap-calculate-literal-size-first t)
603 (while (and (memq (process-status process) '(open run))
604 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
605 (goto-char (point-min))
606 ;; Athena IMTEST can output SSL verify errors
607 (or (while (looking-at "^verify error:num=")
610 (or (while (looking-at "^TLS connection established")
613 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
614 (or (while (looking-at "^C:")
617 ;; cyrus 1.6 imtest print "S: " before server greeting
618 (or (not (looking-at "S: "))
621 ;; GNU SASL may print 'Trying ...' first.
622 (or (not (looking-at "Trying "))
625 (not (and (imap-parse-greeting)
626 ;; success in imtest 1.6:
628 (concat "^\\(\\(Authenticat.*\\)\\|\\("
629 "Client authentication "
632 (setq response (match-string 1)))))
633 (accept-process-output process 1)
637 (message "GSSAPI IMAP connection: %s" (or response "failed"))
638 (if (and response (let ((case-fold-search nil))
639 (not (string-match "failed" response))))
641 (if (memq (process-status process) '(open run))
643 (delete-process process)
647 (defun imap-tls-p (_buffer)
650 (defun imap-tls-open (name buffer server port)
651 (let* ((port (or port imap-default-tls-port))
652 (coding-system-for-read imap-coding-system-for-read)
653 (coding-system-for-write imap-coding-system-for-write)
654 (process (open-network-stream name buffer server port
657 (while (and (memq (process-status process) '(open run))
658 ;; FIXME: Per the "blue moon" comment, the process/buffer
659 ;; handling here, and elsewhere in functions which open
660 ;; streams, looks confused. Obviously we can change buffers
661 ;; if a different process handler kicks in from
662 ;; `accept-process-output' or `sit-for' below, and TRT seems
663 ;; to be to `save-buffer' around those calls. (I wonder why
664 ;; `sit-for' is used with a non-zero wait.) -- fx
665 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
666 (goto-char (point-max))
668 (not (imap-parse-greeting)))
669 (accept-process-output process 1)
672 (when (memq (process-status process) '(open run))
675 (defun imap-network-p (_buffer)
678 (defun imap-network-open (name buffer server port)
679 (let* ((port (or port imap-default-port))
680 (coding-system-for-read imap-coding-system-for-read)
681 (coding-system-for-write imap-coding-system-for-write)
682 (process (open-network-stream name buffer server port)))
684 (while (and (memq (process-status process) '(open run))
685 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
686 (goto-char (point-min))
687 (not (imap-parse-greeting)))
688 (accept-process-output process 1)
691 (when (memq (process-status process) '(open run))
694 (defun imap-shell-p (_buffer)
697 (defun imap-shell-open (name buffer server port)
698 (let ((cmds (if (listp imap-shell-program) imap-shell-program
699 (list imap-shell-program)))
701 (while (and (not done) (setq cmd (pop cmds)))
702 (message "imap: Opening IMAP connection with `%s'..." cmd)
703 (setq imap-client-eol "\n")
704 (let* ((port (or port imap-default-port))
705 (coding-system-for-read imap-coding-system-for-read)
706 (coding-system-for-write imap-coding-system-for-write)
707 (process-connection-type imap-process-connection-type)
708 (process (start-process
709 name buffer shell-file-name shell-command-switch
715 ?p (number-to-string port)
716 ?l imap-default-user)))))
718 (while (and (memq (process-status process) '(open run))
719 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
720 (goto-char (point-max))
722 (not (imap-parse-greeting)))
723 (accept-process-output process 1)
727 (when (memq (process-status process) '(open run))
728 (setq done process)))))
731 (message "imap: Opening IMAP connection with `%s'...done" cmd)
733 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
736 (defun imap-starttls-p (buffer)
737 (imap-capability 'STARTTLS buffer))
739 (defun imap-starttls-open (name buffer server port)
740 (message "imap: Connecting with STARTTLS...")
741 (let* ((port (or port imap-default-port))
742 (coding-system-for-read imap-coding-system-for-read)
743 (coding-system-for-write imap-coding-system-for-write)
744 (process (open-network-stream
745 name buffer server port
747 :capability-command "1 CAPABILITY\r\n"
748 :always-query-capabilities t
749 :end-of-command "\r\n"
752 (lambda (capabilities)
753 (when (string-match-p "STARTTLS" capabilities)
756 (memq (process-status process) '(open run)))))
757 (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
760 ;; Server functions; authenticator stuff:
762 (defun imap-interactive-login (buffer loginfunc)
763 "Login to server in BUFFER.
764 Return t if login was successful, nil otherwise.
766 LOGINFUNC is passed a username and a password. It should return
767 t if it successfully authenticates, nil otherwise."
768 (with-current-buffer buffer
769 (make-local-variable 'imap-username)
770 (make-local-variable 'imap-password)
771 (let (user passwd ret)
772 ;; (condition-case ()
773 (while (or (not user) (not passwd))
774 (setq user (or imap-username
775 (read-from-minibuffer
777 "imap: username for %s (using stream `%s'): "
778 imap-server imap-stream)
779 (or user imap-default-user))))
784 "imap: password for %s@%s (using authenticator `%s'): "
785 user imap-server imap-auth))))
786 (when (and user passwd)
787 (if (funcall loginfunc user passwd)
789 (message "imap: Login successful...")
792 (when (and (not imap-password)
793 (or imap-store-password
794 (y-or-n-p "imap: Store password for this IMAP session? ")))
795 (setq imap-password passwd)))
796 (message "imap: Login failed...")
798 (setq imap-password nil)
800 ;; (quit (with-current-buffer buffer
803 ;; (error (with-current-buffer buffer
808 (defun imap-gssapi-auth-p (_buffer)
809 (eq imap-stream 'gssapi))
811 (defun imap-gssapi-auth (_buffer)
812 (message "imap: Authenticating using GSSAPI...%s"
813 (if (eq imap-stream 'gssapi) "done" "failed"))
814 (eq imap-stream 'gssapi))
816 (defun imap-kerberos4-auth-p (buffer)
817 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
818 (eq imap-stream 'kerberos4)))
820 (defun imap-kerberos4-auth (_buffer)
821 (message "imap: Authenticating using Kerberos 4...%s"
822 (if (eq imap-stream 'kerberos4) "done" "failed"))
823 (eq imap-stream 'kerberos4))
825 (defun imap-cram-md5-p (buffer)
826 (imap-capability 'AUTH=CRAM-MD5 buffer))
828 (defun imap-cram-md5-auth (buffer)
829 "Login to server using the AUTH CRAM-MD5 method."
830 (message "imap: Authenticating using CRAM-MD5...")
831 (let ((done (imap-interactive-login
833 (lambda (user passwd)
835 (imap-send-command-wait
837 "AUTHENTICATE CRAM-MD5"
839 (let* ((decoded (base64-decode-string challenge))
840 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
841 (response (concat user " " hash))
842 (encoded (base64-encode-string response)))
845 (message "imap: Authenticating using CRAM-MD5...done")
846 (message "imap: Authenticating using CRAM-MD5...failed"))))
848 (defun imap-login-p (buffer)
849 (and (not (imap-capability 'LOGINDISABLED buffer))
850 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
852 (defun imap-quote-specials (string)
855 (goto-char (point-min))
856 (while (re-search-forward "[\\\"]" nil t)
862 (defun imap-login-auth (buffer)
863 "Login to server using the LOGIN command."
864 (message "imap: Plaintext authentication...")
865 (imap-interactive-login buffer
866 (lambda (user passwd)
867 (imap-ok-p (imap-send-command-wait
869 (imap-quote-specials user)
871 (imap-quote-specials passwd)
874 (defun imap-anonymous-p (_buffer)
877 (defun imap-anonymous-auth (buffer)
878 (message "imap: Logging in anonymously...")
879 (with-current-buffer buffer
880 (imap-ok-p (imap-send-command-wait
881 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
882 (system-name)) "\"")))))
884 ;;; Compiler directives.
886 (defvar imap-sasl-client)
887 (defvar imap-sasl-step)
889 (defun imap-sasl-make-mechanisms (buffer)
892 (let ((name (symbol-name sym)))
893 (if (and (> (length name) 5)
894 (string-equal "AUTH=" (substring name 0 5 )))
895 (setq mecs (cons (substring name 5) mecs)))))
896 (imap-capability nil buffer))
899 (declare-function sasl-find-mechanism "sasl" (mechanism))
900 (declare-function sasl-mechanism-name "sasl" (mechanism))
901 (declare-function sasl-make-client "sasl" (mechanism name service server))
902 (declare-function sasl-next-step "sasl" (client step))
903 (declare-function sasl-step-data "sasl" (step))
904 (declare-function sasl-step-set-data "sasl" (step data))
906 (defun imap-sasl-auth-p (buffer)
907 (and (condition-case ()
910 (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
912 (defun imap-sasl-auth (buffer)
913 "Login to server using the SASL method."
914 (message "imap: Authenticating using SASL...")
915 (with-current-buffer buffer
916 (make-local-variable 'imap-username)
917 (make-local-variable 'imap-sasl-client)
918 (make-local-variable 'imap-sasl-step)
919 (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
922 (setq user (or imap-username
923 (read-from-minibuffer
924 (concat "IMAP username for " imap-server " using SASL "
925 (sasl-mechanism-name mechanism) ": ")
926 (or user imap-default-user))))
928 (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
929 imap-sasl-step (sasl-next-step imap-sasl-client nil))
930 (let ((tag (imap-send-command
931 (if (sasl-step-data imap-sasl-step)
932 (format "AUTHENTICATE %s %s"
933 (sasl-mechanism-name mechanism)
934 (sasl-step-data imap-sasl-step))
935 (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
937 (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
938 (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
939 (setq imap-continuation nil
940 imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
941 (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
942 (base64-encode-string (sasl-step-data imap-sasl-step) t)
944 (if (imap-ok-p (imap-wait-for-tag tag))
945 (setq imap-username user
947 (message "Login failed...")
951 (defun imap-digest-md5-p (buffer)
952 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
954 (require 'digest-md5)
957 (defun imap-digest-md5-auth (buffer)
958 "Login to server using the AUTH DIGEST-MD5 method."
959 (message "imap: Authenticating using DIGEST-MD5...")
960 (imap-interactive-login
962 (lambda (user passwd)
966 "AUTHENTICATE DIGEST-MD5"
968 (digest-md5-parse-digest-challenge
969 (base64-decode-string challenge))
971 (digest-md5-digest-uri
972 "imap" (digest-md5-challenge 'realm)))
974 (digest-md5-digest-response
975 user passwd digest-uri)))
976 (base64-encode-string response 'no-line-break))))
978 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
980 (setq imap-continuation nil)
981 (imap-send-command-1 "")
982 (imap-ok-p (imap-wait-for-tag tag)))))))
986 (defun imap-open-1 (buffer)
987 (with-current-buffer buffer
989 (setq imap-current-mailbox nil
990 imap-current-message nil
992 imap-process (condition-case ()
993 (funcall (nth 2 (assq imap-stream
995 "imap" buffer imap-server imap-port)
998 (set-process-filter imap-process 'imap-arrival-filter)
999 (set-process-sentinel imap-process 'imap-sentinel)
1000 (while (and (eq imap-state 'initial)
1001 (memq (process-status imap-process) '(open run)))
1002 (message "Waiting for response from %s..." imap-server)
1003 (accept-process-output imap-process 1))
1004 (message "Waiting for response from %s...done" imap-server)
1005 (and (memq (process-status imap-process) '(open run))
1008 (defun imap-open (server &optional port stream auth buffer)
1009 "Open an IMAP connection to host SERVER at PORT returning a buffer.
1010 If PORT is unspecified, a default value is used (143 except
1011 for SSL which use 993).
1012 STREAM indicates the stream to use, see `imap-streams' for available
1013 streams. If nil, it choices the best stream the server is capable of.
1014 AUTH indicates authenticator to use, see `imap-authenticators' for
1015 available authenticators. If nil, it choices the best stream the
1016 server is capable of.
1017 BUFFER can be a buffer or a name of a buffer, which is created if
1018 necessary. If nil, the buffer name is generated."
1019 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1020 (with-current-buffer (get-buffer-create buffer)
1021 (if (imap-opened buffer)
1022 (imap-close buffer))
1023 (mapc 'make-local-variable imap-local-variables)
1024 (imap-disable-multibyte)
1025 (buffer-disable-undo)
1026 (setq imap-server (or server imap-server))
1027 (setq imap-port (or port imap-port))
1028 (setq imap-auth (or auth imap-auth))
1029 (setq imap-stream (or stream imap-stream))
1030 (message "imap: Connecting to %s..." imap-server)
1031 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1032 (imap-open-1 buffer)))
1034 (message "imap: Connecting to %s...failed" imap-server)
1036 (when (null imap-stream)
1037 ;; Need to choose stream.
1038 (let ((streams imap-streams))
1039 (while (setq stream (pop streams))
1040 ;; OK to use this stream?
1041 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1043 (if (not (eq imap-default-stream stream))
1044 (with-current-buffer (get-buffer-create
1045 (generate-new-buffer-name " *temp*"))
1046 (mapc 'make-local-variable imap-local-variables)
1047 (imap-disable-multibyte)
1048 (buffer-disable-undo)
1049 (setq imap-server (or server imap-server))
1050 (setq imap-port (or port imap-port))
1051 (setq imap-auth (or auth imap-auth))
1052 (message "imap: Reconnecting with stream `%s'..." stream)
1053 (if (null (let ((imap-stream stream))
1054 (imap-open-1 (current-buffer))))
1056 (kill-buffer (current-buffer))
1058 "imap: Reconnecting with stream `%s'...failed"
1060 ;; We're done, kill the first connection
1062 (let ((name (if (stringp buffer)
1064 (buffer-name buffer))))
1065 (kill-buffer buffer)
1066 (rename-buffer name)
1067 ;; set the passed buffer to the current one,
1068 ;; so that (imap-opened buffer) later will work
1069 (setq buffer (current-buffer)))
1070 (message "imap: Reconnecting with stream `%s'...done"
1072 (setq imap-stream stream)
1073 (setq imap-capability nil)
1074 (setq streams nil)))
1076 (message "imap: Connecting to %s...done" imap-server)
1077 (setq imap-stream stream)
1078 (setq imap-capability nil)
1079 (setq streams nil))))))
1080 (when (imap-opened buffer)
1081 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1082 ;; (debug "opened+state+auth+buffer" (imap-opened buffer) imap-state imap-auth buffer)
1086 (defcustom imap-ping-server t
1087 "If non-nil, check if IMAP is open.
1088 See the function `imap-ping-server'."
1089 :version "23.1" ;; No Gnus
1093 (defun imap-opened (&optional buffer)
1094 "Return non-nil if connection to imap server in BUFFER is open.
1095 If BUFFER is nil then the current buffer is used."
1096 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1097 (buffer-live-p buffer)
1098 (with-current-buffer buffer
1100 (memq (process-status imap-process) '(open run))
1101 (if imap-ping-server
1105 (defun imap-ping-server (&optional buffer)
1106 "Ping the IMAP server in BUFFER with a \"NOOP\" command.
1107 Return non-nil if the server responds, and nil if it does not
1108 respond. If BUFFER is nil, the current buffer is used."
1110 (imap-ok-p (imap-send-command-wait "NOOP" buffer))
1113 (defun imap-authenticate (&optional user passwd buffer)
1114 "Authenticate to server in BUFFER, using current buffer if nil.
1115 It uses the authenticator specified when opening the server.
1117 Optional arguments USER and PASSWD specify the username and
1118 password to use if the authenticator requires a username and/or
1119 password. If omitted or nil, the authenticator may query the
1120 user for a username and/or password."
1121 (with-current-buffer (or buffer (current-buffer))
1122 (if (not (eq imap-state 'nonauth))
1123 (or (eq imap-state 'auth)
1124 (eq imap-state 'selected)
1125 (eq imap-state 'examine))
1126 (make-local-variable 'imap-username)
1127 (make-local-variable 'imap-password)
1128 (make-local-variable 'imap-last-authenticator)
1129 (when user (setq imap-username user))
1130 (when passwd (setq imap-password passwd))
1132 (and (setq imap-last-authenticator
1133 (assq imap-auth imap-authenticator-alist))
1134 (funcall (nth 2 imap-last-authenticator) (current-buffer))
1135 (setq imap-state 'auth))
1136 ;; Choose authenticator.
1137 (let ((auths imap-authenticators)
1139 (while (setq auth (pop auths))
1140 ;; OK to use authenticator?
1141 (setq imap-last-authenticator
1142 (assq auth imap-authenticator-alist))
1143 (when (funcall (nth 1 imap-last-authenticator) (current-buffer))
1144 (message "imap: Authenticating to `%s' using `%s'..."
1146 (setq imap-auth auth)
1147 (if (funcall (nth 2 imap-last-authenticator) (current-buffer))
1149 (message "imap: Authenticating to `%s' using `%s'...done"
1151 ;; set imap-state correctly on successful auth attempt
1152 (setq imap-state 'auth)
1153 ;; stop iterating through the authenticator list
1155 (message "imap: Authenticating to `%s' using `%s'...failed"
1156 imap-server auth)))))
1159 (defun imap-close (&optional buffer)
1160 "Close connection to server in BUFFER.
1161 If BUFFER is nil, the current buffer is used."
1162 (with-current-buffer (or buffer (current-buffer))
1167 (when (and imap-process
1168 (memq (process-status imap-process) '(open run)))
1169 (delete-process imap-process))
1170 (setq imap-current-mailbox nil
1171 imap-current-message nil
1176 (defun imap-capability (&optional identifier buffer)
1177 "Return a list of identifiers which server in BUFFER support.
1178 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1179 If BUFFER is nil, the current buffer is assumed."
1180 (with-current-buffer (or buffer (current-buffer))
1181 (unless imap-capability
1182 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1183 (setq imap-capability '(IMAP2))))
1185 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1188 (defun imap-id (&optional list-of-values buffer)
1189 "Identify client to server in BUFFER, and return server identity.
1190 LIST-OF-VALUES is nil, or a plist with identifier and value
1191 strings to send to the server to identify the client.
1193 Return a list of identifiers which server in BUFFER support, or
1194 nil if it doesn't support ID or returns no information.
1196 If BUFFER is nil, the current buffer is assumed."
1197 (with-current-buffer (or buffer (current-buffer))
1198 (when (and (imap-capability 'ID)
1199 (imap-ok-p (imap-send-command-wait
1200 (if (null list-of-values)
1202 (concat "ID (" (mapconcat (lambda (el)
1203 (concat "\"" el "\""))
1208 (defun imap-namespace (&optional buffer)
1209 "Return a namespace hierarchy at server in BUFFER.
1210 If BUFFER is nil, the current buffer is assumed."
1211 (with-current-buffer (or buffer (current-buffer))
1212 (unless imap-namespace
1213 (when (imap-capability 'NAMESPACE)
1214 (imap-send-command-wait "NAMESPACE")))
1217 (defun imap-send-command-wait (command &optional buffer)
1218 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1220 (defun imap-logout (&optional buffer)
1221 (or buffer (setq buffer (current-buffer)))
1222 (if imap-logout-timeout
1223 (with-timeout (imap-logout-timeout
1225 (with-current-buffer buffer
1226 (delete-process imap-process))
1228 (imap-send-command "LOGOUT" buffer))
1229 (imap-send-command "LOGOUT" buffer)))
1231 (defun imap-logout-wait (&optional buffer)
1232 (or buffer (setq buffer (current-buffer)))
1233 (if imap-logout-timeout
1234 (with-timeout (imap-logout-timeout
1236 (with-current-buffer buffer
1237 (delete-process imap-process))
1239 (imap-send-command-wait "LOGOUT" buffer))
1240 (imap-send-command-wait "LOGOUT" buffer)))
1243 ;; Mailbox functions:
1245 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1246 (with-current-buffer (or buffer (current-buffer))
1247 (if imap-mailbox-data
1248 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1250 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1251 propname value mailbox (current-buffer)))
1254 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1255 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1258 (defun imap-mailbox-get (propname &optional mailbox buffer)
1259 (let ((mailbox (imap-utf7-encode mailbox)))
1260 (with-current-buffer (or buffer (current-buffer))
1261 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1263 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1264 (with-current-buffer (or buffer (current-buffer))
1268 (push (funcall func (if mailbox-decoder
1269 (funcall mailbox-decoder (symbol-name s))
1270 (symbol-name s))) result))
1274 (defun imap-mailbox-map (func &optional buffer)
1275 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1276 Function should take a mailbox name (a string) as
1278 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1280 (defun imap-current-mailbox (&optional buffer)
1281 (with-current-buffer (or buffer (current-buffer))
1282 (imap-utf7-decode imap-current-mailbox)))
1284 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1285 (and (string= mailbox imap-current-mailbox)
1287 (eq imap-state 'examine))
1289 (eq imap-state 'selected)))))
1291 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1292 (with-current-buffer (or buffer (current-buffer))
1293 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1295 (defun imap-mailbox-select-1 (mailbox &optional examine)
1296 "Select MAILBOX on server in BUFFER.
1297 If EXAMINE is non-nil, do a read-only select."
1298 (if (imap-current-mailbox-p-1 mailbox examine)
1299 imap-current-mailbox
1300 (setq imap-current-mailbox mailbox)
1301 (if (imap-ok-p (imap-send-command-wait
1302 (concat (if examine "EXAMINE" "SELECT") " \""
1305 (setq imap-message-data (make-vector imap-message-prime 0)
1306 imap-state (if examine 'examine 'selected))
1307 imap-current-mailbox)
1308 ;; Failed SELECT/EXAMINE unselects current mailbox
1309 (setq imap-current-mailbox nil))))
1311 (defun imap-mailbox-select (mailbox &optional examine buffer)
1312 (with-current-buffer (or buffer (current-buffer))
1314 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1316 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1317 (with-current-buffer (or buffer (current-buffer))
1318 (imap-mailbox-select-1 mailbox 'examine)))
1320 (defun imap-mailbox-examine (mailbox &optional buffer)
1321 "Examine MAILBOX on server in BUFFER."
1322 (imap-mailbox-select mailbox 'examine buffer))
1324 (defun imap-mailbox-unselect (&optional buffer)
1325 "Close current folder in BUFFER, without expunging articles."
1326 (with-current-buffer (or buffer (current-buffer))
1327 (when (or (eq imap-state 'auth)
1328 (and (imap-capability 'UNSELECT)
1329 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1331 (imap-send-command-wait (concat "EXAMINE \""
1332 imap-current-mailbox
1334 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1335 (setq imap-current-mailbox nil
1336 imap-message-data nil
1340 (defun imap-mailbox-expunge (&optional asynch buffer)
1341 "Expunge articles in current folder in BUFFER.
1342 If ASYNCH, do not wait for successful completion of the command.
1343 If BUFFER is nil the current buffer is assumed."
1344 (with-current-buffer (or buffer (current-buffer))
1345 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1347 (imap-send-command "EXPUNGE")
1348 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1350 (defun imap-mailbox-close (&optional asynch buffer)
1351 "Expunge articles and close current folder in BUFFER.
1352 If ASYNCH, do not wait for successful completion of the command.
1353 If BUFFER is nil the current buffer is assumed."
1354 (with-current-buffer (or buffer (current-buffer))
1355 (when imap-current-mailbox
1357 (imap-add-callback (imap-send-command "CLOSE")
1358 `(lambda (tag status)
1359 (message "IMAP mailbox `%s' closed... %s"
1360 imap-current-mailbox status)
1361 (when (eq ,imap-current-mailbox
1362 imap-current-mailbox)
1363 ;; Don't wipe out data if another mailbox
1365 (setq imap-current-mailbox nil
1366 imap-message-data nil
1367 imap-state 'auth))))
1368 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1369 (setq imap-current-mailbox nil
1370 imap-message-data nil
1374 (defun imap-mailbox-create-1 (mailbox)
1375 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1377 (defun imap-mailbox-create (mailbox &optional buffer)
1378 "Create MAILBOX on server in BUFFER.
1379 If BUFFER is nil the current buffer is assumed."
1380 (with-current-buffer (or buffer (current-buffer))
1381 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1383 (defun imap-mailbox-delete (mailbox &optional buffer)
1384 "Delete MAILBOX on server in BUFFER.
1385 If BUFFER is nil the current buffer is assumed."
1386 (let ((mailbox (imap-utf7-encode mailbox)))
1387 (with-current-buffer (or buffer (current-buffer))
1389 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1391 (defun imap-mailbox-rename (oldname newname &optional buffer)
1392 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1393 If BUFFER is nil the current buffer is assumed."
1394 (let ((oldname (imap-utf7-encode oldname))
1395 (newname (imap-utf7-encode newname)))
1396 (with-current-buffer (or buffer (current-buffer))
1398 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1399 "\"" newname "\""))))))
1401 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1402 "Return a list of subscribed mailboxes on server in BUFFER.
1403 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1404 non-nil, a hierarchy delimiter is added to root. REFERENCE is an
1405 implementation-specific string that has to be passed to lsub command."
1406 (with-current-buffer (or buffer (current-buffer))
1407 ;; Make sure we know the hierarchy separator for root's hierarchy
1408 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1409 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1410 (imap-utf7-encode root) "\"")))
1411 ;; clear list data (NB not delimiter and other stuff)
1412 (imap-mailbox-map-1 (lambda (mailbox)
1413 (imap-mailbox-put 'lsub nil mailbox)))
1415 (imap-send-command-wait
1416 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1417 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1420 (imap-mailbox-map-1 (lambda (mailbox)
1421 (when (imap-mailbox-get-1 'lsub mailbox)
1422 (push (imap-utf7-decode mailbox) out))))
1425 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1426 "Return a list of mailboxes matching ROOT on server in BUFFER.
1427 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1428 root. REFERENCE is an implementation-specific string that has to be
1429 passed to list command."
1430 (with-current-buffer (or buffer (current-buffer))
1431 ;; Make sure we know the hierarchy separator for root's hierarchy
1432 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1433 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1434 (imap-utf7-encode root) "\"")))
1435 ;; clear list data (NB not delimiter and other stuff)
1436 (imap-mailbox-map-1 (lambda (mailbox)
1437 (imap-mailbox-put 'list nil mailbox)))
1439 (imap-send-command-wait
1440 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1441 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1444 (imap-mailbox-map-1 (lambda (mailbox)
1445 (when (imap-mailbox-get-1 'list mailbox)
1446 (push (imap-utf7-decode mailbox) out))))
1449 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1450 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1451 Returns non-nil if successful."
1452 (with-current-buffer (or buffer (current-buffer))
1453 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1454 (imap-utf7-encode mailbox)
1457 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1458 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1459 Returns non-nil if successful."
1460 (with-current-buffer (or buffer (current-buffer))
1461 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1462 (imap-utf7-encode mailbox)
1465 (defun imap-mailbox-status (mailbox items &optional buffer)
1466 "Get status items ITEM in MAILBOX from server in BUFFER.
1467 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1468 the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
1469 or `unseen'. If ITEMS is a list of symbols, a list of values is
1470 returned, if ITEMS is a symbol only its value is returned."
1471 (with-current-buffer (or buffer (current-buffer))
1473 (imap-send-command-wait (list "STATUS \""
1474 (imap-utf7-encode mailbox)
1482 (mapcar (lambda (item)
1483 (imap-mailbox-get item mailbox))
1485 (imap-mailbox-get items mailbox)))))
1487 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1488 "Send status item requests ITEMS on MAILBOX to server in BUFFER.
1489 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1490 the STATUS data items -- i.e., `messages', `recent', `uidnext', `uidvalidity'
1491 or `unseen'. The IMAP command tag is returned."
1492 (with-current-buffer (or buffer (current-buffer))
1493 (imap-send-command (list "STATUS \""
1494 (imap-utf7-encode mailbox)
1502 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1503 "Get ACL on MAILBOX from server in BUFFER."
1504 (let ((mailbox (imap-utf7-encode mailbox)))
1505 (with-current-buffer (or buffer (current-buffer))
1507 (imap-send-command-wait (list "GETACL \""
1508 (or mailbox imap-current-mailbox)
1510 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1512 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1513 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1514 (let ((mailbox (imap-utf7-encode mailbox)))
1515 (with-current-buffer (or buffer (current-buffer))
1517 (imap-send-command-wait (list "SETACL \""
1518 (or mailbox imap-current-mailbox)
1524 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1525 "Remove <id,rights> pairs for IDENTIFIER from MAILBOX on server in BUFFER."
1526 (let ((mailbox (imap-utf7-encode mailbox)))
1527 (with-current-buffer (or buffer (current-buffer))
1529 (imap-send-command-wait (list "DELETEACL \""
1530 (or mailbox imap-current-mailbox)
1535 ;; Message functions:
1537 (defun imap-current-message (&optional buffer)
1538 (with-current-buffer (or buffer (current-buffer))
1539 imap-current-message))
1541 (defun imap-list-to-message-set (list)
1542 (mapconcat (lambda (item)
1543 (number-to-string item))
1549 (defun imap-range-to-message-set (range)
1554 (car item) (cdr item))
1555 (format "%d" item)))
1556 (if (and (listp range) (not (listp (cdr range))))
1557 (list range) ;; make (1 . 2) into ((1 . 2))
1561 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1562 (with-current-buffer (or buffer (current-buffer))
1563 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1565 (imap-list-to-message-set uids)
1569 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1570 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1571 UIDS can be a string, number or a list of numbers. If RECEIVE is
1572 non-nil, return these properties."
1573 (with-current-buffer (or buffer (current-buffer))
1574 (when (imap-ok-p (imap-send-command-wait
1575 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1577 (imap-list-to-message-set uids)
1580 (if (or (null receive) (stringp uids))
1583 (mapcar (lambda (uid)
1585 (mapcar (lambda (prop)
1586 (imap-message-get uid prop))
1588 (imap-message-get uid receive)))
1590 (imap-message-get uids receive))))))
1592 (defun imap-message-put (uid propname value &optional buffer)
1593 (with-current-buffer (or buffer (current-buffer))
1594 (if imap-message-data
1595 (put (intern (number-to-string uid) imap-message-data)
1597 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1598 uid propname value (current-buffer)))
1601 (defun imap-message-get (uid propname &optional buffer)
1602 (with-current-buffer (or buffer (current-buffer))
1603 (get (intern-soft (number-to-string uid) imap-message-data)
1606 (defun imap-message-map (func propname &optional buffer)
1607 "Map a function across each message in `imap-message-data', returning a list."
1608 (with-current-buffer (or buffer (current-buffer))
1612 (push (funcall func (get s 'UID) (get s propname)) result))
1616 (defmacro imap-message-envelope-date (uid &optional buffer)
1617 `(with-current-buffer (or ,buffer (current-buffer))
1618 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1620 (defmacro imap-message-envelope-subject (uid &optional buffer)
1621 `(with-current-buffer (or ,buffer (current-buffer))
1622 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1624 (defmacro imap-message-envelope-from (uid &optional buffer)
1625 `(with-current-buffer (or ,buffer (current-buffer))
1626 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1628 (defmacro imap-message-envelope-sender (uid &optional buffer)
1629 `(with-current-buffer (or ,buffer (current-buffer))
1630 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1632 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1633 `(with-current-buffer (or ,buffer (current-buffer))
1634 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1636 (defmacro imap-message-envelope-to (uid &optional buffer)
1637 `(with-current-buffer (or ,buffer (current-buffer))
1638 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1640 (defmacro imap-message-envelope-cc (uid &optional buffer)
1641 `(with-current-buffer (or ,buffer (current-buffer))
1642 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1644 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1645 `(with-current-buffer (or ,buffer (current-buffer))
1646 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1648 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1649 `(with-current-buffer (or ,buffer (current-buffer))
1650 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1652 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1653 `(with-current-buffer (or ,buffer (current-buffer))
1654 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1656 (defmacro imap-message-body (uid &optional buffer)
1657 `(with-current-buffer (or ,buffer (current-buffer))
1658 (imap-message-get ,uid 'BODY)))
1660 ;; FIXME: Should this try to use CHARSET? -- fx
1661 (defun imap-search (predicate &optional buffer)
1662 (with-current-buffer (or buffer (current-buffer))
1663 (imap-mailbox-put 'search 'dummy)
1664 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1665 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1667 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1669 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1671 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1672 "Return t if FLAG can be permanently saved on articles.
1673 MAILBOX specifies a mailbox on the server in BUFFER."
1674 (with-current-buffer (or buffer (current-buffer))
1675 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1676 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1678 (defun imap-message-flags-set (articles flags &optional silent buffer)
1679 (when (and articles flags)
1680 (with-current-buffer (or buffer (current-buffer))
1681 (imap-ok-p (imap-send-command-wait
1682 (concat "UID STORE " articles
1683 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1685 (defun imap-message-flags-del (articles flags &optional silent buffer)
1686 (when (and articles flags)
1687 (with-current-buffer (or buffer (current-buffer))
1688 (imap-ok-p (imap-send-command-wait
1689 (concat "UID STORE " articles
1690 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1692 (defun imap-message-flags-add (articles flags &optional silent buffer)
1693 (when (and articles flags)
1694 (with-current-buffer (or buffer (current-buffer))
1695 (imap-ok-p (imap-send-command-wait
1696 (concat "UID STORE " articles
1697 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1699 ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
1700 ;; Signal an error if we'd get an integer overflow.
1702 ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
1703 ;; `imap-string-to-integer'.
1704 (defun imap-string-to-integer (string &optional base)
1705 (let ((number (string-to-number string base)))
1706 (if (> number most-positive-fixnum)
1708 (format "String %s cannot be converted to a Lisp integer" number))
1711 (defun imap-fetch-safe (uids props &optional receive nouidfetch buffer)
1712 "Like `imap-fetch', but DTRT with Exchange 2007 bug.
1713 However, UIDS here is a cons, where the car is the canonical form
1714 of the UIDS specification, and the cdr is the one which works with
1715 Exchange 2007 or, potentially, other buggy servers.
1716 See `imap-enable-exchange-bug-workaround'."
1717 ;; The first time we get here for a given, we'll try the canonical
1718 ;; form. If we get the known error from the buggy server, set the
1719 ;; flag buffer-locally (to account for connections to multiple
1720 ;; servers), then re-try with the alternative UIDS spec. We don't
1721 ;; unconditionally use the alternative form, since the
1722 ;; currently-used alternatives are seriously inefficient with some
1723 ;; servers (although they are valid).
1725 ;; FIXME: Maybe it would be cleaner to have a flag to not signal
1726 ;; the error (which otherwise gives a message), and test
1727 ;; `imap-failed-tags'. Also, Other IMAP clients use other forms of
1728 ;; request which work with Exchange, e.g. Claws does "UID FETCH 1:*
1729 ;; (UID)" rather than "FETCH UID 1,*". Is there a good reason not
1731 (condition-case data
1732 ;; Binding `debug-on-error' allows us to get the error from
1733 ;; `imap-parse-response' -- it's normally caught by Emacs around
1734 ;; execution of a process filter.
1735 (let ((debug-on-error t))
1736 (imap-fetch (if imap-enable-exchange-bug-workaround
1739 props receive nouidfetch buffer))
1741 (if (and (not imap-enable-exchange-bug-workaround)
1742 ;; This is the Exchange 2007 response. It may be more
1743 ;; robust just to check for a BAD response to the
1745 (string-match "The specified message set is invalid"
1747 (with-current-buffer (or buffer (current-buffer))
1748 (set (make-local-variable 'imap-enable-exchange-bug-workaround)
1750 (imap-fetch (cdr uids) props receive nouidfetch))
1751 (signal (car data) (cdr data))))))
1753 (defun imap-message-copyuid-1 (mailbox)
1754 (if (imap-capability 'UIDPLUS)
1755 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1756 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1757 (let ((old-mailbox imap-current-mailbox)
1759 (imap-message-data (make-vector 2 0)))
1760 (when (imap-mailbox-examine-1 mailbox)
1762 (and (imap-fetch-safe '("*" . "*:*") "UID")
1763 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1764 (apply 'max (imap-message-map
1765 (lambda (uid _prop) uid) 'UID))))
1767 (imap-mailbox-select old-mailbox (eq state 'examine))
1768 (imap-mailbox-unselect)))))))
1770 (defun imap-message-copyuid (mailbox &optional buffer)
1771 (with-current-buffer (or buffer (current-buffer))
1772 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1774 (defun imap-message-copy (articles mailbox
1775 &optional dont-create no-copyuid buffer)
1776 "Copy ARTICLES to MAILBOX on server in BUFFER.
1777 ARTICLES is a string message set. Create mailbox if it doesn't exist,
1778 unless DONT-CREATE is non-nil. On success, return a list with
1779 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1780 first element. The rest of list contains the saved articles' UIDs."
1782 (with-current-buffer (or buffer (current-buffer))
1783 (let ((mailbox (imap-utf7-encode mailbox)))
1784 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1785 (imap-current-target-mailbox mailbox))
1786 (if (imap-ok-p (imap-send-command-wait cmd))
1788 (when (and (not dont-create)
1789 ;; removed because of buggy Oracle server
1790 ;; that doesn't send TRYCREATE tags (which
1791 ;; is a MUST according to specifications):
1792 ;;(imap-mailbox-get-1 'trycreate mailbox)
1793 (imap-mailbox-create-1 mailbox))
1794 (imap-ok-p (imap-send-command-wait cmd)))))
1796 (imap-message-copyuid-1 mailbox)))))))
1798 ;; FIXME: Amalgamate with imap-message-copyuid-1, using an extra arg, since it
1799 ;; shares most of the code? -- fx
1800 (defun imap-message-appenduid-1 (mailbox)
1801 (if (imap-capability 'UIDPLUS)
1802 (imap-mailbox-get-1 'appenduid mailbox)
1803 (let ((old-mailbox imap-current-mailbox)
1805 (imap-message-data (make-vector 2 0)))
1806 (when (imap-mailbox-examine-1 mailbox)
1808 (and (imap-fetch-safe '("*" . "*:*") "UID")
1809 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1810 (apply 'max (imap-message-map
1811 (lambda (uid _prop) uid) 'UID))))
1813 (imap-mailbox-select old-mailbox (eq state 'examine))
1814 (imap-mailbox-unselect)))))))
1816 (defun imap-message-appenduid (mailbox &optional buffer)
1817 (with-current-buffer (or buffer (current-buffer))
1818 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1820 (defun imap-message-append (mailbox article &optional _flags _date-time buffer)
1821 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1822 FLAGS and DATE-TIME is currently not used. Return a cons holding
1823 uidvalidity of MAILBOX and UID the newly created article got, or nil
1825 (let ((mailbox (imap-utf7-encode mailbox)))
1826 (with-current-buffer (or buffer (current-buffer))
1827 (and (let ((imap-current-target-mailbox mailbox))
1829 (imap-send-command-wait
1830 (list "APPEND \"" mailbox "\" " article))))
1831 (imap-message-appenduid-1 mailbox)))))
1833 (defun imap-body-lines (body)
1834 "Return number of lines in article by looking at the mime bodystructure BODY."
1836 (if (stringp (car body))
1837 (cond ((and (string= (upcase (car body)) "TEXT")
1838 (numberp (nth 7 body)))
1840 ((and (string= (upcase (car body)) "MESSAGE")
1841 (numberp (nth 9 body)))
1844 (apply '+ (mapcar 'imap-body-lines body)))
1847 (defun imap-envelope-from (from)
1848 "Return a FROM string line."
1850 (concat (aref from 0)
1851 (if (aref from 0) " <")
1855 (if (aref from 0) ">"))))
1858 ;; Internal functions.
1860 (defun imap-add-callback (tag func)
1861 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1863 (defun imap-send-command-1 (cmdstr)
1864 (setq cmdstr (concat cmdstr imap-client-eol))
1866 (process-send-string imap-process cmdstr))
1868 (defun imap-send-command (command &optional buffer)
1869 (with-current-buffer (or buffer (current-buffer))
1870 (if (not (listp command)) (setq command (list command)))
1871 (let ((tag (setq imap-tag (1+ imap-tag)))
1873 (setq cmdstr (concat (number-to-string imap-tag) " "))
1874 (while (setq cmd (pop command))
1875 (cond ((stringp cmd)
1876 (setq cmdstr (concat cmdstr cmd)))
1878 (let ((eol imap-client-eol)
1879 (calcfirst imap-calculate-literal-size-first)
1881 (with-current-buffer cmd
1883 (setq size (buffer-size)))
1884 (when (not (equal eol "\r\n"))
1885 ;; XXX modifies buffer!
1886 (goto-char (point-min))
1887 (while (search-forward "\r\n" nil t)
1888 (replace-match eol)))
1890 (setq size (buffer-size))))
1892 (concat cmdstr (format "{%d}" size))))
1895 (imap-send-command-1 cmdstr)
1897 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1898 (setq command nil) ;; abort command if no cont-req
1899 (let ((process imap-process)
1900 (stream imap-stream)
1901 (eol imap-client-eol))
1902 (with-current-buffer cmd
1904 (process-send-region process (point-min)
1906 (process-send-string process imap-client-eol))))
1907 (setq imap-continuation nil)))
1909 (imap-send-command-1 cmdstr)
1913 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1914 nil ;; abort command if no cont-req
1915 (cons (funcall cmd imap-continuation)
1917 (setq imap-continuation nil)))
1919 (error "Unknown command type"))))
1921 (imap-send-command-1 cmdstr))
1924 (defun imap-wait-for-tag (tag &optional buffer)
1925 (with-current-buffer (or buffer (current-buffer))
1926 (let (imap-have-messaged)
1927 (while (and (null imap-continuation)
1928 (memq (process-status imap-process) '(open run))
1929 (< imap-reached-tag tag))
1930 (let ((len (/ (buffer-size) 1024))
1933 (setq imap-have-messaged t)
1934 (message "imap read: %dk" len))
1935 (accept-process-output imap-process
1936 (truncate imap-read-timeout)
1937 (truncate (* (- imap-read-timeout
1938 (truncate imap-read-timeout))
1940 ;; A process can die _before_ we have processed everything it
1941 ;; has to say. Moreover, this can happen in between the call to
1942 ;; accept-process-output and the call to process-status in an
1943 ;; iteration of the loop above.
1944 (when (and (null imap-continuation)
1945 (< imap-reached-tag tag))
1946 (accept-process-output imap-process 0 0))
1947 (when imap-have-messaged
1949 (and (memq (process-status imap-process) '(open run))
1950 (or (assq tag imap-failed-tags)
1951 (if imap-continuation
1955 (defun imap-sentinel (process string)
1956 (delete-process process))
1958 (defun imap-find-next-line ()
1959 "Return point at end of current line, taking into account literals.
1960 Return nil if no complete line has arrived."
1961 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1964 (if (match-string 1)
1965 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1967 (goto-char (+ (point) (string-to-number (match-string 1))))
1968 (imap-find-next-line))
1971 (defun imap-arrival-filter (proc string)
1972 "IMAP process filter."
1973 ;; Sometimes, we are called even though the process has died.
1974 ;; Better abstain from doing stuff in that case.
1975 (when (buffer-name (process-buffer proc))
1976 (with-current-buffer (process-buffer proc)
1977 (goto-char (point-max))
1981 (goto-char (point-min))
1982 (while (setq end (imap-find-next-line))
1984 (narrow-to-region (point-min) end)
1985 (delete-char (- (length imap-server-eol)))
1986 (goto-char (point-min))
1988 (cond ((eq imap-state 'initial)
1989 (imap-parse-greeting))
1990 ((or (eq imap-state 'auth)
1991 (eq imap-state 'nonauth)
1992 (eq imap-state 'selected)
1993 (eq imap-state 'examine))
1994 (imap-parse-response))
1996 (message "Unknown state %s in arrival filter"
1998 (delete-region (point-min) (point-max)))))))))
2003 (defsubst imap-forward ()
2004 (or (eobp) (forward-char)))
2007 ;; ; Unsigned 32-bit integer
2008 ;; ; (0 <= n < 4,294,967,296)
2010 (defsubst imap-parse-number ()
2011 (when (looking-at "[0-9]+")
2013 (string-to-number (match-string 0))
2014 (goto-char (match-end 0)))))
2016 ;; literal = "{" number "}" CRLF *CHAR8
2017 ;; ; Number represents the number of CHAR8s
2019 (defsubst imap-parse-literal ()
2020 (when (looking-at "{\\([0-9]+\\)}\r\n")
2021 (let ((pos (match-end 0))
2022 (len (string-to-number (match-string 1))))
2023 (if (< (point-max) (+ pos len))
2025 (goto-char (+ pos len))
2026 (buffer-substring pos (+ pos len))))))
2028 ;; string = quoted / literal
2030 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
2032 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2033 ;; "\" quoted-specials
2035 ;; quoted-specials = DQUOTE / "\"
2037 ;; TEXT-CHAR = <any CHAR except CR and LF>
2039 (defsubst imap-parse-string ()
2040 (cond ((eq (char-after) ?\")
2042 (let ((p (point)) (name ""))
2043 (skip-chars-forward "^\"\\\\")
2044 (setq name (buffer-substring p (point)))
2045 (while (eq (char-after) ?\\)
2046 (setq p (1+ (point)))
2048 (skip-chars-forward "^\"\\\\")
2049 (setq name (concat name (buffer-substring p (point)))))
2052 ((eq (char-after) ?{)
2053 (imap-parse-literal))))
2057 (defsubst imap-parse-nil ()
2058 (if (looking-at "NIL")
2059 (goto-char (match-end 0))))
2061 ;; nstring = string / nil
2063 (defsubst imap-parse-nstring ()
2064 (or (imap-parse-string)
2065 (and (imap-parse-nil)
2068 ;; astring = atom / string
2070 ;; atom = 1*ATOM-CHAR
2072 ;; ATOM-CHAR = <any CHAR except atom-specials>
2074 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
2077 ;; list-wildcards = "%" / "*"
2079 ;; quoted-specials = DQUOTE / "\"
2081 (defsubst imap-parse-astring ()
2082 (or (imap-parse-string)
2083 (buffer-substring (point)
2084 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2085 (goto-char (1- (match-end 0)))
2089 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
2092 ;; addr-adl = nstring
2093 ;; ; Holds route from [RFC-822] route-addr if
2096 ;; addr-host = nstring
2097 ;; ; nil indicates [RFC-822] group syntax.
2098 ;; ; Otherwise, holds [RFC-822] domain name
2100 ;; addr-mailbox = nstring
2101 ;; ; nil indicates end of [RFC-822] group; if
2102 ;; ; non-nil and addr-host is nil, holds
2103 ;; ; [RFC-822] group name.
2104 ;; ; Otherwise, holds [RFC-822] local-part
2105 ;; ; after removing [RFC-822] quoting
2107 ;; addr-name = nstring
2108 ;; ; If non-nil, holds phrase from [RFC-822]
2109 ;; ; mailbox after removing [RFC-822] quoting
2112 (defsubst imap-parse-address ()
2114 (when (eq (char-after) ?\()
2116 (setq address (vector (prog1 (imap-parse-nstring)
2118 (prog1 (imap-parse-nstring)
2120 (prog1 (imap-parse-nstring)
2122 (imap-parse-nstring)))
2123 (when (eq (char-after) ?\))
2127 ;; address-list = "(" 1*address ")" / nil
2131 (defsubst imap-parse-address-list ()
2132 (if (eq (char-after) ?\()
2133 (let (address addresses)
2135 (while (and (not (eq (char-after) ?\)))
2136 ;; next line for MS Exchange bug
2137 (progn (and (eq (char-after) ? ) (imap-forward)) t)
2138 (setq address (imap-parse-address)))
2139 (setq addresses (cons address addresses)))
2140 (when (eq (char-after) ?\))
2142 (nreverse addresses)))
2143 ;; With assert, the code might not be eval'd.
2144 ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2147 ;; mailbox = "INBOX" / astring
2148 ;; ; INBOX is case-insensitive. All case variants of
2149 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2150 ;; ; not as an astring. An astring which consists of
2151 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
2152 ;; ; is considered to be INBOX and not an astring.
2153 ;; ; Refer to section 5.1 for further
2154 ;; ; semantic details of mailbox names.
2156 (defsubst imap-parse-mailbox ()
2157 (let ((mailbox (imap-parse-astring)))
2158 (if (string-equal "INBOX" (upcase mailbox))
2162 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2164 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
2165 ;; ; Authentication condition
2167 ;; resp-cond-bye = "BYE" SP resp-text
2169 (defun imap-parse-greeting ()
2170 "Parse an IMAP greeting."
2171 (cond ((looking-at "\\* OK ")
2172 (setq imap-state 'nonauth))
2173 ((looking-at "\\* PREAUTH ")
2174 (setq imap-state 'auth))
2175 ((looking-at "\\* BYE ")
2176 (setq imap-state 'closed))))
2178 ;; response = *(continue-req / response-data) response-done
2180 ;; continue-req = "+" SP (resp-text / base64) CRLF
2182 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
2183 ;; mailbox-data / message-data / capability-data) CRLF
2185 ;; response-done = response-tagged / response-fatal
2187 ;; response-fatal = "*" SP resp-cond-bye CRLF
2188 ;; ; Server closes connection immediately
2190 ;; response-tagged = tag SP resp-cond-state CRLF
2192 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2193 ;; ; Status condition
2195 ;; resp-cond-bye = "BYE" SP resp-text
2197 ;; mailbox-data = "FLAGS" SP flag-list /
2198 ;; "LIST" SP mailbox-list /
2199 ;; "LSUB" SP mailbox-list /
2200 ;; "SEARCH" *(SP nz-number) /
2201 ;; "STATUS" SP mailbox SP "("
2202 ;; [status-att SP number *(SP status-att SP number)] ")" /
2203 ;; number SP "EXISTS" /
2204 ;; number SP "RECENT"
2206 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2208 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2210 ;; ; IMAP4rev1 servers which offer RFC 1730
2211 ;; ; compatibility MUST list "IMAP4" as the first
2214 (defun imap-parse-response ()
2215 "Parse an IMAP command response."
2217 (case (setq token (read (current-buffer)))
2218 (+ (setq imap-continuation
2219 (or (buffer-substring (min (point-max) (1+ (point)))
2222 (* (case (prog1 (setq token (read (current-buffer)))
2224 (OK (imap-parse-resp-text))
2225 (NO (imap-parse-resp-text))
2226 (BAD (imap-parse-resp-text))
2227 (BYE (imap-parse-resp-text))
2228 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
2229 (LIST (imap-parse-data-list 'list))
2230 (LSUB (imap-parse-data-list 'lsub))
2231 (SEARCH (imap-mailbox-put
2233 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2234 (STATUS (imap-parse-status))
2235 (CAPABILITY (setq imap-capability
2236 (read (concat "(" (upcase (buffer-substring
2237 (point) (point-max)))
2239 (ID (setq imap-id (read (buffer-substring (point)
2241 (ACL (imap-parse-acl))
2242 (t (case (prog1 (read (current-buffer))
2244 (EXISTS (imap-mailbox-put 'exists token))
2245 (RECENT (imap-mailbox-put 'recent token))
2247 (FETCH (imap-parse-fetch token))
2248 (t (message "Garbage: %s" (buffer-string)))))))
2250 (if (not (integerp token))
2251 (message "Garbage: %s" (buffer-string))
2252 (case (prog1 (setq status (read (current-buffer)))
2255 (setq imap-reached-tag (max imap-reached-tag token))
2256 (imap-parse-resp-text)))
2258 (setq imap-reached-tag (max imap-reached-tag token))
2260 (imap-parse-resp-text))
2262 (when (eq (char-after) ?\[)
2263 (setq code (buffer-substring (point)
2264 (search-forward "]")))
2266 (setq text (buffer-substring (point) (point-max)))
2267 (push (list token status code text)
2268 imap-failed-tags))))
2270 (setq imap-reached-tag (max imap-reached-tag token))
2272 (imap-parse-resp-text))
2274 (when (eq (char-after) ?\[)
2275 (setq code (buffer-substring (point)
2276 (search-forward "]")))
2278 (setq text (buffer-substring (point) (point-max)))
2279 (push (list token status code text) imap-failed-tags)
2280 (error "Internal error, tag %s status %s code %s text %s"
2281 token status code text))))
2282 (t (message "Garbage: %s" (buffer-string))))
2283 (when (assq token imap-callbacks)
2284 (funcall (cdr (assq token imap-callbacks)) token status)
2285 (setq imap-callbacks
2286 (imap-remassoc token imap-callbacks)))))))))
2288 ;; resp-text = ["[" resp-text-code "]" SP] text
2290 ;; text = 1*TEXT-CHAR
2292 ;; TEXT-CHAR = <any CHAR except CR and LF>
2294 (defun imap-parse-resp-text ()
2295 (imap-parse-resp-text-code))
2297 ;; resp-text-code = "ALERT" /
2298 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2299 ;; "NEWNAME" SP string SP string /
2301 ;; "PERMANENTFLAGS" SP "("
2302 ;; [flag-perm *(SP flag-perm)] ")" /
2306 ;; "UIDNEXT" SP nz-number /
2307 ;; "UIDVALIDITY" SP nz-number /
2308 ;; "UNSEEN" SP nz-number /
2309 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2311 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2313 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2315 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2317 ;; ; Identifies a set of messages. For message
2318 ;; ; sequence numbers, these are consecutive
2319 ;; ; numbers from 1 to the number of messages in
2321 ;; ; Comma delimits individual numbers, colon
2322 ;; ; delimits between two numbers inclusive.
2323 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2324 ;; ; 14,15 for a mailbox with 15 messages.
2326 ;; sequence-num = nz-number / "*"
2327 ;; ; * is the largest number in use. For message
2328 ;; ; sequence numbers, it is the number of messages
2329 ;; ; in the mailbox. For unique identifiers, it is
2330 ;; ; the unique identifier of the last message in
2333 ;; flag-perm = flag / "\*"
2335 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2336 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2337 ;; ; Does not include "\Recent"
2339 ;; flag-extension = "\" atom
2340 ;; ; Future expansion. Client implementations
2341 ;; ; MUST accept flag-extension flags. Server
2342 ;; ; implementations MUST NOT generate
2343 ;; ; flag-extension flags except as defined by
2344 ;; ; future standard or standards-track
2345 ;; ; revisions of this specification.
2347 ;; flag-keyword = atom
2349 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2351 (defun imap-parse-resp-text-code ()
2352 ;; xxx next line for stalker communigate pro 3.3.1 bug
2353 (when (looking-at " \\[")
2355 (when (eq (char-after) ?\[)
2357 (cond ((search-forward "PERMANENTFLAGS " nil t)
2358 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2359 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2360 (imap-mailbox-put 'uidnext (match-string 1)))
2361 ((search-forward "UNSEEN " nil t)
2362 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2363 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2364 (imap-mailbox-put 'uidvalidity (match-string 1)))
2365 ((search-forward "READ-ONLY" nil t)
2366 (imap-mailbox-put 'read-only t))
2367 ((search-forward "NEWNAME " nil t)
2368 (let (oldname newname)
2369 (setq oldname (imap-parse-string))
2371 (setq newname (imap-parse-string))
2372 (imap-mailbox-put 'newname newname oldname)))
2373 ((search-forward "TRYCREATE" nil t)
2374 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2375 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2376 (imap-mailbox-put 'appenduid
2377 (list (match-string 1)
2378 (string-to-number (match-string 2)))
2379 imap-current-target-mailbox))
2380 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2381 (imap-mailbox-put 'copyuid (list (match-string 1)
2384 imap-current-target-mailbox))
2385 ((search-forward "ALERT] " nil t)
2386 (message "Imap server %s information: %s" imap-server
2387 (buffer-substring (point) (point-max)))))))
2389 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2390 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2392 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2393 ;; *(SP mbx-list-oflag) /
2394 ;; mbx-list-oflag *(SP mbx-list-oflag)
2396 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2397 ;; ; Other flags; multiple possible per LIST response
2399 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2400 ;; ; Selectability flags; only one per LIST response
2402 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2403 ;; "\" quoted-specials
2405 ;; quoted-specials = DQUOTE / "\"
2407 (defun imap-parse-data-list (type)
2408 (let (flags delimiter mailbox)
2409 (setq flags (imap-parse-flag-list))
2410 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2411 (setq delimiter (match-string 1))
2412 (goto-char (1+ (match-end 0)))
2413 (when (setq mailbox (imap-parse-mailbox))
2414 (imap-mailbox-put type t mailbox)
2415 (imap-mailbox-put 'list-flags flags mailbox)
2416 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2418 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2419 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2420 ;; "INTERNALDATE" SPACE date_time /
2421 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2422 ;; "RFC822.SIZE" SPACE number /
2423 ;; "BODY" ["STRUCTURE"] SPACE body /
2424 ;; "BODY" section ["<" number ">"] SPACE nstring /
2425 ;; "UID" SPACE uniqueid) ")"
2427 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2428 ;; SPACE time SPACE zone <">
2430 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2431 ;; ["." (section_text / "MIME")])] "]"
2433 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2434 ;; SPACE header_list / "TEXT"
2436 ;; header_fld_name ::= astring
2438 ;; header_list ::= "(" 1#header_fld_name ")"
2440 (defsubst imap-parse-header-list ()
2441 (when (eq (char-after) ?\()
2443 (while (not (eq (char-after) ?\)))
2445 (push (imap-parse-astring) strlist))
2447 (nreverse strlist))))
2449 (defsubst imap-parse-fetch-body-section ()
2451 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2452 (if (eq (char-before) ? )
2454 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2455 (search-forward "]" nil t))
2458 (defun imap-parse-fetch (response)
2459 (when (eq (char-after) ?\()
2460 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2461 rfc822size body bodydetail bodystructure flags-empty)
2462 ;; Courier can insert spurious blank characters which will
2463 ;; confuse `read', so skip past them.
2464 (while (let ((moved (skip-chars-forward " \t")))
2465 (prog1 (not (eq (char-after) ?\)))
2466 (unless (= moved 0) (backward-char))))
2468 (let ((token (read (current-buffer))))
2470 (cond ((eq token 'UID)
2471 (setq uid (condition-case ()
2472 (read (current-buffer))
2475 (setq flags (imap-parse-flag-list))
2477 (setq flags-empty 't)))
2478 ((eq token 'ENVELOPE)
2479 (setq envelope (imap-parse-envelope)))
2480 ((eq token 'INTERNALDATE)
2481 (setq internaldate (imap-parse-string)))
2483 (setq rfc822 (imap-parse-nstring)))
2484 ((eq token 'RFC822.HEADER)
2485 (setq rfc822header (imap-parse-nstring)))
2486 ((eq token 'RFC822.TEXT)
2487 (setq rfc822text (imap-parse-nstring)))
2488 ((eq token 'RFC822.SIZE)
2489 (setq rfc822size (read (current-buffer))))
2491 (if (eq (char-before) ?\[)
2493 (upcase (imap-parse-fetch-body-section))
2494 (and (eq (char-after) ?<)
2495 (buffer-substring (1+ (point))
2496 (search-forward ">" nil t)))
2497 (progn (imap-forward)
2498 (imap-parse-nstring)))
2500 (setq body (imap-parse-body))))
2501 ((eq token 'BODYSTRUCTURE)
2502 (setq bodystructure (imap-parse-body))))))
2504 (setq imap-current-message uid)
2505 (imap-message-put uid 'UID uid)
2506 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2507 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2508 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2509 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2510 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2511 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2512 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2513 (and body (imap-message-put uid 'BODY body))
2514 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2515 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2516 (run-hooks 'imap-fetch-data-hook)))))
2518 ;; mailbox-data = ...
2519 ;; "STATUS" SP mailbox SP "("
2520 ;; [status-att SP number
2521 ;; *(SP status-att SP number)] ")"
2524 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2527 (defun imap-parse-status ()
2528 (let ((mailbox (imap-parse-mailbox)))
2529 (if (eq (char-after) ? )
2531 (when (and mailbox (eq (char-after) ?\())
2532 (while (and (not (eq (char-after) ?\)))
2533 (or (forward-char) t)
2534 (looking-at "\\([A-Za-z]+\\) "))
2535 (let ((token (upcase (match-string 1))))
2536 (goto-char (match-end 0))
2537 (cond ((string= token "MESSAGES")
2538 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2539 ((string= token "RECENT")
2540 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2541 ((string= token "UIDNEXT")
2542 (and (looking-at "[0-9]+")
2543 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2544 (goto-char (match-end 0))))
2545 ((string= token "UIDVALIDITY")
2546 (and (looking-at "[0-9]+")
2547 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2548 (goto-char (match-end 0))))
2549 ((string= token "UNSEEN")
2550 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2552 (message "Unknown status data %s in mailbox %s ignored"
2554 (read (current-buffer)))))))))
2556 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2559 ;; identifier ::= astring
2561 ;; rights ::= astring
2563 (defun imap-parse-acl ()
2564 (let ((mailbox (imap-parse-mailbox))
2565 identifier rights acl)
2566 (while (eq (char-after) ?\ )
2568 (setq identifier (imap-parse-astring))
2570 (setq rights (imap-parse-astring))
2571 (setq acl (append acl (list (cons identifier rights)))))
2572 (imap-mailbox-put 'acl acl mailbox)))
2574 ;; flag-list = "(" [flag *(SP flag)] ")"
2576 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2577 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2578 ;; ; Does not include "\Recent"
2580 ;; flag-keyword = atom
2582 ;; flag-extension = "\" atom
2583 ;; ; Future expansion. Client implementations
2584 ;; ; MUST accept flag-extension flags. Server
2585 ;; ; implementations MUST NOT generate
2586 ;; ; flag-extension flags except as defined by
2587 ;; ; future standard or standards-track
2588 ;; ; revisions of this specification.
2590 (defun imap-parse-flag-list ()
2591 (let (flag-list start)
2592 (assert (eq (char-after) ?\() nil "In imap-parse-flag-list 1")
2593 (while (and (not (eq (char-after) ?\)))
2596 ;; next line for Courier IMAP bug.
2597 (skip-chars-forward " ")
2599 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2600 (push (buffer-substring start (point)) flag-list))
2601 (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list 2")
2603 (nreverse flag-list)))
2605 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2606 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2607 ;; env-in-reply-to SP env-message-id ")"
2609 ;; env-bcc = "(" 1*address ")" / nil
2611 ;; env-cc = "(" 1*address ")" / nil
2613 ;; env-date = nstring
2615 ;; env-from = "(" 1*address ")" / nil
2617 ;; env-in-reply-to = nstring
2619 ;; env-message-id = nstring
2621 ;; env-reply-to = "(" 1*address ")" / nil
2623 ;; env-sender = "(" 1*address ")" / nil
2625 ;; env-subject = nstring
2627 ;; env-to = "(" 1*address ")" / nil
2629 (defun imap-parse-envelope ()
2630 (when (eq (char-after) ?\()
2632 (vector (prog1 (imap-parse-nstring) ;; date
2634 (prog1 (imap-parse-nstring) ;; subject
2636 (prog1 (imap-parse-address-list) ;; from
2638 (prog1 (imap-parse-address-list) ;; sender
2640 (prog1 (imap-parse-address-list) ;; reply-to
2642 (prog1 (imap-parse-address-list) ;; to
2644 (prog1 (imap-parse-address-list) ;; cc
2646 (prog1 (imap-parse-address-list) ;; bcc
2648 (prog1 (imap-parse-nstring) ;; in-reply-to
2650 (prog1 (imap-parse-nstring) ;; message-id
2653 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2655 (defsubst imap-parse-string-list ()
2656 (cond ((eq (char-after) ?\() ;; body-fld-param
2659 (while (setq str (imap-parse-string))
2661 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2662 ;; between body-fld-param's sometimes
2663 (or (eq (char-after) ?\")
2665 (nreverse strlist)))
2669 ;; body-extension = nstring / number /
2670 ;; "(" body-extension *(SP body-extension) ")"
2671 ;; ; Future expansion. Client implementations
2672 ;; ; MUST accept body-extension fields. Server
2673 ;; ; implementations MUST NOT generate
2674 ;; ; body-extension fields except as defined by
2675 ;; ; future standard or standards-track
2676 ;; ; revisions of this specification.
2678 (defun imap-parse-body-extension ()
2679 (if (eq (char-after) ?\()
2682 (push (imap-parse-body-extension) b-e)
2683 (while (eq (char-after) ?\ )
2685 (push (imap-parse-body-extension) b-e))
2686 (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2689 (or (imap-parse-number)
2690 (imap-parse-nstring))))
2692 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2693 ;; *(SP body-extension)]]
2694 ;; ; MUST NOT be returned on non-extensible
2697 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2698 ;; *(SP body-extension)]]
2699 ;; ; MUST NOT be returned on non-extensible
2702 (defsubst imap-parse-body-ext ()
2704 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2707 (if (eq (char-after) ?\()
2710 (push (imap-parse-string) dsp)
2712 (push (imap-parse-string-list) dsp)
2714 ;; With assert, the code might not be eval'd.
2715 ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2717 (push (nreverse dsp) ext))
2718 (when (eq (char-after) ?\ ) ;; body-fld-lang
2720 (if (eq (char-after) ?\()
2721 (push (imap-parse-string-list) ext)
2722 (push (imap-parse-nstring) ext))
2723 (while (eq (char-after) ?\ ) ;; body-extension
2725 (setq ext (append (imap-parse-body-extension) ext)))))
2728 ;; body = "(" body-type-1part / body-type-mpart ")"
2730 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2731 ;; *(SP body-extension)]]
2732 ;; ; MUST NOT be returned on non-extensible
2735 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2736 ;; *(SP body-extension)]]
2737 ;; ; MUST NOT be returned on non-extensible
2740 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2741 ;; body-fld-enc SP body-fld-octets
2743 ;; body-fld-desc = nstring
2745 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2747 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2748 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2750 ;; body-fld-id = nstring
2752 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2754 ;; body-fld-lines = number
2756 ;; body-fld-md5 = nstring
2758 ;; body-fld-octets = number
2760 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2762 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2763 ;; [SP body-ext-1part]
2765 ;; body-type-basic = media-basic SP body-fields
2766 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2768 ;; body-type-msg = media-message SP body-fields SP envelope
2769 ;; SP body SP body-fld-lines
2771 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2773 ;; body-type-mpart = 1*body SP media-subtype
2774 ;; [SP body-ext-mpart]
2776 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2777 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2778 ;; ; Defined in [MIME-IMT]
2780 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2781 ;; ; Defined in [MIME-IMT]
2783 ;; media-subtype = string
2784 ;; ; Defined in [MIME-IMT]
2786 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2787 ;; ; Defined in [MIME-IMT]
2789 (defun imap-parse-body ()
2791 (when (eq (char-after) ?\()
2793 (if (eq (char-after) ?\()
2795 (while (and (eq (char-after) ?\()
2796 (setq subbody (imap-parse-body)))
2797 ;; buggy stalker communigate pro 3.0 inserts a SPC between
2798 ;; parts in multiparts
2799 (when (and (eq (char-after) ?\ )
2800 (eq (char-after (1+ (point))) ?\())
2802 (push subbody body))
2804 (push (imap-parse-string) body) ;; media-subtype
2805 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2807 (if (eq (char-after) ?\() ;; body-fld-param
2808 (push (imap-parse-string-list) body)
2809 (push (and (imap-parse-nil) nil) body))
2811 (append (imap-parse-body-ext) body))) ;; body-ext-...
2812 (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2816 (push (imap-parse-string) body) ;; media-type
2818 (push (imap-parse-string) body) ;; media-subtype
2820 ;; next line for Sun SIMS bug
2821 (and (eq (char-after) ? ) (imap-forward))
2822 (if (eq (char-after) ?\() ;; body-fld-param
2823 (push (imap-parse-string-list) body)
2824 (push (and (imap-parse-nil) nil) body))
2826 (push (imap-parse-nstring) body) ;; body-fld-id
2828 (push (imap-parse-nstring) body) ;; body-fld-desc
2830 ;; Next `or' for Sun SIMS bug. It regards body-fld-enc as a
2831 ;; nstring and returns nil instead of defaulting back to 7BIT
2832 ;; as the standard says.
2833 ;; Exchange (2007, at least) does this as well.
2834 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2836 ;; Exchange 2007 can return -1, contrary to the spec...
2837 (if (eq (char-after) ?-)
2839 (skip-chars-forward "-0-9")
2841 (push (imap-parse-number) body)) ;; body-fld-octets
2843 ;; Ok, we're done parsing the required parts, what comes now is one of
2846 ;; envelope (then we're parsing body-type-msg)
2847 ;; body-fld-lines (then we're parsing body-type-text)
2848 ;; body-ext-1part (then we're parsing body-type-basic)
2850 ;; The problem is that the two first are in turn optionally followed
2851 ;; by the third. So we parse the first two here (if there are any)...
2853 (when (eq (char-after) ?\ )
2856 (cond ((eq (char-after) ?\() ;; body-type-msg:
2857 (push (imap-parse-envelope) body) ;; envelope
2859 (push (imap-parse-body) body) ;; body
2860 ;; buggy stalker communigate pro 3.0 doesn't print
2861 ;; number of lines in message/rfc822 attachment
2862 (if (eq (char-after) ?\))
2865 (push (imap-parse-number) body))) ;; body-fld-lines
2866 ((setq lines (imap-parse-number)) ;; body-type-text:
2867 (push lines body)) ;; body-fld-lines
2869 (backward-char))))) ;; no match...
2871 ;; ...and then parse the third one here...
2873 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2875 (push (imap-parse-nstring) body) ;; body-fld-md5
2876 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2878 (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2882 (when imap-debug ; (untrace-all)
2884 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2885 (mapc (lambda (f) (trace-function-background f imap-debug-buffer))
2894 imap-interactive-login
2911 imap-send-command-wait
2916 imap-current-mailbox
2917 imap-current-mailbox-p-1
2918 imap-current-mailbox-p
2919 imap-mailbox-select-1
2921 imap-mailbox-examine-1
2922 imap-mailbox-examine
2923 imap-mailbox-unselect
2924 imap-mailbox-expunge
2926 imap-mailbox-create-1
2932 imap-mailbox-subscribe
2933 imap-mailbox-unsubscribe
2935 imap-mailbox-acl-get
2936 imap-mailbox-acl-set
2937 imap-mailbox-acl-delete
2938 imap-current-message
2939 imap-list-to-message-set
2947 imap-message-flag-permanent-p
2948 imap-message-flags-set
2949 imap-message-flags-del
2950 imap-message-flags-add
2951 imap-message-copyuid-1
2952 imap-message-copyuid
2954 imap-message-appenduid-1
2955 imap-message-appenduid
2967 imap-parse-resp-text
2968 imap-parse-resp-text-code
2969 imap-parse-data-list
2973 imap-parse-flag-list
2975 imap-parse-body-extension
2981 ;;; imap.el ends here