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