Bind `process-connection-type' to nil, so that CRLF doesn't get translated to \n.
[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             (insert (format "%S %d %d y\n"
621                             (gnus-group-real-name group)
622                             (cdr active)
623                             (car active)))))))))
624
625 (defun nnimap-update-infos (flags infos)
626   (dolist (info infos)
627     (let ((group (gnus-group-real-name (gnus-info-group info))))
628       (nnimap-update-info info (cdr (assoc group flags))))))
629
630 (defun nnimap-update-info (info marks)
631   (when marks
632     (destructuring-bind (existing flags high low uidnext start-article) marks
633       (let ((group (gnus-info-group info))
634             (completep (and start-article
635                             (= start-article 1))))
636         ;; First set the active ranges based on high/low.
637         (if (or completep
638                 (not (gnus-active group)))
639             (gnus-set-active group
640                              (if high
641                                  (cons low high)
642                                ;; No articles in this group.
643                                (cons (1- uidnext) uidnext)))
644           (setcdr (gnus-active group) high))
645         ;; Then update the list of read articles.
646         (let* ((unread
647                 (gnus-compress-sequence
648                  (gnus-set-difference
649                   (gnus-set-difference
650                    existing
651                    (cdr (assoc "\\Seen" flags)))
652                   (cdr (assoc "\\Flagged" flags)))))
653                (read (gnus-range-difference
654                       (cons start-article high) unread)))
655           (when (> start-article 1)
656             (setq read
657                   (gnus-range-nconcat
658                    (if (> start-article 1)
659                        (gnus-sorted-range-intersection
660                         (cons 1 (1- start-article))
661                         (gnus-info-read info))
662                      (gnus-info-read info))
663                    read)))
664           (gnus-info-set-read info read)
665           ;; Update the marks.
666           (setq marks (gnus-info-marks info))
667           ;; Note the active level for the next run-through.
668           (let ((active (assq 'active marks)))
669             (if active
670                 (setcdr active (gnus-active group))
671               (push (cons 'active (gnus-active group)) marks)))
672           (dolist (type (cdr nnimap-mark-alist))
673             (let ((old-marks (assoc (car type) marks))
674                   (new-marks (gnus-compress-sequence
675                               (cdr (assoc (cadr type) flags)))))
676               (setq marks (delq old-marks marks))
677               (pop old-marks)
678               (when (and old-marks
679                          (> start-article 1))
680                 (setq old-marks (gnus-range-difference
681                                  old-marks
682                                  (cons start-article high)))
683                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
684               (when new-marks
685                 (push (cons (car type) new-marks) marks)))
686             (gnus-info-set-marks info marks t)
687             (nnimap-store-info info (gnus-active group))))))))
688
689 (defun nnimap-store-info (info active)
690   (let* ((group (gnus-group-real-name (gnus-info-group info)))
691          (entry (assoc group nnimap-current-infos)))
692     (if entry
693         (setcdr entry (list info active))
694       (push (list group info active) nnimap-current-infos))))
695
696 (defun nnimap-flags-to-marks (groups)
697   (let (data group totalp uidnext articles start-article mark)
698     (dolist (elem groups)
699       (setq group (car elem)
700             uidnext (cadr elem)
701             start-article (caddr elem)
702             articles (cdddr elem))
703       (let ((high (caar articles))
704             marks low existing)
705         (dolist (article articles)
706           (setq low (car article))
707           (push (car article) existing)
708           (dolist (flag (cdr article))
709             (setq mark (assoc flag marks))
710             (if (not mark)
711                 (push (list flag (car article)) marks)
712               (setcdr mark (cons (car article) (cdr mark)))))
713           (push (list group existing marks high low uidnext start-article)
714                 data))))
715     data))
716
717 (defun nnimap-parse-flags (sequences)
718   (goto-char (point-min))
719   (let (start end articles groups uidnext elems)
720     (dolist (elem sequences)
721       (destructuring-bind (group-sequence flag-sequence totalp group) elem
722         ;; The EXAMINE was successful.
723         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
724                    (progn
725                      (forward-line 1)
726                      (setq start (point))
727                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
728                                                (or end (point-min)) t)
729                          (setq uidnext (string-to-number (match-string 1)))
730                        (setq uidnext nil))
731                      (goto-char start))
732                    ;; The UID FETCH FLAGS was successful.
733                    (search-forward (format "\n%d OK " flag-sequence) nil t))
734           (setq end (point))
735           (goto-char start)
736           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
737             (setq elems (nnimap-parse-line (match-string 1)))
738             (push (cons (string-to-number (cadr (member "UID" elems)))
739                         (cadr (member "FLAGS" elems)))
740                   articles))
741           (push (nconc (list group uidnext totalp) articles) groups)
742           (setq articles nil))))
743     groups))
744
745 (defun nnimap-find-process-buffer (buffer)
746   (cadr (assoc buffer nnimap-connection-alist)))
747
748 (deffoo nnimap-request-post (&optional server)
749   (setq nnimap-status-string "Read-only server")
750   nil)
751
752 (defun nnimap-possibly-change-group (group server)
753   (let ((open-result t))
754     (when (and server
755                (not (nnimap-server-opened server)))
756       (setq open-result (nnimap-open-server server)))
757     (cond
758      ((not open-result)
759       nil)
760      ((not group)
761       t)
762      (t
763       (with-current-buffer (nnimap-buffer)
764         (if (equal group (nnimap-group nnimap-object))
765             t
766           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
767             (when (car result)
768               (setf (nnimap-group nnimap-object) group
769                     (nnimap-select-result nnimap-object) result)
770               result))))))))
771
772 (defun nnimap-find-connection (buffer)
773   "Find the connection delivering to BUFFER."
774   (let ((entry (assoc buffer nnimap-connection-alist)))
775     (when entry
776       (if (and (buffer-name (cadr entry))
777                (get-buffer-process (cadr entry))
778                (memq (process-status (get-buffer-process (cadr entry)))
779                      '(open run)))
780           (get-buffer-process (cadr entry))
781         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
782         nil))))
783
784 (defvar nnimap-sequence 0)
785
786 (defun nnimap-send-command (&rest args)
787   (process-send-string
788    (get-buffer-process (current-buffer))
789    (nnimap-log-command
790     (format "%d %s%s\n"
791             (incf nnimap-sequence)
792             (apply #'format args)
793             (if (nnimap-newlinep nnimap-object)
794                 ""
795               "\r"))))
796   nnimap-sequence)
797
798 (defun nnimap-log-command (command)
799   (with-current-buffer (get-buffer-create "*imap log*")
800     (goto-char (point-max))
801     (insert (format-time-string "%H:%M:%S") " " command))
802   command)
803
804 (defun nnimap-command (&rest args)
805   (erase-buffer)
806   (let* ((sequence (apply #'nnimap-send-command args))
807          (response (nnimap-get-response sequence)))
808     (if (equal (caar response) "OK")
809         (cons t response)
810       (nnheader-report 'nnimap "%s"
811                        (mapconcat #'identity (car response) " "))
812       nil)))
813
814 (defun nnimap-get-response (sequence)
815   (nnimap-wait-for-response sequence)
816   (nnimap-parse-response))
817
818 (defun nnimap-wait-for-connection ()
819   (let ((process (get-buffer-process (current-buffer))))
820     (goto-char (point-min))
821     (while (and (memq (process-status process)
822                       '(open run))
823                 (not (re-search-forward "^\\* " nil t)))
824       (nnheader-accept-process-output process)
825       (goto-char (point-min)))
826     (and (looking-at "[A-Z0-9]+")
827          (match-string 0))))
828
829 (defun nnimap-wait-for-response (sequence &optional messagep)
830   (goto-char (point-max))
831   (while (not (re-search-backward (format "^%d .*\n" sequence)
832                                   (max (point-min) (- (point) 500))
833                                   t))
834     (when messagep
835       (message "Read %dKB" (/ (buffer-size) 1000)))
836     (nnheader-accept-process-output (get-buffer-process (current-buffer)))
837     (goto-char (point-max))))
838
839 (defun nnimap-parse-response ()
840   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
841         result)
842     (dolist (line lines)
843       (push (cdr (nnimap-parse-line line)) result))
844     ;; Return the OK/error code first, and then all the "continuation
845     ;; lines" afterwards.
846     (cons (pop result)
847           (nreverse result))))
848
849 ;; Parse an IMAP response line lightly.  They look like
850 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
851 ;; the lines into a list of strings and lists of string.
852 (defun nnimap-parse-line (line)
853   (let (char result)
854     (with-temp-buffer
855       (insert line)
856       (goto-char (point-min))
857       (while (not (eobp))
858         (if (eql (setq char (following-char)) ? )
859             (forward-char 1)
860           (push
861            (cond
862             ((eql char ?\[)
863              (split-string (buffer-substring
864                             (1+ (point)) (1- (search-forward "]")))))
865             ((eql char ?\()
866              (split-string (buffer-substring
867                             (1+ (point)) (1- (search-forward ")")))))
868             ((eql char ?\")
869              (forward-char 1)
870              (buffer-substring (point) (1- (search-forward "\""))))
871             (t
872              (buffer-substring (point) (if (search-forward " " nil t)
873                                            (1- (point))
874                                          (goto-char (point-max))))))
875            result)))
876       (nreverse result))))
877
878 (defun nnimap-last-response-string ()
879   (save-excursion
880     (forward-line 1)
881     (let ((end (point)))
882       (forward-line -1)
883       (when (not (bobp))
884         (forward-line -1)
885         (while (and (not (bobp))
886                     (eql (following-char) ?*))
887           (forward-line -1))
888         (unless (eql (following-char) ?*)
889           (forward-line 1)))
890       (buffer-substring (point) end))))
891
892 (defun nnimap-get-responses (sequences)
893   (let (responses)
894     (dolist (sequence sequences)
895       (goto-char (point-min))
896       (when (re-search-forward (format "^%d " sequence) nil t)
897         (push (list sequence (nnimap-parse-response))
898               responses)))
899     responses))
900
901 (defvar nnimap-incoming-split-list nil)
902
903 (defun nnimap-fetch-inbox (articles)
904   (erase-buffer)
905   (nnimap-wait-for-response
906    (nnimap-send-command
907     "UID FETCH %s %s"
908     (nnimap-article-ranges articles)
909     (format "(UID %s%s)"
910             (format
911              (if (member "IMAP4REV1"
912                          (nnimap-capabilities nnimap-object))
913                  "BODY.PEEK[HEADER] BODY.PEEK"
914                "RFC822.PEEK"))
915             (if nnimap-split-download-body-default
916                 ""
917               "[1]")))
918    t))
919
920 (defun nnimap-split-incoming-mail ()
921   (with-current-buffer (nnimap-buffer)
922     (let ((nnimap-incoming-split-list nil)
923           (nnmail-split-methods nnimap-split-methods)
924           (nnmail-inhibit-default-split-group t)
925           (groups (nnimap-get-groups))
926           new-articles)
927       (erase-buffer)
928       (nnimap-command "SELECT %S" nnimap-inbox)
929       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
930       (when new-articles
931         (nnimap-fetch-inbox new-articles)
932         (nnimap-transform-split-mail)
933         (nnheader-ms-strip-cr)
934         (nnmail-cache-open)
935         (nnmail-split-incoming (current-buffer)
936                                #'nnimap-save-mail-spec
937                                nil nil
938                                #'nnimap-dummy-active-number)
939         (when nnimap-incoming-split-list
940           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
941                 sequences)
942             ;; Create any groups that doesn't already exist on the
943             ;; server first.
944             (dolist (spec specs)
945               (unless (member (car spec) groups)
946                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
947             ;; Then copy over all the messages.
948             (erase-buffer)
949             (dolist (spec specs)
950               (let ((group (car spec))
951                     (ranges (cdr spec)))
952                 (push (list (nnimap-send-command "UID COPY %s %S"
953                                                  (nnimap-article-ranges ranges)
954                                                  (utf7-encode group t))
955                             ranges)
956                       sequences)))
957             ;; Wait for the last COPY response...
958             (when sequences
959               (nnimap-wait-for-response (caar sequences))
960               ;; And then mark the successful copy actions as deleted,
961               ;; and possibly expunge them.
962               (nnimap-mark-and-expunge-incoming
963                (nnimap-parse-copied-articles sequences)))))))))
964
965 (defun nnimap-mark-and-expunge-incoming (range)
966   (when range
967     (setq range (nnimap-article-ranges range))
968     (nnimap-send-command
969      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
970     (cond
971      ;; If the server supports it, we now delete the message we have
972      ;; just copied over.
973      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
974       (nnimap-send-command "UID EXPUNGE %s" range))
975      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
976      ;; user has configured it.
977      (nnimap-expunge-inbox
978       (nnimap-send-command "EXPUNGE")))))
979
980 (defun nnimap-parse-copied-articles (sequences)
981   (let (sequence copied range)
982     (goto-char (point-min))
983     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
984       (setq sequence (string-to-number (match-string 1)))
985       (when (setq range (cadr (assq sequence sequences)))
986         (push (gnus-uncompress-range range) copied)))
987     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
988
989 (defun nnimap-new-articles (flags)
990   (let (new)
991     (dolist (elem flags)
992       (when (or (null (cdr elem))
993                 (and (not (member "\\Deleted" (cdr elem)))
994                      (not (member "\\Seen" (cdr elem)))))
995         (push (car elem) new)))
996     (gnus-compress-sequence (nreverse new))))
997
998 (defun nnimap-make-split-specs (list)
999   (let ((specs nil)
1000         entry)
1001     (dolist (elem list)
1002       (destructuring-bind (article spec) elem
1003         (dolist (group (delete nil (mapcar #'car spec)))
1004           (unless (setq entry (assoc group specs))
1005             (push (setq entry (list group)) specs))
1006           (setcdr entry (cons article (cdr entry))))))
1007     (dolist (entry specs)
1008       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1009     specs))
1010
1011 (defun nnimap-transform-split-mail ()
1012   (goto-char (point-min))
1013   (let (article bytes)
1014     (block nil
1015       (while (not (eobp))
1016         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1017           (delete-region (point) (progn (forward-line 1) (point)))
1018           (when (eobp)
1019             (return)))
1020         (setq article (match-string 1)
1021               bytes (nnimap-get-length))
1022         (delete-region (line-beginning-position) (line-end-position))
1023         ;; Insert MMDF separator, and a way to remember what this
1024         ;; article UID is.
1025         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1026         (forward-char (1+ bytes))
1027         (setq bytes (nnimap-get-length))
1028         (delete-region (line-beginning-position) (line-end-position))
1029         (forward-char (1+ bytes))
1030         (delete-region (line-beginning-position) (line-end-position))))))
1031
1032 (defun nnimap-dummy-active-number (group &optional server)
1033   1)
1034
1035 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1036   (let (article)
1037     (goto-char (point-min))
1038     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1039         (error "Invalid nnimap mail")
1040       (setq article (string-to-number (match-string 1))))
1041     (push (list article group-art)
1042           nnimap-incoming-split-list)))
1043
1044 (provide 'nnimap)
1045
1046 ;;; nnimap.el ends here