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