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