(nnoo): Required, so that other packages can require nnimap.
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40
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)
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             (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 to-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)) "\r\n")
493         (let ((result (nnimap-get-response sequence)))
494           (when result
495             (cons group
496                   (nnimap-find-article-by-message-id group message-id))))))))
497
498 (defun nnimap-add-cr ()
499   (goto-char (point-min))
500   (while (re-search-forward "\r?\n" nil t)
501     (replace-match "\r\n" t t)))
502
503 (defun nnimap-get-groups ()
504   (let ((result (nnimap-command "LIST \"\" \"*\""))
505         groups)
506     (when (car result)
507       (dolist (line (cdr result))
508         (when (and (equal (car line) "LIST")
509                    (not (and (caadr line)
510                              (string-match "noselect" (caadr line)))))
511           (push (car (last line)) groups)))
512       (nreverse groups))))
513
514 (deffoo nnimap-request-list (&optional server)
515   (nnimap-possibly-change-group nil server)
516   (with-current-buffer nntp-server-buffer
517     (erase-buffer)
518     (let ((groups
519            (with-current-buffer (nnimap-buffer)
520              (nnimap-get-groups)))
521           sequences responses)
522       (when groups
523         (with-current-buffer (nnimap-buffer)
524           (dolist (group groups)
525             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
526                         group)
527                   sequences))
528           (nnimap-wait-for-response (caar sequences))
529           (setq responses
530                 (nnimap-get-responses (mapcar #'car sequences))))
531         (dolist (response responses)
532           (let* ((sequence (car response))
533                  (response (cadr response))
534                  (group (cadr (assoc sequence sequences))))
535             (when (and group
536                        (equal (caar response) "OK"))
537               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
538                     highest exists)
539                 (dolist (elem response)
540                   (when (equal (cadr elem) "EXISTS")
541                     (setq exists (string-to-number (car elem)))))
542                 (when uidnext
543                   (setq highest (1- (string-to-number (car uidnext)))))
544                 (cond
545                  ((null highest)
546                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
547                  ((zerop exists)
548                   ;; Empty group.
549                   (insert (format "%S %d %d y\n"
550                                   (utf7-decode group t) highest (1+ highest))))
551                  (t
552                   ;; Return the widest possible range.
553                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
554                                   (or highest exists)))))))))
555         t))))
556
557 (deffoo nnimap-retrieve-group-data-early (server infos)
558   (when (nnimap-possibly-change-group nil server)
559     (with-current-buffer (nnimap-buffer)
560       ;; QRESYNC handling isn't implemented.
561       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
562             marks groups sequences)
563         ;; Go through the infos and gather the data needed to know
564         ;; what and how to request the data.
565         (dolist (info infos)
566           (setq marks (gnus-info-marks info))
567           (push (list (gnus-group-real-name (gnus-info-group info))
568                       (cdr (assq 'active marks))
569                       (cdr (assq 'uid marks)))
570                 groups))
571         ;; Then request the data.
572         (erase-buffer)
573         (dolist (elem groups)
574           (if (and qresyncp
575                    (nth 2 elem))
576               (push
577                (list 'qresync
578                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
579                                           (car elem)
580                                           (car (nth 2 elem))
581                                           (cdr (nth 2 elem)))
582                      nil
583                      (car elem))
584                sequences)
585             (let ((start
586                    (if (nth 1 elem)
587                        ;; Fetch the last 100 flags.
588                        (max 1 (- (cdr (nth 1 elem)) 100))
589                      1)))
590               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
591                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
592                           start
593                           (car elem))
594                     sequences))))
595         sequences))))
596
597 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
598   (when (and sequences
599              (nnimap-possibly-change-group nil server))
600     (with-current-buffer (nnimap-buffer)
601       ;; Wait for the final data to trickle in.
602       (nnimap-wait-for-response (cadar sequences))
603       ;; Now we should have all the data we need, no matter whether
604       ;; we're QRESYNCING, fetching all the flags from scratch, or
605       ;; just fetching the last 100 flags per group.
606       (nnimap-update-infos (nnimap-flags-to-marks
607                             (nnimap-parse-flags
608                              (nreverse sequences)))
609                            infos))))
610
611 (defun nnimap-update-infos (flags infos)
612   (dolist (info infos)
613     (let ((group (gnus-group-real-name (gnus-info-group info))))
614       (nnimap-update-info info (cdr (assoc group flags))))))
615
616 (defun nnimap-update-info (info marks)
617   (when marks
618     (destructuring-bind (existing flags high low uidnext start-article) marks
619       (let ((group (gnus-info-group info))
620             (completep (and start-article
621                             (= start-article 1))))
622         ;; First set the active ranges based on high/low.
623         (if (or completep
624                 (not (gnus-active group)))
625             (gnus-set-active group
626                              (if high
627                                  (cons low high)
628                                ;; No articles in this group.
629                                (cons (1- uidnext) uidnext)))
630           (setcdr (gnus-active group) high))
631         ;; Then update the list of read articles.
632         (let* ((unread
633                 (gnus-compress-sequence
634                  (gnus-set-difference
635                   (gnus-set-difference
636                    existing
637                    (cdr (assoc "\\Seen" flags)))
638                   (cdr (assoc "\\Flagged" flags)))))
639                (read (gnus-range-difference
640                       (cons start-article high) unread)))
641           (when (> start-article 1)
642             (setq read
643                   (gnus-range-nconcat
644                    (if (> start-article 1)
645                        (gnus-sorted-range-intersection
646                         (cons 1 (1- start-article))
647                         (gnus-info-read info))
648                      (gnus-info-read info))
649                    read)))
650           (gnus-info-set-read info read)
651           ;; Update the marks.
652           (setq marks (gnus-info-marks info))
653           ;; Note the active level for the next run-through.
654           (let ((active (assq 'active marks)))
655             (if active
656                 (setcdr active (gnus-active group))
657               (push (cons 'active (gnus-active group)) marks)))
658           (dolist (type (cdr nnimap-mark-alist))
659             (let ((old-marks (assoc (car type) marks))
660                   (new-marks (gnus-compress-sequence
661                               (cdr (assoc (cadr type) flags)))))
662               (setq marks (delq old-marks marks))
663               (pop old-marks)
664               (when (and old-marks
665                          (> start-article 1))
666                 (setq old-marks (gnus-range-difference
667                                  old-marks
668                                  (cons start-article high)))
669                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
670               (when new-marks
671                 (push (cons (car type) new-marks) marks)))
672             (gnus-info-set-marks info marks t)
673             (nnimap-store-info info (gnus-active group))))))))
674
675 (defun nnimap-store-info (info active)
676   (let* ((group (gnus-group-real-name (gnus-info-group info)))
677          (entry (assoc group nnimap-current-infos)))
678     (if entry
679         (setcdr entry (list info active))
680       (push (list group info active) nnimap-current-infos))))
681
682 (defun nnimap-flags-to-marks (groups)
683   (let (data group totalp uidnext articles start-article mark)
684     (dolist (elem groups)
685       (setq group (car elem)
686             uidnext (cadr elem)
687             start-article (caddr elem)
688             articles (cdddr elem))
689       (let ((high (caar articles))
690             marks low existing)
691         (dolist (article articles)
692           (setq low (car article))
693           (push (car article) existing)
694           (dolist (flag (cdr article))
695             (setq mark (assoc flag marks))
696             (if (not mark)
697                 (push (list flag (car article)) marks)
698               (setcdr mark (cons (car article) (cdr mark)))))
699           (push (list group existing marks high low uidnext start-article)
700                 data))))
701     data))
702
703 (defun nnimap-parse-flags (sequences)
704   (goto-char (point-min))
705   (let (start end articles groups uidnext elems)
706     (dolist (elem sequences)
707       (destructuring-bind (group-sequence flag-sequence totalp group) elem
708         ;; The EXAMINE was successful.
709         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
710                    (progn
711                      (forward-line 1)
712                      (setq start (point))
713                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
714                                                (or end (point-min)) t)
715                          (setq uidnext (string-to-number (match-string 1)))
716                        (setq uidnext nil))
717                      (goto-char start))
718                    ;; The UID FETCH FLAGS was successful.
719                    (search-forward (format "\n%d OK " flag-sequence) nil t))
720           (setq end (point))
721           (goto-char start)
722           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
723             (setq elems (nnimap-parse-line (match-string 1)))
724             (push (cons (string-to-number (cadr (member "UID" elems)))
725                         (cadr (member "FLAGS" elems)))
726                   articles))
727           (push (nconc (list group uidnext totalp) articles) groups)
728           (setq articles nil))))
729     groups))
730
731 (defun nnimap-find-process-buffer (buffer)
732   (cadr (assoc buffer nnimap-connection-alist)))
733
734 (deffoo nnimap-request-post (&optional server)
735   (setq nnimap-status-string "Read-only server")
736   nil)
737
738 (defun nnimap-possibly-change-group (group server)
739   (let ((open-result t))
740     (when (and server
741                (not (nnimap-server-opened server)))
742       (setq open-result (nnimap-open-server server)))
743     (cond
744      ((not open-result)
745       nil)
746      ((not group)
747       t)
748      (t
749       (with-current-buffer (nnimap-buffer)
750         (if (equal group (nnimap-group nnimap-object))
751             t
752           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
753             (when (car result)
754               (setf (nnimap-group nnimap-object) group
755                     (nnimap-select-result nnimap-object) result)
756               result))))))))
757
758 (defun nnimap-find-connection (buffer)
759   "Find the connection delivering to BUFFER."
760   (let ((entry (assoc buffer nnimap-connection-alist)))
761     (when entry
762       (if (and (buffer-name (cadr entry))
763                (get-buffer-process (cadr entry))
764                (memq (process-status (get-buffer-process (cadr entry)))
765                      '(open run)))
766           (get-buffer-process (cadr entry))
767         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
768         nil))))
769
770 (defvar nnimap-sequence 0)
771
772 (defun nnimap-send-command (&rest args)
773   (process-send-string
774    (get-buffer-process (current-buffer))
775    (nnimap-log-command
776     (format "%d %s\r\n"
777             (incf nnimap-sequence)
778             (apply #'format args))))
779   nnimap-sequence)
780
781 (defun nnimap-log-command (command)
782   (with-current-buffer (get-buffer-create "*imap log*")
783     (goto-char (point-max))
784     (insert (format-time-string "%H:%M:%S") " " command))
785   command)
786
787 (defun nnimap-command (&rest args)
788   (erase-buffer)
789   (let* ((sequence (apply #'nnimap-send-command args))
790          (response (nnimap-get-response sequence)))
791     (if (equal (caar response) "OK")
792         (cons t response)
793       (nnheader-report 'nnimap "%s"
794                        (mapconcat #'identity (car response) " "))
795       nil)))
796
797 (defun nnimap-get-response (sequence)
798   (nnimap-wait-for-response sequence)
799   (nnimap-parse-response))
800
801 (defun nnimap-wait-for-connection ()
802   (let ((process (get-buffer-process (current-buffer))))
803     (goto-char (point-min))
804     (while (and (memq (process-status process)
805                       '(open run))
806                 (not (re-search-forward "^\\* " nil t)))
807       (nnheader-accept-process-output process)
808       (goto-char (point-min)))
809     (and (looking-at "[A-Z0-9]+")
810          (match-string 0))))
811
812 (defun nnimap-wait-for-response (sequence &optional messagep)
813   (goto-char (point-max))
814   (while (or (bobp)
815              (progn
816                (forward-line -1)
817                (not (looking-at (format "^%d .*\n" sequence)))))
818     (when messagep
819       (message "Read %dKB" (/ (buffer-size) 1000)))
820     (nnheader-accept-process-output (get-buffer-process (current-buffer)))
821     (goto-char (point-max))))
822
823 (defun nnimap-parse-response ()
824   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
825         result)
826     (dolist (line lines)
827       (push (cdr (nnimap-parse-line line)) result))
828     ;; Return the OK/error code first, and then all the "continuation
829     ;; lines" afterwards.
830     (cons (pop result)
831           (nreverse result))))
832
833 ;; Parse an IMAP response line lightly.  They look like
834 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
835 ;; the lines into a list of strings and lists of string.
836 (defun nnimap-parse-line (line)
837   (let (char result)
838     (with-temp-buffer
839       (insert line)
840       (goto-char (point-min))
841       (while (not (eobp))
842         (if (eql (setq char (following-char)) ? )
843             (forward-char 1)
844           (push
845            (cond
846             ((eql char ?\[)
847              (split-string (buffer-substring
848                             (1+ (point)) (1- (search-forward "]")))))
849             ((eql char ?\()
850              (split-string (buffer-substring
851                             (1+ (point)) (1- (search-forward ")")))))
852             ((eql char ?\")
853              (forward-char 1)
854              (buffer-substring (point) (1- (search-forward "\""))))
855             (t
856              (buffer-substring (point) (if (search-forward " " nil t)
857                                            (1- (point))
858                                          (goto-char (point-max))))))
859            result)))
860       (nreverse result))))
861
862 (defun nnimap-last-response-string ()
863   (save-excursion
864     (forward-line 1)
865     (let ((end (point)))
866       (forward-line -1)
867       (when (not (bobp))
868         (forward-line -1)
869         (while (and (not (bobp))
870                     (eql (following-char) ?*))
871           (forward-line -1))
872         (unless (eql (following-char) ?*)
873           (forward-line 1)))
874       (buffer-substring (point) end))))
875
876 (defun nnimap-get-responses (sequences)
877   (let (responses)
878     (dolist (sequence sequences)
879       (goto-char (point-min))
880       (when (re-search-forward (format "^%d " sequence) nil t)
881         (push (list sequence (nnimap-parse-response))
882               responses)))
883     responses))
884
885 (defvar nnimap-incoming-split-list nil)
886
887 (defun nnimap-fetch-inbox (articles)
888   (erase-buffer)
889   (nnimap-wait-for-response
890    (nnimap-send-command
891     "UID FETCH %s %s"
892     (nnimap-article-ranges articles)
893     (format "(UID %s%s)"
894             (format
895              (if (member "IMAP4REV1"
896                          (nnimap-capabilities nnimap-object))
897                  "BODY.PEEK[HEADER] BODY.PEEK"
898                "RFC822.PEEK"))
899             (if nnimap-split-download-body-default
900                 ""
901               "[1]")))
902    t))
903
904 (defun nnimap-split-incoming-mail ()
905   (with-current-buffer (nnimap-buffer)
906     (let ((nnimap-incoming-split-list nil)
907           (nnmail-split-methods nnimap-split-methods)
908           (nnmail-inhibit-default-split-group t)
909           (groups (nnimap-get-groups))
910           new-articles)
911       (erase-buffer)
912       (nnimap-command "SELECT %S" nnimap-inbox)
913       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
914       (when new-articles
915         (nnimap-fetch-inbox new-articles)
916         (nnimap-transform-split-mail)
917         (nnheader-ms-strip-cr)
918         (nnmail-cache-open)
919         (nnmail-split-incoming (current-buffer)
920                                #'nnimap-save-mail-spec
921                                nil nil
922                                #'nnimap-dummy-active-number)
923         (when nnimap-incoming-split-list
924           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
925                 sequences)
926             ;; Create any groups that doesn't already exist on the
927             ;; server first.
928             (dolist (spec specs)
929               (unless (member (car spec) groups)
930                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
931             ;; Then copy over all the messages.
932             (erase-buffer)
933             (dolist (spec specs)
934               (let ((group (car spec))
935                     (ranges (cdr spec)))
936                 (push (list (nnimap-send-command "UID COPY %s %S"
937                                                  (nnimap-article-ranges ranges)
938                                                  (utf7-encode group t))
939                             ranges)
940                       sequences)))
941             ;; Wait for the last COPY response...
942             (when sequences
943               (nnimap-wait-for-response (caar sequences))
944               ;; And then mark the successful copy actions as deleted,
945               ;; and possibly expunge them.
946               (nnimap-mark-and-expunge-incoming
947                (nnimap-parse-copied-articles sequences)))))))))
948
949 (defun nnimap-mark-and-expunge-incoming (range)
950   (when range
951     (setq range (nnimap-article-ranges range))
952     (nnimap-send-command
953      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
954     (cond
955      ;; If the server supports it, we now delete the message we have
956      ;; just copied over.
957      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
958       (nnimap-send-command "UID EXPUNGE %s" range))
959      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
960      ;; user has configured it.
961      (nnimap-expunge-inbox
962       (nnimap-send-command "EXPUNGE")))))
963
964 (defun nnimap-parse-copied-articles (sequences)
965   (let (sequence copied range)
966     (goto-char (point-min))
967     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
968       (setq sequence (string-to-number (match-string 1)))
969       (when (setq range (cadr (assq sequence sequences)))
970         (push (gnus-uncompress-range range) copied)))
971     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
972
973 (defun nnimap-new-articles (flags)
974   (let (new)
975     (dolist (elem flags)
976       (when (or (null (cdr elem))
977                 (and (not (member "\\Deleted" (cdr elem)))
978                      (not (member "\\Seen" (cdr elem)))))
979         (push (car elem) new)))
980     (gnus-compress-sequence (nreverse new))))
981
982 (defun nnimap-make-split-specs (list)
983   (let ((specs nil)
984         entry)
985     (dolist (elem list)
986       (destructuring-bind (article spec) elem
987         (dolist (group (delete nil (mapcar #'car spec)))
988           (unless (setq entry (assoc group specs))
989             (push (setq entry (list group)) specs))
990           (setcdr entry (cons article (cdr entry))))))
991     (dolist (entry specs)
992       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
993     specs))
994
995 (defun nnimap-transform-split-mail ()
996   (goto-char (point-min))
997   (let (article bytes)
998     (block nil
999       (while (not (eobp))
1000         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1001           (delete-region (point) (progn (forward-line 1) (point)))
1002           (when (eobp)
1003             (return)))
1004         (setq article (match-string 1)
1005               bytes (nnimap-get-length))
1006         (delete-region (line-beginning-position) (line-end-position))
1007         ;; Insert MMDF separator, and a way to remember what this
1008         ;; article UID is.
1009         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1010         (forward-char (1+ bytes))
1011         (setq bytes (nnimap-get-length))
1012         (delete-region (line-beginning-position) (line-end-position))
1013         (forward-char (1+ bytes))
1014         (delete-region (line-beginning-position) (line-end-position))))))
1015
1016 (defun nnimap-dummy-active-number (group &optional server)
1017   1)
1018
1019 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1020   (let (article)
1021     (goto-char (point-min))
1022     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1023         (error "Invalid nnimap mail")
1024       (setq article (string-to-number (match-string 1))))
1025     (push (list article group-art)
1026           nnimap-incoming-split-list)))
1027
1028 (provide 'nnimap)
1029
1030 ;;; nnimap.el ends here