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