Document reserved keys
[emacs.git] / lisp / net / imap.el
blob3d2a4f948bc58988e38aa65d8c677c9f9d2ab046
1 ;;; imap.el --- imap library
3 ;; Copyright (C) 1998-2018 Free Software Foundation, Inc.
5 ;; Author: Simon Josefsson <simon@josefsson.org>
6 ;; Keywords: mail
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; imap.el is an elisp library providing an interface for talking to
26 ;; IMAP servers.
28 ;; imap.el is roughly divided in two parts, one that parses IMAP
29 ;; responses from the server and storing data into buffer-local
30 ;; variables, and one for utility functions which send commands to
31 ;; server, waits for an answer, and return information. The latter
32 ;; part is layered on top of the previous.
34 ;; The imap.el API consist of the following functions, other functions
35 ;; in this file should not be called directly and the result of doing
36 ;; so are at best undefined.
38 ;; Global commands:
40 ;; imap-open, imap-opened, imap-authenticate, imap-close,
41 ;; imap-capability, imap-namespace, imap-error-text
43 ;; Mailbox commands:
45 ;; imap-mailbox-get, imap-mailbox-map, imap-current-mailbox,
46 ;; imap-current-mailbox-p, imap-search, imap-mailbox-select,
47 ;; imap-mailbox-examine, imap-mailbox-unselect, imap-mailbox-expunge
48 ;; imap-mailbox-close, imap-mailbox-create, imap-mailbox-delete
49 ;; imap-mailbox-rename, imap-mailbox-lsub, imap-mailbox-list
50 ;; imap-mailbox-subscribe, imap-mailbox-unsubscribe, imap-mailbox-status
51 ;; imap-mailbox-acl-get, imap-mailbox-acl-set, imap-mailbox-acl-delete
53 ;; Message commands:
55 ;; imap-fetch-asynch, imap-fetch,
56 ;; imap-current-message, imap-list-to-message-set,
57 ;; imap-message-get, imap-message-map
58 ;; imap-message-envelope-date, imap-message-envelope-subject,
59 ;; imap-message-envelope-from, imap-message-envelope-sender,
60 ;; imap-message-envelope-reply-to, imap-message-envelope-to,
61 ;; imap-message-envelope-cc, imap-message-envelope-bcc
62 ;; imap-message-envelope-in-reply-to, imap-message-envelope-message-id
63 ;; imap-message-body, imap-message-flag-permanent-p
64 ;; imap-message-flags-set, imap-message-flags-del
65 ;; imap-message-flags-add, imap-message-copyuid
66 ;; imap-message-copy, imap-message-appenduid
67 ;; imap-message-append, imap-envelope-from
68 ;; imap-body-lines
70 ;; It is my hope that these commands should be pretty self
71 ;; explanatory for someone who knows IMAP. All functions have
72 ;; additional documentation on how to invoke them.
74 ;; imap.el supports RFC1730/2060/RFC3501 (IMAP4/IMAP4rev1). The implemented
75 ;; IMAP extensions are RFC2195 (CRAM-MD5), RFC2086 (ACL), RFC2342
76 ;; (NAMESPACE), RFC2359 (UIDPLUS), the IMAP-part of RFC2595 (STARTTLS,
77 ;; LOGINDISABLED), and the GSSAPI / Kerberos V4 sections of RFC1731
78 ;; (with use of external program `imtest'), and RFC2971 (ID). It also
79 ;; takes advantage of the UNSELECT extension in Cyrus IMAPD.
81 ;; Without the work of John McClary Prevost and Jim Radford this library
82 ;; would not have seen the light of day. Many thanks.
84 ;; This is a transcript of a short interactive session for demonstration
85 ;; purposes.
87 ;; (imap-open "my.mail.server")
88 ;; => " *imap* my.mail.server:0"
90 ;; The rest are invoked with current buffer as the buffer returned by
91 ;; `imap-open'. It is possible to do it all without this, but it would
92 ;; look ugly here since `buffer' is always the last argument for all
93 ;; imap.el API functions.
95 ;; (imap-authenticate "myusername" "mypassword")
96 ;; => auth
98 ;; (imap-mailbox-lsub "*")
99 ;; => ("INBOX.sentmail" "INBOX.private" "INBOX.draft" "INBOX.spam")
101 ;; (imap-mailbox-list "INBOX.n%")
102 ;; => ("INBOX.namedroppers" "INBOX.nnimap" "INBOX.ntbugtraq")
104 ;; (imap-mailbox-select "INBOX.nnimap")
105 ;; => "INBOX.nnimap"
107 ;; (imap-mailbox-get 'exists)
108 ;; => 166
110 ;; (imap-mailbox-get 'uidvalidity)
111 ;; => "908992622"
113 ;; (imap-search "FLAGGED SINCE 18-DEC-98")
114 ;; => (235 236)
116 ;; (imap-fetch 235 "RFC822.PEEK" 'RFC822)
117 ;; => "X-Sieve: cmu-sieve 1.3^M\nX-Username: <jas@pdc.kth.se>^M\r...."
119 ;; Todo:
121 ;; o Parse UIDs as strings? We need to overcome the 28 bit limit somehow.
122 ;; Use IEEE floats (which are effectively exact)? -- fx
123 ;; o Don't use `read' at all (important places already fixed)
124 ;; o Accept list of articles instead of message set string in most
125 ;; imap-message-* functions.
126 ;; o Send strings as literal if they contain, e.g., ".
128 ;; Revision history:
130 ;; - 19991218 added starttls/digest-md5 patch,
131 ;; by Daiki Ueno <ueno@ueda.info.waseda.ac.jp>
132 ;; NB! you need SLIM for starttls.el and digest-md5.el
133 ;; - 19991023 committed to pgnus
136 ;;; Code:
138 (eval-when-compile (require 'cl))
139 (eval-and-compile
140 ;; For Emacs <22.2 and XEmacs.
141 (unless (fboundp 'declare-function) (defmacro declare-function (&rest _r)))
142 (autoload 'sasl-find-mechanism "sasl")
143 (autoload 'digest-md5-parse-digest-challenge "digest-md5")
144 (autoload 'digest-md5-digest-response "digest-md5")
145 (autoload 'digest-md5-digest-uri "digest-md5")
146 (autoload 'digest-md5-challenge "digest-md5")
147 (autoload 'rfc2104-hash "rfc2104")
148 (autoload 'utf7-encode "utf7")
149 (autoload 'utf7-decode "utf7")
150 (autoload 'format-spec "format-spec")
151 (autoload 'format-spec-make "format-spec"))
153 ;; User variables.
155 (defgroup imap nil
156 "Low-level IMAP issues."
157 :version "21.1"
158 :group 'mail)
160 (defcustom imap-kerberos4-program '("imtest -m kerberos_v4 -u %l -p %p %s"
161 "imtest -kp %s %p")
162 "List of strings containing commands for Kerberos 4 authentication.
163 %s is replaced with server hostname, %p with port to connect to, and
164 %l with the value of `imap-default-user'. The program should accept
165 IMAP commands on stdin and return responses to stdout. Each entry in
166 the list is tried until a successful connection is made."
167 :group 'imap
168 :type '(repeat string))
170 (defcustom imap-gssapi-program (list
171 (concat "gsasl %s %p "
172 "--mechanism GSSAPI "
173 "--authentication-id %l")
174 "imtest -m gssapi -u %l -p %p %s")
175 "List of strings containing commands for GSSAPI (krb5) authentication.
176 %s is replaced with server hostname, %p with port to connect to, and
177 %l with the value of `imap-default-user'. The program should accept
178 IMAP commands on stdin and return responses to stdout. Each entry in
179 the list is tried until a successful connection is made."
180 :group 'imap
181 :type '(repeat string))
183 (defcustom imap-shell-program '("ssh %s imapd"
184 "rsh %s imapd"
185 "ssh %g ssh %s imapd"
186 "rsh %g rsh %s imapd")
187 "A list of strings, containing commands for IMAP connection.
188 Within a string, %s is replaced with the server address, %p with port
189 number on server, %g with `imap-shell-host', and %l with
190 `imap-default-user'. The program should read IMAP commands from stdin
191 and write IMAP response to stdout. Each entry in the list is tried
192 until a successful connection is made."
193 :group 'imap
194 :type '(repeat string))
196 (defcustom imap-process-connection-type nil
197 "Value for `process-connection-type' to use for Kerberos4, GSSAPI, shell, and SSL.
198 The `process-connection-type' variable controls the type of device
199 used to communicate with subprocesses. Values are nil to use a
200 pipe, or t or `pty' to use a pty. The value has no effect if the
201 system has no ptys or if all ptys are busy: then a pipe is used
202 in any case. The value takes effect when an IMAP server is
203 opened; changing it after that has no effect."
204 :version "22.1"
205 :group 'imap
206 :type 'boolean)
208 (defcustom imap-use-utf7 t
209 "If non-nil, do utf7 encoding/decoding of mailbox names.
210 Since the UTF7 decoding currently only decodes into ISO-8859-1
211 characters, you may disable this decoding if you need to access UTF7
212 encoded mailboxes which doesn't translate into ISO-8859-1."
213 :group 'imap
214 :type 'boolean)
216 (defcustom imap-log nil
217 "If non-nil, an imap session trace is placed in `imap-log-buffer'.
218 Note that username, passwords and other privacy sensitive
219 information (such as e-mail) may be stored in the buffer.
220 It is not written to disk, however. Do not enable this
221 variable unless you are comfortable with that.
223 See also `imap-debug'."
224 :group 'imap
225 :type 'boolean)
227 (defcustom imap-debug nil
228 "If non-nil, trace imap- functions into `imap-debug-buffer'.
229 Uses `trace-function-background', so you can turn it off with,
230 say, `untrace-all'.
232 Note that username, passwords and other privacy sensitive
233 information (such as e-mail) may be stored in the buffer.
234 It is not written to disk, however. Do not enable this
235 variable unless you are comfortable with that.
237 This variable only takes effect when loading the `imap' library.
238 See also `imap-log'."
239 :group 'imap
240 :type 'boolean)
242 (defcustom imap-shell-host "gateway"
243 "Hostname of rlogin proxy."
244 :group 'imap
245 :type 'string)
247 (defcustom imap-default-user (user-login-name)
248 "Default username to use."
249 :group 'imap
250 :type 'string)
252 (defcustom imap-read-timeout (if (memq system-type '(windows-nt cygwin))
254 0.1)
255 "How long to wait between checking for the end of output.
256 Shorter values mean quicker response, but is more CPU intensive."
257 :type 'number
258 :group 'imap)
260 (defcustom imap-store-password nil
261 "If non-nil, store session password without prompting."
262 :group 'imap
263 :type 'boolean)
265 ;; Various variables.
267 (defvar imap-fetch-data-hook nil
268 "Hooks called after receiving each FETCH response.")
270 (defvar imap-streams '(gssapi kerberos4 starttls tls ssl network shell)
271 "Priority of streams to consider when opening connection to server.")
273 (defvar imap-stream-alist
274 '((gssapi imap-gssapi-stream-p imap-gssapi-open)
275 (kerberos4 imap-kerberos4-stream-p imap-kerberos4-open)
276 (tls imap-tls-p imap-tls-open)
277 (ssl imap-tls-p imap-tls-open)
278 (network imap-network-p imap-network-open)
279 (shell imap-shell-p imap-shell-open)
280 (starttls imap-starttls-p imap-starttls-open))
281 "Definition of network streams.
283 \(NAME CHECK OPEN)
285 NAME names the stream, CHECK is a function returning non-nil if the
286 server support the stream and OPEN is a function for opening the
287 stream.")
289 (defvar imap-authenticators '(gssapi
290 kerberos4
291 digest-md5
292 cram-md5
293 ;;sasl
294 login
295 anonymous)
296 "Priority of authenticators to consider when authenticating to server.")
298 (defvar imap-authenticator-alist
299 '((gssapi imap-gssapi-auth-p imap-gssapi-auth)
300 (kerberos4 imap-kerberos4-auth-p imap-kerberos4-auth)
301 (sasl imap-sasl-auth-p imap-sasl-auth)
302 (cram-md5 imap-cram-md5-p imap-cram-md5-auth)
303 (login imap-login-p imap-login-auth)
304 (anonymous imap-anonymous-p imap-anonymous-auth)
305 (digest-md5 imap-digest-md5-p imap-digest-md5-auth))
306 "Definition of authenticators.
308 \(NAME CHECK AUTHENTICATE)
310 NAME names the authenticator. CHECK is a function returning non-nil if
311 the server support the authenticator and AUTHENTICATE is a function
312 for doing the actual authentication.")
314 (defvar imap-error nil
315 "Error codes from the last command.")
317 (defvar imap-logout-timeout nil
318 "Close server immediately if it can't logout in this number of seconds.
319 If it is nil, never close server until logout completes. Normally,
320 the value of this variable will be bound to a certain value to which
321 an application program that uses this module specifies on a per-server
322 basis.")
324 ;; Internal constants. Change these and die.
326 (defconst imap-default-port 143)
327 (defconst imap-default-ssl-port 993)
328 (defconst imap-default-tls-port 993)
329 (defconst imap-default-stream 'network)
330 (defconst imap-coding-system-for-read 'binary)
331 (defconst imap-coding-system-for-write 'binary)
332 (defconst imap-local-variables '(imap-server
333 imap-port
334 imap-client-eol
335 imap-server-eol
336 imap-auth
337 imap-stream
338 imap-username
339 imap-password
340 imap-current-mailbox
341 imap-current-target-mailbox
342 imap-message-data
343 imap-capability
344 imap-id
345 imap-namespace
346 imap-state
347 imap-reached-tag
348 imap-failed-tags
349 imap-tag
350 imap-process
351 imap-calculate-literal-size-first
352 imap-mailbox-data))
353 (defconst imap-log-buffer "*imap-log*")
354 (defconst imap-debug-buffer "*imap-debug*")
356 ;; Internal variables.
358 (defvar imap-stream nil)
359 (defvar imap-auth nil)
360 (defvar imap-server nil)
361 (defvar imap-port nil)
362 (defvar imap-username nil)
363 (defvar imap-password nil)
364 (defvar imap-last-authenticator nil)
365 (defvar imap-calculate-literal-size-first nil)
366 (defvar imap-state 'closed
367 "IMAP state.
368 Valid states are `closed', `initial', `nonauth', `auth', `selected'
369 and `examine'.")
371 (defvar imap-server-eol "\r\n"
372 "The EOL string sent from the server.")
374 (defvar imap-client-eol "\r\n"
375 "The EOL string we send to the server.")
377 (defvar imap-current-mailbox nil
378 "Current mailbox name.")
380 (defvar imap-current-target-mailbox nil
381 "Current target mailbox for COPY and APPEND commands.")
383 (defvar imap-mailbox-data nil
384 "Obarray with mailbox data.")
386 (defvar imap-mailbox-prime 997
387 "Length of `imap-mailbox-data'.")
389 (defvar imap-current-message nil
390 "Current message number.")
392 (defvar imap-message-data nil
393 "Obarray with message data.")
395 (defvar imap-message-prime 997
396 "Length of `imap-message-data'.")
398 (defvar imap-capability nil
399 "Capability for server.")
401 (defvar imap-id nil
402 "Identity of server.
403 See RFC 2971.")
405 (defvar imap-namespace nil
406 "Namespace for current server.")
408 (defvar imap-reached-tag 0
409 "Lower limit on command tags that have been parsed.")
411 (defvar imap-failed-tags nil
412 "Alist of tags that failed.
413 Each element is a list with four elements; tag (a integer), response
414 state (a symbol, `OK', `NO' or `BAD'), response code (a string), and
415 human readable response text (a string).")
417 (defvar imap-tag 0
418 "Command tag number.")
420 (defvar imap-process nil
421 "Process.")
423 (defvar imap-continuation nil
424 "Non-nil indicates that the server emitted a continuation request.
425 The actual value is really the text on the continuation line.")
427 (defvar imap-callbacks nil
428 "List of response tags and callbacks, on the form `(number . function)'.
429 The function should take two arguments, the first the IMAP tag and the
430 second the status (OK, NO, BAD etc) of the command.")
432 (defvar imap-enable-exchange-bug-workaround nil
433 "Send FETCH UID commands as *:* instead of *.
435 When non-nil, use an alternative UIDS form. Enabling appears to
436 be required for some servers (e.g., Microsoft Exchange 2007)
437 which otherwise would trigger a response `BAD The specified
438 message set is invalid.'. We don't unconditionally use this
439 form, since this is said to be significantly inefficient.
441 This variable is set to t automatically per server if the
442 canonical form fails.")
445 ;; Utility functions:
447 (defun imap-remassoc (key alist)
448 "Delete by side effect any elements of ALIST whose car is `equal' to KEY.
449 The modified ALIST is returned. If the first member
450 of ALIST has a car that is `equal' to KEY, there is no way to remove it
451 by side effect; therefore, write `(setq foo (remassoc key foo))' to be
452 sure of changing the value of `foo'."
453 (when alist
454 (if (equal key (caar alist))
455 (cdr alist)
456 (setcdr alist (imap-remassoc key (cdr alist)))
457 alist)))
459 (defmacro imap-disable-multibyte ()
460 "Enable multibyte in the current buffer."
461 (unless (featurep 'xemacs)
462 '(set-buffer-multibyte nil)))
464 (defsubst imap-utf7-encode (string)
465 (if imap-use-utf7
466 (and string
467 (condition-case ()
468 (utf7-encode string t)
469 (error (message
470 "imap: Could not UTF7 encode `%s', using it unencoded..."
471 string)
472 string)))
473 string))
475 (defsubst imap-utf7-decode (string)
476 (if imap-use-utf7
477 (and string
478 (condition-case ()
479 (utf7-decode string t)
480 (error (message
481 "imap: Could not UTF7 decode `%s', using it undecoded..."
482 string)
483 string)))
484 string))
486 (defsubst imap-ok-p (status)
487 (if (eq status 'OK)
489 (setq imap-error status)
490 nil))
492 (defun imap-error-text (&optional buffer)
493 (with-current-buffer (or buffer (current-buffer))
494 (nth 3 (car imap-failed-tags))))
497 ;; Server functions; stream stuff:
499 (defun imap-log (string-or-buffer)
500 (when imap-log
501 (with-current-buffer (get-buffer-create imap-log-buffer)
502 (imap-disable-multibyte)
503 (buffer-disable-undo)
504 (goto-char (point-max))
505 (if (bufferp string-or-buffer)
506 (insert-buffer-substring string-or-buffer)
507 (insert string-or-buffer)))))
509 (defun imap-kerberos4-stream-p (buffer)
510 (imap-capability 'AUTH=KERBEROS_V4 buffer))
512 (defun imap-kerberos4-open (name buffer server port)
513 (let ((cmds imap-kerberos4-program)
514 cmd done)
515 (while (and (not done) (setq cmd (pop cmds)))
516 (message "Opening Kerberos 4 IMAP connection with `%s'..." cmd)
517 (erase-buffer)
518 (let* ((port (or port imap-default-port))
519 (coding-system-for-read imap-coding-system-for-read)
520 (coding-system-for-write imap-coding-system-for-write)
521 (process-connection-type imap-process-connection-type)
522 (process (start-process
523 name buffer shell-file-name shell-command-switch
524 (format-spec
526 (format-spec-make
527 ?s server
528 ?p (number-to-string port)
529 ?l imap-default-user))))
530 response)
531 (when process
532 (with-current-buffer buffer
533 (setq imap-client-eol "\n"
534 imap-calculate-literal-size-first t)
535 (while (and (memq (process-status process) '(open run))
536 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
537 (goto-char (point-min))
538 ;; Athena IMTEST can output SSL verify errors
539 (or (while (looking-at "^verify error:num=")
540 (forward-line))
542 (or (while (looking-at "^TLS connection established")
543 (forward-line))
545 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
546 (or (while (looking-at "^C:")
547 (forward-line))
549 ;; cyrus 1.6 imtest print "S: " before server greeting
550 (or (not (looking-at "S: "))
551 (forward-char 3)
553 (not (and (imap-parse-greeting)
554 ;; success in imtest < 1.6:
555 (or (re-search-forward
556 "^__\\(.*\\)__\n" nil t)
557 ;; success in imtest 1.6:
558 (re-search-forward
559 "^\\(Authenticat.*\\)" nil t))
560 (setq response (match-string 1)))))
561 (accept-process-output process 1)
562 (sit-for 1))
563 (erase-buffer)
564 (message "Opening Kerberos 4 IMAP connection with `%s'...%s" cmd
565 (if response (concat "done, " response) "failed"))
566 (if (and response (let ((case-fold-search nil))
567 (not (string-match "failed" response))))
568 (setq done process)
569 (if (memq (process-status process) '(open run))
570 (imap-logout))
571 (delete-process process)
572 nil)))))
573 done))
575 (defun imap-gssapi-stream-p (buffer)
576 (imap-capability 'AUTH=GSSAPI buffer))
578 (defun imap-gssapi-open (name buffer server port)
579 (let ((cmds imap-gssapi-program)
580 cmd done)
581 (while (and (not done) (setq cmd (pop cmds)))
582 (message "Opening GSSAPI IMAP connection with `%s'..." cmd)
583 (erase-buffer)
584 (let* ((port (or port imap-default-port))
585 (coding-system-for-read imap-coding-system-for-read)
586 (coding-system-for-write imap-coding-system-for-write)
587 (process-connection-type imap-process-connection-type)
588 (process (start-process
589 name buffer shell-file-name shell-command-switch
590 (format-spec
592 (format-spec-make
593 ?s server
594 ?p (number-to-string port)
595 ?l imap-default-user))))
596 response)
597 (when process
598 (with-current-buffer buffer
599 (setq imap-client-eol "\n"
600 imap-calculate-literal-size-first t)
601 (while (and (memq (process-status process) '(open run))
602 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
603 (goto-char (point-min))
604 ;; Athena IMTEST can output SSL verify errors
605 (or (while (looking-at "^verify error:num=")
606 (forward-line))
608 (or (while (looking-at "^TLS connection established")
609 (forward-line))
611 ;; cyrus 1.6.x (13? < x <= 22) queries capabilities
612 (or (while (looking-at "^C:")
613 (forward-line))
615 ;; cyrus 1.6 imtest print "S: " before server greeting
616 (or (not (looking-at "S: "))
617 (forward-char 3)
619 ;; GNU SASL may print 'Trying ...' first.
620 (or (not (looking-at "Trying "))
621 (forward-line)
623 (not (and (imap-parse-greeting)
624 ;; success in imtest 1.6:
625 (re-search-forward
626 (concat "^\\(\\(Authenticat.*\\)\\|\\("
627 "Client authentication "
628 "finished.*\\)\\)")
629 nil t)
630 (setq response (match-string 1)))))
631 (accept-process-output process 1)
632 (sit-for 1))
633 (imap-log buffer)
634 (erase-buffer)
635 (message "GSSAPI IMAP connection: %s" (or response "failed"))
636 (if (and response (let ((case-fold-search nil))
637 (not (string-match "failed" response))))
638 (setq done process)
639 (if (memq (process-status process) '(open run))
640 (imap-logout))
641 (delete-process process)
642 nil)))))
643 done))
645 (defun imap-tls-p (_buffer)
646 nil)
648 (defun imap-tls-open (name buffer server port)
649 (let* ((port (or port imap-default-tls-port))
650 (coding-system-for-read imap-coding-system-for-read)
651 (coding-system-for-write imap-coding-system-for-write)
652 (process (open-network-stream name buffer server port
653 :type 'tls)))
654 (when process
655 (while (and (memq (process-status process) '(open run))
656 ;; FIXME: Per the "blue moon" comment, the process/buffer
657 ;; handling here, and elsewhere in functions which open
658 ;; streams, looks confused. Obviously we can change buffers
659 ;; if a different process handler kicks in from
660 ;; `accept-process-output' or `sit-for' below, and TRT seems
661 ;; to be to `save-buffer' around those calls. (I wonder why
662 ;; `sit-for' is used with a non-zero wait.) -- fx
663 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
664 (goto-char (point-max))
665 (forward-line -1)
666 (not (imap-parse-greeting)))
667 (accept-process-output process 1)
668 (sit-for 1))
669 (imap-log buffer)
670 (when (memq (process-status process) '(open run))
671 process))))
673 (defun imap-network-p (_buffer)
676 (defun imap-network-open (name buffer server port)
677 (let* ((port (or port imap-default-port))
678 (coding-system-for-read imap-coding-system-for-read)
679 (coding-system-for-write imap-coding-system-for-write)
680 (process (open-network-stream name buffer server port)))
681 (when process
682 (while (and (memq (process-status process) '(open run))
683 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
684 (goto-char (point-min))
685 (not (imap-parse-greeting)))
686 (accept-process-output process 1)
687 (sit-for 1))
688 (imap-log buffer)
689 (when (memq (process-status process) '(open run))
690 process))))
692 (defun imap-shell-p (_buffer)
693 nil)
695 (defun imap-shell-open (name buffer server port)
696 (let ((cmds (if (listp imap-shell-program) imap-shell-program
697 (list imap-shell-program)))
698 cmd done)
699 (while (and (not done) (setq cmd (pop cmds)))
700 (message "imap: Opening IMAP connection with `%s'..." cmd)
701 (setq imap-client-eol "\n")
702 (let* ((port (or port imap-default-port))
703 (coding-system-for-read imap-coding-system-for-read)
704 (coding-system-for-write imap-coding-system-for-write)
705 (process-connection-type imap-process-connection-type)
706 (process (start-process
707 name buffer shell-file-name shell-command-switch
708 (format-spec
710 (format-spec-make
711 ?s server
712 ?g imap-shell-host
713 ?p (number-to-string port)
714 ?l imap-default-user)))))
715 (when process
716 (while (and (memq (process-status process) '(open run))
717 (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
718 (goto-char (point-max))
719 (forward-line -1)
720 (not (imap-parse-greeting)))
721 (accept-process-output process 1)
722 (sit-for 1))
723 (imap-log buffer)
724 (erase-buffer)
725 (when (memq (process-status process) '(open run))
726 (setq done process)))))
727 (if done
728 (progn
729 (message "imap: Opening IMAP connection with `%s'...done" cmd)
730 done)
731 (message "imap: Opening IMAP connection with `%s'...failed" cmd)
732 nil)))
734 (defun imap-starttls-p (buffer)
735 (imap-capability 'STARTTLS buffer))
737 (defun imap-starttls-open (name buffer server port)
738 (message "imap: Connecting with STARTTLS...")
739 (let* ((port (or port imap-default-port))
740 (coding-system-for-read imap-coding-system-for-read)
741 (coding-system-for-write imap-coding-system-for-write)
742 (process (open-network-stream
743 name buffer server port
744 :type 'starttls
745 :capability-command "1 CAPABILITY\r\n"
746 :always-query-capabilities t
747 :end-of-command "\r\n"
748 :success "^1 OK "
749 :starttls-function
750 #'(lambda (capabilities)
751 (when (string-match-p "STARTTLS" capabilities)
752 "1 STARTTLS\r\n"))))
753 done)
754 (when process
755 (imap-log buffer)
756 (when (memq (process-status process) '(open run))
757 (setq done process)
758 (with-current-buffer buffer
759 (goto-char (point-min))
760 (imap-parse-greeting))))
761 (message "imap: Connecting with STARTTLS...%s" (if done "done" "failed"))
762 done))
764 ;; Server functions; authenticator stuff:
766 (defun imap-interactive-login (buffer loginfunc)
767 "Login to server in BUFFER.
768 Return t if login was successful, nil otherwise.
770 LOGINFUNC is passed a username and a password. It should return
771 t if it successfully authenticates, nil otherwise."
772 (with-current-buffer buffer
773 (make-local-variable 'imap-username)
774 (make-local-variable 'imap-password)
775 (let (user passwd ret)
776 ;; (condition-case ()
777 (while (or (not user) (not passwd))
778 (setq user (or imap-username
779 (read-from-minibuffer
780 (format-message
781 "imap: username for %s (using stream `%s'): "
782 imap-server imap-stream)
783 (or user imap-default-user))))
784 (setq passwd
785 (or imap-password
786 (read-passwd
787 (format-message
788 "imap: password for %s@%s (using authenticator `%s'): "
789 user imap-server imap-auth))))
790 (when (and user passwd)
791 (if (funcall loginfunc user passwd)
792 (progn
793 (message "imap: Login successful...")
794 (setq ret t
795 imap-username user)
796 (when (and (not imap-password)
797 (or imap-store-password
798 (y-or-n-p "imap: Store password for this IMAP session? ")))
799 (setq imap-password passwd)))
800 (message "imap: Login failed...")
801 (setq passwd nil)
802 (setq imap-password nil)
803 (sit-for 1))))
804 ;; (quit (with-current-buffer buffer
805 ;; (setq user nil
806 ;; passwd nil)))
807 ;; (error (with-current-buffer buffer
808 ;; (setq user nil
809 ;; passwd nil))))
810 ret)))
812 (defun imap-gssapi-auth-p (_buffer)
813 (eq imap-stream 'gssapi))
815 (defun imap-gssapi-auth (_buffer)
816 (message "imap: Authenticating using GSSAPI...%s"
817 (if (eq imap-stream 'gssapi) "done" "failed"))
818 (eq imap-stream 'gssapi))
820 (defun imap-kerberos4-auth-p (buffer)
821 (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
822 (eq imap-stream 'kerberos4)))
824 (defun imap-kerberos4-auth (_buffer)
825 (message "imap: Authenticating using Kerberos 4...%s"
826 (if (eq imap-stream 'kerberos4) "done" "failed"))
827 (eq imap-stream 'kerberos4))
829 (defun imap-cram-md5-p (buffer)
830 (imap-capability 'AUTH=CRAM-MD5 buffer))
832 (defun imap-cram-md5-auth (buffer)
833 "Login to server using the AUTH CRAM-MD5 method."
834 (message "imap: Authenticating using CRAM-MD5...")
835 (let ((done (imap-interactive-login
836 buffer
837 (lambda (user passwd)
838 (imap-ok-p
839 (imap-send-command-wait
840 (list
841 "AUTHENTICATE CRAM-MD5"
842 (lambda (challenge)
843 (let* ((decoded (base64-decode-string challenge))
844 (hash (rfc2104-hash 'md5 64 16 passwd decoded))
845 (response (concat user " " hash))
846 (encoded (base64-encode-string response)))
847 encoded)))))))))
848 (if done
849 (message "imap: Authenticating using CRAM-MD5...done")
850 (message "imap: Authenticating using CRAM-MD5...failed"))))
852 (defun imap-login-p (buffer)
853 (and (not (imap-capability 'LOGINDISABLED buffer))
854 (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
856 (defun imap-quote-specials (string)
857 (with-temp-buffer
858 (insert string)
859 (goto-char (point-min))
860 (while (re-search-forward "[\\\"]" nil t)
861 (forward-char -1)
862 (insert "\\")
863 (forward-char 1))
864 (buffer-string)))
866 (defun imap-login-auth (buffer)
867 "Login to server using the LOGIN command."
868 (message "imap: Plaintext authentication...")
869 (imap-interactive-login buffer
870 (lambda (user passwd)
871 (imap-ok-p (imap-send-command-wait
872 (concat "LOGIN \""
873 (imap-quote-specials user)
874 "\" \""
875 (imap-quote-specials passwd)
876 "\""))))))
878 (defun imap-anonymous-p (_buffer)
881 (defun imap-anonymous-auth (buffer)
882 (message "imap: Logging in anonymously...")
883 (with-current-buffer buffer
884 (imap-ok-p (imap-send-command-wait
885 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
886 (system-name)) "\"")))))
888 ;;; Compiler directives.
890 (defvar imap-sasl-client)
891 (defvar imap-sasl-step)
893 (defun imap-sasl-make-mechanisms (buffer)
894 (let ((mecs '()))
895 (mapc (lambda (sym)
896 (let ((name (symbol-name sym)))
897 (if (and (> (length name) 5)
898 (string-equal "AUTH=" (substring name 0 5 )))
899 (setq mecs (cons (substring name 5) mecs)))))
900 (imap-capability nil buffer))
901 mecs))
903 (declare-function sasl-find-mechanism "sasl" (mechanism))
904 (declare-function sasl-mechanism-name "sasl" (mechanism))
905 (declare-function sasl-make-client "sasl" (mechanism name service server))
906 (declare-function sasl-next-step "sasl" (client step))
907 (declare-function sasl-step-data "sasl" (step))
908 (declare-function sasl-step-set-data "sasl" (step data))
910 (defun imap-sasl-auth-p (buffer)
911 (and (condition-case ()
912 (require 'sasl)
913 (error nil))
914 (sasl-find-mechanism (imap-sasl-make-mechanisms buffer))))
916 (defun imap-sasl-auth (buffer)
917 "Login to server using the SASL method."
918 (message "imap: Authenticating using SASL...")
919 (with-current-buffer buffer
920 (make-local-variable 'imap-username)
921 (make-local-variable 'imap-sasl-client)
922 (make-local-variable 'imap-sasl-step)
923 (let ((mechanism (sasl-find-mechanism (imap-sasl-make-mechanisms buffer)))
924 logged user)
925 (while (not logged)
926 (setq user (or imap-username
927 (read-from-minibuffer
928 (concat "IMAP username for " imap-server " using SASL "
929 (sasl-mechanism-name mechanism) ": ")
930 (or user imap-default-user))))
931 (when user
932 (setq imap-sasl-client (sasl-make-client mechanism user "imap2" imap-server)
933 imap-sasl-step (sasl-next-step imap-sasl-client nil))
934 (let ((tag (imap-send-command
935 (if (sasl-step-data imap-sasl-step)
936 (format "AUTHENTICATE %s %s"
937 (sasl-mechanism-name mechanism)
938 (sasl-step-data imap-sasl-step))
939 (format "AUTHENTICATE %s" (sasl-mechanism-name mechanism)))
940 buffer)))
941 (while (eq (imap-wait-for-tag tag) 'INCOMPLETE)
942 (sasl-step-set-data imap-sasl-step (base64-decode-string imap-continuation))
943 (setq imap-continuation nil
944 imap-sasl-step (sasl-next-step imap-sasl-client imap-sasl-step))
945 (imap-send-command-1 (if (sasl-step-data imap-sasl-step)
946 (base64-encode-string (sasl-step-data imap-sasl-step) t)
947 "")))
948 (if (imap-ok-p (imap-wait-for-tag tag))
949 (setq imap-username user
950 logged t)
951 (message "Login failed...")
952 (sit-for 1)))))
953 logged)))
955 (defun imap-digest-md5-p (buffer)
956 (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
957 (condition-case ()
958 (require 'digest-md5)
959 (error nil))))
961 (defun imap-digest-md5-auth (buffer)
962 "Login to server using the AUTH DIGEST-MD5 method."
963 (message "imap: Authenticating using DIGEST-MD5...")
964 (imap-interactive-login
965 buffer
966 (lambda (user passwd)
967 (let ((tag
968 (imap-send-command
969 (list
970 "AUTHENTICATE DIGEST-MD5"
971 (lambda (challenge)
972 (digest-md5-parse-digest-challenge
973 (base64-decode-string challenge))
974 (let* ((digest-uri
975 (digest-md5-digest-uri
976 "imap" (digest-md5-challenge 'realm)))
977 (response
978 (digest-md5-digest-response
979 user passwd digest-uri)))
980 (base64-encode-string response 'no-line-break))))
982 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
984 (setq imap-continuation nil)
985 (imap-send-command-1 "")
986 (imap-ok-p (imap-wait-for-tag tag)))))))
988 ;; Server functions:
990 (defun imap-open-1 (buffer)
991 (with-current-buffer buffer
992 (erase-buffer)
993 (setq imap-current-mailbox nil
994 imap-current-message nil
995 imap-state 'initial
996 imap-process (condition-case ()
997 (funcall (nth 2 (assq imap-stream
998 imap-stream-alist))
999 "imap" buffer imap-server imap-port)
1000 ((error quit) nil)))
1001 (when imap-process
1002 (set-process-filter imap-process 'imap-arrival-filter)
1003 (set-process-sentinel imap-process 'imap-sentinel)
1004 (while (and (eq imap-state 'initial)
1005 (memq (process-status imap-process) '(open run)))
1006 (message "Waiting for response from %s..." imap-server)
1007 (accept-process-output imap-process 1))
1008 (message "Waiting for response from %s...done" imap-server)
1009 (and (memq (process-status imap-process) '(open run))
1010 imap-process))))
1012 (defun imap-open (server &optional port stream auth buffer)
1013 "Open an IMAP connection to host SERVER at PORT returning a buffer.
1014 If PORT is unspecified, a default value is used (143 except
1015 for SSL which use 993).
1016 STREAM indicates the stream to use, see `imap-streams' for available
1017 streams. If nil, it choices the best stream the server is capable of.
1018 AUTH indicates authenticator to use, see `imap-authenticators' for
1019 available authenticators. If nil, it choices the best stream the
1020 server is capable of.
1021 BUFFER can be a buffer or a name of a buffer, which is created if
1022 necessary. If nil, the buffer name is generated."
1023 (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
1024 (with-current-buffer (get-buffer-create buffer)
1025 (if (imap-opened buffer)
1026 (imap-close buffer))
1027 (mapc 'make-local-variable imap-local-variables)
1028 (imap-disable-multibyte)
1029 (buffer-disable-undo)
1030 (setq imap-server (or server imap-server))
1031 (setq imap-port (or port imap-port))
1032 (setq imap-auth (or auth imap-auth))
1033 (setq imap-stream (or stream imap-stream))
1034 (message "imap: Connecting to %s..." imap-server)
1035 (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
1036 (imap-open-1 buffer)))
1037 (progn
1038 (message "imap: Connecting to %s...failed" imap-server)
1039 nil)
1040 (when (null imap-stream)
1041 ;; Need to choose stream.
1042 (let ((streams imap-streams))
1043 (while (setq stream (pop streams))
1044 ;; OK to use this stream?
1045 (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
1046 ;; Stream changed?
1047 (if (not (eq imap-default-stream stream))
1048 (with-current-buffer (get-buffer-create
1049 (generate-new-buffer-name " *temp*"))
1050 (mapc 'make-local-variable imap-local-variables)
1051 (imap-disable-multibyte)
1052 (buffer-disable-undo)
1053 (setq imap-server (or server imap-server))
1054 (setq imap-port (or port imap-port))
1055 (setq imap-auth (or auth imap-auth))
1056 (message "imap: Reconnecting with stream `%s'..." stream)
1057 (if (null (let ((imap-stream stream))
1058 (imap-open-1 (current-buffer))))
1059 (progn
1060 (kill-buffer (current-buffer))
1061 (message
1062 "imap: Reconnecting with stream `%s'...failed"
1063 stream))
1064 ;; We're done, kill the first connection
1065 (imap-close buffer)
1066 (let ((name (if (stringp buffer)
1067 buffer
1068 (buffer-name buffer))))
1069 (kill-buffer buffer)
1070 (rename-buffer name)
1071 ;; set the passed buffer to the current one,
1072 ;; so that (imap-opened buffer) later will work
1073 (setq buffer (current-buffer)))
1074 (message "imap: Reconnecting with stream `%s'...done"
1075 stream)
1076 (setq imap-stream stream)
1077 (setq imap-capability nil)
1078 (setq streams nil)))
1079 ;; We're done
1080 (message "imap: Connecting to %s...done" imap-server)
1081 (setq imap-stream stream)
1082 (setq imap-capability nil)
1083 (setq streams nil))))))
1084 (when (imap-opened buffer)
1085 (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
1086 ;; (debug "opened+state+auth+buffer" (imap-opened buffer) imap-state imap-auth buffer)
1087 (when imap-stream
1088 buffer))))
1090 (defcustom imap-ping-server t
1091 "If non-nil, check if IMAP is open.
1092 See the function `imap-ping-server'."
1093 :version "23.1" ;; No Gnus
1094 :group 'imap
1095 :type 'boolean)
1097 (defun imap-opened (&optional buffer)
1098 "Return non-nil if connection to imap server in BUFFER is open.
1099 If BUFFER is nil then the current buffer is used."
1100 (and (setq buffer (get-buffer (or buffer (current-buffer))))
1101 (buffer-live-p buffer)
1102 (with-current-buffer buffer
1103 (and imap-process
1104 (memq (process-status imap-process) '(open run))
1105 (if imap-ping-server
1106 (imap-ping-server)
1107 t)))))
1109 (defun imap-ping-server (&optional buffer)
1110 "Ping the IMAP server in BUFFER with a \"NOOP\" command.
1111 Return non-nil if the server responds, and nil if it does not
1112 respond. If BUFFER is nil, the current buffer is used."
1113 (condition-case ()
1114 (imap-ok-p (imap-send-command-wait "NOOP" buffer))
1115 (error nil)))
1117 (defun imap-authenticate (&optional user passwd buffer)
1118 "Authenticate to server in BUFFER, using current buffer if nil.
1119 It uses the authenticator specified when opening the server.
1121 Optional arguments USER and PASSWD specify the username and
1122 password to use if the authenticator requires a username and/or
1123 password. If omitted or nil, the authenticator may query the
1124 user for a username and/or password."
1125 (with-current-buffer (or buffer (current-buffer))
1126 (if (not (eq imap-state 'nonauth))
1127 (or (eq imap-state 'auth)
1128 (eq imap-state 'selected)
1129 (eq imap-state 'examine))
1130 (make-local-variable 'imap-username)
1131 (make-local-variable 'imap-password)
1132 (make-local-variable 'imap-last-authenticator)
1133 (when user (setq imap-username user))
1134 (when passwd (setq imap-password passwd))
1135 (if imap-auth
1136 (and (setq imap-last-authenticator
1137 (assq imap-auth imap-authenticator-alist))
1138 (funcall (nth 2 imap-last-authenticator) (current-buffer))
1139 (setq imap-state 'auth))
1140 ;; Choose authenticator.
1141 (let ((auths imap-authenticators)
1142 auth)
1143 (while (setq auth (pop auths))
1144 ;; OK to use authenticator?
1145 (setq imap-last-authenticator
1146 (assq auth imap-authenticator-alist))
1147 (when (funcall (nth 1 imap-last-authenticator) (current-buffer))
1148 (message "imap: Authenticating to `%s' using `%s'..."
1149 imap-server auth)
1150 (setq imap-auth auth)
1151 (if (funcall (nth 2 imap-last-authenticator) (current-buffer))
1152 (progn
1153 (message "imap: Authenticating to `%s' using `%s'...done"
1154 imap-server auth)
1155 ;; set imap-state correctly on successful auth attempt
1156 (setq imap-state 'auth)
1157 ;; stop iterating through the authenticator list
1158 (setq auths nil))
1159 (message "imap: Authenticating to `%s' using `%s'...failed"
1160 imap-server auth)))))
1161 imap-state))))
1163 (defun imap-close (&optional buffer)
1164 "Close connection to server in BUFFER.
1165 If BUFFER is nil, the current buffer is used."
1166 (with-current-buffer (or buffer (current-buffer))
1167 (when (imap-opened)
1168 (condition-case nil
1169 (imap-logout-wait)
1170 (quit nil)))
1171 (when (and imap-process
1172 (memq (process-status imap-process) '(open run)))
1173 (delete-process imap-process))
1174 (setq imap-current-mailbox nil
1175 imap-current-message nil
1176 imap-process nil)
1177 (erase-buffer)
1180 (defun imap-capability (&optional identifier buffer)
1181 "Return a list of identifiers which server in BUFFER support.
1182 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1183 If BUFFER is nil, the current buffer is assumed."
1184 (with-current-buffer (or buffer (current-buffer))
1185 (unless imap-capability
1186 (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1187 (setq imap-capability '(IMAP2))))
1188 (if identifier
1189 (memq (intern (upcase (symbol-name identifier))) imap-capability)
1190 imap-capability)))
1192 (defun imap-id (&optional list-of-values buffer)
1193 "Identify client to server in BUFFER, and return server identity.
1194 LIST-OF-VALUES is nil, or a plist with identifier and value
1195 strings to send to the server to identify the client.
1197 Return a list of identifiers which server in BUFFER support, or
1198 nil if it doesn't support ID or returns no information.
1200 If BUFFER is nil, the current buffer is assumed."
1201 (with-current-buffer (or buffer (current-buffer))
1202 (when (and (imap-capability 'ID)
1203 (imap-ok-p (imap-send-command-wait
1204 (if (null list-of-values)
1205 "ID NIL"
1206 (concat "ID (" (mapconcat (lambda (el)
1207 (concat "\"" el "\""))
1208 list-of-values
1209 " ") ")")))))
1210 imap-id)))
1212 (defun imap-namespace (&optional buffer)
1213 "Return a namespace hierarchy at server in BUFFER.
1214 If BUFFER is nil, the current buffer is assumed."
1215 (with-current-buffer (or buffer (current-buffer))
1216 (unless imap-namespace
1217 (when (imap-capability 'NAMESPACE)
1218 (imap-send-command-wait "NAMESPACE")))
1219 imap-namespace))
1221 (defun imap-send-command-wait (command &optional buffer)
1222 (imap-wait-for-tag (imap-send-command command buffer) buffer))
1224 (defun imap-logout (&optional buffer)
1225 (or buffer (setq buffer (current-buffer)))
1226 (if imap-logout-timeout
1227 (with-timeout (imap-logout-timeout
1228 (condition-case nil
1229 (with-current-buffer buffer
1230 (delete-process imap-process))
1231 (error)))
1232 (imap-send-command "LOGOUT" buffer))
1233 (imap-send-command "LOGOUT" buffer)))
1235 (defun imap-logout-wait (&optional buffer)
1236 (or buffer (setq buffer (current-buffer)))
1237 (if imap-logout-timeout
1238 (with-timeout (imap-logout-timeout
1239 (condition-case nil
1240 (with-current-buffer buffer
1241 (delete-process imap-process))
1242 (error)))
1243 (imap-send-command-wait "LOGOUT" buffer))
1244 (imap-send-command-wait "LOGOUT" buffer)))
1247 ;; Mailbox functions:
1249 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1250 (with-current-buffer (or buffer (current-buffer))
1251 (if imap-mailbox-data
1252 (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1253 propname value)
1254 (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1255 propname value mailbox (current-buffer)))
1258 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1259 (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1260 propname))
1262 (defun imap-mailbox-get (propname &optional mailbox buffer)
1263 (let ((mailbox (imap-utf7-encode mailbox)))
1264 (with-current-buffer (or buffer (current-buffer))
1265 (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1267 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1268 (with-current-buffer (or buffer (current-buffer))
1269 (let (result)
1270 (mapatoms
1271 (lambda (s)
1272 (push (funcall func (if mailbox-decoder
1273 (funcall mailbox-decoder (symbol-name s))
1274 (symbol-name s))) result))
1275 imap-mailbox-data)
1276 result)))
1278 (defun imap-mailbox-map (func &optional buffer)
1279 "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1280 Function should take a mailbox name (a string) as
1281 the only argument."
1282 (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1284 (defun imap-current-mailbox (&optional buffer)
1285 (with-current-buffer (or buffer (current-buffer))
1286 (imap-utf7-decode imap-current-mailbox)))
1288 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1289 (and (string= mailbox imap-current-mailbox)
1290 (or (and examine
1291 (eq imap-state 'examine))
1292 (and (not examine)
1293 (eq imap-state 'selected)))))
1295 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1296 (with-current-buffer (or buffer (current-buffer))
1297 (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1299 (defun imap-mailbox-select-1 (mailbox &optional examine)
1300 "Select MAILBOX on server in BUFFER.
1301 If EXAMINE is non-nil, do a read-only select."
1302 (if (imap-current-mailbox-p-1 mailbox examine)
1303 imap-current-mailbox
1304 (setq imap-current-mailbox mailbox)
1305 (if (imap-ok-p (imap-send-command-wait
1306 (concat (if examine "EXAMINE" "SELECT") " \""
1307 mailbox "\"")))
1308 (progn
1309 (setq imap-message-data (make-vector imap-message-prime 0)
1310 imap-state (if examine 'examine 'selected))
1311 imap-current-mailbox)
1312 ;; Failed SELECT/EXAMINE unselects current mailbox
1313 (setq imap-current-mailbox nil))))
1315 (defun imap-mailbox-select (mailbox &optional examine buffer)
1316 (with-current-buffer (or buffer (current-buffer))
1317 (imap-utf7-decode
1318 (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1320 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1321 (with-current-buffer (or buffer (current-buffer))
1322 (imap-mailbox-select-1 mailbox 'examine)))
1324 (defun imap-mailbox-examine (mailbox &optional buffer)
1325 "Examine MAILBOX on server in BUFFER."
1326 (imap-mailbox-select mailbox 'examine buffer))
1328 (defun imap-mailbox-unselect (&optional buffer)
1329 "Close current folder in BUFFER, without expunging articles."
1330 (with-current-buffer (or buffer (current-buffer))
1331 (when (or (eq imap-state 'auth)
1332 (and (imap-capability 'UNSELECT)
1333 (imap-ok-p (imap-send-command-wait "UNSELECT")))
1334 (and (imap-ok-p
1335 (imap-send-command-wait (concat "EXAMINE \""
1336 imap-current-mailbox
1337 "\"")))
1338 (imap-ok-p (imap-send-command-wait "CLOSE"))))
1339 (setq imap-current-mailbox nil
1340 imap-message-data nil
1341 imap-state 'auth)
1342 t)))
1344 (defun imap-mailbox-expunge (&optional asynch buffer)
1345 "Expunge articles in current folder in BUFFER.
1346 If ASYNCH, do not wait for successful completion of the command.
1347 If BUFFER is nil the current buffer is assumed."
1348 (with-current-buffer (or buffer (current-buffer))
1349 (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1350 (if asynch
1351 (imap-send-command "EXPUNGE")
1352 (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1354 (defun imap-mailbox-close (&optional asynch buffer)
1355 "Expunge articles and close current folder in BUFFER.
1356 If ASYNCH, do not wait for successful completion of the command.
1357 If BUFFER is nil the current buffer is assumed."
1358 (with-current-buffer (or buffer (current-buffer))
1359 (when imap-current-mailbox
1360 (if asynch
1361 (imap-add-callback (imap-send-command "CLOSE")
1362 `(lambda (tag status)
1363 (message "IMAP mailbox `%s' closed... %s"
1364 imap-current-mailbox status)
1365 (when (eq ,imap-current-mailbox
1366 imap-current-mailbox)
1367 ;; Don't wipe out data if another mailbox
1368 ;; was selected...
1369 (setq imap-current-mailbox nil
1370 imap-message-data nil
1371 imap-state 'auth))))
1372 (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1373 (setq imap-current-mailbox nil
1374 imap-message-data nil
1375 imap-state 'auth)))
1376 t)))
1378 (defun imap-mailbox-create-1 (mailbox)
1379 (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1381 (defun imap-mailbox-create (mailbox &optional buffer)
1382 "Create MAILBOX on server in BUFFER.
1383 If BUFFER is nil the current buffer is assumed."
1384 (with-current-buffer (or buffer (current-buffer))
1385 (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1387 (defun imap-mailbox-delete (mailbox &optional buffer)
1388 "Delete MAILBOX on server in BUFFER.
1389 If BUFFER is nil the current buffer is assumed."
1390 (let ((mailbox (imap-utf7-encode mailbox)))
1391 (with-current-buffer (or buffer (current-buffer))
1392 (imap-ok-p
1393 (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1395 (defun imap-mailbox-rename (oldname newname &optional buffer)
1396 "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1397 If BUFFER is nil the current buffer is assumed."
1398 (let ((oldname (imap-utf7-encode oldname))
1399 (newname (imap-utf7-encode newname)))
1400 (with-current-buffer (or buffer (current-buffer))
1401 (imap-ok-p
1402 (imap-send-command-wait (list "RENAME \"" oldname "\" "
1403 "\"" newname "\""))))))
1405 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1406 "Return a list of subscribed mailboxes on server in BUFFER.
1407 If ROOT is non-nil, only list matching mailboxes. If ADD-DELIMITER is
1408 non-nil, a hierarchy delimiter is added to root. REFERENCE is an
1409 implementation-specific string that has to be passed to lsub command."
1410 (with-current-buffer (or buffer (current-buffer))
1411 ;; Make sure we know the hierarchy separator for root's hierarchy
1412 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1413 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1414 (imap-utf7-encode root) "\"")))
1415 ;; clear list data (NB not delimiter and other stuff)
1416 (imap-mailbox-map-1 (lambda (mailbox)
1417 (imap-mailbox-put 'lsub nil mailbox)))
1418 (when (imap-ok-p
1419 (imap-send-command-wait
1420 (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1421 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1422 "%\"")))
1423 (let (out)
1424 (imap-mailbox-map-1 (lambda (mailbox)
1425 (when (imap-mailbox-get-1 'lsub mailbox)
1426 (push (imap-utf7-decode mailbox) out))))
1427 (nreverse out)))))
1429 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1430 "Return a list of mailboxes matching ROOT on server in BUFFER.
1431 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1432 root. REFERENCE is an implementation-specific string that has to be
1433 passed to list command."
1434 (with-current-buffer (or buffer (current-buffer))
1435 ;; Make sure we know the hierarchy separator for root's hierarchy
1436 (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1437 (imap-send-command-wait (concat "LIST \"" reference "\" \""
1438 (imap-utf7-encode root) "\"")))
1439 ;; clear list data (NB not delimiter and other stuff)
1440 (imap-mailbox-map-1 (lambda (mailbox)
1441 (imap-mailbox-put 'list nil mailbox)))
1442 (when (imap-ok-p
1443 (imap-send-command-wait
1444 (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1445 (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1446 "%\"")))
1447 (let (out)
1448 (imap-mailbox-map-1 (lambda (mailbox)
1449 (when (imap-mailbox-get-1 'list mailbox)
1450 (push (imap-utf7-decode mailbox) out))))
1451 (nreverse out)))))
1453 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1454 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1455 Returns non-nil if successful."
1456 (with-current-buffer (or buffer (current-buffer))
1457 (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1458 (imap-utf7-encode mailbox)
1459 "\"")))))
1461 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1462 "Send the SUBSCRIBE command on the MAILBOX to server in BUFFER.
1463 Returns non-nil if successful."
1464 (with-current-buffer (or buffer (current-buffer))
1465 (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1466 (imap-utf7-encode mailbox)
1467 "\"")))))
1469 (defun imap-mailbox-status (mailbox items &optional buffer)
1470 "Get status items ITEM in MAILBOX from server in BUFFER.
1471 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1472 the STATUS data items -- i.e. `messages', `recent', `uidnext', `uidvalidity',
1473 or `unseen'. If ITEMS is a list of symbols, a list of values is
1474 returned, if ITEMS is a symbol only its value is returned."
1475 (with-current-buffer (or buffer (current-buffer))
1476 (when (imap-ok-p
1477 (imap-send-command-wait (list "STATUS \""
1478 (imap-utf7-encode mailbox)
1479 "\" "
1480 (upcase
1481 (format "%s"
1482 (if (listp items)
1483 items
1484 (list items)))))))
1485 (if (listp items)
1486 (mapcar (lambda (item)
1487 (imap-mailbox-get item mailbox))
1488 items)
1489 (imap-mailbox-get items mailbox)))))
1491 (defun imap-mailbox-status-asynch (mailbox items &optional buffer)
1492 "Send status item requests ITEMS on MAILBOX to server in BUFFER.
1493 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1494 the STATUS data items -- i.e., `messages', `recent', `uidnext', `uidvalidity'
1495 or `unseen'. The IMAP command tag is returned."
1496 (with-current-buffer (or buffer (current-buffer))
1497 (imap-send-command (list "STATUS \""
1498 (imap-utf7-encode mailbox)
1499 "\" "
1500 (upcase
1501 (format "%s"
1502 (if (listp items)
1503 items
1504 (list items))))))))
1506 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1507 "Get ACL on MAILBOX from server in BUFFER."
1508 (let ((mailbox (imap-utf7-encode mailbox)))
1509 (with-current-buffer (or buffer (current-buffer))
1510 (when (imap-ok-p
1511 (imap-send-command-wait (list "GETACL \""
1512 (or mailbox imap-current-mailbox)
1513 "\"")))
1514 (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1516 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1517 "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1518 (let ((mailbox (imap-utf7-encode mailbox)))
1519 (with-current-buffer (or buffer (current-buffer))
1520 (imap-ok-p
1521 (imap-send-command-wait (list "SETACL \""
1522 (or mailbox imap-current-mailbox)
1523 "\" "
1524 identifier
1526 rights))))))
1528 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1529 "Remove <id,rights> pairs for IDENTIFIER from MAILBOX on server in BUFFER."
1530 (let ((mailbox (imap-utf7-encode mailbox)))
1531 (with-current-buffer (or buffer (current-buffer))
1532 (imap-ok-p
1533 (imap-send-command-wait (list "DELETEACL \""
1534 (or mailbox imap-current-mailbox)
1535 "\" "
1536 identifier))))))
1539 ;; Message functions:
1541 (defun imap-current-message (&optional buffer)
1542 (with-current-buffer (or buffer (current-buffer))
1543 imap-current-message))
1545 (defun imap-list-to-message-set (list)
1546 (mapconcat (lambda (item)
1547 (number-to-string item))
1548 (if (listp list)
1549 list
1550 (list list))
1551 ","))
1553 (defun imap-range-to-message-set (range)
1554 (mapconcat
1555 (lambda (item)
1556 (if (consp item)
1557 (format "%d:%d"
1558 (car item) (cdr item))
1559 (format "%d" item)))
1560 (if (and (listp range) (not (listp (cdr range))))
1561 (list range) ;; make (1 . 2) into ((1 . 2))
1562 range)
1563 ","))
1565 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1566 (with-current-buffer (or buffer (current-buffer))
1567 (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1568 (if (listp uids)
1569 (imap-list-to-message-set uids)
1570 uids)
1571 props))))
1573 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1574 "Fetch properties PROPS from message set UIDS from server in BUFFER.
1575 UIDS can be a string, number or a list of numbers. If RECEIVE is
1576 non-nil, return these properties."
1577 (with-current-buffer (or buffer (current-buffer))
1578 (when (imap-ok-p (imap-send-command-wait
1579 (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1580 (if (listp uids)
1581 (imap-list-to-message-set uids)
1582 uids)
1583 props)))
1584 (if (or (null receive) (stringp uids))
1586 (if (listp uids)
1587 (mapcar (lambda (uid)
1588 (if (listp receive)
1589 (mapcar (lambda (prop)
1590 (imap-message-get uid prop))
1591 receive)
1592 (imap-message-get uid receive)))
1593 uids)
1594 (imap-message-get uids receive))))))
1596 (defun imap-message-put (uid propname value &optional buffer)
1597 (with-current-buffer (or buffer (current-buffer))
1598 (if imap-message-data
1599 (put (intern (number-to-string uid) imap-message-data)
1600 propname value)
1601 (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1602 uid propname value (current-buffer)))
1605 (defun imap-message-get (uid propname &optional buffer)
1606 (with-current-buffer (or buffer (current-buffer))
1607 (get (intern-soft (number-to-string uid) imap-message-data)
1608 propname)))
1610 (defun imap-message-map (func propname &optional buffer)
1611 "Map a function across each message in `imap-message-data', returning a list."
1612 (with-current-buffer (or buffer (current-buffer))
1613 (let (result)
1614 (mapatoms
1615 (lambda (s)
1616 (push (funcall func (get s 'UID) (get s propname)) result))
1617 imap-message-data)
1618 result)))
1620 (defmacro imap-message-envelope-date (uid &optional buffer)
1621 `(with-current-buffer (or ,buffer (current-buffer))
1622 (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1624 (defmacro imap-message-envelope-subject (uid &optional buffer)
1625 `(with-current-buffer (or ,buffer (current-buffer))
1626 (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1628 (defmacro imap-message-envelope-from (uid &optional buffer)
1629 `(with-current-buffer (or ,buffer (current-buffer))
1630 (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1632 (defmacro imap-message-envelope-sender (uid &optional buffer)
1633 `(with-current-buffer (or ,buffer (current-buffer))
1634 (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1636 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1637 `(with-current-buffer (or ,buffer (current-buffer))
1638 (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1640 (defmacro imap-message-envelope-to (uid &optional buffer)
1641 `(with-current-buffer (or ,buffer (current-buffer))
1642 (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1644 (defmacro imap-message-envelope-cc (uid &optional buffer)
1645 `(with-current-buffer (or ,buffer (current-buffer))
1646 (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1648 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1649 `(with-current-buffer (or ,buffer (current-buffer))
1650 (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1652 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1653 `(with-current-buffer (or ,buffer (current-buffer))
1654 (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1656 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1657 `(with-current-buffer (or ,buffer (current-buffer))
1658 (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1660 (defmacro imap-message-body (uid &optional buffer)
1661 `(with-current-buffer (or ,buffer (current-buffer))
1662 (imap-message-get ,uid 'BODY)))
1664 ;; FIXME: Should this try to use CHARSET? -- fx
1665 (defun imap-search (predicate &optional buffer)
1666 (with-current-buffer (or buffer (current-buffer))
1667 (imap-mailbox-put 'search 'dummy)
1668 (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1669 (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1670 (progn
1671 (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1672 nil)
1673 (imap-mailbox-get-1 'search imap-current-mailbox)))))
1675 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1676 "Return t if FLAG can be permanently saved on articles.
1677 MAILBOX specifies a mailbox on the server in BUFFER."
1678 (with-current-buffer (or buffer (current-buffer))
1679 (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1680 (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1682 (defun imap-message-flags-set (articles flags &optional silent buffer)
1683 (when (and articles flags)
1684 (with-current-buffer (or buffer (current-buffer))
1685 (imap-ok-p (imap-send-command-wait
1686 (concat "UID STORE " articles
1687 " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1689 (defun imap-message-flags-del (articles flags &optional silent buffer)
1690 (when (and articles flags)
1691 (with-current-buffer (or buffer (current-buffer))
1692 (imap-ok-p (imap-send-command-wait
1693 (concat "UID STORE " articles
1694 " -FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1696 (defun imap-message-flags-add (articles flags &optional silent buffer)
1697 (when (and articles flags)
1698 (with-current-buffer (or buffer (current-buffer))
1699 (imap-ok-p (imap-send-command-wait
1700 (concat "UID STORE " articles
1701 " +FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1703 ;; Cf. http://thread.gmane.org/gmane.emacs.gnus.general/65317/focus=65343
1704 ;; Signal an error if we'd get an integer overflow.
1706 ;; FIXME: Identify relevant calls to `string-to-number' and replace them with
1707 ;; `imap-string-to-integer'.
1708 (defun imap-string-to-integer (string &optional base)
1709 (let ((number (string-to-number string base)))
1710 (if (> number most-positive-fixnum)
1711 (error
1712 (format "String %s cannot be converted to a Lisp integer" number))
1713 number)))
1715 (defun imap-fetch-safe (uids props &optional receive nouidfetch buffer)
1716 "Like `imap-fetch', but DTRT with Exchange 2007 bug.
1717 However, UIDS here is a cons, where the car is the canonical form
1718 of the UIDS specification, and the cdr is the one which works with
1719 Exchange 2007 or, potentially, other buggy servers.
1720 See `imap-enable-exchange-bug-workaround'."
1721 ;; The first time we get here for a given, we'll try the canonical
1722 ;; form. If we get the known error from the buggy server, set the
1723 ;; flag buffer-locally (to account for connections to multiple
1724 ;; servers), then re-try with the alternative UIDS spec. We don't
1725 ;; unconditionally use the alternative form, since the
1726 ;; currently-used alternatives are seriously inefficient with some
1727 ;; servers (although they are valid).
1729 ;; FIXME: Maybe it would be cleaner to have a flag to not signal
1730 ;; the error (which otherwise gives a message), and test
1731 ;; `imap-failed-tags'. Also, Other IMAP clients use other forms of
1732 ;; request which work with Exchange, e.g. Claws does "UID FETCH 1:*
1733 ;; (UID)" rather than "FETCH UID 1,*". Is there a good reason not
1734 ;; to do the same?
1735 (condition-case data
1736 ;; Binding `debug-on-error' allows us to get the error from
1737 ;; `imap-parse-response' -- it's normally caught by Emacs around
1738 ;; execution of a process filter.
1739 (let ((debug-on-error t))
1740 (imap-fetch (if imap-enable-exchange-bug-workaround
1741 (cdr uids)
1742 (car uids))
1743 props receive nouidfetch buffer))
1744 (error
1745 (if (and (not imap-enable-exchange-bug-workaround)
1746 ;; This is the Exchange 2007 response. It may be more
1747 ;; robust just to check for a BAD response to the
1748 ;; attempted fetch.
1749 (string-match "The specified message set is invalid"
1750 (cadr data)))
1751 (with-current-buffer (or buffer (current-buffer))
1752 (set (make-local-variable 'imap-enable-exchange-bug-workaround)
1754 (imap-fetch (cdr uids) props receive nouidfetch))
1755 (signal (car data) (cdr data))))))
1757 (defun imap-message-copyuid-1 (mailbox)
1758 (if (imap-capability 'UIDPLUS)
1759 (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1760 (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1761 (let ((old-mailbox imap-current-mailbox)
1762 (state imap-state)
1763 (imap-message-data (make-vector 2 0)))
1764 (when (imap-mailbox-examine-1 mailbox)
1765 (prog1
1766 (and (imap-fetch-safe '("*" . "*:*") "UID")
1767 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1768 (apply 'max (imap-message-map
1769 (lambda (uid _prop) uid) 'UID))))
1770 (if old-mailbox
1771 (imap-mailbox-select old-mailbox (eq state 'examine))
1772 (imap-mailbox-unselect)))))))
1774 (defun imap-message-copyuid (mailbox &optional buffer)
1775 (with-current-buffer (or buffer (current-buffer))
1776 (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1778 (defun imap-message-copy (articles mailbox
1779 &optional dont-create no-copyuid buffer)
1780 "Copy ARTICLES to MAILBOX on server in BUFFER.
1781 ARTICLES is a string message set. Create mailbox if it doesn't exist,
1782 unless DONT-CREATE is non-nil. On success, return a list with
1783 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1784 first element. The rest of list contains the saved articles' UIDs."
1785 (when articles
1786 (with-current-buffer (or buffer (current-buffer))
1787 (let ((mailbox (imap-utf7-encode mailbox)))
1788 (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1789 (imap-current-target-mailbox mailbox))
1790 (if (imap-ok-p (imap-send-command-wait cmd))
1792 (when (and (not dont-create)
1793 ;; removed because of buggy Oracle server
1794 ;; that doesn't send TRYCREATE tags (which
1795 ;; is a MUST according to specifications):
1796 ;;(imap-mailbox-get-1 'trycreate mailbox)
1797 (imap-mailbox-create-1 mailbox))
1798 (imap-ok-p (imap-send-command-wait cmd)))))
1799 (or no-copyuid
1800 (imap-message-copyuid-1 mailbox)))))))
1802 ;; FIXME: Amalgamate with imap-message-copyuid-1, using an extra arg, since it
1803 ;; shares most of the code? -- fx
1804 (defun imap-message-appenduid-1 (mailbox)
1805 (if (imap-capability 'UIDPLUS)
1806 (imap-mailbox-get-1 'appenduid mailbox)
1807 (let ((old-mailbox imap-current-mailbox)
1808 (state imap-state)
1809 (imap-message-data (make-vector 2 0)))
1810 (when (imap-mailbox-examine-1 mailbox)
1811 (prog1
1812 (and (imap-fetch-safe '("*" . "*:*") "UID")
1813 (list (imap-mailbox-get-1 'uidvalidity mailbox)
1814 (apply 'max (imap-message-map
1815 (lambda (uid _prop) uid) 'UID))))
1816 (if old-mailbox
1817 (imap-mailbox-select old-mailbox (eq state 'examine))
1818 (imap-mailbox-unselect)))))))
1820 (defun imap-message-appenduid (mailbox &optional buffer)
1821 (with-current-buffer (or buffer (current-buffer))
1822 (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1824 (defun imap-message-append (mailbox article &optional _flags _date-time buffer)
1825 "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1826 FLAGS and DATE-TIME is currently not used. Return a cons holding
1827 uidvalidity of MAILBOX and UID the newly created article got, or nil
1828 on failure."
1829 (let ((mailbox (imap-utf7-encode mailbox)))
1830 (with-current-buffer (or buffer (current-buffer))
1831 (and (let ((imap-current-target-mailbox mailbox))
1832 (imap-ok-p
1833 (imap-send-command-wait
1834 (list "APPEND \"" mailbox "\" " article))))
1835 (imap-message-appenduid-1 mailbox)))))
1837 (defun imap-body-lines (body)
1838 "Return number of lines in article by looking at the mime bodystructure BODY."
1839 (if (listp body)
1840 (if (stringp (car body))
1841 (cond ((and (string= (upcase (car body)) "TEXT")
1842 (numberp (nth 7 body)))
1843 (nth 7 body))
1844 ((and (string= (upcase (car body)) "MESSAGE")
1845 (numberp (nth 9 body)))
1846 (nth 9 body))
1847 (t 0))
1848 (apply '+ (mapcar 'imap-body-lines body)))
1851 (defun imap-envelope-from (from)
1852 "Return a FROM string line."
1853 (and from
1854 (concat (aref from 0)
1855 (if (aref from 0) " <")
1856 (aref from 2)
1858 (aref from 3)
1859 (if (aref from 0) ">"))))
1862 ;; Internal functions.
1864 (defun imap-add-callback (tag func)
1865 (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1867 (defun imap-send-command-1 (cmdstr)
1868 (setq cmdstr (concat cmdstr imap-client-eol))
1869 (imap-log cmdstr)
1870 (process-send-string imap-process cmdstr))
1872 (defun imap-send-command (command &optional buffer)
1873 (with-current-buffer (or buffer (current-buffer))
1874 (if (not (listp command)) (setq command (list command)))
1875 (let ((tag (setq imap-tag (1+ imap-tag)))
1876 cmd cmdstr)
1877 (setq cmdstr (concat (number-to-string imap-tag) " "))
1878 (while (setq cmd (pop command))
1879 (cond ((stringp cmd)
1880 (setq cmdstr (concat cmdstr cmd)))
1881 ((bufferp cmd)
1882 (let ((eol imap-client-eol)
1883 (calcfirst imap-calculate-literal-size-first)
1884 size)
1885 (with-current-buffer cmd
1886 (if calcfirst
1887 (setq size (buffer-size)))
1888 (when (not (equal eol "\r\n"))
1889 ;; XXX modifies buffer!
1890 (goto-char (point-min))
1891 (while (search-forward "\r\n" nil t)
1892 (replace-match eol)))
1893 (if (not calcfirst)
1894 (setq size (buffer-size))))
1895 (setq cmdstr
1896 (concat cmdstr (format "{%d}" size))))
1897 (unwind-protect
1898 (progn
1899 (imap-send-command-1 cmdstr)
1900 (setq cmdstr nil)
1901 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1902 (setq command nil) ;; abort command if no cont-req
1903 (let ((process imap-process)
1904 (stream imap-stream)
1905 (eol imap-client-eol))
1906 (with-current-buffer cmd
1907 (imap-log cmd)
1908 (process-send-region process (point-min)
1909 (point-max)))
1910 (process-send-string process imap-client-eol))))
1911 (setq imap-continuation nil)))
1912 ((functionp cmd)
1913 (imap-send-command-1 cmdstr)
1914 (setq cmdstr nil)
1915 (unwind-protect
1916 (setq command
1917 (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1918 nil ;; abort command if no cont-req
1919 (cons (funcall cmd imap-continuation)
1920 command)))
1921 (setq imap-continuation nil)))
1923 (error "Unknown command type"))))
1924 (if cmdstr
1925 (imap-send-command-1 cmdstr))
1926 tag)))
1928 (defun imap-wait-for-tag (tag &optional buffer)
1929 (with-current-buffer (or buffer (current-buffer))
1930 (let (imap-have-messaged)
1931 (while (and (null imap-continuation)
1932 (memq (process-status imap-process) '(open run))
1933 (< imap-reached-tag tag))
1934 (let ((len (/ (buffer-size) 1024))
1935 message-log-max)
1936 (unless (< len 10)
1937 (setq imap-have-messaged t)
1938 (message "imap read: %dk" len))
1939 (accept-process-output imap-process
1940 (truncate imap-read-timeout)
1941 (truncate (* (- imap-read-timeout
1942 (truncate imap-read-timeout))
1943 1000)))))
1944 ;; A process can die _before_ we have processed everything it
1945 ;; has to say. Moreover, this can happen in between the call to
1946 ;; accept-process-output and the call to process-status in an
1947 ;; iteration of the loop above.
1948 (when (and (null imap-continuation)
1949 (< imap-reached-tag tag))
1950 (accept-process-output imap-process 0 0))
1951 (when imap-have-messaged
1952 (message ""))
1953 (and (memq (process-status imap-process) '(open run))
1954 (or (assq tag imap-failed-tags)
1955 (if imap-continuation
1956 'INCOMPLETE
1957 'OK))))))
1959 (defun imap-sentinel (process string)
1960 (delete-process process))
1962 (defun imap-find-next-line ()
1963 "Return point at end of current line, taking into account literals.
1964 Return nil if no complete line has arrived."
1965 (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1966 imap-server-eol)
1967 nil t)
1968 (if (match-string 1)
1969 (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1971 (goto-char (+ (point) (string-to-number (match-string 1))))
1972 (imap-find-next-line))
1973 (point))))
1975 (defun imap-arrival-filter (proc string)
1976 "IMAP process filter."
1977 ;; Sometimes, we are called even though the process has died.
1978 ;; Better abstain from doing stuff in that case.
1979 (when (buffer-name (process-buffer proc))
1980 (with-current-buffer (process-buffer proc)
1981 (goto-char (point-max))
1982 (insert string)
1983 (imap-log string)
1984 (let (end)
1985 (goto-char (point-min))
1986 (while (setq end (imap-find-next-line))
1987 (save-restriction
1988 (narrow-to-region (point-min) end)
1989 (delete-char (- (length imap-server-eol)))
1990 (goto-char (point-min))
1991 (unwind-protect
1992 (cond ((eq imap-state 'initial)
1993 (imap-parse-greeting))
1994 ((or (eq imap-state 'auth)
1995 (eq imap-state 'nonauth)
1996 (eq imap-state 'selected)
1997 (eq imap-state 'examine))
1998 (imap-parse-response))
2000 (message "Unknown state %s in arrival filter"
2001 imap-state)))
2002 (delete-region (point-min) (point-max)))))))))
2005 ;; Imap parser.
2007 (defsubst imap-forward ()
2008 (or (eobp) (forward-char)))
2010 ;; number = 1*DIGIT
2011 ;; ; Unsigned 32-bit integer
2012 ;; ; (0 <= n < 4,294,967,296)
2014 (defsubst imap-parse-number ()
2015 (when (looking-at "[0-9]+")
2016 (prog1
2017 (string-to-number (match-string 0))
2018 (goto-char (match-end 0)))))
2020 ;; literal = "{" number "}" CRLF *CHAR8
2021 ;; ; Number represents the number of CHAR8s
2023 (defsubst imap-parse-literal ()
2024 (when (looking-at "{\\([0-9]+\\)}\r\n")
2025 (let ((pos (match-end 0))
2026 (len (string-to-number (match-string 1))))
2027 (if (< (point-max) (+ pos len))
2029 (goto-char (+ pos len))
2030 (buffer-substring pos (+ pos len))))))
2032 ;; string = quoted / literal
2034 ;; quoted = DQUOTE *QUOTED-CHAR DQUOTE
2036 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2037 ;; "\" quoted-specials
2039 ;; quoted-specials = DQUOTE / "\"
2041 ;; TEXT-CHAR = <any CHAR except CR and LF>
2043 (defsubst imap-parse-string ()
2044 (cond ((eq (char-after) ?\")
2045 (forward-char 1)
2046 (let ((p (point)) (name ""))
2047 (skip-chars-forward "^\"\\\\")
2048 (setq name (buffer-substring p (point)))
2049 (while (eq (char-after) ?\\)
2050 (setq p (1+ (point)))
2051 (forward-char 2)
2052 (skip-chars-forward "^\"\\\\")
2053 (setq name (concat name (buffer-substring p (point)))))
2054 (forward-char 1)
2055 name))
2056 ((eq (char-after) ?{)
2057 (imap-parse-literal))))
2059 ;; nil = "NIL"
2061 (defsubst imap-parse-nil ()
2062 (if (looking-at "NIL")
2063 (goto-char (match-end 0))))
2065 ;; nstring = string / nil
2067 (defsubst imap-parse-nstring ()
2068 (or (imap-parse-string)
2069 (and (imap-parse-nil)
2070 nil)))
2072 ;; astring = atom / string
2074 ;; atom = 1*ATOM-CHAR
2076 ;; ATOM-CHAR = <any CHAR except atom-specials>
2078 ;; atom-specials = "(" / ")" / "{" / SP / CTL / list-wildcards /
2079 ;; quoted-specials
2081 ;; list-wildcards = "%" / "*"
2083 ;; quoted-specials = DQUOTE / "\"
2085 (defsubst imap-parse-astring ()
2086 (or (imap-parse-string)
2087 (buffer-substring (point)
2088 (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
2089 (goto-char (1- (match-end 0)))
2090 (end-of-line)
2091 (point)))))
2093 ;; address = "(" addr-name SP addr-adl SP addr-mailbox SP
2094 ;; addr-host ")"
2096 ;; addr-adl = nstring
2097 ;; ; Holds route from [RFC-822] route-addr if
2098 ;; ; non-nil
2100 ;; addr-host = nstring
2101 ;; ; nil indicates [RFC-822] group syntax.
2102 ;; ; Otherwise, holds [RFC-822] domain name
2104 ;; addr-mailbox = nstring
2105 ;; ; nil indicates end of [RFC-822] group; if
2106 ;; ; non-nil and addr-host is nil, holds
2107 ;; ; [RFC-822] group name.
2108 ;; ; Otherwise, holds [RFC-822] local-part
2109 ;; ; after removing [RFC-822] quoting
2111 ;; addr-name = nstring
2112 ;; ; If non-nil, holds phrase from [RFC-822]
2113 ;; ; mailbox after removing [RFC-822] quoting
2116 (defsubst imap-parse-address ()
2117 (let (address)
2118 (when (eq (char-after) ?\()
2119 (imap-forward)
2120 (setq address (vector (prog1 (imap-parse-nstring)
2121 (imap-forward))
2122 (prog1 (imap-parse-nstring)
2123 (imap-forward))
2124 (prog1 (imap-parse-nstring)
2125 (imap-forward))
2126 (imap-parse-nstring)))
2127 (when (eq (char-after) ?\))
2128 (imap-forward)
2129 address))))
2131 ;; address-list = "(" 1*address ")" / nil
2133 ;; nil = "NIL"
2135 (defsubst imap-parse-address-list ()
2136 (if (eq (char-after) ?\()
2137 (let (address addresses)
2138 (imap-forward)
2139 (while (and (not (eq (char-after) ?\)))
2140 ;; next line for MS Exchange bug
2141 (progn (and (eq (char-after) ? ) (imap-forward)) t)
2142 (setq address (imap-parse-address)))
2143 (setq addresses (cons address addresses)))
2144 (when (eq (char-after) ?\))
2145 (imap-forward)
2146 (nreverse addresses)))
2147 ;; With assert, the code might not be eval'd.
2148 ;; (assert (imap-parse-nil) t "In imap-parse-address-list")
2149 (imap-parse-nil)))
2151 ;; mailbox = "INBOX" / astring
2152 ;; ; INBOX is case-insensitive. All case variants of
2153 ;; ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
2154 ;; ; not as an astring. An astring which consists of
2155 ;; ; the case-insensitive sequence "I" "N" "B" "O" "X"
2156 ;; ; is considered to be INBOX and not an astring.
2157 ;; ; Refer to section 5.1 for further
2158 ;; ; semantic details of mailbox names.
2160 (defsubst imap-parse-mailbox ()
2161 (let ((mailbox (imap-parse-astring)))
2162 (if (string-equal "INBOX" (upcase mailbox))
2163 "INBOX"
2164 mailbox)))
2166 ;; greeting = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
2168 ;; resp-cond-auth = ("OK" / "PREAUTH") SP resp-text
2169 ;; ; Authentication condition
2171 ;; resp-cond-bye = "BYE" SP resp-text
2173 (defun imap-parse-greeting ()
2174 "Parse an IMAP greeting."
2175 (cond ((looking-at "\\* OK ")
2176 (setq imap-state 'nonauth))
2177 ((looking-at "\\* PREAUTH ")
2178 (setq imap-state 'auth))
2179 ((looking-at "\\* BYE ")
2180 (setq imap-state 'closed))))
2182 ;; response = *(continue-req / response-data) response-done
2184 ;; continue-req = "+" SP (resp-text / base64) CRLF
2186 ;; response-data = "*" SP (resp-cond-state / resp-cond-bye /
2187 ;; mailbox-data / message-data / capability-data) CRLF
2189 ;; response-done = response-tagged / response-fatal
2191 ;; response-fatal = "*" SP resp-cond-bye CRLF
2192 ;; ; Server closes connection immediately
2194 ;; response-tagged = tag SP resp-cond-state CRLF
2196 ;; resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
2197 ;; ; Status condition
2199 ;; resp-cond-bye = "BYE" SP resp-text
2201 ;; mailbox-data = "FLAGS" SP flag-list /
2202 ;; "LIST" SP mailbox-list /
2203 ;; "LSUB" SP mailbox-list /
2204 ;; "SEARCH" *(SP nz-number) /
2205 ;; "STATUS" SP mailbox SP "("
2206 ;; [status-att SP number *(SP status-att SP number)] ")" /
2207 ;; number SP "EXISTS" /
2208 ;; number SP "RECENT"
2210 ;; message-data = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
2212 ;; capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
2213 ;; *(SP capability)
2214 ;; ; IMAP4rev1 servers which offer RFC 1730
2215 ;; ; compatibility MUST list "IMAP4" as the first
2216 ;; ; capability.
2218 (defun imap-parse-response ()
2219 "Parse an IMAP command response."
2220 (let (token)
2221 (case (setq token (read (current-buffer)))
2222 (+ (setq imap-continuation
2223 (or (buffer-substring (min (point-max) (1+ (point)))
2224 (point-max))
2225 t)))
2226 (* (case (prog1 (setq token (read (current-buffer)))
2227 (imap-forward))
2228 (OK (imap-parse-resp-text))
2229 (NO (imap-parse-resp-text))
2230 (BAD (imap-parse-resp-text))
2231 (BYE (imap-parse-resp-text))
2232 (FLAGS (imap-mailbox-put 'flags (imap-parse-flag-list)))
2233 (LIST (imap-parse-data-list 'list))
2234 (LSUB (imap-parse-data-list 'lsub))
2235 (SEARCH (imap-mailbox-put
2236 'search
2237 (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
2238 (STATUS (imap-parse-status))
2239 (CAPABILITY (setq imap-capability
2240 (read (concat "(" (upcase (buffer-substring
2241 (point) (point-max)))
2242 ")"))))
2243 (ID (setq imap-id (read (buffer-substring (point)
2244 (point-max)))))
2245 (ACL (imap-parse-acl))
2246 (t (case (prog1 (read (current-buffer))
2247 (imap-forward))
2248 (EXISTS (imap-mailbox-put 'exists token))
2249 (RECENT (imap-mailbox-put 'recent token))
2250 (EXPUNGE t)
2251 (FETCH (imap-parse-fetch token))
2252 (t (message "Garbage: %s" (buffer-string)))))))
2253 (t (let (status)
2254 (if (not (integerp token))
2255 (message "Garbage: %s" (buffer-string))
2256 (case (prog1 (setq status (read (current-buffer)))
2257 (imap-forward))
2258 (OK (progn
2259 (setq imap-reached-tag (max imap-reached-tag token))
2260 (imap-parse-resp-text)))
2261 (NO (progn
2262 (setq imap-reached-tag (max imap-reached-tag token))
2263 (save-excursion
2264 (imap-parse-resp-text))
2265 (let (code text)
2266 (when (eq (char-after) ?\[)
2267 (setq code (buffer-substring (point)
2268 (search-forward "]")))
2269 (imap-forward))
2270 (setq text (buffer-substring (point) (point-max)))
2271 (push (list token status code text)
2272 imap-failed-tags))))
2273 (BAD (progn
2274 (setq imap-reached-tag (max imap-reached-tag token))
2275 (save-excursion
2276 (imap-parse-resp-text))
2277 (let (code text)
2278 (when (eq (char-after) ?\[)
2279 (setq code (buffer-substring (point)
2280 (search-forward "]")))
2281 (imap-forward))
2282 (setq text (buffer-substring (point) (point-max)))
2283 (push (list token status code text) imap-failed-tags)
2284 (error "Internal error, tag %s status %s code %s text %s"
2285 token status code text))))
2286 (t (message "Garbage: %s" (buffer-string))))
2287 (when (assq token imap-callbacks)
2288 (funcall (cdr (assq token imap-callbacks)) token status)
2289 (setq imap-callbacks
2290 (imap-remassoc token imap-callbacks)))))))))
2292 ;; resp-text = ["[" resp-text-code "]" SP] text
2294 ;; text = 1*TEXT-CHAR
2296 ;; TEXT-CHAR = <any CHAR except CR and LF>
2298 (defun imap-parse-resp-text ()
2299 (imap-parse-resp-text-code))
2301 ;; resp-text-code = "ALERT" /
2302 ;; "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2303 ;; "NEWNAME" SP string SP string /
2304 ;; "PARSE" /
2305 ;; "PERMANENTFLAGS" SP "("
2306 ;; [flag-perm *(SP flag-perm)] ")" /
2307 ;; "READ-ONLY" /
2308 ;; "READ-WRITE" /
2309 ;; "TRYCREATE" /
2310 ;; "UIDNEXT" SP nz-number /
2311 ;; "UIDVALIDITY" SP nz-number /
2312 ;; "UNSEEN" SP nz-number /
2313 ;; resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2315 ;; resp_code_apnd = "APPENDUID" SPACE nz_number SPACE uniqueid
2317 ;; resp_code_copy = "COPYUID" SPACE nz_number SPACE set SPACE set
2319 ;; set = sequence-num / (sequence-num ":" sequence-num) /
2320 ;; (set "," set)
2321 ;; ; Identifies a set of messages. For message
2322 ;; ; sequence numbers, these are consecutive
2323 ;; ; numbers from 1 to the number of messages in
2324 ;; ; the mailbox
2325 ;; ; Comma delimits individual numbers, colon
2326 ;; ; delimits between two numbers inclusive.
2327 ;; ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2328 ;; ; 14,15 for a mailbox with 15 messages.
2330 ;; sequence-num = nz-number / "*"
2331 ;; ; * is the largest number in use. For message
2332 ;; ; sequence numbers, it is the number of messages
2333 ;; ; in the mailbox. For unique identifiers, it is
2334 ;; ; the unique identifier of the last message in
2335 ;; ; the mailbox.
2337 ;; flag-perm = flag / "\*"
2339 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2340 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2341 ;; ; Does not include "\Recent"
2343 ;; flag-extension = "\" atom
2344 ;; ; Future expansion. Client implementations
2345 ;; ; MUST accept flag-extension flags. Server
2346 ;; ; implementations MUST NOT generate
2347 ;; ; flag-extension flags except as defined by
2348 ;; ; future standard or standards-track
2349 ;; ; revisions of this specification.
2351 ;; flag-keyword = atom
2353 ;; resp-text-atom = 1*<any ATOM-CHAR except "]">
2355 (defun imap-parse-resp-text-code ()
2356 ;; xxx next line for stalker communigate pro 3.3.1 bug
2357 (when (looking-at " \\[")
2358 (imap-forward))
2359 (when (eq (char-after) ?\[)
2360 (imap-forward)
2361 (cond ((search-forward "PERMANENTFLAGS " nil t)
2362 (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2363 ((search-forward "UIDNEXT \\([0-9]+\\)" nil t)
2364 (imap-mailbox-put 'uidnext (match-string 1)))
2365 ((search-forward "UNSEEN " nil t)
2366 (imap-mailbox-put 'first-unseen (read (current-buffer))))
2367 ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2368 (imap-mailbox-put 'uidvalidity (match-string 1)))
2369 ((search-forward "READ-ONLY" nil t)
2370 (imap-mailbox-put 'read-only t))
2371 ((search-forward "NEWNAME " nil t)
2372 (let (oldname newname)
2373 (setq oldname (imap-parse-string))
2374 (imap-forward)
2375 (setq newname (imap-parse-string))
2376 (imap-mailbox-put 'newname newname oldname)))
2377 ((search-forward "TRYCREATE" nil t)
2378 (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2379 ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2380 (imap-mailbox-put 'appenduid
2381 (list (match-string 1)
2382 (string-to-number (match-string 2)))
2383 imap-current-target-mailbox))
2384 ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2385 (imap-mailbox-put 'copyuid (list (match-string 1)
2386 (match-string 2)
2387 (match-string 3))
2388 imap-current-target-mailbox))
2389 ((search-forward "ALERT] " nil t)
2390 (message "Imap server %s information: %s" imap-server
2391 (buffer-substring (point) (point-max)))))))
2393 ;; mailbox-list = "(" [mbx-list-flags] ")" SP
2394 ;; (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2396 ;; mbx-list-flags = *(mbx-list-oflag SP) mbx-list-sflag
2397 ;; *(SP mbx-list-oflag) /
2398 ;; mbx-list-oflag *(SP mbx-list-oflag)
2400 ;; mbx-list-oflag = "\Noinferiors" / flag-extension
2401 ;; ; Other flags; multiple possible per LIST response
2403 ;; mbx-list-sflag = "\Noselect" / "\Marked" / "\Unmarked"
2404 ;; ; Selectability flags; only one per LIST response
2406 ;; QUOTED-CHAR = <any TEXT-CHAR except quoted-specials> /
2407 ;; "\" quoted-specials
2409 ;; quoted-specials = DQUOTE / "\"
2411 (defun imap-parse-data-list (type)
2412 (let (flags delimiter mailbox)
2413 (setq flags (imap-parse-flag-list))
2414 (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2415 (setq delimiter (match-string 1))
2416 (goto-char (1+ (match-end 0)))
2417 (when (setq mailbox (imap-parse-mailbox))
2418 (imap-mailbox-put type t mailbox)
2419 (imap-mailbox-put 'list-flags flags mailbox)
2420 (imap-mailbox-put 'delimiter delimiter mailbox)))))
2422 ;; msg_att ::= "(" 1#("ENVELOPE" SPACE envelope /
2423 ;; "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2424 ;; "INTERNALDATE" SPACE date_time /
2425 ;; "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2426 ;; "RFC822.SIZE" SPACE number /
2427 ;; "BODY" ["STRUCTURE"] SPACE body /
2428 ;; "BODY" section ["<" number ">"] SPACE nstring /
2429 ;; "UID" SPACE uniqueid) ")"
2431 ;; date_time ::= <"> date_day_fixed "-" date_month "-" date_year
2432 ;; SPACE time SPACE zone <">
2434 ;; section ::= "[" [section_text / (nz_number *["." nz_number]
2435 ;; ["." (section_text / "MIME")])] "]"
2437 ;; section_text ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2438 ;; SPACE header_list / "TEXT"
2440 ;; header_fld_name ::= astring
2442 ;; header_list ::= "(" 1#header_fld_name ")"
2444 (defsubst imap-parse-header-list ()
2445 (when (eq (char-after) ?\()
2446 (let (strlist)
2447 (while (not (eq (char-after) ?\)))
2448 (imap-forward)
2449 (push (imap-parse-astring) strlist))
2450 (imap-forward)
2451 (nreverse strlist))))
2453 (defsubst imap-parse-fetch-body-section ()
2454 (let ((section
2455 (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2456 (if (eq (char-before) ? )
2457 (prog1
2458 (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2459 (search-forward "]" nil t))
2460 section)))
2462 (defun imap-parse-fetch (response)
2463 (when (eq (char-after) ?\()
2464 (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2465 rfc822size body bodydetail bodystructure flags-empty)
2466 ;; Courier can insert spurious blank characters which will
2467 ;; confuse `read', so skip past them.
2468 (while (let ((moved (skip-chars-forward " \t")))
2469 (prog1 (not (eq (char-after) ?\)))
2470 (unless (= moved 0) (backward-char))))
2471 (imap-forward)
2472 (let ((token (read (current-buffer))))
2473 (imap-forward)
2474 (cond ((eq token 'UID)
2475 (setq uid (condition-case ()
2476 (read (current-buffer))
2477 (error))))
2478 ((eq token 'FLAGS)
2479 (setq flags (imap-parse-flag-list))
2480 (if (not flags)
2481 (setq flags-empty 't)))
2482 ((eq token 'ENVELOPE)
2483 (setq envelope (imap-parse-envelope)))
2484 ((eq token 'INTERNALDATE)
2485 (setq internaldate (imap-parse-string)))
2486 ((eq token 'RFC822)
2487 (setq rfc822 (imap-parse-nstring)))
2488 ((eq token 'RFC822.HEADER)
2489 (setq rfc822header (imap-parse-nstring)))
2490 ((eq token 'RFC822.TEXT)
2491 (setq rfc822text (imap-parse-nstring)))
2492 ((eq token 'RFC822.SIZE)
2493 (setq rfc822size (read (current-buffer))))
2494 ((eq token 'BODY)
2495 (if (eq (char-before) ?\[)
2496 (push (list
2497 (upcase (imap-parse-fetch-body-section))
2498 (and (eq (char-after) ?<)
2499 (buffer-substring (1+ (point))
2500 (search-forward ">" nil t)))
2501 (progn (imap-forward)
2502 (imap-parse-nstring)))
2503 bodydetail)
2504 (setq body (imap-parse-body))))
2505 ((eq token 'BODYSTRUCTURE)
2506 (setq bodystructure (imap-parse-body))))))
2507 (when uid
2508 (setq imap-current-message uid)
2509 (imap-message-put uid 'UID uid)
2510 (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2511 (and envelope (imap-message-put uid 'ENVELOPE envelope))
2512 (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2513 (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2514 (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2515 (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2516 (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2517 (and body (imap-message-put uid 'BODY body))
2518 (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2519 (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2520 (run-hooks 'imap-fetch-data-hook)))))
2522 ;; mailbox-data = ...
2523 ;; "STATUS" SP mailbox SP "("
2524 ;; [status-att SP number
2525 ;; *(SP status-att SP number)] ")"
2526 ;; ...
2528 ;; status-att = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2529 ;; "UNSEEN"
2531 (defun imap-parse-status ()
2532 (let ((mailbox (imap-parse-mailbox)))
2533 (if (eq (char-after) ? )
2534 (forward-char))
2535 (when (and mailbox (eq (char-after) ?\())
2536 (while (and (not (eq (char-after) ?\)))
2537 (or (forward-char) t)
2538 (looking-at "\\([A-Za-z]+\\) "))
2539 (let ((token (upcase (match-string 1))))
2540 (goto-char (match-end 0))
2541 (cond ((string= token "MESSAGES")
2542 (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2543 ((string= token "RECENT")
2544 (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2545 ((string= token "UIDNEXT")
2546 (and (looking-at "[0-9]+")
2547 (imap-mailbox-put 'uidnext (match-string 0) mailbox)
2548 (goto-char (match-end 0))))
2549 ((string= token "UIDVALIDITY")
2550 (and (looking-at "[0-9]+")
2551 (imap-mailbox-put 'uidvalidity (match-string 0) mailbox)
2552 (goto-char (match-end 0))))
2553 ((string= token "UNSEEN")
2554 (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2556 (message "Unknown status data %s in mailbox %s ignored"
2557 token mailbox)
2558 (read (current-buffer)))))))))
2560 ;; acl_data ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2561 ;; rights)
2563 ;; identifier ::= astring
2565 ;; rights ::= astring
2567 (defun imap-parse-acl ()
2568 (let ((mailbox (imap-parse-mailbox))
2569 identifier rights acl)
2570 (while (eq (char-after) ?\ )
2571 (imap-forward)
2572 (setq identifier (imap-parse-astring))
2573 (imap-forward)
2574 (setq rights (imap-parse-astring))
2575 (setq acl (append acl (list (cons identifier rights)))))
2576 (imap-mailbox-put 'acl acl mailbox)))
2578 ;; flag-list = "(" [flag *(SP flag)] ")"
2580 ;; flag = "\Answered" / "\Flagged" / "\Deleted" /
2581 ;; "\Seen" / "\Draft" / flag-keyword / flag-extension
2582 ;; ; Does not include "\Recent"
2584 ;; flag-keyword = atom
2586 ;; flag-extension = "\" atom
2587 ;; ; Future expansion. Client implementations
2588 ;; ; MUST accept flag-extension flags. Server
2589 ;; ; implementations MUST NOT generate
2590 ;; ; flag-extension flags except as defined by
2591 ;; ; future standard or standards-track
2592 ;; ; revisions of this specification.
2594 (defun imap-parse-flag-list ()
2595 (let (flag-list start)
2596 (assert (eq (char-after) ?\() nil "In imap-parse-flag-list 1")
2597 (while (and (not (eq (char-after) ?\)))
2598 (setq start (progn
2599 (imap-forward)
2600 ;; next line for Courier IMAP bug.
2601 (skip-chars-forward " ")
2602 (point)))
2603 (> (skip-chars-forward "^ )" (point-at-eol)) 0))
2604 (push (buffer-substring start (point)) flag-list))
2605 (assert (eq (char-after) ?\)) nil "In imap-parse-flag-list 2")
2606 (imap-forward)
2607 (nreverse flag-list)))
2609 ;; envelope = "(" env-date SP env-subject SP env-from SP env-sender SP
2610 ;; env-reply-to SP env-to SP env-cc SP env-bcc SP
2611 ;; env-in-reply-to SP env-message-id ")"
2613 ;; env-bcc = "(" 1*address ")" / nil
2615 ;; env-cc = "(" 1*address ")" / nil
2617 ;; env-date = nstring
2619 ;; env-from = "(" 1*address ")" / nil
2621 ;; env-in-reply-to = nstring
2623 ;; env-message-id = nstring
2625 ;; env-reply-to = "(" 1*address ")" / nil
2627 ;; env-sender = "(" 1*address ")" / nil
2629 ;; env-subject = nstring
2631 ;; env-to = "(" 1*address ")" / nil
2633 (defun imap-parse-envelope ()
2634 (when (eq (char-after) ?\()
2635 (imap-forward)
2636 (vector (prog1 (imap-parse-nstring) ;; date
2637 (imap-forward))
2638 (prog1 (imap-parse-nstring) ;; subject
2639 (imap-forward))
2640 (prog1 (imap-parse-address-list) ;; from
2641 (imap-forward))
2642 (prog1 (imap-parse-address-list) ;; sender
2643 (imap-forward))
2644 (prog1 (imap-parse-address-list) ;; reply-to
2645 (imap-forward))
2646 (prog1 (imap-parse-address-list) ;; to
2647 (imap-forward))
2648 (prog1 (imap-parse-address-list) ;; cc
2649 (imap-forward))
2650 (prog1 (imap-parse-address-list) ;; bcc
2651 (imap-forward))
2652 (prog1 (imap-parse-nstring) ;; in-reply-to
2653 (imap-forward))
2654 (prog1 (imap-parse-nstring) ;; message-id
2655 (imap-forward)))))
2657 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2659 (defsubst imap-parse-string-list ()
2660 (cond ((eq (char-after) ?\() ;; body-fld-param
2661 (let (strlist str)
2662 (imap-forward)
2663 (while (setq str (imap-parse-string))
2664 (push str strlist)
2665 ;; buggy stalker communigate pro 3.0 doesn't print SPC
2666 ;; between body-fld-param's sometimes
2667 (or (eq (char-after) ?\")
2668 (imap-forward)))
2669 (nreverse strlist)))
2670 ((imap-parse-nil)
2671 nil)))
2673 ;; body-extension = nstring / number /
2674 ;; "(" body-extension *(SP body-extension) ")"
2675 ;; ; Future expansion. Client implementations
2676 ;; ; MUST accept body-extension fields. Server
2677 ;; ; implementations MUST NOT generate
2678 ;; ; body-extension fields except as defined by
2679 ;; ; future standard or standards-track
2680 ;; ; revisions of this specification.
2682 (defun imap-parse-body-extension ()
2683 (if (eq (char-after) ?\()
2684 (let (b-e)
2685 (imap-forward)
2686 (push (imap-parse-body-extension) b-e)
2687 (while (eq (char-after) ?\ )
2688 (imap-forward)
2689 (push (imap-parse-body-extension) b-e))
2690 (assert (eq (char-after) ?\)) nil "In imap-parse-body-extension")
2691 (imap-forward)
2692 (nreverse b-e))
2693 (or (imap-parse-number)
2694 (imap-parse-nstring))))
2696 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2697 ;; *(SP body-extension)]]
2698 ;; ; MUST NOT be returned on non-extensible
2699 ;; ; "BODY" fetch
2701 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2702 ;; *(SP body-extension)]]
2703 ;; ; MUST NOT be returned on non-extensible
2704 ;; ; "BODY" fetch
2706 (defsubst imap-parse-body-ext ()
2707 (let (ext)
2708 (when (eq (char-after) ?\ ) ;; body-fld-dsp
2709 (imap-forward)
2710 (let (dsp)
2711 (if (eq (char-after) ?\()
2712 (progn
2713 (imap-forward)
2714 (push (imap-parse-string) dsp)
2715 (imap-forward)
2716 (push (imap-parse-string-list) dsp)
2717 (imap-forward))
2718 ;; With assert, the code might not be eval'd.
2719 ;; (assert (imap-parse-nil) t "In imap-parse-body-ext")
2720 (imap-parse-nil))
2721 (push (nreverse dsp) ext))
2722 (when (eq (char-after) ?\ ) ;; body-fld-lang
2723 (imap-forward)
2724 (if (eq (char-after) ?\()
2725 (push (imap-parse-string-list) ext)
2726 (push (imap-parse-nstring) ext))
2727 (while (eq (char-after) ?\ ) ;; body-extension
2728 (imap-forward)
2729 (setq ext (append (imap-parse-body-extension) ext)))))
2730 ext))
2732 ;; body = "(" body-type-1part / body-type-mpart ")"
2734 ;; body-ext-1part = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2735 ;; *(SP body-extension)]]
2736 ;; ; MUST NOT be returned on non-extensible
2737 ;; ; "BODY" fetch
2739 ;; body-ext-mpart = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2740 ;; *(SP body-extension)]]
2741 ;; ; MUST NOT be returned on non-extensible
2742 ;; ; "BODY" fetch
2744 ;; body-fields = body-fld-param SP body-fld-id SP body-fld-desc SP
2745 ;; body-fld-enc SP body-fld-octets
2747 ;; body-fld-desc = nstring
2749 ;; body-fld-dsp = "(" string SP body-fld-param ")" / nil
2751 ;; body-fld-enc = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2752 ;; "QUOTED-PRINTABLE") DQUOTE) / string
2754 ;; body-fld-id = nstring
2756 ;; body-fld-lang = nstring / "(" string *(SP string) ")"
2758 ;; body-fld-lines = number
2760 ;; body-fld-md5 = nstring
2762 ;; body-fld-octets = number
2764 ;; body-fld-param = "(" string SP string *(SP string SP string) ")" / nil
2766 ;; body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2767 ;; [SP body-ext-1part]
2769 ;; body-type-basic = media-basic SP body-fields
2770 ;; ; MESSAGE subtype MUST NOT be "RFC822"
2772 ;; body-type-msg = media-message SP body-fields SP envelope
2773 ;; SP body SP body-fld-lines
2775 ;; body-type-text = media-text SP body-fields SP body-fld-lines
2777 ;; body-type-mpart = 1*body SP media-subtype
2778 ;; [SP body-ext-mpart]
2780 ;; media-basic = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2781 ;; "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2782 ;; ; Defined in [MIME-IMT]
2784 ;; media-message = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2785 ;; ; Defined in [MIME-IMT]
2787 ;; media-subtype = string
2788 ;; ; Defined in [MIME-IMT]
2790 ;; media-text = DQUOTE "TEXT" DQUOTE SP media-subtype
2791 ;; ; Defined in [MIME-IMT]
2793 (defun imap-parse-body ()
2794 (let (body)
2795 (when (eq (char-after) ?\()
2796 (imap-forward)
2797 (if (eq (char-after) ?\()
2798 (let (subbody)
2799 (while (and (eq (char-after) ?\()
2800 (setq subbody (imap-parse-body)))
2801 ;; buggy stalker communigate pro 3.0 inserts a SPC between
2802 ;; parts in multiparts
2803 (when (and (eq (char-after) ?\ )
2804 (eq (char-after (1+ (point))) ?\())
2805 (imap-forward))
2806 (push subbody body))
2807 (imap-forward)
2808 (push (imap-parse-string) body) ;; media-subtype
2809 (when (eq (char-after) ?\ ) ;; body-ext-mpart:
2810 (imap-forward)
2811 (if (eq (char-after) ?\() ;; body-fld-param
2812 (push (imap-parse-string-list) body)
2813 (push (and (imap-parse-nil) nil) body))
2814 (setq body
2815 (append (imap-parse-body-ext) body))) ;; body-ext-...
2816 (assert (eq (char-after) ?\)) nil "In imap-parse-body")
2817 (imap-forward)
2818 (nreverse body))
2820 (push (imap-parse-string) body) ;; media-type
2821 (imap-forward)
2822 (push (imap-parse-string) body) ;; media-subtype
2823 (imap-forward)
2824 ;; next line for Sun SIMS bug
2825 (and (eq (char-after) ? ) (imap-forward))
2826 (if (eq (char-after) ?\() ;; body-fld-param
2827 (push (imap-parse-string-list) body)
2828 (push (and (imap-parse-nil) nil) body))
2829 (imap-forward)
2830 (push (imap-parse-nstring) body) ;; body-fld-id
2831 (imap-forward)
2832 (push (imap-parse-nstring) body) ;; body-fld-desc
2833 (imap-forward)
2834 ;; Next `or' for Sun SIMS bug. It regards body-fld-enc as a
2835 ;; nstring and returns nil instead of defaulting back to 7BIT
2836 ;; as the standard says.
2837 ;; Exchange (2007, at least) does this as well.
2838 (push (or (imap-parse-nstring) "7BIT") body) ;; body-fld-enc
2839 (imap-forward)
2840 ;; Exchange 2007 can return -1, contrary to the spec...
2841 (if (eq (char-after) ?-)
2842 (progn
2843 (skip-chars-forward "-0-9")
2844 (push nil body))
2845 (push (imap-parse-number) body)) ;; body-fld-octets
2847 ;; Ok, we're done parsing the required parts, what comes now is one of
2848 ;; three things:
2850 ;; envelope (then we're parsing body-type-msg)
2851 ;; body-fld-lines (then we're parsing body-type-text)
2852 ;; body-ext-1part (then we're parsing body-type-basic)
2854 ;; The problem is that the two first are in turn optionally followed
2855 ;; by the third. So we parse the first two here (if there are any)...
2857 (when (eq (char-after) ?\ )
2858 (imap-forward)
2859 (let (lines)
2860 (cond ((eq (char-after) ?\() ;; body-type-msg:
2861 (push (imap-parse-envelope) body) ;; envelope
2862 (imap-forward)
2863 (push (imap-parse-body) body) ;; body
2864 ;; buggy stalker communigate pro 3.0 doesn't print
2865 ;; number of lines in message/rfc822 attachment
2866 (if (eq (char-after) ?\))
2867 (push 0 body)
2868 (imap-forward)
2869 (push (imap-parse-number) body))) ;; body-fld-lines
2870 ((setq lines (imap-parse-number)) ;; body-type-text:
2871 (push lines body)) ;; body-fld-lines
2873 (backward-char))))) ;; no match...
2875 ;; ...and then parse the third one here...
2877 (when (eq (char-after) ?\ ) ;; body-ext-1part:
2878 (imap-forward)
2879 (push (imap-parse-nstring) body) ;; body-fld-md5
2880 (setq body (append (imap-parse-body-ext) body))) ;; body-ext-1part..
2882 (assert (eq (char-after) ?\)) nil "In imap-parse-body 2")
2883 (imap-forward)
2884 (nreverse body)))))
2886 (when imap-debug ; (untrace-all)
2887 (require 'trace)
2888 (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2889 (mapc (lambda (f) (trace-function-background f imap-debug-buffer))
2891 imap-utf7-encode
2892 imap-utf7-decode
2893 imap-error-text
2894 imap-kerberos4s-p
2895 imap-kerberos4-open
2896 imap-network-p
2897 imap-network-open
2898 imap-interactive-login
2899 imap-kerberos4a-p
2900 imap-kerberos4-auth
2901 imap-cram-md5-p
2902 imap-cram-md5-auth
2903 imap-login-p
2904 imap-login-auth
2905 imap-anonymous-p
2906 imap-anonymous-auth
2907 imap-open-1
2908 imap-open
2909 imap-opened
2910 imap-ping-server
2911 imap-authenticate
2912 imap-close
2913 imap-capability
2914 imap-namespace
2915 imap-send-command-wait
2916 imap-mailbox-put
2917 imap-mailbox-get
2918 imap-mailbox-map-1
2919 imap-mailbox-map
2920 imap-current-mailbox
2921 imap-current-mailbox-p-1
2922 imap-current-mailbox-p
2923 imap-mailbox-select-1
2924 imap-mailbox-select
2925 imap-mailbox-examine-1
2926 imap-mailbox-examine
2927 imap-mailbox-unselect
2928 imap-mailbox-expunge
2929 imap-mailbox-close
2930 imap-mailbox-create-1
2931 imap-mailbox-create
2932 imap-mailbox-delete
2933 imap-mailbox-rename
2934 imap-mailbox-lsub
2935 imap-mailbox-list
2936 imap-mailbox-subscribe
2937 imap-mailbox-unsubscribe
2938 imap-mailbox-status
2939 imap-mailbox-acl-get
2940 imap-mailbox-acl-set
2941 imap-mailbox-acl-delete
2942 imap-current-message
2943 imap-list-to-message-set
2944 imap-fetch-asynch
2945 imap-fetch
2946 imap-fetch-safe
2947 imap-message-put
2948 imap-message-get
2949 imap-message-map
2950 imap-search
2951 imap-message-flag-permanent-p
2952 imap-message-flags-set
2953 imap-message-flags-del
2954 imap-message-flags-add
2955 imap-message-copyuid-1
2956 imap-message-copyuid
2957 imap-message-copy
2958 imap-message-appenduid-1
2959 imap-message-appenduid
2960 imap-message-append
2961 imap-body-lines
2962 imap-envelope-from
2963 imap-send-command-1
2964 imap-send-command
2965 imap-wait-for-tag
2966 imap-sentinel
2967 imap-find-next-line
2968 imap-arrival-filter
2969 imap-parse-greeting
2970 imap-parse-response
2971 imap-parse-resp-text
2972 imap-parse-resp-text-code
2973 imap-parse-data-list
2974 imap-parse-fetch
2975 imap-parse-status
2976 imap-parse-acl
2977 imap-parse-flag-list
2978 imap-parse-envelope
2979 imap-parse-body-extension
2980 imap-parse-body
2983 (provide 'imap)
2985 ;;; imap.el ends here