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