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