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