* elmo.el (elmo-folder-list-flagged): New generic function.
[elisp/wanderlust.git] / elmo / elmo-pop3.el
1 ;;; elmo-pop3.el --- POP3 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
6 ;; Author: Yuuichi Teranishi <teranisi@gohome.org>
7 ;;      Kenichi OKADA <okada@opaopa.org>
8 ;; Keywords: mail, net news
9
10 ;; This file is part of ELMO (Elisp Library for Message Orchestration).
11
12 ;; This program is free software; you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation; either version 2, or (at your option)
15 ;; any later version.
16 ;;
17 ;; This program is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21 ;;
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
24 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
25 ;; Boston, MA 02111-1307, USA.
26 ;;
27
28 ;;; Commentary:
29 ;;
30
31 ;;; Code:
32 ;;
33
34 (require 'elmo-msgdb)
35 (require 'elmo-net)
36
37 (eval-when-compile
38   (require 'elmo-util))
39
40 (eval-and-compile
41   (autoload 'md5 "md5"))
42
43 (defcustom elmo-pop3-default-use-uidl t
44   "If non-nil, use UIDL on POP3."
45   :type 'boolean
46   :group 'elmo)
47
48 (defvar elmo-pop3-use-uidl-internal t
49   "(Internal switch for using UIDL on POP3).")
50
51 (defvar elmo-pop3-use-cache t
52   "Use cache in pop3 folder.")
53
54 (defvar elmo-pop3-send-command-synchronously nil
55   "If non-nil, commands are send synchronously.
56 If server doesn't accept asynchronous commands, this variable should be
57 set as non-nil.")
58
59 (defvar elmo-pop3-exists-exactly t)
60 (defvar sasl-mechanism-alist)
61
62 (defvar elmo-pop3-total-size nil)
63
64 ;; For debugging.
65 (defvar elmo-pop3-debug nil
66   "Non-nil forces POP3 folder as debug mode.
67 Debug information is inserted in the buffer \"*POP3 DEBUG*\"")
68
69 ;;; Debug
70 (defsubst elmo-pop3-debug (message &rest args)
71   (if elmo-pop3-debug
72       (let ((biff (string-match "BIFF-" (buffer-name)))
73             pos)
74         (with-current-buffer (get-buffer-create (concat "*POP3 DEBUG*"
75                                                         (if biff "BIFF")))
76           (goto-char (point-max))
77           (setq pos (point))
78           (insert (apply 'format message args) "\n")))))
79
80 ;;; ELMO POP3 folder
81 (eval-and-compile
82   (luna-define-class elmo-pop3-folder (elmo-net-folder)
83                      (use-uidl location-alist))
84   (luna-define-internal-accessors 'elmo-pop3-folder))
85
86 (luna-define-method elmo-folder-initialize :around ((folder
87                                                      elmo-pop3-folder)
88                                                     name)
89   (let ((elmo-network-stream-type-alist
90          (if elmo-pop3-stream-type-alist
91              (append elmo-pop3-stream-type-alist
92                      elmo-network-stream-type-alist)
93            elmo-network-stream-type-alist))
94         parse)
95     (setq name (luna-call-next-method))
96     ;; user
97     (setq parse (elmo-parse-token name "/:"))
98     (elmo-net-folder-set-user-internal folder
99                                        (if (eq (length (car parse)) 0)
100                                            elmo-pop3-default-user
101                                          (car parse)))
102     ;; auth
103     (setq parse (elmo-parse-prefixed-element ?/ (cdr parse) ":"))
104     (elmo-net-folder-set-auth-internal folder
105                                        (if (eq (length (car parse)) 0)
106                                            elmo-pop3-default-authenticate-type
107                                          (intern (downcase (car parse)))))
108     ;; uidl
109     (setq parse (elmo-parse-prefixed-element ?: (cdr parse)))
110     (elmo-pop3-folder-set-use-uidl-internal folder
111                                             (if (eq (length (car parse)) 0)
112                                                 elmo-pop3-default-use-uidl
113                                               (string= (car parse) "uidl")))
114     (unless (elmo-net-folder-server-internal folder)
115       (elmo-net-folder-set-server-internal folder
116                                            elmo-pop3-default-server))
117     (unless (elmo-net-folder-port-internal folder)
118       (elmo-net-folder-set-port-internal folder
119                                          elmo-pop3-default-port))
120     (unless (elmo-net-folder-stream-type-internal folder)
121       (elmo-net-folder-set-stream-type-internal
122        folder
123        (elmo-get-network-stream-type
124         elmo-pop3-default-stream-type)))
125     folder))
126
127 ;;; POP3 session
128 (luna-define-class elmo-pop3-session (elmo-network-session) ())
129
130 ;; buffer-local
131 (defvar elmo-pop3-read-point nil)
132 (defvar elmo-pop3-number-uidl-hash nil) ; number -> uidl
133 (defvar elmo-pop3-uidl-number-hash nil) ; uidl -> number
134 (defvar elmo-pop3-size-hash nil) ; number -> size
135 (defvar elmo-pop3-uidl-done nil)
136 (defvar elmo-pop3-list-done nil)
137 (defvar elmo-pop3-lock nil)
138
139 (defvar elmo-pop3-local-variables '(elmo-pop3-read-point
140                                     elmo-pop3-uidl-number-hash
141                                     elmo-pop3-number-uidl-hash
142                                     elmo-pop3-uidl-done
143                                     elmo-pop3-size-hash
144                                     elmo-pop3-list-done
145                                     elmo-pop3-lock))
146
147 (luna-define-method elmo-network-close-session ((session elmo-pop3-session))
148   (when (elmo-network-session-process-internal session)
149     (when (memq (process-status
150                  (elmo-network-session-process-internal session))
151                 '(open run))
152       (elmo-pop3-send-command (elmo-network-session-process-internal session)
153                               "quit")
154       ;; process is dead.
155       (or (elmo-pop3-read-response
156            (elmo-network-session-process-internal session)
157            t)
158           (error "POP error: QUIT failed")))
159     (kill-buffer (process-buffer
160                   (elmo-network-session-process-internal session)))
161     (delete-process (elmo-network-session-process-internal session))))
162
163 (defun elmo-pop3-get-session (folder &optional if-exists)
164   (let ((elmo-pop3-use-uidl-internal (if elmo-inhibit-number-mapping
165                                          nil
166                                        (elmo-pop3-folder-use-uidl-internal
167                                         folder))))
168     (elmo-network-get-session 'elmo-pop3-session
169                               (concat
170                                (if (elmo-folder-biff-internal folder)
171                                    "BIFF-")
172                                "POP3")
173                               folder if-exists)))
174
175 (defun elmo-pop3-send-command (process command &optional no-erase no-log)
176   (with-current-buffer (process-buffer process)
177     (unless no-erase
178       (erase-buffer))
179     (goto-char (point-min))
180     (setq elmo-pop3-read-point (point))
181     (elmo-pop3-debug "SEND: %s\n" (if no-log "<NO LOGGING>" command))
182     (process-send-string process command)
183     (process-send-string process "\r\n")))
184
185 (defun elmo-pop3-read-response (process &optional not-command)
186   ;; buffer is in case for process is dead.
187   (with-current-buffer (process-buffer process)
188     (let ((case-fold-search nil)
189           (response-string nil)
190           (response-continue t)
191           (return-value nil)
192           match-end)
193       (while response-continue
194         (goto-char elmo-pop3-read-point)
195         (while (not (re-search-forward "\r?\n" nil t))
196           (accept-process-output process 1)
197           (goto-char elmo-pop3-read-point))
198         (setq match-end (point))
199         (setq response-string
200               (buffer-substring elmo-pop3-read-point (- match-end 2)))
201         (goto-char elmo-pop3-read-point)
202         (if (looking-at "\\+.*$")
203             (progn
204               (setq response-continue nil)
205               (setq elmo-pop3-read-point match-end)
206               (setq return-value
207                     (if return-value
208                         (concat return-value "\n" response-string)
209                       response-string)))
210           (if (looking-at "\\-.*$")
211               (progn
212                 (setq response-continue nil)
213                 (setq elmo-pop3-read-point match-end)
214                 (setq return-value nil))
215             (setq elmo-pop3-read-point match-end)
216             (if not-command
217                 (setq response-continue nil))
218             (setq return-value
219                   (if return-value
220                       (concat return-value "\n" response-string)
221                     response-string)))
222           (setq elmo-pop3-read-point match-end)))
223       return-value)))
224
225 (defun elmo-pop3-process-filter (process output)
226   (with-current-buffer (process-buffer process)
227     (goto-char (point-max))
228     (insert output)
229     (elmo-pop3-debug "RECEIVED: %s\n" output)
230     (if (and elmo-pop3-total-size
231              (> elmo-pop3-total-size
232                 (min elmo-display-retrieval-progress-threshold 100)))
233         (elmo-display-progress
234          'elmo-display-retrieval-progress
235          (format "Retrieving (%d/%d bytes)..."
236                  (buffer-size)
237                  elmo-pop3-total-size)
238          (/ (buffer-size) (/ elmo-pop3-total-size 100))))))
239
240 (defun elmo-pop3-auth-user (session)
241   (let ((process (elmo-network-session-process-internal session)))
242     ;; try USER/PASS
243     (elmo-pop3-send-command
244      process
245      (format "user %s" (elmo-network-session-user-internal session))
246      nil 'no-log)
247     (or (elmo-pop3-read-response process t)
248         (progn
249           (delete-process process)
250           (signal 'elmo-authenticate-error
251                   '(elmo-pop-auth-user))))
252     (elmo-pop3-send-command  process
253                              (format
254                               "pass %s"
255                               (elmo-get-passwd
256                                (elmo-network-session-password-key session)))
257                              nil 'no-log)
258     (or (elmo-pop3-read-response process t)
259         (progn
260           (delete-process process)
261           (signal 'elmo-authenticate-error
262                   '(elmo-pop-auth-user))))))
263
264 (defun elmo-pop3-auth-apop (session)
265   (if (string-match "^\+OK .*\\(<[^\>]+>\\)"
266                     (elmo-network-session-greeting-internal session))
267       ;; good, APOP ready server
268       (progn
269         (elmo-pop3-send-command
270          (elmo-network-session-process-internal session)
271          (format "apop %s %s"
272                  (elmo-network-session-user-internal session)
273                  (md5
274                   (concat (match-string
275                            1
276                            (elmo-network-session-greeting-internal session))
277                           (elmo-get-passwd
278                            (elmo-network-session-password-key session)))))
279          nil 'no-log)
280         (or (elmo-pop3-read-response
281              (elmo-network-session-process-internal session)
282              t)
283             (progn
284               (delete-process (elmo-network-session-process-internal session))
285               (signal 'elmo-authenticate-error
286                       '(elmo-pop3-auth-apop)))))
287     (signal 'elmo-open-error '(elmo-pop3-auth-apop))))
288
289 (luna-define-method elmo-network-initialize-session-buffer :after
290   ((session elmo-pop3-session) buffer)
291   (with-current-buffer buffer
292     (mapcar 'make-variable-buffer-local elmo-pop3-local-variables)))
293
294 (luna-define-method elmo-network-initialize-session ((session
295                                                       elmo-pop3-session))
296   (let ((process (elmo-network-session-process-internal session))
297         response mechanism)
298     (with-current-buffer (process-buffer process)
299       (set-process-filter process 'elmo-pop3-process-filter)
300       (setq elmo-pop3-read-point (point-min))
301       ;; Skip garbage output from process before greeting.
302       (while (and (memq (process-status process) '(open run))
303                   (goto-char (point-max))
304                   (forward-line -1)
305                   (not (looking-at "+OK")))
306         (accept-process-output process 1))
307       (setq elmo-pop3-read-point (point))
308       (or (elmo-network-session-set-greeting-internal
309            session
310            (elmo-pop3-read-response process t))
311           (signal 'elmo-open-error
312                   '(elmo-network-intialize-session)))
313       (when (eq (elmo-network-stream-type-symbol
314                  (elmo-network-session-stream-type-internal session))
315                 'starttls)
316         (elmo-pop3-send-command process "stls")
317         (if (string-match "^\+OK"
318                           (elmo-pop3-read-response process))
319             (starttls-negotiate process)
320           (signal 'elmo-open-error
321                   '(elmo-pop3-starttls-error)))))))
322
323 (luna-define-method elmo-network-authenticate-session ((session
324                                                         elmo-pop3-session))
325   (with-current-buffer (process-buffer
326                         (elmo-network-session-process-internal session))
327     (let* ((process (elmo-network-session-process-internal session))
328            (auth (elmo-network-session-auth-internal session))
329            (auth (mapcar '(lambda (mechanism) (upcase (symbol-name mechanism)))
330                          (if (listp auth) auth (list auth))))
331            sasl-mechanisms
332            client name step response mechanism
333            sasl-read-passphrase)
334       (or (and (string= "USER" (car auth))
335                (elmo-pop3-auth-user session))
336           (and (string= "APOP" (car auth))
337                (elmo-pop3-auth-apop session))
338           (progn
339             (require 'sasl)
340             (setq sasl-mechanisms (mapcar 'car sasl-mechanism-alist))
341             (setq mechanism (sasl-find-mechanism auth))
342             (unless mechanism
343               (signal 'elmo-authenticate-error '(elmo-pop3-auth-no-mechanisms)))
344             (setq client
345                   (sasl-make-client
346                    mechanism
347                    (elmo-network-session-user-internal session)
348                    "pop"
349                    (elmo-network-session-server-internal session)))
350 ;;;         (if elmo-pop3-auth-user-realm
351 ;;;             (sasl-client-set-property client 'realm elmo-pop3-auth-user-realm))
352             (setq name (sasl-mechanism-name mechanism))
353             (elmo-network-session-set-auth-internal session
354                                                     (intern (downcase name)))
355             (setq sasl-read-passphrase
356                   (function
357                    (lambda (prompt)
358                      (elmo-get-passwd
359                       (elmo-network-session-password-key session)))))
360             (setq step (sasl-next-step client nil))
361             (elmo-pop3-send-command
362              process
363              (concat "AUTH " name
364                      (and (sasl-step-data step)
365                           (concat
366                            " "
367                            (elmo-base64-encode-string
368                             (sasl-step-data step) 'no-line-break))))
369              nil 'no-log)
370             (catch 'done
371               (while t
372                 (unless (setq response (elmo-pop3-read-response process t))
373                   ;; response is NO or BAD.
374                   (signal 'elmo-authenticate-error
375                           (list (intern
376                                  (concat "elmo-pop3-auth-"
377                                          (downcase name))))))
378                 (if (string-match "^\+OK" response)
379                     (if (sasl-next-step client step)
380                         ;; Bogus server?
381                         (signal 'elmo-authenticate-error
382                                 (list (intern
383                                        (concat "elmo-pop3-auth-"
384                                                (downcase name)))))
385                       ;; The authentication process is finished.
386                       (throw 'done nil)))
387                 (sasl-step-set-data
388                  step
389                  (elmo-base64-decode-string
390                   (cadr (split-string response " "))))
391                 (setq step (sasl-next-step client step))
392                 (elmo-pop3-send-command
393                  process
394                  (if (sasl-step-data step)
395                      (elmo-base64-encode-string (sasl-step-data step)
396                                                 'no-line-break)
397                    "") nil 'no-log))))))))
398
399 (luna-define-method elmo-network-setup-session ((session
400                                                  elmo-pop3-session))
401   (let ((process (elmo-network-session-process-internal session))
402         count response)
403     (with-current-buffer (process-buffer process)
404       (setq elmo-pop3-size-hash (elmo-make-hash 31))
405       ;; To get obarray of uidl and size
406       (elmo-pop3-send-command process "list")
407       (if (null (elmo-pop3-read-response process))
408           (error "POP LIST command failed"))
409       (if (null (setq response
410                       (elmo-pop3-read-contents
411                        (current-buffer) process)))
412           (error "POP LIST command failed"))
413       ;; POP server always returns a sequence of serial numbers.
414       (setq count (elmo-pop3-parse-list-response response))
415       ;; UIDL
416       (when elmo-pop3-use-uidl-internal
417         (setq elmo-pop3-uidl-number-hash (elmo-make-hash (* count 2)))
418         (setq elmo-pop3-number-uidl-hash (elmo-make-hash (* count 2)))
419         ;; UIDL
420         (elmo-pop3-send-command process "uidl")
421         (unless (elmo-pop3-read-response process)
422           (error "POP UIDL failed"))
423         (unless (setq response (elmo-pop3-read-contents
424                                 (current-buffer) process))
425           (error "POP UIDL failed"))
426         (elmo-pop3-parse-uidl-response response)))))
427
428 (defun elmo-pop3-read-contents (buffer process)
429   (with-current-buffer buffer
430     (let ((case-fold-search nil)
431           match-end)
432       (goto-char elmo-pop3-read-point)
433       (while (not (re-search-forward "^\\.\r\n" nil t))
434         (accept-process-output process 1)
435         (goto-char elmo-pop3-read-point))
436       (setq match-end (point))
437       (elmo-delete-cr
438        (buffer-substring elmo-pop3-read-point
439                          (- match-end 3))))))
440
441 (luna-define-method elmo-folder-expand-msgdb-path ((folder elmo-pop3-folder))
442   (convert-standard-filename
443    (expand-file-name
444     (elmo-safe-filename (elmo-net-folder-user-internal folder))
445     (expand-file-name (elmo-net-folder-server-internal folder)
446                       (expand-file-name
447                        "pop"
448                        elmo-msgdb-directory)))))
449
450 (luna-define-method elmo-folder-exists-p ((folder elmo-pop3-folder))
451   (if (and elmo-pop3-exists-exactly
452            (elmo-folder-plugged-p folder))
453       (save-excursion
454         (let (elmo-auto-change-plugged  ; don't change plug status.
455               (elmo-inhibit-number-mapping t) ; No need to use uidl.
456               session)
457           (prog1
458               (setq session (elmo-pop3-get-session folder))
459             (if session
460                 (elmo-network-close-session session)))))
461     (file-directory-p (elmo-folder-msgdb-path folder))))
462
463 (defun elmo-pop3-parse-uidl-response (string)
464   (let ((buffer (current-buffer))
465         number list size)
466     (with-temp-buffer
467       (let (number uid list)
468         (insert string)
469         (goto-char (point-min))
470         (while (re-search-forward "^\\([0-9]+\\)[\t ]+\\([^ \n]+\\)$" nil t)
471           (setq number  (elmo-match-buffer 1))
472           (setq uid (elmo-match-buffer 2))
473           (with-current-buffer buffer
474             (elmo-set-hash-val uid number elmo-pop3-uidl-number-hash)
475             (elmo-set-hash-val (concat "#" number) uid
476                                elmo-pop3-number-uidl-hash))
477           (setq list (cons uid list)))
478         (with-current-buffer buffer (setq elmo-pop3-uidl-done t))
479         (nreverse list)))))
480
481 (defun elmo-pop3-parse-list-response (string)
482   (let ((buffer (current-buffer))
483         (count 0)
484         alist)
485     (with-temp-buffer
486       (insert string)
487       (goto-char (point-min))
488       (while (re-search-forward "^\\([0-9]+\\)[\t ]+\\([0-9]+\\)$" nil t)
489         (setq alist
490               (cons
491                (cons (elmo-match-buffer 1)
492                      (elmo-match-buffer 2))
493                alist))
494         (setq count (1+ count)))
495       (with-current-buffer buffer
496         (setq elmo-pop3-size-hash (elmo-make-hash (* (length alist) 2)))
497         (while alist
498           (elmo-set-hash-val (concat "#" (car (car alist)))
499                              (cdr (car alist))
500                              elmo-pop3-size-hash)
501           (setq alist (cdr alist)))
502         (setq elmo-pop3-list-done t))
503       count)))
504
505 (defun elmo-pop3-list-location (folder)
506   (with-current-buffer (process-buffer
507                         (elmo-network-session-process-internal
508                          (elmo-pop3-get-session folder)))
509     (let (locations)
510       (if elmo-pop3-uidl-done
511           (progn
512             (mapatoms
513              (lambda (atom)
514                (setq locations (cons (symbol-name atom) locations)))
515              elmo-pop3-uidl-number-hash)
516             (sort locations
517                   (lambda (loc1 loc2)
518                     (< (elmo-pop3-uidl-to-number loc1)
519                        (elmo-pop3-uidl-to-number loc2)))))
520         (error "POP3: Error in UIDL")))))
521
522 (defun elmo-pop3-list-folder-by-location (folder locations)
523   (let* ((location-alist (elmo-pop3-folder-location-alist-internal folder))
524          (locations-in-db (mapcar 'cdr location-alist))
525          result new-locs new-alist deleted-locs i)
526     (setq new-locs
527           (elmo-delete-if (function
528                            (lambda (x) (member x locations-in-db)))
529                           locations))
530     (setq deleted-locs
531           (elmo-delete-if (function
532                            (lambda (x) (member x locations)))
533                           locations-in-db))
534     (setq i (or (elmo-max-of-list (mapcar 'car location-alist)) 0))
535     (mapcar
536      (function
537       (lambda (x)
538         (setq location-alist
539               (delq (rassoc x location-alist) location-alist))))
540      deleted-locs)
541     (while new-locs
542       (setq i (1+ i))
543       (setq new-alist (cons (cons i (car new-locs)) new-alist))
544       (setq new-locs (cdr new-locs)))
545     (setq result (nconc location-alist new-alist))
546     (setq result (sort result (lambda (x y) (< (car x)(car y)))))
547     (elmo-pop3-folder-set-location-alist-internal folder result)
548     (mapcar 'car result)))
549
550 (defun elmo-pop3-list-by-uidl-subr (folder &optional nonsort)
551   (let ((flist (elmo-pop3-list-folder-by-location
552                 folder
553                 (elmo-pop3-list-location folder))))
554     (if nonsort
555         (cons (elmo-max-of-list flist) (length flist))
556       (sort flist '<))))
557
558 (defun elmo-pop3-list-by-list (folder)
559   (with-current-buffer (process-buffer
560                         (elmo-network-session-process-internal
561                          (elmo-pop3-get-session folder)))
562     (let (list)
563       (if elmo-pop3-list-done
564           (progn
565             (mapatoms (lambda (atom)
566                         (setq list (cons (string-to-int
567                                           (substring (symbol-name atom) 1))
568                                          list)))
569                       elmo-pop3-size-hash)
570             (sort list '<))
571         (error "POP3: Error in list")))))
572
573 (defsubst elmo-pop3-folder-list-messages (folder)
574   (if (and (not elmo-inhibit-number-mapping)
575            (elmo-pop3-folder-use-uidl-internal folder))
576       (elmo-pop3-list-by-uidl-subr folder)
577     (elmo-pop3-list-by-list folder)))
578
579 (luna-define-method elmo-folder-list-messages-plugged
580   ((folder elmo-pop3-folder) &optional nohide)
581   (elmo-pop3-folder-list-messages folder))
582
583 (luna-define-method elmo-folder-status ((folder elmo-pop3-folder))
584   (elmo-folder-open-internal folder)
585   (elmo-folder-check folder)
586   (if (elmo-pop3-folder-use-uidl-internal folder)
587       (prog1
588           (elmo-pop3-list-by-uidl-subr folder 'nonsort)
589         (elmo-folder-close-internal folder))
590     (let* ((process
591             (elmo-network-session-process-internal
592              (elmo-pop3-get-session folder)))
593            (total 0)
594            response)
595       (with-current-buffer (process-buffer process)
596         (elmo-pop3-send-command process "STAT")
597         (setq response (elmo-pop3-read-response process))
598         ;; response: "^\+OK 2 7570$"
599         (if (not (string-match "^\+OK[ \t]*\\([0-9]*\\)" response))
600             (error "POP STAT command failed")
601           (setq total
602                 (string-to-int
603                  (substring response (match-beginning 1)(match-end 1 ))))
604           (elmo-folder-close-internal folder)
605           (cons total total))))))
606
607 (defvar elmo-pop3-header-fetch-chop-length 200)
608
609 (defsubst elmo-pop3-next-result-arrived-p ()
610   (cond
611    ((eq (following-char) ?+)
612     (if (re-search-forward "\n\\.\r?\n" nil t)
613         t
614       nil))
615    ((looking-at "-")
616     (if (search-forward "\n" nil t)
617         t
618       nil))
619    (t
620     nil)))
621
622 (defun elmo-pop3-retrieve-headers (buffer tobuffer process articles)
623   (save-excursion
624     (set-buffer buffer)
625     (erase-buffer)
626     (let ((number (length articles))
627           (count 0)
628           (received 0)
629           (last-point (point-min)))
630       ;; Send HEAD commands.
631       (while articles
632         (elmo-pop3-send-command process (format
633                                          "top %s 0" (car articles))
634                                 'no-erase)
635 ;;;     (accept-process-output process 1)
636         (setq articles (cdr articles))
637         (setq count (1+ count))
638         ;; Every 200 requests we have to read the stream in
639         ;; order to avoid deadlocks.
640         (when (or elmo-pop3-send-command-synchronously
641                   (null articles)       ;All requests have been sent.
642                   (zerop (% count elmo-pop3-header-fetch-chop-length)))
643           (unless elmo-pop3-send-command-synchronously
644             (accept-process-output process 1))
645           (discard-input)
646           (while (progn
647                    (set-buffer buffer)
648                    (goto-char last-point)
649                    ;; Count replies.
650                    (while (elmo-pop3-next-result-arrived-p)
651                      (setq last-point (point))
652                      (setq received (1+ received)))
653                    (< received count))
654             (when (> number elmo-display-progress-threshold)
655               (if (or (zerop (% received 5)) (= received number))
656                   (elmo-display-progress
657                    'elmo-pop3-retrieve-headers "Getting headers..."
658                    (/ (* received 100) number))))
659             (accept-process-output process 1)
660 ;;;         (accept-process-output process)
661             (discard-input))))
662       ;; Remove all "\r"'s.
663       (goto-char (point-min))
664       (while (search-forward "\r\n" nil t)
665         (replace-match "\n"))
666       (copy-to-buffer tobuffer (point-min) (point-max)))))
667
668 (luna-define-method elmo-folder-msgdb-create ((folder elmo-pop3-folder)
669                                               numlist seen-list)
670   (let ((process (elmo-network-session-process-internal
671                   (elmo-pop3-get-session folder))))
672     (with-current-buffer (process-buffer process)
673       (elmo-pop3-sort-msgdb-by-original-number
674        folder
675        (elmo-pop3-msgdb-create-by-header
676         process
677         numlist
678         seen-list
679         (if (elmo-pop3-folder-use-uidl-internal folder)
680             (elmo-pop3-folder-location-alist-internal folder)))))))
681
682 (defun elmo-pop3-sort-overview-by-original-number (overview loc-alist)
683   (if loc-alist
684       (sort overview
685             (lambda (ent1 ent2)
686               (< (elmo-pop3-uidl-to-number
687                   (cdr (assq (elmo-msgdb-overview-entity-get-number ent1)
688                              loc-alist)))
689                  (elmo-pop3-uidl-to-number
690                   (cdr (assq (elmo-msgdb-overview-entity-get-number ent2)
691                              loc-alist))))))
692     overview))
693
694 (defun elmo-pop3-sort-msgdb-by-original-number (folder msgdb)
695   (message "Sorting...")
696   (let ((overview (elmo-msgdb-get-overview msgdb)))
697     (setq overview (elmo-pop3-sort-overview-by-original-number
698                     overview
699                     (elmo-pop3-folder-location-alist-internal folder)))
700     (message "Sorting...done")
701     (list overview (nth 1 msgdb)(nth 2 msgdb)(nth 3 msgdb))))
702
703 (defun elmo-pop3-uidl-to-number (uidl)
704   (string-to-number (elmo-get-hash-val uidl
705                                        elmo-pop3-uidl-number-hash)))
706
707 (defun elmo-pop3-number-to-uidl (number)
708   (elmo-get-hash-val (format "#%d" number)
709                      elmo-pop3-number-uidl-hash))
710
711 (defun elmo-pop3-number-to-size (number)
712   (elmo-get-hash-val (format "#%d" number)
713                      elmo-pop3-size-hash))
714
715 (defun elmo-pop3-msgdb-create-by-header (process numlist
716                                                  seen-list
717                                                  loc-alist)
718   (let ((tmp-buffer (get-buffer-create " *ELMO Overview TMP*")))
719     (with-current-buffer (process-buffer process)
720       (if loc-alist ; use uidl.
721           (setq numlist
722                 (delq
723                  nil
724                  (mapcar
725                   (lambda (number)
726                     (elmo-pop3-uidl-to-number (cdr (assq number loc-alist))))
727                   numlist))))
728       (elmo-pop3-retrieve-headers (process-buffer process)
729                                   tmp-buffer process numlist)
730       (prog1
731           (elmo-pop3-msgdb-create-message
732            tmp-buffer
733            process
734            (length numlist)
735            numlist
736            seen-list loc-alist)
737         (kill-buffer tmp-buffer)))))
738
739 (defun elmo-pop3-msgdb-create-message (buffer
740                                        process
741                                        num
742                                        numlist
743                                        seen-list
744                                        loc-alist)
745   (save-excursion
746     (let (beg overview number-alist mark-alist
747               entity i number message-id gmark seen size)
748       (set-buffer buffer)
749       (elmo-set-buffer-multibyte default-enable-multibyte-characters)
750       (goto-char (point-min))
751       (setq i 0)
752       (message "Creating msgdb...")
753       (while (not (eobp))
754         (setq beg (save-excursion (forward-line 1) (point)))
755         (elmo-pop3-next-result-arrived-p)
756         (save-excursion
757           (forward-line -1)
758           (save-restriction
759             (narrow-to-region beg (point))
760             (setq entity
761                   (elmo-msgdb-create-overview-from-buffer
762                    (car numlist)))
763             (setq numlist (cdr numlist))
764             (when entity
765               (setq overview
766                     (elmo-msgdb-append-element
767                      overview entity))
768               (with-current-buffer (process-buffer process)
769                 (elmo-msgdb-overview-entity-set-size
770                  entity
771                  (string-to-number
772                   (elmo-pop3-number-to-size
773                    (elmo-msgdb-overview-entity-get-number entity))))
774                 (if (setq number
775                           (car
776                            (rassoc
777                             (elmo-pop3-number-to-uidl
778                              (elmo-msgdb-overview-entity-get-number entity))
779                             loc-alist)))
780                     (elmo-msgdb-overview-entity-set-number entity number)))
781               (setq number-alist
782                     (elmo-msgdb-number-add
783                      number-alist
784                      (elmo-msgdb-overview-entity-get-number entity)
785                      (car entity)))
786               (setq message-id (car entity))
787               (setq seen (member message-id seen-list))
788               (if (setq gmark (or (elmo-msgdb-global-mark-get message-id)
789                                   (if (elmo-file-cache-status
790                                        (elmo-file-cache-get message-id))
791                                       (if seen
792                                           nil
793                                         elmo-msgdb-unread-cached-mark)
794                                     (if seen
795                                         (if elmo-pop3-use-cache
796                                             elmo-msgdb-read-uncached-mark)
797                                       elmo-msgdb-new-mark))))
798                   (setq mark-alist
799                         (elmo-msgdb-mark-append
800                          mark-alist
801                          (elmo-msgdb-overview-entity-get-number entity)
802                          gmark))))))
803         (when (> num elmo-display-progress-threshold)
804           (setq i (1+ i))
805           (if (or (zerop (% i 5)) (= i num))
806               (elmo-display-progress
807                'elmo-pop3-msgdb-create-message "Creating msgdb..."
808                (/ (* i 100) num)))))
809       (list overview number-alist mark-alist))))
810
811 (defun elmo-pop3-read-body (process outbuf)
812   (with-current-buffer (process-buffer process)
813     (let ((start elmo-pop3-read-point)
814           end)
815       (goto-char start)
816       (while (not (re-search-forward "^\\.\r?\n" nil t))
817         (accept-process-output process 1)
818         (goto-char start))
819       (setq end (point))
820       (with-current-buffer outbuf
821         (erase-buffer)
822         (insert-buffer-substring (process-buffer process) start (- end 3)))
823       t)))
824
825 (luna-define-method elmo-folder-open-internal ((folder elmo-pop3-folder))
826   (if (and (not elmo-inhibit-number-mapping)
827            (elmo-pop3-folder-use-uidl-internal folder))
828       (elmo-pop3-folder-set-location-alist-internal
829        folder (elmo-msgdb-location-load (elmo-folder-msgdb-path folder)))))
830
831 (luna-define-method elmo-folder-commit :after ((folder elmo-pop3-folder))
832   (when (elmo-folder-persistent-p folder)
833     (elmo-msgdb-location-save (elmo-folder-msgdb-path folder)
834                               (elmo-pop3-folder-location-alist-internal
835                                folder))))
836
837 (luna-define-method elmo-folder-close-internal ((folder elmo-pop3-folder))
838   (elmo-pop3-folder-set-location-alist-internal folder nil)
839   ;; Just close connection
840   (elmo-folder-check folder))
841
842 (luna-define-method elmo-message-fetch-plugged ((folder elmo-pop3-folder)
843                                                 number strategy
844                                                 &optional section
845                                                 outbuf unseen)
846   (let* ((loc-alist (elmo-pop3-folder-location-alist-internal folder))
847          (process (elmo-network-session-process-internal
848                    (elmo-pop3-get-session folder)))
849         size  response errmsg msg)
850     (with-current-buffer (process-buffer process)
851       (if loc-alist
852           (setq number (elmo-pop3-uidl-to-number
853                         (cdr (assq number loc-alist)))))
854       (setq size (string-to-number
855                   (elmo-pop3-number-to-size number)))
856       (when number
857         (elmo-pop3-send-command process
858                                 (format "retr %s" number))
859         (unless elmo-inhibit-display-retrieval-progress
860           (setq elmo-pop3-total-size size)
861           (elmo-display-progress
862            'elmo-display-retrieval-progress
863            (format "Retrieving (0/%d bytes)..." elmo-pop3-total-size)
864            0))
865         (unwind-protect
866             (progn
867               (when (null (setq response (elmo-pop3-read-response
868                                           process t)))
869                 (error "Fetching message failed"))
870               (setq response  (elmo-pop3-read-body process outbuf)))
871           (setq elmo-pop3-total-size nil))
872         (unless elmo-inhibit-display-retrieval-progress
873           (elmo-display-progress
874            'elmo-display-retrieval-progress
875            "Retrieving..." 100)  ; remove progress bar.
876           (message "Retrieving...done."))
877         (set-buffer outbuf)
878         (goto-char (point-min))
879         (while (re-search-forward "^\\." nil t)
880           (replace-match "")
881           (forward-line))
882         response))))
883
884 (defun elmo-pop3-delete-msg (process number loc-alist)
885   (with-current-buffer (process-buffer process)
886     (let (response errmsg msg)
887       (if loc-alist
888           (setq number (elmo-pop3-uidl-to-number
889                         (cdr (assq number loc-alist)))))
890       (if number
891           (progn
892             (elmo-pop3-send-command process
893                                     (format "dele %s" number))
894             (when (null (setq response (elmo-pop3-read-response
895                                         process t)))
896               (error "Deleting message failed")))
897         (error "Deleting message failed")))))
898
899 (luna-define-method elmo-folder-delete-messages-plugged
900   ((folder elmo-pop3-folder) msgs)
901   (let ((loc-alist (elmo-pop3-folder-location-alist-internal folder))
902         (process (elmo-network-session-process-internal
903                   (elmo-pop3-get-session folder))))
904     (mapcar '(lambda (msg) (elmo-pop3-delete-msg
905                             process msg loc-alist))
906             msgs)))
907
908 (luna-define-method elmo-message-use-cache-p ((folder elmo-pop3-folder) number)
909   elmo-pop3-use-cache)
910
911 (luna-define-method elmo-folder-persistent-p ((folder elmo-pop3-folder))
912   (and (elmo-folder-persistent-internal folder)
913        (elmo-pop3-folder-use-uidl-internal folder)))
914
915 (luna-define-method elmo-folder-clear :around ((folder elmo-pop3-folder)
916                                                &optional keep-killed)
917   (unless keep-killed
918     (elmo-pop3-folder-set-location-alist-internal folder nil))
919   (luna-call-next-method))
920
921 (luna-define-method elmo-folder-check ((folder elmo-pop3-folder))
922   (if (elmo-folder-plugged-p folder)
923       (let ((session (elmo-pop3-get-session folder 'if-exists)))
924         (when session
925           (elmo-network-close-session session)))))
926
927 (require 'product)
928 (product-provide (provide 'elmo-pop3) (require 'elmo-version))
929
930 ;;; elmo-pop3.el ends here