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