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