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