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