1 ;;; imap.el --- imap library
2 ;; Copyright (C) 1998, 1999, 2000
3 ;; Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <jas@pdc.kth.se>
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING. If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
27 ;; imap.el is a elisp library providing an interface for talking to
30 ;; imap.el is roughly divided in two parts, one that parses IMAP
31 ;; responses from the server and storing data into buffer-local
32 ;; variables, and one for utility functions which send commands to
33 ;; server, waits for an answer, and return information. The latter
34 ;; part is layered on top of the previous.
36 ;; The imap.el API consist of the following functions, other functions
37 ;; in this file should not be called directly and the result of doing
38 ;; so are at best undefined.
42 ;; imap-open, imap-opened, imap-authenticate, imap-close,
43 ;; imap-capability, imap-namespace, imap-error-text
47 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
48 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
49 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
50 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
51 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
52 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
53 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
57 ;; imap-fetch-asynch, imap-fetch,
58 ;; imap-current-message, imap-list-to-message-set,
59 ;; imap-message-get, imap-message-map
60 ;; imap-message-envelope-date, imap-message-envelope-subject,
61 ;; imap-message-envelope-from, imap-message-envelope-sender,
62 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
63 ;; imap-message-envelope-cc, imap-message-envelope-bcc
64 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
65 ;; imap-message-body, imap-message-flag-permanent-p
66 ;; imap-message-flags-set, imap-message-flags-del
67 ;; imap-message-flags-add, imap-message-copyuid
68 ;; imap-message-copy, imap-message-appenduid
69 ;; imap-message-append, imap-envelope-from
72 ;; It is my hope that theese commands should be pretty self
73 ;; explanatory for someone that know IMAP. All functions have
74 ;; additional documentation on how to invoke them.
76 ;; imap.el support RFC1730/2060 (IMAP4/IMAP4rev1), implemented IMAP
77 ;; extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
78 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
79 ;; LOGINDISABLED) (with use of external library starttls.el and
80 ;; program starttls) and the GSSAPI / kerberos V4 sections of RFC1731
81 ;; (with use of external program `imtest'). It also take advantage
82 ;; the UNSELECT extension in Cyrus IMAPD.
84 ;; Without the work of John McClary Prevost and Jim Radford this library
85 ;; would not have seen the light of day. Many thanks.
87 ;; This is a transcript of short interactive session for demonstration
90 ;; (imap-open "my.mail.server")
91 ;; => " *imap* my.mail.server:0"
93 ;; The rest are invoked with current buffer as the buffer returned by
94 ;; `imap-open'. It is possible to do all without this, but it would
95 ;; look ugly here since `buffer' is always the last argument for all
96 ;; imap.el API functions.
98 ;; (imap-authenticate "myusername" "mypassword")
101 ;; (imap-mailbox-lsub "*")
102 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
104 ;; (imap-mailbox-list "INBOX.n%")
105 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
107 ;; (imap-mailbox-select "INBOX.nnimap")
110 ;; (imap-mailbox-get 'exists)
113 ;; (imap-mailbox-get 'uidvalidity)
116 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
119 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
120 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
124 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
125 ;; o Don't use `read' at all (important places already fixed)
126 ;; o Accept list of articles instead of message set string in most
127 ;; imap-message-* functions.
131 ;; - 19991218 added starttls/digest-md5 patch,
132 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
133 ;; NB! you need SLIM for starttls.el and digest-md5.el
134 ;; - 19991023 commited to pgnus
139 (eval-when-compile (require 'cl))
141 (autoload 'open-ssl-stream "ssl")
142 (autoload 'base64-decode-string "base64")
143 (autoload 'base64-encode-string "base64")
144 (autoload 'starttls-open-stream "starttls")
145 (autoload 'starttls-negotiate "starttls")
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 'md5 "md5")
152 (autoload 'utf7-encode "utf7")
153 (autoload 'utf7-decode "utf7")
154 (autoload 'format-spec "format-spec")
155 (autoload 'format-spec-make "format-spec"))
160 "Low-level IMAP issues."
163 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
165 "List of strings containing commands for Kerberos 4 authentication.
166 %s is replaced with server hostname, %p with port to connect to, and
167 %l with the value of `imap-default-user'. The program should accept
168 IMAP commands on stdin and return responses to stdout. Each entry in
169 the list is tried until a successful connection is made."
171 :type '(repeat string))
173 (defcustom imap-gssapi-program '("imtest -m gssapi -u %l -p %p %s")
174 "List of strings containing commands for GSSAPI (krb5) authentication.
175 %s is replaced with server hostname, %p with port to connect to, and
176 %l with the value of `imap-default-user'. The program should accept
177 IMAP commands on stdin and return responses to stdout. Each entry in
178 the list is tried until a successful connection is made."
180 :type '(repeat string))
182 (defcustom imap-ssl-program '("openssl s_client -ssl3 -connect %s:%p"
183 "openssl s_client -ssl2 -connect %s:%p"
184 "s_client -ssl3 -connect %s:%p"
185 "s_client -ssl2 -connect %s:%p")
186 "A string, or list of strings, containing commands for SSL connections.
187 Within a string, %s is replaced with the server address and %p with
188 port number on server. The program should accept IMAP commands on
189 stdin and return responses to stdout. Each entry in the list is tried
190 until a successful connection is made."
192 :type '(choice string
195 (defcustom imap-shell-program '("ssh %s imapd"
197 "ssh %g ssh %s imapd"
198 "rsh %g rsh %s imapd")
199 "A list of strings, containing commands for IMAP connection.
200 Within a string, %s is replaced with the server address, %p with port
201 number on server, %g with `imap-shell-host', and %l with
202 `imap-default-user'. The program should read IMAP commands from stdin
203 and write IMAP response to stdout. Each entry in the list is tried
204 until a successful connection is made."
206 :type '(repeat string))
208 (defvar imap-shell-host "gateway"
209 "Hostname of rlogin proxy.")
211 (defvar imap-default-user (user-login-name)
212 "Default username to use.")
214 (defvar imap-error nil
215 "Error codes from the last command.")
217 ;; Various variables.
219 (defvar imap-fetch-data-hook nil
220 "Hooks called after receiving each FETCH response.")
222 (defvar imap-streams '(gssapi kerberos4 starttls ssl network shell)
223 "Priority of streams to consider when opening connection to server.")
225 (defvar imap-stream-alist
226 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
227 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
228 (ssl imap-ssl-p imap-ssl-open)
229 (network imap-network-p imap-network-open)
230 (shell imap-shell-p imap-shell-open)
231 (starttls imap-starttls-p imap-starttls-open))
232 "Definition of network streams.
236 NAME names the stream, CHECK is a function returning non-nil if the
237 server support the stream and OPEN is a function for opening the
240 (defvar imap-authenticators '(gssapi
246 "Priority of authenticators to consider when authenticating to server.")
248 (defvar imap-authenticator-alist
249 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
250 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
251 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
252 (login imap-login-p imap-login-auth)
253 (anonymous imap-anonymous-p imap-anonymous-auth)
254 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
255 "Definition of authenticators.
257 (NAME CHECK AUTHENTICATE)
259 NAME names the authenticator. CHECK is a function returning non-nil if
260 the server support the authenticator and AUTHENTICATE is a function
261 for doing the actuall authentification.")
263 (defvar imap-use-utf7 t
264 "If non-nil, do utf7 encoding/decoding of mailbox names.
265 Since the UTF7 decoding currently only decodes into ISO-8859-1
266 characters, you may disable this decoding if you need to access UTF7
267 encoded mailboxes which doesn't translate into ISO-8859-1.")
269 ;; Internal constants. Change theese and die.
271 (defconst imap-default-port 143)
272 (defconst imap-default-ssl-port 993)
273 (defconst imap-default-stream 'network)
274 (defconst imap-coding-system-for-read 'binary)
275 (defconst imap-coding-system-for-write 'binary)
276 (defconst imap-local-variables '(imap-server
285 imap-current-target-mailbox
294 imap-calculate-literal-size-first
297 ;; Internal variables.
299 (defvar imap-stream nil)
300 (defvar imap-auth nil)
301 (defvar imap-server nil)
302 (defvar imap-port nil)
303 (defvar imap-username nil)
304 (defvar imap-password nil)
305 (defvar imap-calculate-literal-size-first nil)
306 (defvar imap-state 'closed
308 Valid states are `closed', `initial', `nonauth', `auth', `selected'
311 (defvar imap-server-eol "\r\n"
312 "The EOL string sent from the server.")
314 (defvar imap-client-eol "\r\n"
315 "The EOL string we send to the server.")
317 (defvar imap-current-mailbox nil
318 "Current mailbox name.")
320 (defvar imap-current-target-mailbox nil
321 "Current target mailbox for COPY and APPEND commands.")
323 (defvar imap-mailbox-data nil
324 "Obarray with mailbox data.")
326 (defvar imap-mailbox-prime 997
327 "Length of imap-mailbox-data.")
329 (defvar imap-current-message nil
330 "Current message number.")
332 (defvar imap-message-data nil
333 "Obarray with message data.")
335 (defvar imap-message-prime 997
336 "Length of imap-message-data.")
338 (defvar imap-capability nil
339 "Capability for server.")
341 (defvar imap-namespace nil
342 "Namespace for current server.")
344 (defvar imap-reached-tag 0
345 "Lower limit on command tags that have been parsed.")
347 (defvar imap-failed-tags nil
348 "Alist of tags that failed.
349 Each element is a list with four elements; tag (a integer), response
350 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
351 human readable response text (a string).")
354 "Command tag number.")
356 (defvar imap-process nil
359 (defvar imap-continuation nil
360 "Non-nil indicates that the server emitted a continuation request.
361 The actually value is really the text on the continuation line.")
364 "Name of buffer for imap session trace.
365 For example: (setq imap-log \"*imap-log*\")")
367 (defvar imap-debug nil ;"*imap-debug*"
368 "Name of buffer for random debug spew.
369 For example: (setq imap-debug \"*imap-debug*\")")
372 ;; Utility functions:
374 (defsubst imap-disable-multibyte ()
375 "Enable multibyte in the current buffer."
376 (when (fboundp 'set-buffer-multibyte)
377 (set-buffer-multibyte nil)))
379 (defun imap-read-passwd (prompt &rest args)
380 "Read a password using PROMPT.
381 If ARGS, PROMPT is used as an argument to `format'."
382 (let ((prompt (if args
383 (apply 'format prompt args)
385 (funcall (if (or (fboundp 'read-passwd)
387 (fboundp 'read-passwd))
388 (and (load "passwd" t)
389 (fboundp 'read-passwd)))
391 (autoload 'ange-ftp-read-passwd "ange-ftp")
392 'ange-ftp-read-passwd)
395 (defsubst imap-utf7-encode (string)
399 (utf7-encode string t)
401 "imap: Could not UTF7 encode `%s', using it unencoded..."
406 (defsubst imap-utf7-decode (string)
410 (utf7-decode string t)
412 "imap: Could not UTF7 decode `%s', using it undecoded..."
417 (defsubst imap-ok-p (status)
420 (setq imap-error status)
423 (defun imap-error-text (&optional buffer)
424 (with-current-buffer (or buffer (current-buffer))
425 (nth 3 (car imap-failed-tags))))
428 ;; Server functions; stream stuff:
430 (defun imap-kerberos4-stream-p (buffer)
431 (imap-capability 'AUTH=KERBEROS_V4 buffer))
433 (defun imap-kerberos4-open (name buffer server port)
434 (let ((cmds imap-kerberos4-program)
436 (while (and (not done) (setq cmd (pop cmds)))
437 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
439 (let* ((port (or port imap-default-port))
440 (coding-system-for-read imap-coding-system-for-read)
441 (coding-system-for-write imap-coding-system-for-write)
442 (process (start-process
443 name buffer shell-file-name shell-command-switch
448 ?p (number-to-string port)
449 ?l imap-default-user))))
452 (with-current-buffer buffer
453 (setq imap-client-eol "\n"
454 imap-calculate-literal-size-first t)
455 (while (and (memq (process-status process) '(open run))
456 (goto-char (point-min))
457 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
458 (or (while (looking-at "^C:")
461 ;; cyrus 1.6 imtest print "S: " before server greeting
462 (or (not (looking-at "S: "))
465 (not (and (imap-parse-greeting)
466 ;; success in imtest < 1.6:
467 (or (re-search-forward
468 "^__\\(.*\\)__\n" nil t)
469 ;; success in imtest 1.6:
471 "^\\(Authenticat.*\\)" nil t))
472 (setq response (match-string 1)))))
473 (accept-process-output process 1)
476 (with-current-buffer (get-buffer-create imap-log)
477 (imap-disable-multibyte)
478 (buffer-disable-undo)
479 (goto-char (point-max))
480 (insert-buffer-substring buffer)))
482 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
483 (if response (concat "done, " response) "failed"))
484 (if (and response (let ((case-fold-search nil))
485 (not (string-match "failed" response))))
487 (if (memq (process-status process) '(open run))
488 (imap-send-command-wait "LOGOUT"))
489 (delete-process process)
493 (defun imap-gssapi-stream-p (buffer)
494 (imap-capability 'AUTH=GSSAPI buffer))
496 (defun imap-gssapi-open (name buffer server port)
497 (let ((cmds imap-gssapi-program)
499 (while (and (not done) (setq cmd (pop cmds)))
500 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
501 (let* ((port (or port imap-default-port))
502 (coding-system-for-read imap-coding-system-for-read)
503 (coding-system-for-write imap-coding-system-for-write)
504 (process (start-process
505 name buffer shell-file-name shell-command-switch
510 ?p (number-to-string port)
511 ?l imap-default-user))))
514 (with-current-buffer buffer
515 (setq imap-client-eol "\n")
516 (while (and (memq (process-status process) '(open run))
517 (goto-char (point-min))
518 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
519 (or (while (looking-at "^C:")
522 ;; cyrus 1.6 imtest print "S: " before server greeting
523 (or (not (looking-at "S: "))
526 (not (and (imap-parse-greeting)
527 ;; success in imtest 1.6:
529 "^\\(Authenticat.*\\)" nil t)
530 (setq response (match-string 1)))))
531 (accept-process-output process 1)
534 (with-current-buffer (get-buffer-create imap-log)
535 (imap-disable-multibyte)
536 (buffer-disable-undo)
537 (goto-char (point-max))
538 (insert-buffer-substring buffer)))
540 (message "GSSAPI IMAP connection: %s" (or response "failed"))
541 (if (and response (let ((case-fold-search nil))
542 (not (string-match "failed" response))))
544 (if (memq (process-status process) '(open run))
545 (imap-send-command-wait "LOGOUT"))
546 (delete-process process)
550 (defun imap-ssl-p (buffer)
553 (defun imap-ssl-open (name buffer server port)
554 "Open a SSL connection to server."
555 (let ((cmds (if (listp imap-ssl-program) imap-ssl-program
556 (list imap-ssl-program)))
558 (while (and (not done) (setq cmd (pop cmds)))
559 (message "imap: Opening SSL connection with `%s'..." cmd)
560 (let* ((port (or port imap-default-ssl-port))
561 (coding-system-for-read imap-coding-system-for-read)
562 (coding-system-for-write imap-coding-system-for-write)
563 (ssl-program-name shell-file-name)
564 (ssl-program-arguments
565 (list shell-command-switch
566 (format-spec cmd (format-spec-make
568 ?p (number-to-string port)))))
570 (when (setq process (ignore-errors (open-ssl-stream
571 name buffer server port)))
572 (with-current-buffer buffer
573 (goto-char (point-min))
574 (while (and (memq (process-status process) '(open run))
575 (goto-char (point-max))
577 (not (imap-parse-greeting)))
578 (accept-process-output process 1)
581 (with-current-buffer (get-buffer-create imap-log)
582 (imap-disable-multibyte)
583 (buffer-disable-undo)
584 (goto-char (point-max))
585 (insert-buffer-substring buffer)))
587 (when (memq (process-status process) '(open run))
588 (setq done process))))))
591 (message "imap: Opening SSL connection with `%s'...done" cmd)
593 (message "imap: Opening SSL connection with `%s'...failed" cmd)
596 (defun imap-network-p (buffer)
599 (defun imap-network-open (name buffer server port)
600 (let* ((port (or port imap-default-port))
601 (coding-system-for-read imap-coding-system-for-read)
602 (coding-system-for-write imap-coding-system-for-write)
603 (process (open-network-stream name buffer server port)))
605 (while (and (memq (process-status process) '(open run))
606 (goto-char (point-min))
607 (not (imap-parse-greeting)))
608 (accept-process-output process 1)
611 (with-current-buffer (get-buffer-create imap-log)
612 (imap-disable-multibyte)
613 (buffer-disable-undo)
614 (goto-char (point-max))
615 (insert-buffer-substring buffer)))
616 (when (memq (process-status process) '(open run))
619 (defun imap-shell-p (buffer)
622 (defun imap-shell-open (name buffer server port)
623 (let ((cmds imap-shell-program)
625 (while (and (not done) (setq cmd (pop cmds)))
626 (message "imap: Opening IMAP connection with `%s'..." cmd)
627 (setq imap-client-eol "\n")
628 (let* ((port (or port imap-default-port))
629 (coding-system-for-read imap-coding-system-for-read)
630 (coding-system-for-write imap-coding-system-for-write)
631 (process (start-process
632 name buffer shell-file-name shell-command-switch
638 ?p (number-to-string port)
639 ?l imap-default-user)))))
641 (while (and (memq (process-status process) '(open run))
642 (goto-char (point-min))
643 (not (imap-parse-greeting)))
644 (accept-process-output process 1)
648 (with-current-buffer (get-buffer-create imap-log)
649 (imap-disable-multibyte)
650 (buffer-disable-undo)
651 (goto-char (point-max))
652 (insert-buffer-substring buffer)))
653 (when (memq (process-status process) '(open run))
654 (setq done process)))))
657 (message "imap: Opening IMAP connection with `%s'...done" cmd)
659 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
662 (defun imap-starttls-p (buffer)
663 (and (imap-capability 'STARTTLS buffer)
667 (call-process "starttls"))
670 (defun imap-starttls-open (name buffer server port)
671 (let* ((port (or port imap-default-port))
672 (coding-system-for-read imap-coding-system-for-read)
673 (coding-system-for-write imap-coding-system-for-write)
674 (process (starttls-open-stream name buffer server port))
676 (message "imap: Connecting with STARTTLS...")
678 (while (and (memq (process-status process) '(open run))
679 (goto-char (point-min))
680 (not (imap-parse-greeting)))
681 (accept-process-output process 1)
684 (with-current-buffer (get-buffer-create imap-log)
685 (buffer-disable-undo)
686 (goto-char (point-max))
687 (insert-buffer-substring buffer)))
688 (let ((imap-process process))
691 (set-process-filter imap-process 'imap-arrival-filter)
692 (when (and (eq imap-stream 'starttls)
693 (imap-ok-p (imap-send-command-wait "STARTTLS")))
694 (starttls-negotiate imap-process)))
695 (set-process-filter imap-process nil)))
696 (when (memq (process-status process) '(open run))
697 (setq done process)))
700 (message "imap: Connecting with STARTTLS...done")
702 (message "imap: Connecting with STARTTLS...failed")
705 ;; Server functions; authenticator stuff:
707 (defun imap-interactive-login (buffer loginfunc)
708 "Login to server in BUFFER.
709 LOGINFUNC is passed a username and a password, it should return t if
710 it where sucessful authenticating itself to the server, nil otherwise.
711 Returns t if login was successful, nil otherwise."
712 (with-current-buffer buffer
713 (make-variable-buffer-local 'imap-username)
714 (make-variable-buffer-local 'imap-password)
715 (let (user passwd ret)
716 ;; (condition-case ()
717 (while (or (not user) (not passwd))
718 (setq user (or imap-username
719 (read-from-minibuffer
720 (concat "IMAP username for " imap-server ": ")
721 (or user imap-default-user))))
722 (setq passwd (or imap-password
724 (concat "IMAP password for " user "@"
726 (when (and user passwd)
727 (if (funcall loginfunc user passwd)
731 (if (and (not imap-password)
732 (y-or-n-p "Store password for this session? "))
733 (setq imap-password passwd)))
734 (message "Login failed...")
737 ;; (quit (with-current-buffer buffer
740 ;; (error (with-current-buffer buffer
745 (defun imap-gssapi-auth-p (buffer)
746 (imap-capability 'AUTH=GSSAPI buffer))
748 (defun imap-gssapi-auth (buffer)
749 (message "imap: Authenticating using GSSAPI...%s"
750 (if (eq imap-stream 'gssapi) "done" "failed"))
751 (eq imap-stream 'gssapi))
753 (defun imap-kerberos4-auth-p (buffer)
754 (imap-capability 'AUTH=KERBEROS_V4 buffer))
756 (defun imap-kerberos4-auth (buffer)
757 (message "imap: Authenticating using Kerberos 4...%s"
758 (if (eq imap-stream 'kerberos4) "done" "failed"))
759 (eq imap-stream 'kerberos4))
761 (defun imap-cram-md5-p (buffer)
762 (imap-capability 'AUTH=CRAM-MD5 buffer))
764 (defun imap-cram-md5-auth (buffer)
765 "Login to server using the AUTH CRAM-MD5 method."
766 (message "imap: Authenticating using CRAM-MD5...")
767 (let ((done (imap-interactive-login
769 (lambda (user passwd)
771 (imap-send-command-wait
773 "AUTHENTICATE CRAM-MD5"
775 (let* ((decoded (base64-decode-string challenge))
776 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
777 (response (concat user " " hash))
778 (encoded (base64-encode-string response)))
781 (message "imap: Authenticating using CRAM-MD5...done")
782 (message "imap: Authenticating using CRAM-MD5...failed"))))
786 (defun imap-login-p (buffer)
787 (and (not (imap-capability 'LOGINDISABLED buffer))
788 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
790 (defun imap-login-auth (buffer)
791 "Login to server using the LOGIN command."
792 (message "imap: Plaintext authentication...")
793 (imap-interactive-login buffer
794 (lambda (user passwd)
795 (imap-ok-p (imap-send-command-wait
796 (concat "LOGIN \"" user "\" \""
799 (defun imap-anonymous-p (buffer)
802 (defun imap-anonymous-auth (buffer)
803 (message "imap: Loging in anonymously...")
804 (with-current-buffer buffer
805 (imap-ok-p (imap-send-command-wait
806 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
807 (system-name)) "\"")))))
809 (defun imap-digest-md5-p (buffer)
810 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
812 (require 'digest-md5)
815 (defun imap-digest-md5-auth (buffer)
816 "Login to server using the AUTH DIGEST-MD5 method."
817 (message "imap: Authenticating using DIGEST-MD5...")
818 (imap-interactive-login
820 (lambda (user passwd)
824 "AUTHENTICATE DIGEST-MD5"
826 (digest-md5-parse-digest-challenge
827 (base64-decode-string challenge))
829 (digest-md5-digest-uri
830 "imap" (digest-md5-challenge 'realm)))
832 (digest-md5-digest-response
833 user passwd digest-uri)))
834 (base64-encode-string response 'no-line-break))))
836 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
838 (setq imap-continuation nil)
839 (imap-send-command-1 "")
840 (imap-ok-p (imap-wait-for-tag tag)))))))
844 (defun imap-open-1 (buffer)
845 (with-current-buffer buffer
847 (setq imap-current-mailbox nil
848 imap-current-message nil
850 imap-process (condition-case ()
851 (funcall (nth 2 (assq imap-stream
853 "imap" buffer imap-server imap-port)
856 (set-process-filter imap-process 'imap-arrival-filter)
857 (set-process-sentinel imap-process 'imap-sentinel)
858 (while (and (eq imap-state 'initial)
859 (memq (process-status imap-process) '(open run)))
860 (message "Waiting for response from %s..." imap-server)
861 (accept-process-output imap-process 1))
862 (message "Waiting for response from %s...done" imap-server)
863 (and (memq (process-status imap-process) '(open run))
866 (defun imap-open (server &optional port stream auth buffer)
867 "Open a IMAP connection to host SERVER at PORT returning a buffer.
868 If PORT is unspecified, a default value is used (143 except
869 for SSL which use 993).
870 STREAM indicates the stream to use, see `imap-streams' for available
871 streams. If nil, it choices the best stream the server is capable of.
872 AUTH indicates authenticator to use, see `imap-authenticators' for
873 available authenticators. If nil, it choices the best stream the
874 server is capable of.
875 BUFFER can be a buffer or a name of a buffer, which is created if
876 necessery. If nil, the buffer name is generated."
877 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
878 (with-current-buffer (get-buffer-create buffer)
879 (if (imap-opened buffer)
881 (mapcar 'make-variable-buffer-local imap-local-variables)
882 (imap-disable-multibyte)
883 (buffer-disable-undo)
884 (setq imap-server (or server imap-server))
885 (setq imap-port (or port imap-port))
886 (setq imap-auth (or auth imap-auth))
887 (setq imap-stream (or stream imap-stream))
888 (message "imap: Connecting to %s..." imap-server)
889 (if (let ((imap-stream (or imap-stream imap-default-stream)))
890 (imap-open-1 buffer))
892 (let (stream-changed)
893 (message "imap: Connecting to %s...done" imap-server)
894 (when (null imap-stream)
895 (let ((streams imap-streams))
896 (while (setq stream (pop streams))
897 (if (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
898 (setq stream-changed (not (eq (or imap-stream
904 (error "Couldn't figure out a stream for server"))))
906 (message "imap: Reconnecting with stream `%s'..." imap-stream)
908 (if (imap-open-1 buffer)
909 (message "imap: Reconnecting with stream `%s'...done"
911 (message "imap: Reconnecting with stream `%s'...failed"
913 (setq imap-capability nil))
914 (if (imap-opened buffer)
915 ;; Choose authenticator
916 (when (and (null imap-auth) (not (eq imap-state 'auth)))
917 (let ((auths imap-authenticators))
918 (while (setq auth (pop auths))
919 (if (funcall (nth 1 (assq auth imap-authenticator-alist))
924 (error "Couldn't figure out authenticator for server"))))))
925 (message "imap: Connecting to %s...failed" imap-server))
926 (when (imap-opened buffer)
927 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0))
930 (defun imap-opened (&optional buffer)
931 "Return non-nil if connection to imap server in BUFFER is open.
932 If BUFFER is nil then the current buffer is used."
933 (and (setq buffer (get-buffer (or buffer (current-buffer))))
934 (buffer-live-p buffer)
935 (with-current-buffer buffer
937 (memq (process-status imap-process) '(open run))))))
939 (defun imap-authenticate (&optional user passwd buffer)
940 "Authenticate to server in BUFFER, using current buffer if nil.
941 It uses the authenticator specified when opening the server. If the
942 authenticator requires username/passwords, they are queried from the
943 user and optionally stored in the buffer. If USER and/or PASSWD is
944 specified, the user will not be questioned and the username and/or
945 password is remembered in the buffer."
946 (with-current-buffer (or buffer (current-buffer))
947 (if (not (eq imap-state 'nonauth))
948 (or (eq imap-state 'auth)
949 (eq imap-state 'select)
950 (eq imap-state 'examine))
951 (make-variable-buffer-local 'imap-username)
952 (make-variable-buffer-local 'imap-password)
953 (if user (setq imap-username user))
954 (if passwd (setq imap-password passwd))
955 (if (funcall (nth 2 (assq imap-auth imap-authenticator-alist)) buffer)
956 (setq imap-state 'auth)))))
958 (defun imap-close (&optional buffer)
959 "Close connection to server in BUFFER.
960 If BUFFER is nil, the current buffer is used."
961 (with-current-buffer (or buffer (current-buffer))
963 (not (imap-ok-p (imap-send-command-wait "LOGOUT")))
964 (message "Server %s didn't let me log out" imap-server))
965 (when (and imap-process
966 (memq (process-status imap-process) '(open run)))
967 (delete-process imap-process))
968 (setq imap-current-mailbox nil
969 imap-current-message nil
974 (defun imap-capability (&optional identifier buffer)
975 "Return a list of identifiers which server in BUFFER support.
976 If IDENTIFIER, return non-nil if it's among the servers capabilities.
977 If BUFFER is nil, the current buffer is assumed."
978 (with-current-buffer (or buffer (current-buffer))
979 (unless imap-capability
980 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
981 (setq imap-capability '(IMAP2))))
983 (memq (intern (upcase (symbol-name identifier))) imap-capability)
986 (defun imap-namespace (&optional buffer)
987 "Return a namespace hierarchy at server in BUFFER.
988 If BUFFER is nil, the current buffer is assumed."
989 (with-current-buffer (or buffer (current-buffer))
990 (unless imap-namespace
991 (when (imap-capability 'NAMESPACE)
992 (imap-send-command-wait "NAMESPACE")))
995 (defun imap-send-command-wait (command &optional buffer)
996 (imap-wait-for-tag (imap-send-command command buffer) buffer))
999 ;; Mailbox functions:
1001 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1002 (with-current-buffer (or buffer (current-buffer))
1003 (if imap-mailbox-data
1004 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1006 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1007 propname value mailbox (current-buffer)))
1010 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1011 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1014 (defun imap-mailbox-get (propname &optional mailbox buffer)
1015 (let ((mailbox (imap-utf7-encode mailbox)))
1016 (with-current-buffer (or buffer (current-buffer))
1017 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1019 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1020 (with-current-buffer (or buffer (current-buffer))
1024 (push (funcall func (if mailbox-decoder
1025 (funcall mailbox-decoder (symbol-name s))
1026 (symbol-name s))) result))
1030 (defun imap-mailbox-map (func &optional buffer)
1031 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1032 Function should take a mailbox name (a string) as
1034 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1036 (defun imap-current-mailbox (&optional buffer)
1037 (with-current-buffer (or buffer (current-buffer))
1038 (imap-utf7-decode imap-current-mailbox)))
1040 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1041 (and (string= mailbox imap-current-mailbox)
1043 (eq imap-state 'examine))
1045 (eq imap-state 'selected)))))
1047 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1048 (with-current-buffer (or buffer (current-buffer))
1049 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1051 (defun imap-mailbox-select-1 (mailbox &optional examine)
1052 "Select MAILBOX on server in BUFFER.
1053 If EXAMINE is non-nil, do a read-only select."
1054 (if (imap-current-mailbox-p-1 mailbox examine)
1055 imap-current-mailbox
1056 (setq imap-current-mailbox mailbox)
1057 (if (imap-ok-p (imap-send-command-wait
1058 (concat (if examine "EXAMINE" "SELECT") " \""
1061 (setq imap-message-data (make-vector imap-message-prime 0)
1062 imap-state (if examine 'examine 'selected))
1063 imap-current-mailbox)
1064 ;; Failed SELECT/EXAMINE unselects current mailbox
1065 (setq imap-current-mailbox nil))))
1067 (defun imap-mailbox-select (mailbox &optional examine buffer)
1068 (with-current-buffer (or buffer (current-buffer))
1070 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1072 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1073 (with-current-buffer (or buffer (current-buffer))
1074 (imap-mailbox-select-1 mailbox 'exmine)))
1076 (defun imap-mailbox-examine (mailbox &optional buffer)
1077 "Examine MAILBOX on server in BUFFER."
1078 (imap-mailbox-select mailbox 'exmine buffer))
1080 (defun imap-mailbox-unselect (&optional buffer)
1081 "Close current folder in BUFFER, without expunging articles."
1082 (with-current-buffer (or buffer (current-buffer))
1083 (when (or (eq imap-state 'auth)
1084 (and (imap-capability 'UNSELECT)
1085 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1087 (imap-send-command-wait (concat "EXAMINE \""
1088 imap-current-mailbox
1090 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1091 (setq imap-current-mailbox nil
1092 imap-message-data nil
1096 (defun imap-mailbox-expunge (&optional buffer)
1097 "Expunge articles in current folder in BUFFER.
1098 If BUFFER is nil the current buffer is assumed."
1099 (with-current-buffer (or buffer (current-buffer))
1100 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1101 (imap-ok-p (imap-send-command-wait "EXPUNGE")))))
1103 (defun imap-mailbox-close (&optional buffer)
1104 "Expunge articles and close current folder in BUFFER.
1105 If BUFFER is nil the current buffer is assumed."
1106 (with-current-buffer (or buffer (current-buffer))
1107 (when (and imap-current-mailbox
1108 (imap-ok-p (imap-send-command-wait "CLOSE")))
1109 (setq imap-current-mailbox nil
1110 imap-message-data nil
1114 (defun imap-mailbox-create-1 (mailbox)
1115 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1117 (defun imap-mailbox-create (mailbox &optional buffer)
1118 "Create MAILBOX on server in BUFFER.
1119 If BUFFER is nil the current buffer is assumed."
1120 (with-current-buffer (or buffer (current-buffer))
1121 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1123 (defun imap-mailbox-delete (mailbox &optional buffer)
1124 "Delete MAILBOX on server in BUFFER.
1125 If BUFFER is nil the current buffer is assumed."
1126 (let ((mailbox (imap-utf7-encode mailbox)))
1127 (with-current-buffer (or buffer (current-buffer))
1129 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1131 (defun imap-mailbox-rename (oldname newname &optional buffer)
1132 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1133 If BUFFER is nil the current buffer is assumed."
1134 (let ((oldname (imap-utf7-encode oldname))
1135 (newname (imap-utf7-encode newname)))
1136 (with-current-buffer (or buffer (current-buffer))
1138 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1139 "\"" newname "\""))))))
1141 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1142 "Return a list of subscribed mailboxes on server in BUFFER.
1143 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1144 non-nil, a hierarchy delimiter is added to root. REFERENCE is a
1145 implementation-specific string that has to be passed to lsub command."
1146 (with-current-buffer (or buffer (current-buffer))
1147 ;; Make sure we know the hierarchy separator for root's hierarchy
1148 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1149 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1150 (imap-utf7-encode root) "\"")))
1151 ;; clear list data (NB not delimiter and other stuff)
1152 (imap-mailbox-map-1 (lambda (mailbox)
1153 (imap-mailbox-put 'lsub nil mailbox)))
1155 (imap-send-command-wait
1156 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1157 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1160 (imap-mailbox-map-1 (lambda (mailbox)
1161 (when (imap-mailbox-get-1 'lsub mailbox)
1162 (push (imap-utf7-decode mailbox) out))))
1165 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1166 "Return a list of mailboxes matching ROOT on server in BUFFER.
1167 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1168 root. REFERENCE is a implementation-specific string that has to be
1169 passed to list command."
1170 (with-current-buffer (or buffer (current-buffer))
1171 ;; Make sure we know the hierarchy separator for root's hierarchy
1172 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1173 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1174 (imap-utf7-encode root) "\"")))
1175 ;; clear list data (NB not delimiter and other stuff)
1176 (imap-mailbox-map-1 (lambda (mailbox)
1177 (imap-mailbox-put 'list nil mailbox)))
1179 (imap-send-command-wait
1180 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1181 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1184 (imap-mailbox-map-1 (lambda (mailbox)
1185 (when (imap-mailbox-get-1 'list mailbox)
1186 (push (imap-utf7-decode mailbox) out))))
1189 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1190 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1191 Returns non-nil if successful."
1192 (with-current-buffer (or buffer (current-buffer))
1193 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1194 (imap-utf7-encode mailbox)
1197 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1198 "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1199 Returns non-nil if successful."
1200 (with-current-buffer (or buffer (current-buffer))
1201 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1202 (imap-utf7-encode mailbox)
1205 (defun imap-mailbox-status (mailbox items &optional buffer)
1206 "Get status items ITEM in MAILBOX from server in BUFFER.
1207 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1208 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1209 or 'unseen. If ITEMS is a list of symbols, a list of values is
1210 returned, if ITEMS is a symbol only it's value is returned."
1211 (with-current-buffer (or buffer (current-buffer))
1213 (imap-send-command-wait (list "STATUS \""
1214 (imap-utf7-encode mailbox)
1221 (mapcar (lambda (item)
1222 (imap-mailbox-get item mailbox))
1224 (imap-mailbox-get items mailbox)))))
1226 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1227 "Get ACL on mailbox from server in BUFFER."
1228 (let ((mailbox (imap-utf7-encode mailbox)))
1229 (with-current-buffer (or buffer (current-buffer))
1231 (imap-send-command-wait (list "GETACL \""
1232 (or mailbox imap-current-mailbox)
1234 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1236 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1237 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1238 (let ((mailbox (imap-utf7-encode mailbox)))
1239 (with-current-buffer (or buffer (current-buffer))
1241 (imap-send-command-wait (list "SETACL \""
1242 (or mailbox imap-current-mailbox)
1248 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1249 "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1250 (let ((mailbox (imap-utf7-encode mailbox)))
1251 (with-current-buffer (or buffer (current-buffer))
1253 (imap-send-command-wait (list "DELETEACL \""
1254 (or mailbox imap-current-mailbox)
1259 ;; Message functions:
1261 (defun imap-current-message (&optional buffer)
1262 (with-current-buffer (or buffer (current-buffer))
1263 imap-current-message))
1265 (defun imap-list-to-message-set (list)
1266 (mapconcat (lambda (item)
1267 (number-to-string item))
1273 (defun imap-range-to-message-set (range)
1278 (car item) (cdr item))
1279 (format "%d" item)))
1280 (if (and (listp range) (not (listp (cdr range))))
1281 (list range) ;; make (1 . 2) into ((1 . 2))
1285 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1286 (with-current-buffer (or buffer (current-buffer))
1287 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1289 (imap-list-to-message-set uids)
1293 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1294 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1295 UIDS can be a string, number or a list of numbers. If RECEIVE
1296 is non-nil return theese properties."
1297 (with-current-buffer (or buffer (current-buffer))
1298 (when (imap-ok-p (imap-send-command-wait
1299 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1301 (imap-list-to-message-set uids)
1304 (if (or (null receive) (stringp uids))
1307 (mapcar (lambda (uid)
1309 (mapcar (lambda (prop)
1310 (imap-message-get uid prop))
1312 (imap-message-get uid receive)))
1314 (imap-message-get uids receive))))))
1316 (defun imap-message-put (uid propname value &optional buffer)
1317 (with-current-buffer (or buffer (current-buffer))
1318 (if imap-message-data
1319 (put (intern (number-to-string uid) imap-message-data)
1321 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1322 uid propname value (current-buffer)))
1325 (defun imap-message-get (uid propname &optional buffer)
1326 (with-current-buffer (or buffer (current-buffer))
1327 (get (intern-soft (number-to-string uid) imap-message-data)
1330 (defun imap-message-map (func propname &optional buffer)
1331 "Map a function across each mailbox in `imap-message-data', returning a list."
1332 (with-current-buffer (or buffer (current-buffer))
1336 (push (funcall func (get s 'UID) (get s propname)) result))
1340 (defmacro imap-message-envelope-date (uid &optional buffer)
1341 `(with-current-buffer (or ,buffer (current-buffer))
1342 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1344 (defmacro imap-message-envelope-subject (uid &optional buffer)
1345 `(with-current-buffer (or ,buffer (current-buffer))
1346 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1348 (defmacro imap-message-envelope-from (uid &optional buffer)
1349 `(with-current-buffer (or ,buffer (current-buffer))
1350 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1352 (defmacro imap-message-envelope-sender (uid &optional buffer)
1353 `(with-current-buffer (or ,buffer (current-buffer))
1354 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1356 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1357 `(with-current-buffer (or ,buffer (current-buffer))
1358 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1360 (defmacro imap-message-envelope-to (uid &optional buffer)
1361 `(with-current-buffer (or ,buffer (current-buffer))
1362 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1364 (defmacro imap-message-envelope-cc (uid &optional buffer)
1365 `(with-current-buffer (or ,buffer (current-buffer))
1366 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1368 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1369 `(with-current-buffer (or ,buffer (current-buffer))
1370 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1372 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1373 `(with-current-buffer (or ,buffer (current-buffer))
1374 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1376 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1377 `(with-current-buffer (or ,buffer (current-buffer))
1378 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1380 (defmacro imap-message-body (uid &optional buffer)
1381 `(with-current-buffer (or ,buffer (current-buffer))
1382 (imap-message-get ,uid 'BODY)))
1384 (defun imap-search (predicate &optional buffer)
1385 (with-current-buffer (or buffer (current-buffer))
1386 (imap-mailbox-put 'search 'dummy)
1387 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1388 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1389 (error "Missing SEARCH response to a SEARCH command")
1390 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1392 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1393 "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1394 (with-current-buffer (or buffer (current-buffer))
1395 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1396 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1398 (defun imap-message-flags-set (articles flags &optional silent buffer)
1399 (when (and articles flags)
1400 (with-current-buffer (or buffer (current-buffer))
1401 (imap-ok-p (imap-send-command-wait
1402 (concat "UID STORE " articles
1403 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1405 (defun imap-message-flags-del (articles flags &optional silent buffer)
1406 (when (and articles flags)
1407 (with-current-buffer (or buffer (current-buffer))
1408 (imap-ok-p (imap-send-command-wait
1409 (concat "UID STORE " articles
1410 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1412 (defun imap-message-flags-add (articles flags &optional silent buffer)
1413 (when (and articles flags)
1414 (with-current-buffer (or buffer (current-buffer))
1415 (imap-ok-p (imap-send-command-wait
1416 (concat "UID STORE " articles
1417 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1419 (defun imap-message-copyuid-1 (mailbox)
1420 (if (imap-capability 'UIDPLUS)
1421 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1422 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1423 (let ((old-mailbox imap-current-mailbox)
1425 (imap-message-data (make-vector 2 0)))
1426 (when (imap-mailbox-examine-1 mailbox)
1428 (and (imap-fetch "*" "UID")
1429 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1430 (apply 'max (imap-message-map
1431 (lambda (uid prop) uid) 'UID))))
1433 (imap-mailbox-select old-mailbox (eq state 'examine))
1434 (imap-mailbox-unselect)))))))
1436 (defun imap-message-copyuid (mailbox &optional buffer)
1437 (with-current-buffer (or buffer (current-buffer))
1438 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1440 (defun imap-message-copy (articles mailbox
1441 &optional dont-create no-copyuid buffer)
1442 "Copy ARTICLES (a string message set) to MAILBOX on server in
1443 BUFFER, creating mailbox if it doesn't exist. If dont-create is
1444 non-nil, it will not create a mailbox. On success, return a list with
1445 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1446 first element, rest of list contain the saved articles' UIDs."
1448 (with-current-buffer (or buffer (current-buffer))
1449 (let ((mailbox (imap-utf7-encode mailbox)))
1450 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1451 (imap-current-target-mailbox mailbox))
1452 (if (imap-ok-p (imap-send-command-wait cmd))
1454 (when (and (not dont-create)
1455 (imap-mailbox-get-1 'trycreate mailbox))
1456 (imap-mailbox-create-1 mailbox)
1457 (imap-ok-p (imap-send-command-wait cmd)))))
1459 (imap-message-copyuid-1 mailbox)))))))
1461 (defun imap-message-appenduid-1 (mailbox)
1462 (if (imap-capability 'UIDPLUS)
1463 (imap-mailbox-get-1 'appenduid mailbox)
1464 (let ((old-mailbox imap-current-mailbox)
1466 (imap-message-data (make-vector 2 0)))
1467 (when (imap-mailbox-examine-1 mailbox)
1469 (and (imap-fetch "*" "UID")
1470 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1471 (apply 'max (imap-message-map
1472 (lambda (uid prop) uid) 'UID))))
1474 (imap-mailbox-select old-mailbox (eq state 'examine))
1475 (imap-mailbox-unselect)))))))
1477 (defun imap-message-appenduid (mailbox &optional buffer)
1478 (with-current-buffer (or buffer (current-buffer))
1479 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1481 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1482 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1483 FLAGS and DATE-TIME is currently not used. Return a cons holding
1484 uidvalidity of MAILBOX and UID the newly created article got, or nil
1486 (let ((mailbox (imap-utf7-encode mailbox)))
1487 (with-current-buffer (or buffer (current-buffer))
1488 (and (let ((imap-current-target-mailbox mailbox))
1490 (imap-send-command-wait
1491 (list "APPEND \"" mailbox "\" " article))))
1492 (imap-message-appenduid-1 mailbox)))))
1494 (defun imap-body-lines (body)
1495 "Return number of lines in article by looking at the mime bodystructure BODY."
1497 (if (stringp (car body))
1498 (cond ((and (string= (upcase (car body)) "TEXT")
1499 (numberp (nth 7 body)))
1501 ((and (string= (upcase (car body)) "MESSAGE")
1502 (numberp (nth 9 body)))
1505 (apply '+ (mapcar 'imap-body-lines body)))
1508 (defun imap-envelope-from (from)
1509 "Return a from string line."
1511 (concat (aref from 0)
1512 (if (aref from 0) " <")
1516 (if (aref from 0) ">"))))
1519 ;; Internal functions.
1521 (defun imap-send-command-1 (cmdstr)
1522 (setq cmdstr (concat cmdstr imap-client-eol))
1524 (with-current-buffer (get-buffer-create imap-log)
1525 (imap-disable-multibyte)
1526 (buffer-disable-undo)
1527 (goto-char (point-max))
1529 (process-send-string imap-process cmdstr))
1531 (defun imap-send-command (command &optional buffer)
1532 (with-current-buffer (or buffer (current-buffer))
1533 (if (not (listp command)) (setq command (list command)))
1534 (let ((tag (setq imap-tag (1+ imap-tag)))
1536 (setq cmdstr (concat (number-to-string imap-tag) " "))
1537 (while (setq cmd (pop command))
1538 (cond ((stringp cmd)
1539 (setq cmdstr (concat cmdstr cmd)))
1541 (let ((eol imap-client-eol)
1542 (calcfirst imap-calculate-literal-size-first)
1544 (with-current-buffer cmd
1546 (setq size (buffer-size)))
1547 (when (not (equal eol "\r\n"))
1548 ;; XXX modifies buffer!
1549 (goto-char (point-min))
1550 (while (search-forward "\r\n" nil t)
1551 (replace-match eol)))
1553 (setq size (buffer-size))))
1555 (concat cmdstr (format "{%d}" size))))
1558 (imap-send-command-1 cmdstr)
1560 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1561 (setq command nil);; abort command if no cont-req
1562 (let ((process imap-process)
1563 (stream imap-stream)
1564 (eol imap-client-eol))
1565 (with-current-buffer cmd
1567 (with-current-buffer (get-buffer-create
1569 (imap-disable-multibyte)
1570 (buffer-disable-undo)
1571 (goto-char (point-max))
1572 (insert-buffer-substring cmd)))
1573 (process-send-region process (point-min)
1575 (process-send-string process imap-client-eol))))
1576 (setq imap-continuation nil)))
1578 (imap-send-command-1 cmdstr)
1581 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1582 (setq command nil);; abort command if no cont-req
1583 (setq command (cons (funcall cmd imap-continuation)
1585 (setq imap-continuation nil)))
1587 (error "Unknown command type"))))
1589 (imap-send-command-1 cmdstr))
1592 (defun imap-wait-for-tag (tag &optional buffer)
1593 (with-current-buffer (or buffer (current-buffer))
1594 (while (and (null imap-continuation)
1595 (< imap-reached-tag tag))
1596 (or (and (not (memq (process-status imap-process) '(open run)))
1598 (accept-process-output imap-process 1)))
1599 (or (assq tag imap-failed-tags)
1600 (if imap-continuation
1604 (defun imap-sentinel (process string)
1605 (delete-process process))
1607 (defun imap-find-next-line ()
1608 "Return point at end of current line, taking into account literals.
1609 Return nil if no complete line has arrived."
1610 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1613 (if (match-string 1)
1614 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1616 (goto-char (+ (point) (string-to-number (match-string 1))))
1617 (imap-find-next-line))
1620 (defun imap-arrival-filter (proc string)
1621 "IMAP process filter."
1622 (with-current-buffer (process-buffer proc)
1623 (goto-char (point-max))
1626 (with-current-buffer (get-buffer-create imap-log)
1627 (imap-disable-multibyte)
1628 (buffer-disable-undo)
1629 (goto-char (point-max))
1632 (goto-char (point-min))
1633 (while (setq end (imap-find-next-line))
1635 (narrow-to-region (point-min) end)
1636 (delete-backward-char (length imap-server-eol))
1637 (goto-char (point-min))
1639 (cond ((eq imap-state 'initial)
1640 (imap-parse-greeting))
1641 ((or (eq imap-state 'auth)
1642 (eq imap-state 'nonauth)
1643 (eq imap-state 'selected)
1644 (eq imap-state 'examine))
1645 (imap-parse-response))
1647 (message "Unknown state %s in arrival filter"
1649 (delete-region (point-min) (point-max))))))))
1654 (defsubst imap-forward ()
1655 (or (eobp) (forward-char)))
1658 ;; ; Unsigned 32-bit integer
1659 ;; ; (0 <= n < 4,294,967,296)
1661 (defsubst imap-parse-number ()
1662 (when (looking-at "[0-9]+")
1664 (string-to-number (match-string 0))
1665 (goto-char (match-end 0)))))
1667 ;; literal = "{" number "}" CRLF *CHAR8
1668 ;; ; Number represents the number of CHAR8s
1670 (defsubst imap-parse-literal ()
1671 (when (looking-at "{\\([0-9]+\\)}\r\n")
1672 (let ((pos (match-end 0))
1673 (len (string-to-number (match-string 1))))
1674 (if (< (point-max) (+ pos len))
1676 (goto-char (+ pos len))
1677 (buffer-substring pos (+ pos len))))))
1679 ;; string = quoted / literal
1681 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
1683 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
1684 ;; "\" quoted-specials
1686 ;; quoted-specials = DQUOTE / "\"
1688 ;; TEXT-CHAR = <any CHAR except CR and LF>
1690 (defsubst imap-parse-string ()
1691 (cond ((eq (char-after) ?\")
1693 (let ((p (point)) (name ""))
1694 (skip-chars-forward "^\"\\\\")
1695 (setq name (buffer-substring p (point)))
1696 (while (eq (char-after) ?\\)
1697 (setq p (1+ (point)))
1699 (skip-chars-forward "^\"\\\\")
1700 (setq name (concat name (buffer-substring p (point)))))
1703 ((eq (char-after) ?{)
1704 (imap-parse-literal))))
1708 (defsubst imap-parse-nil ()
1709 (if (looking-at "NIL")
1710 (goto-char (match-end 0))))
1712 ;; nstring = string / nil
1714 (defsubst imap-parse-nstring ()
1715 (or (imap-parse-string)
1716 (and (imap-parse-nil)
1719 ;; astring = atom / string
1721 ;; atom = 1*ATOM-CHAR
1723 ;; ATOM-CHAR = <any CHAR except atom-specials>
1725 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
1728 ;; list-wildcards = "%" / "*"
1730 ;; quoted-specials = DQUOTE / "\"
1732 (defsubst imap-parse-astring ()
1733 (or (imap-parse-string)
1734 (buffer-substring (point)
1735 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1736 (goto-char (1- (match-end 0)))
1740 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
1743 ;; addr-adl = nstring
1744 ;; ; Holds route from [RFC-822] route-addr if
1747 ;; addr-host = nstring
1748 ;; ; NIL indicates [RFC-822] group syntax.
1749 ;; ; Otherwise, holds [RFC-822] domain name
1751 ;; addr-mailbox = nstring
1752 ;; ; NIL indicates end of [RFC-822] group; if
1753 ;; ; non-NIL and addr-host is NIL, holds
1754 ;; ; [RFC-822] group name.
1755 ;; ; Otherwise, holds [RFC-822] local-part
1756 ;; ; after removing [RFC-822] quoting
1758 ;; addr-name = nstring
1759 ;; ; If non-NIL, holds phrase from [RFC-822]
1760 ;; ; mailbox after removing [RFC-822] quoting
1763 (defsubst imap-parse-address ()
1765 (when (eq (char-after) ?\()
1767 (setq address (vector (prog1 (imap-parse-nstring)
1769 (prog1 (imap-parse-nstring)
1771 (prog1 (imap-parse-nstring)
1773 (imap-parse-nstring)))
1774 (when (eq (char-after) ?\))
1778 ;; address-list = "(" 1*address ")" / nil
1782 (defsubst imap-parse-address-list ()
1783 (if (eq (char-after) ?\()
1784 (let (address addresses)
1786 (while (and (not (eq (char-after) ?\)))
1787 ;; next line for MS Exchange bug
1788 (progn (and (eq (char-after) ? ) (imap-forward)) t)
1789 (setq address (imap-parse-address)))
1790 (setq addresses (cons address addresses)))
1791 (when (eq (char-after) ?\))
1793 (nreverse addresses)))
1794 (assert (imap-parse-nil))))
1796 ;; mailbox = "INBOX" / astring
1797 ;; ; INBOX is case-insensitive. All case variants of
1798 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1799 ;; ; not as an astring. An astring which consists of
1800 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
1801 ;; ; is considered to be INBOX and not an astring.
1802 ;; ; Refer to section 5.1 for further
1803 ;; ; semantic details of mailbox names.
1805 (defsubst imap-parse-mailbox ()
1806 (let ((mailbox (imap-parse-astring)))
1807 (if (string-equal "INBOX" (upcase mailbox))
1811 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1813 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
1814 ;; ; Authentication condition
1816 ;; resp-cond-bye = "BYE" SP resp-text
1818 (defun imap-parse-greeting ()
1819 "Parse a IMAP greeting."
1820 (cond ((looking-at "\\* OK ")
1821 (setq imap-state 'nonauth))
1822 ((looking-at "\\* PREAUTH ")
1823 (setq imap-state 'auth))
1824 ((looking-at "\\* BYE ")
1825 (setq imap-state 'closed))))
1827 ;; response = *(continue-req / response-data) response-done
1829 ;; continue-req = "+" SP (resp-text / base64) CRLF
1831 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
1832 ;; mailbox-data / message-data / capability-data) CRLF
1834 ;; response-done = response-tagged / response-fatal
1836 ;; response-fatal = "*" SP resp-cond-bye CRLF
1837 ;; ; Server closes connection immediately
1839 ;; response-tagged = tag SP resp-cond-state CRLF
1841 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1842 ;; ; Status condition
1844 ;; resp-cond-bye = "BYE" SP resp-text
1846 ;; mailbox-data = "FLAGS" SP flag-list /
1847 ;; "LIST" SP mailbox-list /
1848 ;; "LSUB" SP mailbox-list /
1849 ;; "SEARCH" *(SP nz-number) /
1850 ;; "STATUS" SP mailbox SP "("
1851 ;; [status-att SP number *(SP status-att SP number)] ")" /
1852 ;; number SP "EXISTS" /
1853 ;; number SP "RECENT"
1855 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1857 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1859 ;; ; IMAP4rev1 servers which offer RFC 1730
1860 ;; ; compatibility MUST list "IMAP4" as the first
1863 (defun imap-parse-response ()
1864 "Parse a IMAP command response."
1866 (case (setq token (read (current-buffer)))
1867 (+ (setq imap-continuation
1868 (or (buffer-substring (min (point-max) (1+ (point)))
1871 (* (case (prog1 (setq token (read (current-buffer)))
1873 (OK (imap-parse-resp-text))
1874 (NO (imap-parse-resp-text))
1875 (BAD (imap-parse-resp-text))
1876 (BYE (imap-parse-resp-text))
1877 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
1878 (LIST (imap-parse-data-list 'list))
1879 (LSUB (imap-parse-data-list 'lsub))
1880 (SEARCH (imap-mailbox-put
1882 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1883 (STATUS (imap-parse-status))
1884 (CAPABILITY (setq imap-capability
1885 (read (concat "(" (upcase (buffer-substring
1886 (point) (point-max)))
1888 (ACL (imap-parse-acl))
1889 (t (case (prog1 (read (current-buffer))
1891 (EXISTS (imap-mailbox-put 'exists token))
1892 (RECENT (imap-mailbox-put 'recent token))
1894 (FETCH (imap-parse-fetch token))
1895 (t (message "Garbage: %s" (buffer-string)))))))
1897 (if (not (integerp token))
1898 (message "Garbage: %s" (buffer-string))
1899 (case (prog1 (setq status (read (current-buffer)))
1902 (setq imap-reached-tag (max imap-reached-tag token))
1903 (imap-parse-resp-text)))
1905 (setq imap-reached-tag (max imap-reached-tag token))
1907 (imap-parse-resp-text))
1909 (when (eq (char-after) ?\[)
1910 (setq code (buffer-substring (point)
1911 (search-forward "]")))
1913 (setq text (buffer-substring (point) (point-max)))
1914 (push (list token status code text)
1915 imap-failed-tags))))
1917 (setq imap-reached-tag (max imap-reached-tag token))
1919 (imap-parse-resp-text))
1921 (when (eq (char-after) ?\[)
1922 (setq code (buffer-substring (point)
1923 (search-forward "]")))
1925 (setq text (buffer-substring (point) (point-max)))
1926 (push (list token status code text) imap-failed-tags)
1927 (error "Internal error, tag %s status %s code %s text %s"
1928 token status code text))))
1929 (t (message "Garbage: %s" (buffer-string))))))))))
1931 ;; resp-text = ["[" resp-text-code "]" SP] text
1933 ;; text = 1*TEXT-CHAR
1935 ;; TEXT-CHAR = <any CHAR except CR and LF>
1937 (defun imap-parse-resp-text ()
1938 (imap-parse-resp-text-code))
1940 ;; resp-text-code = "ALERT" /
1941 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
1942 ;; "NEWNAME" SP string SP string /
1944 ;; "PERMANENTFLAGS" SP "("
1945 ;; [flag-perm *(SP flag-perm)] ")" /
1949 ;; "UIDNEXT" SP nz-number /
1950 ;; "UIDVALIDITY" SP nz-number /
1951 ;; "UNSEEN" SP nz-number /
1952 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
1954 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
1956 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
1958 ;; set = sequence-num / (sequence-num ":" sequence-num) /
1960 ;; ; Identifies a set of messages. For message
1961 ;; ; sequence numbers, these are consecutive
1962 ;; ; numbers from 1 to the number of messages in
1964 ;; ; Comma delimits individual numbers, colon
1965 ;; ; delimits between two numbers inclusive.
1966 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
1967 ;; ; 14,15 for a mailbox with 15 messages.
1969 ;; sequence-num = nz-number / "*"
1970 ;; ; * is the largest number in use. For message
1971 ;; ; sequence numbers, it is the number of messages
1972 ;; ; in the mailbox. For unique identifiers, it is
1973 ;; ; the unique identifier of the last message in
1976 ;; flag-perm = flag / "\*"
1978 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
1979 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
1980 ;; ; Does not include "\Recent"
1982 ;; flag-extension = "\" atom
1983 ;; ; Future expansion. Client implementations
1984 ;; ; MUST accept flag-extension flags. Server
1985 ;; ; implementations MUST NOT generate
1986 ;; ; flag-extension flags except as defined by
1987 ;; ; future standard or standards-track
1988 ;; ; revisions of this specification.
1990 ;; flag-keyword = atom
1992 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
1994 (defun imap-parse-resp-text-code ()
1995 ;; xxx next line for stalker communigate pro 3.3.1 bug
1996 (when (looking-at " \\[")
1998 (when (eq (char-after) ?\[)
2000 (cond ((search-forward "PERMANENTFLAGS " nil t)
2001 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2002 ((search-forward "UIDNEXT " nil t)
2003 (imap-mailbox-put 'uidnext (read (current-buffer))))
2004 ((search-forward "UNSEEN " nil t)
2005 (imap-mailbox-put 'unseen (read (current-buffer))))
2006 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2007 (imap-mailbox-put 'uidvalidity (match-string 1)))
2008 ((search-forward "READ-ONLY" nil t)
2009 (imap-mailbox-put 'read-only t))
2010 ((search-forward "NEWNAME " nil t)
2011 (let (oldname newname)
2012 (setq oldname (imap-parse-string))
2014 (setq newname (imap-parse-string))
2015 (imap-mailbox-put 'newname newname oldname)))
2016 ((search-forward "TRYCREATE" nil t)
2017 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2018 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2019 (imap-mailbox-put 'appenduid
2020 (list (match-string 1)
2021 (string-to-number (match-string 2)))
2022 imap-current-target-mailbox))
2023 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2024 (imap-mailbox-put 'copyuid (list (match-string 1)
2027 imap-current-target-mailbox))
2028 ((search-forward "ALERT] " nil t)
2029 (message "Imap server %s information: %s" imap-server
2030 (buffer-substring (point) (point-max)))))))
2032 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2033 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2035 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2036 ;; *(SP mbx-list-oflag) /
2037 ;; mbx-list-oflag *(SP mbx-list-oflag)
2039 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2040 ;; ; Other flags; multiple possible per LIST response
2042 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2043 ;; ; Selectability flags; only one per LIST response
2045 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2046 ;; "\" quoted-specials
2048 ;; quoted-specials = DQUOTE / "\"
2050 (defun imap-parse-data-list (type)
2051 (let (flags delimiter mailbox)
2052 (setq flags (imap-parse-flag-list))
2053 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2054 (setq delimiter (match-string 1))
2055 (goto-char (1+ (match-end 0)))
2056 (when (setq mailbox (imap-parse-mailbox))
2057 (imap-mailbox-put type t mailbox)
2058 (imap-mailbox-put 'list-flags flags mailbox)
2059 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2061 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2062 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2063 ;; "INTERNALDATE" SPACE date_time /
2064 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2065 ;; "RFC822.SIZE" SPACE number /
2066 ;; "BODY" ["STRUCTURE"] SPACE body /
2067 ;; "BODY" section ["<" number ">"] SPACE nstring /
2068 ;; "UID" SPACE uniqueid) ")"
2070 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2071 ;; SPACE time SPACE zone <">
2073 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2074 ;; ["." (section_text / "MIME")])] "]"
2076 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2077 ;; SPACE header_list / "TEXT"
2079 ;; header_fld_name ::= astring
2081 ;; header_list ::= "(" 1#header_fld_name ")"
2083 (defsubst imap-parse-header-list ()
2084 (when (eq (char-after) ?\()
2086 (while (not (eq (char-after) ?\)))
2088 (push (imap-parse-astring) strlist))
2090 (nreverse strlist))))
2092 (defsubst imap-parse-fetch-body-section ()
2094 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2095 (if (eq (char-before) ? )
2097 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2098 (search-forward "]" nil t))
2101 (defun imap-parse-fetch (response)
2102 (when (eq (char-after) ?\()
2103 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2104 rfc822size body bodydetail bodystructure)
2105 (while (not (eq (char-after) ?\)))
2107 (let ((token (read (current-buffer))))
2109 (cond ((eq token 'UID)
2110 (setq uid (ignore-errors (read (current-buffer)))))
2112 (setq flags (imap-parse-flag-list)))
2113 ((eq token 'ENVELOPE)
2114 (setq envelope (imap-parse-envelope)))
2115 ((eq token 'INTERNALDATE)
2116 (setq internaldate (imap-parse-string)))
2118 (setq rfc822 (imap-parse-nstring)))
2119 ((eq token 'RFC822.HEADER)
2120 (setq rfc822header (imap-parse-nstring)))
2121 ((eq token 'RFC822.TEXT)
2122 (setq rfc822text (imap-parse-nstring)))
2123 ((eq token 'RFC822.SIZE)
2124 (setq rfc822size (read (current-buffer))))
2126 (if (eq (char-before) ?\[)
2128 (upcase (imap-parse-fetch-body-section))
2129 (and (eq (char-after) ?<)
2130 (buffer-substring (1+ (point))
2131 (search-forward ">" nil t)))
2132 (progn (imap-forward)
2133 (imap-parse-nstring)))
2135 (setq body (imap-parse-body))))
2136 ((eq token 'BODYSTRUCTURE)
2137 (setq bodystructure (imap-parse-body))))))
2139 (setq imap-current-message uid)
2140 (imap-message-put uid 'UID uid)
2141 (and flags (imap-message-put uid 'FLAGS flags))
2142 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2143 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2144 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2145 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2146 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2147 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2148 (and body (imap-message-put uid 'BODY body))
2149 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2150 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2151 (run-hooks 'imap-fetch-data-hook)))))
2153 ;; mailbox-data = ...
2154 ;; "STATUS" SP mailbox SP "("
2155 ;; [status-att SP number
2156 ;; *(SP status-att SP number)] ")"
2159 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2162 (defun imap-parse-status ()
2163 (let ((mailbox (imap-parse-mailbox)))
2164 (when (and mailbox (search-forward "(" nil t))
2165 (while (not (eq (char-after) ?\)))
2166 (let ((token (read (current-buffer))))
2167 (cond ((eq token 'MESSAGES)
2168 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2170 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2171 ((eq token 'UIDNEXT)
2172 (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2173 ((eq token 'UIDVALIDITY)
2174 (and (looking-at " \\([0-9]+\\)")
2175 (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2176 (goto-char (match-end 1))))
2178 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2180 (message "Unknown status data %s in mailbox %s ignored"
2181 token mailbox))))))))
2183 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2186 ;; identifier ::= astring
2188 ;; rights ::= astring
2190 (defun imap-parse-acl ()
2191 (let ((mailbox (imap-parse-mailbox))
2192 identifier rights acl)
2193 (while (eq (char-after) ?\ )
2195 (setq identifier (imap-parse-astring))
2197 (setq rights (imap-parse-astring))
2198 (setq acl (append acl (list (cons identifier rights)))))
2199 (imap-mailbox-put 'acl acl mailbox)))
2201 ;; flag-list = "(" [flag *(SP flag)] ")"
2203 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2204 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2205 ;; ; Does not include "\Recent"
2207 ;; flag-keyword = atom
2209 ;; flag-extension = "\" atom
2210 ;; ; Future expansion. Client implementations
2211 ;; ; MUST accept flag-extension flags. Server
2212 ;; ; implementations MUST NOT generate
2213 ;; ; flag-extension flags except as defined by
2214 ;; ; future standard or standards-track
2215 ;; ; revisions of this specification.
2217 (defun imap-parse-flag-list ()
2218 (let (flag-list start)
2219 (assert (eq (char-after) ?\())
2220 (while (and (not (eq (char-after) ?\)))
2221 (setq start (progn (imap-forward) (point)))
2222 (> (skip-chars-forward "^ )" (gnus-point-at-eol)) 0))
2223 (push (buffer-substring start (point)) flag-list))
2224 (assert (eq (char-after) ?\)))
2226 (nreverse flag-list)))
2228 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2229 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2230 ;; env-in-reply-to SP env-message-id ")"
2232 ;; env-bcc = "(" 1*address ")" / nil
2234 ;; env-cc = "(" 1*address ")" / nil
2236 ;; env-date = nstring
2238 ;; env-from = "(" 1*address ")" / nil
2240 ;; env-in-reply-to = nstring
2242 ;; env-message-id = nstring
2244 ;; env-reply-to = "(" 1*address ")" / nil
2246 ;; env-sender = "(" 1*address ")" / nil
2248 ;; env-subject = nstring
2250 ;; env-to = "(" 1*address ")" / nil
2252 (defun imap-parse-envelope ()
2253 (when (eq (char-after) ?\()
2255 (vector (prog1 (imap-parse-nstring);; date
2257 (prog1 (imap-parse-nstring);; subject
2259 (prog1 (imap-parse-address-list);; from
2261 (prog1 (imap-parse-address-list);; sender
2263 (prog1 (imap-parse-address-list);; reply-to
2265 (prog1 (imap-parse-address-list);; to
2267 (prog1 (imap-parse-address-list);; cc
2269 (prog1 (imap-parse-address-list);; bcc
2271 (prog1 (imap-parse-nstring);; in-reply-to
2273 (prog1 (imap-parse-nstring);; message-id
2276 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2278 (defsubst imap-parse-string-list ()
2279 (cond ((eq (char-after) ?\();; body-fld-param
2282 (while (setq str (imap-parse-string))
2284 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2285 ;; between body-fld-param's sometimes
2286 (or (eq (char-after) ?\")
2288 (nreverse strlist)))
2292 ;; body-extension = nstring / number /
2293 ;; "(" body-extension *(SP body-extension) ")"
2294 ;; ; Future expansion. Client implementations
2295 ;; ; MUST accept body-extension fields. Server
2296 ;; ; implementations MUST NOT generate
2297 ;; ; body-extension fields except as defined by
2298 ;; ; future standard or standards-track
2299 ;; ; revisions of this specification.
2301 (defun imap-parse-body-extension ()
2302 (if (eq (char-after) ?\()
2305 (push (imap-parse-body-extension) b-e)
2306 (while (eq (char-after) ?\ )
2308 (push (imap-parse-body-extension) b-e))
2309 (assert (eq (char-after) ?\)))
2312 (or (imap-parse-number)
2313 (imap-parse-nstring))))
2315 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2316 ;; *(SP body-extension)]]
2317 ;; ; MUST NOT be returned on non-extensible
2320 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2321 ;; *(SP body-extension)]]
2322 ;; ; MUST NOT be returned on non-extensible
2325 (defsubst imap-parse-body-ext ()
2327 (when (eq (char-after) ?\ );; body-fld-dsp
2330 (if (eq (char-after) ?\()
2333 (push (imap-parse-string) dsp)
2335 (push (imap-parse-string-list) dsp)
2337 (assert (imap-parse-nil)))
2338 (push (nreverse dsp) ext))
2339 (when (eq (char-after) ?\ );; body-fld-lang
2341 (if (eq (char-after) ?\()
2342 (push (imap-parse-string-list) ext)
2343 (push (imap-parse-nstring) ext))
2344 (while (eq (char-after) ?\ );; body-extension
2346 (setq ext (append (imap-parse-body-extension) ext)))))
2349 ;; body = "(" body-type-1part / body-type-mpart ")"
2351 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2352 ;; *(SP body-extension)]]
2353 ;; ; MUST NOT be returned on non-extensible
2356 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2357 ;; *(SP body-extension)]]
2358 ;; ; MUST NOT be returned on non-extensible
2361 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2362 ;; body-fld-enc SP body-fld-octets
2364 ;; body-fld-desc = nstring
2366 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2368 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2369 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2371 ;; body-fld-id = nstring
2373 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2375 ;; body-fld-lines = number
2377 ;; body-fld-md5 = nstring
2379 ;; body-fld-octets = number
2381 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2383 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2384 ;; [SP body-ext-1part]
2386 ;; body-type-basic = media-basic SP body-fields
2387 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2389 ;; body-type-msg = media-message SP body-fields SP envelope
2390 ;; SP body SP body-fld-lines
2392 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2394 ;; body-type-mpart = 1*body SP media-subtype
2395 ;; [SP body-ext-mpart]
2397 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2398 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2399 ;; ; Defined in [MIME-IMT]
2401 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2402 ;; ; Defined in [MIME-IMT]
2404 ;; media-subtype = string
2405 ;; ; Defined in [MIME-IMT]
2407 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2408 ;; ; Defined in [MIME-IMT]
2410 (defun imap-parse-body ()
2412 (when (eq (char-after) ?\()
2414 (if (eq (char-after) ?\()
2416 (while (and (eq (char-after) ?\()
2417 (setq subbody (imap-parse-body)))
2418 ;; buggy stalker communigate pro 3.0 insert a SPC between
2419 ;; parts in multiparts
2420 (when (and (eq (char-after) ?\ )
2421 (eq (char-after (1+ (point))) ?\())
2423 (push subbody body))
2425 (push (imap-parse-string) body);; media-subtype
2426 (when (eq (char-after) ?\ );; body-ext-mpart:
2428 (if (eq (char-after) ?\();; body-fld-param
2429 (push (imap-parse-string-list) body)
2430 (push (and (imap-parse-nil) nil) body))
2432 (append (imap-parse-body-ext) body)));; body-ext-...
2433 (assert (eq (char-after) ?\)))
2437 (push (imap-parse-string) body);; media-type
2439 (push (imap-parse-string) body);; media-subtype
2441 ;; next line for Sun SIMS bug
2442 (and (eq (char-after) ? ) (imap-forward))
2443 (if (eq (char-after) ?\();; body-fld-param
2444 (push (imap-parse-string-list) body)
2445 (push (and (imap-parse-nil) nil) body))
2447 (push (imap-parse-nstring) body);; body-fld-id
2449 (push (imap-parse-nstring) body);; body-fld-desc
2451 ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2452 ;; nstring and return NIL instead of defaulting back to 7BIT
2453 ;; as the standard says.
2454 (push (or (imap-parse-nstring) "7BIT") body);; body-fld-enc
2456 (push (imap-parse-number) body);; body-fld-octets
2458 ;; ok, we're done parsing the required parts, what comes now is one
2461 ;; envelope (then we're parsing body-type-msg)
2462 ;; body-fld-lines (then we're parsing body-type-text)
2463 ;; body-ext-1part (then we're parsing body-type-basic)
2465 ;; the problem is that the two first are in turn optionally followed
2466 ;; by the third. So we parse the first two here (if there are any)...
2468 (when (eq (char-after) ?\ )
2471 (cond ((eq (char-after) ?\();; body-type-msg:
2472 (push (imap-parse-envelope) body);; envelope
2474 (push (imap-parse-body) body);; body
2475 ;; buggy stalker communigate pro 3.0 doesn't print
2476 ;; number of lines in message/rfc822 attachment
2477 (if (eq (char-after) ?\))
2480 (push (imap-parse-number) body))) ;; body-fld-lines
2481 ((setq lines (imap-parse-number)) ;; body-type-text:
2482 (push lines body)) ;; body-fld-lines
2484 (backward-char))))) ;; no match...
2486 ;; ...and then parse the third one here...
2488 (when (eq (char-after) ?\ );; body-ext-1part:
2490 (push (imap-parse-nstring) body);; body-fld-md5
2491 (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2493 (assert (eq (char-after) ?\)))
2497 (when imap-debug ; (untrace-all)
2499 (buffer-disable-undo (get-buffer-create imap-debug))
2500 (mapcar (lambda (f) (trace-function-background f imap-debug))
2512 imap-interactive-login
2528 imap-send-command-wait
2533 imap-current-mailbox
2534 imap-current-mailbox-p-1
2535 imap-current-mailbox-p
2536 imap-mailbox-select-1
2538 imap-mailbox-examine-1
2539 imap-mailbox-examine
2540 imap-mailbox-unselect
2541 imap-mailbox-expunge
2543 imap-mailbox-create-1
2549 imap-mailbox-subscribe
2550 imap-mailbox-unsubscribe
2552 imap-mailbox-acl-get
2553 imap-mailbox-acl-set
2554 imap-mailbox-acl-delete
2555 imap-current-message
2556 imap-list-to-message-set
2563 imap-message-flag-permanent-p
2564 imap-message-flags-set
2565 imap-message-flags-del
2566 imap-message-flags-add
2567 imap-message-copyuid-1
2568 imap-message-copyuid
2570 imap-message-appenduid-1
2571 imap-message-appenduid
2583 imap-parse-resp-text
2584 imap-parse-resp-text-code
2585 imap-parse-data-list
2589 imap-parse-flag-list
2591 imap-parse-body-extension
2597 ;;; imap.el ends here