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