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