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