6c60bb443004ad5edd5f07bb4bdc87e58b1ec521
[elisp/wanderlust.git] / elmo / elmo-imap4.el
1 ;;; elmo-imap4.el --- IMAP4 Interface for ELMO.
2
3 ;; Copyright (C) 1998,1999,2000 Yuuichi Teranishi <teranisi@gohome.org>
4 ;; Copyright (C) 1999,2000      Kenichi OKADA <okada@opaopa.org>
5 ;; Copyright (C) 2000           OKAZAKI Tetsurou <okazaki@be.to>
6 ;; Copyright (C) 2000           Daiki Ueno <ueno@unixuser.org>
7
8 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
9 ;;      Kenichi OKADA <okada@opaopa.org>
10 ;;      OKAZAKI Tetsurou <okazaki@be.to>
11 ;;      Daiki Ueno <ueno@unixuser.org>
12 ;; Keywords: mail, net news
13
14 ;; This file is part of ELMO (Elisp Library for Message Orchestration).
15
16 ;; This program is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20 ;;
21 ;; This program is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 ;; GNU General Public License for more details.
25 ;;
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
28 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
29 ;; Boston, MA 02111-1307, USA.
30 ;;
31
32 ;;; Commentary:
33 ;;
34 ;; Origin of IMAP parser part is imap.el, included in Gnus.
35 ;;
36 ;;    Copyright (C) 1998, 1999, 2000
37 ;;    Free Software Foundation, Inc.
38 ;;    Author: Simon Josefsson <jas@pdc.kth.se>
39 ;;
40
41 (require 'elmo-vars)
42 (require 'elmo-util)
43 (require 'elmo-date)
44 (require 'elmo-msgdb)
45 (require 'elmo-cache)
46 (require 'elmo)
47 (require 'elmo-net)
48 (require 'utf7)
49 (require 'elmo-mime)
50
51 ;;; Code:
52 (eval-when-compile (require 'cl))
53
54 (defvar elmo-imap4-disuse-server-flag-mailbox-regexp "^#mh" ; UW imapd
55   "Regexp to match IMAP4 mailbox names whose message flags on server should be ignored (For STATUS command).")
56
57 (defvar elmo-imap4-overview-fetch-chop-length 200
58   "*Number of overviews to fetch in one request.")
59
60 ;; c.f. rfc2683 3.2.1.5 Long Command Lines
61 ;;
62 ;; "A client should limit the length of the command lines it generates
63 ;;  to approximately 1000 octets (including all quoted strings but not
64 ;;  including literals). If the client is unable to group things into
65 ;;  ranges so that the command line is within that length, it should
66 ;;  split the request into multiple commands. The client should use
67 ;;  literals instead of long quoted strings, in order to keep the command
68 ;;  length down.
69 ;;  For its part, a server should allow for a command line of at least
70 ;;  8000 octets. This provides plenty of leeway for accepting reasonable
71 ;;  length commands from clients. The server should send a BAD response
72 ;;  to a command that does not end within the server's maximum accepted
73 ;;  command length. "
74
75 ;; To limit command line length, chop number set.
76 (defvar elmo-imap4-number-set-chop-length 1000
77   "*Number of messages to specify as a number-set argument for one request.")
78
79 (defvar elmo-imap4-force-login nil
80   "*Non-nil forces to try 'login' if there is no 'auth' capability in imapd.")
81
82 (defvar elmo-imap4-use-select-to-update-status nil
83   "*Some imapd have to send select command to update status.
84 \(ex. UW imapd 4.5-BETA?\).  For these imapd, you must set this variable t.")
85
86 (defvar elmo-imap4-use-modified-utf7 nil
87   "*Use mofidied UTF-7 (rfc2060) encoding for IMAP4 folder name.")
88
89 (defvar elmo-imap4-use-cache t
90   "Use cache in imap4 folder.")
91
92 (defvar elmo-imap4-extra-namespace-alist
93   '(("^\\({.*/nntp}\\).*$" . ".")) ; Default is for UW's remote nntp mailbox...
94   "Extra namespace alist.
95 A list of cons cell like: (REGEXP . DELIMITER).
96 REGEXP should have a grouping for namespace prefix.")
97 ;;
98 ;;; internal variables
99 ;;
100 (defvar elmo-imap4-seq-prefix "elmo-imap4")
101 (defvar elmo-imap4-seqno 0)
102 (defvar elmo-imap4-use-uid t
103   "Use UID as message number.")
104
105 (defvar elmo-imap4-current-response nil)
106 (defvar elmo-imap4-status nil)
107 (defvar elmo-imap4-reached-tag "elmo-imap40")
108
109 ;;; buffer local variables
110 (defvar elmo-imap4-default-hierarchy-delimiter "/")
111
112 (defvar elmo-imap4-server-capability nil)
113 (defvar elmo-imap4-server-namespace nil)
114
115 (defvar elmo-imap4-parsing nil) ; indicates parsing.
116
117 (defvar elmo-imap4-fetch-callback nil)
118 (defvar elmo-imap4-fetch-callback-data nil)
119 (defvar elmo-imap4-status-callback nil)
120 (defvar elmo-imap4-status-callback-data nil)
121
122 (defvar elmo-imap4-server-diff-async-callback nil)
123 (defvar elmo-imap4-server-diff-async-callback-data nil)
124
125 ;;; progress...(no use?)
126 (defvar elmo-imap4-count-progress nil)
127 (defvar elmo-imap4-count-progress-message nil)
128 (defvar elmo-imap4-progress-count nil)
129
130 ;;; XXX Temporal implementation
131 (defvar elmo-imap4-current-msgdb nil)
132 (defvar elmo-imap4-seen-messages nil)
133
134 (defvar elmo-imap4-local-variables
135   '(elmo-imap4-status
136     elmo-imap4-current-response
137     elmo-imap4-seqno
138     elmo-imap4-parsing
139     elmo-imap4-reached-tag
140     elmo-imap4-count-progress
141     elmo-imap4-count-progress-message
142     elmo-imap4-progress-count
143     elmo-imap4-fetch-callback
144     elmo-imap4-fetch-callback-data
145     elmo-imap4-status-callback
146     elmo-imap4-status-callback-data
147     elmo-imap4-current-msgdb
148     elmo-imap4-seen-messages))
149
150 ;;;;
151
152 (defconst elmo-imap4-quoted-specials-list '(?\\ ?\"))
153
154 (defconst elmo-imap4-non-atom-char-regex
155   (eval-when-compile
156     (concat "[^" "]!#$&'+,./0-9:;<=>?@A-Z[^_`a-z|}~-" "]")))
157
158 (defconst elmo-imap4-non-text-char-regex
159   (eval-when-compile
160     (concat "[^"
161             "]\x01-\x09\x0b\x0c\x0e-\x1f\x7f !\"#$%&'()*+,./0-9:;<=>?@A-Z[\\^_`a-z{|}~-"
162             "]")))
163
164 (defconst elmo-imap4-literal-threshold 1024
165  "Limitation of characters that can be used in a quoted string.")
166
167 (defconst elmo-imap4-flag-specs '((important "\\Flagged")
168                                   (read "\\Seen")
169                                   (unread "\\Seen" 'remove)
170                                   (answered "\\Answered")
171                                   ;; draft-melnikov-imap-keywords-03.txt
172                                   (forwarded "$Forwarded")
173                                   (work "$Work")
174                                   (personal "$Personal")
175                                   (shouldreply "$ShouldReply")))
176
177 ;; For debugging.
178 (defvar elmo-imap4-debug nil
179   "Non-nil forces IMAP4 folder as debug mode.
180 Debug information is inserted in the buffer \"*IMAP4 DEBUG*\"")
181
182 (defvar elmo-imap4-debug-inhibit-logging nil)
183
184 ;;; ELMO IMAP4 folder
185 (eval-and-compile
186   (luna-define-class elmo-imap4-folder (elmo-net-folder)
187                      (mailbox))
188   (luna-define-internal-accessors 'elmo-imap4-folder))
189
190 ;;; Session
191 (eval-and-compile
192   (luna-define-class elmo-imap4-session (elmo-network-session)
193                      (capability current-mailbox read-only flags))
194   (luna-define-internal-accessors 'elmo-imap4-session))
195
196 ;;; MIME-ELMO-IMAP Location
197 (eval-and-compile
198   (luna-define-class mime-elmo-imap-location
199                      (mime-imap-location)
200                      (folder number rawbuf strategy))
201   (luna-define-internal-accessors 'mime-elmo-imap-location))
202
203 ;;; Debug
204 (defmacro elmo-imap4-debug (message &rest args)
205   (` (if elmo-imap4-debug
206          (elmo-imap4-debug-1 (, message) (,@ args)))))
207
208 (defun elmo-imap4-debug-1 (message &rest args)
209   (with-current-buffer (get-buffer-create "*IMAP4 DEBUG*")
210     (goto-char (point-max))
211     (if elmo-imap4-debug-inhibit-logging
212         (insert "NO LOGGING\n")
213       (insert (apply 'format message args) "\n"))))
214
215 (defsubst elmo-imap4-decode-folder-string (string)
216   (if elmo-imap4-use-modified-utf7
217       (utf7-decode-string string 'imap)
218     string))
219
220 (defsubst elmo-imap4-encode-folder-string (string)
221   (if elmo-imap4-use-modified-utf7
222       (utf7-encode-string string 'imap)
223     string))
224
225 ;;; Response
226
227 (defmacro elmo-imap4-response-continue-req-p (response)
228   "Returns non-nil if RESPONSE is '+' response."
229   (` (assq 'continue-req (, response))))
230
231 (defmacro elmo-imap4-response-ok-p (response)
232   "Returns non-nil if RESPONSE is an 'OK' response."
233   (` (assq 'ok (, response))))
234
235 (defmacro elmo-imap4-response-bye-p (response)
236   "Returns non-nil if RESPONSE is an 'BYE' response."
237   (` (assq 'bye (, response))))
238
239 (defmacro elmo-imap4-response-garbage-p (response)
240   "Returns non-nil if RESPONSE is an 'garbage' response."
241   (` (assq 'garbage (, response))))
242
243 (defmacro elmo-imap4-response-value (response symbol)
244   "Get value of the SYMBOL from RESPONSE."
245   (` (nth 1 (assq (, symbol) (, response)))))
246
247 (defsubst elmo-imap4-response-value-all (response symbol)
248   "Get all value of the SYMBOL from RESPONSE."
249   (let (matched)
250     (while response
251       (if (eq (car (car response)) symbol)
252           (setq matched (nconc matched (nth 1 (car response)))))
253       (setq response (cdr response)))
254     matched))
255
256 (defmacro elmo-imap4-response-error-text (response)
257   "Returns text of NO, BAD, BYE response."
258   (` (nth 1 (or (elmo-imap4-response-value (, response) 'no)
259                 (elmo-imap4-response-value (, response) 'bad)
260                 (elmo-imap4-response-value (, response) 'bye)))))
261
262 (defmacro elmo-imap4-response-bodydetail-text (response)
263   "Returns text of BODY[section]<partial>."
264   (` (nth 3 (assq 'bodydetail (, response)))))
265
266 ;;; Session commands.
267
268 ; (defun elmo-imap4-send-command-wait (session command)
269 ;   "Send COMMAND to the SESSION and wait for response.
270 ; Returns RESPONSE (parsed lisp object) of IMAP session."
271 ;   (elmo-imap4-read-response session
272 ;                           (elmo-imap4-send-command
273 ;                            session
274 ;                            command)))
275
276 (defun elmo-imap4-send-command-wait (session command)
277   "Send COMMAND to the SESSION.
278 Returns RESPONSE (parsed lisp object) of IMAP session.
279 If response is not `OK', causes error with IMAP response text."
280   (elmo-imap4-accept-ok session
281                         (elmo-imap4-send-command
282                          session
283                          command)))
284
285 (defun elmo-imap4-send-command (session command)
286   "Send COMMAND to the SESSION.
287 Returns a TAG string which is assigned to the COMMAND."
288   (let* ((command-args (if (listp command)
289                            command
290                          (list command)))
291          (process (elmo-network-session-process-internal session))
292          cmdstr tag token kind)
293     (with-current-buffer (process-buffer process)
294       (setq tag (concat elmo-imap4-seq-prefix
295                         (number-to-string
296                          (setq elmo-imap4-seqno (+ 1 elmo-imap4-seqno)))))
297       (setq cmdstr (concat tag " "))
298       ;; (erase-buffer) No need.
299       (goto-char (point-min))
300       (when (elmo-imap4-response-bye-p elmo-imap4-current-response)
301         (elmo-imap4-process-bye session))
302       (setq elmo-imap4-current-response nil)
303       (when elmo-imap4-parsing
304         (message "Waiting for IMAP response...")
305         (accept-process-output (elmo-network-session-process-internal
306                                 session))
307         (message "Waiting for IMAP response...done"))
308       (setq elmo-imap4-parsing t)
309       (elmo-imap4-debug "<-(%s)- %s" tag command)
310       (while (setq token (car command-args))
311         (cond ((stringp token)   ; formatted
312                (setq cmdstr (concat cmdstr token)))
313               ((listp token)     ; unformatted
314                (setq kind (car token))
315                (cond ((eq kind 'atom)
316                       (setq cmdstr (concat cmdstr (nth 1 token))))
317                      ((eq kind 'quoted)
318                       (setq cmdstr (concat
319                                     cmdstr
320                                     (elmo-imap4-format-quoted (nth 1 token)))))
321                      ((eq kind 'literal)
322                       (setq cmdstr (concat cmdstr
323                                            (format "{%d}" (nth 2 token))))
324                       (process-send-string process cmdstr)
325                       (process-send-string process "\r\n")
326                       (setq cmdstr nil)
327                       (elmo-imap4-accept-continue-req session)
328                       (cond ((stringp (nth 1 token))
329                              (setq cmdstr (nth 1 token)))
330                             ((bufferp (nth 1 token))
331                              (with-current-buffer (nth 1 token)
332                                (process-send-region
333                                 process
334                                 (point-min)
335                                 (+ (point-min) (nth 2 token)))))
336                             (t
337                              (error "Wrong argument for literal"))))
338                      (t
339                       (error "Unknown token kind %s" kind))))
340               (t
341                (error "Invalid argument")))
342         (setq command-args (cdr command-args)))
343       (if cmdstr
344           (process-send-string process cmdstr))
345       (process-send-string process "\r\n")
346       tag)))
347
348 (defun elmo-imap4-send-string (session string)
349   "Send STRING to the SESSION."
350   (with-current-buffer (process-buffer
351                         (elmo-network-session-process-internal session))
352     (setq elmo-imap4-current-response nil)
353     (goto-char (point-min))
354     (elmo-imap4-debug "<-- %s" string)
355     (process-send-string (elmo-network-session-process-internal session)
356                          string)
357     (process-send-string (elmo-network-session-process-internal session)
358                          "\r\n")))
359
360 (defun elmo-imap4-read-response (session tag)
361   "Read parsed response from SESSION.
362 TAG is the tag of the command"
363   (with-current-buffer (process-buffer
364                         (elmo-network-session-process-internal session))
365     (while (not (or (string= tag elmo-imap4-reached-tag)
366                     (elmo-imap4-response-bye-p elmo-imap4-current-response)
367                     (when (elmo-imap4-response-garbage-p
368                            elmo-imap4-current-response)
369                       (message "Garbage response: %s"
370                                (elmo-imap4-response-value
371                                 elmo-imap4-current-response
372                                 'garbage))
373                       t)))
374       (when (memq (process-status
375                    (elmo-network-session-process-internal session))
376                   '(open run))
377         (accept-process-output (elmo-network-session-process-internal session)
378                                1)))
379     (elmo-imap4-debug "=>%s" (prin1-to-string elmo-imap4-current-response))
380     (setq elmo-imap4-parsing nil)
381     elmo-imap4-current-response))
382
383 (defsubst elmo-imap4-read-untagged (process)
384   (with-current-buffer (process-buffer process)
385     (while (not elmo-imap4-current-response)
386       (accept-process-output process 1))
387     (elmo-imap4-debug "=>%s" (prin1-to-string elmo-imap4-current-response))
388     elmo-imap4-current-response))
389
390 (defun elmo-imap4-read-continue-req (session)
391   "Returns a text following to continue-req in SESSION.
392 If response is not `+' response, returns nil."
393   (elmo-imap4-response-value
394    (elmo-imap4-read-untagged
395     (elmo-network-session-process-internal session))
396    'continue-req))
397
398 (defun elmo-imap4-process-bye (session)
399   (with-current-buffer (elmo-network-session-buffer session)
400     (let ((r elmo-imap4-current-response))
401       (setq elmo-imap4-current-response nil)
402       (elmo-network-close-session session)
403       (signal 'elmo-imap4-bye-error
404               (list (concat (elmo-imap4-response-error-text r))
405                     "Try Again")))))
406
407 (defun elmo-imap4-accept-continue-req (session)
408   "Returns non-nil if `+' (continue-req) response is arrived in SESSION.
409 If response is not `+' response, cause an error."
410   (let (response)
411     (setq response
412           (elmo-imap4-read-untagged
413            (elmo-network-session-process-internal session)))
414     (or (elmo-imap4-response-continue-req-p response)
415         (error "IMAP error: %s"
416                (or (elmo-imap4-response-error-text response)
417                    "No continut-req from server.")))))
418
419 (defun elmo-imap4-read-ok (session tag)
420   "Returns non-nil if `OK' response of the command with TAG is arrived
421 in SESSION. If response is not `OK' response, returns nil."
422   (elmo-imap4-response-ok-p
423    (elmo-imap4-read-response session tag)))
424
425 (defun elmo-imap4-accept-ok (session tag)
426   "Accept only `OK' response from SESSION.
427 If response is not `OK' response, causes error with IMAP response text."
428   (let ((response (elmo-imap4-read-response session tag)))
429     (if (elmo-imap4-response-ok-p response)
430         response
431       (if (elmo-imap4-response-bye-p response)
432           (elmo-imap4-process-bye session)
433         (error "IMAP error: %s"
434                (or (elmo-imap4-response-error-text response)
435                    "No `OK' response from server."))))))
436
437 ;;; MIME-ELMO-IMAP Location
438 (luna-define-method mime-imap-location-section-body ((location
439                                                       mime-elmo-imap-location)
440                                                      section)
441   (if (and (stringp section)
442            (string= section "HEADER"))
443       ;; Even in the section mode, header fields should be saved to the
444       ;; raw buffer .
445       (with-current-buffer (mime-elmo-imap-location-rawbuf-internal location)
446         (erase-buffer)
447         (elmo-message-fetch
448          (mime-elmo-imap-location-folder-internal location)
449          (mime-elmo-imap-location-number-internal location)
450          (mime-elmo-imap-location-strategy-internal location)
451          section
452          (current-buffer)
453          'unseen)
454         (buffer-string))
455     (elmo-message-fetch
456      (mime-elmo-imap-location-folder-internal location)
457      (mime-elmo-imap-location-number-internal location)
458      (mime-elmo-imap-location-strategy-internal location)
459      section
460      nil 'unseen)))
461
462
463 (luna-define-method mime-imap-location-bodystructure
464   ((location mime-elmo-imap-location))
465   (elmo-message-fetch-bodystructure
466    (mime-elmo-imap-location-folder-internal location)
467    (mime-elmo-imap-location-number-internal location)
468    (mime-elmo-imap-location-strategy-internal location)))
469
470 (luna-define-method mime-imap-location-fetch-entity-p
471   ((location mime-elmo-imap-location) entity)
472   (or (not elmo-message-displaying) ; Fetching entity to save or force display.
473       ;; cache exists
474       (file-exists-p
475        (expand-file-name
476         (mmimap-entity-section (mime-entity-node-id-internal entity))
477         (elmo-fetch-strategy-cache-path
478          (mime-elmo-imap-location-strategy-internal location))))
479       ;; not too large to fetch.
480       (> elmo-message-fetch-threshold
481          (or (mime-imap-entity-size-internal entity) 0))))
482
483 ;;;
484
485 (defun elmo-imap4-session-check (session)
486   (with-current-buffer (elmo-network-session-buffer session)
487     (setq elmo-imap4-fetch-callback nil)
488     (setq elmo-imap4-fetch-callback-data nil))
489   (elmo-imap4-send-command session "check"))
490
491 (defun elmo-imap4-atom-p (string)
492   "Return t if STRING is an atom defined in rfc2060."
493   (if (string= string "")
494       nil
495     (save-match-data
496       (not (string-match elmo-imap4-non-atom-char-regex string)))))
497
498 (defun elmo-imap4-quotable-p (string)
499   "Return t if STRING can be formatted as a quoted defined in rfc2060."
500   (save-match-data
501     (not (string-match elmo-imap4-non-text-char-regex string))))
502
503 (defun elmo-imap4-nil (string)
504   "Return a list represents the special atom \"NIL\" defined in rfc2060, \
505 if STRING is nil.
506 Otherwise return nil."
507   (if (eq string nil)
508       (list 'atom "NIL")))
509
510 (defun elmo-imap4-atom (string)
511   "Return a list represents STRING as an atom defined in rfc2060.
512 Return nil if STRING is not an atom.  See `elmo-imap4-atom-p'."
513   (if (elmo-imap4-atom-p string)
514       (list 'atom string)))
515
516 (defun elmo-imap4-quoted (string)
517   "Return a list represents STRING as a quoted defined in rfc2060.
518 Return nil if STRING can not be formatted as a quoted.  See `elmo-imap4-quotable-p'."
519   (if (elmo-imap4-quotable-p string)
520       (list 'quoted string)))
521
522 (defun elmo-imap4-literal-1 (string-or-buffer length)
523   "Internal function for `elmo-imap4-literal' and `elmo-imap4-buffer-literal'.
524 Return a list represents STRING-OR-BUFFER as a literal defined in rfc2060.
525 STRING-OR-BUFFER must be an encoded string or a single-byte string or a single-byte buffer.
526 LENGTH must be the number of octets for STRING-OR-BUFFER."
527   (list 'literal string-or-buffer length))
528
529 (defun elmo-imap4-literal (string)
530   "Return a list represents STRING as a literal defined in rfc2060.
531 STRING must be an encoded or a single-byte string."
532   (elmo-imap4-literal-1 string (length string)))
533
534 (defun elmo-imap4-buffer-literal (buffer)
535   "Return a list represents BUFFER as a literal defined in rfc2060.
536 BUFFER must be a single-byte buffer."
537   (elmo-imap4-literal-1 buffer (with-current-buffer buffer
538                                  (buffer-size))))
539
540 (defun elmo-imap4-string-1 (string length)
541   "Internal function for `elmo-imap4-string' and `elmo-imap4-buffer-string'.
542 Return a list represents STRING as a string defined in rfc2060.
543 STRING must be an encoded or a single-byte string.
544 LENGTH must be the number of octets for STRING."
545   (or (elmo-imap4-quoted string)
546       (elmo-imap4-literal-1 string length)))
547
548 (defun elmo-imap4-string (string)
549   "Return a list represents STRING as a string defined in rfc2060.
550 STRING must be an encoded or a single-byte string."
551   (let ((length (length string)))
552     (if (< elmo-imap4-literal-threshold length)
553         (elmo-imap4-literal-1 string length)
554       (elmo-imap4-string-1 string length))))
555
556 (defun elmo-imap4-buffer-string (buffer)
557   "Return a list represents BUFFER as a string defined in rfc2060.
558 BUFFER must be a single-byte buffer."
559   (let ((length (with-current-buffer buffer
560                   (buffer-size))))
561     (if (< elmo-imap4-literal-threshold length)
562         (elmo-imap4-literal-1 buffer length)
563       (elmo-imap4-string-1 (with-current-buffer buffer
564                              (buffer-string))
565                            length))))
566
567 (defun elmo-imap4-astring-1 (string length)
568   "Internal function for `elmo-imap4-astring' and `elmo-imap4-buffer-astring'.
569 Return a list represents STRING as an astring defined in rfc2060.
570 STRING must be an encoded or a single-byte string.
571 LENGTH must be the number of octets for STRING."
572   (or (elmo-imap4-atom string)
573       (elmo-imap4-string-1 string length)))
574
575 (defun elmo-imap4-astring (string)
576   "Return a list represents STRING as an astring defined in rfc2060.
577 STRING must be an encoded or a single-byte string."
578   (let ((length (length string)))
579     (if (< elmo-imap4-literal-threshold length)
580         (elmo-imap4-literal-1 string length)
581       (elmo-imap4-astring-1 string length))))
582
583 (defun elmo-imap4-buffer-astring (buffer)
584   "Return a list represents BUFFER as an astring defined in rfc2060.
585 BUFFER must be a single-byte buffer."
586   (let ((length (with-current-buffer buffer
587                   (buffer-size))))
588     (if (< elmo-imap4-literal-threshold length)
589         (elmo-imap4-literal-1 buffer length)
590       (elmo-imap4-astring-1 (with-current-buffer buffer
591                               (buffer-string))
592                             length))))
593
594 (defun elmo-imap4-nstring (string)
595   "Return a list represents STRING as a nstring defined in rfc2060.
596 STRING must be an encoded or a single-byte string."
597    (or (elmo-imap4-nil string)
598        (elmo-imap4-string string)))
599
600 (defun elmo-imap4-buffer-nstring (buffer)
601   "Return a list represents BUFFER as a nstring defined in rfc2060.
602 BUFFER must be a single-byte buffer."
603    (or (elmo-imap4-nil buffer)
604        (elmo-imap4-buffer-string buffer)))
605
606 (defalias 'elmo-imap4-mailbox 'elmo-imap4-astring)
607 (defalias 'elmo-imap4-field-body 'elmo-imap4-astring)
608 (defalias 'elmo-imap4-userid 'elmo-imap4-astring)
609 (defalias 'elmo-imap4-password 'elmo-imap4-astring)
610
611 (defun elmo-imap4-format-quoted (string)
612   "Return STRING in a form of the quoted-string defined in rfc2060."
613   (concat "\""
614           (std11-wrap-as-quoted-pairs string elmo-imap4-quoted-specials-list)
615           "\""))
616
617 (defsubst elmo-imap4-response-get-selectable-mailbox-list (response)
618   (delq nil
619         (mapcar
620          (lambda (entry)
621            (if (and (eq 'list (car entry))
622                     (not (elmo-string-member-ignore-case "\\Noselect" (nth 1 (nth 1 entry)))))
623                (car (nth 1 entry))))
624          response)))
625
626 (luna-define-method elmo-message-fetch-bodystructure ((folder
627                                                        elmo-imap4-folder)
628                                                       number strategy)
629   (if (elmo-fetch-strategy-use-cache strategy)
630       (elmo-object-load
631        (elmo-file-cache-expand-path
632         (elmo-fetch-strategy-cache-path strategy)
633         "bodystructure"))
634     (let ((session (elmo-imap4-get-session folder))
635           bodystructure)
636       (elmo-imap4-session-select-mailbox
637        session
638        (elmo-imap4-folder-mailbox-internal folder))
639       (with-current-buffer (elmo-network-session-buffer session)
640         (setq elmo-imap4-fetch-callback nil)
641         (setq elmo-imap4-fetch-callback-data nil))
642       (prog1 (setq bodystructure
643                    (elmo-imap4-response-value
644                     (elmo-imap4-response-value
645                      (elmo-imap4-send-command-wait
646                       session
647                       (format
648                        (if elmo-imap4-use-uid
649                            "uid fetch %s bodystructure"
650                          "fetch %s bodystructure")
651                        number))
652                      'fetch)
653                     'bodystructure))
654         (when (elmo-fetch-strategy-save-cache strategy)
655           (elmo-file-cache-delete
656            (elmo-fetch-strategy-cache-path strategy))
657           (elmo-object-save
658            (elmo-file-cache-expand-path
659             (elmo-fetch-strategy-cache-path strategy)
660             "bodystructure")
661            bodystructure))))))
662
663 ;;; Backend methods.
664 (luna-define-method elmo-create-folder-plugged ((folder elmo-imap4-folder))
665   (elmo-imap4-send-command-wait
666    (elmo-imap4-get-session folder)
667    (list "create " (elmo-imap4-mailbox
668                     (elmo-imap4-folder-mailbox-internal folder)))))
669
670 (defun elmo-imap4-get-session (folder &optional if-exists)
671   (elmo-network-get-session 'elmo-imap4-session
672                             (concat
673                              (if (elmo-folder-biff-internal folder)
674                                  "BIFF-")
675                              "IMAP")
676                             folder if-exists))
677
678 (defun elmo-imap4-session-select-mailbox (session mailbox
679                                                   &optional force no-error)
680   "Select MAILBOX in SESSION.
681 If optional argument FORCE is non-nil, select mailbox even if current mailbox
682 is same as MAILBOX.
683 If second optional argument NO-ERROR is non-nil, don't cause an error when
684 selecting folder was failed.
685 If NO-ERROR is 'notify-bye, only BYE response is reported as error.
686 Returns response value if selecting folder succeed. "
687   (when (or force
688             (not (string=
689                   (elmo-imap4-session-current-mailbox-internal session)
690                   mailbox)))
691     (let (response result)
692       (unwind-protect
693           (setq response
694                 (elmo-imap4-read-response
695                  session
696                  (elmo-imap4-send-command
697                   session
698                   (list
699                    "select "
700                    (elmo-imap4-mailbox mailbox)))))
701         (if (setq result (elmo-imap4-response-ok-p response))
702             (progn
703               (elmo-imap4-session-set-current-mailbox-internal session mailbox)
704               (elmo-imap4-session-set-read-only-internal
705                session
706                (nth 1 (assq 'read-only (assq 'ok response))))
707               (elmo-imap4-session-set-flags-internal
708                session
709                (nth 1 (or (assq 'permanentflags response)
710                           (assq 'flags response)))))
711           (elmo-imap4-session-set-current-mailbox-internal session nil)
712           (if (and (eq no-error 'notify-bye)
713                    (elmo-imap4-response-bye-p response))
714               (elmo-imap4-process-bye session)
715             (unless no-error
716               (error "%s"
717                      (or (elmo-imap4-response-error-text response)
718                          (format "Select %s failed" mailbox)))))))
719       (and result response))))
720
721 (defun elmo-imap4-check-validity (spec validity-file)
722 ;;; Not used.
723 ;;;(elmo-imap4-send-command-wait
724 ;;;(elmo-imap4-get-session spec)
725 ;;;(list "status "
726 ;;;      (elmo-imap4-mailbox
727 ;;;       (elmo-imap4-spec-mailbox spec))
728 ;;;      " (uidvalidity)")))
729   )
730
731 (defun elmo-imap4-sync-validity  (spec validity-file)
732   ;; Not used.
733   )
734
735 (defun elmo-imap4-list (folder flag)
736   (let ((session (elmo-imap4-get-session folder)))
737     (elmo-imap4-session-select-mailbox
738      session
739      (elmo-imap4-folder-mailbox-internal folder))
740     (elmo-imap4-response-value
741      (elmo-imap4-send-command-wait
742       session
743       (format (if elmo-imap4-use-uid "uid search %s"
744                 "search %s") flag))
745      'search)))
746
747 (defun elmo-imap4-session-flag-available-p (session flag)
748   (case flag
749     ((read unread) (elmo-string-member-ignore-case
750                     "\\seen" (elmo-imap4-session-flags-internal session)))
751     (important
752      (elmo-string-member-ignore-case
753       "\\flagged" (elmo-imap4-session-flags-internal session)))
754     (digest
755      (or (elmo-string-member-ignore-case
756           "\\seen" (elmo-imap4-session-flags-internal session))
757          (elmo-string-member-ignore-case
758           "\\flagged" (elmo-imap4-session-flags-internal session))))
759     (answered
760      (elmo-string-member-ignore-case
761       (concat "\\" (symbol-name flag))
762       (elmo-imap4-session-flags-internal session)))
763     (t
764      (member "\\*" (elmo-imap4-session-flags-internal session)))))
765
766 (defun elmo-imap4-flag-to-imap-search-key (flag)
767   (case flag
768     (read "seen")
769     (unread "unseen")
770     (important "flagged")
771     (answered "answered")
772     (new "new")
773     (t (concat
774         "keyword "
775         (or (car (cdr (assq flag elmo-imap4-flag-specs)))
776             (symbol-name flag))))))
777
778 (defun elmo-imap4-flag-to-imap-criteria (flag)
779   (case flag
780     ((any digest)
781      (let ((criteria "flagged")
782            (global-flags (delq 'important (elmo-get-global-flags t t))))
783        (dolist (flag (delete 'new
784                              (delete 'cached
785                                      (copy-sequence
786                                       (case flag
787                                         (any
788                                          elmo-preserved-flags)
789                                         (digest
790                                          elmo-digest-flags))))))
791          (setq criteria (concat "or "
792                                 (elmo-imap4-flag-to-imap-search-key flag)
793                                 " "
794                                 criteria)))
795        (while global-flags
796          (setq criteria (concat "or keyword "
797                                 (symbol-name (car global-flags))
798                                 " "
799                                 criteria))
800          (setq global-flags (cdr global-flags)))
801        criteria))
802     (t
803      (elmo-imap4-flag-to-imap-search-key flag))))
804
805 (defun elmo-imap4-folder-list-flagged (folder flag)
806   "List flagged message numbers in the FOLDER.
807 FLAG is one of the `unread', `read', `important', `answered', `any'."
808   (let ((session (elmo-imap4-get-session folder))
809         (criteria (elmo-imap4-flag-to-imap-criteria flag)))
810     (if (elmo-imap4-session-flag-available-p session flag)
811         (progn
812           (elmo-imap4-session-select-mailbox
813            session
814            (elmo-imap4-folder-mailbox-internal folder))
815           (elmo-imap4-response-value
816            (elmo-imap4-send-command-wait
817             session
818             (format (if elmo-imap4-use-uid "uid search %s"
819                       "search %s") criteria))
820            'search))
821       ;; List flagged messages in the msgdb.
822       (elmo-msgdb-list-flagged (elmo-folder-msgdb folder) flag))))
823
824 (defvar elmo-imap4-rfc822-size "RFC822\.SIZE")
825 (defvar elmo-imap4-rfc822-text "RFC822\.TEXT")
826 (defvar elmo-imap4-rfc822-header "RFC822\.HEADER")
827 (defvar elmo-imap4-header-fields "HEADER\.FIELDS")
828
829 (defun elmo-imap4-make-number-set-list (msg-list &optional chop-length)
830   "Make RFC2060's message set specifier from MSG-LIST.
831 Returns a list of (NUMBER . SET-STRING).
832 SET-STRING is the message set specifier described in RFC2060.
833 NUMBER is contained message number in SET-STRING.
834 Every SET-STRING does not contain number of messages longer than CHOP-LENGTH.
835 If CHOP-LENGTH is not specified, message set is not chopped."
836   (let (count cont-list set-list)
837     (setq msg-list (sort (copy-sequence msg-list) '<))
838     (while msg-list
839       (setq cont-list nil)
840       (setq count 0)
841       (unless chop-length
842         (setq chop-length (length msg-list)))
843       (while (and (not (null msg-list))
844                   (< count chop-length))
845         (setq cont-list
846               (elmo-number-set-append
847                cont-list (car msg-list)))
848         (incf count)
849         (setq msg-list (cdr msg-list)))
850       (setq set-list
851             (cons
852              (cons
853               count
854               (mapconcat
855                (lambda (x)
856                  (cond ((consp x)
857                         (format "%s:%s" (car x) (cdr x)))
858                        ((integerp x)
859                         (int-to-string x))))
860                cont-list
861                ","))
862              set-list)))
863     (nreverse set-list)))
864
865 ;;
866 ;; app-data:
867 ;; cons of flag-table and folder structure
868 (defsubst elmo-imap4-fetch-callback-1-subr (entity flags app-data)
869   "A msgdb entity callback function."
870   (let ((use-flag (elmo-folder-use-flag-p (cdr app-data)))
871         (flag-table (car app-data))
872         (msg-id (elmo-message-entity-field entity 'message-id))
873         saved-flags flag-list)
874 ;;    (when (elmo-string-member-ignore-case "\\Flagged" flags)
875 ;;      (elmo-msgdb-global-mark-set msg-id elmo-msgdb-important-mark))
876     (setq saved-flags (elmo-flag-table-get flag-table msg-id)
877           flag-list
878           (if use-flag
879               (append
880                (and (memq 'new saved-flags)
881                     (not (elmo-string-member-ignore-case "\\Seen" flags))
882                     '(new))
883                (and (elmo-string-member-ignore-case "\\Flagged" flags)
884                     '(important))
885                (and (not (elmo-string-member-ignore-case "\\Seen" flags))
886                     '(unread))
887                (and (elmo-string-member-ignore-case "\\Answered" flags)
888                     '(answered))
889                (and (elmo-file-cache-exists-p msg-id)
890                     '(cached)))
891             saved-flags))
892     (when (and (or (memq 'important flag-list)
893                    (memq 'answered flag-list))
894                (memq 'unread flag-list))
895       (setq elmo-imap4-seen-messages
896             (cons (elmo-message-entity-number entity)
897                   elmo-imap4-seen-messages)))
898     (elmo-msgdb-append-entity elmo-imap4-current-msgdb
899                               entity
900                               flag-list)))
901
902 ;; Current buffer is process buffer.
903 (defun elmo-imap4-fetch-callback-1 (element app-data)
904   (let ((handler (elmo-msgdb-message-entity-handler elmo-imap4-current-msgdb)))
905     (elmo-imap4-fetch-callback-1-subr
906      (with-temp-buffer
907        (insert (or (elmo-imap4-response-bodydetail-text element)
908                    ""))
909        ;; Replace all CRLF with LF.
910        (elmo-delete-cr-buffer)
911        (elmo-msgdb-create-message-entity-from-buffer
912         handler
913         (elmo-imap4-response-value element 'uid)
914         :size (elmo-imap4-response-value element 'rfc822size)))
915      (elmo-imap4-response-value element 'flags)
916      app-data)))
917
918 (defun elmo-imap4-parse-capability (string)
919   (if (string-match "^\\*\\(.*\\)$" string)
920       (read
921        (concat "(" (downcase (elmo-match-string 1 string)) ")"))))
922
923 (defun elmo-imap4-clear-login (session)
924   (let ((elmo-imap4-debug-inhibit-logging t))
925     (or
926      (elmo-imap4-read-ok
927       session
928       (elmo-imap4-send-command
929        session
930        (list "login "
931              (elmo-imap4-userid (elmo-network-session-user-internal session))
932              " "
933              (elmo-imap4-password
934               (elmo-get-passwd (elmo-network-session-password-key session))))))
935      (signal 'elmo-authenticate-error '(elmo-imap4-clear-login)))))
936
937 (defun elmo-imap4-auth-login (session)
938   (let ((tag (elmo-imap4-send-command session "authenticate login"))
939         (elmo-imap4-debug-inhibit-logging t))
940     (or (elmo-imap4-read-continue-req session)
941         (signal 'elmo-authenticate-error '(elmo-imap4-auth-login)))
942     (elmo-imap4-send-string session
943                             (elmo-base64-encode-string
944                              (elmo-network-session-user-internal session)))
945     (or (elmo-imap4-read-continue-req session)
946         (signal 'elmo-authenticate-error '(elmo-imap4-auth-login)))
947     (elmo-imap4-send-string session
948                             (elmo-base64-encode-string
949                              (elmo-get-passwd
950                               (elmo-network-session-password-key session))))
951     (or (elmo-imap4-read-ok session tag)
952         (signal 'elmo-authenticate-error '(elmo-imap4-auth-login)))
953     (setq elmo-imap4-status 'auth)))
954
955 (luna-define-method
956   elmo-network-initialize-session-buffer :after ((session
957                                                   elmo-imap4-session) buffer)
958   (with-current-buffer buffer
959     (mapcar 'make-variable-buffer-local elmo-imap4-local-variables)
960     (setq elmo-imap4-seqno 0)
961     (setq elmo-imap4-status 'initial)))
962
963 (luna-define-method elmo-network-initialize-session ((session
964                                                       elmo-imap4-session))
965   (let ((process (elmo-network-session-process-internal session)))
966     (with-current-buffer (process-buffer process)
967       ;; Skip garbage output from process before greeting.
968       (while (and (memq (process-status process) '(open run))
969                   (goto-char (point-max))
970                   (forward-line -1)
971                   (not (elmo-imap4-parse-greeting)))
972         (accept-process-output process 1))
973       (set-process-filter process 'elmo-imap4-arrival-filter)
974       (set-process-sentinel process 'elmo-imap4-sentinel)
975 ;;;   (while (and (memq (process-status process) '(open run))
976 ;;;               (eq elmo-imap4-status 'initial))
977 ;;;     (message "Waiting for server response...")
978 ;;;     (accept-process-output process 1))
979 ;;;   (message "")
980       (unless (memq elmo-imap4-status '(nonauth auth))
981         (signal 'elmo-open-error
982                 (list 'elmo-network-initialize-session)))
983       (elmo-imap4-session-set-capability-internal
984        session
985        (elmo-imap4-response-value
986         (elmo-imap4-send-command-wait session "capability")
987         'capability))
988       (when (eq (elmo-network-stream-type-symbol
989                  (elmo-network-session-stream-type-internal session))
990                 'starttls)
991         (or (memq 'starttls
992                   (elmo-imap4-session-capability-internal session))
993             (signal 'elmo-open-error
994                     '(elmo-imap4-starttls-error)))
995         (elmo-imap4-send-command-wait session "starttls")
996         (starttls-negotiate process)
997         (elmo-imap4-session-set-capability-internal
998          session
999          (elmo-imap4-response-value
1000           (elmo-imap4-send-command-wait session "capability")
1001           'capability))))))
1002
1003 (luna-define-method elmo-network-authenticate-session ((session
1004                                                         elmo-imap4-session))
1005   (with-current-buffer (process-buffer
1006                         (elmo-network-session-process-internal session))
1007     (let* ((auth (elmo-network-session-auth-internal session))
1008            (auth (if (listp auth) auth (list auth))))
1009       (unless (or (eq elmo-imap4-status 'auth)
1010                   (null auth))
1011         (cond
1012          ((eq 'clear (car auth))
1013           (elmo-imap4-clear-login session))
1014          ((eq 'login (car auth))
1015           (elmo-imap4-auth-login session))
1016          (t
1017           (let* ((elmo-imap4-debug-inhibit-logging t)
1018                  (sasl-mechanisms
1019                   (delq nil
1020                         (mapcar
1021                          '(lambda (cap)
1022                             (if (string-match "^auth=\\(.*\\)$"
1023                                               (symbol-name cap))
1024                                 (match-string 1 (upcase (symbol-name cap)))))
1025                          (elmo-imap4-session-capability-internal session))))
1026                  (mechanism
1027                   (sasl-find-mechanism
1028                    (delq nil
1029                          (mapcar '(lambda (cap) (upcase (symbol-name cap)))
1030                                  (if (listp auth)
1031                                      auth
1032                                    (list auth)))))) ;)
1033                  client name step response tag
1034                  sasl-read-passphrase)
1035             (unless mechanism
1036               (if (or elmo-imap4-force-login
1037                       (y-or-n-p
1038                        (format
1039                         "There's no %s capability in server. continue?"
1040                         (elmo-list-to-string
1041                          (elmo-network-session-auth-internal session)))))
1042                   (setq mechanism (sasl-find-mechanism
1043                                    sasl-mechanisms))
1044                 (signal 'elmo-authenticate-error
1045                         '(elmo-imap4-auth-no-mechanisms))))
1046             (setq client
1047                   (sasl-make-client
1048                    mechanism
1049                    (elmo-network-session-user-internal session)
1050                    "imap"
1051                    (elmo-network-session-server-internal session)))
1052 ;;;         (if elmo-imap4-auth-user-realm
1053 ;;;             (sasl-client-set-property client 'realm elmo-imap4-auth-user-realm))
1054             (setq name (sasl-mechanism-name mechanism)
1055                   step (sasl-next-step client nil))
1056             (elmo-network-session-set-auth-internal
1057              session
1058              (intern (downcase name)))
1059             (setq sasl-read-passphrase
1060                   (function
1061                    (lambda (prompt)
1062                      (elmo-get-passwd
1063                       (elmo-network-session-password-key session)))))
1064             (setq tag
1065                   (elmo-imap4-send-command
1066                    session
1067                    (concat "AUTHENTICATE " name
1068                            (and (sasl-step-data step)
1069                                 (concat
1070                                  " "
1071                                  (elmo-base64-encode-string
1072                                   (sasl-step-data step)
1073                                   'no-lin-break))))))
1074             (catch 'done
1075               (while t
1076                 (setq response
1077                       (elmo-imap4-read-untagged
1078                        (elmo-network-session-process-internal session)))
1079                 (if (elmo-imap4-response-ok-p response)
1080                     (if (sasl-next-step client step)
1081                         ;; Bogus server?
1082                         (signal 'elmo-authenticate-error
1083                                 (list (intern
1084                                        (concat "elmo-imap4-auth-"
1085                                                (downcase name)))))
1086                       ;; The authentication process is finished.
1087                       (throw 'done nil)))
1088                 (unless (elmo-imap4-response-continue-req-p response)
1089                   ;; response is NO or BAD.
1090                   (signal 'elmo-authenticate-error
1091                           (list (intern
1092                                  (concat "elmo-imap4-auth-"
1093                                          (downcase name))))))
1094                 (sasl-step-set-data
1095                  step
1096                  (elmo-base64-decode-string
1097                   (elmo-imap4-response-value response 'continue-req)))
1098                 (setq step (sasl-next-step client step))
1099                 (setq tag
1100                       (elmo-imap4-send-string
1101                        session
1102                        (if (sasl-step-data step)
1103                            (elmo-base64-encode-string (sasl-step-data step)
1104                                                       'no-line-break)
1105                          ""))))))))))))
1106
1107 (luna-define-method elmo-network-setup-session ((session
1108                                                  elmo-imap4-session))
1109   (with-current-buffer (elmo-network-session-buffer session)
1110     (when (memq 'namespace (elmo-imap4-session-capability-internal session))
1111       (setq elmo-imap4-server-namespace
1112             (elmo-imap4-response-value
1113              (elmo-imap4-send-command-wait session "namespace")
1114              'namespace)))))
1115
1116 (defun elmo-imap4-setup-send-buffer (&optional string)
1117   (let ((send-buf (get-buffer-create " *elmo-imap4-setup-send-buffer*"))
1118         (source-buf (unless string (current-buffer))))
1119     (save-excursion
1120       (save-match-data
1121         (set-buffer send-buf)
1122         (erase-buffer)
1123         (set-buffer-multibyte nil)
1124         (if string
1125             (insert string)
1126           (with-current-buffer source-buf
1127             (copy-to-buffer send-buf (point-min) (point-max))))
1128         (goto-char (point-min))
1129         (if (eq (re-search-forward "^$" nil t)
1130                 (point-max))
1131             (insert "\n"))
1132         (goto-char (point-min))
1133         (while (search-forward "\n" nil t)
1134           (replace-match "\r\n"))))
1135     send-buf))
1136
1137 (defun elmo-imap4-setup-send-buffer-from-file (file)
1138   (let ((tmp-buf (get-buffer-create
1139                   " *elmo-imap4-setup-send-buffer-from-file*")))
1140     (save-excursion
1141       (save-match-data
1142         (set-buffer tmp-buf)
1143         (erase-buffer)
1144         (as-binary-input-file
1145          (insert-file-contents file))
1146         (goto-char (point-min))
1147         (if (eq (re-search-forward "^$" nil t)
1148                 (point-max))
1149             (insert "\n"))
1150         (goto-char (point-min))
1151         (while (search-forward "\n" nil t)
1152           (replace-match "\r\n"))))
1153     tmp-buf))
1154
1155 (luna-define-method elmo-delete-message-safe ((folder elmo-imap4-folder)
1156                                               number msgid)
1157   (let ((session (elmo-imap4-get-session folder))
1158         candidates)
1159     (elmo-imap4-session-select-mailbox
1160      session
1161      (elmo-imap4-folder-mailbox-internal folder))
1162     (setq candidates
1163           (elmo-imap4-response-value
1164            (elmo-imap4-send-command-wait session
1165                                          (list
1166                                           (if elmo-imap4-use-uid
1167                                               "uid search header message-id "
1168                                             "search header message-id ")
1169                                           (elmo-imap4-field-body msgid)))
1170            'search))
1171     (if (memq number candidates)
1172         (elmo-folder-delete-messages folder (list number)))))
1173
1174 (defun elmo-imap4-server-diff-async-callback-1 (status data)
1175   (funcall elmo-imap4-server-diff-async-callback
1176            (list (elmo-imap4-response-value status 'recent)
1177                  (elmo-imap4-response-value status 'unseen)
1178                  (elmo-imap4-response-value status 'messages))
1179            data))
1180
1181 (defun elmo-imap4-server-diff-async (folder)
1182   (let ((session (elmo-imap4-get-session folder)))
1183     ;; We should `check' folder to obtain newest information here.
1184     ;; But since there's no asynchronous check mechanism in elmo yet,
1185     ;; checking is not done here.
1186     (with-current-buffer (elmo-network-session-buffer session)
1187       (setq elmo-imap4-status-callback
1188             'elmo-imap4-server-diff-async-callback-1)
1189       (setq elmo-imap4-status-callback-data
1190             elmo-imap4-server-diff-async-callback-data))
1191     (elmo-imap4-send-command session
1192                              (list
1193                               "status "
1194                               (elmo-imap4-mailbox
1195                                (elmo-imap4-folder-mailbox-internal folder))
1196                               " (recent unseen messages)"))))
1197
1198 (luna-define-method elmo-server-diff-async ((folder elmo-imap4-folder))
1199   (let ((session (elmo-imap4-get-session folder)))
1200     ;; commit.
1201     ;; (elmo-imap4-commit spec)
1202     (with-current-buffer (elmo-network-session-buffer session)
1203       (setq elmo-imap4-status-callback
1204             'elmo-imap4-server-diff-async-callback-1)
1205       (setq elmo-imap4-status-callback-data
1206             elmo-imap4-server-diff-async-callback-data))
1207     (elmo-imap4-send-command session
1208                              (list
1209                               "status "
1210                               (elmo-imap4-mailbox
1211                                (elmo-imap4-folder-mailbox-internal folder))
1212                               " (recent unseen messages)"))))
1213
1214 ;;; IMAP parser.
1215
1216 (defvar elmo-imap4-server-eol "\r\n"
1217   "The EOL string sent from the server.")
1218
1219 (defvar elmo-imap4-client-eol "\r\n"
1220   "The EOL string we send to the server.")
1221
1222 (defvar elmo-imap4-display-literal-progress nil)
1223
1224 (defun elmo-imap4-find-next-line ()
1225   "Return point at end of current line, taking into account literals.
1226 Return nil if no complete line has arrived."
1227   (when (re-search-forward (concat elmo-imap4-server-eol "\\|{\\([0-9]+\\)}"
1228                                    elmo-imap4-server-eol)
1229                            nil t)
1230     (if (match-string 1)
1231         (if (< (point-max) (+ (point) (string-to-number (match-string 1))))
1232             (progn
1233               (if (and elmo-imap4-display-literal-progress
1234                        (> (string-to-number (match-string 1))
1235                           (min elmo-display-retrieval-progress-threshold 100)))
1236                   (elmo-display-progress
1237                    'elmo-imap4-display-literal-progress
1238                    (format "Retrieving (%d/%d bytes)..."
1239                            (- (point-max) (point))
1240                            (string-to-number (match-string 1)))
1241                    (/ (- (point-max) (point))
1242                       (/ (string-to-number (match-string 1)) 100))))
1243               nil)
1244           (goto-char (+ (point) (string-to-number (match-string 1))))
1245           (elmo-imap4-find-next-line))
1246       (point))))
1247
1248 (defun elmo-imap4-sentinel (process string)
1249   (delete-process process))
1250
1251 (defun elmo-imap4-arrival-filter (proc string)
1252   "IMAP process filter."
1253   (when (buffer-live-p (process-buffer proc))
1254   (with-current-buffer (process-buffer proc)
1255     (elmo-imap4-debug "-> %s" string)
1256     (goto-char (point-max))
1257     (insert string)
1258     (let (end)
1259       (goto-char (point-min))
1260       (while (setq end (elmo-imap4-find-next-line))
1261         (save-restriction
1262           (narrow-to-region (point-min) end)
1263           (delete-backward-char (length elmo-imap4-server-eol))
1264           (goto-char (point-min))
1265           (unwind-protect
1266               (cond ((eq elmo-imap4-status 'initial)
1267                      (setq elmo-imap4-current-response
1268                            (list
1269                             (list 'greeting (elmo-imap4-parse-greeting)))))
1270                     ((or (eq elmo-imap4-status 'auth)
1271                          (eq elmo-imap4-status 'nonauth)
1272                          (eq elmo-imap4-status 'selected)
1273                          (eq elmo-imap4-status 'examine))
1274                      (setq elmo-imap4-current-response
1275                            (cons
1276                             (elmo-imap4-parse-response)
1277                             elmo-imap4-current-response)))
1278                     (t
1279                      (message "Unknown state %s in arrival filter"
1280                               elmo-imap4-status))))
1281           (delete-region (point-min) (point-max))))))))
1282
1283 ;; IMAP parser.
1284
1285 (defsubst elmo-imap4-forward ()
1286   (or (eobp) (forward-char 1)))
1287
1288 (defsubst elmo-imap4-parse-number ()
1289   (when (looking-at "[0-9]+")
1290     (prog1
1291         (string-to-number (match-string 0))
1292       (goto-char (match-end 0)))))
1293
1294 (defsubst elmo-imap4-parse-literal ()
1295   (when (looking-at "{\\([0-9]+\\)}\r\n")
1296     (let ((pos (match-end 0))
1297           (len (string-to-number (match-string 1))))
1298       (if (< (point-max) (+ pos len))
1299           nil
1300         (goto-char (+ pos len))
1301         (buffer-substring pos (+ pos len))))))
1302 ;;;     (list ' pos (+ pos len))))))
1303
1304 (defsubst elmo-imap4-parse-string ()
1305   (cond ((eq (char-after (point)) ?\")
1306          (forward-char 1)
1307          (let ((p (point)) (name ""))
1308            (skip-chars-forward "^\"\\\\")
1309            (setq name (buffer-substring p (point)))
1310            (while (eq (char-after (point)) ?\\)
1311              (setq p (1+ (point)))
1312              (forward-char 2)
1313              (skip-chars-forward "^\"\\\\")
1314              (setq name (concat name (buffer-substring p (point)))))
1315            (forward-char 1)
1316            name))
1317         ((eq (char-after (point)) ?{)
1318          (elmo-imap4-parse-literal))))
1319
1320 (defsubst elmo-imap4-parse-nil ()
1321   (if (looking-at "NIL")
1322       (goto-char (match-end 0))))
1323
1324 (defsubst elmo-imap4-parse-nstring ()
1325   (or (elmo-imap4-parse-string)
1326       (and (elmo-imap4-parse-nil)
1327            nil)))
1328
1329 (defsubst elmo-imap4-parse-astring ()
1330   (or (elmo-imap4-parse-string)
1331       (buffer-substring (point)
1332                         (if (re-search-forward "[(){ \r\n%*\"\\]" nil t)
1333                             (goto-char (1- (match-end 0)))
1334                           (end-of-line)
1335                           (point)))))
1336
1337 (defsubst elmo-imap4-parse-address ()
1338   (let (address)
1339     (when (eq (char-after (point)) ?\()
1340       (elmo-imap4-forward)
1341       (setq address (vector (prog1 (elmo-imap4-parse-nstring)
1342                               (elmo-imap4-forward))
1343                             (prog1 (elmo-imap4-parse-nstring)
1344                               (elmo-imap4-forward))
1345                             (prog1 (elmo-imap4-parse-nstring)
1346                               (elmo-imap4-forward))
1347                             (elmo-imap4-parse-nstring)))
1348       (when (eq (char-after (point)) ?\))
1349         (elmo-imap4-forward)
1350         address))))
1351
1352 (defsubst elmo-imap4-parse-address-list ()
1353   (if (eq (char-after (point)) ?\()
1354       (let (address addresses)
1355         (elmo-imap4-forward)
1356         (while (and (not (eq (char-after (point)) ?\)))
1357                     ;; next line for MS Exchange bug
1358                     (progn (and (eq (char-after (point)) ? ) (elmo-imap4-forward)) t)
1359                     (setq address (elmo-imap4-parse-address)))
1360           (setq addresses (cons address addresses)))
1361         (when (eq (char-after (point)) ?\))
1362           (elmo-imap4-forward)
1363           (nreverse addresses)))
1364     (assert (elmo-imap4-parse-nil))))
1365
1366 (defsubst elmo-imap4-parse-mailbox ()
1367   (let ((mailbox (elmo-imap4-parse-astring)))
1368     (if (string-equal "INBOX" (upcase mailbox))
1369         "INBOX"
1370       mailbox)))
1371
1372 (defun elmo-imap4-parse-greeting ()
1373   "Parse a IMAP greeting."
1374   (cond ((looking-at "\\* OK ")
1375          (setq elmo-imap4-status 'nonauth))
1376         ((looking-at "\\* PREAUTH ")
1377          (setq elmo-imap4-status 'auth))
1378         ((looking-at "\\* BYE ")
1379          (setq elmo-imap4-status 'closed))))
1380
1381 (defun elmo-imap4-parse-response ()
1382   "Parse a IMAP command response."
1383   (let (token)
1384     (case (setq token (read (current-buffer)))
1385       (+ (progn
1386            (skip-chars-forward " ")
1387            (list 'continue-req (buffer-substring (point) (point-max)))))
1388       (* (case (prog1 (setq token (read (current-buffer)))
1389                  (elmo-imap4-forward))
1390            (OK         (elmo-imap4-parse-resp-text-code))
1391            (NO         (elmo-imap4-parse-resp-text-code))
1392            (BAD        (elmo-imap4-parse-resp-text-code))
1393            (BYE        (elmo-imap4-parse-bye))
1394            (FLAGS      (list 'flags
1395                              (elmo-imap4-parse-flag-list)))
1396            (LIST       (list 'list (elmo-imap4-parse-data-list)))
1397            (LSUB       (list 'lsub (elmo-imap4-parse-data-list)))
1398            (SEARCH     (list
1399                         'search
1400                         (read (concat "("
1401                                       (buffer-substring (point) (point-max))
1402                                       ")"))))
1403            (STATUS     (elmo-imap4-parse-status))
1404            ;; Added
1405            (NAMESPACE  (elmo-imap4-parse-namespace))
1406            (CAPABILITY (list 'capability
1407                              (read
1408                               (concat "(" (downcase (buffer-substring
1409                                                      (point) (point-max)))
1410                                       ")"))))
1411            (ACL (elmo-imap4-parse-acl))
1412            (t       (case (prog1 (read (current-buffer))
1413                             (elmo-imap4-forward))
1414                       (EXISTS  (list 'exists token))
1415                       (RECENT  (list 'recent token))
1416                       (EXPUNGE (list 'expunge token))
1417                       (FETCH   (elmo-imap4-parse-fetch token))
1418                       (t       (list 'garbage (buffer-string)))))))
1419       (t (if (not (string-match elmo-imap4-seq-prefix (symbol-name token)))
1420              (list 'garbage (buffer-string))
1421            (case (prog1 (read (current-buffer))
1422                    (elmo-imap4-forward))
1423              (OK  (progn
1424                     (setq elmo-imap4-parsing nil)
1425                     (setq token (symbol-name token))
1426                     (elmo-unintern token)
1427                     (elmo-imap4-debug "*%s* OK arrived" token)
1428                     (setq elmo-imap4-reached-tag token)
1429                     (list 'ok (elmo-imap4-parse-resp-text-code))))
1430              (NO  (progn
1431                     (setq elmo-imap4-parsing nil)
1432                     (setq token (symbol-name token))
1433                     (elmo-unintern token)
1434                     (elmo-imap4-debug "*%s* NO arrived" token)
1435                     (setq elmo-imap4-reached-tag token)
1436                     (let (code text)
1437                       (when (eq (char-after (point)) ?\[)
1438                         (setq code (buffer-substring (point)
1439                                                      (search-forward "]")))
1440                         (elmo-imap4-forward))
1441                       (setq text (buffer-substring (point) (point-max)))
1442                       (list 'no (list code text)))))
1443              (BAD (progn
1444                     (setq elmo-imap4-parsing nil)
1445                     (elmo-imap4-debug "*%s* BAD arrived" token)
1446                     (setq token (symbol-name token))
1447                     (elmo-unintern token)
1448                     (setq elmo-imap4-reached-tag token)
1449                     (let (code text)
1450                       (when (eq (char-after (point)) ?\[)
1451                         (setq code (buffer-substring (point)
1452                                                      (search-forward "]")))
1453                         (elmo-imap4-forward))
1454                       (setq text (buffer-substring (point) (point-max)))
1455                       (list 'bad (list code text)))))
1456              (t   (list 'garbage (buffer-string)))))))))
1457
1458 (defun elmo-imap4-parse-bye ()
1459   (let (code text)
1460     (when (eq (char-after (point)) ?\[)
1461       (setq code (buffer-substring (point)
1462                                    (search-forward "]")))
1463       (elmo-imap4-forward))
1464     (setq text (buffer-substring (point) (point-max)))
1465     (list 'bye (list code text))))
1466
1467 (defun elmo-imap4-parse-text ()
1468   (goto-char (point-min))
1469   (when (search-forward "[" nil t)
1470     (search-forward "]")
1471     (elmo-imap4-forward))
1472   (list 'text (buffer-substring (point) (point-max))))
1473
1474 (defun elmo-imap4-parse-resp-text-code ()
1475   (when (eq (char-after (point)) ?\[)
1476     (elmo-imap4-forward)
1477     (cond ((search-forward "PERMANENTFLAGS " nil t)
1478            (list 'permanentflags (elmo-imap4-parse-flag-list)))
1479           ((search-forward "UIDNEXT " nil t)
1480            (list 'uidnext (read (current-buffer))))
1481           ((search-forward "UNSEEN " nil t)
1482            (list 'unseen (read (current-buffer))))
1483           ((looking-at "UIDVALIDITY \\([0-9]+\\)")
1484            (list 'uidvalidity (match-string 1)))
1485           ((search-forward "READ-ONLY" nil t)
1486            (list 'read-only t))
1487           ((search-forward "READ-WRITE" nil t)
1488            (list 'read-write t))
1489           ((search-forward "NEWNAME " nil t)
1490            (let (oldname newname)
1491              (setq oldname (elmo-imap4-parse-string))
1492              (elmo-imap4-forward)
1493              (setq newname (elmo-imap4-parse-string))
1494              (list 'newname newname oldname)))
1495           ((search-forward "TRYCREATE" nil t)
1496            (list 'trycreate t))
1497           ((looking-at "APPENDUID \\([0-9]+\\) \\([0-9]+\\)")
1498            (list 'appenduid
1499                  (list (match-string 1)
1500                        (string-to-number (match-string 2)))))
1501           ((looking-at "COPYUID \\([0-9]+\\) \\([0-9,:]+\\) \\([0-9,:]+\\)")
1502            (list 'copyuid (list (match-string 1)
1503                                 (match-string 2)
1504                                 (match-string 3))))
1505           ((search-forward "ALERT] " nil t)
1506            (message "IMAP server information: %s"
1507                     (buffer-substring (point) (point-max))))
1508           (t (list 'unknown)))))
1509
1510 (defun elmo-imap4-parse-data-list ()
1511   (let (flags delimiter mailbox)
1512     (setq flags (elmo-imap4-parse-flag-list))
1513     (when (looking-at " NIL\\| \"\\\\?\\(.\\)\"")
1514       (setq delimiter (match-string 1))
1515       (goto-char (1+ (match-end 0)))
1516       (when (setq mailbox (elmo-imap4-parse-mailbox))
1517         (list mailbox flags delimiter)))))
1518
1519 (defsubst elmo-imap4-parse-header-list ()
1520   (when (eq (char-after (point)) ?\()
1521     (let (strlist)
1522       (while (not (eq (char-after (point)) ?\)))
1523         (elmo-imap4-forward)
1524         (push (elmo-imap4-parse-astring) strlist))
1525       (elmo-imap4-forward)
1526       (nreverse strlist))))
1527
1528 (defsubst elmo-imap4-parse-fetch-body-section ()
1529   (let ((section
1530          (buffer-substring (point)
1531                            (1-
1532                             (progn (re-search-forward "[] ]" nil t)
1533                                    (point))))))
1534     (if (eq (char-before) ? )
1535         (prog1
1536             (mapconcat 'identity
1537                        (cons section (elmo-imap4-parse-header-list)) " ")
1538           (search-forward "]" nil t))
1539       section)))
1540
1541 (defun elmo-imap4-parse-fetch (response)
1542   (when (eq (char-after (point)) ?\()
1543     (let (element list)
1544       (while (not (eq (char-after (point)) ?\)))
1545         (elmo-imap4-forward)
1546         (let ((token (read (current-buffer))))
1547           (elmo-imap4-forward)
1548           (setq element
1549                 (cond ((eq token 'UID)
1550                        (list 'uid (condition-case nil
1551                                       (read (current-buffer))
1552                                     (error nil))))
1553                       ((eq token 'FLAGS)
1554                        (list 'flags (elmo-imap4-parse-flag-list)))
1555                       ((eq token 'ENVELOPE)
1556                        (list 'envelope (elmo-imap4-parse-envelope)))
1557                       ((eq token 'INTERNALDATE)
1558                        (list 'internaldate (elmo-imap4-parse-string)))
1559                       ((eq token 'RFC822)
1560                        (list 'rfc822 (elmo-imap4-parse-nstring)))
1561                       ((eq token (intern elmo-imap4-rfc822-header))
1562                        (list 'rfc822header (elmo-imap4-parse-nstring)))
1563                       ((eq token (intern elmo-imap4-rfc822-text))
1564                        (list 'rfc822text (elmo-imap4-parse-nstring)))
1565                       ((eq token (intern elmo-imap4-rfc822-size))
1566                        (list 'rfc822size (read (current-buffer))))
1567                       ((eq token 'BODY)
1568                        (if (eq (char-before) ?\[)
1569                            (list
1570                             'bodydetail
1571                             (upcase (elmo-imap4-parse-fetch-body-section))
1572                             (and
1573                              (eq (char-after (point)) ?<)
1574                              (buffer-substring (1+ (point))
1575                                                (progn
1576                                                  (search-forward ">" nil t)
1577                                                  (point))))
1578                             (progn (elmo-imap4-forward)
1579                                    (elmo-imap4-parse-nstring)))
1580                          (list 'body (elmo-imap4-parse-body))))
1581                       ((eq token 'BODYSTRUCTURE)
1582                        (list 'bodystructure (elmo-imap4-parse-body)))))
1583           (setq list (cons element list))))
1584       (and elmo-imap4-fetch-callback
1585            (funcall elmo-imap4-fetch-callback
1586                     list elmo-imap4-fetch-callback-data))
1587       (list 'fetch list))))
1588
1589 (defun elmo-imap4-parse-status ()
1590   (let ((mailbox (elmo-imap4-parse-mailbox))
1591         status)
1592     (when (and mailbox (search-forward "(" nil t))
1593       (while (not (eq (char-after (point)) ?\)))
1594         (setq status
1595               (cons
1596                (let ((token (read (current-buffer))))
1597                  (cond ((eq token 'MESSAGES)
1598                         (list 'messages (read (current-buffer))))
1599                        ((eq token 'RECENT)
1600                         (list 'recent (read (current-buffer))))
1601                        ((eq token 'UIDNEXT)
1602                         (list 'uidnext (read (current-buffer))))
1603                        ((eq token 'UIDVALIDITY)
1604                         (and (looking-at " \\([0-9]+\\)")
1605                              (prog1 (list 'uidvalidity (match-string 1))
1606                                (goto-char (match-end 1)))))
1607                        ((eq token 'UNSEEN)
1608                         (list 'unseen (read (current-buffer))))
1609                        (t
1610                         (message
1611                          "Unknown status data %s in mailbox %s ignored"
1612                          token mailbox))))
1613                status))
1614         (skip-chars-forward " ")))
1615     (and elmo-imap4-status-callback
1616          (funcall elmo-imap4-status-callback
1617                   status
1618                   elmo-imap4-status-callback-data))
1619     (list 'status status)))
1620
1621
1622 (defmacro elmo-imap4-value (value)
1623   (` (if (eq (, value) 'NIL) nil
1624        (, value))))
1625
1626 (defmacro elmo-imap4-nth (pos list)
1627   (` (let ((value (nth (, pos) (, list))))
1628        (elmo-imap4-value value))))
1629
1630 (defun elmo-imap4-parse-namespace ()
1631   (list 'namespace
1632         (nconc
1633          (copy-sequence elmo-imap4-extra-namespace-alist)
1634          (elmo-imap4-parse-namespace-subr
1635           (read (concat "(" (buffer-substring
1636                              (point) (point-max))
1637                         ")"))))))
1638
1639 (defun elmo-imap4-parse-namespace-subr (ns)
1640   (let (prefix delim namespace-alist default-delim)
1641     ;; 0: personal, 1: other, 2: shared
1642     (dotimes (i 3)
1643       (setq namespace-alist
1644             (nconc namespace-alist
1645                    (delq nil
1646                          (mapcar
1647                           (lambda (namespace)
1648                             (setq prefix (elmo-imap4-nth 0 namespace)
1649                                   delim (elmo-imap4-nth 1 namespace))
1650                             (if (and prefix delim
1651                                      (string-match
1652                                       (concat (regexp-quote delim) "\\'")
1653                                       prefix))
1654                                 (setq prefix (substring prefix 0
1655                                                         (match-beginning 0))))
1656                             (if (eq (length prefix) 0)
1657                                 (progn (setq default-delim delim) nil)
1658                               (cons
1659                                (concat "^\\("
1660                                        (if (string= (downcase prefix) "inbox")
1661                                            "[Ii][Nn][Bb][Oo][Xx]"
1662                                          (regexp-quote prefix))
1663                                        "\\).*$")
1664                                delim)))
1665                           (elmo-imap4-nth i ns))))))
1666     (if default-delim
1667         (setq namespace-alist
1668               (nconc namespace-alist
1669                      (list (cons "^.*$" default-delim)))))
1670     namespace-alist))
1671
1672 (defun elmo-imap4-parse-acl ()
1673   (let ((mailbox (elmo-imap4-parse-mailbox))
1674         identifier rights acl)
1675     (while (eq (char-after (point)) ?\ )
1676       (elmo-imap4-forward)
1677       (setq identifier (elmo-imap4-parse-astring))
1678       (elmo-imap4-forward)
1679       (setq rights (elmo-imap4-parse-astring))
1680       (setq acl (append acl (list (cons identifier rights)))))
1681     (list 'acl acl mailbox)))
1682
1683 (defun elmo-imap4-parse-flag-list ()
1684   (let ((str (buffer-substring (+ (point) 1)
1685                                (progn (search-forward ")" nil t)
1686                                       (- (point) 1)))))
1687     (unless (eq (length str) 0)
1688       (split-string str))))
1689
1690 (defun elmo-imap4-parse-envelope ()
1691   (when (eq (char-after (point)) ?\()
1692     (elmo-imap4-forward)
1693     (vector (prog1 (elmo-imap4-parse-nstring);; date
1694               (elmo-imap4-forward))
1695             (prog1 (elmo-imap4-parse-nstring);; subject
1696               (elmo-imap4-forward))
1697             (prog1 (elmo-imap4-parse-address-list);; from
1698               (elmo-imap4-forward))
1699             (prog1 (elmo-imap4-parse-address-list);; sender
1700               (elmo-imap4-forward))
1701             (prog1 (elmo-imap4-parse-address-list);; reply-to
1702               (elmo-imap4-forward))
1703             (prog1 (elmo-imap4-parse-address-list);; to
1704               (elmo-imap4-forward))
1705             (prog1 (elmo-imap4-parse-address-list);; cc
1706               (elmo-imap4-forward))
1707             (prog1 (elmo-imap4-parse-address-list);; bcc
1708               (elmo-imap4-forward))
1709             (prog1 (elmo-imap4-parse-nstring);; in-reply-to
1710               (elmo-imap4-forward))
1711             (prog1 (elmo-imap4-parse-nstring);; message-id
1712               (elmo-imap4-forward)))))
1713
1714 (defsubst elmo-imap4-parse-string-list ()
1715   (cond ((eq (char-after (point)) ?\();; body-fld-param
1716          (let (strlist str)
1717            (elmo-imap4-forward)
1718            (while (setq str (elmo-imap4-parse-string))
1719              (push str strlist)
1720              (elmo-imap4-forward))
1721            (nreverse strlist)))
1722         ((elmo-imap4-parse-nil)
1723          nil)))
1724
1725 (defun elmo-imap4-parse-body-extension ()
1726   (if (eq (char-after (point)) ?\()
1727       (let (b-e)
1728         (elmo-imap4-forward)
1729         (push (elmo-imap4-parse-body-extension) b-e)
1730         (while (eq (char-after (point)) ?\ )
1731           (elmo-imap4-forward)
1732           (push (elmo-imap4-parse-body-extension) b-e))
1733         (assert (eq (char-after (point)) ?\)))
1734         (elmo-imap4-forward)
1735         (nreverse b-e))
1736     (or (elmo-imap4-parse-number)
1737         (elmo-imap4-parse-nstring))))
1738
1739 (defsubst elmo-imap4-parse-body-ext ()
1740   (let (ext)
1741     (when (eq (char-after (point)) ?\ );; body-fld-dsp
1742       (elmo-imap4-forward)
1743       (let (dsp)
1744         (if (eq (char-after (point)) ?\()
1745             (progn
1746               (elmo-imap4-forward)
1747               (push (elmo-imap4-parse-string) dsp)
1748               (elmo-imap4-forward)
1749               (push (elmo-imap4-parse-string-list) dsp)
1750               (elmo-imap4-forward))
1751           (assert (elmo-imap4-parse-nil)))
1752         (push (nreverse dsp) ext))
1753       (when (eq (char-after (point)) ?\ );; body-fld-lang
1754         (elmo-imap4-forward)
1755         (if (eq (char-after (point)) ?\()
1756             (push (elmo-imap4-parse-string-list) ext)
1757           (push (elmo-imap4-parse-nstring) ext))
1758         (while (eq (char-after (point)) ?\ );; body-extension
1759           (elmo-imap4-forward)
1760           (setq ext (append (elmo-imap4-parse-body-extension) ext)))))
1761     ext))
1762
1763 (defun elmo-imap4-parse-body ()
1764   (let (body)
1765     (when (eq (char-after (point)) ?\()
1766       (elmo-imap4-forward)
1767       (if (eq (char-after (point)) ?\()
1768           (let (subbody)
1769             (while (and (eq (char-after (point)) ?\()
1770                         (setq subbody (elmo-imap4-parse-body)))
1771               (push subbody body))
1772             (elmo-imap4-forward)
1773             (push (elmo-imap4-parse-string) body);; media-subtype
1774             (when (eq (char-after (point)) ?\ );; body-ext-mpart:
1775               (elmo-imap4-forward)
1776               (if (eq (char-after (point)) ?\();; body-fld-param
1777                   (push (elmo-imap4-parse-string-list) body)
1778                 (push (and (elmo-imap4-parse-nil) nil) body))
1779               (setq body
1780                     (append (elmo-imap4-parse-body-ext) body)));; body-ext-...
1781             (assert (eq (char-after (point)) ?\)))
1782             (elmo-imap4-forward)
1783             (nreverse body))
1784
1785         (push (elmo-imap4-parse-string) body);; media-type
1786         (elmo-imap4-forward)
1787         (push (elmo-imap4-parse-string) body);; media-subtype
1788         (elmo-imap4-forward)
1789         ;; next line for Sun SIMS bug
1790         (and (eq (char-after (point)) ? ) (elmo-imap4-forward))
1791         (if (eq (char-after (point)) ?\();; body-fld-param
1792             (push (elmo-imap4-parse-string-list) body)
1793           (push (and (elmo-imap4-parse-nil) nil) body))
1794         (elmo-imap4-forward)
1795         (push (elmo-imap4-parse-nstring) body);; body-fld-id
1796         (elmo-imap4-forward)
1797         (push (elmo-imap4-parse-nstring) body);; body-fld-desc
1798         (elmo-imap4-forward)
1799         (push (elmo-imap4-parse-string) body);; body-fld-enc
1800         (elmo-imap4-forward)
1801         (push (elmo-imap4-parse-number) body);; body-fld-octets
1802
1803         ;; ok, we're done parsing the required parts, what comes now is one
1804         ;; of three things:
1805         ;;
1806         ;; envelope       (then we're parsing body-type-msg)
1807         ;; body-fld-lines (then we're parsing body-type-text)
1808         ;; body-ext-1part (then we're parsing body-type-basic)
1809         ;;
1810         ;; the problem is that the two first are in turn optionally followed
1811         ;; by the third.  So we parse the first two here (if there are any)...
1812
1813         (when (eq (char-after (point)) ?\ )
1814           (elmo-imap4-forward)
1815           (let (lines)
1816             (cond ((eq (char-after (point)) ?\();; body-type-msg:
1817                    (push (elmo-imap4-parse-envelope) body);; envelope
1818                    (elmo-imap4-forward)
1819                    (push (elmo-imap4-parse-body) body);; body
1820                    (elmo-imap4-forward)
1821                    (push (elmo-imap4-parse-number) body));; body-fld-lines
1822                   ((setq lines (elmo-imap4-parse-number));; body-type-text:
1823                    (push lines body));; body-fld-lines
1824                   (t
1825                    (backward-char)))));; no match...
1826
1827         ;; ...and then parse the third one here...
1828
1829         (when (eq (char-after (point)) ?\ );; body-ext-1part:
1830           (elmo-imap4-forward)
1831           (push (elmo-imap4-parse-nstring) body);; body-fld-md5
1832           (setq body
1833                 (append (elmo-imap4-parse-body-ext) body)));; body-ext-1part..
1834
1835         (assert (eq (char-after (point)) ?\)))
1836         (elmo-imap4-forward)
1837         (nreverse body)))))
1838
1839 (luna-define-method elmo-folder-initialize :around ((folder
1840                                                      elmo-imap4-folder)
1841                                                     name)
1842   (let ((default-user   elmo-imap4-default-user)
1843         (default-server elmo-imap4-default-server)
1844         (default-port   elmo-imap4-default-port)
1845         (elmo-network-stream-type-alist
1846          (if elmo-imap4-stream-type-alist
1847              (append elmo-imap4-stream-type-alist
1848                      elmo-network-stream-type-alist)
1849            elmo-network-stream-type-alist))
1850         parse)
1851     (when (string-match "\\(.*\\)@\\(.*\\)" default-server)
1852       ;; case: imap4-default-server is specified like
1853       ;; "hoge%imap.server@gateway".
1854       (setq default-user (elmo-match-string 1 default-server))
1855       (setq default-server (elmo-match-string 2 default-server)))
1856     (setq name (luna-call-next-method))
1857     ;; mailbox
1858     (setq parse (elmo-parse-token name ":"))
1859     (elmo-imap4-folder-set-mailbox-internal folder
1860                                             (elmo-imap4-encode-folder-string
1861                                              (car parse)))
1862     ;; user
1863     (setq parse (elmo-parse-prefixed-element ?: (cdr parse) "/"))
1864     (elmo-net-folder-set-user-internal folder
1865                                        (if (eq (length (car parse)) 0)
1866                                            default-user
1867                                          (car parse)))
1868     ;; auth
1869     (setq parse (elmo-parse-prefixed-element ?/ (cdr parse)))
1870     (elmo-net-folder-set-auth-internal
1871      folder
1872      (if (eq (length (car parse)) 0)
1873          (or elmo-imap4-default-authenticate-type 'clear)
1874        (intern (car parse))))
1875     (unless (elmo-net-folder-server-internal folder)
1876       (elmo-net-folder-set-server-internal folder default-server))
1877     (unless (elmo-net-folder-port-internal folder)
1878       (elmo-net-folder-set-port-internal folder default-port))
1879     (unless (elmo-net-folder-stream-type-internal folder)
1880       (elmo-net-folder-set-stream-type-internal
1881        folder
1882        (elmo-get-network-stream-type elmo-imap4-default-stream-type)))
1883     folder))
1884
1885 ;;; ELMO IMAP4 folder
1886 (luna-define-method elmo-folder-expand-msgdb-path ((folder
1887                                                     elmo-imap4-folder))
1888   (convert-standard-filename
1889    (let ((mailbox (elmo-imap4-folder-mailbox-internal folder)))
1890      (if (string= "inbox" (downcase mailbox))
1891          (setq mailbox "inbox"))
1892      (if (eq (string-to-char mailbox) ?/)
1893          (setq mailbox (substring mailbox 1 (length mailbox))))
1894      ;; don't use expand-file-name (e.g. %~/something)
1895      (concat
1896       (expand-file-name
1897        (or (elmo-net-folder-user-internal folder) "nobody")
1898        (expand-file-name (or (elmo-net-folder-server-internal folder)
1899                              "nowhere")
1900                          (expand-file-name
1901                           "imap"
1902                           elmo-msgdb-directory)))
1903       "/" mailbox))))
1904
1905 (luna-define-method elmo-folder-status-plugged ((folder
1906                                                  elmo-imap4-folder))
1907   (elmo-imap4-folder-status-plugged folder))
1908
1909 (defun elmo-imap4-folder-status-plugged (folder)
1910   (let ((session (elmo-imap4-get-session folder))
1911         (killed (elmo-msgdb-killed-list-load
1912                  (elmo-folder-msgdb-path folder)))
1913         status)
1914     (with-current-buffer (elmo-network-session-buffer session)
1915       (setq elmo-imap4-status-callback nil)
1916       (setq elmo-imap4-status-callback-data nil))
1917     (setq status (elmo-imap4-response-value
1918                   (elmo-imap4-send-command-wait
1919                    session
1920                    (list "status "
1921                          (elmo-imap4-mailbox
1922                           (elmo-imap4-folder-mailbox-internal folder))
1923                          " (uidnext messages)"))
1924                   'status))
1925     (cons
1926      (- (elmo-imap4-response-value status 'uidnext) 1)
1927      (if killed
1928          (-
1929           (elmo-imap4-response-value status 'messages)
1930           (elmo-msgdb-killed-list-length killed))
1931        (elmo-imap4-response-value status 'messages)))))
1932
1933 (luna-define-method elmo-folder-list-messages-plugged ((folder
1934                                                         elmo-imap4-folder)
1935                                                        &optional
1936                                                        enable-killed)
1937   (elmo-imap4-list folder
1938                    (let ((killed
1939                           (elmo-folder-killed-list-internal
1940                            folder)))
1941                      (if (and killed
1942                               (eq (length killed) 1)
1943                               (consp (car killed))
1944                               (eq (car (car killed)) 1))
1945                          (format "uid %d:*" (cdr (car killed)))
1946                        "all"))))
1947
1948 (luna-define-method elmo-folder-list-flagged-plugged
1949   ((folder elmo-imap4-folder) flag)
1950   (elmo-imap4-folder-list-flagged folder flag))
1951
1952 (luna-define-method elmo-folder-use-flag-p ((folder elmo-imap4-folder))
1953   (not (string-match elmo-imap4-disuse-server-flag-mailbox-regexp
1954                      (elmo-imap4-folder-mailbox-internal folder))))
1955
1956 (luna-define-method elmo-folder-list-subfolders ((folder elmo-imap4-folder)
1957                                                  &optional one-level)
1958   (let* ((root (elmo-imap4-folder-mailbox-internal folder))
1959          (session (elmo-imap4-get-session folder))
1960          (prefix (elmo-folder-prefix-internal folder))
1961          (namespace-assoc
1962                   (elmo-string-matched-assoc
1963                    root
1964                    (with-current-buffer (elmo-network-session-buffer session)
1965                      elmo-imap4-server-namespace)))
1966          (delim (or (cdr namespace-assoc)
1967                  elmo-imap4-default-hierarchy-delimiter))
1968          ;; Append delimiter when root with namespace.
1969          (root (if (and namespace-assoc
1970                         (match-end 1)
1971                         (string= (substring root (match-end 1))
1972                                  ""))
1973                    (concat root delim)
1974                  root))
1975          result append-serv type)
1976     (setq result (elmo-imap4-response-get-selectable-mailbox-list
1977                   (elmo-imap4-send-command-wait
1978                    session
1979                    (list "list " (elmo-imap4-mailbox root) " *"))))
1980     ;; The response of Courier-imap doesn't contain a specified folder itself.
1981     (unless (member root result)
1982       (setq result
1983             (append result
1984                     (elmo-imap4-response-get-selectable-mailbox-list
1985                      (elmo-imap4-send-command-wait
1986                       session
1987                       (list "list \"\" " (elmo-imap4-mailbox root)))))))
1988     (when (or (not (string= (elmo-net-folder-user-internal folder)
1989                             elmo-imap4-default-user))
1990               (not (eq (elmo-net-folder-auth-internal folder)
1991                        (or elmo-imap4-default-authenticate-type 'clear))))
1992       (setq append-serv (concat ":" (elmo-net-folder-user-internal folder))))
1993     (unless (eq (elmo-net-folder-auth-internal folder)
1994                 (or elmo-imap4-default-authenticate-type 'clear))
1995       (setq append-serv
1996             (concat append-serv "/"
1997                     (symbol-name (elmo-net-folder-auth-internal folder)))))
1998     (unless (string= (elmo-net-folder-server-internal folder)
1999                      elmo-imap4-default-server)
2000       (setq append-serv (concat append-serv "@"
2001                                 (elmo-net-folder-server-internal folder))))
2002     (unless (eq (elmo-net-folder-port-internal folder) elmo-imap4-default-port)
2003       (setq append-serv (concat append-serv ":"
2004                                 (int-to-string
2005                                  (elmo-net-folder-port-internal folder)))))
2006     (setq type (elmo-net-folder-stream-type-internal folder))
2007     (unless (eq (elmo-network-stream-type-symbol type)
2008                 elmo-imap4-default-stream-type)
2009       (if type
2010           (setq append-serv (concat append-serv
2011                                     (elmo-network-stream-type-spec-string
2012                                      type)))))
2013     (if one-level
2014         (let ((re-delim (regexp-quote delim))
2015               (case-fold-search nil)
2016               folder ret has-child-p)
2017           ;; Append delimiter
2018           (when (and root
2019                      (not (string= root ""))
2020                      (not (string-match
2021                            (concat "\\(.*\\)" re-delim "\\'")
2022                            root)))
2023             (setq root (concat root delim)))
2024           (while (setq folder (car result))
2025             (when (string-match
2026                    (concat "^\\(" (regexp-quote root) "[^" re-delim "]" "+\\)"
2027                            re-delim)
2028                    folder)
2029               (setq folder (match-string 1 folder)))
2030             (setq has-child-p nil
2031                   result (delq
2032                           nil
2033                           (mapcar (lambda (fld)
2034                                     (if (string-match
2035                                          (concat "^" (regexp-quote folder)
2036                                                  "\\(" re-delim "\\|\\'\\)")
2037                                          fld)
2038                                         (progn (setq has-child-p t) nil)
2039                                       fld))
2040                                   (cdr result)))
2041                   folder (concat prefix
2042                                  (elmo-imap4-decode-folder-string folder)
2043                                  (and append-serv
2044                                       (eval append-serv)))
2045                   ret (append ret (if has-child-p
2046                                       (list (list folder))
2047                                     (list folder)))))
2048           ret)
2049       (mapcar (lambda (fld)
2050                 (concat prefix (elmo-imap4-decode-folder-string fld)
2051                         (and append-serv
2052                              (eval append-serv))))
2053               result))))
2054
2055 (luna-define-method elmo-folder-exists-p-plugged ((folder elmo-imap4-folder))
2056   (let ((session (elmo-imap4-get-session folder)))
2057     (if (string=
2058          (elmo-imap4-session-current-mailbox-internal session)
2059          (elmo-imap4-folder-mailbox-internal folder))
2060         t
2061       (elmo-imap4-session-select-mailbox
2062        session
2063        (elmo-imap4-folder-mailbox-internal folder)
2064        'force 'notify-bye))))
2065
2066 (luna-define-method elmo-folder-creatable-p ((folder elmo-imap4-folder))
2067   t)
2068
2069 (luna-define-method elmo-folder-writable-p ((folder elmo-imap4-folder))
2070   t)
2071
2072 (luna-define-method elmo-folder-delete ((folder elmo-imap4-folder))
2073   (let ((msgs (and (elmo-folder-exists-p folder)
2074                    (elmo-folder-list-messages folder))))
2075     (when (yes-or-no-p (format "%sDelete msgdb and substance of \"%s\"? "
2076                                (if (> (length msgs) 0)
2077                                    (format "%d msg(s) exists. " (length msgs))
2078                                  "")
2079                                (elmo-folder-name-internal folder)))
2080       (let ((session (elmo-imap4-get-session folder)))
2081         (when (elmo-imap4-folder-mailbox-internal folder)
2082           (when msgs (elmo-folder-delete-messages folder msgs))
2083           (elmo-imap4-send-command-wait session "close")
2084           (elmo-imap4-send-command-wait
2085            session
2086            (list "delete "
2087                  (elmo-imap4-mailbox
2088                   (elmo-imap4-folder-mailbox-internal folder)))))
2089         (elmo-imap4-session-set-current-mailbox-internal session nil))
2090       (elmo-msgdb-delete-path folder)
2091       t)))
2092
2093 (luna-define-method elmo-folder-rename-internal ((folder elmo-imap4-folder)
2094                                                  new-folder)
2095   (let ((session (elmo-imap4-get-session folder)))
2096     ;; make sure the folder is selected.
2097     (elmo-imap4-session-select-mailbox session
2098                                        (elmo-imap4-folder-mailbox-internal
2099                                         folder))
2100     (elmo-imap4-send-command-wait session "close")
2101     (elmo-imap4-send-command-wait
2102      session
2103      (list "rename "
2104            (elmo-imap4-mailbox
2105             (elmo-imap4-folder-mailbox-internal folder))
2106            " "
2107            (elmo-imap4-mailbox
2108             (elmo-imap4-folder-mailbox-internal new-folder))))
2109     (elmo-imap4-session-set-current-mailbox-internal
2110      session (elmo-imap4-folder-mailbox-internal new-folder))))
2111
2112 (defun elmo-imap4-copy-messages (src-folder dst-folder numbers)
2113   (let ((session (elmo-imap4-get-session src-folder))
2114         (set-list (elmo-imap4-make-number-set-list
2115                    numbers
2116                    elmo-imap4-number-set-chop-length))
2117         succeeds)
2118     (elmo-imap4-session-select-mailbox session
2119                                        (elmo-imap4-folder-mailbox-internal
2120                                         src-folder))
2121     (while set-list
2122       (if (elmo-imap4-send-command-wait session
2123                                         (list
2124                                          (format
2125                                           (if elmo-imap4-use-uid
2126                                               "uid copy %s "
2127                                             "copy %s ")
2128                                           (cdr (car set-list)))
2129                                          (elmo-imap4-mailbox
2130                                           (elmo-imap4-folder-mailbox-internal
2131                                            dst-folder))))
2132           (setq succeeds (append succeeds numbers)))
2133       (setq set-list (cdr set-list)))
2134     succeeds))
2135
2136 (defun elmo-imap4-set-flag (folder numbers flag &optional remove)
2137   "Set flag on messages.
2138 FOLDER is the ELMO folder structure.
2139 NUMBERS is the message numbers to be flagged.
2140 FLAG is the flag name.
2141 If optional argument REMOVE is non-nil, remove FLAG."
2142   (let ((session (elmo-imap4-get-session folder))
2143         response set-list)
2144     (elmo-imap4-session-select-mailbox session
2145                                        (elmo-imap4-folder-mailbox-internal
2146                                         folder))
2147     (when (or (elmo-string-member-ignore-case
2148                flag
2149                (elmo-imap4-session-flags-internal session))
2150               (member "\\*" (elmo-imap4-session-flags-internal session))
2151               (string= flag "\\Deleted")) ; XXX Humm..
2152       (setq set-list (elmo-imap4-make-number-set-list
2153                       numbers
2154                       elmo-imap4-number-set-chop-length))
2155       (while set-list
2156         (with-current-buffer (elmo-network-session-buffer session)
2157           (setq elmo-imap4-fetch-callback nil)
2158           (setq elmo-imap4-fetch-callback-data nil))
2159         (unless (elmo-imap4-response-ok-p
2160                  (elmo-imap4-send-command-wait
2161                   session
2162                   (format
2163                    (if elmo-imap4-use-uid
2164                        "uid store %s %sflags.silent (%s)"
2165                      "store %s %sflags.silent (%s)")
2166                    (cdr (car set-list))
2167                    (if remove "-" "+")
2168                    flag)))
2169           (setq response 'fail))
2170         (setq set-list (cdr set-list)))
2171       (not (eq response 'fail)))))
2172
2173 (luna-define-method elmo-folder-delete-messages-plugged
2174   ((folder elmo-imap4-folder) numbers)
2175   (let ((session (elmo-imap4-get-session folder)))
2176     (elmo-imap4-session-select-mailbox
2177      session
2178      (elmo-imap4-folder-mailbox-internal folder))
2179     (unless (elmo-imap4-set-flag folder numbers "\\Deleted")
2180       (error "Failed to set deleted flag"))
2181     (elmo-imap4-send-command session "expunge")))
2182
2183 (defmacro elmo-imap4-detect-search-charset (string)
2184   (` (with-temp-buffer
2185        (insert (, string))
2186        (detect-mime-charset-region (point-min) (point-max)))))
2187
2188 (defun elmo-imap4-search-internal-primitive (folder session filter from-msgs)
2189   (let ((search-key (elmo-filter-key filter))
2190         (imap-search-keys '("bcc" "body" "cc" "from" "subject" "to"
2191                             "larger" "smaller" "flag"))
2192         (total 0)
2193         (length (length from-msgs))
2194         charset set-list end results)
2195     (message "Searching...")
2196     (cond
2197      ((string= "last" search-key)
2198       (let ((numbers (or from-msgs (elmo-folder-list-messages folder))))
2199         (nthcdr (max (- (length numbers)
2200                         (string-to-int (elmo-filter-value filter)))
2201                      0)
2202                 numbers)))
2203      ((string= "first" search-key)
2204       (let* ((numbers (or from-msgs (elmo-folder-list-messages folder)))
2205              (rest (nthcdr (string-to-int (elmo-filter-value filter) )
2206                            numbers)))
2207         (mapcar '(lambda (x) (delete x numbers)) rest)
2208         numbers))
2209      ((string= "flag" search-key)
2210       (elmo-imap4-folder-list-flagged
2211        folder (intern (elmo-filter-value filter))))
2212      ((or (string= "since" search-key)
2213           (string= "before" search-key))
2214       (setq search-key (concat "sent" search-key)
2215             set-list (elmo-imap4-make-number-set-list
2216                       from-msgs
2217                       elmo-imap4-number-set-chop-length)
2218             end nil)
2219       (while (not end)
2220         (setq results
2221               (append
2222                results
2223                (elmo-imap4-response-value
2224                 (elmo-imap4-send-command-wait
2225                  session
2226                  (format
2227                   (if elmo-imap4-use-uid
2228                       "uid search %s%s%s %s"
2229                     "search %s%s%s %s")
2230                   (if from-msgs
2231                       (concat
2232                        (if elmo-imap4-use-uid "uid ")
2233                        (cdr (car set-list))
2234                        " ")
2235                     "")
2236                   (if (eq (elmo-filter-type filter)
2237                           'unmatch)
2238                       "not " "")
2239                   search-key
2240                   (elmo-date-get-description
2241                    (elmo-date-get-datevec
2242                     (elmo-filter-value filter)))))
2243                 'search)))
2244         (when (> length elmo-display-progress-threshold)
2245           (setq total (+ total (car (car set-list))))
2246           (elmo-display-progress
2247            'elmo-imap4-search "Searching..."
2248            (/ (* total 100) length)))
2249         (setq set-list (cdr set-list)
2250               end (null set-list)))
2251       results)
2252      (t
2253       (setq charset
2254             (if (eq (length (elmo-filter-value filter)) 0)
2255                 (setq charset 'us-ascii)
2256               (elmo-imap4-detect-search-charset
2257                (elmo-filter-value filter)))
2258             set-list (elmo-imap4-make-number-set-list
2259                       from-msgs
2260                       elmo-imap4-number-set-chop-length)
2261             end nil)
2262       (while (not end)
2263         (setq results
2264               (append
2265                results
2266                (elmo-imap4-response-value
2267                 (elmo-imap4-send-command-wait
2268                  session
2269                  (list
2270                   (if elmo-imap4-use-uid "uid ")
2271                   "search "
2272                   "CHARSET "
2273                   (elmo-imap4-astring
2274                    (symbol-name charset))
2275                   " "
2276                   (if from-msgs
2277                       (concat
2278                        (if elmo-imap4-use-uid "uid ")
2279                        (cdr (car set-list))
2280                        " ")
2281                     "")
2282                   (if (eq (elmo-filter-type filter)
2283                           'unmatch)
2284                       "not " "")
2285                   (format "%s%s "
2286                           (if (member
2287                                (elmo-filter-key filter)
2288                                imap-search-keys)
2289                               ""
2290                             "header ")
2291                           (elmo-filter-key filter))
2292                   (elmo-imap4-astring
2293                    (encode-mime-charset-string
2294                     (elmo-filter-value filter) charset))))
2295                 'search)))
2296         (when (> length elmo-display-progress-threshold)
2297           (setq total (+ total (car (car set-list))))
2298           (elmo-display-progress
2299            'elmo-imap4-search "Searching..."
2300            (/ (* total 100) length)))
2301         (setq set-list (cdr set-list)
2302               end (null set-list)))
2303       results))))
2304
2305 (defun elmo-imap4-search-internal (folder session condition from-msgs)
2306   (let (result)
2307     (cond
2308      ((vectorp condition)
2309       (setq result (elmo-imap4-search-internal-primitive
2310                     folder session condition from-msgs)))
2311      ((eq (car condition) 'and)
2312       (setq result (elmo-imap4-search-internal folder session (nth 1 condition)
2313                                                from-msgs)
2314             result (elmo-list-filter result
2315                                      (elmo-imap4-search-internal
2316                                       folder session (nth 2 condition)
2317                                       from-msgs))))
2318      ((eq (car condition) 'or)
2319       (setq result (elmo-imap4-search-internal
2320                     folder session (nth 1 condition) from-msgs)
2321             result (elmo-uniq-list
2322                     (nconc result
2323                            (elmo-imap4-search-internal
2324                             folder session (nth 2 condition) from-msgs)))
2325             result (sort result '<))))))
2326
2327 (luna-define-method elmo-folder-search :around ((folder elmo-imap4-folder)
2328                                                 condition &optional numbers)
2329   (if (elmo-folder-plugged-p folder)
2330       (save-excursion
2331         (let ((session (elmo-imap4-get-session folder)))
2332           (elmo-imap4-session-select-mailbox
2333            session
2334            (elmo-imap4-folder-mailbox-internal folder))
2335           (elmo-imap4-search-internal folder session condition numbers)))
2336     (luna-call-next-method)))
2337
2338 (luna-define-method elmo-folder-msgdb-create-plugged
2339   ((folder elmo-imap4-folder) numbers flag-table)
2340   (when numbers
2341     (let ((session (elmo-imap4-get-session folder))
2342           (headers
2343            (append
2344             '("Subject" "From" "To" "Cc" "Date"
2345               "Message-Id" "References" "In-Reply-To")
2346             elmo-msgdb-extra-fields))
2347           (total 0)
2348           (length (length numbers))
2349           print-length print-depth
2350           rfc2060 set-list)
2351       (setq rfc2060 (memq 'imap4rev1
2352                           (elmo-imap4-session-capability-internal
2353                            session)))
2354       (message "Getting overview...")
2355       (elmo-imap4-session-select-mailbox
2356        session (elmo-imap4-folder-mailbox-internal folder))
2357       (setq set-list (elmo-imap4-make-number-set-list
2358                       numbers
2359                       elmo-imap4-overview-fetch-chop-length))
2360       ;; Setup callback.
2361       (with-current-buffer (elmo-network-session-buffer session)
2362         (setq elmo-imap4-current-msgdb (elmo-make-msgdb)
2363               elmo-imap4-seen-messages nil
2364               elmo-imap4-fetch-callback 'elmo-imap4-fetch-callback-1
2365               elmo-imap4-fetch-callback-data (cons flag-table folder))
2366         (while set-list
2367           (elmo-imap4-send-command-wait
2368            session
2369            ;; get overview entity from IMAP4
2370            (format "%sfetch %s (%s rfc822.size flags)"
2371                    (if elmo-imap4-use-uid "uid " "")
2372                    (cdr (car set-list))
2373                    (if rfc2060
2374                        (format "body.peek[header.fields %s]" headers)
2375                      (format "%s" headers))))
2376           (when (> length elmo-display-progress-threshold)
2377             (setq total (+ total (car (car set-list))))
2378             (elmo-display-progress
2379              'elmo-imap4-msgdb-create "Getting overview..."
2380              (/ (* total 100) length)))
2381           (setq set-list (cdr set-list)))
2382         (message "Getting overview...done")
2383         (when elmo-imap4-seen-messages
2384           (elmo-imap4-set-flag folder elmo-imap4-seen-messages "\\Seen"))
2385         ;; cannot setup the global flag while retrieval.
2386         (dolist (number (elmo-msgdb-list-messages elmo-imap4-current-msgdb))
2387           (elmo-global-flags-set (elmo-msgdb-flags elmo-imap4-current-msgdb
2388                                                    number)
2389                                  folder number
2390                                  (elmo-message-entity-field
2391                                   (elmo-msgdb-message-entity
2392                                    elmo-imap4-current-msgdb number)
2393                                   'message-id)))
2394         elmo-imap4-current-msgdb))))
2395
2396 (luna-define-method elmo-folder-set-flag-plugged ((folder elmo-imap4-folder)
2397                                                   numbers flag)
2398   (let ((spec (cdr (assq flag elmo-imap4-flag-specs))))
2399     (elmo-imap4-set-flag folder numbers (or (car spec)
2400                                             (capitalize (symbol-name flag)))
2401                          (nth 1 spec))))
2402
2403 (luna-define-method elmo-folder-unset-flag-plugged ((folder elmo-imap4-folder)
2404                                                     numbers flag)
2405   (let ((spec (cdr (assq flag elmo-imap4-flag-specs))))
2406     (elmo-imap4-set-flag folder numbers (or (car spec)
2407                                             (capitalize (symbol-name flag)))
2408                          (not (nth 1 spec)))))
2409
2410 (luna-define-method elmo-message-use-cache-p ((folder elmo-imap4-folder)
2411                                               number)
2412   elmo-imap4-use-cache)
2413
2414 (luna-define-method elmo-folder-message-appendable-p ((folder elmo-imap4-folder))
2415   (if (elmo-folder-plugged-p folder)
2416       (not (elmo-imap4-session-read-only-internal
2417             (elmo-imap4-get-session folder)))
2418     elmo-enable-disconnected-operation)) ; offline refile.
2419
2420 (luna-define-method elmo-folder-check-plugged ((folder elmo-imap4-folder))
2421   (let ((session (elmo-imap4-get-session folder 'if-exists)))
2422     (when session
2423       (if (string=
2424            (elmo-imap4-session-current-mailbox-internal session)
2425            (elmo-imap4-folder-mailbox-internal folder))
2426           (if elmo-imap4-use-select-to-update-status
2427               (elmo-imap4-session-select-mailbox
2428                session
2429                (elmo-imap4-folder-mailbox-internal folder)
2430                'force)
2431             (elmo-imap4-session-check session))))))
2432
2433 (defsubst elmo-imap4-folder-diff-plugged (folder)
2434   (let ((session (elmo-imap4-get-session folder))
2435         messages new unread response killed uidnext)
2436 ;;; (elmo-imap4-commit spec)
2437     (with-current-buffer (elmo-network-session-buffer session)
2438       (setq elmo-imap4-status-callback nil)
2439       (setq elmo-imap4-status-callback-data nil))
2440     (if elmo-imap4-use-select-to-update-status
2441         (elmo-imap4-session-select-mailbox
2442          session
2443          (elmo-imap4-folder-mailbox-internal folder)))
2444     (setq response
2445           (elmo-imap4-send-command-wait session
2446                                         (list
2447                                          "status "
2448                                          (elmo-imap4-mailbox
2449                                           (elmo-imap4-folder-mailbox-internal
2450                                            folder))
2451                                          " (recent unseen messages uidnext)")))
2452     (setq response (elmo-imap4-response-value response 'status))
2453     (setq messages (elmo-imap4-response-value response 'messages))
2454     (setq uidnext (elmo-imap4-response-value response 'uidnext))
2455     (setq killed (elmo-msgdb-killed-list-load (elmo-folder-msgdb-path folder)))
2456     ;;
2457     (when killed
2458       (when (and (consp (car killed))
2459                  (eq (car (car killed)) 1))
2460         (setq messages (- uidnext (cdr (car killed)) 1)))
2461       (setq messages (- messages
2462                         (elmo-msgdb-killed-list-length (cdr killed)))))
2463     (setq new (elmo-imap4-response-value response 'recent)
2464           unread (elmo-imap4-response-value response 'unseen))
2465     (if (< unread new) (setq new unread))
2466     (list new unread messages)))
2467
2468 (luna-define-method elmo-folder-diff-plugged ((folder elmo-imap4-folder))
2469   (elmo-imap4-folder-diff-plugged folder))
2470
2471 (luna-define-method elmo-folder-diff-async ((folder elmo-imap4-folder))
2472   (setq elmo-imap4-server-diff-async-callback
2473         elmo-folder-diff-async-callback)
2474   (setq elmo-imap4-server-diff-async-callback-data
2475         elmo-folder-diff-async-callback-data)
2476   (elmo-imap4-server-diff-async folder))
2477
2478 (luna-define-method elmo-folder-open :around ((folder elmo-imap4-folder)
2479                                               &optional load-msgdb)
2480   (if (elmo-folder-plugged-p folder)
2481       (let (session mailbox msgdb result response tag)
2482         (condition-case err
2483             (progn
2484               (setq session (elmo-imap4-get-session folder)
2485                     mailbox (elmo-imap4-folder-mailbox-internal folder)
2486                     tag (elmo-imap4-send-command session
2487                                                  (list "select "
2488                                                        (elmo-imap4-mailbox
2489                                                         mailbox))))
2490               (message "Selecting %s..."
2491                        (elmo-folder-name-internal folder))
2492               (if load-msgdb
2493                   (setq msgdb (elmo-folder-msgdb-load folder 'silent)))
2494               (elmo-folder-set-killed-list-internal
2495                folder
2496                (elmo-msgdb-killed-list-load (elmo-folder-msgdb-path folder)))
2497               (if (setq result (elmo-imap4-response-ok-p
2498                                 (setq response
2499                                       (elmo-imap4-read-response session tag))))
2500                   (progn
2501                     (elmo-imap4-session-set-current-mailbox-internal
2502                      session mailbox)
2503                     (elmo-imap4-session-set-read-only-internal
2504                      session
2505                      (nth 1 (assq 'read-only (assq 'ok response))))
2506                     (elmo-imap4-session-set-flags-internal
2507                      session
2508                      (nth 1 (or (assq 'permanentflags response)
2509                                 (assq 'flags response)))))
2510                 (elmo-imap4-session-set-current-mailbox-internal session nil)
2511                 (if (elmo-imap4-response-bye-p response)
2512                     (elmo-imap4-process-bye session)
2513                   (error "%s"
2514                          (or (elmo-imap4-response-error-text response)
2515                              (format "Select %s failed" mailbox)))))
2516               (message "Selecting %s...done"
2517                        (elmo-folder-name-internal folder))
2518               (elmo-folder-set-msgdb-internal
2519                folder msgdb))
2520           (quit
2521            (if (elmo-imap4-response-ok-p response)
2522                (elmo-imap4-session-set-current-mailbox-internal
2523                 session mailbox)
2524              (and session
2525                   (elmo-imap4-session-set-current-mailbox-internal
2526                    session nil))))
2527           (error
2528            (if (elmo-imap4-response-ok-p response)
2529                (elmo-imap4-session-set-current-mailbox-internal
2530                 session mailbox)
2531              (and session
2532                   (elmo-imap4-session-set-current-mailbox-internal
2533                    session nil))))))
2534     (luna-call-next-method)))
2535
2536 ;; elmo-folder-open-internal: do nothing.
2537
2538 (luna-define-method elmo-find-fetch-strategy
2539   ((folder elmo-imap4-folder) entity &optional ignore-cache)
2540   (let ((number (elmo-message-entity-number entity))
2541         cache-file size message-id)
2542     (setq size (elmo-message-entity-field entity 'size))
2543     (setq message-id (elmo-message-entity-field entity 'message-id))
2544     (setq cache-file (elmo-file-cache-get message-id))
2545     (if (or ignore-cache
2546             (null (elmo-file-cache-status cache-file)))
2547         (if (and elmo-message-fetch-threshold
2548                  (integerp size)
2549                  (>= size elmo-message-fetch-threshold)
2550                  (or (not elmo-message-fetch-confirm)
2551                      (not (prog1 (y-or-n-p
2552                                   (format
2553                                    "Fetch entire message at once? (%dbytes)"
2554                                    size))
2555                             (message "")))))
2556             ;; Fetch message as imap message.
2557             (elmo-make-fetch-strategy 'section
2558                                       nil
2559                                       (elmo-message-use-cache-p
2560                                        folder number)
2561                                       (elmo-file-cache-path
2562                                        cache-file))
2563           ;; Don't use existing cache and fetch entire message at once.
2564           (elmo-make-fetch-strategy 'entire nil
2565                                     (elmo-message-use-cache-p
2566                                      folder number)
2567                                     (elmo-file-cache-path cache-file)))
2568       ;; Cache found and use it.
2569       (if (not ignore-cache)
2570           (if (eq (elmo-file-cache-status cache-file) 'section)
2571               ;; Fetch message with imap message.
2572               (elmo-make-fetch-strategy 'section
2573                                         t
2574                                         (elmo-message-use-cache-p
2575                                          folder number)
2576                                         (elmo-file-cache-path
2577                                          cache-file))
2578             (elmo-make-fetch-strategy 'entire
2579                                       t
2580                                       (elmo-message-use-cache-p
2581                                        folder number)
2582                                       (elmo-file-cache-path
2583                                        cache-file)))))))
2584
2585 (luna-define-method elmo-folder-create-plugged ((folder elmo-imap4-folder))
2586   (elmo-imap4-send-command-wait
2587    (elmo-imap4-get-session folder)
2588    (list "create "
2589          (elmo-imap4-mailbox
2590           (elmo-imap4-folder-mailbox-internal folder)))))
2591
2592 (defun elmo-imap4-flags-to-imap (flags)
2593   "Convert FLAGS to the IMAP flag string."
2594   (let ((imap-flag (if (not (memq 'unread flags)) "\\Seen"))
2595         (flags (delq 'cached (delq 'unread flags)))
2596         spec)
2597     (dolist (flag flags)
2598       (setq imap-flag (concat imap-flag (if imap-flag " ")
2599                               (or (car (cdr (assq flag elmo-imap4-flag-specs)))
2600                                   (capitalize (symbol-name flag))))))
2601     imap-flag))
2602
2603 (luna-define-method elmo-folder-append-buffer
2604   ((folder elmo-imap4-folder) &optional flags number)
2605   (if (elmo-folder-plugged-p folder)
2606       (let ((session (elmo-imap4-get-session folder))
2607             send-buffer result)
2608         (elmo-imap4-session-select-mailbox session
2609                                            (elmo-imap4-folder-mailbox-internal
2610                                             folder))
2611         (setq send-buffer (elmo-imap4-setup-send-buffer))
2612         (unwind-protect
2613             (setq result
2614                   (elmo-imap4-send-command-wait
2615                    session
2616                    (list
2617                     "append "
2618                     (elmo-imap4-mailbox (elmo-imap4-folder-mailbox-internal
2619                                          folder))
2620                     (if (and flags (elmo-folder-use-flag-p folder))
2621                         (concat " (" (elmo-imap4-flags-to-imap flags) ") ")
2622                       " () ")
2623                     (elmo-imap4-buffer-literal send-buffer))))
2624           (kill-buffer send-buffer))
2625         (when result
2626           (elmo-folder-preserve-flags
2627            folder (elmo-msgdb-get-message-id-from-buffer) flags))
2628         result)
2629     ;; Unplugged
2630     (if elmo-enable-disconnected-operation
2631         (elmo-folder-append-buffer-dop folder flags number)
2632       (error "Unplugged"))))
2633
2634 (eval-when-compile
2635   (defmacro elmo-imap4-identical-system-p (folder1 folder2)
2636     "Return t if FOLDER1 and FOLDER2 are in the same IMAP4 system."
2637     (` (and (string= (elmo-net-folder-server-internal (, folder1))
2638                      (elmo-net-folder-server-internal (, folder2)))
2639             (eq (elmo-net-folder-port-internal (, folder1))
2640                 (elmo-net-folder-port-internal (, folder2)))
2641             (string= (elmo-net-folder-user-internal (, folder1))
2642                      (elmo-net-folder-user-internal (, folder2)))))))
2643
2644 (luna-define-method elmo-folder-next-message-number-plugged
2645   ((folder elmo-imap4-folder))
2646   (let ((session (elmo-imap4-get-session folder))
2647         messages new unread response killed uidnext)
2648     (with-current-buffer (elmo-network-session-buffer session)
2649       (setq elmo-imap4-status-callback nil)
2650       (setq elmo-imap4-status-callback-data nil))
2651     (if elmo-imap4-use-select-to-update-status
2652         (elmo-imap4-session-select-mailbox
2653          session
2654          (elmo-imap4-folder-mailbox-internal folder)))
2655     (setq response
2656           (elmo-imap4-send-command-wait session
2657                                         (list
2658                                          "status "
2659                                          (elmo-imap4-mailbox
2660                                           (elmo-imap4-folder-mailbox-internal
2661                                            folder))
2662                                          " (uidnext)"))
2663           response (elmo-imap4-response-value response 'status))
2664     (elmo-imap4-response-value response 'uidnext)))
2665
2666 (luna-define-method elmo-folder-append-messages :around
2667   ((folder elmo-imap4-folder) src-folder numbers &optional same-number)
2668   (if (and (eq (elmo-folder-type-internal src-folder) 'imap4)
2669            (elmo-imap4-identical-system-p folder src-folder)
2670            (elmo-folder-plugged-p folder))
2671       ;; Plugged
2672       (prog1
2673           (elmo-imap4-copy-messages src-folder folder numbers)
2674         (elmo-progress-notify 'elmo-folder-move-messages (length numbers)))
2675     (luna-call-next-method)))
2676
2677 (luna-define-method elmo-message-deletable-p ((folder elmo-imap4-folder)
2678                                               number)
2679   (if (elmo-folder-plugged-p folder)
2680       (not (elmo-imap4-session-read-only-internal
2681             (elmo-imap4-get-session folder)))
2682     elmo-enable-disconnected-operation)) ; offline refile.
2683
2684 ;(luna-define-method elmo-message-fetch-unplugged
2685 ;  ((folder elmo-imap4-folder)
2686 ;   number strategy  &optional section outbuf unseen)
2687 ;  (error "%d%s is not cached." number (if section
2688 ;                                         (format "(%s)" section)
2689 ;                                       "")))
2690
2691 (defsubst elmo-imap4-message-fetch (folder number strategy
2692                                            section outbuf unseen)
2693   (let ((session (elmo-imap4-get-session folder))
2694         response)
2695     (elmo-imap4-session-select-mailbox session
2696                                        (elmo-imap4-folder-mailbox-internal
2697                                         folder))
2698     (with-current-buffer (elmo-network-session-buffer session)
2699       (setq elmo-imap4-fetch-callback nil)
2700       (setq elmo-imap4-fetch-callback-data nil))
2701     (unless elmo-inhibit-display-retrieval-progress
2702       (setq elmo-imap4-display-literal-progress t))
2703     (unwind-protect
2704         (setq response
2705               (elmo-imap4-send-command-wait session
2706                                             (format
2707                                              (if elmo-imap4-use-uid
2708                                                  "uid fetch %s body%s[%s]"
2709                                                "fetch %s body%s[%s]")
2710                                              number
2711                                              (if unseen ".peek" "")
2712                                              (or section "")
2713                                              )))
2714       (setq elmo-imap4-display-literal-progress nil))
2715     (unless elmo-inhibit-display-retrieval-progress
2716       (elmo-display-progress 'elmo-imap4-display-literal-progress
2717                              "Retrieving..." 100)  ; remove progress bar.
2718       (message "Retrieving...done"))
2719     (if (setq response (elmo-imap4-response-bodydetail-text
2720                         (elmo-imap4-response-value-all
2721                          response 'fetch)))
2722         (with-current-buffer outbuf
2723           (erase-buffer)
2724           (insert response)
2725           (elmo-delete-cr-buffer)
2726           t))))
2727
2728 (luna-define-method elmo-message-fetch-plugged ((folder elmo-imap4-folder)
2729                                                 number strategy
2730                                                 &optional section
2731                                                 outbuf unseen)
2732   (elmo-imap4-message-fetch folder number strategy section outbuf unseen))
2733
2734 (luna-define-method elmo-message-fetch-field ((folder elmo-imap4-folder)
2735                                               number field)
2736   (let ((session (elmo-imap4-get-session folder)))
2737     (elmo-imap4-session-select-mailbox session
2738                                        (elmo-imap4-folder-mailbox-internal
2739                                         folder))
2740     (with-current-buffer (elmo-network-session-buffer session)
2741       (setq elmo-imap4-fetch-callback nil)
2742       (setq elmo-imap4-fetch-callback-data nil))
2743     (with-temp-buffer
2744       (insert
2745        (elmo-imap4-response-bodydetail-text
2746         (elmo-imap4-response-value
2747          (elmo-imap4-send-command-wait session
2748                                        (concat
2749                                         (if elmo-imap4-use-uid
2750                                             "uid ")
2751                                         (format
2752                                          "fetch %s (body.peek[header.fields (%s)])"
2753                                          number field)))
2754          'fetch)))
2755       (elmo-delete-cr-buffer)
2756       (goto-char (point-min))
2757       (std11-field-body (symbol-name field)))))
2758
2759 (luna-define-method elmo-folder-search-requires-msgdb-p ((folder
2760                                                           elmo-imap4-folder)
2761                                                          condition)
2762   nil)
2763
2764 (autoload 'elmo-global-flags-set "elmo-flag")
2765 (autoload 'elmo-get-global-flags "elmo-flag")
2766
2767 (require 'product)
2768 (product-provide (provide 'elmo-imap4) (require 'elmo-version))
2769
2770 ;;; elmo-imap4.el ends here