1 ;;; imap.el --- imap library
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004,
4 ;; 2005, 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
6 ;; Author: Simon Josefsson <simon@josefsson.org>
9 ;; This file is part of GNU Emacs.
11 ;; GNU Emacs is free software: you can redistribute it and/or modify
12 ;; it under the terms of the GNU General Public License as published by
13 ;; the Free Software Foundation, either version 3 of the License, or
14 ;; (at your option) any later version.
16 ;; GNU Emacs is distributed in the hope that it will be useful,
17 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
18 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 ;; GNU General Public License for more details.
21 ;; You should have received a copy of the GNU General Public License
22 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
26 ;; imap.el is an elisp library providing an interface for talking to
29 ;; imap.el is roughly divided in two parts, one that parses IMAP
30 ;; responses from the server and storing data into buffer-local
31 ;; variables, and one for utility functions which send commands to
32 ;; server, waits for an answer, and return information. The latter
33 ;; part is layered on top of the previous.
35 ;; The imap.el API consist of the following functions, other functions
36 ;; in this file should not be called directly and the result of doing
37 ;; so are at best undefined.
41 ;; imap-open, imap-opened, imap-authenticate, imap-close,
42 ;; imap-capability, imap-namespace, imap-error-text
46 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
47 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
48 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
49 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
50 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
51 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
52 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
56 ;; imap-fetch-asynch, imap-fetch,
57 ;; imap-current-message, imap-list-to-message-set,
58 ;; imap-message-get, imap-message-map
59 ;; imap-message-envelope-date, imap-message-envelope-subject,
60 ;; imap-message-envelope-from, imap-message-envelope-sender,
61 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
62 ;; imap-message-envelope-cc, imap-message-envelope-bcc
63 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
64 ;; imap-message-body, imap-message-flag-permanent-p
65 ;; imap-message-flags-set, imap-message-flags-del
66 ;; imap-message-flags-add, imap-message-copyuid
67 ;; imap-message-copy, imap-message-appenduid
68 ;; imap-message-append, imap-envelope-from
71 ;; It is my hope that these commands should be pretty self
72 ;; explanatory for someone that know IMAP. All functions have
73 ;; additional documentation on how to invoke them.
75 ;; imap.el supports RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1). The implemented
76 ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
77 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
78 ;; LOGINDISABLED) (with use of external library starttls.el and
79 ;; program starttls), and the GSSAPI / Kerberos V4 sections of RFC1731
80 ;; (with use of external program `imtest'), and RFC2971 (ID). It also
81 ;; takes advantage of the UNSELECT extension in Cyrus IMAPD.
83 ;; Without the work of John McClary Prevost and Jim Radford this library
84 ;; would not have seen the light of day. Many thanks.
86 ;; This is a transcript of a short interactive session for demonstration
89 ;; (imap-open "my.mail.server")
90 ;; => " *imap* my.mail.server:0"
92 ;; The rest are invoked with current buffer as the buffer returned by
93 ;; `imap-open'. It is possible to do it all without this, but it would
94 ;; look ugly here since `buffer' is always the last argument for all
95 ;; imap.el API functions.
97 ;; (imap-authenticate "myusername" "mypassword")
100 ;; (imap-mailbox-lsub "*")
101 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
103 ;; (imap-mailbox-list "INBOX.n%")
104 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
106 ;; (imap-mailbox-select "INBOX.nnimap")
109 ;; (imap-mailbox-get 'exists)
112 ;; (imap-mailbox-get 'uidvalidity)
115 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
118 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
119 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
123 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
124 ;; Use IEEE floats (which are effectively exact)? -- fx
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
128 ;; o Send strings as literal if they contain, e.g., ".
132 ;; - 19991218 added starttls/digest-md5 patch,
133 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
134 ;; NB! you need SLIM for starttls.el and digest-md5.el
135 ;; - 19991023 committed to pgnus
140 (eval-when-compile (require 'cl))
142 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r)))
143 (autoload 'starttls-open-stream "starttls")
144 (autoload 'starttls-negotiate "starttls")
145 (autoload 'sasl-find-mechanism "sasl")
146 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
147 (autoload 'digest-md5-digest-response "digest-md5")
148 (autoload 'digest-md5-digest-uri "digest-md5")
149 (autoload 'digest-md5-challenge "digest-md5")
150 (autoload 'rfc2104-hash "rfc2104")
151 (autoload 'utf7-encode "utf7")
152 (autoload 'utf7-decode "utf7")
153 (autoload 'format-spec "format-spec")
154 (autoload 'format-spec-make "format-spec")
155 (autoload 'open-tls-stream "tls"))
160 "Low-level IMAP issues."
164 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
166 "List of strings containing commands for Kerberos 4 authentication.
167 %s is replaced with server hostname, %p with port to connect to, and
168 %l with the value of `imap-default-user'. The program should accept
169 IMAP commands on stdin and return responses to stdout. Each entry in
170 the list is tried until a successful connection is made."
172 :type '(repeat string))
174 (defcustom imap-gssapi-program (list
175 (concat "gsasl %s %p "
176 "--mechanism GSSAPI "
177 "--authentication-id %l")
178 "imtest -m gssapi -u %l -p %p %s")
179 "List of strings containing commands for GSSAPI (krb5) authentication.
180 %s is replaced with server hostname, %p with port to connect to, and
181 %l with the value of `imap-default-user'. The program should accept
182 IMAP commands on stdin and return responses to stdout. Each entry in
183 the list is tried until a successful connection is made."
185 :type '(repeat string))
187 (defcustom imap-ssl-program '("openssl s_client -quiet -ssl3 -connect %s:%p"
188 "openssl s_client -quiet -ssl2 -connect %s:%p"
189 "s_client -quiet -ssl3 -connect %s:%p"
190 "s_client -quiet -ssl2 -connect %s:%p")
191 "A string, or list of strings, containing commands for SSL connections.
192 Within a string, %s is replaced with the server address and %p with
193 port number on server. The program should accept IMAP commands on
194 stdin and return responses to stdout. Each entry in the list is tried
195 until a successful connection is made."
197 :type '(choice string
200 (defcustom imap-shell-program '("ssh %s imapd"
202 "ssh %g ssh %s imapd"
203 "rsh %g rsh %s imapd")
204 "A list of strings, containing commands for IMAP connection.
205 Within a string, %s is replaced with the server address, %p with port
206 number on server, %g with `imap-shell-host', and %l with
207 `imap-default-user'. The program should read IMAP commands from stdin
208 and write IMAP response to stdout. Each entry in the list is tried
209 until a successful connection is made."
211 :type '(repeat string))
213 (defcustom imap-process-connection-type nil
214 "*Value for `process-connection-type' to use for Kerberos4, GSSAPI and SSL.
215 The `process-connection-type' variable controls the type of device
216 used to communicate with subprocesses. Values are nil to use a
217 pipe, or t or `pty' to use a pty. The value has no effect if the
218 system has no ptys or if all ptys are busy: then a pipe is used
219 in any case. The value takes effect when an IMAP server is
220 opened; changing it after that has no effect."
225 (defcustom imap-use-utf7 t
226 "If non-nil, do utf7 encoding/decoding of mailbox names.
227 Since the UTF7 decoding currently only decodes into ISO-8859-1
228 characters, you may disable this decoding if you need to access UTF7
229 encoded mailboxes which doesn't translate into ISO-8859-1."
233 (defcustom imap-log nil
234 "If non-nil, an imap session trace is placed in `imap-log-buffer'.
235 Note that username, passwords and other privacy sensitive
236 information (such as e-mail) may be stored in the buffer.
237 It is not written to disk, however. Do not enable this
238 variable unless you are comfortable with that.
240 See also `imap-debug'."
244 (defcustom imap-debug nil
245 "If non-nil, trace imap- functions into `imap-debug-buffer'.
246 Uses `trace-function-background', so you can turn it off with,
249 Note that username, passwords and other privacy sensitive
250 information (such as e-mail) may be stored in the buffer.
251 It is not written to disk, however. Do not enable this
252 variable unless you are comfortable with that.
254 This variable only takes effect when loading the `imap' library.
255 See also `imap-log'."
259 (defcustom imap-shell-host "gateway"
260 "Hostname of rlogin proxy."
264 (defcustom imap-default-user (user-login-name)
265 "Default username to use."
269 (defcustom imap-read-timeout (if (string-match
270 "windows-nt\\|os/2\\|cygwin"
271 (symbol-name system-type))
274 "*How long to wait between checking for the end of output.
275 Shorter values mean quicker response, but is more CPU intensive."
279 (defcustom imap-store-password nil
280 "If non-nil, store session password without prompting."
284 ;; Various variables.
286 (defvar imap-fetch-data-hook nil
287 "Hooks called after receiving each FETCH response.")
289 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
290 "Priority of streams to consider when opening connection to server.")
292 (defvar imap-stream-alist
293 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
294 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
295 (tls imap-tls-p imap-tls-open)
296 (ssl imap-ssl-p imap-ssl-open)
297 (network imap-network-p imap-network-open)
298 (shell imap-shell-p imap-shell-open)
299 (starttls imap-starttls-p imap-starttls-open))
300 "Definition of network streams.
304 NAME names the stream, CHECK is a function returning non-nil if the
305 server support the stream and OPEN is a function for opening the
308 (defvar imap-authenticators '(gssapi
315 "Priority of authenticators to consider when authenticating to server.")
317 (defvar imap-authenticator-alist
318 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
319 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
320 (sasl imap-sasl-auth-p imap-sasl-auth)
321 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
322 (login imap-login-p imap-login-auth)
323 (anonymous imap-anonymous-p imap-anonymous-auth)
324 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
325 "Definition of authenticators.
327 \(NAME CHECK AUTHENTICATE)
329 NAME names the authenticator. CHECK is a function returning non-nil if
330 the server support the authenticator and AUTHENTICATE is a function
331 for doing the actual authentication.")
333 (defvar imap-error nil
334 "Error codes from the last command.")
336 (defvar imap-logout-timeout nil
337 "Close server immediately if it can't logout in this number of seconds.
338 If it is nil, never close server until logout completes. Normally,
339 the value of this variable will be bound to a certain value to which
340 an application program that uses this module specifies on a per-server
343 ;; Internal constants. Change these and die.
345 (defconst imap-default-port 143)
346 (defconst imap-default-ssl-port 993)
347 (defconst imap-default-tls-port 993)
348 (defconst imap-default-stream 'network)
349 (defconst imap-coding-system-for-read 'binary)
350 (defconst imap-coding-system-for-write 'binary)
351 (defconst imap-local-variables '(imap-server
360 imap-current-target-mailbox
370 imap-calculate-literal-size-first
372 (defconst imap-log-buffer "*imap-log*")
373 (defconst imap-debug-buffer "*imap-debug*")
375 ;; Internal variables.
377 (defvar imap-stream nil)
378 (defvar imap-auth nil)
379 (defvar imap-server nil)
380 (defvar imap-port nil)
381 (defvar imap-username nil)
382 (defvar imap-password nil)
383 (defvar imap-last-authenticator nil)
384 (defvar imap-calculate-literal-size-first nil)
385 (defvar imap-state 'closed
387 Valid states are `closed', `initial', `nonauth', `auth', `selected'
390 (defvar imap-server-eol "\r\n"
391 "The EOL string sent from the server.")
393 (defvar imap-client-eol "\r\n"
394 "The EOL string we send to the server.")
396 (defvar imap-current-mailbox nil
397 "Current mailbox name.")
399 (defvar imap-current-target-mailbox nil
400 "Current target mailbox for COPY and APPEND commands.")
402 (defvar imap-mailbox-data nil
403 "Obarray with mailbox data.")
405 (defvar imap-mailbox-prime 997
406 "Length of `imap-mailbox-data'.")
408 (defvar imap-current-message nil
409 "Current message number.")
411 (defvar imap-message-data nil
412 "Obarray with message data.")
414 (defvar imap-message-prime 997
415 "Length of `imap-message-data'.")
417 (defvar imap-capability nil
418 "Capability for server.")
424 (defvar imap-namespace nil
425 "Namespace for current server.")
427 (defvar imap-reached-tag 0
428 "Lower limit on command tags that have been parsed.")
430 (defvar imap-failed-tags nil
431 "Alist of tags that failed.
432 Each element is a list with four elements; tag (a integer), response
433 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
434 human readable response text (a string).")
437 "Command tag number.")
439 (defvar imap-process nil
442 (defvar imap-continuation nil
443 "Non-nil indicates that the server emitted a continuation request.
444 The actual value is really the text on the continuation line.")
446 (defvar imap-callbacks nil
447 "List of response tags and callbacks, on the form `(number . function)'.
448 The function should take two arguments, the first the IMAP tag and the
449 second the status (OK, NO, BAD etc) of the command.")
452 ;; Utility functions:
454 (defun imap-remassoc (key alist)
455 "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
456 The modified ALIST is returned. If the first member
457 of ALIST has a car that is `equal' to KEY, there is no way to remove it
458 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
459 sure of changing the value of `foo'."
461 (if (equal key (caar alist))
463 (setcdr alist (imap-remassoc key (cdr alist)))
466 (defmacro imap-disable-multibyte ()
467 "Enable multibyte in the current buffer."
468 (unless (featurep 'xemacs)
469 '(set-buffer-multibyte nil)))
471 (defsubst imap-utf7-encode (string)
475 (utf7-encode string t)
477 "imap: Could not UTF7 encode `%s', using it unencoded..."
482 (defsubst imap-utf7-decode (string)
486 (utf7-decode string t)
488 "imap: Could not UTF7 decode `%s', using it undecoded..."
493 (defsubst imap-ok-p (status)
496 (setq imap-error status)
499 (defun imap-error-text (&optional buffer)
500 (with-current-buffer (or buffer (current-buffer))
501 (nth 3 (car imap-failed-tags))))
504 ;; Server functions; stream stuff:
506 (defun imap-log (string-or-buffer)
508 (with-current-buffer (get-buffer-create imap-log-buffer)
509 (imap-disable-multibyte)
510 (buffer-disable-undo)
511 (goto-char (point-max))
512 (if (bufferp string-or-buffer)
513 (insert-buffer-substring string-or-buffer)
514 (insert string-or-buffer)))))
516 (defun imap-kerberos4-stream-p (buffer)
517 (imap-capability 'AUTH=KERBEROS_V4 buffer))
519 (defun imap-kerberos4-open (name buffer server port)
520 (let ((cmds imap-kerberos4-program)
522 (while (and (not done) (setq cmd (pop cmds)))
523 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
525 (let* ((port (or port imap-default-port))
526 (coding-system-for-read imap-coding-system-for-read)
527 (coding-system-for-write imap-coding-system-for-write)
528 (process-connection-type imap-process-connection-type)
529 (process (start-process
530 name buffer shell-file-name shell-command-switch
535 ?p (number-to-string port)
536 ?l imap-default-user))))
539 (with-current-buffer buffer
540 (setq imap-client-eol "\n"
541 imap-calculate-literal-size-first t)
542 (while (and (memq (process-status process) '(open run))
543 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
544 (goto-char (point-min))
545 ;; Athena IMTEST can output SSL verify errors
546 (or (while (looking-at "^verify error:num=")
549 (or (while (looking-at "^TLS connection established")
552 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
553 (or (while (looking-at "^C:")
556 ;; cyrus 1.6 imtest print "S: " before server greeting
557 (or (not (looking-at "S: "))
560 (not (and (imap-parse-greeting)
561 ;; success in imtest < 1.6:
562 (or (re-search-forward
563 "^__\\(.*\\)__\n" nil t)
564 ;; success in imtest 1.6:
566 "^\\(Authenticat.*\\)" nil t))
567 (setq response (match-string 1)))))
568 (accept-process-output process 1)
571 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
572 (if response (concat "done, " response) "failed"))
573 (if (and response (let ((case-fold-search nil))
574 (not (string-match "failed" response))))
576 (if (memq (process-status process) '(open run))
578 (delete-process process)
582 (defun imap-gssapi-stream-p (buffer)
583 (imap-capability 'AUTH=GSSAPI buffer))
585 (defun imap-gssapi-open (name buffer server port)
586 (let ((cmds imap-gssapi-program)
588 (while (and (not done) (setq cmd (pop cmds)))
589 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
591 (let* ((port (or port imap-default-port))
592 (coding-system-for-read imap-coding-system-for-read)
593 (coding-system-for-write imap-coding-system-for-write)
594 (process-connection-type imap-process-connection-type)
595 (process (start-process
596 name buffer shell-file-name shell-command-switch
601 ?p (number-to-string port)
602 ?l imap-default-user))))
605 (with-current-buffer buffer
606 (setq imap-client-eol "\n"
607 imap-calculate-literal-size-first t)
608 (while (and (memq (process-status process) '(open run))
609 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
610 (goto-char (point-min))
611 ;; Athena IMTEST can output SSL verify errors
612 (or (while (looking-at "^verify error:num=")
615 (or (while (looking-at "^TLS connection established")
618 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
619 (or (while (looking-at "^C:")
622 ;; cyrus 1.6 imtest print "S: " before server greeting
623 (or (not (looking-at "S: "))
626 ;; GNU SASL may print 'Trying ...' first.
627 (or (not (looking-at "Trying "))
630 (not (and (imap-parse-greeting)
631 ;; success in imtest 1.6:
633 (concat "^\\(\\(Authenticat.*\\)\\|\\("
634 "Client authentication "
637 (setq response (match-string 1)))))
638 (accept-process-output process 1)
642 (message "GSSAPI IMAP connection: %s" (or response "failed"))
643 (if (and response (let ((case-fold-search nil))
644 (not (string-match "failed" response))))
646 (if (memq (process-status process) '(open run))
648 (delete-process process)
652 (defun imap-ssl-p (buffer)
655 (defun imap-ssl-open (name buffer server port)
656 "Open an SSL connection to SERVER."
657 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
658 (list imap-ssl-program)))
660 (while (and (not done) (setq cmd (pop cmds)))
661 (message "imap: Opening SSL connection with `%s'..." cmd)
663 (let* ((port (or port imap-default-ssl-port))
664 (coding-system-for-read imap-coding-system-for-read)
665 (coding-system-for-write imap-coding-system-for-write)
666 (process-connection-type imap-process-connection-type)
667 (set-process-query-on-exit-flag
668 (if (fboundp 'set-process-query-on-exit-flag)
669 'set-process-query-on-exit-flag
670 'process-kill-without-query))
673 (setq process (start-process
674 name buffer shell-file-name
679 ?p (number-to-string port)))))
680 (funcall set-process-query-on-exit-flag process nil)
682 (with-current-buffer buffer
683 (goto-char (point-min))
684 (while (and (memq (process-status process) '(open run))
685 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
686 (goto-char (point-max))
688 (not (imap-parse-greeting)))
689 (accept-process-output process 1)
693 (when (memq (process-status process) '(open run))
694 (setq done process))))))
697 (message "imap: Opening SSL connection with `%s'...done" cmd)
699 (message "imap: Opening SSL connection with `%s'...failed" cmd)
702 (defun imap-tls-p (buffer)
705 (defun imap-tls-open (name buffer server port)
706 (let* ((port (or port imap-default-tls-port))
707 (coding-system-for-read imap-coding-system-for-read)
708 (coding-system-for-write imap-coding-system-for-write)
709 (process (open-tls-stream name buffer server port)))
711 (while (and (memq (process-status process) '(open run))
712 ;; FIXME: Per the "blue moon" comment, the process/buffer
713 ;; handling here, and elsewhere in functions which open
714 ;; streams, looks confused. Obviously we can change buffers
715 ;; if a different process handler kicks in from
716 ;; `accept-process-output' or `sit-for' below, and TRT seems
717 ;; to be to `save-buffer' around those calls. (I wonder why
718 ;; `sit-for' is used with a non-zero wait.) -- fx
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)
726 (when (memq (process-status process) '(open run))
729 (defun imap-network-p (buffer)
732 (defun imap-network-open (name buffer server port)
733 (let* ((port (or port imap-default-port))
734 (coding-system-for-read imap-coding-system-for-read)
735 (coding-system-for-write imap-coding-system-for-write)
736 (process (open-network-stream name buffer server port)))
738 (while (and (memq (process-status process) '(open run))
739 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
740 (goto-char (point-min))
741 (not (imap-parse-greeting)))
742 (accept-process-output process 1)
745 (when (memq (process-status process) '(open run))
748 (defun imap-shell-p (buffer)
751 (defun imap-shell-open (name buffer server port)
752 (let ((cmds (if (listp imap-shell-program) imap-shell-program
753 (list imap-shell-program)))
755 (while (and (not done) (setq cmd (pop cmds)))
756 (message "imap: Opening IMAP connection with `%s'..." cmd)
757 (setq imap-client-eol "\n")
758 (let* ((port (or port imap-default-port))
759 (coding-system-for-read imap-coding-system-for-read)
760 (coding-system-for-write imap-coding-system-for-write)
761 (process (start-process
762 name buffer shell-file-name shell-command-switch
768 ?p (number-to-string port)
769 ?l imap-default-user)))))
771 (while (and (memq (process-status process) '(open run))
772 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
773 (goto-char (point-max))
775 (not (imap-parse-greeting)))
776 (accept-process-output process 1)
780 (when (memq (process-status process) '(open run))
781 (setq done process)))))
784 (message "imap: Opening IMAP connection with `%s'...done" cmd)
786 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
789 (defun imap-starttls-p (buffer)
790 (imap-capability 'STARTTLS buffer))
792 (defun imap-starttls-open (name buffer server port)
793 (let* ((port (or port imap-default-port))
794 (coding-system-for-read imap-coding-system-for-read)
795 (coding-system-for-write imap-coding-system-for-write)
796 (process (starttls-open-stream name buffer server port))
798 (message "imap: Connecting with STARTTLS...")
800 (while (and (memq (process-status process) '(open run))
801 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
802 (goto-char (point-max))
804 (not (imap-parse-greeting)))
805 (accept-process-output process 1)
807 (imap-send-command "STARTTLS")
808 (while (and (memq (process-status process) '(open run))
809 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
810 (goto-char (point-max))
812 (not (re-search-forward "[0-9]+ OK.*\r?\n" nil t)))
813 (accept-process-output process 1)
816 (when (and (setq tls-info (starttls-negotiate process))
817 (memq (process-status process) '(open run)))
818 (setq done process)))
819 (if (stringp tls-info)
820 (message "imap: STARTTLS info: %s" tls-info))
821 (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
824 ;; Server functions; authenticator stuff:
826 (defun imap-interactive-login (buffer loginfunc)
827 "Login to server in BUFFER.
828 LOGINFUNC is passed a username and a password, it should return t if
829 it where successful authenticating itself to the server, nil otherwise.
830 Returns t if login was successful, nil otherwise."
831 (with-current-buffer buffer
832 (make-local-variable 'imap-username)
833 (make-local-variable 'imap-password)
834 (let (user passwd ret)
835 ;; (condition-case ()
836 (while (or (not user) (not passwd))
837 (setq user (or imap-username
838 (read-from-minibuffer
839 (concat "imap: username for " imap-server
840 " (using stream `" (symbol-name imap-stream)
842 (or user imap-default-user))))
843 (setq passwd (or imap-password
845 (concat "imap: password for " user "@"
846 imap-server " (using authenticator `"
847 (symbol-name imap-auth) "'): "))))
848 (when (and user passwd)
849 (if (funcall loginfunc user passwd)
851 (message "imap: Login successful...")
854 (when (and (not imap-password)
855 (or imap-store-password
856 (y-or-n-p "imap: Store password for this IMAP session? ")))
857 (setq imap-password passwd)))
858 (message "imap: Login failed...")
860 (setq imap-password nil)
862 ;; (quit (with-current-buffer buffer
865 ;; (error (with-current-buffer buffer
870 (defun imap-gssapi-auth-p (buffer)
871 (eq imap-stream 'gssapi))
873 (defun imap-gssapi-auth (buffer)
874 (message "imap: Authenticating using GSSAPI...%s"
875 (if (eq imap-stream 'gssapi) "done" "failed"))
876 (eq imap-stream 'gssapi))
878 (defun imap-kerberos4-auth-p (buffer)
879 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
880 (eq imap-stream 'kerberos4)))
882 (defun imap-kerberos4-auth (buffer)
883 (message "imap: Authenticating using Kerberos 4...%s"
884 (if (eq imap-stream 'kerberos4) "done" "failed"))
885 (eq imap-stream 'kerberos4))
887 (defun imap-cram-md5-p (buffer)
888 (imap-capability 'AUTH=CRAM-MD5 buffer))
890 (defun imap-cram-md5-auth (buffer)
891 "Login to server using the AUTH CRAM-MD5 method."
892 (message "imap: Authenticating using CRAM-MD5...")
893 (let ((done (imap-interactive-login
895 (lambda (user passwd)
897 (imap-send-command-wait
899 "AUTHENTICATE CRAM-MD5"
901 (let* ((decoded (base64-decode-string challenge))
902 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
903 (response (concat user " " hash))
904 (encoded (base64-encode-string response)))
907 (message "imap: Authenticating using CRAM-MD5...done")
908 (message "imap: Authenticating using CRAM-MD5...failed"))))
910 (defun imap-login-p (buffer)
911 (and (not (imap-capability 'LOGINDISABLED buffer))
912 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
914 (defun imap-quote-specials (string)
917 (goto-char (point-min))
918 (while (re-search-forward "[\\\"]" nil t)
924 (defun imap-login-auth (buffer)
925 "Login to server using the LOGIN command."
926 (message "imap: Plaintext authentication...")
927 (imap-interactive-login buffer
928 (lambda (user passwd)
929 (imap-ok-p (imap-send-command-wait
931 (imap-quote-specials user)
933 (imap-quote-specials passwd)
936 (defun imap-anonymous-p (buffer)
939 (defun imap-anonymous-auth (buffer)
940 (message "imap: Logging in anonymously...")
941 (with-current-buffer buffer
942 (imap-ok-p (imap-send-command-wait
943 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
944 (system-name)) "\"")))))
946 ;;; Compiler directives.
948 (defvar imap-sasl-client)
949 (defvar imap-sasl-step)
951 (defun imap-sasl-make-mechanisms (buffer)
954 (let ((name (symbol-name sym)))
955 (if (and (> (length name) 5)
956 (string-equal "AUTH=" (substring name 0 5 )))
957 (setq mecs (cons (substring name 5) mecs)))))
958 (imap-capability nil buffer))
961 (declare-function sasl-find-mechanism "sasl" (mechanism))
962 (declare-function sasl-mechanism-name "sasl" (mechanism))
963 (declare-function sasl-make-client "sasl" (mechanism name service server))
964 (declare-function sasl-next-step "sasl" (client step))
965 (declare-function sasl-step-data "sasl" (step))
966 (declare-function sasl-step-set-data "sasl" (step data))
968 (defun imap-sasl-auth-p (buffer)
969 (and (condition-case ()
972 (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
974 (defun imap-sasl-auth (buffer)
975 "Login to server using the SASL method."
976 (message "imap: Authenticating using SASL...")
977 (with-current-buffer buffer
978 (make-local-variable 'imap-username)
979 (make-local-variable 'imap-sasl-client)
980 (make-local-variable 'imap-sasl-step)
981 (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
984 (setq user (or imap-username
985 (read-from-minibuffer
986 (concat "IMAP username for " imap-server " using SASL "
987 (sasl-mechanism-name mechanism) ": ")
988 (or user imap-default-user))))
990 (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
991 imap-sasl-step (sasl-next-step imap-sasl-client nil))
992 (let ((tag (imap-send-command
993 (if (sasl-step-data imap-sasl-step)
994 (format "AUTHENTICATE %s %s"
995 (sasl-mechanism-name mechanism)
996 (sasl-step-data imap-sasl-step))
997 (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
999 (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
1000 (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
1001 (setq imap-continuation nil
1002 imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
1003 (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
1004 (base64-encode-string (sasl-step-data imap-sasl-step) t)
1006 (if (imap-ok-p (imap-wait-for-tag tag))
1007 (setq imap-username user
1009 (message "Login failed...")
1013 (defun imap-digest-md5-p (buffer)
1014 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
1016 (require 'digest-md5)
1019 (defun imap-digest-md5-auth (buffer)
1020 "Login to server using the AUTH DIGEST-MD5 method."
1021 (message "imap: Authenticating using DIGEST-MD5...")
1022 (imap-interactive-login
1024 (lambda (user passwd)
1028 "AUTHENTICATE DIGEST-MD5"
1030 (digest-md5-parse-digest-challenge
1031 (base64-decode-string challenge))
1033 (digest-md5-digest-uri
1034 "imap" (digest-md5-challenge 'realm)))
1036 (digest-md5-digest-response
1037 user passwd digest-uri)))
1038 (base64-encode-string response 'no-line-break))))
1040 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1042 (setq imap-continuation nil)
1043 (imap-send-command-1 "")
1044 (imap-ok-p (imap-wait-for-tag tag)))))))
1046 ;; Server functions:
1048 (defun imap-open-1 (buffer)
1049 (with-current-buffer buffer
1051 (setq imap-current-mailbox nil
1052 imap-current-message nil
1054 imap-process (condition-case ()
1055 (funcall (nth 2 (assq imap-stream
1057 "imap" buffer imap-server imap-port)
1058 ((error quit) nil)))
1060 (set-process-filter imap-process 'imap-arrival-filter)
1061 (set-process-sentinel imap-process 'imap-sentinel)
1062 (while (and (eq imap-state 'initial)
1063 (memq (process-status imap-process) '(open run)))
1064 (message "Waiting for response from %s..." imap-server)
1065 (accept-process-output imap-process 1))
1066 (message "Waiting for response from %s...done" imap-server)
1067 (and (memq (process-status imap-process) '(open run))
1070 (defun imap-open (server &optional port stream auth buffer)
1071 "Open an IMAP connection to host SERVER at PORT returning a buffer.
1072 If PORT is unspecified, a default value is used (143 except
1073 for SSL which use 993).
1074 STREAM indicates the stream to use, see `imap-streams' for available
1075 streams. If nil, it choices the best stream the server is capable of.
1076 AUTH indicates authenticator to use, see `imap-authenticators' for
1077 available authenticators. If nil, it choices the best stream the
1078 server is capable of.
1079 BUFFER can be a buffer or a name of a buffer, which is created if
1080 necessary. If nil, the buffer name is generated."
1081 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1082 (with-current-buffer (get-buffer-create buffer)
1083 (if (imap-opened buffer)
1084 (imap-close buffer))
1085 (mapc 'make-local-variable imap-local-variables)
1086 (imap-disable-multibyte)
1087 (buffer-disable-undo)
1088 (setq imap-server (or server imap-server))
1089 (setq imap-port (or port imap-port))
1090 (setq imap-auth (or auth imap-auth))
1091 (setq imap-stream (or stream imap-stream))
1092 (message "imap: Connecting to %s..." imap-server)
1093 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1094 (imap-open-1 buffer)))
1096 (message "imap: Connecting to %s...failed" imap-server)
1098 (when (null imap-stream)
1099 ;; Need to choose stream.
1100 (let ((streams imap-streams))
1101 (while (setq stream (pop streams))
1102 ;; OK to use this stream?
1103 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1105 (if (not (eq imap-default-stream stream))
1106 (with-current-buffer (get-buffer-create
1107 (generate-new-buffer-name " *temp*"))
1108 (mapc 'make-local-variable imap-local-variables)
1109 (imap-disable-multibyte)
1110 (buffer-disable-undo)
1111 (setq imap-server (or server imap-server))
1112 (setq imap-port (or port imap-port))
1113 (setq imap-auth (or auth imap-auth))
1114 (message "imap: Reconnecting with stream `%s'..." stream)
1115 (if (null (let ((imap-stream stream))
1116 (imap-open-1 (current-buffer))))
1118 (kill-buffer (current-buffer))
1120 "imap: Reconnecting with stream `%s'...failed"
1122 ;; We're done, kill the first connection
1124 (let ((name (if (stringp buffer)
1126 (buffer-name buffer))))
1127 (kill-buffer buffer)
1128 (rename-buffer name)
1129 ;; set the passed buffer to the current one,
1130 ;; so that (imap-opened buffer) later will work
1131 (setq buffer (current-buffer)))
1132 (message "imap: Reconnecting with stream `%s'...done"
1134 (setq imap-stream stream)
1135 (setq imap-capability nil)
1136 (setq streams nil)))
1138 (message "imap: Connecting to %s...done" imap-server)
1139 (setq imap-stream stream)
1140 (setq imap-capability nil)
1141 (setq streams nil))))))
1142 (when (imap-opened buffer)
1143 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1144 ;; (debug "opened+state+auth+buffer" (imap-opened buffer) imap-state imap-auth buffer)
1148 (defcustom imap-ping-server t
1149 "If non-nil, check if IMAP is open.
1150 See the function `imap-ping-server'."
1151 :version "23.1" ;; No Gnus
1155 (defun imap-opened (&optional buffer)
1156 "Return non-nil if connection to imap server in BUFFER is open.
1157 If BUFFER is nil then the current buffer is used."
1158 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1159 (buffer-live-p buffer)
1160 (with-current-buffer buffer
1162 (memq (process-status imap-process) '(open run))
1163 (if imap-ping-server
1167 (defun imap-ping-server (&optional buffer)
1168 "Ping the IMAP server in BUFFER with a \"NOOP\" command.
1169 Return non-nil if the server responds, and nil if it does not
1170 respond. If BUFFER is nil, the current buffer is used."
1172 (imap-ok-p (imap-send-command-wait "NOOP" buffer))
1175 (defun imap-authenticate (&optional user passwd buffer)
1176 "Authenticate to server in BUFFER, using current buffer if nil.
1177 It uses the authenticator specified when opening the server. If the
1178 authenticator requires username/passwords, they are queried from the
1179 user and optionally stored in the buffer. If USER and/or PASSWD is
1180 specified, the user will not be questioned and the username and/or
1181 password is remembered in the buffer."
1182 (with-current-buffer (or buffer (current-buffer))
1183 (if (not (eq imap-state 'nonauth))
1184 (or (eq imap-state 'auth)
1185 (eq imap-state 'selected)
1186 (eq imap-state 'examine))
1187 (make-local-variable 'imap-username)
1188 (make-local-variable 'imap-password)
1189 (make-local-variable 'imap-last-authenticator)
1190 (when user (setq imap-username user))
1191 (when passwd (setq imap-password passwd))
1193 (and (setq imap-last-authenticator
1194 (assq imap-auth imap-authenticator-alist))
1195 (funcall (nth 2 imap-last-authenticator) (current-buffer))
1196 (setq imap-state 'auth))
1197 ;; Choose authenticator.
1198 (let ((auths imap-authenticators)
1200 (while (setq auth (pop auths))
1201 ;; OK to use authenticator?
1202 (setq imap-last-authenticator
1203 (assq auth imap-authenticator-alist))
1204 (when (funcall (nth 1 imap-last-authenticator) (current-buffer))
1205 (message "imap: Authenticating to `%s' using `%s'..."
1207 (setq imap-auth auth)
1208 (if (funcall (nth 2 imap-last-authenticator) (current-buffer))
1210 (message "imap: Authenticating to `%s' using `%s'...done"
1212 ;; set imap-state correctly on successful auth attempt
1213 (setq imap-state 'auth)
1214 ;; stop iterating through the authenticator list
1216 (message "imap: Authenticating to `%s' using `%s'...failed"
1217 imap-server auth)))))
1220 (defun imap-close (&optional buffer)
1221 "Close connection to server in BUFFER.
1222 If BUFFER is nil, the current buffer is used."
1223 (with-current-buffer (or buffer (current-buffer))
1228 (when (and imap-process
1229 (memq (process-status imap-process) '(open run)))
1230 (delete-process imap-process))
1231 (setq imap-current-mailbox nil
1232 imap-current-message nil
1237 (defun imap-capability (&optional identifier buffer)
1238 "Return a list of identifiers which server in BUFFER support.
1239 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1240 If BUFFER is nil, the current buffer is assumed."
1241 (with-current-buffer (or buffer (current-buffer))
1242 (unless imap-capability
1243 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1244 (setq imap-capability '(IMAP2))))
1246 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1249 (defun imap-id (&optional list-of-values buffer)
1250 "Identify client to server in BUFFER, and return server identity.
1251 LIST-OF-VALUES is nil, or a plist with identifier and value
1252 strings to send to the server to identify the client.
1254 Return a list of identifiers which server in BUFFER support, or
1255 nil if it doesn't support ID or returns no information.
1257 If BUFFER is nil, the current buffer is assumed."
1258 (with-current-buffer (or buffer (current-buffer))
1259 (when (and (imap-capability 'ID)
1260 (imap-ok-p (imap-send-command-wait
1261 (if (null list-of-values)
1263 (concat "ID (" (mapconcat (lambda (el)
1264 (concat "\"" el "\""))
1269 (defun imap-namespace (&optional buffer)
1270 "Return a namespace hierarchy at server in BUFFER.
1271 If BUFFER is nil, the current buffer is assumed."
1272 (with-current-buffer (or buffer (current-buffer))
1273 (unless imap-namespace
1274 (when (imap-capability 'NAMESPACE)
1275 (imap-send-command-wait "NAMESPACE")))
1278 (defun imap-send-command-wait (command &optional buffer)
1279 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1281 (defun imap-logout (&optional buffer)
1282 (or buffer (setq buffer (current-buffer)))
1283 (if imap-logout-timeout
1284 (with-timeout (imap-logout-timeout
1286 (with-current-buffer buffer
1287 (delete-process imap-process))
1289 (imap-send-command "LOGOUT" buffer))
1290 (imap-send-command "LOGOUT" buffer)))
1292 (defun imap-logout-wait (&optional buffer)
1293 (or buffer (setq buffer (current-buffer)))
1294 (if imap-logout-timeout
1295 (with-timeout (imap-logout-timeout
1297 (with-current-buffer buffer
1298 (delete-process imap-process))
1300 (imap-send-command-wait "LOGOUT" buffer))
1301 (imap-send-command-wait "LOGOUT" buffer)))
1304 ;; Mailbox functions:
1306 (defun imap-mailbox-put (propname value &optional mailbox)
1307 (if imap-mailbox-data
1308 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1310 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1311 propname value mailbox (current-buffer)))
1314 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1315 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1318 (defun imap-mailbox-get (propname &optional mailbox)
1319 (imap-mailbox-get-1 propname (or (imap-utf7-encode mailbox)
1320 imap-current-mailbox)))
1322 (defun imap-mailbox-map-1 (func &optional mailbox-decoder)
1326 (push (funcall func (if mailbox-decoder
1327 (funcall mailbox-decoder (symbol-name s))
1328 (symbol-name s))) result))
1332 (defun imap-mailbox-map (func)
1333 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1334 Function should take a mailbox name (a string) as
1336 (imap-mailbox-map-1 func 'imap-utf7-decode))
1338 (defun imap-current-mailbox (&optional buffer)
1339 (with-current-buffer (or buffer (current-buffer))
1340 (imap-utf7-decode imap-current-mailbox)))
1342 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1343 (and (string= mailbox imap-current-mailbox)
1345 (eq imap-state 'examine))
1347 (eq imap-state 'selected)))))
1349 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1350 (with-current-buffer (or buffer (current-buffer))
1351 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1353 (defun imap-mailbox-select-1 (mailbox &optional examine)
1354 "Select MAILBOX on server in BUFFER.
1355 If EXAMINE is non-nil, do a read-only select."
1356 (if (imap-current-mailbox-p-1 mailbox examine)
1357 imap-current-mailbox
1358 (setq imap-current-mailbox mailbox)
1359 (if (imap-ok-p (imap-send-command-wait
1360 (concat (if examine "EXAMINE" "SELECT") " \""
1363 (setq imap-message-data (make-vector imap-message-prime 0)
1364 imap-state (if examine 'examine 'selected))
1365 imap-current-mailbox)
1366 ;; Failed SELECT/EXAMINE unselects current mailbox
1367 (setq imap-current-mailbox nil))))
1369 (defun imap-mailbox-select (mailbox &optional examine buffer)
1370 (with-current-buffer (or buffer (current-buffer))
1372 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1374 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1375 (with-current-buffer (or buffer (current-buffer))
1376 (imap-mailbox-select-1 mailbox 'examine)))
1378 (defun imap-mailbox-examine (mailbox &optional buffer)
1379 "Examine MAILBOX on server in BUFFER."
1380 (imap-mailbox-select mailbox 'examine buffer))
1382 (defun imap-mailbox-unselect (&optional buffer)
1383 "Close current folder in BUFFER, without expunging articles."
1384 (with-current-buffer (or buffer (current-buffer))
1385 (when (or (eq imap-state 'auth)
1386 (and (imap-capability 'UNSELECT)
1387 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1389 (imap-send-command-wait (concat "EXAMINE \""
1390 imap-current-mailbox
1392 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1393 (setq imap-current-mailbox nil
1394 imap-message-data nil
1398 (defun imap-mailbox-expunge (&optional asynch buffer)
1399 "Expunge articles in current folder in BUFFER.
1400 If ASYNCH, do not wait for successful completion of the command.
1401 If BUFFER is nil the current buffer is assumed."
1402 (with-current-buffer (or buffer (current-buffer))
1403 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1405 (imap-send-command "EXPUNGE")
1406 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1408 (defun imap-mailbox-close (&optional asynch buffer)
1409 "Expunge articles and close current folder in BUFFER.
1410 If ASYNCH, do not wait for successful completion of the command.
1411 If BUFFER is nil the current buffer is assumed."
1412 (with-current-buffer (or buffer (current-buffer))
1413 (when imap-current-mailbox
1415 (imap-add-callback (imap-send-command "CLOSE")
1416 `(lambda (tag status)
1417 (message "IMAP mailbox `%s' closed... %s"
1418 imap-current-mailbox status)
1419 (when (eq ,imap-current-mailbox
1420 imap-current-mailbox)
1421 ;; Don't wipe out data if another mailbox
1423 (setq imap-current-mailbox nil
1424 imap-message-data nil
1425 imap-state 'auth))))
1426 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1427 (setq imap-current-mailbox nil
1428 imap-message-data nil
1432 (defun imap-mailbox-create-1 (mailbox)
1433 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1435 (defun imap-mailbox-create (mailbox &optional buffer)
1436 "Create MAILBOX on server in BUFFER.
1437 If BUFFER is nil the current buffer is assumed."
1438 (with-current-buffer (or buffer (current-buffer))
1439 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1441 (defun imap-mailbox-delete (mailbox &optional buffer)
1442 "Delete MAILBOX on server in BUFFER.
1443 If BUFFER is nil the current buffer is assumed."
1444 (let ((mailbox (imap-utf7-encode mailbox)))
1445 (with-current-buffer (or buffer (current-buffer))
1447 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1449 (defun imap-mailbox-rename (oldname newname &optional buffer)
1450 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1451 If BUFFER is nil the current buffer is assumed."
1452 (let ((oldname (imap-utf7-encode oldname))
1453 (newname (imap-utf7-encode newname)))
1454 (with-current-buffer (or buffer (current-buffer))
1456 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1457 "\"" newname "\""))))))
1459 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1460 "Return a list of subscribed mailboxes on server in BUFFER.
1461 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1462 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1463 implementation-specific string that has to be passed to lsub command."
1464 (with-current-buffer (or buffer (current-buffer))
1465 ;; Make sure we know the hierarchy separator for root's hierarchy
1466 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1467 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1468 (imap-utf7-encode root) "\"")))
1469 ;; clear list data (NB not delimiter and other stuff)
1470 (imap-mailbox-map-1 (lambda (mailbox)
1471 (imap-mailbox-put 'lsub nil mailbox)))
1473 (imap-send-command-wait
1474 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1475 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1478 (imap-mailbox-map-1 (lambda (mailbox)
1479 (when (imap-mailbox-get-1 'lsub mailbox)
1480 (push (imap-utf7-decode mailbox) out))))
1483 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1484 "Return a list of mailboxes matching ROOT on server in BUFFER.
1485 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1486 root. REFERENCE is a implementation-specific string that has to be
1487 passed to list command."
1488 (with-current-buffer (or buffer (current-buffer))
1489 ;; Make sure we know the hierarchy separator for root's hierarchy
1490 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1491 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1492 (imap-utf7-encode root) "\"")))
1493 ;; clear list data (NB not delimiter and other stuff)
1494 (imap-mailbox-map-1 (lambda (mailbox)
1495 (imap-mailbox-put 'list nil mailbox)))
1497 (imap-send-command-wait
1498 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1499 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1502 (imap-mailbox-map-1 (lambda (mailbox)
1503 (when (imap-mailbox-get-1 'list mailbox)
1504 (push (imap-utf7-decode mailbox) out))))
1507 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1508 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1509 Returns non-nil if successful."
1510 (with-current-buffer (or buffer (current-buffer))
1511 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1512 (imap-utf7-encode mailbox)
1515 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1516 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1517 Returns non-nil if successful."
1518 (with-current-buffer (or buffer (current-buffer))
1519 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1520 (imap-utf7-encode mailbox)
1523 (defun imap-mailbox-status (mailbox items &optional buffer)
1524 "Get status items ITEM in MAILBOX from server in BUFFER.
1525 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1526 the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
1527 or `unseen'. If ITEMS is a list of symbols, a list of values is
1528 returned, if ITEMS is a symbol only its value is returned."
1529 (with-current-buffer (or buffer (current-buffer))
1531 (imap-send-command-wait (list "STATUS \""
1532 (imap-utf7-encode mailbox)
1540 (mapcar (lambda (item)
1541 (imap-mailbox-get item mailbox))
1543 (imap-mailbox-get items mailbox)))))
1545 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1546 "Send status item request ITEM on MAILBOX to server in BUFFER.
1547 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1548 the STATUS data items -- i.e. 'messages, 'recent, 'uidnext, 'uidvalidity
1549 or 'unseen. The IMAP command tag is returned."
1550 (with-current-buffer (or buffer (current-buffer))
1551 (imap-send-command (list "STATUS \""
1552 (imap-utf7-encode mailbox)
1560 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1561 "Get ACL on MAILBOX from server in BUFFER."
1562 (let ((mailbox (imap-utf7-encode mailbox)))
1563 (with-current-buffer (or buffer (current-buffer))
1565 (imap-send-command-wait (list "GETACL \""
1566 (or mailbox imap-current-mailbox)
1568 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1570 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1571 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1572 (let ((mailbox (imap-utf7-encode mailbox)))
1573 (with-current-buffer (or buffer (current-buffer))
1575 (imap-send-command-wait (list "SETACL \""
1576 (or mailbox imap-current-mailbox)
1582 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1583 "Remove any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1584 (let ((mailbox (imap-utf7-encode mailbox)))
1585 (with-current-buffer (or buffer (current-buffer))
1587 (imap-send-command-wait (list "DELETEACL \""
1588 (or mailbox imap-current-mailbox)
1593 ;; Message functions:
1595 (defun imap-current-message (&optional buffer)
1596 (with-current-buffer (or buffer (current-buffer))
1597 imap-current-message))
1599 (defun imap-list-to-message-set (list)
1600 (mapconcat (lambda (item)
1601 (number-to-string item))
1607 (defun imap-range-to-message-set (range)
1612 (car item) (cdr item))
1613 (format "%d" item)))
1614 (if (and (listp range) (not (listp (cdr range))))
1615 (list range) ;; make (1 . 2) into ((1 . 2))
1619 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1620 (with-current-buffer (or buffer (current-buffer))
1621 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1623 (imap-list-to-message-set uids)
1627 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1628 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1629 UIDS can be a string, number or a list of numbers. If RECEIVE
1630 is non-nil return these properties."
1631 (with-current-buffer (or buffer (current-buffer))
1632 (when (imap-ok-p (imap-send-command-wait
1633 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1635 (imap-list-to-message-set uids)
1638 (if (or (null receive) (stringp uids))
1641 (mapcar (lambda (uid)
1643 (mapcar (lambda (prop)
1644 (imap-message-get uid prop))
1646 (imap-message-get uid receive)))
1648 (imap-message-get uids receive))))))
1650 (defun imap-message-put (uid propname value)
1651 (if imap-message-data
1652 (put (intern (number-to-string uid) imap-message-data)
1654 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1655 uid propname value (current-buffer)))
1658 (defun imap-message-get (uid propname)
1659 (get (intern-soft (number-to-string uid) imap-message-data)
1662 (defun imap-message-map (func propname)
1663 "Map a function across each message in `imap-message-data', returning a list."
1667 (push (funcall func (get s 'UID) (get s propname)) result))
1671 (defmacro imap-message-envelope-date (uid &optional buffer)
1672 `(with-current-buffer (or ,buffer (current-buffer))
1673 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1675 (defmacro imap-message-envelope-subject (uid &optional buffer)
1676 `(with-current-buffer (or ,buffer (current-buffer))
1677 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1679 (defmacro imap-message-envelope-from (uid &optional buffer)
1680 `(with-current-buffer (or ,buffer (current-buffer))
1681 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1683 (defmacro imap-message-envelope-sender (uid &optional buffer)
1684 `(with-current-buffer (or ,buffer (current-buffer))
1685 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1687 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1688 `(with-current-buffer (or ,buffer (current-buffer))
1689 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1691 (defmacro imap-message-envelope-to (uid &optional buffer)
1692 `(with-current-buffer (or ,buffer (current-buffer))
1693 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1695 (defmacro imap-message-envelope-cc (uid &optional buffer)
1696 `(with-current-buffer (or ,buffer (current-buffer))
1697 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1699 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1700 `(with-current-buffer (or ,buffer (current-buffer))
1701 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1703 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1704 `(with-current-buffer (or ,buffer (current-buffer))
1705 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1707 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1708 `(with-current-buffer (or ,buffer (current-buffer))
1709 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1711 (defmacro imap-message-body (uid &optional buffer)
1712 `(with-current-buffer (or ,buffer (current-buffer))
1713 (imap-message-get ,uid 'BODY)))
1715 ;; FIXME: Should this try to use CHARSET? -- fx
1716 (defun imap-search (predicate &optional buffer)
1717 (with-current-buffer (or buffer (current-buffer))
1718 (imap-mailbox-put 'search 'dummy)
1719 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1720 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1722 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1724 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1726 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1727 "Return t if FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1728 (with-current-buffer (or buffer (current-buffer))
1729 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1730 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1732 (defun imap-message-flags-set (articles flags &optional silent buffer)
1733 (when (and articles flags)
1734 (with-current-buffer (or buffer (current-buffer))
1735 (imap-ok-p (imap-send-command-wait
1736 (concat "UID STORE " articles
1737 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1739 (defun imap-message-flags-del (articles flags &optional silent buffer)
1740 (when (and articles flags)
1741 (with-current-buffer (or buffer (current-buffer))
1742 (imap-ok-p (imap-send-command-wait
1743 (concat "UID STORE " articles
1744 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1746 (defun imap-message-flags-add (articles flags &optional silent buffer)
1747 (when (and articles flags)
1748 (with-current-buffer (or buffer (current-buffer))
1749 (imap-ok-p (imap-send-command-wait
1750 (concat "UID STORE " articles
1751 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1753 ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
1754 ;; Signal an error if we'd get an integer overflow.
1756 ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
1757 ;; `imap-string-to-integer'.
1758 (defun imap-string-to-integer (string &optional base)
1759 (let ((number (string-to-number string base)))
1760 (if (> number most-positive-fixnum)
1762 (format "String %s cannot be converted to a Lisp integer" number))
1765 (defun imap-message-copyuid-1 (mailbox)
1766 (if (imap-capability 'UIDPLUS)
1767 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1768 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1769 (let ((old-mailbox imap-current-mailbox)
1771 (imap-message-data (make-vector 2 0)))
1772 (when (imap-mailbox-examine-1 mailbox)
1774 (and (imap-fetch "*:*" "UID")
1775 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1776 (apply 'max (imap-message-map
1777 (lambda (uid prop) uid) 'UID))))
1779 (imap-mailbox-select old-mailbox (eq state 'examine))
1780 (imap-mailbox-unselect)))))))
1782 (defun imap-message-copyuid (mailbox &optional buffer)
1783 (with-current-buffer (or buffer (current-buffer))
1784 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1786 (defun imap-message-copy (articles mailbox
1787 &optional dont-create no-copyuid buffer)
1788 "Copy ARTICLES to MAILBOX on server in BUFFER.
1789 ARTICLES is a string message set. Create mailbox if it doesn't exist,
1790 unless DONT-CREATE is non-nil. On success, return a list with
1791 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1792 first element. The rest of list contains the saved articles' UIDs."
1794 (with-current-buffer (or buffer (current-buffer))
1795 (let ((mailbox (imap-utf7-encode mailbox)))
1796 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1797 (imap-current-target-mailbox mailbox))
1798 (if (imap-ok-p (imap-send-command-wait cmd))
1800 (when (and (not dont-create)
1801 ;; removed because of buggy Oracle server
1802 ;; that doesn't send TRYCREATE tags (which
1803 ;; is a MUST according to specifications):
1804 ;;(imap-mailbox-get-1 'trycreate mailbox)
1805 (imap-mailbox-create-1 mailbox))
1806 (imap-ok-p (imap-send-command-wait cmd)))))
1808 (imap-message-copyuid-1 mailbox)))))))
1810 ;; FIXME: Amalgamate with imap-message-copyuid-1, using an extra arg, since it
1811 ;; shares most of the code? -- fx
1812 (defun imap-message-appenduid-1 (mailbox)
1813 (if (imap-capability 'UIDPLUS)
1814 (imap-mailbox-get-1 'appenduid mailbox)
1815 (let ((old-mailbox imap-current-mailbox)
1817 (imap-message-data (make-vector 2 0)))
1818 (when (imap-mailbox-examine-1 mailbox)
1820 (and (imap-fetch "*:*" "UID")
1821 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1822 (apply 'max (imap-message-map
1823 (lambda (uid prop) uid) 'UID))))
1825 (imap-mailbox-select old-mailbox (eq state 'examine))
1826 (imap-mailbox-unselect)))))))
1828 (defun imap-message-appenduid (mailbox &optional buffer)
1829 (with-current-buffer (or buffer (current-buffer))
1830 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1832 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1833 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1834 FLAGS and DATE-TIME is currently not used. Return a cons holding
1835 uidvalidity of MAILBOX and UID the newly created article got, or nil
1837 (let ((mailbox (imap-utf7-encode mailbox)))
1838 (with-current-buffer (or buffer (current-buffer))
1839 (and (let ((imap-current-target-mailbox mailbox))
1841 (imap-send-command-wait
1842 (list "APPEND \"" mailbox "\" " article))))
1843 (imap-message-appenduid-1 mailbox)))))
1845 (defun imap-body-lines (body)
1846 "Return number of lines in article by looking at the mime bodystructure BODY."
1848 (if (stringp (car body))
1849 (cond ((and (string= (upcase (car body)) "TEXT")
1850 (numberp (nth 7 body)))
1852 ((and (string= (upcase (car body)) "MESSAGE")
1853 (numberp (nth 9 body)))
1856 (apply '+ (mapcar 'imap-body-lines body)))
1859 (defun imap-envelope-from (from)
1860 "Return a from string line."
1862 (concat (aref from 0)
1863 (if (aref from 0) " <")
1867 (if (aref from 0) ">"))))
1870 ;; Internal functions.
1872 (defun imap-add-callback (tag func)
1873 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1875 (defun imap-send-command-1 (cmdstr)
1876 (setq cmdstr (concat cmdstr imap-client-eol))
1878 (process-send-string imap-process cmdstr))
1880 (defun imap-send-command (command &optional buffer)
1881 (with-current-buffer (or buffer (current-buffer))
1882 (if (not (listp command)) (setq command (list command)))
1883 (let ((tag (setq imap-tag (1+ imap-tag)))
1885 (setq cmdstr (concat (number-to-string imap-tag) " "))
1886 (while (setq cmd (pop command))
1887 (cond ((stringp cmd)
1888 (setq cmdstr (concat cmdstr cmd)))
1890 (let ((eol imap-client-eol)
1891 (calcfirst imap-calculate-literal-size-first)
1893 (with-current-buffer cmd
1895 (setq size (buffer-size)))
1896 (when (not (equal eol "\r\n"))
1897 ;; XXX modifies buffer!
1898 (goto-char (point-min))
1899 (while (search-forward "\r\n" nil t)
1900 (replace-match eol)))
1902 (setq size (buffer-size))))
1904 (concat cmdstr (format "{%d}" size))))
1907 (imap-send-command-1 cmdstr)
1909 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1910 (setq command nil) ;; abort command if no cont-req
1911 (let ((process imap-process)
1912 (stream imap-stream)
1913 (eol imap-client-eol))
1914 (with-current-buffer cmd
1916 (process-send-region process (point-min)
1918 (process-send-string process imap-client-eol))))
1919 (setq imap-continuation nil)))
1921 (imap-send-command-1 cmdstr)
1925 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1926 nil ;; abort command if no cont-req
1927 (cons (funcall cmd imap-continuation)
1929 (setq imap-continuation nil)))
1931 (error "Unknown command type"))))
1933 (imap-send-command-1 cmdstr))
1936 (defun imap-wait-for-tag (tag &optional buffer)
1937 (with-current-buffer (or buffer (current-buffer))
1938 (let (imap-have-messaged)
1939 (while (and (null imap-continuation)
1940 (memq (process-status imap-process) '(open run))
1941 (< imap-reached-tag tag))
1942 (let ((len (/ (buffer-size) 1024))
1945 (setq imap-have-messaged t)
1946 (message "imap read: %dk" len))
1947 (accept-process-output imap-process
1948 (truncate imap-read-timeout)
1949 (truncate (* (- imap-read-timeout
1950 (truncate imap-read-timeout))
1952 ;; A process can die _before_ we have processed everything it
1953 ;; has to say. Moreover, this can happen in between the call to
1954 ;; accept-process-output and the call to process-status in an
1955 ;; iteration of the loop above.
1956 (when (and (null imap-continuation)
1957 (< imap-reached-tag tag))
1958 (accept-process-output imap-process 0 0))
1959 (when imap-have-messaged
1961 (and (memq (process-status imap-process) '(open run))
1962 (or (assq tag imap-failed-tags)
1963 (if imap-continuation
1967 (defun imap-sentinel (process string)
1968 (delete-process process))
1970 (defun imap-find-next-line ()
1971 "Return point at end of current line, taking into account literals.
1972 Return nil if no complete line has arrived."
1973 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1976 (if (match-string 1)
1977 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1979 (goto-char (+ (point) (string-to-number (match-string 1))))
1980 (imap-find-next-line))
1983 (defun imap-arrival-filter (proc string)
1984 "IMAP process filter."
1985 ;; Sometimes, we are called even though the process has died.
1986 ;; Better abstain from doing stuff in that case.
1987 (when (buffer-name (process-buffer proc))
1988 (with-current-buffer (process-buffer proc)
1989 (goto-char (point-max))
1993 (goto-char (point-min))
1994 (while (setq end (imap-find-next-line))
1996 (narrow-to-region (point-min) end)
1997 (delete-char (- (length imap-server-eol)))
1998 (goto-char (point-min))
2000 (cond ((eq imap-state 'initial)
2001 (imap-parse-greeting))
2002 ((or (eq imap-state 'auth)
2003 (eq imap-state 'nonauth)
2004 (eq imap-state 'selected)
2005 (eq imap-state 'examine))
2006 (imap-parse-response))
2008 (message "Unknown state %s in arrival filter"
2010 (delete-region (point-min) (point-max)))))))))
2015 (defsubst imap-forward ()
2016 (or (eobp) (forward-char)))
2019 ;; ; Unsigned 32-bit integer
2020 ;; ; (0 <= n < 4,294,967,296)
2022 (defsubst imap-parse-number ()
2023 (when (looking-at "[0-9]+")
2025 (string-to-number (match-string 0))
2026 (goto-char (match-end 0)))))
2028 ;; literal = "{" number "}" CRLF *CHAR8
2029 ;; ; Number represents the number of CHAR8s
2031 (defsubst imap-parse-literal ()
2032 (when (looking-at "{\\([0-9]+\\)}\r\n")
2033 (let ((pos (match-end 0))
2034 (len (string-to-number (match-string 1))))
2035 (if (< (point-max) (+ pos len))
2037 (goto-char (+ pos len))
2038 (buffer-substring pos (+ pos len))))))
2040 ;; string = quoted / literal
2042 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
2044 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2045 ;; "\" quoted-specials
2047 ;; quoted-specials = DQUOTE / "\"
2049 ;; TEXT-CHAR = <any CHAR except CR and LF>
2051 (defsubst imap-parse-string ()
2052 (cond ((eq (char-after) ?\")
2054 (let ((p (point)) (name ""))
2055 (skip-chars-forward "^\"\\\\")
2056 (setq name (buffer-substring p (point)))
2057 (while (eq (char-after) ?\\)
2058 (setq p (1+ (point)))
2060 (skip-chars-forward "^\"\\\\")
2061 (setq name (concat name (buffer-substring p (point)))))
2064 ((eq (char-after) ?{)
2065 (imap-parse-literal))))
2069 (defsubst imap-parse-nil ()
2070 (if (looking-at "NIL")
2071 (goto-char (match-end 0))))
2073 ;; nstring = string / nil
2075 (defsubst imap-parse-nstring ()
2076 (or (imap-parse-string)
2077 (and (imap-parse-nil)
2080 ;; astring = atom / string
2082 ;; atom = 1*ATOM-CHAR
2084 ;; ATOM-CHAR = <any CHAR except atom-specials>
2086 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
2089 ;; list-wildcards = "%" / "*"
2091 ;; quoted-specials = DQUOTE / "\"
2093 (defsubst imap-parse-astring ()
2094 (or (imap-parse-string)
2095 (buffer-substring (point)
2096 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2097 (goto-char (1- (match-end 0)))
2101 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
2104 ;; addr-adl = nstring
2105 ;; ; Holds route from [RFC-822] route-addr if
2108 ;; addr-host = nstring
2109 ;; ; nil indicates [RFC-822] group syntax.
2110 ;; ; Otherwise, holds [RFC-822] domain name
2112 ;; addr-mailbox = nstring
2113 ;; ; nil indicates end of [RFC-822] group; if
2114 ;; ; non-nil and addr-host is nil, holds
2115 ;; ; [RFC-822] group name.
2116 ;; ; Otherwise, holds [RFC-822] local-part
2117 ;; ; after removing [RFC-822] quoting
2119 ;; addr-name = nstring
2120 ;; ; If non-nil, holds phrase from [RFC-822]
2121 ;; ; mailbox after removing [RFC-822] quoting
2124 (defsubst imap-parse-address ()
2126 (when (eq (char-after) ?\()
2128 (setq address (vector (prog1 (imap-parse-nstring)
2130 (prog1 (imap-parse-nstring)
2132 (prog1 (imap-parse-nstring)
2134 (imap-parse-nstring)))
2135 (when (eq (char-after) ?\))
2139 ;; address-list = "(" 1*address ")" / nil
2143 (defsubst imap-parse-address-list ()
2144 (if (eq (char-after) ?\()
2145 (let (address addresses)
2147 (while (and (not (eq (char-after) ?\)))
2148 ;; next line for MS Exchange bug
2149 (progn (and (eq (char-after) ? ) (imap-forward)) t)
2150 (setq address (imap-parse-address)))
2151 (setq addresses (cons address addresses)))
2152 (when (eq (char-after) ?\))
2154 (nreverse addresses)))
2155 ;; With assert, the code might not be eval'd.
2156 ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2159 ;; mailbox = "INBOX" / astring
2160 ;; ; INBOX is case-insensitive. All case variants of
2161 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2162 ;; ; not as an astring. An astring which consists of
2163 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
2164 ;; ; is considered to be INBOX and not an astring.
2165 ;; ; Refer to section 5.1 for further
2166 ;; ; semantic details of mailbox names.
2168 (defsubst imap-parse-mailbox ()
2169 (let ((mailbox (imap-parse-astring)))
2170 (if (string-equal "INBOX" (upcase mailbox))
2174 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2176 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
2177 ;; ; Authentication condition
2179 ;; resp-cond-bye = "BYE" SP resp-text
2181 (defun imap-parse-greeting ()
2182 "Parse an IMAP greeting."
2183 (cond ((looking-at "\\* OK ")
2184 (setq imap-state 'nonauth))
2185 ((looking-at "\\* PREAUTH ")
2186 (setq imap-state 'auth))
2187 ((looking-at "\\* BYE ")
2188 (setq imap-state 'closed))))
2190 ;; response = *(continue-req / response-data) response-done
2192 ;; continue-req = "+" SP (resp-text / base64) CRLF
2194 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
2195 ;; mailbox-data / message-data / capability-data) CRLF
2197 ;; response-done = response-tagged / response-fatal
2199 ;; response-fatal = "*" SP resp-cond-bye CRLF
2200 ;; ; Server closes connection immediately
2202 ;; response-tagged = tag SP resp-cond-state CRLF
2204 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2205 ;; ; Status condition
2207 ;; resp-cond-bye = "BYE" SP resp-text
2209 ;; mailbox-data = "FLAGS" SP flag-list /
2210 ;; "LIST" SP mailbox-list /
2211 ;; "LSUB" SP mailbox-list /
2212 ;; "SEARCH" *(SP nz-number) /
2213 ;; "STATUS" SP mailbox SP "("
2214 ;; [status-att SP number *(SP status-att SP number)] ")" /
2215 ;; number SP "EXISTS" /
2216 ;; number SP "RECENT"
2218 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2220 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2222 ;; ; IMAP4rev1 servers which offer RFC 1730
2223 ;; ; compatibility MUST list "IMAP4" as the first
2226 (defun imap-parse-response ()
2227 "Parse a IMAP command response."
2229 (case (setq token (read (current-buffer)))
2230 (+ (setq imap-continuation
2231 (or (buffer-substring (min (point-max) (1+ (point)))
2234 (* (case (prog1 (setq token (read (current-buffer)))
2236 (OK (imap-parse-resp-text))
2237 (NO (imap-parse-resp-text))
2238 (BAD (imap-parse-resp-text))
2239 (BYE (imap-parse-resp-text))
2240 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
2241 (LIST (imap-parse-data-list 'list))
2242 (LSUB (imap-parse-data-list 'lsub))
2243 (SEARCH (imap-mailbox-put
2245 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2246 (STATUS (imap-parse-status))
2247 (CAPABILITY (setq imap-capability
2248 (read (concat "(" (upcase (buffer-substring
2249 (point) (point-max)))
2251 (ID (setq imap-id (read (buffer-substring (point)
2253 (ACL (imap-parse-acl))
2254 (t (case (prog1 (read (current-buffer))
2256 (EXISTS (imap-mailbox-put 'exists token))
2257 (RECENT (imap-mailbox-put 'recent token))
2259 (FETCH (imap-parse-fetch token))
2260 (t (message "Garbage: %s" (buffer-string)))))))
2262 (if (not (integerp token))
2263 (message "Garbage: %s" (buffer-string))
2264 (case (prog1 (setq status (read (current-buffer)))
2267 (setq imap-reached-tag (max imap-reached-tag token))
2268 (imap-parse-resp-text)))
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)
2280 imap-failed-tags))))
2282 (setq imap-reached-tag (max imap-reached-tag token))
2284 (imap-parse-resp-text))
2286 (when (eq (char-after) ?\[)
2287 (setq code (buffer-substring (point)
2288 (search-forward "]")))
2290 (setq text (buffer-substring (point) (point-max)))
2291 (push (list token status code text) imap-failed-tags)
2292 (error "Internal error, tag %s status %s code %s text %s"
2293 token status code text))))
2294 (t (message "Garbage: %s" (buffer-string))))
2295 (when (assq token imap-callbacks)
2296 (funcall (cdr (assq token imap-callbacks)) token status)
2297 (setq imap-callbacks
2298 (imap-remassoc token imap-callbacks)))))))))
2300 ;; resp-text = ["[" resp-text-code "]" SP] text
2302 ;; text = 1*TEXT-CHAR
2304 ;; TEXT-CHAR = <any CHAR except CR and LF>
2306 (defun imap-parse-resp-text ()
2307 (imap-parse-resp-text-code))
2309 ;; resp-text-code = "ALERT" /
2310 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2311 ;; "NEWNAME" SP string SP string /
2313 ;; "PERMANENTFLAGS" SP "("
2314 ;; [flag-perm *(SP flag-perm)] ")" /
2318 ;; "UIDNEXT" SP nz-number /
2319 ;; "UIDVALIDITY" SP nz-number /
2320 ;; "UNSEEN" SP nz-number /
2321 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2323 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2325 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2327 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2329 ;; ; Identifies a set of messages. For message
2330 ;; ; sequence numbers, these are consecutive
2331 ;; ; numbers from 1 to the number of messages in
2333 ;; ; Comma delimits individual numbers, colon
2334 ;; ; delimits between two numbers inclusive.
2335 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2336 ;; ; 14,15 for a mailbox with 15 messages.
2338 ;; sequence-num = nz-number / "*"
2339 ;; ; * is the largest number in use. For message
2340 ;; ; sequence numbers, it is the number of messages
2341 ;; ; in the mailbox. For unique identifiers, it is
2342 ;; ; the unique identifier of the last message in
2345 ;; flag-perm = flag / "\*"
2347 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2348 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2349 ;; ; Does not include "\Recent"
2351 ;; flag-extension = "\" atom
2352 ;; ; Future expansion. Client implementations
2353 ;; ; MUST accept flag-extension flags. Server
2354 ;; ; implementations MUST NOT generate
2355 ;; ; flag-extension flags except as defined by
2356 ;; ; future standard or standards-track
2357 ;; ; revisions of this specification.
2359 ;; flag-keyword = atom
2361 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2363 (defun imap-parse-resp-text-code ()
2364 ;; xxx next line for stalker communigate pro 3.3.1 bug
2365 (when (looking-at " \\[")
2367 (when (eq (char-after) ?\[)
2369 (cond ((search-forward "PERMANENTFLAGS " nil t)
2370 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2371 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2372 (imap-mailbox-put 'uidnext (match-string 1)))
2373 ((search-forward "UNSEEN " nil t)
2374 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2375 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2376 (imap-mailbox-put 'uidvalidity (match-string 1)))
2377 ((search-forward "READ-ONLY" nil t)
2378 (imap-mailbox-put 'read-only t))
2379 ((search-forward "NEWNAME " nil t)
2380 (let (oldname newname)
2381 (setq oldname (imap-parse-string))
2383 (setq newname (imap-parse-string))
2384 (imap-mailbox-put 'newname newname oldname)))
2385 ((search-forward "TRYCREATE" nil t)
2386 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2387 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2388 (imap-mailbox-put 'appenduid
2389 (list (match-string 1)
2390 (string-to-number (match-string 2)))
2391 imap-current-target-mailbox))
2392 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2393 (imap-mailbox-put 'copyuid (list (match-string 1)
2396 imap-current-target-mailbox))
2397 ((search-forward "ALERT] " nil t)
2398 (message "Imap server %s information: %s" imap-server
2399 (buffer-substring (point) (point-max)))))))
2401 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2402 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2404 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2405 ;; *(SP mbx-list-oflag) /
2406 ;; mbx-list-oflag *(SP mbx-list-oflag)
2408 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2409 ;; ; Other flags; multiple possible per LIST response
2411 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2412 ;; ; Selectability flags; only one per LIST response
2414 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2415 ;; "\" quoted-specials
2417 ;; quoted-specials = DQUOTE / "\"
2419 (defun imap-parse-data-list (type)
2420 (let (flags delimiter mailbox)
2421 (setq flags (imap-parse-flag-list))
2422 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2423 (setq delimiter (match-string 1))
2424 (goto-char (1+ (match-end 0)))
2425 (when (setq mailbox (imap-parse-mailbox))
2426 (imap-mailbox-put type t mailbox)
2427 (imap-mailbox-put 'list-flags flags mailbox)
2428 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2430 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2431 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2432 ;; "INTERNALDATE" SPACE date_time /
2433 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2434 ;; "RFC822.SIZE" SPACE number /
2435 ;; "BODY" ["STRUCTURE"] SPACE body /
2436 ;; "BODY" section ["<" number ">"] SPACE nstring /
2437 ;; "UID" SPACE uniqueid) ")"
2439 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2440 ;; SPACE time SPACE zone <">
2442 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2443 ;; ["." (section_text / "MIME")])] "]"
2445 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2446 ;; SPACE header_list / "TEXT"
2448 ;; header_fld_name ::= astring
2450 ;; header_list ::= "(" 1#header_fld_name ")"
2452 (defsubst imap-parse-header-list ()
2453 (when (eq (char-after) ?\()
2455 (while (not (eq (char-after) ?\)))
2457 (push (imap-parse-astring) strlist))
2459 (nreverse strlist))))
2461 (defsubst imap-parse-fetch-body-section ()
2463 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2464 (if (eq (char-before) ? )
2466 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2467 (search-forward "]" nil t))
2470 (defun imap-parse-fetch (response)
2471 (when (eq (char-after) ?\()
2472 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2473 rfc822size body bodydetail bodystructure flags-empty)
2474 ;; Courier can insert spurious blank characters which will
2475 ;; confuse `read', so skip past them.
2476 (while (let ((moved (skip-chars-forward " \t")))
2477 (prog1 (not (eq (char-after) ?\)))
2478 (unless (= moved 0) (backward-char))))
2480 (let ((token (read (current-buffer))))
2482 (cond ((eq token 'UID)
2483 (setq uid (condition-case ()
2484 (read (current-buffer))
2487 (setq flags (imap-parse-flag-list))
2489 (setq flags-empty 't)))
2490 ((eq token 'ENVELOPE)
2491 (setq envelope (imap-parse-envelope)))
2492 ((eq token 'INTERNALDATE)
2493 (setq internaldate (imap-parse-string)))
2495 (setq rfc822 (imap-parse-nstring)))
2496 ((eq token 'RFC822.HEADER)
2497 (setq rfc822header (imap-parse-nstring)))
2498 ((eq token 'RFC822.TEXT)
2499 (setq rfc822text (imap-parse-nstring)))
2500 ((eq token 'RFC822.SIZE)
2501 (setq rfc822size (read (current-buffer))))
2503 (if (eq (char-before) ?\[)
2505 (upcase (imap-parse-fetch-body-section))
2506 (and (eq (char-after) ?<)
2507 (buffer-substring (1+ (point))
2508 (search-forward ">" nil t)))
2509 (progn (imap-forward)
2510 (imap-parse-nstring)))
2512 (setq body (imap-parse-body))))
2513 ((eq token 'BODYSTRUCTURE)
2514 (setq bodystructure (imap-parse-body))))))
2516 (setq imap-current-message uid)
2517 (imap-message-put uid 'UID uid)
2518 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2519 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2520 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2521 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2522 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2523 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2524 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2525 (and body (imap-message-put uid 'BODY body))
2526 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2527 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2528 (run-hooks 'imap-fetch-data-hook)))))
2530 ;; mailbox-data = ...
2531 ;; "STATUS" SP mailbox SP "("
2532 ;; [status-att SP number
2533 ;; *(SP status-att SP number)] ")"
2536 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2539 (defun imap-parse-status ()
2540 (let ((mailbox (imap-parse-mailbox)))
2541 (if (eq (char-after) ? )
2543 (when (and mailbox (eq (char-after) ?\())
2544 (while (and (not (eq (char-after) ?\)))
2545 (or (forward-char) t)
2546 (looking-at "\\([A-Za-z]+\\) "))
2547 (let ((token (upcase (match-string 1))))
2548 (goto-char (match-end 0))
2549 (cond ((string= token "MESSAGES")
2550 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2551 ((string= token "RECENT")
2552 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2553 ((string= token "UIDNEXT")
2554 (and (looking-at "[0-9]+")
2555 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2556 (goto-char (match-end 0))))
2557 ((string= token "UIDVALIDITY")
2558 (and (looking-at "[0-9]+")
2559 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2560 (goto-char (match-end 0))))
2561 ((string= token "UNSEEN")
2562 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2564 (message "Unknown status data %s in mailbox %s ignored"
2566 (read (current-buffer)))))))))
2568 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2571 ;; identifier ::= astring
2573 ;; rights ::= astring
2575 (defun imap-parse-acl ()
2576 (let ((mailbox (imap-parse-mailbox))
2577 identifier rights acl)
2578 (while (eq (char-after) ?\ )
2580 (setq identifier (imap-parse-astring))
2582 (setq rights (imap-parse-astring))
2583 (setq acl (append acl (list (cons identifier rights)))))
2584 (imap-mailbox-put 'acl acl mailbox)))
2586 ;; flag-list = "(" [flag *(SP flag)] ")"
2588 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2589 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2590 ;; ; Does not include "\Recent"
2592 ;; flag-keyword = atom
2594 ;; flag-extension = "\" atom
2595 ;; ; Future expansion. Client implementations
2596 ;; ; MUST accept flag-extension flags. Server
2597 ;; ; implementations MUST NOT generate
2598 ;; ; flag-extension flags except as defined by
2599 ;; ; future standard or standards-track
2600 ;; ; revisions of this specification.
2602 (defun imap-parse-flag-list ()
2603 (let (flag-list start)
2604 (assert (eq (char-after) ?\() nil "In imap-parse-flag-list 1")
2605 (while (and (not (eq (char-after) ?\)))
2608 ;; next line for Courier IMAP bug.
2609 (skip-chars-forward " ")
2611 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2612 (push (buffer-substring start (point)) flag-list))
2613 (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list 2")
2615 (nreverse flag-list)))
2617 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2618 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2619 ;; env-in-reply-to SP env-message-id ")"
2621 ;; env-bcc = "(" 1*address ")" / nil
2623 ;; env-cc = "(" 1*address ")" / nil
2625 ;; env-date = nstring
2627 ;; env-from = "(" 1*address ")" / nil
2629 ;; env-in-reply-to = nstring
2631 ;; env-message-id = nstring
2633 ;; env-reply-to = "(" 1*address ")" / nil
2635 ;; env-sender = "(" 1*address ")" / nil
2637 ;; env-subject = nstring
2639 ;; env-to = "(" 1*address ")" / nil
2641 (defun imap-parse-envelope ()
2642 (when (eq (char-after) ?\()
2644 (vector (prog1 (imap-parse-nstring) ;; date
2646 (prog1 (imap-parse-nstring) ;; subject
2648 (prog1 (imap-parse-address-list) ;; from
2650 (prog1 (imap-parse-address-list) ;; sender
2652 (prog1 (imap-parse-address-list) ;; reply-to
2654 (prog1 (imap-parse-address-list) ;; to
2656 (prog1 (imap-parse-address-list) ;; cc
2658 (prog1 (imap-parse-address-list) ;; bcc
2660 (prog1 (imap-parse-nstring) ;; in-reply-to
2662 (prog1 (imap-parse-nstring) ;; message-id
2665 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2667 (defsubst imap-parse-string-list ()
2668 (cond ((eq (char-after) ?\() ;; body-fld-param
2671 (while (setq str (imap-parse-string))
2673 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2674 ;; between body-fld-param's sometimes
2675 (or (eq (char-after) ?\")
2677 (nreverse strlist)))
2681 ;; body-extension = nstring / number /
2682 ;; "(" body-extension *(SP body-extension) ")"
2683 ;; ; Future expansion. Client implementations
2684 ;; ; MUST accept body-extension fields. Server
2685 ;; ; implementations MUST NOT generate
2686 ;; ; body-extension fields except as defined by
2687 ;; ; future standard or standards-track
2688 ;; ; revisions of this specification.
2690 (defun imap-parse-body-extension ()
2691 (if (eq (char-after) ?\()
2694 (push (imap-parse-body-extension) b-e)
2695 (while (eq (char-after) ?\ )
2697 (push (imap-parse-body-extension) b-e))
2698 (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2701 (or (imap-parse-number)
2702 (imap-parse-nstring))))
2704 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2705 ;; *(SP body-extension)]]
2706 ;; ; MUST NOT be returned on non-extensible
2709 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2710 ;; *(SP body-extension)]]
2711 ;; ; MUST NOT be returned on non-extensible
2714 (defsubst imap-parse-body-ext ()
2716 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2719 (if (eq (char-after) ?\()
2722 (push (imap-parse-string) dsp)
2724 (push (imap-parse-string-list) dsp)
2726 ;; With assert, the code might not be eval'd.
2727 ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2729 (push (nreverse dsp) ext))
2730 (when (eq (char-after) ?\ ) ;; body-fld-lang
2732 (if (eq (char-after) ?\()
2733 (push (imap-parse-string-list) ext)
2734 (push (imap-parse-nstring) ext))
2735 (while (eq (char-after) ?\ ) ;; body-extension
2737 (setq ext (append (imap-parse-body-extension) ext)))))
2740 ;; body = "(" body-type-1part / body-type-mpart ")"
2742 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2743 ;; *(SP body-extension)]]
2744 ;; ; MUST NOT be returned on non-extensible
2747 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2748 ;; *(SP body-extension)]]
2749 ;; ; MUST NOT be returned on non-extensible
2752 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2753 ;; body-fld-enc SP body-fld-octets
2755 ;; body-fld-desc = nstring
2757 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2759 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2760 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2762 ;; body-fld-id = nstring
2764 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2766 ;; body-fld-lines = number
2768 ;; body-fld-md5 = nstring
2770 ;; body-fld-octets = number
2772 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2774 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2775 ;; [SP body-ext-1part]
2777 ;; body-type-basic = media-basic SP body-fields
2778 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2780 ;; body-type-msg = media-message SP body-fields SP envelope
2781 ;; SP body SP body-fld-lines
2783 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2785 ;; body-type-mpart = 1*body SP media-subtype
2786 ;; [SP body-ext-mpart]
2788 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2789 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2790 ;; ; Defined in [MIME-IMT]
2792 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2793 ;; ; Defined in [MIME-IMT]
2795 ;; media-subtype = string
2796 ;; ; Defined in [MIME-IMT]
2798 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2799 ;; ; Defined in [MIME-IMT]
2801 (defun imap-parse-body ()
2803 (when (eq (char-after) ?\()
2805 (if (eq (char-after) ?\()
2807 (while (and (eq (char-after) ?\()
2808 (setq subbody (imap-parse-body)))
2809 ;; buggy stalker communigate pro 3.0 inserts a SPC between
2810 ;; parts in multiparts
2811 (when (and (eq (char-after) ?\ )
2812 (eq (char-after (1+ (point))) ?\())
2814 (push subbody body))
2816 (push (imap-parse-string) body) ;; media-subtype
2817 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2819 (if (eq (char-after) ?\() ;; body-fld-param
2820 (push (imap-parse-string-list) body)
2821 (push (and (imap-parse-nil) nil) body))
2823 (append (imap-parse-body-ext) body))) ;; body-ext-...
2824 (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2828 (push (imap-parse-string) body) ;; media-type
2830 (push (imap-parse-string) body) ;; media-subtype
2832 ;; next line for Sun SIMS bug
2833 (and (eq (char-after) ? ) (imap-forward))
2834 (if (eq (char-after) ?\() ;; body-fld-param
2835 (push (imap-parse-string-list) body)
2836 (push (and (imap-parse-nil) nil) body))
2838 (push (imap-parse-nstring) body) ;; body-fld-id
2840 (push (imap-parse-nstring) body) ;; body-fld-desc
2842 ;; Next `or' for Sun SIMS bug. It regards body-fld-enc as a
2843 ;; nstring and returns nil instead of defaulting back to 7BIT
2844 ;; as the standard says.
2845 ;; Exchange (2007, at least) does this as well.
2846 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2848 ;; Exchange 2007 can return -1, contrary to the spec...
2849 (if (eq (char-after) ?-)
2851 (skip-chars-forward "-0-9")
2853 (push (imap-parse-number) body)) ;; body-fld-octets
2855 ;; Ok, we're done parsing the required parts, what comes now is one of
2858 ;; envelope (then we're parsing body-type-msg)
2859 ;; body-fld-lines (then we're parsing body-type-text)
2860 ;; body-ext-1part (then we're parsing body-type-basic)
2862 ;; The problem is that the two first are in turn optionally followed
2863 ;; by the third. So we parse the first two here (if there are any)...
2865 (when (eq (char-after) ?\ )
2868 (cond ((eq (char-after) ?\() ;; body-type-msg:
2869 (push (imap-parse-envelope) body) ;; envelope
2871 (push (imap-parse-body) body) ;; body
2872 ;; buggy stalker communigate pro 3.0 doesn't print
2873 ;; number of lines in message/rfc822 attachment
2874 (if (eq (char-after) ?\))
2877 (push (imap-parse-number) body))) ;; body-fld-lines
2878 ((setq lines (imap-parse-number)) ;; body-type-text:
2879 (push lines body)) ;; body-fld-lines
2881 (backward-char))))) ;; no match...
2883 ;; ...and then parse the third one here...
2885 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2887 (push (imap-parse-nstring) body) ;; body-fld-md5
2888 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2890 (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2896 ;;; imap.el ends here