Synch with the released version of Oort Gnus v0.05. After translating
[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 actually 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-wait "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-wait "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                         (cond ((eq system-type 'windows-nt)
608                                (let (selective-display
609                                      (coding-system-for-write 'binary)
610                                      (coding-system-for-read 'raw-text-dos)
611                                      (output-coding-system 'binary)
612                                      (input-coding-system 'raw-text-dos))
613                                  (open-ssl-stream name buffer server port)))
614                               (t
615                                (as-binary-process
616                                 (open-ssl-stream name buffer server port))))
617                       (error nil)))
618           (with-current-buffer buffer
619             (goto-char (point-min))
620             (while (and (memq (process-status process) '(open run))
621                         (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
622                         (goto-char (point-max))
623                         (forward-line -1)
624                         (not (imap-parse-greeting)))
625               (accept-process-output process 1)
626               (sit-for 1))
627             (and imap-log
628                  (with-current-buffer (get-buffer-create imap-log-buffer)
629                    (buffer-disable-undo)
630                    (goto-char (point-max))
631                    (insert-buffer-substring buffer)))
632             (erase-buffer)
633             (when (memq (process-status process) '(open run))
634               (setq done process))))))
635     (if done
636         (progn
637           (message "imap: Opening SSL connection with `%s'...done" cmd)
638           done)
639       (message "imap: Opening SSL connection with `%s'...failed" cmd)
640       nil)))
641
642 (defun imap-network-p (buffer)
643   t)
644
645 (defun imap-network-open (name buffer server port)
646   (let* ((port (or port imap-default-port))
647          (process (open-network-stream-as-binary name buffer server port)))
648     (when process
649       (while (and (memq (process-status process) '(open run))
650                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
651                   (goto-char (point-min))
652                   (not (imap-parse-greeting)))
653         (accept-process-output process 1)
654         (sit-for 1))
655       (and imap-log
656            (with-current-buffer (get-buffer-create imap-log-buffer)
657              (buffer-disable-undo)
658              (goto-char (point-max))
659              (insert-buffer-substring buffer)))
660       (when (memq (process-status process) '(open run))
661         process))))
662
663 (defun imap-shell-p (buffer)
664   nil)
665
666 (defun imap-shell-open (name buffer server port)
667   (let ((cmds imap-shell-program)
668         cmd done)
669     (while (and (not done) (setq cmd (pop cmds)))
670       (message "imap: Opening IMAP connection with `%s'..." cmd)
671       (setq imap-client-eol "\n")
672       (let* ((port (or port imap-default-port))
673              (process (as-binary-process
674                        (start-process
675                         name buffer shell-file-name shell-command-switch
676                         (format-spec
677                          cmd
678                          (format-spec-make
679                           ?s server
680                           ?g imap-shell-host
681                           ?p (number-to-string port)
682                           ?l imap-default-user))))))
683         (when process
684           (while (and (memq (process-status process) '(open run))
685                       (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
686                       (goto-char (point-min))
687                       (not (imap-parse-greeting)))
688             (accept-process-output process 1)
689             (sit-for 1))
690           (and imap-log
691                (with-current-buffer (get-buffer-create imap-log-buffer)
692                  (buffer-disable-undo)
693                  (goto-char (point-max))
694                  (insert-buffer-substring buffer)))
695           (erase-buffer)
696           (when (memq (process-status process) '(open run))
697             (setq done process)))))
698     (if done
699         (progn
700           (message "imap: Opening IMAP connection with `%s'...done" cmd)
701           done)
702       (message "imap: Opening IMAP connection with `%s'...failed" cmd)
703       nil)))
704
705 (defun imap-starttls-p (buffer)
706   (imap-capability 'STARTTLS buffer))
707
708 (defun imap-starttls-open (name buffer server port)
709   (let* ((port (or port imap-default-port))
710          (process (as-binary-process
711                    (starttls-open-stream name buffer server port)))
712          done)
713     (message "imap: Connecting with STARTTLS...")
714     (when process
715       (while (and (memq (process-status process) '(open run))
716                   (set-buffer buffer) ;; XXX "blue moon" nntp.el bug
717                   (goto-char (point-min))
718                   (not (imap-parse-greeting)))
719         (accept-process-output process 1)
720         (sit-for 1))
721       (and imap-log
722            (with-current-buffer (get-buffer-create imap-log-buffer)
723              (buffer-disable-undo)
724              (goto-char (point-max))
725              (insert-buffer-substring buffer)))
726       (let ((imap-process process))
727         (unwind-protect
728             (progn
729               (set-process-filter imap-process 'imap-arrival-filter)
730               (when (and (eq imap-stream 'starttls)
731                          (imap-ok-p (imap-send-command-wait "STARTTLS")))
732                 (starttls-negotiate imap-process)))
733           (set-process-filter imap-process nil)))
734       (when (memq (process-status process) '(open run))
735         (setq done process)))
736     (if done
737         (progn
738           (message "imap: Connecting with STARTTLS...done")
739           done)
740       (message "imap: Connecting with STARTTLS...failed")
741       nil)))
742
743 ;; Server functions; authenticator stuff:
744
745 (defun imap-interactive-login (buffer loginfunc)
746   "Login to server in BUFFER.
747 LOGINFUNC is passed a username and a password, it should return t if
748 it where sucessful authenticating itself to the server, nil otherwise.
749 Returns t if login was successful, nil otherwise."
750   (with-current-buffer buffer
751     (make-local-variable 'imap-username)
752     (make-local-variable 'imap-password)
753     (let (user passwd ret)
754       ;;      (condition-case ()
755       (while (or (not user) (not passwd))
756         (setq user (or imap-username
757                        (read-from-minibuffer
758                         (concat "IMAP username for " imap-server 
759                                 " (using stream `" (symbol-name imap-stream)
760                                 "'): ")
761                         (or user imap-default-user))))
762         (setq passwd (or imap-password
763                          (imap-read-passwd
764                           (concat "IMAP password for " user "@"
765                                   imap-server " (using authenticator `"
766                                   (symbol-name imap-auth) "'): "))))
767         (when (and user passwd)
768           (if (funcall loginfunc user passwd)
769               (progn
770                 (setq ret t
771                       imap-username user)
772                 (if (and (not imap-password)
773                          (y-or-n-p "Store password for this session? "))
774                     (setq imap-password passwd)))
775             (message "Login failed...")
776             (setq passwd nil)
777             (sit-for 1))))
778       ;;        (quit (with-current-buffer buffer
779       ;;                (setq user nil
780       ;;                      passwd nil)))
781       ;;        (error (with-current-buffer buffer
782       ;;                 (setq user nil
783       ;;                       passwd nil))))
784       ret)))
785
786 (defun imap-gssapi-auth-p (buffer)
787   (and (imap-capability 'AUTH=GSSAPI buffer)
788        (eq imap-stream 'gssapi)))
789
790 (defun imap-gssapi-auth (buffer)
791   (message "imap: Authenticating using GSSAPI...%s"
792            (if (eq imap-stream 'gssapi) "done" "failed"))
793   (eq imap-stream 'gssapi))
794
795 (defun imap-kerberos4-auth-p (buffer)
796   (and (imap-capability 'AUTH=KERBEROS_V4 buffer)
797        (eq imap-stream 'kerberos4)))
798
799 (defun imap-kerberos4-auth (buffer)
800   (message "imap: Authenticating using Kerberos 4...%s"
801            (if (eq imap-stream 'kerberos4) "done" "failed"))
802   (eq imap-stream 'kerberos4))
803
804 (defun imap-cram-md5-p (buffer)
805   (imap-capability 'AUTH=CRAM-MD5 buffer))
806
807 (defun imap-cram-md5-auth (buffer)
808   "Login to server using the AUTH CRAM-MD5 method."
809   (message "imap: Authenticating using CRAM-MD5...")
810   (let ((done (imap-interactive-login
811                buffer
812                (lambda (user passwd)
813                  (imap-ok-p
814                   (imap-send-command-wait
815                    (list
816                     "AUTHENTICATE CRAM-MD5"
817                     (lambda (challenge)
818                       (let* ((decoded (base64-decode-string challenge))
819                              (hash-function
820                               (if (and (featurep 'xemacs)
821                                        (>= (function-max-args 'md5) 4))
822                                   (lambda (object &optional start end)
823                                     (md5 object start end 'binary))
824                                 'md5))
825                              (hash (rfc2104-hash hash-function 64 16
826                                                  passwd decoded))
827                              (response (concat user " " hash))
828                              (encoded (base64-encode-string response)))
829                         encoded)))))))))
830     (if done
831         (message "imap: Authenticating using CRAM-MD5...done")
832       (message "imap: Authenticating using CRAM-MD5...failed"))))
833
834 (defun imap-login-p (buffer)
835   (and (not (imap-capability 'LOGINDISABLED buffer))
836        (not (imap-capability 'X-LOGIN-CMD-DISABLED buffer))))
837
838 (defun imap-login-auth (buffer)
839   "Login to server using the LOGIN command."
840   (message "imap: Plaintext authentication...")
841   (imap-interactive-login buffer
842                           (lambda (user passwd)
843                             (imap-ok-p (imap-send-command-wait
844                                         (concat "LOGIN \"" user "\" \""
845                                                 passwd "\""))))))
846
847 (defun imap-anonymous-p (buffer)
848   t)
849
850 (defun imap-anonymous-auth (buffer)
851   (message "imap: Loging in anonymously...")
852   (with-current-buffer buffer
853     (imap-ok-p (imap-send-command-wait
854                 (concat "LOGIN anonymous \"" (concat (user-login-name) "@"
855                                                      (system-name)) "\"")))))
856
857 (defun imap-digest-md5-p (buffer)
858   (and (imap-capability 'AUTH=DIGEST-MD5 buffer)
859        (condition-case ()
860            (require 'digest-md5)
861          (error nil))))
862
863 (defun imap-digest-md5-auth (buffer)
864   "Login to server using the AUTH DIGEST-MD5 method."
865   (message "imap: Authenticating using DIGEST-MD5...")
866   (imap-interactive-login
867    buffer
868    (lambda (user passwd)
869      (let ((tag
870             (imap-send-command
871              (list
872               "AUTHENTICATE DIGEST-MD5"
873               (lambda (challenge)
874                 (base64-encode-string
875                  (sasl-digest-md5-digest-response
876                   (base64-decode-string challenge)
877                   user passwd "imap" imap-server)
878                  'no-line-break))))))
879        (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
880            nil
881          (setq imap-continuation nil)
882          (imap-send-command-1 "")
883          (imap-ok-p (imap-wait-for-tag tag)))))))
884
885 ;; Server functions:
886
887 (defun imap-open-1 (buffer)
888   (with-current-buffer buffer
889     (erase-buffer)
890     (setq imap-current-mailbox nil
891           imap-current-message nil
892           imap-state 'initial
893           imap-process (condition-case ()
894                            (funcall (nth 2 (assq imap-stream
895                                                  imap-stream-alist))
896                                     "imap" buffer imap-server imap-port)
897                          ((error quit) nil)))
898     (when imap-process
899       (set-process-filter imap-process 'imap-arrival-filter)
900       (set-process-sentinel imap-process 'imap-sentinel)
901       (while (and (eq imap-state 'initial)
902                   (memq (process-status imap-process) '(open run)))
903         (message "Waiting for response from %s..." imap-server)
904         (accept-process-output imap-process 1))
905       (message "Waiting for response from %s...done" imap-server)
906       (and (memq (process-status imap-process) '(open run))
907            imap-process))))
908
909 (defun imap-open (server &optional port stream auth buffer)
910   "Open a IMAP connection to host SERVER at PORT returning a buffer.
911 If PORT is unspecified, a default value is used (143 except
912 for SSL which use 993).
913 STREAM indicates the stream to use, see `imap-streams' for available
914 streams.  If nil, it choices the best stream the server is capable of.
915 AUTH indicates authenticator to use, see `imap-authenticators' for
916 available authenticators.  If nil, it choices the best stream the
917 server is capable of.
918 BUFFER can be a buffer or a name of a buffer, which is created if
919 necessery.  If nil, the buffer name is generated."
920   (setq buffer (or buffer (format " *imap* %s:%d" server (or port 0))))
921   (with-current-buffer (get-buffer-create buffer)
922     (if (imap-opened buffer)
923         (imap-close buffer))
924     (mapcar 'make-local-variable imap-local-variables)
925     (set-buffer-multibyte nil)
926     (buffer-disable-undo)
927     (setq imap-server (or server imap-server))
928     (setq imap-port (or port imap-port))
929     (setq imap-auth (or auth imap-auth))
930     (setq imap-stream (or stream imap-stream))
931     (message "imap: Connecting to %s..." imap-server)
932     (if (null (let ((imap-stream (or imap-stream imap-default-stream)))
933                 (imap-open-1 buffer)))
934         (progn
935           (message "imap: Connecting to %s...failed" imap-server)
936           nil)
937       (when (null imap-stream)
938         ;; Need to choose stream.
939         (let ((streams imap-streams))
940           (while (setq stream (pop streams))
941             ;; OK to use this stream?
942             (when (funcall (nth 1 (assq stream imap-stream-alist)) buffer)
943               ;; Stream changed?
944               (if (not (eq imap-default-stream stream))
945                   (with-current-buffer (get-buffer-create
946                                         (generate-new-buffer-name " *temp*"))
947                     (mapcar 'make-local-variable imap-local-variables)
948                     (set-buffer-multibyte nil)
949                     (imap-disable-multibyte)
950                     (buffer-disable-undo)
951                     (setq imap-server (or server imap-server))
952                     (setq imap-port imap-port)
953                     (setq imap-auth imap-auth)
954                     (message "imap: Reconnecting with stream `%s'..." stream)
955                     (if (null (let ((imap-stream stream))
956                                 (imap-open-1 (current-buffer))))
957                         (progn
958                           (kill-buffer (current-buffer))
959                           (message 
960                            "imap: Reconnecting with stream `%s'...failed" 
961                            stream))
962                       ;; We're done, kill the first connection
963                       (imap-close buffer)
964                       (kill-buffer buffer)
965                       (rename-buffer buffer)
966                       (message "imap: Reconnecting with stream `%s'...done"
967                                stream)
968                       (setq imap-stream stream)
969                       (setq imap-capability nil)
970                       (setq streams nil)))
971                 ;; We're done
972                 (message "imap: Connecting to %s...done" imap-server)
973                 (setq imap-stream stream)
974                 (setq imap-capability nil)
975                 (setq streams nil))))))
976       (when (imap-opened buffer)
977         (setq imap-mailbox-data (make-vector imap-mailbox-prime 0)))
978       (when imap-stream 
979         buffer))))
980
981 (defun imap-opened (&optional buffer)
982   "Return non-nil if connection to imap server in BUFFER is open.
983 If BUFFER is nil then the current buffer is used."
984   (and (setq buffer (get-buffer (or buffer (current-buffer))))
985        (buffer-live-p buffer)
986        (with-current-buffer buffer
987          (and imap-process
988               (memq (process-status imap-process) '(open run))))))
989
990 (defun imap-authenticate (&optional user passwd buffer)
991   "Authenticate to server in BUFFER, using current buffer if nil.
992 It uses the authenticator specified when opening the server.  If the
993 authenticator requires username/passwords, they are queried from the
994 user and optionally stored in the buffer.  If USER and/or PASSWD is
995 specified, the user will not be questioned and the username and/or
996 password is remembered in the buffer."
997   (with-current-buffer (or buffer (current-buffer))
998     (if (not (eq imap-state 'nonauth))
999         (or (eq imap-state 'auth)
1000             (eq imap-state 'select)
1001             (eq imap-state 'examine))
1002       (make-local-variable 'imap-username)
1003       (make-local-variable 'imap-password)
1004       (if user (setq imap-username user))
1005       (if passwd (setq imap-password passwd))
1006       (if imap-auth
1007           (and (funcall (nth 2 (assq imap-auth 
1008                                      imap-authenticator-alist)) buffer)
1009                (setq imap-state 'auth))
1010         ;; Choose authenticator.
1011         (let ((auths imap-authenticators)
1012               auth)
1013           (while (setq auth (pop auths))
1014             ;; OK to use authenticator?
1015             (when (funcall (nth 1 (assq auth imap-authenticator-alist)) buffer)
1016               (message "imap: Authenticating to `%s' using `%s'..."
1017                        imap-server auth)
1018               (setq imap-auth auth)
1019               (if (funcall (nth 2 (assq auth imap-authenticator-alist)) buffer)
1020                   (progn
1021                     (message "imap: Authenticating to `%s' using `%s'...done"
1022                              imap-server auth)
1023                     (setq auths nil))
1024                 (message "imap: Authenticating to `%s' using `%s'...failed"
1025                          imap-server auth)))))
1026         imap-state))))
1027
1028 (defun imap-close (&optional buffer)
1029   "Close connection to server in BUFFER.
1030 If BUFFER is nil, the current buffer is used."
1031   (with-current-buffer (or buffer (current-buffer))
1032     (when (imap-opened)
1033       (condition-case nil
1034           (imap-send-command-wait "LOGOUT")
1035         (quit nil)))
1036     (when (and imap-process
1037                (memq (process-status imap-process) '(open run)))
1038       (delete-process imap-process))
1039     (setq imap-current-mailbox nil
1040           imap-current-message nil
1041           imap-process nil)
1042     (erase-buffer)
1043     t))
1044
1045 (defun imap-capability (&optional identifier buffer)
1046   "Return a list of identifiers which server in BUFFER support.
1047 If IDENTIFIER, return non-nil if it's among the servers capabilities.
1048 If BUFFER is nil, the current buffer is assumed."
1049   (with-current-buffer (or buffer (current-buffer))
1050     (unless imap-capability
1051       (unless (imap-ok-p (imap-send-command-wait "CAPABILITY"))
1052         (setq imap-capability '(IMAP2))))
1053     (if identifier
1054         (memq (intern (upcase (symbol-name identifier))) imap-capability)
1055       imap-capability)))
1056
1057 (defun imap-namespace (&optional buffer)
1058   "Return a namespace hierarchy at server in BUFFER.
1059 If BUFFER is nil, the current buffer is assumed."
1060   (with-current-buffer (or buffer (current-buffer))
1061     (unless imap-namespace
1062       (when (imap-capability 'NAMESPACE)
1063         (imap-send-command-wait "NAMESPACE")))
1064     imap-namespace))
1065
1066 (defun imap-send-command-wait (command &optional buffer)
1067   (imap-wait-for-tag (imap-send-command command buffer) buffer))
1068
1069 \f
1070 ;; Mailbox functions:
1071
1072 (defun imap-mailbox-put (propname value &optional mailbox buffer)
1073   (with-current-buffer (or buffer (current-buffer))
1074     (if imap-mailbox-data
1075         (put (intern (or mailbox imap-current-mailbox) imap-mailbox-data)
1076              propname value)
1077       (error "Imap-mailbox-data is nil, prop %s value %s mailbox %s buffer %s"
1078              propname value mailbox (current-buffer)))
1079     t))
1080
1081 (defsubst imap-mailbox-get-1 (propname &optional mailbox)
1082   (get (intern-soft (or mailbox imap-current-mailbox) imap-mailbox-data)
1083        propname))
1084
1085 (defun imap-mailbox-get (propname &optional mailbox buffer)
1086   (let ((mailbox (imap-utf7-encode mailbox)))
1087     (with-current-buffer (or buffer (current-buffer))
1088       (imap-mailbox-get-1 propname (or mailbox imap-current-mailbox)))))
1089
1090 (defun imap-mailbox-map-1 (func &optional mailbox-decoder buffer)
1091   (with-current-buffer (or buffer (current-buffer))
1092     (let (result)
1093       (mapatoms
1094        (lambda (s)
1095          (push (funcall func (if mailbox-decoder
1096                                  (funcall mailbox-decoder (symbol-name s))
1097                                (symbol-name s))) result))
1098        imap-mailbox-data)
1099       result)))
1100
1101 (defun imap-mailbox-map (func &optional buffer)
1102   "Map a function across each mailbox in `imap-mailbox-data', returning a list.
1103 Function should take a mailbox name (a string) as
1104 the only argument."
1105   (imap-mailbox-map-1 func 'imap-utf7-decode buffer))
1106
1107 (defun imap-current-mailbox (&optional buffer)
1108   (with-current-buffer (or buffer (current-buffer))
1109     (imap-utf7-decode imap-current-mailbox)))
1110
1111 (defun imap-current-mailbox-p-1 (mailbox &optional examine)
1112   (and (string= mailbox imap-current-mailbox)
1113        (or (and examine
1114                 (eq imap-state 'examine))
1115            (and (not examine)
1116                 (eq imap-state 'selected)))))
1117
1118 (defun imap-current-mailbox-p (mailbox &optional examine buffer)
1119   (with-current-buffer (or buffer (current-buffer))
1120     (imap-current-mailbox-p-1 (imap-utf7-encode mailbox) examine)))
1121
1122 (defun imap-mailbox-select-1 (mailbox &optional examine)
1123   "Select MAILBOX on server in BUFFER.
1124 If EXAMINE is non-nil, do a read-only select."
1125   (if (imap-current-mailbox-p-1 mailbox examine)
1126       imap-current-mailbox
1127     (setq imap-current-mailbox mailbox)
1128     (if (imap-ok-p (imap-send-command-wait
1129                     (concat (if examine "EXAMINE" "SELECT") " \""
1130                             mailbox "\"")))
1131         (progn
1132           (setq imap-message-data (make-vector imap-message-prime 0)
1133                 imap-state (if examine 'examine 'selected))
1134           imap-current-mailbox)
1135       ;; Failed SELECT/EXAMINE unselects current mailbox
1136       (setq imap-current-mailbox nil))))
1137
1138 (defun imap-mailbox-select (mailbox &optional examine buffer)
1139   (with-current-buffer (or buffer (current-buffer))
1140     (imap-utf7-decode
1141      (imap-mailbox-select-1 (imap-utf7-encode mailbox) examine))))
1142
1143 (defun imap-mailbox-examine-1 (mailbox &optional buffer)
1144   (with-current-buffer (or buffer (current-buffer))
1145     (imap-mailbox-select-1 mailbox 'examine)))
1146
1147 (defun imap-mailbox-examine (mailbox &optional buffer)
1148   "Examine MAILBOX on server in BUFFER."
1149   (imap-mailbox-select mailbox 'examine buffer))
1150
1151 (defun imap-mailbox-unselect (&optional buffer)
1152   "Close current folder in BUFFER, without expunging articles."
1153   (with-current-buffer (or buffer (current-buffer))
1154     (when (or (eq imap-state 'auth)
1155               (and (imap-capability 'UNSELECT)
1156                    (imap-ok-p (imap-send-command-wait "UNSELECT")))
1157               (and (imap-ok-p
1158                     (imap-send-command-wait (concat "EXAMINE \""
1159                                                     imap-current-mailbox
1160                                                     "\"")))
1161                    (imap-ok-p (imap-send-command-wait "CLOSE"))))
1162       (setq imap-current-mailbox nil
1163             imap-message-data nil
1164             imap-state 'auth)
1165       t)))
1166
1167 (defun imap-mailbox-expunge (&optional asynch buffer)
1168   "Expunge articles in current folder in BUFFER.
1169 If ASYNCH, do not wait for succesful completion of the command.
1170 If BUFFER is nil the current buffer is assumed."
1171   (with-current-buffer (or buffer (current-buffer))
1172     (when (and imap-current-mailbox (not (eq imap-state 'examine)))
1173       (if asynch
1174           (imap-send-command "EXPUNGE")
1175       (imap-ok-p (imap-send-command-wait "EXPUNGE"))))))
1176
1177 (defun imap-mailbox-close (&optional asynch buffer)
1178   "Expunge articles and close current folder in BUFFER.
1179 If ASYNCH, do not wait for succesful completion of the command.
1180 If BUFFER is nil the current buffer is assumed."
1181   (with-current-buffer (or buffer (current-buffer))
1182     (when imap-current-mailbox
1183       (if asynch
1184           (imap-add-callback (imap-send-command "CLOSE")
1185                              `(lambda (tag status)
1186                                 (message "IMAP mailbox `%s' closed... %s"
1187                                          imap-current-mailbox status)
1188                                 (when (eq ,imap-current-mailbox
1189                                           imap-current-mailbox)
1190                                   ;; Don't wipe out data if another mailbox
1191                                   ;; was selected...
1192                                   (setq imap-current-mailbox nil
1193                                         imap-message-data nil
1194                                         imap-state 'auth))))
1195         (when (imap-ok-p (imap-send-command-wait "CLOSE"))
1196           (setq imap-current-mailbox nil
1197                 imap-message-data nil
1198                 imap-state 'auth)))
1199       t)))
1200
1201 (defun imap-mailbox-create-1 (mailbox)
1202   (imap-ok-p (imap-send-command-wait (list "CREATE \"" mailbox "\""))))
1203
1204 (defun imap-mailbox-create (mailbox &optional buffer)
1205   "Create MAILBOX on server in BUFFER.
1206 If BUFFER is nil the current buffer is assumed."
1207   (with-current-buffer (or buffer (current-buffer))
1208     (imap-mailbox-create-1 (imap-utf7-encode mailbox))))
1209
1210 (defun imap-mailbox-delete (mailbox &optional buffer)
1211   "Delete MAILBOX on server in BUFFER.
1212 If BUFFER is nil the current buffer is assumed."
1213   (let ((mailbox (imap-utf7-encode mailbox)))
1214     (with-current-buffer (or buffer (current-buffer))
1215       (imap-ok-p
1216        (imap-send-command-wait (list "DELETE \"" mailbox "\""))))))
1217
1218 (defun imap-mailbox-rename (oldname newname &optional buffer)
1219   "Rename mailbox OLDNAME to NEWNAME on server in BUFFER.
1220 If BUFFER is nil the current buffer is assumed."
1221   (let ((oldname (imap-utf7-encode oldname))
1222         (newname (imap-utf7-encode newname)))
1223     (with-current-buffer (or buffer (current-buffer))
1224       (imap-ok-p
1225        (imap-send-command-wait (list "RENAME \"" oldname "\" "
1226                                      "\"" newname "\""))))))
1227
1228 (defun imap-mailbox-lsub (&optional root reference add-delimiter buffer)
1229   "Return a list of subscribed mailboxes on server in BUFFER.
1230 If ROOT is non-nil, only list matching mailboxes.  If ADD-DELIMITER is
1231 non-nil, a hierarchy delimiter is added to root.  REFERENCE is a
1232 implementation-specific string that has to be passed to lsub command."
1233   (with-current-buffer (or buffer (current-buffer))
1234     ;; Make sure we know the hierarchy separator for root's hierarchy
1235     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1236       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1237                                       (imap-utf7-encode root) "\"")))
1238     ;; clear list data (NB not delimiter and other stuff)
1239     (imap-mailbox-map-1 (lambda (mailbox)
1240                           (imap-mailbox-put 'lsub nil mailbox)))
1241     (when (imap-ok-p
1242            (imap-send-command-wait
1243             (concat "LSUB \"" reference "\" \"" (imap-utf7-encode root)
1244                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1245                     "%\"")))
1246       (let (out)
1247         (imap-mailbox-map-1 (lambda (mailbox)
1248                               (when (imap-mailbox-get-1 'lsub mailbox)
1249                                 (push (imap-utf7-decode mailbox) out))))
1250         (nreverse out)))))
1251
1252 (defun imap-mailbox-list (root &optional reference add-delimiter buffer)
1253   "Return a list of mailboxes matching ROOT on server in BUFFER.
1254 If ADD-DELIMITER is non-nil, a hierarchy delimiter is added to
1255 root.  REFERENCE is a implementation-specific string that has to be
1256 passed to list command."
1257   (with-current-buffer (or buffer (current-buffer))
1258     ;; Make sure we know the hierarchy separator for root's hierarchy
1259     (when (and add-delimiter (null (imap-mailbox-get-1 'delimiter root)))
1260       (imap-send-command-wait (concat "LIST \"" reference "\" \""
1261                                       (imap-utf7-encode root) "\"")))
1262     ;; clear list data (NB not delimiter and other stuff)
1263     (imap-mailbox-map-1 (lambda (mailbox)
1264                           (imap-mailbox-put 'list nil mailbox)))
1265     (when (imap-ok-p
1266            (imap-send-command-wait
1267             (concat "LIST \"" reference "\" \"" (imap-utf7-encode root)
1268                     (and add-delimiter (imap-mailbox-get-1 'delimiter root))
1269                     "%\"")))
1270       (let (out)
1271         (imap-mailbox-map-1 (lambda (mailbox)
1272                               (when (imap-mailbox-get-1 'list mailbox)
1273                                 (push (imap-utf7-decode mailbox) out))))
1274         (nreverse out)))))
1275
1276 (defun imap-mailbox-subscribe (mailbox &optional buffer)
1277   "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1278 Returns non-nil if successful."
1279   (with-current-buffer (or buffer (current-buffer))
1280     (imap-ok-p (imap-send-command-wait (concat "SUBSCRIBE \""
1281                                                (imap-utf7-encode mailbox)
1282                                                "\"")))))
1283
1284 (defun imap-mailbox-unsubscribe (mailbox &optional buffer)
1285   "Send the SUBSCRIBE command on the mailbox to server in BUFFER.
1286 Returns non-nil if successful."
1287   (with-current-buffer (or buffer (current-buffer))
1288     (imap-ok-p (imap-send-command-wait (concat "UNSUBSCRIBE "
1289                                                (imap-utf7-encode mailbox)
1290                                                "\"")))))
1291
1292 (defun imap-mailbox-status (mailbox items &optional buffer)
1293   "Get status items ITEM in MAILBOX from server in BUFFER.
1294 ITEMS can be a symbol or a list of symbols, valid symbols are one of
1295 the STATUS data items -- ie 'messages, 'recent, 'uidnext, 'uidvalidity
1296 or 'unseen.  If ITEMS is a list of symbols, a list of values is
1297 returned, if ITEMS is a symbol only it's value is returned."
1298   (with-current-buffer (or buffer (current-buffer))
1299     (when (imap-ok-p
1300            (imap-send-command-wait (list "STATUS \""
1301                                          (imap-utf7-encode mailbox)
1302                                          "\" "
1303                                          (format "%s"
1304                                                  (if (listp items)
1305                                                      items
1306                                                    (list items))))))
1307       (if (listp items)
1308           (mapcar (lambda (item)
1309                     (imap-mailbox-get item mailbox))
1310                   items)
1311         (imap-mailbox-get items mailbox)))))
1312
1313 (defun imap-mailbox-acl-get (&optional mailbox buffer)
1314   "Get ACL on mailbox from server in BUFFER."
1315   (let ((mailbox (imap-utf7-encode mailbox)))
1316     (with-current-buffer (or buffer (current-buffer))
1317       (when (imap-ok-p
1318              (imap-send-command-wait (list "GETACL \""
1319                                            (or mailbox imap-current-mailbox)
1320                                            "\"")))
1321         (imap-mailbox-get-1 'acl (or mailbox imap-current-mailbox))))))
1322
1323 (defun imap-mailbox-acl-set (identifier rights &optional mailbox buffer)
1324   "Change/set ACL for IDENTIFIER to RIGHTS in MAILBOX from server in BUFFER."
1325   (let ((mailbox (imap-utf7-encode mailbox)))
1326     (with-current-buffer (or buffer (current-buffer))
1327       (imap-ok-p
1328        (imap-send-command-wait (list "SETACL \""
1329                                      (or mailbox imap-current-mailbox)
1330                                      "\" "
1331                                      identifier
1332                                      " "
1333                                      rights))))))
1334
1335 (defun imap-mailbox-acl-delete (identifier &optional mailbox buffer)
1336   "Removes any <identifier,rights> pair for IDENTIFIER in MAILBOX from server in BUFFER."
1337   (let ((mailbox (imap-utf7-encode mailbox)))
1338     (with-current-buffer (or buffer (current-buffer))
1339       (imap-ok-p
1340        (imap-send-command-wait (list "DELETEACL \""
1341                                      (or mailbox imap-current-mailbox)
1342                                      "\" "
1343                                      identifier))))))
1344
1345 \f
1346 ;; Message functions:
1347
1348 (defun imap-current-message (&optional buffer)
1349   (with-current-buffer (or buffer (current-buffer))
1350     imap-current-message))
1351
1352 (defun imap-list-to-message-set (list)
1353   (mapconcat (lambda (item)
1354                (number-to-string item))
1355              (if (listp list)
1356                  list
1357                (list list))
1358              ","))
1359
1360 (defun imap-range-to-message-set (range)
1361   (mapconcat
1362    (lambda (item)
1363      (if (consp item)
1364          (format "%d:%d"
1365                  (car item) (cdr item))
1366        (format "%d" item)))
1367    (if (and (listp range) (not (listp (cdr range))))
1368        (list range) ;; make (1 . 2) into ((1 . 2))
1369      range)
1370    ","))
1371
1372 (defun imap-fetch-asynch (uids props &optional nouidfetch buffer)
1373   (with-current-buffer (or buffer (current-buffer))
1374     (imap-send-command (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1375                                (if (listp uids)
1376                                    (imap-list-to-message-set uids)
1377                                  uids)
1378                                props))))
1379
1380 (defun imap-fetch (uids props &optional receive nouidfetch buffer)
1381   "Fetch properties PROPS from message set UIDS from server in BUFFER.
1382 UIDS can be a string, number or a list of numbers.  If RECEIVE
1383 is non-nil return theese properties."
1384   (with-current-buffer (or buffer (current-buffer))
1385     (when (imap-ok-p (imap-send-command-wait
1386                       (format "%sFETCH %s %s" (if nouidfetch "" "UID ")
1387                               (if (listp uids)
1388                                   (imap-list-to-message-set uids)
1389                                 uids)
1390                               props)))
1391       (if (or (null receive) (stringp uids))
1392           t
1393         (if (listp uids)
1394             (mapcar (lambda (uid)
1395                       (if (listp receive)
1396                           (mapcar (lambda (prop)
1397                                     (imap-message-get uid prop))
1398                                   receive)
1399                         (imap-message-get uid receive)))
1400                     uids)
1401           (imap-message-get uids receive))))))
1402
1403 (defun imap-message-put (uid propname value &optional buffer)
1404   (with-current-buffer (or buffer (current-buffer))
1405     (if imap-message-data
1406         (put (intern (number-to-string uid) imap-message-data)
1407              propname value)
1408       (error "Imap-message-data is nil, uid %s prop %s value %s buffer %s"
1409              uid propname value (current-buffer)))
1410     t))
1411
1412 (defun imap-message-get (uid propname &optional buffer)
1413   (with-current-buffer (or buffer (current-buffer))
1414     (get (intern-soft (number-to-string uid) imap-message-data)
1415          propname)))
1416
1417 (defun imap-message-map (func propname &optional buffer)
1418   "Map a function across each mailbox in `imap-message-data', returning a list."
1419   (with-current-buffer (or buffer (current-buffer))
1420     (let (result)
1421       (mapatoms
1422        (lambda (s)
1423          (push (funcall func (get s 'UID) (get s propname)) result))
1424        imap-message-data)
1425       result)))
1426
1427 (defmacro imap-message-envelope-date (uid &optional buffer)
1428   `(with-current-buffer (or ,buffer (current-buffer))
1429      (elt (imap-message-get ,uid 'ENVELOPE) 0)))
1430
1431 (defmacro imap-message-envelope-subject (uid &optional buffer)
1432   `(with-current-buffer (or ,buffer (current-buffer))
1433      (elt (imap-message-get ,uid 'ENVELOPE) 1)))
1434
1435 (defmacro imap-message-envelope-from (uid &optional buffer)
1436   `(with-current-buffer (or ,buffer (current-buffer))
1437      (elt (imap-message-get ,uid 'ENVELOPE) 2)))
1438
1439 (defmacro imap-message-envelope-sender (uid &optional buffer)
1440   `(with-current-buffer (or ,buffer (current-buffer))
1441      (elt (imap-message-get ,uid 'ENVELOPE) 3)))
1442
1443 (defmacro imap-message-envelope-reply-to (uid &optional buffer)
1444   `(with-current-buffer (or ,buffer (current-buffer))
1445      (elt (imap-message-get ,uid 'ENVELOPE) 4)))
1446
1447 (defmacro imap-message-envelope-to (uid &optional buffer)
1448   `(with-current-buffer (or ,buffer (current-buffer))
1449      (elt (imap-message-get ,uid 'ENVELOPE) 5)))
1450
1451 (defmacro imap-message-envelope-cc (uid &optional buffer)
1452   `(with-current-buffer (or ,buffer (current-buffer))
1453      (elt (imap-message-get ,uid 'ENVELOPE) 6)))
1454
1455 (defmacro imap-message-envelope-bcc (uid &optional buffer)
1456   `(with-current-buffer (or ,buffer (current-buffer))
1457      (elt (imap-message-get ,uid 'ENVELOPE) 7)))
1458
1459 (defmacro imap-message-envelope-in-reply-to (uid &optional buffer)
1460   `(with-current-buffer (or ,buffer (current-buffer))
1461      (elt (imap-message-get ,uid 'ENVELOPE) 8)))
1462
1463 (defmacro imap-message-envelope-message-id (uid &optional buffer)
1464   `(with-current-buffer (or ,buffer (current-buffer))
1465      (elt (imap-message-get ,uid 'ENVELOPE) 9)))
1466
1467 (defmacro imap-message-body (uid &optional buffer)
1468   `(with-current-buffer (or ,buffer (current-buffer))
1469      (imap-message-get ,uid 'BODY)))
1470
1471 (defun imap-search (predicate &optional buffer)
1472   (with-current-buffer (or buffer (current-buffer))
1473     (imap-mailbox-put 'search 'dummy)
1474     (when (imap-ok-p (imap-send-command-wait (concat "UID SEARCH " predicate)))
1475       (if (eq (imap-mailbox-get-1 'search imap-current-mailbox) 'dummy)
1476           (progn
1477             (message "Missing SEARCH response to a SEARCH command (server not RFC compliant)...")
1478             nil)
1479         (imap-mailbox-get-1 'search imap-current-mailbox)))))
1480
1481 (defun imap-message-flag-permanent-p (flag &optional mailbox buffer)
1482   "Return t iff FLAG can be permanently (between IMAP sessions) saved on articles, in MAILBOX on server in BUFFER."
1483   (with-current-buffer (or buffer (current-buffer))
1484     (or (member "\\*" (imap-mailbox-get 'permanentflags mailbox))
1485         (member flag (imap-mailbox-get 'permanentflags mailbox)))))
1486
1487 (defun imap-message-flags-set (articles flags &optional silent buffer)
1488   (when (and articles flags)
1489     (with-current-buffer (or buffer (current-buffer))
1490       (imap-ok-p (imap-send-command-wait
1491                   (concat "UID STORE " articles
1492                           " FLAGS" (if silent ".SILENT") " (" flags ")"))))))
1493
1494 (defun imap-message-flags-del (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-add (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-copyuid-1 (mailbox)
1509   (if (imap-capability 'UIDPLUS)
1510       (list (nth 0 (imap-mailbox-get-1 'copyuid mailbox))
1511             (string-to-number (nth 2 (imap-mailbox-get-1 'copyuid mailbox))))
1512     (let ((old-mailbox imap-current-mailbox)
1513           (state imap-state)
1514           (imap-message-data (make-vector 2 0)))
1515       (when (imap-mailbox-examine-1 mailbox)
1516         (prog1
1517             (and (imap-fetch "*" "UID")
1518                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1519                        (apply 'max (imap-message-map
1520                                     (lambda (uid prop) uid) 'UID))))
1521           (if old-mailbox
1522               (imap-mailbox-select old-mailbox (eq state 'examine))
1523             (imap-mailbox-unselect)))))))
1524
1525 (defun imap-message-copyuid (mailbox &optional buffer)
1526   (with-current-buffer (or buffer (current-buffer))
1527     (imap-message-copyuid-1 (imap-utf7-decode mailbox))))
1528
1529 (defun imap-message-copy (articles mailbox
1530                                    &optional dont-create no-copyuid buffer)
1531   "Copy ARTICLES (a string message set) to MAILBOX on server in
1532 BUFFER, creating mailbox if it doesn't exist.  If dont-create is
1533 non-nil, it will not create a mailbox.  On success, return a list with
1534 the UIDVALIDITY of the mailbox the article(s) was copied to as the
1535 first element, rest of list contain the saved articles' UIDs."
1536   (when articles
1537     (with-current-buffer (or buffer (current-buffer))
1538       (let ((mailbox (imap-utf7-encode mailbox)))
1539         (if (let ((cmd (concat "UID COPY " articles " \"" mailbox "\""))
1540                   (imap-current-target-mailbox mailbox))
1541               (if (imap-ok-p (imap-send-command-wait cmd))
1542                   t
1543                 (when (and (not dont-create)
1544                            ;; removed because of buggy Oracle server
1545                            ;; that doesn't send TRYCREATE tags (which
1546                            ;; is a MUST according to specifications):
1547                            ;;(imap-mailbox-get-1 'trycreate mailbox)
1548                            (imap-mailbox-create-1 mailbox))
1549                   (imap-ok-p (imap-send-command-wait cmd)))))
1550             (or no-copyuid
1551                 (imap-message-copyuid-1 mailbox)))))))
1552
1553 (defun imap-message-appenduid-1 (mailbox)
1554   (if (imap-capability 'UIDPLUS)
1555       (imap-mailbox-get-1 'appenduid mailbox)
1556     (let ((old-mailbox imap-current-mailbox)
1557           (state imap-state)
1558           (imap-message-data (make-vector 2 0)))
1559       (when (imap-mailbox-examine-1 mailbox)
1560         (prog1
1561             (and (imap-fetch "*" "UID")
1562                  (list (imap-mailbox-get-1 'uidvalidity mailbox)
1563                        (apply 'max (imap-message-map
1564                                     (lambda (uid prop) uid) 'UID))))
1565           (if old-mailbox
1566               (imap-mailbox-select old-mailbox (eq state 'examine))
1567             (imap-mailbox-unselect)))))))
1568
1569 (defun imap-message-appenduid (mailbox &optional buffer)
1570   (with-current-buffer (or buffer (current-buffer))
1571     (imap-message-appenduid-1 (imap-utf7-encode mailbox))))
1572
1573 (defun imap-message-append (mailbox article &optional flags date-time buffer)
1574   "Append ARTICLE (a buffer) to MAILBOX on server in BUFFER.
1575 FLAGS and DATE-TIME is currently not used.  Return a cons holding
1576 uidvalidity of MAILBOX and UID the newly created article got, or nil
1577 on failure."
1578   (let ((mailbox (imap-utf7-encode mailbox)))
1579     (with-current-buffer (or buffer (current-buffer))
1580       (and (let ((imap-current-target-mailbox mailbox))
1581              (imap-ok-p
1582               (imap-send-command-wait
1583                (list "APPEND \"" mailbox "\" "  article))))
1584            (imap-message-appenduid-1 mailbox)))))
1585
1586 (defun imap-body-lines (body)
1587   "Return number of lines in article by looking at the mime bodystructure BODY."
1588   (if (listp body)
1589       (if (stringp (car body))
1590           (cond ((and (string= (upcase (car body)) "TEXT")
1591                       (numberp (nth 7 body)))
1592                  (nth 7 body))
1593                 ((and (string= (upcase (car body)) "MESSAGE")
1594                       (numberp (nth 9 body)))
1595                  (nth 9 body))
1596                 (t 0))
1597         (apply '+ (mapcar 'imap-body-lines body)))
1598     0))
1599
1600 (defun imap-envelope-from (from)
1601   "Return a from string line."
1602   (and from
1603        (concat (aref from 0)
1604                (if (aref from 0) " <")
1605                (aref from 2)
1606                "@"
1607                (aref from 3)
1608                (if (aref from 0) ">"))))
1609
1610 \f
1611 ;; Internal functions.
1612
1613 (defun imap-add-callback (tag func)
1614   (setq imap-callbacks (append (list (cons tag func)) imap-callbacks)))
1615
1616 (defun imap-send-command-1 (cmdstr)
1617   (setq cmdstr (concat cmdstr imap-client-eol))
1618   (and imap-log
1619        (with-current-buffer (get-buffer-create imap-log-buffer)
1620          (buffer-disable-undo)
1621          (goto-char (point-max))
1622          (insert cmdstr)))
1623   (process-send-string imap-process cmdstr))
1624
1625 (defun imap-send-command (command &optional buffer)
1626   (with-current-buffer (or buffer (current-buffer))
1627     (if (not (listp command)) (setq command (list command)))
1628     (let ((tag (setq imap-tag (1+ imap-tag)))
1629           cmd cmdstr)
1630       (setq cmdstr (concat (number-to-string imap-tag) " "))
1631       (while (setq cmd (pop command))
1632         (cond ((stringp cmd)
1633                (setq cmdstr (concat cmdstr cmd)))
1634               ((bufferp cmd)
1635                (let ((eol imap-client-eol)
1636                      (calcfirst imap-calculate-literal-size-first)
1637                      size)
1638                  (with-current-buffer cmd
1639                    (if calcfirst
1640                        (setq size (buffer-size)))
1641                    (when (not (equal eol "\r\n"))
1642                      ;; XXX modifies buffer!
1643                      (goto-char (point-min))
1644                      (while (search-forward "\r\n" nil t)
1645                        (replace-match eol)))
1646                    (if (not calcfirst)
1647                        (setq size (buffer-size))))
1648                  (setq cmdstr
1649                        (concat cmdstr (format "{%d}" size))))
1650                (unwind-protect
1651                    (progn
1652                      (imap-send-command-1 cmdstr)
1653                      (setq cmdstr nil)
1654                      (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1655                          (setq command nil);; abort command if no cont-req
1656                        (let ((process imap-process)
1657                              (stream imap-stream)
1658                              (eol imap-client-eol))
1659                          (with-current-buffer cmd
1660                            (and imap-log
1661                                 (with-current-buffer (get-buffer-create
1662                                                       imap-log-buffer)
1663                                   (buffer-disable-undo)
1664                                   (goto-char (point-max))
1665                                   (insert-buffer-substring cmd)))
1666                            (process-send-region process (point-min)
1667                                                 (point-max)))
1668                          (process-send-string process imap-client-eol))))
1669                  (setq imap-continuation nil)))
1670               ((functionp cmd)
1671                (imap-send-command-1 cmdstr)
1672                (setq cmdstr nil)
1673                (unwind-protect
1674                    (if (not (eq (imap-wait-for-tag tag) 'INCOMPLETE))
1675                        (setq command nil);; abort command if no cont-req
1676                      (setq command (cons (funcall cmd imap-continuation)
1677                                          command)))
1678                  (setq imap-continuation nil)))
1679               (t
1680                (error "Unknown command type"))))
1681       (if cmdstr
1682           (imap-send-command-1 cmdstr))
1683       tag)))
1684
1685 (defun imap-wait-for-tag (tag &optional buffer)
1686   (with-current-buffer (or buffer (current-buffer))
1687     (let (imap-have-messaged)
1688       (while (and (null imap-continuation)
1689                   (memq (process-status imap-process) '(open run))
1690                   (< imap-reached-tag tag))
1691         (let ((len (/ (point-max) 1024))
1692               message-log-max)
1693           (unless (< len 10)
1694             (setq imap-have-messaged t)
1695             (message "imap read: %dk" len))
1696           (accept-process-output imap-process 1)))
1697       (when imap-have-messaged
1698         (message ""))
1699       (and (memq (process-status imap-process) '(open run))
1700            (or (assq tag imap-failed-tags)
1701                (if imap-continuation
1702                    'INCOMPLETE
1703                  'OK))))))
1704
1705 (defun imap-sentinel (process string)
1706   (delete-process process))
1707
1708 (defun imap-find-next-line ()
1709   "Return point at end of current line, taking into account literals.
1710 Return nil if no complete line has arrived."
1711   (when (re-search-forward (concat imap-server-eol "\\|{\\([0-9]+\\)}"
1712                                    imap-server-eol)
1713                            nil t)
1714     (if (match-string 1)
1715         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1716             nil
1717           (goto-char (+ (point) (string-to-number (match-string 1))))
1718           (imap-find-next-line))
1719       (point))))
1720
1721 (defun imap-arrival-filter (proc string)
1722   "IMAP process filter."
1723   (with-current-buffer (process-buffer proc)
1724     (goto-char (point-max))
1725     (insert string)
1726     (and imap-log
1727          (with-current-buffer (get-buffer-create imap-log-buffer)
1728            (buffer-disable-undo)
1729            (goto-char (point-max))
1730            (insert string)))
1731     (let (end)
1732       (goto-char (point-min))
1733       (while (setq end (imap-find-next-line))
1734         (save-restriction
1735           (narrow-to-region (point-min) end)
1736           (delete-backward-char (length imap-server-eol))
1737           (goto-char (point-min))
1738           (unwind-protect
1739               (cond ((eq imap-state 'initial)
1740                      (imap-parse-greeting))
1741                     ((or (eq imap-state 'auth)
1742                          (eq imap-state 'nonauth)
1743                          (eq imap-state 'selected)
1744                          (eq imap-state 'examine))
1745                      (imap-parse-response))
1746                     (t
1747                      (message "Unknown state %s in arrival filter"
1748                               imap-state)))
1749             (delete-region (point-min) (point-max))))))))
1750
1751 \f
1752 ;; Imap parser.
1753
1754 (defsubst imap-forward ()
1755   (or (eobp) (forward-char)))
1756
1757 ;;   number          = 1*DIGIT
1758 ;;                       ; Unsigned 32-bit integer
1759 ;;                       ; (0 <= n < 4,294,967,296)
1760
1761 (defsubst imap-parse-number ()
1762   (when (looking-at "[0-9]+")
1763     (prog1
1764         (string-to-number (match-string 0))
1765       (goto-char (match-end 0)))))
1766
1767 ;;   literal         = "{" number "}" CRLF *CHAR8
1768 ;;                       ; Number represents the number of CHAR8s
1769
1770 (defsubst imap-parse-literal ()
1771   (when (looking-at "{\\([0-9]+\\)}\r\n")
1772     (let ((pos (match-end 0))
1773           (len (string-to-number (match-string 1))))
1774       (if (< (point-max) (+ pos len))
1775           nil
1776         (goto-char (+ pos len))
1777         (buffer-substring pos (+ pos len))))))
1778
1779 ;;   string          = quoted / literal
1780 ;;
1781 ;;   quoted          = DQUOTE *QUOTED-CHAR DQUOTE
1782 ;;
1783 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
1784 ;;                     "\" quoted-specials
1785 ;;
1786 ;;   quoted-specials = DQUOTE / "\"
1787 ;;
1788 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
1789
1790 (defsubst imap-parse-string ()
1791   (cond ((eq (char-after) ?\")
1792          (forward-char 1)
1793          (let ((p (point)) (name ""))
1794            (skip-chars-forward "^\"\\\\")
1795            (setq name (buffer-substring p (point)))
1796            (while (eq (char-after) ?\\)
1797              (setq p (1+ (point)))
1798              (forward-char 2)
1799              (skip-chars-forward "^\"\\\\")
1800              (setq name (concat name (buffer-substring p (point)))))
1801            (forward-char 1)
1802            name))
1803         ((eq (char-after) ?{)
1804          (imap-parse-literal))))
1805
1806 ;;   nil             = "NIL"
1807
1808 (defsubst imap-parse-nil ()
1809   (if (looking-at "NIL")
1810       (goto-char (match-end 0))))
1811
1812 ;;   nstring         = string / nil
1813
1814 (defsubst imap-parse-nstring ()
1815   (or (imap-parse-string)
1816       (and (imap-parse-nil)
1817            nil)))
1818
1819 ;;   astring         = atom / string
1820 ;;
1821 ;;   atom            = 1*ATOM-CHAR
1822 ;;
1823 ;;   ATOM-CHAR       = <any CHAR except atom-specials>
1824 ;;
1825 ;;   atom-specials   = "(" / ")" / "{" / SP / CTL / list-wildcards /
1826 ;;                     quoted-specials
1827 ;;
1828 ;;   list-wildcards  = "%" / "*"
1829 ;;
1830 ;;   quoted-specials = DQUOTE / "\"
1831
1832 (defsubst imap-parse-astring ()
1833   (or (imap-parse-string)
1834       (buffer-substring (point)
1835                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1836                             (goto-char (1- (match-end 0)))
1837                           (end-of-line)
1838                           (point)))))
1839
1840 ;;   address         = "(" addr-name SP addr-adl SP addr-mailbox SP
1841 ;;                      addr-host ")"
1842 ;;
1843 ;;   addr-adl        = nstring
1844 ;;                       ; Holds route from [RFC-822] route-addr if
1845 ;;                       ; non-nil
1846 ;;
1847 ;;   addr-host       = nstring
1848 ;;                       ; nil indicates [RFC-822] group syntax.
1849 ;;                       ; Otherwise, holds [RFC-822] domain name
1850 ;;
1851 ;;   addr-mailbox    = nstring
1852 ;;                       ; nil indicates end of [RFC-822] group; if
1853 ;;                       ; non-nil and addr-host is nil, holds
1854 ;;                       ; [RFC-822] group name.
1855 ;;                       ; Otherwise, holds [RFC-822] local-part
1856 ;;                       ; after removing [RFC-822] quoting
1857 ;;
1858 ;;   addr-name       = nstring
1859 ;;                       ; If non-nil, holds phrase from [RFC-822]
1860 ;;                       ; mailbox after removing [RFC-822] quoting
1861 ;;
1862
1863 (defsubst imap-parse-address ()
1864   (let (address)
1865     (when (eq (char-after) ?\()
1866       (imap-forward)
1867       (setq address (vector (prog1 (imap-parse-nstring)
1868                               (imap-forward))
1869                             (prog1 (imap-parse-nstring)
1870                               (imap-forward))
1871                             (prog1 (imap-parse-nstring)
1872                               (imap-forward))
1873                             (imap-parse-nstring)))
1874       (when (eq (char-after) ?\))
1875         (imap-forward)
1876         address))))
1877
1878 ;;   address-list    = "(" 1*address ")" / nil
1879 ;;
1880 ;;   nil             = "NIL"
1881
1882 (defsubst imap-parse-address-list ()
1883   (if (eq (char-after) ?\()
1884       (let (address addresses)
1885         (imap-forward)
1886         (while (and (not (eq (char-after) ?\)))
1887                     ;; next line for MS Exchange bug
1888                     (progn (and (eq (char-after) ? ) (imap-forward)) t)
1889                     (setq address (imap-parse-address)))
1890           (setq addresses (cons address addresses)))
1891         (when (eq (char-after) ?\))
1892           (imap-forward)
1893           (nreverse addresses)))
1894     (assert (imap-parse-nil) t "In imap-parse-address-list")))
1895
1896 ;;   mailbox         = "INBOX" / astring
1897 ;;                       ; INBOX is case-insensitive.  All case variants of
1898 ;;                       ; INBOX (e.g. "iNbOx") MUST be interpreted as INBOX
1899 ;;                       ; not as an astring.  An astring which consists of
1900 ;;                       ; the case-insensitive sequence "I" "N" "B" "O" "X"
1901 ;;                       ; is considered to be INBOX and not an astring.
1902 ;;                       ;  Refer to section 5.1 for further
1903 ;;                       ; semantic details of mailbox names.
1904
1905 (defsubst imap-parse-mailbox ()
1906   (let ((mailbox (imap-parse-astring)))
1907     (if (string-equal "INBOX" (upcase mailbox))
1908         "INBOX"
1909       mailbox)))
1910
1911 ;;   greeting        = "*" SP (resp-cond-auth / resp-cond-bye) CRLF
1912 ;;
1913 ;;   resp-cond-auth  = ("OK" / "PREAUTH") SP resp-text
1914 ;;                       ; Authentication condition
1915 ;;
1916 ;;   resp-cond-bye   = "BYE" SP resp-text
1917
1918 (defun imap-parse-greeting ()
1919   "Parse a IMAP greeting."
1920   (cond ((looking-at "\\* OK ")
1921          (setq imap-state 'nonauth))
1922         ((looking-at "\\* PREAUTH ")
1923          (setq imap-state 'auth))
1924         ((looking-at "\\* BYE ")
1925          (setq imap-state 'closed))))
1926
1927 ;;   response        = *(continue-req / response-data) response-done
1928 ;;
1929 ;;   continue-req    = "+" SP (resp-text / base64) CRLF
1930 ;;
1931 ;;   response-data   = "*" SP (resp-cond-state / resp-cond-bye /
1932 ;;                     mailbox-data / message-data / capability-data) CRLF
1933 ;;
1934 ;;   response-done   = response-tagged / response-fatal
1935 ;;
1936 ;;   response-fatal  = "*" SP resp-cond-bye CRLF
1937 ;;                       ; Server closes connection immediately
1938 ;;
1939 ;;   response-tagged = tag SP resp-cond-state CRLF
1940 ;;
1941 ;;   resp-cond-state = ("OK" / "NO" / "BAD") SP resp-text
1942 ;;                       ; Status condition
1943 ;;
1944 ;;   resp-cond-bye   = "BYE" SP resp-text
1945 ;;
1946 ;;   mailbox-data    =  "FLAGS" SP flag-list /
1947 ;;                      "LIST" SP mailbox-list /
1948 ;;                      "LSUB" SP mailbox-list /
1949 ;;                      "SEARCH" *(SP nz-number) /
1950 ;;                      "STATUS" SP mailbox SP "("
1951 ;;                            [status-att SP number *(SP status-att SP number)] ")" /
1952 ;;                      number SP "EXISTS" /
1953 ;;                      number SP "RECENT"
1954 ;;
1955 ;;   message-data    = nz-number SP ("EXPUNGE" / ("FETCH" SP msg-att))
1956 ;;
1957 ;;   capability-data = "CAPABILITY" *(SP capability) SP "IMAP4rev1"
1958 ;;                     *(SP capability)
1959 ;;                       ; IMAP4rev1 servers which offer RFC 1730
1960 ;;                       ; compatibility MUST list "IMAP4" as the first
1961 ;;                       ; capability.
1962
1963 (defun imap-parse-response ()
1964   "Parse a IMAP command response."
1965   (let (token)
1966     (case (setq token (read (current-buffer)))
1967       (+ (setq imap-continuation
1968                (or (buffer-substring (min (point-max) (1+ (point)))
1969                                      (point-max))
1970                    t)))
1971       (* (case (prog1 (setq token (read (current-buffer)))
1972                  (imap-forward))
1973            (OK         (imap-parse-resp-text))
1974            (NO         (imap-parse-resp-text))
1975            (BAD        (imap-parse-resp-text))
1976            (BYE        (imap-parse-resp-text))
1977            (FLAGS      (imap-mailbox-put 'flags (imap-parse-flag-list)))
1978            (LIST       (imap-parse-data-list 'list))
1979            (LSUB       (imap-parse-data-list 'lsub))
1980            (SEARCH     (imap-mailbox-put
1981                         'search
1982                         (read (concat "(" (buffer-substring (point) (point-max)) ")"))))
1983            (STATUS     (imap-parse-status))
1984            (CAPABILITY (setq imap-capability
1985                                (read (concat "(" (upcase (buffer-substring
1986                                                           (point) (point-max)))
1987                                              ")"))))
1988            (ACL        (imap-parse-acl))
1989            (t       (case (prog1 (read (current-buffer))
1990                             (imap-forward))
1991                       (EXISTS  (imap-mailbox-put 'exists token))
1992                       (RECENT  (imap-mailbox-put 'recent token))
1993                       (EXPUNGE t)
1994                       (FETCH   (imap-parse-fetch token))
1995                       (t       (message "Garbage: %s" (buffer-string)))))))
1996       (t (let (status)
1997            (if (not (integerp token))
1998                (message "Garbage: %s" (buffer-string))
1999              (case (prog1 (setq status (read (current-buffer)))
2000                      (imap-forward))
2001                (OK  (progn
2002                       (setq imap-reached-tag (max imap-reached-tag token))
2003                       (imap-parse-resp-text)))
2004                (NO  (progn
2005                       (setq imap-reached-tag (max imap-reached-tag token))
2006                       (save-excursion
2007                         (imap-parse-resp-text))
2008                       (let (code text)
2009                         (when (eq (char-after) ?\[)
2010                           (setq code (buffer-substring (point)
2011                                                        (search-forward "]")))
2012                           (imap-forward))
2013                         (setq text (buffer-substring (point) (point-max)))
2014                         (push (list token status code text)
2015                               imap-failed-tags))))
2016                (BAD (progn
2017                       (setq imap-reached-tag (max imap-reached-tag token))
2018                       (save-excursion
2019                         (imap-parse-resp-text))
2020                       (let (code text)
2021                         (when (eq (char-after) ?\[)
2022                           (setq code (buffer-substring (point)
2023                                                        (search-forward "]")))
2024                           (imap-forward))
2025                         (setq text (buffer-substring (point) (point-max)))
2026                         (push (list token status code text) imap-failed-tags)
2027                         (error "Internal error, tag %s status %s code %s text %s"
2028                                token status code text))))
2029                (t   (message "Garbage: %s" (buffer-string))))
2030              (when (assq token imap-callbacks)
2031                (funcall (cdr (assq token imap-callbacks)) token status)
2032                (setq imap-callbacks
2033                      (imap-remassoc token imap-callbacks)))))))))
2034
2035 ;;   resp-text       = ["[" resp-text-code "]" SP] text
2036 ;;
2037 ;;   text            = 1*TEXT-CHAR
2038 ;;
2039 ;;   TEXT-CHAR       = <any CHAR except CR and LF>
2040
2041 (defun imap-parse-resp-text ()
2042   (imap-parse-resp-text-code))
2043
2044 ;;   resp-text-code  = "ALERT" /
2045 ;;                     "BADCHARSET [SP "(" astring *(SP astring) ")" ] /
2046 ;;                     "NEWNAME" SP string SP string /
2047 ;;                     "PARSE" /
2048 ;;                     "PERMANENTFLAGS" SP "("
2049 ;;                               [flag-perm *(SP flag-perm)] ")" /
2050 ;;                     "READ-ONLY" /
2051 ;;                     "READ-WRITE" /
2052 ;;                     "TRYCREATE" /
2053 ;;                     "UIDNEXT" SP nz-number /
2054 ;;                     "UIDVALIDITY" SP nz-number /
2055 ;;                     "UNSEEN" SP nz-number /
2056 ;;                     resp-text-atom [SP 1*<any TEXT-CHAR except "]">]
2057 ;;
2058 ;;   resp_code_apnd  = "APPENDUID" SPACE nz_number SPACE uniqueid
2059 ;;
2060 ;;   resp_code_copy  = "COPYUID" SPACE nz_number SPACE set SPACE set
2061 ;;
2062 ;;   set             = sequence-num / (sequence-num ":" sequence-num) /
2063 ;;                        (set "," set)
2064 ;;                          ; Identifies a set of messages.  For message
2065 ;;                          ; sequence numbers, these are consecutive
2066 ;;                          ; numbers from 1 to the number of messages in
2067 ;;                          ; the mailbox
2068 ;;                          ; Comma delimits individual numbers, colon
2069 ;;                          ; delimits between two numbers inclusive.
2070 ;;                          ; Example: 2,4:7,9,12:* is 2,4,5,6,7,9,12,13,
2071 ;;                          ; 14,15 for a mailbox with 15 messages.
2072 ;;
2073 ;;   sequence-num    = nz-number / "*"
2074 ;;                          ; * is the largest number in use.  For message
2075 ;;                          ; sequence numbers, it is the number of messages
2076 ;;                          ; in the mailbox.  For unique identifiers, it is
2077 ;;                          ; the unique identifier of the last message in
2078 ;;                          ; the mailbox.
2079 ;;
2080 ;;   flag-perm       = flag / "\*"
2081 ;;
2082 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2083 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2084 ;;                       ; Does not include "\Recent"
2085 ;;
2086 ;;   flag-extension  = "\" atom
2087 ;;                       ; Future expansion.  Client implementations
2088 ;;                       ; MUST accept flag-extension flags.  Server
2089 ;;                       ; implementations MUST NOT generate
2090 ;;                       ; flag-extension flags except as defined by
2091 ;;                       ; future standard or standards-track
2092 ;;                       ; revisions of this specification.
2093 ;;
2094 ;;   flag-keyword    = atom
2095 ;;
2096 ;;   resp-text-atom  = 1*<any ATOM-CHAR except "]">
2097
2098 (defun imap-parse-resp-text-code ()
2099   ;; xxx next line for stalker communigate pro 3.3.1 bug
2100   (when (looking-at " \\[")
2101     (imap-forward))
2102   (when (eq (char-after) ?\[)
2103     (imap-forward)
2104     (cond ((search-forward "PERMANENTFLAGS " nil t)
2105            (imap-mailbox-put 'permanentflags (imap-parse-flag-list)))
2106           ((search-forward "UIDNEXT " nil t)
2107            (imap-mailbox-put 'uidnext (read (current-buffer))))
2108           ((search-forward "UNSEEN " nil t)
2109            (imap-mailbox-put 'unseen (read (current-buffer))))
2110           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
2111            (imap-mailbox-put 'uidvalidity (match-string 1)))
2112           ((search-forward "READ-ONLY" nil t)
2113            (imap-mailbox-put 'read-only t))
2114           ((search-forward "NEWNAME " nil t)
2115            (let (oldname newname)
2116              (setq oldname (imap-parse-string))
2117              (imap-forward)
2118              (setq newname (imap-parse-string))
2119              (imap-mailbox-put 'newname newname oldname)))
2120           ((search-forward "TRYCREATE" nil t)
2121            (imap-mailbox-put 'trycreate t imap-current-target-mailbox))
2122           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
2123            (imap-mailbox-put 'appenduid
2124                              (list (match-string 1)
2125                                    (string-to-number (match-string 2)))
2126                              imap-current-target-mailbox))
2127           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
2128            (imap-mailbox-put 'copyuid (list (match-string 1)
2129                                             (match-string 2)
2130                                             (match-string 3))
2131                              imap-current-target-mailbox))
2132           ((search-forward "ALERT] " nil t)
2133            (message "Imap server %s information: %s" imap-server
2134                     (buffer-substring (point) (point-max)))))))
2135
2136 ;;   mailbox-list    = "(" [mbx-list-flags] ")" SP
2137 ;;                      (DQUOTE QUOTED-CHAR DQUOTE / nil) SP mailbox
2138 ;;
2139 ;;   mbx-list-flags  = *(mbx-list-oflag SP) mbx-list-sflag
2140 ;;                     *(SP mbx-list-oflag) /
2141 ;;                     mbx-list-oflag *(SP mbx-list-oflag)
2142 ;;
2143 ;;   mbx-list-oflag  = "\Noinferiors" / flag-extension
2144 ;;                       ; Other flags; multiple possible per LIST response
2145 ;;
2146 ;;   mbx-list-sflag  = "\Noselect" / "\Marked" / "\Unmarked"
2147 ;;                       ; Selectability flags; only one per LIST response
2148 ;;
2149 ;;   QUOTED-CHAR     = <any TEXT-CHAR except quoted-specials> /
2150 ;;                     "\" quoted-specials
2151 ;;
2152 ;;   quoted-specials = DQUOTE / "\"
2153
2154 (defun imap-parse-data-list (type)
2155   (let (flags delimiter mailbox)
2156     (setq flags (imap-parse-flag-list))
2157     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
2158       (setq delimiter (match-string 1))
2159       (goto-char (1+ (match-end 0)))
2160       (when (setq mailbox (imap-parse-mailbox))
2161         (imap-mailbox-put type t mailbox)
2162         (imap-mailbox-put 'list-flags flags mailbox)
2163         (imap-mailbox-put 'delimiter delimiter mailbox)))))
2164
2165 ;;  msg_att         ::= "(" 1#("ENVELOPE" SPACE envelope /
2166 ;;                      "FLAGS" SPACE "(" #(flag / "\Recent") ")" /
2167 ;;                      "INTERNALDATE" SPACE date_time /
2168 ;;                      "RFC822" [".HEADER" / ".TEXT"] SPACE nstring /
2169 ;;                      "RFC822.SIZE" SPACE number /
2170 ;;                      "BODY" ["STRUCTURE"] SPACE body /
2171 ;;                      "BODY" section ["<" number ">"] SPACE nstring /
2172 ;;                      "UID" SPACE uniqueid) ")"
2173 ;;
2174 ;;  date_time       ::= <"> date_day_fixed "-" date_month "-" date_year
2175 ;;                      SPACE time SPACE zone <">
2176 ;;
2177 ;;  section         ::= "[" [section_text / (nz_number *["." nz_number]
2178 ;;                      ["." (section_text / "MIME")])] "]"
2179 ;;
2180 ;;  section_text    ::= "HEADER" / "HEADER.FIELDS" [".NOT"]
2181 ;;                      SPACE header_list / "TEXT"
2182 ;;
2183 ;;  header_fld_name ::= astring
2184 ;;
2185 ;;  header_list     ::= "(" 1#header_fld_name ")"
2186
2187 (defsubst imap-parse-header-list ()
2188   (when (eq (char-after) ?\()
2189     (let (strlist)
2190       (while (not (eq (char-after) ?\)))
2191         (imap-forward)
2192         (push (imap-parse-astring) strlist))
2193       (imap-forward)
2194       (nreverse strlist))))
2195
2196 (defsubst imap-parse-fetch-body-section ()
2197   (let ((section
2198          (buffer-substring (point) (1- (re-search-forward "[] ]" nil t)))))
2199     (if (eq (char-before) ? )
2200         (prog1
2201             (mapconcat 'identity (cons section (imap-parse-header-list)) " ")
2202           (search-forward "]" nil t))
2203       section)))
2204
2205 (defun imap-parse-fetch (response)
2206   (when (eq (char-after) ?\()
2207     (let (uid flags envelope internaldate rfc822 rfc822header rfc822text
2208               rfc822size body bodydetail bodystructure flags-empty)
2209       (while (not (eq (char-after) ?\)))
2210         (imap-forward)
2211         (let ((token (read (current-buffer))))
2212           (imap-forward)
2213           (cond ((eq token 'UID)
2214                  (setq uid (condition-case ()
2215                                (read (current-buffer))
2216                              (error))))
2217                 ((eq token 'FLAGS)
2218                  (setq flags (imap-parse-flag-list))
2219                  (if (not flags)
2220                      (setq flags-empty 't)))
2221                 ((eq token 'ENVELOPE)
2222                  (setq envelope (imap-parse-envelope)))
2223                 ((eq token 'INTERNALDATE)
2224                  (setq internaldate (imap-parse-string)))
2225                 ((eq token 'RFC822)
2226                  (setq rfc822 (imap-parse-nstring)))
2227                 ((eq token 'RFC822.HEADER)
2228                  (setq rfc822header (imap-parse-nstring)))
2229                 ((eq token 'RFC822.TEXT)
2230                  (setq rfc822text (imap-parse-nstring)))
2231                 ((eq token 'RFC822.SIZE)
2232                  (setq rfc822size (read (current-buffer))))
2233                 ((eq token 'BODY)
2234                  (if (eq (char-before) ?\[)
2235                      (push (list
2236                             (upcase (imap-parse-fetch-body-section))
2237                             (and (eq (char-after) ?<)
2238                                  (buffer-substring (1+ (point))
2239                                                    (search-forward ">" nil t)))
2240                             (progn (imap-forward)
2241                                    (imap-parse-nstring)))
2242                            bodydetail)
2243                    (setq body (imap-parse-body))))
2244                 ((eq token 'BODYSTRUCTURE)
2245                  (setq bodystructure (imap-parse-body))))))
2246       (when uid
2247         (setq imap-current-message uid)
2248         (imap-message-put uid 'UID uid)
2249         (and (or flags flags-empty) (imap-message-put uid 'FLAGS flags))
2250         (and envelope (imap-message-put uid 'ENVELOPE envelope))
2251         (and internaldate (imap-message-put uid 'INTERNALDATE internaldate))
2252         (and rfc822 (imap-message-put uid 'RFC822 rfc822))
2253         (and rfc822header (imap-message-put uid 'RFC822.HEADER rfc822header))
2254         (and rfc822text (imap-message-put uid 'RFC822.TEXT rfc822text))
2255         (and rfc822size (imap-message-put uid 'RFC822.SIZE rfc822size))
2256         (and body (imap-message-put uid 'BODY body))
2257         (and bodydetail (imap-message-put uid 'BODYDETAIL bodydetail))
2258         (and bodystructure (imap-message-put uid 'BODYSTRUCTURE bodystructure))
2259         (run-hooks 'imap-fetch-data-hook)))))
2260
2261 ;;   mailbox-data    =  ...
2262 ;;                      "STATUS" SP mailbox SP "("
2263 ;;                            [status-att SP number
2264 ;;                            *(SP status-att SP number)] ")"
2265 ;;                      ...
2266 ;;
2267 ;;   status-att      = "MESSAGES" / "RECENT" / "UIDNEXT" / "UIDVALIDITY" /
2268 ;;                     "UNSEEN"
2269
2270 (defun imap-parse-status ()
2271   (let ((mailbox (imap-parse-mailbox)))
2272     (when (and mailbox (search-forward "(" nil t))
2273       (while (not (eq (char-after) ?\)))
2274         (let ((token (read (current-buffer))))
2275           (cond ((eq token 'MESSAGES)
2276                  (imap-mailbox-put 'messages (read (current-buffer)) mailbox))
2277                 ((eq token 'RECENT)
2278                  (imap-mailbox-put 'recent (read (current-buffer)) mailbox))
2279                 ((eq token 'UIDNEXT)
2280                  (imap-mailbox-put 'uidnext (read (current-buffer)) mailbox))
2281                 ((eq token 'UIDVALIDITY)
2282                  (and (looking-at " \\([0-9]+\\)")
2283                       (imap-mailbox-put 'uidvalidity (match-string 1) mailbox)
2284                       (goto-char (match-end 1))))
2285                 ((eq token 'UNSEEN)
2286                  (imap-mailbox-put 'unseen (read (current-buffer)) mailbox))
2287                 (t
2288                  (message "Unknown status data %s in mailbox %s ignored"
2289                           token mailbox))))))))
2290
2291 ;;   acl_data        ::= "ACL" SPACE mailbox *(SPACE identifier SPACE
2292 ;;                        rights)
2293 ;;
2294 ;;   identifier      ::= astring
2295 ;;
2296 ;;   rights          ::= astring
2297
2298 (defun imap-parse-acl ()
2299   (let ((mailbox (imap-parse-mailbox))
2300         identifier rights acl)
2301     (while (eq (char-after) ?\ )
2302       (imap-forward)
2303       (setq identifier (imap-parse-astring))
2304       (imap-forward)
2305       (setq rights (imap-parse-astring))
2306       (setq acl (append acl (list (cons identifier rights)))))
2307     (imap-mailbox-put 'acl acl mailbox)))
2308
2309 ;;   flag-list       = "(" [flag *(SP flag)] ")"
2310 ;;
2311 ;;   flag            = "\Answered" / "\Flagged" / "\Deleted" /
2312 ;;                     "\Seen" / "\Draft" / flag-keyword / flag-extension
2313 ;;                       ; Does not include "\Recent"
2314 ;;
2315 ;;   flag-keyword    = atom
2316 ;;
2317 ;;   flag-extension  = "\" atom
2318 ;;                       ; Future expansion.  Client implementations
2319 ;;                       ; MUST accept flag-extension flags.  Server
2320 ;;                       ; implementations MUST NOT generate
2321 ;;                       ; flag-extension flags except as defined by
2322 ;;                       ; future standard or standards-track
2323 ;;                       ; revisions of this specification.
2324
2325 (defun imap-parse-flag-list ()
2326   (let (flag-list start)
2327     (assert (eq (char-after) ?\() t "In imap-parse-flag-list")
2328     (while (and (not (eq (char-after) ?\)))
2329                 (setq start (progn
2330                               (imap-forward)
2331                               ;; next line for Courier IMAP bug.
2332                               (skip-chars-forward " ")
2333                               (point)))
2334                 (> (skip-chars-forward "^ )" (imap-point-at-eol)) 0))
2335       (push (buffer-substring start (point)) flag-list))
2336     (assert (eq (char-after) ?\)) t "In imap-parse-flag-list")
2337     (imap-forward)
2338     (nreverse flag-list)))
2339
2340 ;;   envelope        = "(" env-date SP env-subject SP env-from SP env-sender SP
2341 ;;                     env-reply-to SP env-to SP env-cc SP env-bcc SP
2342 ;;                     env-in-reply-to SP env-message-id ")"
2343 ;;
2344 ;;   env-bcc         = "(" 1*address ")" / nil
2345 ;;
2346 ;;   env-cc          = "(" 1*address ")" / nil
2347 ;;
2348 ;;   env-date        = nstring
2349 ;;
2350 ;;   env-from        = "(" 1*address ")" / nil
2351 ;;
2352 ;;   env-in-reply-to = nstring
2353 ;;
2354 ;;   env-message-id  = nstring
2355 ;;
2356 ;;   env-reply-to    = "(" 1*address ")" / nil
2357 ;;
2358 ;;   env-sender      = "(" 1*address ")" / nil
2359 ;;
2360 ;;   env-subject     = nstring
2361 ;;
2362 ;;   env-to          = "(" 1*address ")" / nil
2363
2364 (defun imap-parse-envelope ()
2365   (when (eq (char-after) ?\()
2366     (imap-forward)
2367     (vector (prog1 (imap-parse-nstring);; date
2368               (imap-forward))
2369             (prog1 (imap-parse-nstring);; subject
2370               (imap-forward))
2371             (prog1 (imap-parse-address-list);; from
2372               (imap-forward))
2373             (prog1 (imap-parse-address-list);; sender
2374               (imap-forward))
2375             (prog1 (imap-parse-address-list);; reply-to
2376               (imap-forward))
2377             (prog1 (imap-parse-address-list);; to
2378               (imap-forward))
2379             (prog1 (imap-parse-address-list);; cc
2380               (imap-forward))
2381             (prog1 (imap-parse-address-list);; bcc
2382               (imap-forward))
2383             (prog1 (imap-parse-nstring);; in-reply-to
2384               (imap-forward))
2385             (prog1 (imap-parse-nstring);; message-id
2386               (imap-forward)))))
2387
2388 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2389
2390 (defsubst imap-parse-string-list ()
2391   (cond ((eq (char-after) ?\();; body-fld-param
2392          (let (strlist str)
2393            (imap-forward)
2394            (while (setq str (imap-parse-string))
2395              (push str strlist)
2396              ;; buggy stalker communigate pro 3.0 doesn't print SPC
2397              ;; between body-fld-param's sometimes
2398              (or (eq (char-after) ?\")
2399                  (imap-forward)))
2400            (nreverse strlist)))
2401         ((imap-parse-nil)
2402          nil)))
2403
2404 ;;   body-extension  = nstring / number /
2405 ;;                      "(" body-extension *(SP body-extension) ")"
2406 ;;                       ; Future expansion.  Client implementations
2407 ;;                       ; MUST accept body-extension fields.  Server
2408 ;;                       ; implementations MUST NOT generate
2409 ;;                       ; body-extension fields except as defined by
2410 ;;                       ; future standard or standards-track
2411 ;;                       ; revisions of this specification.
2412
2413 (defun imap-parse-body-extension ()
2414   (if (eq (char-after) ?\()
2415       (let (b-e)
2416         (imap-forward)
2417         (push (imap-parse-body-extension) b-e)
2418         (while (eq (char-after) ?\ )
2419           (imap-forward)
2420           (push (imap-parse-body-extension) b-e))
2421         (assert (eq (char-after) ?\)) t "In imap-parse-body-extension")
2422         (imap-forward)
2423         (nreverse b-e))
2424     (or (imap-parse-number)
2425         (imap-parse-nstring))))
2426
2427 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2428 ;;                     *(SP body-extension)]]
2429 ;;                       ; MUST NOT be returned on non-extensible
2430 ;;                       ; "BODY" fetch
2431 ;;
2432 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2433 ;;                     *(SP body-extension)]]
2434 ;;                       ; MUST NOT be returned on non-extensible
2435 ;;                       ; "BODY" fetch
2436
2437 (defsubst imap-parse-body-ext ()
2438   (let (ext)
2439     (when (eq (char-after) ?\ );; body-fld-dsp
2440       (imap-forward)
2441       (let (dsp)
2442         (if (eq (char-after) ?\()
2443             (progn
2444               (imap-forward)
2445               (push (imap-parse-string) dsp)
2446               (imap-forward)
2447               (push (imap-parse-string-list) dsp)
2448               (imap-forward))
2449           (assert (imap-parse-nil) t "In imap-parse-body-ext"))
2450         (push (nreverse dsp) ext))
2451       (when (eq (char-after) ?\ );; body-fld-lang
2452         (imap-forward)
2453         (if (eq (char-after) ?\()
2454             (push (imap-parse-string-list) ext)
2455           (push (imap-parse-nstring) ext))
2456         (while (eq (char-after) ?\ );; body-extension
2457           (imap-forward)
2458           (setq ext (append (imap-parse-body-extension) ext)))))
2459     ext))
2460
2461 ;;   body            = "(" body-type-1part / body-type-mpart ")"
2462 ;;
2463 ;;   body-ext-1part  = body-fld-md5 [SP body-fld-dsp [SP body-fld-lang
2464 ;;                     *(SP body-extension)]]
2465 ;;                       ; MUST NOT be returned on non-extensible
2466 ;;                       ; "BODY" fetch
2467 ;;
2468 ;;   body-ext-mpart  = body-fld-param [SP body-fld-dsp [SP body-fld-lang
2469 ;;                     *(SP body-extension)]]
2470 ;;                       ; MUST NOT be returned on non-extensible
2471 ;;                       ; "BODY" fetch
2472 ;;
2473 ;;   body-fields     = body-fld-param SP body-fld-id SP body-fld-desc SP
2474 ;;                     body-fld-enc SP body-fld-octets
2475 ;;
2476 ;;   body-fld-desc   = nstring
2477 ;;
2478 ;;   body-fld-dsp    = "(" string SP body-fld-param ")" / nil
2479 ;;
2480 ;;   body-fld-enc    = (DQUOTE ("7BIT" / "8BIT" / "BINARY" / "BASE64"/
2481 ;;                     "QUOTED-PRINTABLE") DQUOTE) / string
2482 ;;
2483 ;;   body-fld-id     = nstring
2484 ;;
2485 ;;   body-fld-lang   = nstring / "(" string *(SP string) ")"
2486 ;;
2487 ;;   body-fld-lines  = number
2488 ;;
2489 ;;   body-fld-md5    = nstring
2490 ;;
2491 ;;   body-fld-octets = number
2492 ;;
2493 ;;   body-fld-param  = "(" string SP string *(SP string SP string) ")" / nil
2494 ;;
2495 ;;   body-type-1part = (body-type-basic / body-type-msg / body-type-text)
2496 ;;                     [SP body-ext-1part]
2497 ;;
2498 ;;   body-type-basic = media-basic SP body-fields
2499 ;;                       ; MESSAGE subtype MUST NOT be "RFC822"
2500 ;;
2501 ;;   body-type-msg   = media-message SP body-fields SP envelope
2502 ;;                     SP body SP body-fld-lines
2503 ;;
2504 ;;   body-type-text  = media-text SP body-fields SP body-fld-lines
2505 ;;
2506 ;;   body-type-mpart = 1*body SP media-subtype
2507 ;;                     [SP body-ext-mpart]
2508 ;;
2509 ;;   media-basic     = ((DQUOTE ("APPLICATION" / "AUDIO" / "IMAGE" /
2510 ;;                     "MESSAGE" / "VIDEO") DQUOTE) / string) SP media-subtype
2511 ;;                       ; Defined in [MIME-IMT]
2512 ;;
2513 ;;   media-message   = DQUOTE "MESSAGE" DQUOTE SP DQUOTE "RFC822" DQUOTE
2514 ;;                      ; Defined in [MIME-IMT]
2515 ;;
2516 ;;   media-subtype   = string
2517 ;;                       ; Defined in [MIME-IMT]
2518 ;;
2519 ;;   media-text      = DQUOTE "TEXT" DQUOTE SP media-subtype
2520 ;;                       ; Defined in [MIME-IMT]
2521
2522 (defun imap-parse-body ()
2523   (let (body)
2524     (when (eq (char-after) ?\()
2525       (imap-forward)
2526       (if (eq (char-after) ?\()
2527           (let (subbody)
2528             (while (and (eq (char-after) ?\()
2529                         (setq subbody (imap-parse-body)))
2530               ;; buggy stalker communigate pro 3.0 insert a SPC between
2531               ;; parts in multiparts
2532               (when (and (eq (char-after) ?\ )
2533                          (eq (char-after (1+ (point))) ?\())
2534                 (imap-forward))
2535               (push subbody body))
2536             (imap-forward)
2537             (push (imap-parse-string) body);; media-subtype
2538             (when (eq (char-after) ?\ );; body-ext-mpart:
2539               (imap-forward)
2540               (if (eq (char-after) ?\();; body-fld-param
2541                   (push (imap-parse-string-list) body)
2542                 (push (and (imap-parse-nil) nil) body))
2543               (setq body
2544                     (append (imap-parse-body-ext) body)));; body-ext-...
2545             (assert (eq (char-after) ?\)) t "In imap-parse-body")
2546             (imap-forward)
2547             (nreverse body))
2548
2549         (push (imap-parse-string) body);; media-type
2550         (imap-forward)
2551         (push (imap-parse-string) body);; media-subtype
2552         (imap-forward)
2553         ;; next line for Sun SIMS bug
2554         (and (eq (char-after) ? ) (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         (imap-forward)
2559         (push (imap-parse-nstring) body);; body-fld-id
2560         (imap-forward)
2561         (push (imap-parse-nstring) body);; body-fld-desc
2562         (imap-forward)
2563         ;; next `or' for Sun SIMS bug, it regard body-fld-enc as a
2564         ;; nstring and return nil instead of defaulting back to 7BIT
2565         ;; as the standard says.
2566         (push (or (imap-parse-nstring) "7BIT") body);; body-fld-enc
2567         (imap-forward)
2568         (push (imap-parse-number) body);; body-fld-octets
2569
2570         ;; ok, we're done parsing the required parts, what comes now is one
2571         ;; of three things:
2572         ;;
2573         ;; envelope       (then we're parsing body-type-msg)
2574         ;; body-fld-lines (then we're parsing body-type-text)
2575         ;; body-ext-1part (then we're parsing body-type-basic)
2576         ;;
2577         ;; the problem is that the two first are in turn optionally followed
2578         ;; by the third.  So we parse the first two here (if there are any)...
2579
2580         (when (eq (char-after) ?\ )
2581           (imap-forward)
2582           (let (lines)
2583             (cond ((eq (char-after) ?\();; body-type-msg:
2584                    (push (imap-parse-envelope) body);; envelope
2585                    (imap-forward)
2586                    (push (imap-parse-body) body);; body
2587                    ;; buggy stalker communigate pro 3.0 doesn't print
2588                    ;; number of lines in message/rfc822 attachment
2589                    (if (eq (char-after) ?\))
2590                        (push 0 body)
2591                      (imap-forward)
2592                      (push (imap-parse-number) body))) ;; body-fld-lines
2593                   ((setq lines (imap-parse-number))    ;; body-type-text:
2594                    (push lines body))                  ;; body-fld-lines
2595                   (t
2596                    (backward-char)))))                 ;; no match...
2597
2598         ;; ...and then parse the third one here...
2599
2600         (when (eq (char-after) ?\ );; body-ext-1part:
2601           (imap-forward)
2602           (push (imap-parse-nstring) body);; body-fld-md5
2603           (setq body (append (imap-parse-body-ext) body)));; body-ext-1part..
2604
2605         (assert (eq (char-after) ?\)) t "In imap-parse-body 2")
2606         (imap-forward)
2607         (nreverse body)))))
2608
2609 (when imap-debug                        ; (untrace-all)
2610   (require 'trace)
2611   (buffer-disable-undo (get-buffer-create imap-debug-buffer))
2612   (mapcar (lambda (f) (trace-function-background f imap-debug-buffer))
2613           '(
2614             imap-read-passwd
2615             imap-utf7-encode
2616             imap-utf7-decode
2617             imap-error-text
2618             imap-kerberos4s-p
2619             imap-kerberos4-open
2620             imap-ssl-p
2621             imap-ssl-open
2622             imap-network-p
2623             imap-network-open
2624             imap-interactive-login
2625             imap-kerberos4a-p
2626             imap-kerberos4-auth
2627             imap-cram-md5-p
2628             imap-cram-md5-auth
2629             imap-login-p
2630             imap-login-auth
2631             imap-anonymous-p
2632             imap-anonymous-auth
2633             imap-open-1
2634             imap-open
2635             imap-opened
2636             imap-authenticate
2637             imap-close
2638             imap-capability
2639             imap-namespace
2640             imap-send-command-wait
2641             imap-mailbox-put
2642             imap-mailbox-get
2643             imap-mailbox-map-1
2644             imap-mailbox-map
2645             imap-current-mailbox
2646             imap-current-mailbox-p-1
2647             imap-current-mailbox-p
2648             imap-mailbox-select-1
2649             imap-mailbox-select
2650             imap-mailbox-examine-1
2651             imap-mailbox-examine
2652             imap-mailbox-unselect
2653             imap-mailbox-expunge
2654             imap-mailbox-close
2655             imap-mailbox-create-1
2656             imap-mailbox-create
2657             imap-mailbox-delete
2658             imap-mailbox-rename
2659             imap-mailbox-lsub
2660             imap-mailbox-list
2661             imap-mailbox-subscribe
2662             imap-mailbox-unsubscribe
2663             imap-mailbox-status
2664             imap-mailbox-acl-get
2665             imap-mailbox-acl-set
2666             imap-mailbox-acl-delete
2667             imap-current-message
2668             imap-list-to-message-set
2669             imap-fetch-asynch
2670             imap-fetch
2671             imap-message-put
2672             imap-message-get
2673             imap-message-map
2674             imap-search
2675             imap-message-flag-permanent-p
2676             imap-message-flags-set
2677             imap-message-flags-del
2678             imap-message-flags-add
2679             imap-message-copyuid-1
2680             imap-message-copyuid
2681             imap-message-copy
2682             imap-message-appenduid-1
2683             imap-message-appenduid
2684             imap-message-append
2685             imap-body-lines
2686             imap-envelope-from
2687             imap-send-command-1
2688             imap-send-command
2689             imap-wait-for-tag
2690             imap-sentinel
2691             imap-find-next-line
2692             imap-arrival-filter
2693             imap-parse-greeting
2694             imap-parse-response
2695             imap-parse-resp-text
2696             imap-parse-resp-text-code
2697             imap-parse-data-list
2698             imap-parse-fetch
2699             imap-parse-status
2700             imap-parse-acl
2701             imap-parse-flag-list
2702             imap-parse-envelope
2703             imap-parse-body-extension
2704             imap-parse-body
2705             )))
2706
2707 (provide 'imap)
2708
2709 ;;; imap.el ends here