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