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