Start preparing for partial downloads.
[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 nnimap-address ports))))
272                 (setq nnimap-object nil)
273               (setq login-result (nnimap-command "LOGIN %S %S"
274                                                  (car credentials)
275                                                  (cadr credentials)))
276               (unless (car login-result)
277                 (delete-process (nnimap-process nnimap-object))
278                 (setq nnimap-object nil))))
279           (when nnimap-object
280             (setf (nnimap-capabilities nnimap-object)
281                   (mapcar
282                    #'upcase
283                    (or (nnimap-find-parameter "CAPABILITY" (cdr login-result))
284                        (nnimap-find-parameter
285                         "CAPABILITY" (cdr (nnimap-command "CAPABILITY"))))))
286             (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
287               (nnimap-command "ENABLE QRESYNC"))
288             t))))))
289
290 (defun nnimap-find-parameter (parameter elems)
291   (let (result)
292     (dolist (elem elems)
293       (cond
294        ((equal (car elem) parameter)
295         (setq result (cdr elem)))
296        ((and (equal (car elem) "OK")
297              (consp (cadr elem))
298              (equal (caadr elem) parameter))
299         (setq result (cdr (cadr elem))))))
300     result))
301
302 (deffoo nnimap-close-server (&optional server)
303   t)
304
305 (deffoo nnimap-request-close ()
306   t)
307
308 (deffoo nnimap-server-opened (&optional server)
309   (and (nnoo-current-server-p 'nnimap server)
310        nntp-server-buffer
311        (gnus-buffer-live-p nntp-server-buffer)
312        (nnimap-find-connection nntp-server-buffer)))
313
314 (deffoo nnimap-status-message (&optional server)
315   nnimap-status-string)
316
317 (deffoo nnimap-request-article (article &optional group server to-buffer)
318   (with-current-buffer nntp-server-buffer
319     (let ((result (nnimap-possibly-change-group group server))
320           parts)
321       (when (stringp article)
322         (setq article (nnimap-find-article-by-message-id group article)))
323       (when (and result
324                  article)
325         (erase-buffer)
326         (with-current-buffer (nnimap-buffer)
327           (erase-buffer)
328           (when nnimap-fetch-partial-articles
329             (if (eq nnimap-fetch-partial-articles t)
330                 (setq parts '(1))
331               (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
332               (goto-char (point-min))
333               (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
334                 (let ((structure (ignore-errors (read (current-buffer)))))
335                   (setq parts (nnimap-find-wanted-parts structure))))))
336           (setq result
337                 (nnimap-command
338                  (if (member "IMAP4REV1" (nnimap-capabilities nnimap-object))
339                      "UID FETCH %d BODY.PEEK[]"
340                    "UID FETCH %d RFC822.PEEK")
341                  article))
342           ;; Check that we really got an article.
343           (goto-char (point-min))
344           (unless (looking-at "\\* [0-9]+ FETCH")
345             (setq result nil)))
346         (let ((buffer (nnimap-find-process-buffer (current-buffer))))
347           (when (car result)
348             (with-current-buffer (or to-buffer nntp-server-buffer)
349               (insert-buffer-substring buffer)
350               (goto-char (point-min))
351               (let ((bytes (nnimap-get-length)))
352                 (delete-region (line-beginning-position)
353                                (progn (forward-line 1) (point)))
354                 (goto-char (+ (point) bytes))
355                 (delete-region (point) (point-max))
356                 (nnheader-ms-strip-cr))
357               t)))))))
358
359 (defun nnimap-find-wanted-parts (structure)
360   (let ((nnimap-level 1))
361     (message-flatten-list (nnimap-find-wanted-parts-1 structure))))
362
363 (defun nnimap-find-wanted-parts-1 (structure)
364   (let (levels)
365     (while (consp (car structure))
366       (let ((sub (pop structure)))
367         (if (consp (car sub))
368             (push (nnimap-find-wanted-parts-1 sub) levels)
369           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub))))
370             (when (string-match nnimap-fetch-partial-articles type)
371               (push nnimap-level levels)))
372           (incf nnimap-level))))
373     (nreverse levels)))
374
375 (deffoo nnimap-request-group (group &optional server dont-check info)
376   (with-current-buffer nntp-server-buffer
377     (let ((result (nnimap-possibly-change-group group server))
378           articles active marks high low)
379       (when result
380         (if (and dont-check
381                  (setq active (nth 2 (assoc group nnimap-current-infos))))
382             (insert (format "211 %d %d %d %S\n"
383                             (- (cdr active) (car active))
384                             (car active)
385                             (cdr active)
386                             group))
387           (with-current-buffer (nnimap-buffer)
388             (erase-buffer)
389             (let ((group-sequence
390                    (nnimap-send-command "SELECT %S" (utf7-encode group)))
391                   (flag-sequence
392                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
393               (nnimap-wait-for-response flag-sequence)
394               (setq marks
395                     (nnimap-flags-to-marks
396                      (nnimap-parse-flags
397                       (list (list group-sequence flag-sequence 1 group)))))
398               (when info
399                 (nnimap-update-infos marks (list info)))
400               (goto-char (point-max))
401               (cond
402                (marks
403                 (setq high (nth 3 (car marks))
404                       low (nth 4 (car marks))))
405                ((re-search-backward "UIDNEXT \\([0-9]+\\)" nil t)
406                 (setq high (string-to-number (match-string 1))
407                       low 1)))))
408           (erase-buffer)
409           (insert
410            (format
411             "211 %d %d %d %S\n"
412             (1+ (- high low))
413             low high group))))
414       t)))
415
416 (defun nnimap-get-flags (spec)
417   (let ((articles nil)
418         elems)
419     (with-current-buffer (nnimap-buffer)
420       (erase-buffer)
421       (nnimap-wait-for-response (nnimap-send-command
422                                  "UID FETCH %s FLAGS" spec))
423       (goto-char (point-min))
424       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
425         (setq elems (nnimap-parse-line (match-string 1)))
426         (push (cons (string-to-number (cadr (member "UID" elems)))
427                     (cadr (member "FLAGS" elems)))
428               articles)))
429     (nreverse articles)))
430
431 (deffoo nnimap-close-group (group &optional server)
432   t)
433
434 (deffoo nnimap-request-move-article (article group server accept-form
435                                              &optional last internal-move-group)
436   (when (nnimap-possibly-change-group group server)
437     ;; If the move is internal (on the same server), just do it the easy
438     ;; way.
439     (let ((message-id (message-field-value "message-id")))
440       (if internal-move-group
441           (let ((result
442                  (with-current-buffer (nnimap-buffer)
443                    (nnimap-command "UID COPY %d %S"
444                                    article
445                                    (utf7-encode internal-move-group t)))))
446             (when (car result)
447               (nnimap-delete-article article)
448               (cons internal-move-group
449                     (nnimap-find-article-by-message-id
450                      internal-move-group message-id))))
451         (with-temp-buffer
452           (let ((result (eval accept-form)))
453             (when result
454               (nnimap-delete-article article)
455               result)))))))
456
457 (deffoo nnimap-request-expire-articles (articles group &optional server force)
458   (cond
459    ((not (nnimap-possibly-change-group group server))
460     articles)
461    (force
462     (unless (nnimap-delete-article articles)
463       (message "Article marked for deletion, but not expunged."))
464     nil)
465    (t
466     articles)))
467
468 (defun nnimap-find-article-by-message-id (group message-id)
469   (when (nnimap-possibly-change-group group nil)
470     (with-current-buffer (nnimap-buffer)
471       (let ((result
472              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
473             article)
474         (when (car result)
475           ;; Select the last instance of the message in the group.
476           (and (setq article
477                      (car (last (assoc "SEARCH" (cdr result)))))
478                (string-to-number article)))))))
479
480 (defun nnimap-delete-article (articles)
481   (with-current-buffer (nnimap-buffer)
482     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
483                     (nnimap-article-ranges articles))
484     (when (member "UIDPLUS" (nnimap-capabilities nnimap-object))
485       (nnimap-send-command "UID EXPUNGE %s"
486                            (nnimap-article-ranges articles))
487       t)))
488
489 (deffoo nnimap-request-scan (&optional group server)
490   (when (and (nnimap-possibly-change-group nil server)
491              (equal group nnimap-inbox)
492              nnimap-inbox
493              nnimap-split-methods)
494     (nnimap-split-incoming-mail)))
495
496 (defun nnimap-marks-to-flags (marks)
497   (let (flags flag)
498     (dolist (mark marks)
499       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
500         (push flag flags)))
501     flags))
502
503 (deffoo nnimap-request-set-mark (group actions &optional server)
504   (when (nnimap-possibly-change-group group server)
505     (let (sequence)
506       (with-current-buffer (nnimap-buffer)
507         ;; Just send all the STORE commands without waiting for
508         ;; response.  If they're successful, they're successful.
509         (dolist (action actions)
510           (destructuring-bind (range action marks) action
511             (let ((flags (nnimap-marks-to-flags marks)))
512               (when flags
513                 (setq sequence (nnimap-send-command
514                                 "UID STORE %s %sFLAGS.SILENT (%s)"
515                                 (nnimap-article-ranges range)
516                                 (if (eq action 'del)
517                                     "-"
518                                   "+")
519                                 (mapconcat #'identity flags " ")))))))
520         ;; Wait for the last command to complete to avoid later
521         ;; syncronisation problems with the stream.
522         (nnimap-wait-for-response sequence)))))
523
524 (deffoo nnimap-request-accept-article (group &optional server last)
525   (when (nnimap-possibly-change-group nil server)
526     (nnmail-check-syntax)
527     (let ((message (buffer-string))
528           (message-id (message-field-value "message-id"))
529           sequence)
530       (with-current-buffer (nnimap-buffer)
531         (setq sequence (nnimap-send-command
532                         "APPEND %S {%d}" (utf7-encode group t)
533                         (length message)))
534         (process-send-string (get-buffer-process (current-buffer)) message)
535         (process-send-string (get-buffer-process (current-buffer))
536                              (if (nnimap-newlinep nnimap-object)
537                                  "\n"
538                                "\r\n"))
539         (let ((result (nnimap-get-response sequence)))
540           (when result
541             (cons group
542                   (nnimap-find-article-by-message-id group message-id))))))))
543
544 (defun nnimap-add-cr ()
545   (goto-char (point-min))
546   (while (re-search-forward "\r?\n" nil t)
547     (replace-match "\r\n" t t)))
548
549 (defun nnimap-get-groups ()
550   (let ((result (nnimap-command "LIST \"\" \"*\""))
551         groups)
552     (when (car result)
553       (dolist (line (cdr result))
554         (when (and (equal (car line) "LIST")
555                    (not (and (caadr line)
556                              (string-match "noselect" (caadr line)))))
557           (push (car (last line)) groups)))
558       (nreverse groups))))
559
560 (deffoo nnimap-request-list (&optional server)
561   (nnimap-possibly-change-group nil server)
562   (with-current-buffer nntp-server-buffer
563     (erase-buffer)
564     (let ((groups
565            (with-current-buffer (nnimap-buffer)
566              (nnimap-get-groups)))
567           sequences responses)
568       (when groups
569         (with-current-buffer (nnimap-buffer)
570           (dolist (group groups)
571             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
572                         group)
573                   sequences))
574           (nnimap-wait-for-response (caar sequences))
575           (setq responses
576                 (nnimap-get-responses (mapcar #'car sequences))))
577         (dolist (response responses)
578           (let* ((sequence (car response))
579                  (response (cadr response))
580                  (group (cadr (assoc sequence sequences))))
581             (when (and group
582                        (equal (caar response) "OK"))
583               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
584                     highest exists)
585                 (dolist (elem response)
586                   (when (equal (cadr elem) "EXISTS")
587                     (setq exists (string-to-number (car elem)))))
588                 (when uidnext
589                   (setq highest (1- (string-to-number (car uidnext)))))
590                 (cond
591                  ((null highest)
592                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
593                  ((zerop exists)
594                   ;; Empty group.
595                   (insert (format "%S %d %d y\n"
596                                   (utf7-decode group t) highest (1+ highest))))
597                  (t
598                   ;; Return the widest possible range.
599                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
600                                   (or highest exists)))))))))
601         t))))
602
603 (deffoo nnimap-retrieve-group-data-early (server infos)
604   (when (nnimap-possibly-change-group nil server)
605     (with-current-buffer (nnimap-buffer)
606       ;; QRESYNC handling isn't implemented.
607       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
608             marks groups sequences)
609         ;; Go through the infos and gather the data needed to know
610         ;; what and how to request the data.
611         (dolist (info infos)
612           (setq marks (gnus-info-marks info))
613           (push (list (gnus-group-real-name (gnus-info-group info))
614                       (cdr (assq 'active marks))
615                       (cdr (assq 'uid marks)))
616                 groups))
617         ;; Then request the data.
618         (erase-buffer)
619         (dolist (elem groups)
620           (if (and qresyncp
621                    (nth 2 elem))
622               (push
623                (list 'qresync
624                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
625                                           (car elem)
626                                           (car (nth 2 elem))
627                                           (cdr (nth 2 elem)))
628                      nil
629                      (car elem))
630                sequences)
631             (let ((start
632                    (if (nth 1 elem)
633                        ;; Fetch the last 100 flags.
634                        (max 1 (- (cdr (nth 1 elem)) 100))
635                      1)))
636               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
637                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
638                           start
639                           (car elem))
640                     sequences))))
641         sequences))))
642
643 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
644   (when (and sequences
645              (nnimap-possibly-change-group nil server))
646     (with-current-buffer (nnimap-buffer)
647       ;; Wait for the final data to trickle in.
648       (nnimap-wait-for-response (cadar sequences))
649       ;; Now we should have all the data we need, no matter whether
650       ;; we're QRESYNCING, fetching all the flags from scratch, or
651       ;; just fetching the last 100 flags per group.
652       (nnimap-update-infos (nnimap-flags-to-marks
653                             (nnimap-parse-flags
654                              (nreverse sequences)))
655                            infos)
656       ;; Finally, just return something resembling an active file in
657       ;; the nntp buffer, so that the agent can save the info, too.
658       (with-current-buffer nntp-server-buffer
659         (erase-buffer)
660         (dolist (info infos)
661           (let* ((group (gnus-info-group info))
662                  (active (gnus-active group)))
663             (when active
664               (insert (format "%S %d %d y\n"
665                               (gnus-group-real-name group)
666                               (cdr active)
667                               (car active))))))))))
668
669 (defun nnimap-update-infos (flags infos)
670   (dolist (info infos)
671     (let ((group (gnus-group-real-name (gnus-info-group info))))
672       (nnimap-update-info info (cdr (assoc group flags))))))
673
674 (defun nnimap-update-info (info marks)
675   (when marks
676     (destructuring-bind (existing flags high low uidnext start-article) marks
677       (let ((group (gnus-info-group info))
678             (completep (and start-article
679                             (= start-article 1))))
680         ;; First set the active ranges based on high/low.
681         (if (or completep
682                 (not (gnus-active group)))
683             (gnus-set-active group
684                              (if high
685                                  (cons low high)
686                                ;; No articles in this group.
687                                (cons (1- uidnext) uidnext)))
688           (setcdr (gnus-active group) high))
689         ;; Then update the list of read articles.
690         (let* ((unread
691                 (gnus-compress-sequence
692                  (gnus-set-difference
693                   (gnus-set-difference
694                    existing
695                    (cdr (assoc "\\Seen" flags)))
696                   (cdr (assoc "\\Flagged" flags)))))
697                (read (gnus-range-difference
698                       (cons start-article high) unread)))
699           (when (> start-article 1)
700             (setq read
701                   (gnus-range-nconcat
702                    (if (> start-article 1)
703                        (gnus-sorted-range-intersection
704                         (cons 1 (1- start-article))
705                         (gnus-info-read info))
706                      (gnus-info-read info))
707                    read)))
708           (gnus-info-set-read info read)
709           ;; Update the marks.
710           (setq marks (gnus-info-marks info))
711           ;; Note the active level for the next run-through.
712           (let ((active (assq 'active marks)))
713             (if active
714                 (setcdr active (gnus-active group))
715               (push (cons 'active (gnus-active group)) marks)))
716           (dolist (type (cdr nnimap-mark-alist))
717             (let ((old-marks (assoc (car type) marks))
718                   (new-marks (gnus-compress-sequence
719                               (cdr (assoc (cadr type) flags)))))
720               (setq marks (delq old-marks marks))
721               (pop old-marks)
722               (when (and old-marks
723                          (> start-article 1))
724                 (setq old-marks (gnus-range-difference
725                                  old-marks
726                                  (cons start-article high)))
727                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
728               (when new-marks
729                 (push (cons (car type) new-marks) marks)))
730             (gnus-info-set-marks info marks t)
731             (nnimap-store-info info (gnus-active group))))))))
732
733 (defun nnimap-store-info (info active)
734   (let* ((group (gnus-group-real-name (gnus-info-group info)))
735          (entry (assoc group nnimap-current-infos)))
736     (if entry
737         (setcdr entry (list info active))
738       (push (list group info active) nnimap-current-infos))))
739
740 (defun nnimap-flags-to-marks (groups)
741   (let (data group totalp uidnext articles start-article mark)
742     (dolist (elem groups)
743       (setq group (car elem)
744             uidnext (cadr elem)
745             start-article (caddr elem)
746             articles (cdddr elem))
747       (let ((high (caar articles))
748             marks low existing)
749         (dolist (article articles)
750           (setq low (car article))
751           (push (car article) existing)
752           (dolist (flag (cdr article))
753             (setq mark (assoc flag marks))
754             (if (not mark)
755                 (push (list flag (car article)) marks)
756               (setcdr mark (cons (car article) (cdr mark)))))
757           (push (list group existing marks high low uidnext start-article)
758                 data))))
759     data))
760
761 (defun nnimap-parse-flags (sequences)
762   (goto-char (point-min))
763   (let (start end articles groups uidnext elems)
764     (dolist (elem sequences)
765       (destructuring-bind (group-sequence flag-sequence totalp group) elem
766         ;; The EXAMINE was successful.
767         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
768                    (progn
769                      (forward-line 1)
770                      (setq start (point))
771                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
772                                                (or end (point-min)) t)
773                          (setq uidnext (string-to-number (match-string 1)))
774                        (setq uidnext nil))
775                      (goto-char start))
776                    ;; The UID FETCH FLAGS was successful.
777                    (search-forward (format "\n%d OK " flag-sequence) nil t))
778           (setq end (point))
779           (goto-char start)
780           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
781             (setq elems (nnimap-parse-line (match-string 1)))
782             (push (cons (string-to-number (cadr (member "UID" elems)))
783                         (cadr (member "FLAGS" elems)))
784                   articles))
785           (push (nconc (list group uidnext totalp) articles) groups)
786           (setq articles nil))))
787     groups))
788
789 (defun nnimap-find-process-buffer (buffer)
790   (cadr (assoc buffer nnimap-connection-alist)))
791
792 (deffoo nnimap-request-post (&optional server)
793   (setq nnimap-status-string "Read-only server")
794   nil)
795
796 (defun nnimap-possibly-change-group (group server)
797   (let ((open-result t))
798     (when (and server
799                (not (nnimap-server-opened server)))
800       (setq open-result (nnimap-open-server server)))
801     (cond
802      ((not open-result)
803       nil)
804      ((not group)
805       t)
806      (t
807       (with-current-buffer (nnimap-buffer)
808         (if (equal group (nnimap-group nnimap-object))
809             t
810           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
811             (when (car result)
812               (setf (nnimap-group nnimap-object) group
813                     (nnimap-select-result nnimap-object) result)
814               result))))))))
815
816 (defun nnimap-find-connection (buffer)
817   "Find the connection delivering to BUFFER."
818   (let ((entry (assoc buffer nnimap-connection-alist)))
819     (when entry
820       (if (and (buffer-name (cadr entry))
821                (get-buffer-process (cadr entry))
822                (memq (process-status (get-buffer-process (cadr entry)))
823                      '(open run)))
824           (get-buffer-process (cadr entry))
825         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
826         nil))))
827
828 (defvar nnimap-sequence 0)
829
830 (defun nnimap-send-command (&rest args)
831   (process-send-string
832    (get-buffer-process (current-buffer))
833    (nnimap-log-command
834     (format "%d %s%s\n"
835             (incf nnimap-sequence)
836             (apply #'format args)
837             (if (nnimap-newlinep nnimap-object)
838                 ""
839               "\r"))))
840   nnimap-sequence)
841
842 (defun nnimap-log-command (command)
843   (with-current-buffer (get-buffer-create "*imap log*")
844     (goto-char (point-max))
845     (insert (format-time-string "%H:%M:%S") " " command))
846   command)
847
848 (defun nnimap-command (&rest args)
849   (erase-buffer)
850   (let* ((sequence (apply #'nnimap-send-command args))
851          (response (nnimap-get-response sequence)))
852     (if (equal (caar response) "OK")
853         (cons t response)
854       (nnheader-report 'nnimap "%s"
855                        (mapconcat #'identity (car response) " "))
856       nil)))
857
858 (defun nnimap-get-response (sequence)
859   (nnimap-wait-for-response sequence)
860   (nnimap-parse-response))
861
862 (defun nnimap-wait-for-connection ()
863   (let ((process (get-buffer-process (current-buffer))))
864     (goto-char (point-min))
865     (while (and (memq (process-status process)
866                       '(open run))
867                 (not (re-search-forward "^\\* " nil t)))
868       (nnheader-accept-process-output process)
869       (goto-char (point-min)))
870     (and (looking-at "[A-Z0-9]+")
871          (match-string 0))))
872
873 (defun nnimap-wait-for-response (sequence &optional messagep)
874   (let ((process (get-buffer-process (current-buffer))))
875     (goto-char (point-max))
876     (while (and (memq (process-status process)
877                       '(open run))
878                 (not (re-search-backward (format "^%d .*\n" sequence)
879                                          (max (point-min) (- (point) 500))
880                                          t)))
881       (when messagep
882         (message "Read %dKB" (/ (buffer-size) 1000)))
883       (nnheader-accept-process-output process)
884       (goto-char (point-max)))))
885
886 (defun nnimap-parse-response ()
887   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
888         result)
889     (dolist (line lines)
890       (push (cdr (nnimap-parse-line line)) result))
891     ;; Return the OK/error code first, and then all the "continuation
892     ;; lines" afterwards.
893     (cons (pop result)
894           (nreverse result))))
895
896 ;; Parse an IMAP response line lightly.  They look like
897 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
898 ;; the lines into a list of strings and lists of string.
899 (defun nnimap-parse-line (line)
900   (let (char result)
901     (with-temp-buffer
902       (insert line)
903       (goto-char (point-min))
904       (while (not (eobp))
905         (if (eql (setq char (following-char)) ? )
906             (forward-char 1)
907           (push
908            (cond
909             ((eql char ?\[)
910              (split-string (buffer-substring
911                             (1+ (point)) (1- (search-forward "]")))))
912             ((eql char ?\()
913              (split-string (buffer-substring
914                             (1+ (point)) (1- (search-forward ")")))))
915             ((eql char ?\")
916              (forward-char 1)
917              (buffer-substring (point) (1- (search-forward "\""))))
918             (t
919              (buffer-substring (point) (if (search-forward " " nil t)
920                                            (1- (point))
921                                          (goto-char (point-max))))))
922            result)))
923       (nreverse result))))
924
925 (defun nnimap-last-response-string ()
926   (save-excursion
927     (forward-line 1)
928     (let ((end (point)))
929       (forward-line -1)
930       (when (not (bobp))
931         (forward-line -1)
932         (while (and (not (bobp))
933                     (eql (following-char) ?*))
934           (forward-line -1))
935         (unless (eql (following-char) ?*)
936           (forward-line 1)))
937       (buffer-substring (point) end))))
938
939 (defun nnimap-get-responses (sequences)
940   (let (responses)
941     (dolist (sequence sequences)
942       (goto-char (point-min))
943       (when (re-search-forward (format "^%d " sequence) nil t)
944         (push (list sequence (nnimap-parse-response))
945               responses)))
946     responses))
947
948 (defvar nnimap-incoming-split-list nil)
949
950 (defun nnimap-fetch-inbox (articles)
951   (erase-buffer)
952   (nnimap-wait-for-response
953    (nnimap-send-command
954     "UID FETCH %s %s"
955     (nnimap-article-ranges articles)
956     (format "(UID %s%s)"
957             (format
958              (if (member "IMAP4REV1"
959                          (nnimap-capabilities nnimap-object))
960                  "BODY.PEEK[HEADER] BODY.PEEK"
961                "RFC822.PEEK"))
962             (if nnimap-split-download-body-default
963                 ""
964               "[1]")))
965    t))
966
967 (defun nnimap-split-incoming-mail ()
968   (with-current-buffer (nnimap-buffer)
969     (let ((nnimap-incoming-split-list nil)
970           (nnmail-split-methods nnimap-split-methods)
971           (nnmail-inhibit-default-split-group t)
972           (groups (nnimap-get-groups))
973           new-articles)
974       (erase-buffer)
975       (nnimap-command "SELECT %S" nnimap-inbox)
976       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
977       (when new-articles
978         (nnimap-fetch-inbox new-articles)
979         (nnimap-transform-split-mail)
980         (nnheader-ms-strip-cr)
981         (nnmail-cache-open)
982         (nnmail-split-incoming (current-buffer)
983                                #'nnimap-save-mail-spec
984                                nil nil
985                                #'nnimap-dummy-active-number)
986         (when nnimap-incoming-split-list
987           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
988                 sequences)
989             ;; Create any groups that doesn't already exist on the
990             ;; server first.
991             (dolist (spec specs)
992               (unless (member (car spec) groups)
993                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
994             ;; Then copy over all the messages.
995             (erase-buffer)
996             (dolist (spec specs)
997               (let ((group (car spec))
998                     (ranges (cdr spec)))
999                 (push (list (nnimap-send-command "UID COPY %s %S"
1000                                                  (nnimap-article-ranges ranges)
1001                                                  (utf7-encode group t))
1002                             ranges)
1003                       sequences)))
1004             ;; Wait for the last COPY response...
1005             (when sequences
1006               (nnimap-wait-for-response (caar sequences))
1007               ;; And then mark the successful copy actions as deleted,
1008               ;; and possibly expunge them.
1009               (nnimap-mark-and-expunge-incoming
1010                (nnimap-parse-copied-articles sequences)))))))))
1011
1012 (defun nnimap-mark-and-expunge-incoming (range)
1013   (when range
1014     (setq range (nnimap-article-ranges range))
1015     (nnimap-send-command
1016      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
1017     (cond
1018      ;; If the server supports it, we now delete the message we have
1019      ;; just copied over.
1020      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1021       (nnimap-send-command "UID EXPUNGE %s" range))
1022      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1023      ;; user has configured it.
1024      (nnimap-expunge-inbox
1025       (nnimap-send-command "EXPUNGE")))))
1026
1027 (defun nnimap-parse-copied-articles (sequences)
1028   (let (sequence copied range)
1029     (goto-char (point-min))
1030     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1031       (setq sequence (string-to-number (match-string 1)))
1032       (when (setq range (cadr (assq sequence sequences)))
1033         (push (gnus-uncompress-range range) copied)))
1034     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1035
1036 (defun nnimap-new-articles (flags)
1037   (let (new)
1038     (dolist (elem flags)
1039       (when (or (null (cdr elem))
1040                 (and (not (member "\\Deleted" (cdr elem)))
1041                      (not (member "\\Seen" (cdr elem)))))
1042         (push (car elem) new)))
1043     (gnus-compress-sequence (nreverse new))))
1044
1045 (defun nnimap-make-split-specs (list)
1046   (let ((specs nil)
1047         entry)
1048     (dolist (elem list)
1049       (destructuring-bind (article spec) elem
1050         (dolist (group (delete nil (mapcar #'car spec)))
1051           (unless (setq entry (assoc group specs))
1052             (push (setq entry (list group)) specs))
1053           (setcdr entry (cons article (cdr entry))))))
1054     (dolist (entry specs)
1055       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1056     specs))
1057
1058 (defun nnimap-transform-split-mail ()
1059   (goto-char (point-min))
1060   (let (article bytes)
1061     (block nil
1062       (while (not (eobp))
1063         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1064           (delete-region (point) (progn (forward-line 1) (point)))
1065           (when (eobp)
1066             (return)))
1067         (setq article (match-string 1)
1068               bytes (nnimap-get-length))
1069         (delete-region (line-beginning-position) (line-end-position))
1070         ;; Insert MMDF separator, and a way to remember what this
1071         ;; article UID is.
1072         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1073         (forward-char (1+ bytes))
1074         (setq bytes (nnimap-get-length))
1075         (delete-region (line-beginning-position) (line-end-position))
1076         (forward-char (1+ bytes))
1077         (delete-region (line-beginning-position) (line-end-position))))))
1078
1079 (defun nnimap-dummy-active-number (group &optional server)
1080   1)
1081
1082 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1083   (let (article)
1084     (goto-char (point-min))
1085     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1086         (error "Invalid nnimap mail")
1087       (setq article (string-to-number (match-string 1))))
1088     (push (list article group-art)
1089           nnimap-incoming-split-list)))
1090
1091 (provide 'nnimap)
1092
1093 ;;; nnimap.el ends here