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