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