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