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