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