Implement group deletion.
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40
41 (nnoo-declare nnimap)
42
43 (defvoo nnimap-address nil
44   "The address of the IMAP server.")
45
46 (defvoo nnimap-server-port nil
47   "The IMAP port used.
48 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
49 it will default to `imap'.")
50
51 (defvoo nnimap-stream 'ssl
52   "How nnimap will talk to the IMAP server.
53 Values are `ssl' and `network'.")
54
55 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
56                                  (if (listp imap-shell-program)
57                                      (car imap-shell-program)
58                                    imap-shell-program)
59                                "ssh %s imapd"))
60
61 (defvoo nnimap-inbox nil
62   "The mail box where incoming mail arrives and should be split out of.")
63
64 (defvoo nnimap-expunge-inbox nil
65   "If non-nil, expunge the inbox after fetching mail.
66 This is always done if the server supports UID EXPUNGE, but it's
67 not done by default on servers that doesn't support that command.")
68
69 (defvoo nnimap-authenticator nil
70   "How nnimap authenticate itself to the server.
71 Possible choices are nil (use default methods) or `anonymous'.")
72
73 (defvoo nnimap-fetch-partial-articles nil
74   "If non-nil, nnimap will fetch partial articles.
75 If t, nnimap will fetch only the first part.  If a string, it
76 will fetch all parts that have types that match that string.  A
77 likely value would be \"text/\" to automatically fetch all
78 textual parts.")
79
80 (defvoo nnimap-connection-alist nil)
81
82 (defvoo nnimap-current-infos nil)
83
84 (defvar nnimap-process nil)
85
86 (defvar nnimap-status-string "")
87
88 (defvar nnimap-split-download-body-default nil
89   "Internal variable with default value for `nnimap-split-download-body'.")
90
91 (defstruct nnimap
92   group process commands capabilities select-result newlinep)
93
94 (defvar nnimap-object nil)
95
96 (defvar nnimap-mark-alist
97   '((read "\\Seen")
98     (tick "\\Flagged")
99     (reply "\\Answered")
100     (expire "gnus-expire")
101     (dormant "gnus-dormant")
102     (score "gnus-score")
103     (save "gnus-save")
104     (download "gnus-download")
105     (forward "gnus-forward")))
106
107 (defvar nnimap-split-methods nil)
108
109 (defun nnimap-buffer ()
110   (nnimap-find-process-buffer nntp-server-buffer))
111
112 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
113   (with-current-buffer nntp-server-buffer
114     (erase-buffer)
115     (when (nnimap-possibly-change-group group server)
116       (with-current-buffer (nnimap-buffer)
117         (nnimap-send-command "SELECT %S" (utf7-encode group t))
118         (erase-buffer)
119         (nnimap-wait-for-response
120          (nnimap-send-command
121           "UID FETCH %s %s"
122           (nnimap-article-ranges (gnus-compress-sequence articles))
123           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
124                   (format
125                    (if (member "IMAP4REV1"
126                                (nnimap-capabilities nnimap-object))
127                        "BODY.PEEK[HEADER.FIELDS %s]"
128                      "RFC822.HEADER.LINES %s")
129                    (append '(Subject From Date Message-Id
130                                      References In-Reply-To Xref)
131                            nnmail-extra-headers))))
132          t)
133         (nnimap-transform-headers))
134       (insert-buffer-substring
135        (nnimap-find-process-buffer (current-buffer))))
136     t))
137
138 (defun nnimap-transform-headers ()
139   (goto-char (point-min))
140   (let (article bytes lines)
141     (block nil
142       (while (not (eobp))
143         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
144           (delete-region (point) (progn (forward-line 1) (point)))
145           (when (eobp)
146             (return)))
147         (setq article (match-string 1)
148               bytes (nnimap-get-length)
149               lines nil)
150         (beginning-of-line)
151         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
152           (let ((structure (ignore-errors (read (current-buffer)))))
153             (while (and (consp structure)
154                         (not (stringp (car structure))))
155               (setq structure (car structure)))
156             (setq lines (nth 7 structure))))
157         (delete-region (line-beginning-position) (line-end-position))
158         (insert (format "211 %s Article retrieved." article))
159         (forward-line 1)
160         (insert (format "Chars: %d\n" bytes))
161         (when lines
162           (insert (format "Lines: %s\n" lines)))
163         (re-search-forward "^\r$")
164         (delete-region (line-beginning-position) (line-end-position))
165         (insert ".")
166         (forward-line 1)))))
167
168 (defun nnimap-get-length ()
169   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
170        (string-to-number (match-string 1))))
171
172 (defun nnimap-article-ranges (ranges)
173   (let (result)
174     (cond
175      ((numberp ranges)
176       (number-to-string ranges))
177      ((numberp (cdr ranges))
178       (format "%d:%d" (car ranges) (cdr ranges)))
179      (t
180       (dolist (elem ranges)
181         (push
182          (if (consp elem)
183              (format "%d:%d" (car elem) (cdr elem))
184            (number-to-string elem))
185          result))
186       (mapconcat #'identity (nreverse result) ",")))))
187
188 (deffoo nnimap-open-server (server &optional defs)
189   (if (nnimap-server-opened server)
190       t
191     (unless (assq 'nnimap-address defs)
192       (setq defs (append defs (list (list 'nnimap-address server)))))
193     (nnoo-change-server 'nnimap server defs)
194     (or (nnimap-find-connection nntp-server-buffer)
195         (nnimap-open-connection nntp-server-buffer))))
196
197 (defun nnimap-make-process-buffer (buffer)
198   (with-current-buffer
199       (generate-new-buffer (format "*nnimap %s %s %s*"
200                                    nnimap-address nnimap-server-port
201                                    (gnus-buffer-exists-p buffer)))
202     (mm-disable-multibyte)
203     (buffer-disable-undo)
204     (gnus-add-buffer)
205     (set (make-local-variable 'after-change-functions) nil)
206     (set (make-local-variable 'nnimap-object) (make-nnimap))
207     (push (list buffer (current-buffer)) nnimap-connection-alist)
208     (current-buffer)))
209
210 (defun nnimap-open-shell-stream (name buffer host port)
211   (let ((process-connection-type nil))
212     (start-process name buffer shell-file-name
213                    shell-command-switch
214                    (format-spec
215                     nnimap-shell-program
216                     (format-spec-make
217                      ?s host
218                      ?p port)))))
219
220 (defun nnimap-credentials (address ports)
221   (let (port credentials)
222     ;; Request the credentials from all ports, but only query on the
223     ;; last port if all the previous ones have failed.
224     (while (and (null credentials)
225                 (setq port (pop ports)))
226       (setq credentials
227             (auth-source-user-or-password
228              '("login" "password") address port nil (null ports))))
229     credentials))
230
231 (defun nnimap-open-connection (buffer)
232   (with-current-buffer (nnimap-make-process-buffer buffer)
233     (let* ((coding-system-for-read 'binary)
234            (coding-system-for-write 'binary)
235            (ports
236             (cond
237              ((eq nnimap-stream 'network)
238               (open-network-stream
239                "*nnimap*" (current-buffer) nnimap-address
240                (or nnimap-server-port
241                    (if (netrc-find-service-number "imap")
242                        "imap"
243                      "143")))
244               '("143" "imap"))
245              ((eq nnimap-stream 'shell)
246               (nnimap-open-shell-stream
247                "*nnimap*" (current-buffer) nnimap-address
248                (or nnimap-server-port "imap"))
249               '("imap"))
250              ((eq nnimap-stream 'ssl)
251               (open-tls-stream
252                "*nnimap*" (current-buffer) nnimap-address
253                (or nnimap-server-port
254                    (if (netrc-find-service-number "imaps")
255                        "imaps"
256                      "993")))
257               '("143" "993" "imap" "imaps"))))
258            connection-result login-result credentials)
259       (setf (nnimap-process nnimap-object)
260             (get-buffer-process (current-buffer)))
261       (when (and (nnimap-process nnimap-object)
262                  (memq (process-status (nnimap-process nnimap-object))
263                        '(open run)))
264         (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
265         (when (setq connection-result (nnimap-wait-for-connection))
266           (unless (equal connection-result "PREAUTH")
267             (if (not (setq credentials
268                            (if (eq nnimap-authenticator 'anonymous)
269                                (list "anonymous"
270                                      (message-make-address))
271                              (nnimap-credentials
272                               nnimap-address
273                               (if nnimap-server-port
274                                   (cons (format "%s" nnimap-server-port) ports)
275                                 ports)))))
276                 (setq nnimap-object nil)
277               (setq login-result (nnimap-command "LOGIN %S %S"
278                                                  (car credentials)
279                                                  (cadr credentials)))
280               (unless (car login-result)
281                 (delete-process (nnimap-process nnimap-object))
282                 (setq nnimap-object nil))))
283           (when nnimap-object
284             (setf (nnimap-capabilities nnimap-object)
285                   (mapcar
286                    #'upcase
287                    (or (nnimap-find-parameter "CAPABILITY" (cdr login-result))
288                        (nnimap-find-parameter
289                         "CAPABILITY" (cdr (nnimap-command "CAPABILITY"))))))
290             (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
291               (nnimap-command "ENABLE QRESYNC"))
292             t))))))
293
294 (defun nnimap-find-parameter (parameter elems)
295   (let (result)
296     (dolist (elem elems)
297       (cond
298        ((equal (car elem) parameter)
299         (setq result (cdr elem)))
300        ((and (equal (car elem) "OK")
301              (consp (cadr elem))
302              (equal (caadr elem) parameter))
303         (setq result (cdr (cadr elem))))))
304     result))
305
306 (deffoo nnimap-close-server (&optional server)
307   t)
308
309 (deffoo nnimap-request-close ()
310   t)
311
312 (deffoo nnimap-server-opened (&optional server)
313   (and (nnoo-current-server-p 'nnimap server)
314        nntp-server-buffer
315        (gnus-buffer-live-p nntp-server-buffer)
316        (nnimap-find-connection nntp-server-buffer)))
317
318 (deffoo nnimap-status-message (&optional server)
319   nnimap-status-string)
320
321 (deffoo nnimap-request-article (article &optional group server to-buffer)
322   (with-current-buffer nntp-server-buffer
323     (let ((result (nnimap-possibly-change-group group server))
324           parts)
325       (when (stringp article)
326         (setq article (nnimap-find-article-by-message-id group article)))
327       (when (and result
328                  article)
329         (erase-buffer)
330         (with-current-buffer (nnimap-buffer)
331           (erase-buffer)
332           (when nnimap-fetch-partial-articles
333             (if (eq nnimap-fetch-partial-articles t)
334                 (setq parts '(1))
335               (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
336               (goto-char (point-min))
337               (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
338                 (let ((structure (ignore-errors (read (current-buffer)))))
339                   (setq parts (nnimap-find-wanted-parts structure))))))
340           (setq result
341                 (nnimap-command
342                  (if (member "IMAP4REV1" (nnimap-capabilities nnimap-object))
343                      "UID FETCH %d BODY.PEEK[]"
344                    "UID FETCH %d RFC822.PEEK")
345                  article))
346           ;; Check that we really got an article.
347           (goto-char (point-min))
348           (unless (looking-at "\\* [0-9]+ FETCH")
349             (setq result nil)))
350         (let ((buffer (nnimap-find-process-buffer (current-buffer))))
351           (when (car result)
352             (with-current-buffer (or to-buffer nntp-server-buffer)
353               (insert-buffer-substring buffer)
354               (goto-char (point-min))
355               (let ((bytes (nnimap-get-length)))
356                 (delete-region (line-beginning-position)
357                                (progn (forward-line 1) (point)))
358                 (goto-char (+ (point) bytes))
359                 (delete-region (point) (point-max))
360                 (nnheader-ms-strip-cr))
361               (cons group article))))))))
362
363 (defun nnimap-find-wanted-parts (structure)
364   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
365
366 (defun nnimap-find-wanted-parts-1 (structure prefix)
367   (let ((num 1)
368         parts)
369     (while (consp (car structure))
370       (let ((sub (pop structure)))
371         (if (consp (car sub))
372             (push (nnimap-find-wanted-parts-1
373                    sub (if (string= prefix "")
374                            (number-to-string num)
375                          (format "%s.%s" prefix num)))
376                   parts)
377           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub))))
378             (when (string-match nnimap-fetch-partial-articles type)
379               (push (if (string= prefix "")
380                         (number-to-string num)
381                       (format "%s.%s" prefix num))
382                     parts)))
383           (incf num))))
384     (nreverse parts)))
385
386 (deffoo nnimap-request-group (group &optional server dont-check info)
387   (let ((result (nnimap-possibly-change-group group server))
388         articles active marks high low)
389     (with-current-buffer nntp-server-buffer
390       (when result
391         (if (and dont-check
392                  (setq active (nth 2 (assoc group nnimap-current-infos))))
393             (insert (format "211 %d %d %d %S\n"
394                             (- (cdr active) (car active))
395                             (car active)
396                             (cdr active)
397                             group))
398           (with-current-buffer (nnimap-buffer)
399             (erase-buffer)
400             (let ((group-sequence
401                    (nnimap-send-command "SELECT %S" (utf7-encode group)))
402                   (flag-sequence
403                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
404               (nnimap-wait-for-response flag-sequence)
405               (setq marks
406                     (nnimap-flags-to-marks
407                      (nnimap-parse-flags
408                       (list (list group-sequence flag-sequence 1 group)))))
409               (when info
410                 (nnimap-update-infos marks (list info)))
411               (goto-char (point-max))
412               (cond
413                (marks
414                 (setq high (nth 3 (car marks))
415                       low (nth 4 (car marks))))
416                ((re-search-backward "UIDNEXT \\([0-9]+\\)" nil t)
417                 (setq high (string-to-number (match-string 1))
418                       low 1)))))
419           (erase-buffer)
420           (insert
421            (format
422             "211 %d %d %d %S\n"
423             (1+ (- high low))
424             low high group))))
425       t)))
426
427 (deffoo nnimap-request-delete-group (group &optional force server)
428   (when (nnimap-possibly-change-group nil server)
429     (with-current-buffer (nnimap-buffer)
430       (car (nnimap-command "DELETE %S" (utf7-encode group))))))
431
432 (defun nnimap-get-flags (spec)
433   (let ((articles nil)
434         elems)
435     (with-current-buffer (nnimap-buffer)
436       (erase-buffer)
437       (nnimap-wait-for-response (nnimap-send-command
438                                  "UID FETCH %s FLAGS" spec))
439       (goto-char (point-min))
440       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
441         (setq elems (nnimap-parse-line (match-string 1)))
442         (push (cons (string-to-number (cadr (member "UID" elems)))
443                     (cadr (member "FLAGS" elems)))
444               articles)))
445     (nreverse articles)))
446
447 (deffoo nnimap-close-group (group &optional server)
448   t)
449
450 (deffoo nnimap-request-move-article (article group server accept-form
451                                              &optional last internal-move-group)
452   (when (nnimap-possibly-change-group group server)
453     ;; If the move is internal (on the same server), just do it the easy
454     ;; way.
455     (let ((message-id (message-field-value "message-id")))
456       (if internal-move-group
457           (let ((result
458                  (with-current-buffer (nnimap-buffer)
459                    (nnimap-command "UID COPY %d %S"
460                                    article
461                                    (utf7-encode internal-move-group t)))))
462             (when (car result)
463               (nnimap-delete-article article)
464               (cons internal-move-group
465                     (nnimap-find-article-by-message-id
466                      internal-move-group message-id))))
467         (with-temp-buffer
468           (let ((result (eval accept-form)))
469             (when result
470               (nnimap-delete-article article)
471               result)))))))
472
473 (deffoo nnimap-request-expire-articles (articles group &optional server force)
474   (cond
475    ((not (nnimap-possibly-change-group group server))
476     articles)
477    (force
478     (unless (nnimap-delete-article articles)
479       (message "Article marked for deletion, but not expunged."))
480     nil)
481    (t
482     articles)))
483
484 (defun nnimap-find-article-by-message-id (group message-id)
485   (when (nnimap-possibly-change-group group nil)
486     (with-current-buffer (nnimap-buffer)
487       (let ((result
488              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
489             article)
490         (when (car result)
491           ;; Select the last instance of the message in the group.
492           (and (setq article
493                      (car (last (assoc "SEARCH" (cdr result)))))
494                (string-to-number article)))))))
495
496 (defun nnimap-delete-article (articles)
497   (with-current-buffer (nnimap-buffer)
498     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
499                     (nnimap-article-ranges articles))
500     (when (member "UIDPLUS" (nnimap-capabilities nnimap-object))
501       (nnimap-send-command "UID EXPUNGE %s"
502                            (nnimap-article-ranges articles))
503       t)))
504
505 (deffoo nnimap-request-scan (&optional group server)
506   (when (and (nnimap-possibly-change-group nil server)
507              (equal group nnimap-inbox)
508              nnimap-inbox
509              nnimap-split-methods)
510     (nnimap-split-incoming-mail)))
511
512 (defun nnimap-marks-to-flags (marks)
513   (let (flags flag)
514     (dolist (mark marks)
515       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
516         (push flag flags)))
517     flags))
518
519 (deffoo nnimap-request-set-mark (group actions &optional server)
520   (when (nnimap-possibly-change-group group server)
521     (let (sequence)
522       (with-current-buffer (nnimap-buffer)
523         ;; Just send all the STORE commands without waiting for
524         ;; response.  If they're successful, they're successful.
525         (dolist (action actions)
526           (destructuring-bind (range action marks) action
527             (let ((flags (nnimap-marks-to-flags marks)))
528               (when flags
529                 (setq sequence (nnimap-send-command
530                                 "UID STORE %s %sFLAGS.SILENT (%s)"
531                                 (nnimap-article-ranges range)
532                                 (if (eq action 'del)
533                                     "-"
534                                   "+")
535                                 (mapconcat #'identity flags " ")))))))
536         ;; Wait for the last command to complete to avoid later
537         ;; syncronisation problems with the stream.
538         (when sequence
539           (nnimap-wait-for-response sequence))))))
540
541 (deffoo nnimap-request-accept-article (group &optional server last)
542   (when (nnimap-possibly-change-group nil server)
543     (nnmail-check-syntax)
544     (let ((message (buffer-string))
545           (message-id (message-field-value "message-id"))
546           sequence)
547       (with-current-buffer (nnimap-buffer)
548         (setq sequence (nnimap-send-command
549                         "APPEND %S {%d}" (utf7-encode group t)
550                         (length message)))
551         (process-send-string (get-buffer-process (current-buffer)) message)
552         (process-send-string (get-buffer-process (current-buffer))
553                              (if (nnimap-newlinep nnimap-object)
554                                  "\n"
555                                "\r\n"))
556         (let ((result (nnimap-get-response sequence)))
557           (when result
558             (cons group
559                   (nnimap-find-article-by-message-id group message-id))))))))
560
561 (defun nnimap-add-cr ()
562   (goto-char (point-min))
563   (while (re-search-forward "\r?\n" nil t)
564     (replace-match "\r\n" t t)))
565
566 (defun nnimap-get-groups ()
567   (let ((result (nnimap-command "LIST \"\" \"*\""))
568         groups)
569     (when (car result)
570       (dolist (line (cdr result))
571         (when (and (equal (car line) "LIST")
572                    (not (and (caadr line)
573                              (string-match "noselect" (caadr line)))))
574           (push (car (last line)) groups)))
575       (nreverse groups))))
576
577 (deffoo nnimap-request-list (&optional server)
578   (nnimap-possibly-change-group nil server)
579   (with-current-buffer nntp-server-buffer
580     (erase-buffer)
581     (let ((groups
582            (with-current-buffer (nnimap-buffer)
583              (nnimap-get-groups)))
584           sequences responses)
585       (when groups
586         (with-current-buffer (nnimap-buffer)
587           (dolist (group groups)
588             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
589                         group)
590                   sequences))
591           (nnimap-wait-for-response (caar sequences))
592           (setq responses
593                 (nnimap-get-responses (mapcar #'car sequences))))
594         (dolist (response responses)
595           (let* ((sequence (car response))
596                  (response (cadr response))
597                  (group (cadr (assoc sequence sequences))))
598             (when (and group
599                        (equal (caar response) "OK"))
600               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
601                     highest exists)
602                 (dolist (elem response)
603                   (when (equal (cadr elem) "EXISTS")
604                     (setq exists (string-to-number (car elem)))))
605                 (when uidnext
606                   (setq highest (1- (string-to-number (car uidnext)))))
607                 (cond
608                  ((null highest)
609                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
610                  ((zerop exists)
611                   ;; Empty group.
612                   (insert (format "%S %d %d y\n"
613                                   (utf7-decode group t) highest (1+ highest))))
614                  (t
615                   ;; Return the widest possible range.
616                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
617                                   (or highest exists)))))))))
618         t))))
619
620 (deffoo nnimap-retrieve-group-data-early (server infos)
621   (when (nnimap-possibly-change-group nil server)
622     (with-current-buffer (nnimap-buffer)
623       ;; QRESYNC handling isn't implemented.
624       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
625             marks groups sequences)
626         ;; Go through the infos and gather the data needed to know
627         ;; what and how to request the data.
628         (dolist (info infos)
629           (setq marks (gnus-info-marks info))
630           (push (list (gnus-group-real-name (gnus-info-group info))
631                       (cdr (assq 'active marks))
632                       (cdr (assq 'uid marks)))
633                 groups))
634         ;; Then request the data.
635         (erase-buffer)
636         (dolist (elem groups)
637           (if (and qresyncp
638                    (nth 2 elem))
639               (push
640                (list 'qresync
641                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
642                                           (car elem)
643                                           (car (nth 2 elem))
644                                           (cdr (nth 2 elem)))
645                      nil
646                      (car elem))
647                sequences)
648             (let ((start
649                    (if (nth 1 elem)
650                        ;; Fetch the last 100 flags.
651                        (max 1 (- (cdr (nth 1 elem)) 100))
652                      1)))
653               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
654                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
655                           start
656                           (car elem))
657                     sequences))))
658         sequences))))
659
660 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
661   (when (and sequences
662              (nnimap-possibly-change-group nil server))
663     (with-current-buffer (nnimap-buffer)
664       ;; Wait for the final data to trickle in.
665       (nnimap-wait-for-response (cadar sequences))
666       ;; Now we should have all the data we need, no matter whether
667       ;; we're QRESYNCING, fetching all the flags from scratch, or
668       ;; just fetching the last 100 flags per group.
669       (nnimap-update-infos (nnimap-flags-to-marks
670                             (nnimap-parse-flags
671                              (nreverse sequences)))
672                            infos)
673       ;; Finally, just return something resembling an active file in
674       ;; the nntp buffer, so that the agent can save the info, too.
675       (with-current-buffer nntp-server-buffer
676         (erase-buffer)
677         (dolist (info infos)
678           (let* ((group (gnus-info-group info))
679                  (active (gnus-active group)))
680             (when active
681               (insert (format "%S %d %d y\n"
682                               (gnus-group-real-name group)
683                               (cdr active)
684                               (car active))))))))))
685
686 (defun nnimap-update-infos (flags infos)
687   (dolist (info infos)
688     (let ((group (gnus-group-real-name (gnus-info-group info))))
689       (nnimap-update-info info (cdr (assoc group flags))))))
690
691 (defun nnimap-update-info (info marks)
692   (when marks
693     (destructuring-bind (existing flags high low uidnext start-article) marks
694       (let ((group (gnus-info-group info))
695             (completep (and start-article
696                             (= start-article 1))))
697         ;; First set the active ranges based on high/low.
698         (if (or completep
699                 (not (gnus-active group)))
700             (gnus-set-active group
701                              (if high
702                                  (cons low high)
703                                ;; No articles in this group.
704                                (cons (1- uidnext) uidnext)))
705           (setcdr (gnus-active group) high))
706         ;; Then update the list of read articles.
707         (let* ((unread
708                 (gnus-compress-sequence
709                  (gnus-set-difference
710                   (gnus-set-difference
711                    existing
712                    (cdr (assoc "\\Seen" flags)))
713                   (cdr (assoc "\\Flagged" flags)))))
714                (read (gnus-range-difference
715                       (cons start-article high) unread)))
716           (when (> start-article 1)
717             (setq read
718                   (gnus-range-nconcat
719                    (if (> start-article 1)
720                        (gnus-sorted-range-intersection
721                         (cons 1 (1- start-article))
722                         (gnus-info-read info))
723                      (gnus-info-read info))
724                    read)))
725           (gnus-info-set-read info read)
726           ;; Update the marks.
727           (setq marks (gnus-info-marks info))
728           ;; Note the active level for the next run-through.
729           (let ((active (assq 'active marks)))
730             (if active
731                 (setcdr active (gnus-active group))
732               (push (cons 'active (gnus-active group)) marks)))
733           (dolist (type (cdr nnimap-mark-alist))
734             (let ((old-marks (assoc (car type) marks))
735                   (new-marks (gnus-compress-sequence
736                               (cdr (assoc (cadr type) flags)))))
737               (setq marks (delq old-marks marks))
738               (pop old-marks)
739               (when (and old-marks
740                          (> start-article 1))
741                 (setq old-marks (gnus-range-difference
742                                  old-marks
743                                  (cons start-article high)))
744                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
745               (when new-marks
746                 (push (cons (car type) new-marks) marks)))
747             (gnus-info-set-marks info marks t)
748             (nnimap-store-info info (gnus-active group))))))))
749
750 (defun nnimap-store-info (info active)
751   (let* ((group (gnus-group-real-name (gnus-info-group info)))
752          (entry (assoc group nnimap-current-infos)))
753     (if entry
754         (setcdr entry (list info active))
755       (push (list group info active) nnimap-current-infos))))
756
757 (defun nnimap-flags-to-marks (groups)
758   (let (data group totalp uidnext articles start-article mark)
759     (dolist (elem groups)
760       (setq group (car elem)
761             uidnext (cadr elem)
762             start-article (caddr elem)
763             articles (cdddr elem))
764       (let ((high (caar articles))
765             marks low existing)
766         (dolist (article articles)
767           (setq low (car article))
768           (push (car article) existing)
769           (dolist (flag (cdr article))
770             (setq mark (assoc flag marks))
771             (if (not mark)
772                 (push (list flag (car article)) marks)
773               (setcdr mark (cons (car article) (cdr mark)))))
774           (push (list group existing marks high low uidnext start-article)
775                 data))))
776     data))
777
778 (defun nnimap-parse-flags (sequences)
779   (goto-char (point-min))
780   (let (start end articles groups uidnext elems)
781     (dolist (elem sequences)
782       (destructuring-bind (group-sequence flag-sequence totalp group) elem
783         ;; The EXAMINE was successful.
784         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
785                    (progn
786                      (forward-line 1)
787                      (setq start (point))
788                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
789                                                (or end (point-min)) t)
790                          (setq uidnext (string-to-number (match-string 1)))
791                        (setq uidnext nil))
792                      (goto-char start))
793                    ;; The UID FETCH FLAGS was successful.
794                    (search-forward (format "\n%d OK " flag-sequence) nil t))
795           (setq end (point))
796           (goto-char start)
797           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
798             (setq elems (nnimap-parse-line (match-string 1)))
799             (push (cons (string-to-number (cadr (member "UID" elems)))
800                         (cadr (member "FLAGS" elems)))
801                   articles))
802           (push (nconc (list group uidnext totalp) articles) groups)
803           (setq articles nil))))
804     groups))
805
806 (defun nnimap-find-process-buffer (buffer)
807   (cadr (assoc buffer nnimap-connection-alist)))
808
809 (deffoo nnimap-request-post (&optional server)
810   (setq nnimap-status-string "Read-only server")
811   nil)
812
813 (defun nnimap-possibly-change-group (group server)
814   (let ((open-result t))
815     (when (and server
816                (not (nnimap-server-opened server)))
817       (setq open-result (nnimap-open-server server)))
818     (cond
819      ((not open-result)
820       nil)
821      ((not group)
822       t)
823      (t
824       (with-current-buffer (nnimap-buffer)
825         (if (equal group (nnimap-group nnimap-object))
826             t
827           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
828             (when (car result)
829               (setf (nnimap-group nnimap-object) group
830                     (nnimap-select-result nnimap-object) result)
831               result))))))))
832
833 (defun nnimap-find-connection (buffer)
834   "Find the connection delivering to BUFFER."
835   (let ((entry (assoc buffer nnimap-connection-alist)))
836     (when entry
837       (if (and (buffer-name (cadr entry))
838                (get-buffer-process (cadr entry))
839                (memq (process-status (get-buffer-process (cadr entry)))
840                      '(open run)))
841           (get-buffer-process (cadr entry))
842         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
843         nil))))
844
845 (defvar nnimap-sequence 0)
846
847 (defun nnimap-send-command (&rest args)
848   (process-send-string
849    (get-buffer-process (current-buffer))
850    (nnimap-log-command
851     (format "%d %s%s\n"
852             (incf nnimap-sequence)
853             (apply #'format args)
854             (if (nnimap-newlinep nnimap-object)
855                 ""
856               "\r"))))
857   nnimap-sequence)
858
859 (defun nnimap-log-command (command)
860   (with-current-buffer (get-buffer-create "*imap log*")
861     (goto-char (point-max))
862     (insert (format-time-string "%H:%M:%S") " " command))
863   command)
864
865 (defun nnimap-command (&rest args)
866   (erase-buffer)
867   (let* ((sequence (apply #'nnimap-send-command args))
868          (response (nnimap-get-response sequence)))
869     (if (equal (caar response) "OK")
870         (cons t response)
871       (nnheader-report 'nnimap "%s"
872                        (mapconcat #'identity (car response) " "))
873       nil)))
874
875 (defun nnimap-get-response (sequence)
876   (nnimap-wait-for-response sequence)
877   (nnimap-parse-response))
878
879 (defun nnimap-wait-for-connection ()
880   (let ((process (get-buffer-process (current-buffer))))
881     (goto-char (point-min))
882     (while (and (memq (process-status process)
883                       '(open run))
884                 (not (re-search-forward "^\\* .*\n" nil t)))
885       (nnheader-accept-process-output process)
886       (goto-char (point-min)))
887     (forward-line -1)
888     (and (looking-at "\\* \\([A-Z0-9]+\\)")
889          (match-string 1))))
890
891 (defun nnimap-wait-for-response (sequence &optional messagep)
892   (let ((process (get-buffer-process (current-buffer))))
893     (goto-char (point-max))
894     (while (and (memq (process-status process)
895                       '(open run))
896                 (not (re-search-backward (format "^%d .*\n" sequence)
897                                          (max (point-min) (- (point) 500))
898                                          t)))
899       (when messagep
900         (message "Read %dKB" (/ (buffer-size) 1000)))
901       (nnheader-accept-process-output process)
902       (goto-char (point-max)))))
903
904 (defun nnimap-parse-response ()
905   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
906         result)
907     (dolist (line lines)
908       (push (cdr (nnimap-parse-line line)) result))
909     ;; Return the OK/error code first, and then all the "continuation
910     ;; lines" afterwards.
911     (cons (pop result)
912           (nreverse result))))
913
914 ;; Parse an IMAP response line lightly.  They look like
915 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
916 ;; the lines into a list of strings and lists of string.
917 (defun nnimap-parse-line (line)
918   (let (char result)
919     (with-temp-buffer
920       (insert line)
921       (goto-char (point-min))
922       (while (not (eobp))
923         (if (eql (setq char (following-char)) ? )
924             (forward-char 1)
925           (push
926            (cond
927             ((eql char ?\[)
928              (split-string (buffer-substring
929                             (1+ (point)) (1- (search-forward "]")))))
930             ((eql char ?\()
931              (split-string (buffer-substring
932                             (1+ (point)) (1- (search-forward ")")))))
933             ((eql char ?\")
934              (forward-char 1)
935              (buffer-substring (point) (1- (search-forward "\""))))
936             (t
937              (buffer-substring (point) (if (search-forward " " nil t)
938                                            (1- (point))
939                                          (goto-char (point-max))))))
940            result)))
941       (nreverse result))))
942
943 (defun nnimap-last-response-string ()
944   (save-excursion
945     (forward-line 1)
946     (let ((end (point)))
947       (forward-line -1)
948       (when (not (bobp))
949         (forward-line -1)
950         (while (and (not (bobp))
951                     (eql (following-char) ?*))
952           (forward-line -1))
953         (unless (eql (following-char) ?*)
954           (forward-line 1)))
955       (buffer-substring (point) end))))
956
957 (defun nnimap-get-responses (sequences)
958   (let (responses)
959     (dolist (sequence sequences)
960       (goto-char (point-min))
961       (when (re-search-forward (format "^%d " sequence) nil t)
962         (push (list sequence (nnimap-parse-response))
963               responses)))
964     responses))
965
966 (defvar nnimap-incoming-split-list nil)
967
968 (defun nnimap-fetch-inbox (articles)
969   (erase-buffer)
970   (nnimap-wait-for-response
971    (nnimap-send-command
972     "UID FETCH %s %s"
973     (nnimap-article-ranges articles)
974     (format "(UID %s%s)"
975             (format
976              (if (member "IMAP4REV1"
977                          (nnimap-capabilities nnimap-object))
978                  "BODY.PEEK[HEADER] BODY.PEEK"
979                "RFC822.PEEK"))
980             (if nnimap-split-download-body-default
981                 "[]"
982               "[1]")))
983    t))
984
985 (defun nnimap-split-incoming-mail ()
986   (with-current-buffer (nnimap-buffer)
987     (let ((nnimap-incoming-split-list nil)
988           (nnmail-split-methods nnimap-split-methods)
989           (nnmail-inhibit-default-split-group t)
990           (groups (nnimap-get-groups))
991           new-articles)
992       (erase-buffer)
993       (nnimap-command "SELECT %S" nnimap-inbox)
994       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
995       (when new-articles
996         (nnimap-fetch-inbox new-articles)
997         (nnimap-transform-split-mail)
998         (nnheader-ms-strip-cr)
999         (nnmail-cache-open)
1000         (nnmail-split-incoming (current-buffer)
1001                                #'nnimap-save-mail-spec
1002                                nil nil
1003                                #'nnimap-dummy-active-number)
1004         (when nnimap-incoming-split-list
1005           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1006                 sequences)
1007             ;; Create any groups that doesn't already exist on the
1008             ;; server first.
1009             (dolist (spec specs)
1010               (unless (member (car spec) groups)
1011                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1012             ;; Then copy over all the messages.
1013             (erase-buffer)
1014             (dolist (spec specs)
1015               (let ((group (car spec))
1016                     (ranges (cdr spec)))
1017                 (push (list (nnimap-send-command "UID COPY %s %S"
1018                                                  (nnimap-article-ranges ranges)
1019                                                  (utf7-encode group t))
1020                             ranges)
1021                       sequences)))
1022             ;; Wait for the last COPY response...
1023             (when sequences
1024               (nnimap-wait-for-response (caar sequences))
1025               ;; And then mark the successful copy actions as deleted,
1026               ;; and possibly expunge them.
1027               (nnimap-mark-and-expunge-incoming
1028                (nnimap-parse-copied-articles sequences)))))))))
1029
1030 (defun nnimap-mark-and-expunge-incoming (range)
1031   (when range
1032     (setq range (nnimap-article-ranges range))
1033     (nnimap-send-command
1034      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
1035     (cond
1036      ;; If the server supports it, we now delete the message we have
1037      ;; just copied over.
1038      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1039       (nnimap-send-command "UID EXPUNGE %s" range))
1040      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1041      ;; user has configured it.
1042      (nnimap-expunge-inbox
1043       (nnimap-send-command "EXPUNGE")))))
1044
1045 (defun nnimap-parse-copied-articles (sequences)
1046   (let (sequence copied range)
1047     (goto-char (point-min))
1048     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1049       (setq sequence (string-to-number (match-string 1)))
1050       (when (setq range (cadr (assq sequence sequences)))
1051         (push (gnus-uncompress-range range) copied)))
1052     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1053
1054 (defun nnimap-new-articles (flags)
1055   (let (new)
1056     (dolist (elem flags)
1057       (when (or (null (cdr elem))
1058                 (and (not (member "\\Deleted" (cdr elem)))
1059                      (not (member "\\Seen" (cdr elem)))))
1060         (push (car elem) new)))
1061     (gnus-compress-sequence (nreverse new))))
1062
1063 (defun nnimap-make-split-specs (list)
1064   (let ((specs nil)
1065         entry)
1066     (dolist (elem list)
1067       (destructuring-bind (article spec) elem
1068         (dolist (group (delete nil (mapcar #'car spec)))
1069           (unless (setq entry (assoc group specs))
1070             (push (setq entry (list group)) specs))
1071           (setcdr entry (cons article (cdr entry))))))
1072     (dolist (entry specs)
1073       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1074     specs))
1075
1076 (defun nnimap-transform-split-mail ()
1077   (goto-char (point-min))
1078   (let (article bytes)
1079     (block nil
1080       (while (not (eobp))
1081         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1082           (delete-region (point) (progn (forward-line 1) (point)))
1083           (when (eobp)
1084             (return)))
1085         (setq article (match-string 1)
1086               bytes (nnimap-get-length))
1087         (delete-region (line-beginning-position) (line-end-position))
1088         ;; Insert MMDF separator, and a way to remember what this
1089         ;; article UID is.
1090         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1091         (forward-char (1+ bytes))
1092         (setq bytes (nnimap-get-length))
1093         (delete-region (line-beginning-position) (line-end-position))
1094         (forward-char (1+ bytes))
1095         (delete-region (line-beginning-position) (line-end-position))))))
1096
1097 (defun nnimap-dummy-active-number (group &optional server)
1098   1)
1099
1100 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1101   (let (article)
1102     (goto-char (point-min))
1103     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1104         (error "Invalid nnimap mail")
1105       (setq article (string-to-number (match-string 1))))
1106     (push (list article group-art)
1107           nnimap-incoming-split-list)))
1108
1109 (provide 'nnimap)
1110
1111 ;;; nnimap.el ends here