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', `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)
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               bytes (nnimap-get-length)
151               lines nil)
152         (beginning-of-line)
153         (setq size
154               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
155                                       (line-end-position)
156                                       t)
157                    (match-string 1)))
158         (beginning-of-line)
159         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
160           (let ((structure (ignore-errors (read (current-buffer)))))
161             (while (and (consp structure)
162                         (not (stringp (car structure))))
163               (setq structure (car structure)))
164             (setq lines (nth 7 structure))))
165         (delete-region (line-beginning-position) (line-end-position))
166         (insert (format "211 %s Article retrieved." article))
167         (forward-line 1)
168         (when size
169           (insert (format "Chars: %s\n" size)))
170         (when lines
171           (insert (format "Lines: %s\n" lines)))
172         (re-search-forward "^\r$")
173         (delete-region (line-beginning-position) (line-end-position))
174         (insert ".")
175         (forward-line 1)))))
176
177 (defun nnimap-get-length ()
178   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
179        (string-to-number (match-string 1))))
180
181 (defun nnimap-article-ranges (ranges)
182   (let (result)
183     (cond
184      ((numberp ranges)
185       (number-to-string ranges))
186      ((numberp (cdr ranges))
187       (format "%d:%d" (car ranges) (cdr ranges)))
188      (t
189       (dolist (elem ranges)
190         (push
191          (if (consp elem)
192              (format "%d:%d" (car elem) (cdr elem))
193            (number-to-string elem))
194          result))
195       (mapconcat #'identity (nreverse result) ",")))))
196
197 (deffoo nnimap-open-server (server &optional defs)
198   (if (nnimap-server-opened server)
199       t
200     (unless (assq 'nnimap-address defs)
201       (setq defs (append defs (list (list 'nnimap-address server)))))
202     (nnoo-change-server 'nnimap server defs)
203     (or (nnimap-find-connection nntp-server-buffer)
204         (nnimap-open-connection nntp-server-buffer))))
205
206 (defun nnimap-make-process-buffer (buffer)
207   (with-current-buffer
208       (generate-new-buffer (format "*nnimap %s %s %s*"
209                                    nnimap-address nnimap-server-port
210                                    (gnus-buffer-exists-p buffer)))
211     (mm-disable-multibyte)
212     (buffer-disable-undo)
213     (gnus-add-buffer)
214     (set (make-local-variable 'after-change-functions) nil)
215     (set (make-local-variable 'nnimap-object)
216          (make-nnimap :server (nnoo-current-server '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               (let ((uidnext (nth 5 (car marks))))
423                 (setq high (if uidnext
424                                (1- uidnext)
425                              (nth 3 (car marks)))
426                       low (or (nth 4 (car marks)) uidnext)))))
427           (erase-buffer)
428           (insert
429            (format
430             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
431         t))))
432
433 (deffoo nnimap-request-create-group (group &optional server args)
434   (when (nnimap-possibly-change-group nil server)
435     (with-current-buffer (nnimap-buffer)
436       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
437
438 (deffoo nnimap-request-delete-group (group &optional force server)
439   (when (nnimap-possibly-change-group nil server)
440     (with-current-buffer (nnimap-buffer)
441       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
442
443 (deffoo nnimap-request-expunge-group (group &optional server)
444   (when (nnimap-possibly-change-group group server)
445     (with-current-buffer (nnimap-buffer)
446       (car (nnimap-command "EXPUNGE")))))
447
448 (defun nnimap-get-flags (spec)
449   (let ((articles nil)
450         elems)
451     (with-current-buffer (nnimap-buffer)
452       (erase-buffer)
453       (nnimap-wait-for-response (nnimap-send-command
454                                  "UID FETCH %s FLAGS" spec))
455       (goto-char (point-min))
456       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
457         (setq elems (nnimap-parse-line (match-string 1)))
458         (push (cons (string-to-number (cadr (member "UID" elems)))
459                     (cadr (member "FLAGS" elems)))
460               articles)))
461     (nreverse articles)))
462
463 (deffoo nnimap-close-group (group &optional server)
464   t)
465
466 (deffoo nnimap-request-move-article (article group server accept-form
467                                              &optional last internal-move-group)
468   (with-temp-buffer
469     (when (nnimap-request-article article group server (current-buffer))
470       ;; If the move is internal (on the same server), just do it the easy
471       ;; way.
472       (let ((message-id (message-field-value "message-id")))
473         (if internal-move-group
474             (let ((result
475                    (with-current-buffer (nnimap-buffer)
476                      (nnimap-command "UID COPY %d %S"
477                                      article
478                                      (utf7-encode internal-move-group t)))))
479               (when (car result)
480                 (nnimap-delete-article article)
481                 (cons internal-move-group
482                       (nnimap-find-article-by-message-id
483                        internal-move-group message-id))))
484           ;; Move the article to a different method.
485           (let ((result (eval accept-form)))
486             (when result
487               (nnimap-delete-article article)
488               result)))))))
489
490 (deffoo nnimap-request-expire-articles (articles group &optional server force)
491   (cond
492    ((null articles)
493     nil)
494    ((not (nnimap-possibly-change-group group server))
495     articles)
496    ((and force
497          (eq nnmail-expiry-target 'delete))
498     (unless (nnimap-delete-article articles)
499       (message "Article marked for deletion, but not expunged."))
500     nil)
501    (t
502     (let ((deletable-articles
503            (if (or force
504                    (eq nnmail-expiry-wait 'immediate))
505                articles
506              (gnus-sorted-intersection
507               articles
508               (nnimap-find-expired-articles group)))))
509       (if (null deletable-articles)
510           articles
511         (if (eq nnmail-expiry-target 'delete)
512             (nnimap-delete-article deletable-articles)
513           (setq deletable-articles
514                 (nnimap-process-expiry-targets
515                  deletable-articles group server)))
516         ;; Return the articles we didn't delete.
517         (gnus-sorted-complement articles deletable-articles))))))
518
519 (defun nnimap-process-expiry-targets (articles group server)
520   (let ((deleted-articles nil))
521     (dolist (article articles)
522       (let ((target nnmail-expiry-target))
523         (with-temp-buffer
524           (when (nnimap-request-article article group server (current-buffer))
525             (message "Expiring article %s:%d" group article)
526             (when (functionp target)
527               (setq target (funcall target group)))
528             (when (and target
529                        (not (eq target 'delete)))
530               (if (or (gnus-request-group target t)
531                       (gnus-request-create-group target))
532                   (nnmail-expiry-target-group target group)
533                 (setq target nil)))
534             (when target
535               (push article deleted-articles))))))
536     ;; Change back to the current group again.
537     (nnimap-possibly-change-group group server)
538     (setq deleted-articles (nreverse deleted-articles))
539     (nnimap-delete-article deleted-articles)
540     deleted-articles))
541
542 (defun nnimap-find-expired-articles (group)
543   (let ((cutoff (nnmail-expired-article-p group nil nil)))
544     (with-current-buffer (nnimap-buffer)
545       (let ((result
546              (nnimap-command
547               "UID SEARCH SENTBEFORE %s"
548               (format-time-string
549                (format "%%d-%s-%%Y"
550                        (upcase
551                         (car (rassoc (nth 4 (decode-time cutoff))
552                                      parse-time-months))))
553                cutoff))))
554         (and (car result)
555              (delete 0 (mapcar #'string-to-number
556                                (cdr (assoc "SEARCH" (cdr result))))))))))
557
558
559 (defun nnimap-find-article-by-message-id (group message-id)
560   (when (nnimap-possibly-change-group group nil)
561     (with-current-buffer (nnimap-buffer)
562       (let ((result
563              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
564             article)
565         (when (car result)
566           ;; Select the last instance of the message in the group.
567           (and (setq article
568                      (car (last (assoc "SEARCH" (cdr result)))))
569                (string-to-number article)))))))
570
571 (defun nnimap-delete-article (articles)
572   (with-current-buffer (nnimap-buffer)
573     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
574                     (nnimap-article-ranges articles))
575     (cond
576      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
577       (nnimap-command "UID EXPUNGE %s"
578                       (nnimap-article-ranges articles))
579       t)
580      (nnimap-expunge
581       (nnimap-command "EXPUNGE")
582       t)
583      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
584                                 "server doesn't support UIDPLUS, so we won't "
585                                 "delete this article now"))))))
586
587 (deffoo nnimap-request-scan (&optional group server)
588   (when (and (nnimap-possibly-change-group nil server)
589              nnimap-inbox
590              nnimap-split-methods)
591     (message "nnimap %s splitting mail..." server)
592     (nnimap-split-incoming-mail)))
593
594 (defun nnimap-marks-to-flags (marks)
595   (let (flags flag)
596     (dolist (mark marks)
597       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
598         (push flag flags)))
599     flags))
600
601 (deffoo nnimap-request-set-mark (group actions &optional server)
602   (when (nnimap-possibly-change-group group server)
603     (let (sequence)
604       (with-current-buffer (nnimap-buffer)
605         ;; Just send all the STORE commands without waiting for
606         ;; response.  If they're successful, they're successful.
607         (dolist (action actions)
608           (destructuring-bind (range action marks) action
609             (let ((flags (nnimap-marks-to-flags marks)))
610               (when flags
611                 (setq sequence (nnimap-send-command
612                                 "UID STORE %s %sFLAGS.SILENT (%s)"
613                                 (nnimap-article-ranges range)
614                                 (if (eq action 'del)
615                                     "-"
616                                   "+")
617                                 (mapconcat #'identity flags " ")))))))
618         ;; Wait for the last command to complete to avoid later
619         ;; syncronisation problems with the stream.
620         (when sequence
621           (nnimap-wait-for-response sequence))))))
622
623 (deffoo nnimap-request-accept-article (group &optional server last)
624   (when (nnimap-possibly-change-group nil server)
625     (nnmail-check-syntax)
626     (let ((message (buffer-string))
627           (message-id (message-field-value "message-id"))
628           sequence)
629       (with-current-buffer (nnimap-buffer)
630         (setq sequence (nnimap-send-command
631                         "APPEND %S {%d}" (utf7-encode group t)
632                         (length message)))
633         (process-send-string (get-buffer-process (current-buffer)) message)
634         (process-send-string (get-buffer-process (current-buffer))
635                              (if (nnimap-newlinep nnimap-object)
636                                  "\n"
637                                "\r\n"))
638         (let ((result (nnimap-get-response sequence)))
639           (when result
640             (cons group
641                   (nnimap-find-article-by-message-id group message-id))))))))
642
643 (defun nnimap-add-cr ()
644   (goto-char (point-min))
645   (while (re-search-forward "\r?\n" nil t)
646     (replace-match "\r\n" t t)))
647
648 (defun nnimap-get-groups ()
649   (let ((result (nnimap-command "LIST \"\" \"*\""))
650         groups)
651     (when (car result)
652       (dolist (line (cdr result))
653         (when (and (equal (car line) "LIST")
654                    (not (and (caadr line)
655                              (string-match "noselect" (caadr line)))))
656           (push (car (last line)) groups)))
657       (nreverse groups))))
658
659 (deffoo nnimap-request-list (&optional server)
660   (nnimap-possibly-change-group nil server)
661   (with-current-buffer nntp-server-buffer
662     (erase-buffer)
663     (let ((groups
664            (with-current-buffer (nnimap-buffer)
665              (nnimap-get-groups)))
666           sequences responses)
667       (when groups
668         (with-current-buffer (nnimap-buffer)
669           (setf (nnimap-group nnimap-object) nil)
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         (setf (nnimap-group nnimap-object) nil)
720         (dolist (elem groups)
721           (if (and qresyncp
722                    (nth 2 elem))
723               (push
724                (list 'qresync
725                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
726                                           (car elem)
727                                           (car (nth 2 elem))
728                                           (cdr (nth 2 elem)))
729                      nil
730                      (car elem))
731                sequences)
732             (let ((start
733                    (if (nth 1 elem)
734                        ;; Fetch the last 100 flags.
735                        (max 1 (- (cdr (nth 1 elem)) 100))
736                      1)))
737               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
738                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
739                           start
740                           (car elem))
741                     sequences))))
742         sequences))))
743
744 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
745   (when (and sequences
746              (nnimap-possibly-change-group nil server))
747     (with-current-buffer (nnimap-buffer)
748       ;; Wait for the final data to trickle in.
749       (nnimap-wait-for-response (cadar sequences))
750       ;; Now we should have all the data we need, no matter whether
751       ;; we're QRESYNCING, fetching all the flags from scratch, or
752       ;; just fetching the last 100 flags per group.
753       (nnimap-update-infos (nnimap-flags-to-marks
754                             (nnimap-parse-flags
755                              (nreverse sequences)))
756                            infos)
757       ;; Finally, just return something resembling an active file in
758       ;; the nntp buffer, so that the agent can save the info, too.
759       (with-current-buffer nntp-server-buffer
760         (erase-buffer)
761         (dolist (info infos)
762           (let* ((group (gnus-info-group info))
763                  (active (gnus-active group)))
764             (when active
765               (insert (format "%S %d %d y\n"
766                               (gnus-group-real-name group)
767                               (cdr active)
768                               (car active))))))))))
769
770 (defun nnimap-update-infos (flags infos)
771   (dolist (info infos)
772     (let ((group (gnus-group-real-name (gnus-info-group info))))
773       (nnimap-update-info info (cdr (assoc group flags))))))
774
775 (defun nnimap-update-info (info marks)
776   (when marks
777     (destructuring-bind (existing flags high low uidnext start-article
778                                   permanent-flags) marks
779       (let ((group (gnus-info-group info))
780             (completep (and start-article
781                             (= start-article 1))))
782         (when uidnext
783           (setq high (1- uidnext)))
784         ;; First set the active ranges based on high/low.
785         (if (or completep
786                 (not (gnus-active group)))
787             (gnus-set-active group
788                              (if (and low high)
789                                  (cons low high)
790                                ;; No articles in this group.
791                                (cons uidnext (1- uidnext))))
792           (setcdr (gnus-active group) (or high (1- uidnext))))
793         (unless high
794           (setq high (1- uidnext)))
795         ;; Then update the list of read articles.
796         (let* ((unread
797                 (gnus-compress-sequence
798                  (gnus-set-difference
799                   (gnus-set-difference
800                    existing
801                    (cdr (assoc '%Seen flags)))
802                   (cdr (assoc '%Flagged flags)))))
803                (read (gnus-range-difference
804                       (cons start-article high) unread)))
805           (when (> start-article 1)
806             (setq read
807                   (gnus-range-nconcat
808                    (if (> start-article 1)
809                        (gnus-sorted-range-intersection
810                         (cons 1 (1- start-article))
811                         (gnus-info-read info))
812                      (gnus-info-read info))
813                    read)))
814           (gnus-info-set-read info read)
815           ;; Update the marks.
816           (setq marks (gnus-info-marks info))
817           ;; Note the active level for the next run-through.
818           (let ((active (assq 'active marks)))
819             (if active
820                 (setcdr active (gnus-active group))
821               (push (cons 'active (gnus-active group)) marks)))
822           (dolist (type (cdr nnimap-mark-alist))
823             (let ((old-marks (assoc (car type) marks))
824                   (new-marks
825                    (gnus-compress-sequence
826                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
827                              (assoc (intern (cadr type) obarray) flags)
828                              (assoc (cadr type) flags)))))) ; "\Flagged"
829               (setq marks (delq old-marks marks))
830               (pop old-marks)
831               (when (and old-marks
832                          (> start-article 1))
833                 (setq old-marks (gnus-range-difference
834                                  old-marks
835                                  (cons start-article high)))
836                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
837               (when new-marks
838                 (push (cons (car type) new-marks) marks)))
839             (gnus-info-set-marks info marks t)
840             (nnimap-store-info info (gnus-active group))))))))
841
842 (defun nnimap-store-info (info active)
843   (let* ((group (gnus-group-real-name (gnus-info-group info)))
844          (entry (assoc group nnimap-current-infos)))
845     (if entry
846         (setcdr entry (list info active))
847       (push (list group info active) nnimap-current-infos))))
848
849 (defun nnimap-flags-to-marks (groups)
850   (let (data group totalp uidnext articles start-article mark permanent-flags)
851     (dolist (elem groups)
852       (setq group (car elem)
853             uidnext (nth 1 elem)
854             start-article (nth 2 elem)
855             permanent-flags (nth 3 elem)
856             articles (nthcdr 4 elem))
857       (let ((high (caar articles))
858             marks low existing)
859         (dolist (article articles)
860           (setq low (car article))
861           (push (car article) existing)
862           (dolist (flag (cdr article))
863             (setq mark (assoc flag marks))
864             (if (not mark)
865                 (push (list flag (car article)) marks)
866               (setcdr mark (cons (car article) (cdr mark))))))
867         (push (list group existing marks high low uidnext start-article
868                     permanent-flags)
869               data)))
870     data))
871
872 (defun nnimap-parse-flags (sequences)
873   (goto-char (point-min))
874   ;; Change \Delete etc to %Delete, so that the reader can read it.
875   (subst-char-in-region (point-min) (point-max)
876                         ?\\ ?% t)
877   (let (start end articles groups uidnext elems permanent-flags)
878     (dolist (elem sequences)
879       (destructuring-bind (group-sequence flag-sequence totalp group) elem
880         (setq start (point))
881         ;; The EXAMINE was successful.
882         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
883                    (progn
884                      (forward-line 1)
885                      (setq end (point))
886                      (goto-char start)
887                      (setq permanent-flags
888                            (and (search-forward "PERMANENTFLAGS "
889                                                  (or end (point-min)) t)
890                                 (read (current-buffer))))
891                      (goto-char start)
892                      (setq uidnext
893                            (and (search-forward "UIDNEXT "
894                                                  (or end (point-min)) t)
895                                 (read (current-buffer))))
896                      (goto-char end)
897                      (forward-line -1))
898                    ;; The UID FETCH FLAGS was successful.
899                    (search-forward (format "\n%d OK " flag-sequence) nil t))
900           (setq start (point))
901           (goto-char end)
902           (while (search-forward " FETCH " start t)
903             (setq elems (read (current-buffer)))
904             (push (cons (cadr (memq 'UID elems))
905                         (cadr (memq 'FLAGS elems)))
906                   articles))
907           (push (nconc (list group uidnext totalp permanent-flags) articles)
908                 groups)
909           (setq articles nil))))
910     groups))
911
912 (defun nnimap-find-process-buffer (buffer)
913   (cadr (assoc buffer nnimap-connection-alist)))
914
915 (deffoo nnimap-request-post (&optional server)
916   (setq nnimap-status-string "Read-only server")
917   nil)
918
919 (defun nnimap-possibly-change-group (group server)
920   (let ((open-result t))
921     (when (and server
922                (not (nnimap-server-opened server)))
923       (setq open-result (nnimap-open-server server)))
924     (cond
925      ((not open-result)
926       nil)
927      ((not group)
928       t)
929      (t
930       (with-current-buffer (nnimap-buffer)
931         (if (equal group (nnimap-group nnimap-object))
932             t
933           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
934             (when (car result)
935               (setf (nnimap-group nnimap-object) group
936                     (nnimap-select-result nnimap-object) result)
937               result))))))))
938
939 (defun nnimap-find-connection (buffer)
940   "Find the connection delivering to BUFFER."
941   (let ((entry (assoc buffer nnimap-connection-alist)))
942     (when entry
943       (if (and (buffer-name (cadr entry))
944                (get-buffer-process (cadr entry))
945                (memq (process-status (get-buffer-process (cadr entry)))
946                      '(open run)))
947           (get-buffer-process (cadr entry))
948         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
949         nil))))
950
951 (defvar nnimap-sequence 0)
952
953 (defun nnimap-send-command (&rest args)
954   (process-send-string
955    (get-buffer-process (current-buffer))
956    (nnimap-log-command
957     (format "%d %s%s\n"
958             (incf nnimap-sequence)
959             (apply #'format args)
960             (if (nnimap-newlinep nnimap-object)
961                 ""
962               "\r"))))
963   nnimap-sequence)
964
965 (defun nnimap-log-command (command)
966   (with-current-buffer (get-buffer-create "*imap log*")
967     (goto-char (point-max))
968     (insert (format-time-string "%H:%M:%S") " " command))
969   command)
970
971 (defun nnimap-command (&rest args)
972   (erase-buffer)
973   (let* ((sequence (apply #'nnimap-send-command args))
974          (response (nnimap-get-response sequence)))
975     (if (equal (caar response) "OK")
976         (cons t response)
977       (nnheader-report 'nnimap "%s"
978                        (mapconcat (lambda (a)
979                                     (format "%s" a))
980                                   (car response) " "))
981       nil)))
982
983 (defun nnimap-get-response (sequence)
984   (nnimap-wait-for-response sequence)
985   (nnimap-parse-response))
986
987 (defun nnimap-wait-for-connection ()
988   (let ((process (get-buffer-process (current-buffer))))
989     (goto-char (point-min))
990     (while (and (memq (process-status process)
991                       '(open run))
992                 (not (re-search-forward "^\\* .*\n" nil t)))
993       (nnheader-accept-process-output process)
994       (goto-char (point-min)))
995     (forward-line -1)
996     (and (looking-at "\\* \\([A-Z0-9]+\\)")
997          (match-string 1))))
998
999 (defun nnimap-wait-for-response (sequence &optional messagep)
1000   (let ((process (get-buffer-process (current-buffer))))
1001     (goto-char (point-max))
1002     (while (and (memq (process-status process)
1003                       '(open run))
1004                 (not (re-search-backward (format "^%d .*\n" sequence)
1005                                          (max (point-min) (- (point) 500))
1006                                          t)))
1007       (when messagep
1008         (message "Read %dKB" (/ (buffer-size) 1000)))
1009       (nnheader-accept-process-output process)
1010       (goto-char (point-max)))))
1011
1012 (defun nnimap-parse-response ()
1013   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1014         result)
1015     (dolist (line lines)
1016       (push (cdr (nnimap-parse-line line)) result))
1017     ;; Return the OK/error code first, and then all the "continuation
1018     ;; lines" afterwards.
1019     (cons (pop result)
1020           (nreverse result))))
1021
1022 ;; Parse an IMAP response line lightly.  They look like
1023 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1024 ;; the lines into a list of strings and lists of string.
1025 (defun nnimap-parse-line (line)
1026   (let (char result)
1027     (with-temp-buffer
1028       (insert line)
1029       (goto-char (point-min))
1030       (while (not (eobp))
1031         (if (eql (setq char (following-char)) ? )
1032             (forward-char 1)
1033           (push
1034            (cond
1035             ((eql char ?\[)
1036              (split-string (buffer-substring
1037                             (1+ (point)) (1- (search-forward "]")))))
1038             ((eql char ?\()
1039              (split-string (buffer-substring
1040                             (1+ (point)) (1- (search-forward ")")))))
1041             ((eql char ?\")
1042              (forward-char 1)
1043              (buffer-substring (point) (1- (search-forward "\""))))
1044             (t
1045              (buffer-substring (point) (if (search-forward " " nil t)
1046                                            (1- (point))
1047                                          (goto-char (point-max))))))
1048            result)))
1049       (nreverse result))))
1050
1051 (defun nnimap-last-response-string ()
1052   (save-excursion
1053     (forward-line 1)
1054     (let ((end (point)))
1055       (forward-line -1)
1056       (when (not (bobp))
1057         (forward-line -1)
1058         (while (and (not (bobp))
1059                     (eql (following-char) ?*))
1060           (forward-line -1))
1061         (unless (eql (following-char) ?*)
1062           (forward-line 1)))
1063       (buffer-substring (point) end))))
1064
1065 (defun nnimap-get-responses (sequences)
1066   (let (responses)
1067     (dolist (sequence sequences)
1068       (goto-char (point-min))
1069       (when (re-search-forward (format "^%d " sequence) nil t)
1070         (push (list sequence (nnimap-parse-response))
1071               responses)))
1072     responses))
1073
1074 (defvar nnimap-incoming-split-list nil)
1075
1076 (defun nnimap-fetch-inbox (articles)
1077   (erase-buffer)
1078   (nnimap-wait-for-response
1079    (nnimap-send-command
1080     "UID FETCH %s %s"
1081     (nnimap-article-ranges articles)
1082     (format "(UID %s%s)"
1083             (format
1084              (if (member "IMAP4REV1"
1085                          (nnimap-capabilities nnimap-object))
1086                  "BODY.PEEK[HEADER] BODY.PEEK"
1087                "RFC822.PEEK"))
1088             (if nnimap-split-download-body-default
1089                 "[]"
1090               "[1]")))
1091    t))
1092
1093 (defun nnimap-split-incoming-mail ()
1094   (with-current-buffer (nnimap-buffer)
1095     (let ((nnimap-incoming-split-list nil)
1096           (nnmail-split-methods nnimap-split-methods)
1097           (nnmail-inhibit-default-split-group t)
1098           (groups (nnimap-get-groups))
1099           new-articles)
1100       (erase-buffer)
1101       (nnimap-command "SELECT %S" nnimap-inbox)
1102       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1103       (when new-articles
1104         (nnimap-fetch-inbox new-articles)
1105         (nnimap-transform-split-mail)
1106         (nnheader-ms-strip-cr)
1107         (nnmail-cache-open)
1108         (nnmail-split-incoming (current-buffer)
1109                                #'nnimap-save-mail-spec
1110                                nil nil
1111                                #'nnimap-dummy-active-number
1112                                #'nnimap-save-mail-spec)
1113         (when nnimap-incoming-split-list
1114           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1115                 sequences junk-articles)
1116             ;; Create any groups that doesn't already exist on the
1117             ;; server first.
1118             (dolist (spec specs)
1119               (when (and (not (member (car spec) groups))
1120                          (not (eq (car spec) 'junk)))
1121                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1122             ;; Then copy over all the messages.
1123             (erase-buffer)
1124             (dolist (spec specs)
1125               (let ((group (car spec))
1126                     (ranges (cdr spec)))
1127                 (if (eq group 'junk)
1128                     (setq junk-articles ranges)
1129                   (push (list (nnimap-send-command
1130                                "UID COPY %s %S"
1131                                (nnimap-article-ranges ranges)
1132                                (utf7-encode group t))
1133                               ranges)
1134                         sequences))))
1135             ;; Wait for the last COPY response...
1136             (when sequences
1137               (nnimap-wait-for-response (caar sequences))
1138               ;; And then mark the successful copy actions as deleted,
1139               ;; and possibly expunge them.
1140               (nnimap-mark-and-expunge-incoming
1141                (nnimap-parse-copied-articles sequences))
1142               (nnimap-mark-and-expunge-incoming junk-articles))))))))
1143
1144 (defun nnimap-mark-and-expunge-incoming (range)
1145   (when range
1146     (setq range (nnimap-article-ranges range))
1147     (let ((sequence
1148            (nnimap-send-command
1149             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1150       (cond
1151        ;; If the server supports it, we now delete the message we have
1152        ;; just copied over.
1153        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1154         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1155        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1156        ;; user has configured it.
1157        (nnimap-expunge
1158         (setq sequence (nnimap-send-command "EXPUNGE"))))
1159       (nnimap-wait-for-response sequence))))
1160
1161 (defun nnimap-parse-copied-articles (sequences)
1162   (let (sequence copied range)
1163     (goto-char (point-min))
1164     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1165       (setq sequence (string-to-number (match-string 1)))
1166       (when (setq range (cadr (assq sequence sequences)))
1167         (push (gnus-uncompress-range range) copied)))
1168     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1169
1170 (defun nnimap-new-articles (flags)
1171   (let (new)
1172     (dolist (elem flags)
1173       (when (or (null (cdr elem))
1174                 (and (not (memq '%Deleted (cdr elem)))
1175                      (not (memq '%Seen (cdr elem)))))
1176         (push (car elem) new)))
1177     (gnus-compress-sequence (nreverse new))))
1178
1179 (defun nnimap-make-split-specs (list)
1180   (let ((specs nil)
1181         entry)
1182     (dolist (elem list)
1183       (destructuring-bind (article spec) elem
1184         (dolist (group (delete nil (mapcar #'car spec)))
1185           (unless (setq entry (assoc group specs))
1186             (push (setq entry (list group)) specs))
1187           (setcdr entry (cons article (cdr entry))))))
1188     (dolist (entry specs)
1189       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1190     specs))
1191
1192 (defun nnimap-transform-split-mail ()
1193   (goto-char (point-min))
1194   (let (article bytes)
1195     (block nil
1196       (while (not (eobp))
1197         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1198           (delete-region (point) (progn (forward-line 1) (point)))
1199           (when (eobp)
1200             (return)))
1201         (setq article (match-string 1)
1202               bytes (nnimap-get-length))
1203         (delete-region (line-beginning-position) (line-end-position))
1204         ;; Insert MMDF separator, and a way to remember what this
1205         ;; article UID is.
1206         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1207         (forward-char (1+ bytes))
1208         (setq bytes (nnimap-get-length))
1209         (delete-region (line-beginning-position) (line-end-position))
1210         (forward-char (1+ bytes))
1211         (delete-region (line-beginning-position) (line-end-position))))))
1212
1213 (defun nnimap-dummy-active-number (group &optional server)
1214   1)
1215
1216 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1217   (let (article)
1218     (goto-char (point-min))
1219     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1220         (error "Invalid nnimap mail")
1221       (setq article (string-to-number (match-string 1))))
1222     (push (list article
1223                 (if (eq group-art 'junk)
1224                     (list (cons 'junk 1))
1225                   group-art))
1226           nnimap-incoming-split-list)))
1227
1228 (provide 'nnimap)
1229
1230 ;;; nnimap.el ends here