Allow nnimap to just delete 'junk messages when splitting.
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40 (require 'parse-time)
41
42 (nnoo-declare nnimap)
43
44 (defvoo nnimap-address nil
45   "The address of the IMAP server.")
46
47 (defvoo nnimap-server-port nil
48   "The IMAP port used.
49 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
50 it will default to `imap'.")
51
52 (defvoo nnimap-stream 'ssl
53   "How nnimap will talk to the IMAP server.
54 Values are `ssl' and `network'.")
55
56 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
57                                  (if (listp imap-shell-program)
58                                      (car imap-shell-program)
59                                    imap-shell-program)
60                                "ssh %s imapd"))
61
62 (defvoo nnimap-inbox nil
63   "The mail box where incoming mail arrives and should be split out of.")
64
65 (defvoo nnimap-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)
95
96 (defvar nnimap-object nil)
97
98 (defvar nnimap-mark-alist
99   '((read "\\Seen")
100     (tick "\\Flagged")
101     (reply "\\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) (make-nnimap))
216     (push (list buffer (current-buffer)) nnimap-connection-alist)
217     (current-buffer)))
218
219 (defun nnimap-open-shell-stream (name buffer host port)
220   (let ((process-connection-type nil))
221     (start-process name buffer shell-file-name
222                    shell-command-switch
223                    (format-spec
224                     nnimap-shell-program
225                     (format-spec-make
226                      ?s host
227                      ?p port)))))
228
229 (defun nnimap-credentials (address ports)
230   (let (port credentials)
231     ;; Request the credentials from all ports, but only query on the
232     ;; last port if all the previous ones have failed.
233     (while (and (null credentials)
234                 (setq port (pop ports)))
235       (setq credentials
236             (auth-source-user-or-password
237              '("login" "password") address port nil (null ports))))
238     credentials))
239
240 (defun nnimap-open-connection (buffer)
241   (with-current-buffer (nnimap-make-process-buffer buffer)
242     (let* ((coding-system-for-read 'binary)
243            (coding-system-for-write 'binary)
244            (ports
245             (cond
246              ((eq nnimap-stream 'network)
247               (open-network-stream
248                "*nnimap*" (current-buffer) nnimap-address
249                (or nnimap-server-port
250                    (if (netrc-find-service-number "imap")
251                        "imap"
252                      "143")))
253               '("143" "imap"))
254              ((eq nnimap-stream 'shell)
255               (nnimap-open-shell-stream
256                "*nnimap*" (current-buffer) nnimap-address
257                (or nnimap-server-port "imap"))
258               '("imap"))
259              ((eq nnimap-stream 'ssl)
260               (open-tls-stream
261                "*nnimap*" (current-buffer) nnimap-address
262                (or nnimap-server-port
263                    (if (netrc-find-service-number "imaps")
264                        "imaps"
265                      "993")))
266               '("143" "993" "imap" "imaps"))))
267            connection-result login-result credentials)
268       (setf (nnimap-process nnimap-object)
269             (get-buffer-process (current-buffer)))
270       (when (and (nnimap-process nnimap-object)
271                  (memq (process-status (nnimap-process nnimap-object))
272                        '(open run)))
273         (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
274         (when (setq connection-result (nnimap-wait-for-connection))
275           (unless (equal connection-result "PREAUTH")
276             (if (not (setq credentials
277                            (if (eq nnimap-authenticator 'anonymous)
278                                (list "anonymous"
279                                      (message-make-address))
280                              (nnimap-credentials
281                               nnimap-address
282                               (if nnimap-server-port
283                                   (cons (format "%s" nnimap-server-port) ports)
284                                 ports)))))
285                 (setq nnimap-object nil)
286               (setq login-result (nnimap-command "LOGIN %S %S"
287                                                  (car credentials)
288                                                  (cadr credentials)))
289               (unless (car login-result)
290                 (delete-process (nnimap-process nnimap-object))
291                 (setq nnimap-object nil))))
292           (when nnimap-object
293             (setf (nnimap-capabilities nnimap-object)
294                   (mapcar
295                    #'upcase
296                    (or (nnimap-find-parameter "CAPABILITY" (cdr login-result))
297                        (nnimap-find-parameter
298                         "CAPABILITY" (cdr (nnimap-command "CAPABILITY"))))))
299             (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
300               (nnimap-command "ENABLE QRESYNC"))
301             t))))))
302
303 (defun nnimap-find-parameter (parameter elems)
304   (let (result)
305     (dolist (elem elems)
306       (cond
307        ((equal (car elem) parameter)
308         (setq result (cdr elem)))
309        ((and (equal (car elem) "OK")
310              (consp (cadr elem))
311              (equal (caadr elem) parameter))
312         (setq result (cdr (cadr elem))))))
313     result))
314
315 (deffoo nnimap-close-server (&optional server)
316   t)
317
318 (deffoo nnimap-request-close ()
319   t)
320
321 (deffoo nnimap-server-opened (&optional server)
322   (and (nnoo-current-server-p 'nnimap server)
323        nntp-server-buffer
324        (gnus-buffer-live-p nntp-server-buffer)
325        (nnimap-find-connection nntp-server-buffer)))
326
327 (deffoo nnimap-status-message (&optional server)
328   nnimap-status-string)
329
330 (deffoo nnimap-request-article (article &optional group server to-buffer)
331   (with-current-buffer nntp-server-buffer
332     (let ((result (nnimap-possibly-change-group group server))
333           parts)
334       (when (stringp article)
335         (setq article (nnimap-find-article-by-message-id group article)))
336       (when (and result
337                  article)
338         (erase-buffer)
339         (with-current-buffer (nnimap-buffer)
340           (erase-buffer)
341           (when nnimap-fetch-partial-articles
342             (if (eq nnimap-fetch-partial-articles t)
343                 (setq parts '(1))
344               (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
345               (goto-char (point-min))
346               (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
347                 (let ((structure (ignore-errors (read (current-buffer)))))
348                   (setq parts (nnimap-find-wanted-parts structure))))))
349           (setq result
350                 (nnimap-command
351                  (if (member "IMAP4REV1" (nnimap-capabilities nnimap-object))
352                      "UID FETCH %d BODY.PEEK[]"
353                    "UID FETCH %d RFC822.PEEK")
354                  article))
355           ;; Check that we really got an article.
356           (goto-char (point-min))
357           (unless (looking-at "\\* [0-9]+ FETCH")
358             (setq result nil)))
359         (let ((buffer (nnimap-find-process-buffer (current-buffer))))
360           (when (car result)
361             (with-current-buffer (or to-buffer nntp-server-buffer)
362               (insert-buffer-substring buffer)
363               (goto-char (point-min))
364               (let ((bytes (nnimap-get-length)))
365                 (delete-region (line-beginning-position)
366                                (progn (forward-line 1) (point)))
367                 (goto-char (+ (point) bytes))
368                 (delete-region (point) (point-max))
369                 (nnheader-ms-strip-cr))
370               (cons group article))))))))
371
372 (defun nnimap-find-wanted-parts (structure)
373   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
374
375 (defun nnimap-find-wanted-parts-1 (structure prefix)
376   (let ((num 1)
377         parts)
378     (while (consp (car structure))
379       (let ((sub (pop structure)))
380         (if (consp (car sub))
381             (push (nnimap-find-wanted-parts-1
382                    sub (if (string= prefix "")
383                            (number-to-string num)
384                          (format "%s.%s" prefix num)))
385                   parts)
386           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub))))
387             (when (string-match nnimap-fetch-partial-articles type)
388               (push (if (string= prefix "")
389                         (number-to-string num)
390                       (format "%s.%s" prefix num))
391                     parts)))
392           (incf num))))
393     (nreverse parts)))
394
395 (deffoo nnimap-request-group (group &optional server dont-check info)
396   (let ((result (nnimap-possibly-change-group group server))
397         articles active marks high low)
398     (with-current-buffer nntp-server-buffer
399       (when result
400         (if (and dont-check
401                  (setq active (nth 2 (assoc group nnimap-current-infos))))
402             (insert (format "211 %d %d %d %S\n"
403                             (- (cdr active) (car active))
404                             (car active)
405                             (cdr active)
406                             group))
407           (with-current-buffer (nnimap-buffer)
408             (erase-buffer)
409             (let ((group-sequence
410                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
411                   (flag-sequence
412                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
413               (nnimap-wait-for-response flag-sequence)
414               (setq marks
415                     (nnimap-flags-to-marks
416                      (nnimap-parse-flags
417                       (list (list group-sequence flag-sequence 1 group)))))
418               (when info
419                 (nnimap-update-infos marks (list info)))
420               (goto-char (point-max))
421               (cond
422                (marks
423                 (setq high (nth 3 (car marks))
424                       low (nth 4 (car marks))))
425                ((re-search-backward "UIDNEXT \\([0-9]+\\)" nil t)
426                 (setq high (1- (string-to-number (match-string 1)))
427                       low 1)))))
428           (erase-buffer)
429           (insert
430            (format
431             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
432         t))))
433
434 (deffoo nnimap-request-create-group (group &optional server args)
435   (when (nnimap-possibly-change-group nil server)
436     (with-current-buffer (nnimap-buffer)
437       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
438
439 (deffoo nnimap-request-delete-group (group &optional force server)
440   (when (nnimap-possibly-change-group nil server)
441     (with-current-buffer (nnimap-buffer)
442       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
443
444 (deffoo nnimap-request-expunge-group (group &optional server)
445   (when (nnimap-possibly-change-group group server)
446     (with-current-buffer (nnimap-buffer)
447       (car (nnimap-command "EXPUNGE")))))
448
449 (defun nnimap-get-flags (spec)
450   (let ((articles nil)
451         elems)
452     (with-current-buffer (nnimap-buffer)
453       (erase-buffer)
454       (nnimap-wait-for-response (nnimap-send-command
455                                  "UID FETCH %s FLAGS" spec))
456       (goto-char (point-min))
457       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
458         (setq elems (nnimap-parse-line (match-string 1)))
459         (push (cons (string-to-number (cadr (member "UID" elems)))
460                     (cadr (member "FLAGS" elems)))
461               articles)))
462     (nreverse articles)))
463
464 (deffoo nnimap-close-group (group &optional server)
465   t)
466
467 (deffoo nnimap-request-move-article (article group server accept-form
468                                              &optional last internal-move-group)
469   (with-temp-buffer
470     (when (nnimap-request-article article group server (current-buffer))
471       ;; If the move is internal (on the same server), just do it the easy
472       ;; way.
473       (let ((message-id (message-field-value "message-id")))
474         (if internal-move-group
475             (let ((result
476                    (with-current-buffer (nnimap-buffer)
477                      (nnimap-command "UID COPY %d %S"
478                                      article
479                                      (utf7-encode internal-move-group t)))))
480               (when (car result)
481                 (nnimap-delete-article article)
482                 (cons internal-move-group
483                       (nnimap-find-article-by-message-id
484                        internal-move-group message-id))))
485           ;; Move the article to a different method.
486           (let ((result (eval accept-form)))
487             (when result
488               (nnimap-delete-article article)
489               result)))))))
490
491 (deffoo nnimap-request-expire-articles (articles group &optional server force)
492   (cond
493    ((null articles)
494     nil)
495    ((not (nnimap-possibly-change-group group server))
496     articles)
497    ((and force
498          (eq nnmail-expiry-target 'delete))
499     (unless (nnimap-delete-article articles)
500       (message "Article marked for deletion, but not expunged."))
501     nil)
502    (t
503     (let ((deletable-articles
504            (if force
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              (equal group nnimap-inbox)
590              nnimap-inbox
591              nnimap-split-methods)
592     (message "nnimap %s splitting mail..." server)
593     (nnimap-split-incoming-mail)))
594
595 (defun nnimap-marks-to-flags (marks)
596   (let (flags flag)
597     (dolist (mark marks)
598       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
599         (push flag flags)))
600     flags))
601
602 (deffoo nnimap-request-set-mark (group actions &optional server)
603   (when (nnimap-possibly-change-group group server)
604     (let (sequence)
605       (with-current-buffer (nnimap-buffer)
606         ;; Just send all the STORE commands without waiting for
607         ;; response.  If they're successful, they're successful.
608         (dolist (action actions)
609           (destructuring-bind (range action marks) action
610             (let ((flags (nnimap-marks-to-flags marks)))
611               (when flags
612                 (setq sequence (nnimap-send-command
613                                 "UID STORE %s %sFLAGS.SILENT (%s)"
614                                 (nnimap-article-ranges range)
615                                 (if (eq action 'del)
616                                     "-"
617                                   "+")
618                                 (mapconcat #'identity flags " ")))))))
619         ;; Wait for the last command to complete to avoid later
620         ;; syncronisation problems with the stream.
621         (when sequence
622           (nnimap-wait-for-response sequence))))))
623
624 (deffoo nnimap-request-accept-article (group &optional server last)
625   (when (nnimap-possibly-change-group nil server)
626     (nnmail-check-syntax)
627     (let ((message (buffer-string))
628           (message-id (message-field-value "message-id"))
629           sequence)
630       (with-current-buffer (nnimap-buffer)
631         (setq sequence (nnimap-send-command
632                         "APPEND %S {%d}" (utf7-encode group t)
633                         (length message)))
634         (process-send-string (get-buffer-process (current-buffer)) message)
635         (process-send-string (get-buffer-process (current-buffer))
636                              (if (nnimap-newlinep nnimap-object)
637                                  "\n"
638                                "\r\n"))
639         (let ((result (nnimap-get-response sequence)))
640           (when result
641             (cons group
642                   (nnimap-find-article-by-message-id group message-id))))))))
643
644 (defun nnimap-add-cr ()
645   (goto-char (point-min))
646   (while (re-search-forward "\r?\n" nil t)
647     (replace-match "\r\n" t t)))
648
649 (defun nnimap-get-groups ()
650   (let ((result (nnimap-command "LIST \"\" \"*\""))
651         groups)
652     (when (car result)
653       (dolist (line (cdr result))
654         (when (and (equal (car line) "LIST")
655                    (not (and (caadr line)
656                              (string-match "noselect" (caadr line)))))
657           (push (car (last line)) groups)))
658       (nreverse groups))))
659
660 (deffoo nnimap-request-list (&optional server)
661   (nnimap-possibly-change-group nil server)
662   (with-current-buffer nntp-server-buffer
663     (erase-buffer)
664     (let ((groups
665            (with-current-buffer (nnimap-buffer)
666              (nnimap-get-groups)))
667           sequences responses)
668       (when groups
669         (with-current-buffer (nnimap-buffer)
670           (setf (nnimap-group nnimap-object) nil)
671           (dolist (group groups)
672             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
673                         group)
674                   sequences))
675           (nnimap-wait-for-response (caar sequences))
676           (setq responses
677                 (nnimap-get-responses (mapcar #'car sequences))))
678         (dolist (response responses)
679           (let* ((sequence (car response))
680                  (response (cadr response))
681                  (group (cadr (assoc sequence sequences))))
682             (when (and group
683                        (equal (caar response) "OK"))
684               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
685                     highest exists)
686                 (dolist (elem response)
687                   (when (equal (cadr elem) "EXISTS")
688                     (setq exists (string-to-number (car elem)))))
689                 (when uidnext
690                   (setq highest (1- (string-to-number (car uidnext)))))
691                 (cond
692                  ((null highest)
693                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
694                  ((zerop exists)
695                   ;; Empty group.
696                   (insert (format "%S %d %d y\n"
697                                   (utf7-decode group t) highest (1+ highest))))
698                  (t
699                   ;; Return the widest possible range.
700                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
701                                   (or highest exists)))))))))
702         t))))
703
704 (deffoo nnimap-retrieve-group-data-early (server infos)
705   (when (nnimap-possibly-change-group nil server)
706     (with-current-buffer (nnimap-buffer)
707       ;; QRESYNC handling isn't implemented.
708       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
709             marks groups sequences)
710         ;; Go through the infos and gather the data needed to know
711         ;; what and how to request the data.
712         (dolist (info infos)
713           (setq marks (gnus-info-marks info))
714           (push (list (gnus-group-real-name (gnus-info-group info))
715                       (cdr (assq 'active marks))
716                       (cdr (assq 'uid marks)))
717                 groups))
718         ;; Then request the data.
719         (erase-buffer)
720         (setf (nnimap-group nnimap-object) nil)
721         (dolist (elem groups)
722           (if (and qresyncp
723                    (nth 2 elem))
724               (push
725                (list 'qresync
726                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
727                                           (car elem)
728                                           (car (nth 2 elem))
729                                           (cdr (nth 2 elem)))
730                      nil
731                      (car elem))
732                sequences)
733             (let ((start
734                    (if (nth 1 elem)
735                        ;; Fetch the last 100 flags.
736                        (max 1 (- (cdr (nth 1 elem)) 100))
737                      1)))
738               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
739                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
740                           start
741                           (car elem))
742                     sequences))))
743         sequences))))
744
745 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
746   (when (and sequences
747              (nnimap-possibly-change-group nil server))
748     (with-current-buffer (nnimap-buffer)
749       ;; Wait for the final data to trickle in.
750       (nnimap-wait-for-response (cadar sequences))
751       ;; Now we should have all the data we need, no matter whether
752       ;; we're QRESYNCING, fetching all the flags from scratch, or
753       ;; just fetching the last 100 flags per group.
754       (nnimap-update-infos (nnimap-flags-to-marks
755                             (nnimap-parse-flags
756                              (nreverse sequences)))
757                            infos)
758       ;; Finally, just return something resembling an active file in
759       ;; the nntp buffer, so that the agent can save the info, too.
760       (with-current-buffer nntp-server-buffer
761         (erase-buffer)
762         (dolist (info infos)
763           (let* ((group (gnus-info-group info))
764                  (active (gnus-active group)))
765             (when active
766               (insert (format "%S %d %d y\n"
767                               (gnus-group-real-name group)
768                               (cdr active)
769                               (car active))))))))))
770
771 (defun nnimap-update-infos (flags infos)
772   (dolist (info infos)
773     (let ((group (gnus-group-real-name (gnus-info-group info))))
774       (nnimap-update-info info (cdr (assoc group flags))))))
775
776 (defun nnimap-update-info (info marks)
777   (when marks
778     (destructuring-bind (existing flags high low uidnext start-article) marks
779       (let ((group (gnus-info-group info))
780             (completep (and start-article
781                             (= start-article 1))))
782         ;; First set the active ranges based on high/low.
783         (if (or completep
784                 (not (gnus-active group)))
785             (gnus-set-active group
786                              (if high
787                                  (cons low high)
788                                ;; No articles in this group.
789                                (cons (1- uidnext) uidnext)))
790           (setcdr (gnus-active group) high))
791         ;; Then update the list of read articles.
792         (let* ((unread
793                 (gnus-compress-sequence
794                  (gnus-set-difference
795                   (gnus-set-difference
796                    existing
797                    (cdr (assoc "\\Seen" flags)))
798                   (cdr (assoc "\\Flagged" flags)))))
799                (read (gnus-range-difference
800                       (cons start-article high) unread)))
801           (when (> start-article 1)
802             (setq read
803                   (gnus-range-nconcat
804                    (if (> start-article 1)
805                        (gnus-sorted-range-intersection
806                         (cons 1 (1- start-article))
807                         (gnus-info-read info))
808                      (gnus-info-read info))
809                    read)))
810           (gnus-info-set-read info read)
811           ;; Update the marks.
812           (setq marks (gnus-info-marks info))
813           ;; Note the active level for the next run-through.
814           (let ((active (assq 'active marks)))
815             (if active
816                 (setcdr active (gnus-active group))
817               (push (cons 'active (gnus-active group)) marks)))
818           (dolist (type (cdr nnimap-mark-alist))
819             (let ((old-marks (assoc (car type) marks))
820                   (new-marks (gnus-compress-sequence
821                               (cdr (assoc (cadr type) flags)))))
822               (setq marks (delq old-marks marks))
823               (pop old-marks)
824               (when (and old-marks
825                          (> start-article 1))
826                 (setq old-marks (gnus-range-difference
827                                  old-marks
828                                  (cons start-article high)))
829                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
830               (when new-marks
831                 (push (cons (car type) new-marks) marks)))
832             (gnus-info-set-marks info marks t)
833             (nnimap-store-info info (gnus-active group))))))))
834
835 (defun nnimap-store-info (info active)
836   (let* ((group (gnus-group-real-name (gnus-info-group info)))
837          (entry (assoc group nnimap-current-infos)))
838     (if entry
839         (setcdr entry (list info active))
840       (push (list group info active) nnimap-current-infos))))
841
842 (defun nnimap-flags-to-marks (groups)
843   (let (data group totalp uidnext articles start-article mark)
844     (dolist (elem groups)
845       (setq group (car elem)
846             uidnext (cadr elem)
847             start-article (caddr elem)
848             articles (cdddr elem))
849       (let ((high (caar articles))
850             marks low existing)
851         (dolist (article articles)
852           (setq low (car article))
853           (push (car article) existing)
854           (dolist (flag (cdr article))
855             (setq mark (assoc flag marks))
856             (if (not mark)
857                 (push (list flag (car article)) marks)
858               (setcdr mark (cons (car article) (cdr mark)))))
859           (push (list group existing marks high low uidnext start-article)
860                 data))))
861     data))
862
863 (defun nnimap-parse-flags (sequences)
864   (goto-char (point-min))
865   (let (start end articles groups uidnext elems)
866     (dolist (elem sequences)
867       (destructuring-bind (group-sequence flag-sequence totalp group) elem
868         ;; The EXAMINE was successful.
869         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
870                    (progn
871                      (forward-line 1)
872                      (setq start (point))
873                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
874                                                (or end (point-min)) t)
875                          (setq uidnext (string-to-number (match-string 1)))
876                        (setq uidnext nil))
877                      (goto-char start))
878                    ;; The UID FETCH FLAGS was successful.
879                    (search-forward (format "\n%d OK " flag-sequence) nil t))
880           (setq end (point))
881           (goto-char start)
882           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
883             (setq elems (nnimap-parse-line (match-string 1)))
884             (push (cons (string-to-number (cadr (member "UID" elems)))
885                         (cadr (member "FLAGS" elems)))
886                   articles))
887           (push (nconc (list group uidnext totalp) articles) groups)
888           (setq articles nil))))
889     groups))
890
891 (defun nnimap-find-process-buffer (buffer)
892   (cadr (assoc buffer nnimap-connection-alist)))
893
894 (deffoo nnimap-request-post (&optional server)
895   (setq nnimap-status-string "Read-only server")
896   nil)
897
898 (defun nnimap-possibly-change-group (group server)
899   (let ((open-result t))
900     (when (and server
901                (not (nnimap-server-opened server)))
902       (setq open-result (nnimap-open-server server)))
903     (cond
904      ((not open-result)
905       nil)
906      ((not group)
907       t)
908      (t
909       (with-current-buffer (nnimap-buffer)
910         (if (equal group (nnimap-group nnimap-object))
911             t
912           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
913             (when (car result)
914               (setf (nnimap-group nnimap-object) group
915                     (nnimap-select-result nnimap-object) result)
916               result))))))))
917
918 (defun nnimap-find-connection (buffer)
919   "Find the connection delivering to BUFFER."
920   (let ((entry (assoc buffer nnimap-connection-alist)))
921     (when entry
922       (if (and (buffer-name (cadr entry))
923                (get-buffer-process (cadr entry))
924                (memq (process-status (get-buffer-process (cadr entry)))
925                      '(open run)))
926           (get-buffer-process (cadr entry))
927         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
928         nil))))
929
930 (defvar nnimap-sequence 0)
931
932 (defun nnimap-send-command (&rest args)
933   (process-send-string
934    (get-buffer-process (current-buffer))
935    (nnimap-log-command
936     (format "%d %s%s\n"
937             (incf nnimap-sequence)
938             (apply #'format args)
939             (if (nnimap-newlinep nnimap-object)
940                 ""
941               "\r"))))
942   nnimap-sequence)
943
944 (defun nnimap-log-command (command)
945   (with-current-buffer (get-buffer-create "*imap log*")
946     (goto-char (point-max))
947     (insert (format-time-string "%H:%M:%S") " " command))
948   command)
949
950 (defun nnimap-command (&rest args)
951   (erase-buffer)
952   (let* ((sequence (apply #'nnimap-send-command args))
953          (response (nnimap-get-response sequence)))
954     (if (equal (caar response) "OK")
955         (cons t response)
956       (nnheader-report 'nnimap "%s"
957                        (mapconcat (lambda (a)
958                                     (format "%s" a))
959                                   (car response) " "))
960       nil)))
961
962 (defun nnimap-get-response (sequence)
963   (nnimap-wait-for-response sequence)
964   (nnimap-parse-response))
965
966 (defun nnimap-wait-for-connection ()
967   (let ((process (get-buffer-process (current-buffer))))
968     (goto-char (point-min))
969     (while (and (memq (process-status process)
970                       '(open run))
971                 (not (re-search-forward "^\\* .*\n" nil t)))
972       (nnheader-accept-process-output process)
973       (goto-char (point-min)))
974     (forward-line -1)
975     (and (looking-at "\\* \\([A-Z0-9]+\\)")
976          (match-string 1))))
977
978 (defun nnimap-wait-for-response (sequence &optional messagep)
979   (let ((process (get-buffer-process (current-buffer))))
980     (goto-char (point-max))
981     (while (and (memq (process-status process)
982                       '(open run))
983                 (not (re-search-backward (format "^%d .*\n" sequence)
984                                          (max (point-min) (- (point) 500))
985                                          t)))
986       (when messagep
987         (message "Read %dKB" (/ (buffer-size) 1000)))
988       (nnheader-accept-process-output process)
989       (goto-char (point-max)))))
990
991 (defun nnimap-parse-response ()
992   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
993         result)
994     (dolist (line lines)
995       (push (cdr (nnimap-parse-line line)) result))
996     ;; Return the OK/error code first, and then all the "continuation
997     ;; lines" afterwards.
998     (cons (pop result)
999           (nreverse result))))
1000
1001 ;; Parse an IMAP response line lightly.  They look like
1002 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1003 ;; the lines into a list of strings and lists of string.
1004 (defun nnimap-parse-line (line)
1005   (let (char result)
1006     (with-temp-buffer
1007       (insert line)
1008       (goto-char (point-min))
1009       (while (not (eobp))
1010         (if (eql (setq char (following-char)) ? )
1011             (forward-char 1)
1012           (push
1013            (cond
1014             ((eql char ?\[)
1015              (split-string (buffer-substring
1016                             (1+ (point)) (1- (search-forward "]")))))
1017             ((eql char ?\()
1018              (split-string (buffer-substring
1019                             (1+ (point)) (1- (search-forward ")")))))
1020             ((eql char ?\")
1021              (forward-char 1)
1022              (buffer-substring (point) (1- (search-forward "\""))))
1023             (t
1024              (buffer-substring (point) (if (search-forward " " nil t)
1025                                            (1- (point))
1026                                          (goto-char (point-max))))))
1027            result)))
1028       (nreverse result))))
1029
1030 (defun nnimap-last-response-string ()
1031   (save-excursion
1032     (forward-line 1)
1033     (let ((end (point)))
1034       (forward-line -1)
1035       (when (not (bobp))
1036         (forward-line -1)
1037         (while (and (not (bobp))
1038                     (eql (following-char) ?*))
1039           (forward-line -1))
1040         (unless (eql (following-char) ?*)
1041           (forward-line 1)))
1042       (buffer-substring (point) end))))
1043
1044 (defun nnimap-get-responses (sequences)
1045   (let (responses)
1046     (dolist (sequence sequences)
1047       (goto-char (point-min))
1048       (when (re-search-forward (format "^%d " sequence) nil t)
1049         (push (list sequence (nnimap-parse-response))
1050               responses)))
1051     responses))
1052
1053 (defvar nnimap-incoming-split-list nil)
1054
1055 (defun nnimap-fetch-inbox (articles)
1056   (erase-buffer)
1057   (nnimap-wait-for-response
1058    (nnimap-send-command
1059     "UID FETCH %s %s"
1060     (nnimap-article-ranges articles)
1061     (format "(UID %s%s)"
1062             (format
1063              (if (member "IMAP4REV1"
1064                          (nnimap-capabilities nnimap-object))
1065                  "BODY.PEEK[HEADER] BODY.PEEK"
1066                "RFC822.PEEK"))
1067             (if nnimap-split-download-body-default
1068                 "[]"
1069               "[1]")))
1070    t))
1071
1072 (defun nnimap-split-incoming-mail ()
1073   (with-current-buffer (nnimap-buffer)
1074     (let ((nnimap-incoming-split-list nil)
1075           (nnmail-split-methods nnimap-split-methods)
1076           (nnmail-inhibit-default-split-group t)
1077           (groups (nnimap-get-groups))
1078           new-articles)
1079       (erase-buffer)
1080       (nnimap-command "SELECT %S" nnimap-inbox)
1081       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1082       (when new-articles
1083         (nnimap-fetch-inbox new-articles)
1084         (nnimap-transform-split-mail)
1085         (nnheader-ms-strip-cr)
1086         (nnmail-cache-open)
1087         (nnmail-split-incoming (current-buffer)
1088                                #'nnimap-save-mail-spec
1089                                nil nil
1090                                #'nnimap-dummy-active-number
1091                                #'nnimap-save-mail-spec)
1092         (when nnimap-incoming-split-list
1093           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1094                 sequences junk-articles)
1095             ;; Create any groups that doesn't already exist on the
1096             ;; server first.
1097             (dolist (spec specs)
1098               (when (and (not (member (car spec) groups))
1099                          (not (eq (car spec) 'junk)))
1100                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1101             ;; Then copy over all the messages.
1102             (erase-buffer)
1103             (dolist (spec specs)
1104               (let ((group (car spec))
1105                     (ranges (cdr spec)))
1106                 (if (eq group 'junk)
1107                     (setq junk-articles ranges)
1108                   (push (list (nnimap-send-command
1109                                "UID COPY %s %S"
1110                                (nnimap-article-ranges ranges)
1111                                (utf7-encode group t))
1112                               ranges)
1113                         sequences))))
1114             ;; Wait for the last COPY response...
1115             (when sequences
1116               (nnimap-wait-for-response (caar sequences))
1117               ;; And then mark the successful copy actions as deleted,
1118               ;; and possibly expunge them.
1119               (nnimap-mark-and-expunge-incoming
1120                (nnimap-parse-copied-articles sequences))
1121               (nnimap-mark-and-expunge-incoming junk-articles))))))))
1122
1123 (defun nnimap-mark-and-expunge-incoming (range)
1124   (when range
1125     (setq range (nnimap-article-ranges range))
1126     (let ((sequence
1127            (nnimap-send-command
1128             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1129       (cond
1130        ;; If the server supports it, we now delete the message we have
1131        ;; just copied over.
1132        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1133         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1134        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1135        ;; user has configured it.
1136        (nnimap-expunge
1137         (setq sequence (nnimap-send-command "EXPUNGE"))))
1138       (nnimap-wait-for-response sequence))))
1139
1140 (defun nnimap-parse-copied-articles (sequences)
1141   (let (sequence copied range)
1142     (goto-char (point-min))
1143     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1144       (setq sequence (string-to-number (match-string 1)))
1145       (when (setq range (cadr (assq sequence sequences)))
1146         (push (gnus-uncompress-range range) copied)))
1147     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1148
1149 (defun nnimap-new-articles (flags)
1150   (let (new)
1151     (dolist (elem flags)
1152       (when (or (null (cdr elem))
1153                 (and (not (member "\\Deleted" (cdr elem)))
1154                      (not (member "\\Seen" (cdr elem)))))
1155         (push (car elem) new)))
1156     (gnus-compress-sequence (nreverse new))))
1157
1158 (defun nnimap-make-split-specs (list)
1159   (let ((specs nil)
1160         entry)
1161     (dolist (elem list)
1162       (destructuring-bind (article spec) elem
1163         (dolist (group (delete nil (mapcar #'car spec)))
1164           (unless (setq entry (assoc group specs))
1165             (push (setq entry (list group)) specs))
1166           (setcdr entry (cons article (cdr entry))))))
1167     (dolist (entry specs)
1168       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1169     specs))
1170
1171 (defun nnimap-transform-split-mail ()
1172   (goto-char (point-min))
1173   (let (article bytes)
1174     (block nil
1175       (while (not (eobp))
1176         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1177           (delete-region (point) (progn (forward-line 1) (point)))
1178           (when (eobp)
1179             (return)))
1180         (setq article (match-string 1)
1181               bytes (nnimap-get-length))
1182         (delete-region (line-beginning-position) (line-end-position))
1183         ;; Insert MMDF separator, and a way to remember what this
1184         ;; article UID is.
1185         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1186         (forward-char (1+ bytes))
1187         (setq bytes (nnimap-get-length))
1188         (delete-region (line-beginning-position) (line-end-position))
1189         (forward-char (1+ bytes))
1190         (delete-region (line-beginning-position) (line-end-position))))))
1191
1192 (defun nnimap-dummy-active-number (group &optional server)
1193   1)
1194
1195 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1196   (let (article)
1197     (goto-char (point-min))
1198     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1199         (error "Invalid nnimap mail")
1200       (setq article (string-to-number (match-string 1))))
1201     (push (list article
1202                 (if (eq group-art 'junk)
1203                     (list (cons 'junk 1))
1204                   group-art))
1205           nnimap-incoming-split-list)))
1206
1207 (provide 'nnimap)
1208
1209 ;;; nnimap.el ends here