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