(gnus-group-completing-read): Remove all newlines from group names. They mess up...
[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 ;; For Emacs <22.2 and XEmacs.
30 (eval-and-compile
31   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
33 (eval-and-compile
34   (require 'nnheader))
35
36 (eval-when-compile
37   (require 'cl))
38
39 (require 'nnheader)
40 (require 'gnus-util)
41 (require 'gnus)
42 (require 'nnoo)
43 (require 'netrc)
44 (require 'utf7)
45 (require 'tls)
46 (require 'parse-time)
47
48 (autoload 'auth-source-forget-user-or-password "auth-source")
49 (autoload 'auth-source-user-or-password "auth-source")
50
51 (nnoo-declare nnimap)
52
53 (defvoo nnimap-address nil
54   "The address of the IMAP server.")
55
56 (defvoo nnimap-server-port nil
57   "The IMAP port used.
58 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
59 it will default to `imap'.")
60
61 (defvoo nnimap-stream 'ssl
62   "How nnimap will talk to the IMAP server.
63 Values are `ssl', `network', `starttls' or `shell'.")
64
65 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
66                                  (if (listp imap-shell-program)
67                                      (car imap-shell-program)
68                                    imap-shell-program)
69                                "ssh %s imapd"))
70
71 (defvoo nnimap-inbox nil
72   "The mail box where incoming mail arrives and should be split out of.")
73
74 (defvoo nnimap-split-methods nil
75   "How mail is split.
76 Uses the same syntax as nnmail-split-methods")
77
78 (defvoo nnimap-split-fancy nil
79   "Uses the same syntax as nnmail-split-fancy.")
80
81 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
82                         "Emacs 24.1")
83
84 (defvoo nnimap-authenticator nil
85   "How nnimap authenticate itself to the server.
86 Possible choices are nil (use default methods) or `anonymous'.")
87
88 (defvoo nnimap-expunge t
89   "If non-nil, expunge articles after deleting them.
90 This is always done if the server supports UID EXPUNGE, but it's
91 not done by default on servers that doesn't support that command.")
92
93 (defvoo nnimap-streaming t
94   "If non-nil, try to use streaming commands with IMAP servers.
95 Switching this off will make nnimap slower, but it helps with
96 some servers.")
97
98 (defvoo nnimap-connection-alist nil)
99
100 (defvoo nnimap-current-infos nil)
101
102 (defvoo nnimap-fetch-partial-articles nil
103   "If non-nil, Gnus will fetch partial articles.
104 If t, nnimap will fetch only the first part.  If a string, it
105 will fetch all parts that have types that match that string.  A
106 likely value would be \"text/\" to automatically fetch all
107 textual parts.")
108
109 (defvar nnimap-process nil)
110
111 (defvar nnimap-status-string "")
112
113 (defvar nnimap-split-download-body-default nil
114   "Internal variable with default value for `nnimap-split-download-body'.")
115
116 (defvar nnimap-keepalive-timer nil)
117 (defvar nnimap-process-buffers nil)
118
119 (defstruct nnimap
120   group process commands capabilities select-result newlinep server
121   last-command-time greeting)
122
123 (defvar nnimap-object nil)
124
125 (defvar nnimap-mark-alist
126   '((read "\\Seen" %Seen)
127     (tick "\\Flagged" %Flagged)
128     (reply "\\Answered" %Answered)
129     (expire "gnus-expire")
130     (dormant "gnus-dormant")
131     (score "gnus-score")
132     (save "gnus-save")
133     (download "gnus-download")
134     (forward "gnus-forward")))
135
136 (defun nnimap-buffer ()
137   (nnimap-find-process-buffer nntp-server-buffer))
138
139 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
140   (with-current-buffer nntp-server-buffer
141     (erase-buffer)
142     (when (nnimap-possibly-change-group group server)
143       (with-current-buffer (nnimap-buffer)
144         (erase-buffer)
145         (nnimap-wait-for-response
146          (nnimap-send-command
147           "UID FETCH %s %s"
148           (nnimap-article-ranges (gnus-compress-sequence articles))
149           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
150                   (format
151                    (if (nnimap-ver4-p)
152                        "BODY.PEEK[HEADER.FIELDS %s]"
153                      "RFC822.HEADER.LINES %s")
154                    (append '(Subject From Date Message-Id
155                                      References In-Reply-To Xref)
156                            nnmail-extra-headers))))
157          t)
158         (nnimap-transform-headers))
159       (insert-buffer-substring
160        (nnimap-find-process-buffer (current-buffer))))
161     'headers))
162
163 (defun nnimap-transform-headers ()
164   (goto-char (point-min))
165   (let (article bytes lines size string)
166     (block nil
167       (while (not (eobp))
168         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
169           (delete-region (point) (progn (forward-line 1) (point)))
170           (when (eobp)
171             (return)))
172         (setq article (match-string 1))
173         ;; Unfold quoted {number} strings.
174         (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
175                                   (1+ (line-end-position)) t)
176           (setq size (string-to-number (match-string 1)))
177           (delete-region (+ (match-beginning 0) 2) (point))
178           (setq string (delete-region (point) (+ (point) size)))
179           (insert (format "%S" string)))
180         (setq bytes (nnimap-get-length)
181               lines nil)
182         (beginning-of-line)
183         (setq size
184               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
185                                       (line-end-position)
186                                       t)
187                    (match-string 1)))
188         (beginning-of-line)
189         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
190           (let ((structure (ignore-errors
191                              (read (current-buffer)))))
192             (while (and (consp structure)
193                         (not (stringp (car structure))))
194               (setq structure (car structure)))
195             (setq lines (nth 7 structure))))
196         (delete-region (line-beginning-position) (line-end-position))
197         (insert (format "211 %s Article retrieved." article))
198         (forward-line 1)
199         (when size
200           (insert (format "Chars: %s\n" size)))
201         (when lines
202           (insert (format "Lines: %s\n" lines)))
203         (re-search-forward "^\r$")
204         (delete-region (line-beginning-position) (line-end-position))
205         (insert ".")
206         (forward-line 1)))))
207
208 (defun nnimap-get-length ()
209   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
210        (string-to-number (match-string 1))))
211
212 (defun nnimap-article-ranges (ranges)
213   (let (result)
214     (cond
215      ((numberp ranges)
216       (number-to-string ranges))
217      ((numberp (cdr ranges))
218       (format "%d:%d" (car ranges) (cdr ranges)))
219      (t
220       (dolist (elem ranges)
221         (push
222          (if (consp elem)
223              (format "%d:%d" (car elem) (cdr elem))
224            (number-to-string elem))
225          result))
226       (mapconcat #'identity (nreverse result) ",")))))
227
228 (deffoo nnimap-open-server (server &optional defs)
229   (if (nnimap-server-opened server)
230       t
231     (unless (assq 'nnimap-address defs)
232       (setq defs (append defs (list (list 'nnimap-address server)))))
233     (nnoo-change-server 'nnimap server defs)
234     (or (nnimap-find-connection nntp-server-buffer)
235         (nnimap-open-connection nntp-server-buffer))))
236
237 (defun nnimap-make-process-buffer (buffer)
238   (with-current-buffer
239       (generate-new-buffer (format "*nnimap %s %s %s*"
240                                    nnimap-address nnimap-server-port
241                                    (gnus-buffer-exists-p buffer)))
242     (mm-disable-multibyte)
243     (buffer-disable-undo)
244     (gnus-add-buffer)
245     (set (make-local-variable 'after-change-functions) nil)
246     (set (make-local-variable 'nnimap-object)
247          (make-nnimap :server (nnoo-current-server 'nnimap)))
248     (push (list buffer (current-buffer)) nnimap-connection-alist)
249     (push (current-buffer) nnimap-process-buffers)
250     (current-buffer)))
251
252 (defun nnimap-open-shell-stream (name buffer host port)
253   (let ((process-connection-type nil))
254     (start-process name buffer shell-file-name
255                    shell-command-switch
256                    (format-spec
257                     nnimap-shell-program
258                     (format-spec-make
259                      ?s host
260                      ?p port)))))
261
262 (defun nnimap-credentials (address ports &optional inhibit-create)
263   (let (port credentials)
264     ;; Request the credentials from all ports, but only query on the
265     ;; last port if all the previous ones have failed.
266     (while (and (null credentials)
267                 (setq port (pop ports)))
268       (setq credentials
269             (auth-source-user-or-password
270              '("login" "password") address port nil
271              (if inhibit-create
272                  nil
273                (null ports)))))
274     credentials))
275
276 (defun nnimap-keepalive ()
277   (let ((now (current-time)))
278     (dolist (buffer nnimap-process-buffers)
279       (when (buffer-name buffer)
280         (with-current-buffer buffer
281           (when (and nnimap-object
282                      (nnimap-last-command-time nnimap-object)
283                      (> (time-to-seconds
284                          (time-subtract
285                           now
286                           (nnimap-last-command-time nnimap-object)))
287                         ;; More than five minutes since the last command.
288                         (* 5 60)))
289             (nnimap-send-command "NOOP")))))))
290
291 (declare-function gnutls-negotiate "subr" (fn file &optional arglist fileonly))
292
293 (defun nnimap-open-connection (buffer)
294   (unless nnimap-keepalive-timer
295     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
296                                               'nnimap-keepalive)))
297   (block nil
298     (with-current-buffer (nnimap-make-process-buffer buffer)
299       (let* ((coding-system-for-read 'binary)
300              (coding-system-for-write 'binary)
301              (port nil)
302              (ports
303               (cond
304                ((or (eq nnimap-stream 'network)
305                     (and (eq nnimap-stream 'starttls)
306                          (fboundp 'open-gnutls-stream)))
307                 (nnheader-message 7 "Opening connection to %s..."
308                                   nnimap-address)
309                 (open-network-stream
310                  "*nnimap*" (current-buffer) nnimap-address
311                  (setq port
312                        (or nnimap-server-port
313                            (if (netrc-find-service-number "imap")
314                                "imap"
315                              "143"))))
316                 '("143" "imap"))
317                ((eq nnimap-stream 'shell)
318                 (nnheader-message 7 "Opening connection to %s via shell..."
319                                   nnimap-address)
320                 (nnimap-open-shell-stream
321                  "*nnimap*" (current-buffer) nnimap-address
322                  (setq port (or nnimap-server-port "imap")))
323                 '("imap"))
324                ((eq nnimap-stream 'starttls)
325                 (nnheader-message 7 "Opening connection to %s via starttls..."
326                          nnimap-address)
327                 (let ((tls-program
328                        '("openssl s_client -connect %h:%p -no_ssl2 -ign_eof -starttls imap")))
329                   (open-tls-stream
330                    "*nnimap*" (current-buffer) nnimap-address
331                    (setq port (or nnimap-server-port "imap"))))
332                 '("imap"))
333                ((memq nnimap-stream '(ssl tls))
334                 (nnheader-message 7 "Opening connection to %s via tls..."
335                                   nnimap-address)
336                 (funcall (if (fboundp 'open-gnutls-stream)
337                              'open-gnutls-stream
338                            'open-tls-stream)
339                          "*nnimap*" (current-buffer) nnimap-address
340                          (setq port
341                                (or nnimap-server-port
342                                    (if (netrc-find-service-number "imaps")
343                                        "imaps"
344                                      "993"))))
345                 '("143" "993" "imap" "imaps"))
346                (t
347                 (error "Unknown stream type: %s" nnimap-stream))))
348              connection-result login-result credentials)
349         (setf (nnimap-process nnimap-object)
350               (get-buffer-process (current-buffer)))
351         (if (not (and (nnimap-process nnimap-object)
352                       (memq (process-status (nnimap-process nnimap-object))
353                             '(open run))))
354             (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
355                              nnimap-address port nnimap-stream)
356           (gnus-set-process-query-on-exit-flag
357            (nnimap-process nnimap-object) nil)
358           (if (not (setq connection-result (nnimap-wait-for-connection)))
359               (nnheader-report 'nnimap
360                                "%s" (buffer-substring
361                                      (point) (line-end-position)))
362             ;; Store the greeting (for debugging purposes).
363             (setf (nnimap-greeting nnimap-object)
364                   (buffer-substring (line-beginning-position)
365                                     (line-end-position)))
366             ;; Store the capabilities.
367             (setf (nnimap-capabilities nnimap-object)
368                   (mapcar
369                    #'upcase
370                    (nnimap-find-parameter
371                     "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
372             (when nnimap-server-port
373               (push (format "%s" nnimap-server-port) ports))
374             ;; If this is a STARTTLS-capable server, then sever the
375             ;; connection and start a STARTTLS connection instead.
376             (cond
377              ((and (or (and (eq nnimap-stream 'network)
378                             (member "STARTTLS"
379                                     (nnimap-capabilities nnimap-object)))
380                        (eq nnimap-stream 'starttls))
381                    (fboundp 'open-gnutls-stream))
382               (nnimap-command "STARTTLS")
383               (gnutls-negotiate (nnimap-process nnimap-object) nil))
384              ((and (eq nnimap-stream 'network)
385                    (member "STARTTLS" (nnimap-capabilities nnimap-object)))
386               (let ((nnimap-stream 'starttls))
387                 (let ((tls-process
388                        (nnimap-open-connection buffer)))
389                   ;; If the STARTTLS connection was successful, we
390                   ;; kill our first non-encrypted connection.  If it
391                   ;; wasn't successful, we just use our unencrypted
392                   ;; connection.
393                   (when (memq (process-status tls-process) '(open run))
394                     (delete-process (nnimap-process nnimap-object))
395                     (kill-buffer (current-buffer))
396                     (return tls-process))))))
397             (unless (equal connection-result "PREAUTH")
398               (if (not (setq credentials
399                              (if (eq nnimap-authenticator 'anonymous)
400                                  (list "anonymous"
401                                        (message-make-address))
402                                (or
403                                 ;; First look for the credentials based
404                                 ;; on the virtual server name.
405                                 (nnimap-credentials
406                                  (nnoo-current-server 'nnimap) ports t)
407                                 ;; Then look them up based on the
408                                 ;; physical address.
409                                 (nnimap-credentials nnimap-address ports)))))
410                   (setq nnimap-object nil)
411                 (setq login-result (nnimap-command "LOGIN %S %S"
412                                                    (car credentials)
413                                                    (cadr credentials)))
414                 (unless (car login-result)
415                   ;; If the login failed, then forget the credentials
416                   ;; that are now possibly cached.
417                   (dolist (host (list (nnoo-current-server 'nnimap)
418                                       nnimap-address))
419                     (dolist (port ports)
420                       (dolist (element '("login" "password"))
421                         (auth-source-forget-user-or-password
422                          element host port))))
423                   (delete-process (nnimap-process nnimap-object))
424                   (setq nnimap-object nil))))
425             (when nnimap-object
426               (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
427                 (nnimap-command "ENABLE QRESYNC"))
428               (nnimap-process nnimap-object))))))))
429
430 (defun nnimap-find-parameter (parameter elems)
431   (let (result)
432     (dolist (elem elems)
433       (cond
434        ((equal (car elem) parameter)
435         (setq result (cdr elem)))
436        ((and (equal (car elem) "OK")
437              (consp (cadr elem))
438              (equal (caadr elem) parameter))
439         (setq result (cdr (cadr elem))))))
440     result))
441
442 (deffoo nnimap-close-server (&optional server)
443   (when (nnoo-change-server 'nnimap server nil)
444     (ignore-errors
445       (delete-process (get-buffer-process (nnimap-buffer))))
446     (nnoo-close-server 'nnimap server)
447     t))
448
449 (deffoo nnimap-request-close ()
450   t)
451
452 (deffoo nnimap-server-opened (&optional server)
453   (and (nnoo-current-server-p 'nnimap server)
454        nntp-server-buffer
455        (gnus-buffer-live-p nntp-server-buffer)
456        (nnimap-find-connection nntp-server-buffer)))
457
458 (deffoo nnimap-status-message (&optional server)
459   nnimap-status-string)
460
461 (deffoo nnimap-request-article (article &optional group server to-buffer)
462   (with-current-buffer nntp-server-buffer
463     (let ((result (nnimap-possibly-change-group group server))
464           parts structure)
465       (when (stringp article)
466         (setq article (nnimap-find-article-by-message-id group article)))
467       (when (and result
468                  article)
469         (erase-buffer)
470         (with-current-buffer (nnimap-buffer)
471           (erase-buffer)
472           (when nnimap-fetch-partial-articles
473             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
474             (goto-char (point-min))
475             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
476               (setq structure (ignore-errors
477                                 (let ((start (point)))
478                                   (forward-sexp 1)
479                                   (downcase-region start (point))
480                                   (goto-char start)
481                                   (read (current-buffer))))
482                     parts (nnimap-find-wanted-parts structure))))
483           (when (if parts
484                     (nnimap-get-partial-article article parts structure)
485                   (nnimap-get-whole-article article))
486             (let ((buffer (current-buffer)))
487               (with-current-buffer (or to-buffer nntp-server-buffer)
488                 (erase-buffer)
489                 (insert-buffer-substring buffer)
490                 (nnheader-ms-strip-cr)
491                 (cons group article)))))))))
492
493 (defun nnimap-get-whole-article (article)
494   (let ((result
495          (nnimap-command
496           (if (nnimap-ver4-p)
497               "UID FETCH %d BODY.PEEK[]"
498             "UID FETCH %d RFC822.PEEK")
499           article)))
500     ;; Check that we really got an article.
501     (goto-char (point-min))
502     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
503       (setq result nil))
504     (when result
505       ;; Remove any data that may have arrived before the FETCH data.
506       (beginning-of-line)
507       (unless (bobp)
508         (delete-region (point-min) (point)))
509       (let ((bytes (nnimap-get-length)))
510         (delete-region (line-beginning-position)
511                        (progn (forward-line 1) (point)))
512         (goto-char (+ (point) bytes))
513         (delete-region (point) (point-max)))
514       t)))
515
516 (defun nnimap-ver4-p ()
517   (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
518
519 (defun nnimap-get-partial-article (article parts structure)
520   (let ((result
521          (nnimap-command
522           "UID FETCH %d (%s %s)"
523           article
524           (if (nnimap-ver4-p)
525               "BODY.PEEK[HEADER]"
526             "RFC822.HEADER")
527           (if (nnimap-ver4-p)
528               (mapconcat (lambda (part)
529                            (format "BODY.PEEK[%s]" part))
530                          parts " ")
531             (mapconcat (lambda (part)
532                          (format "RFC822.PEEK[%s]" part))
533                        parts " ")))))
534     (when result
535       (nnimap-convert-partial-article structure))))
536
537 (defun nnimap-convert-partial-article (structure)
538   ;; First just skip past the headers.
539   (goto-char (point-min))
540   (let ((bytes (nnimap-get-length))
541         id parts)
542     ;; Delete "FETCH" line.
543     (delete-region (line-beginning-position)
544                    (progn (forward-line 1) (point)))
545     (goto-char (+ (point) bytes))
546     ;; Collect all the body parts.
547     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
548       (setq id (match-string 1)
549             bytes (nnimap-get-length))
550       (beginning-of-line)
551       (delete-region (point) (progn (forward-line 1) (point)))
552       (push (list id (buffer-substring (point) (+ (point) bytes)))
553             parts)
554       (delete-region (point) (+ (point) bytes)))
555     ;; Delete trailing junk.
556     (delete-region (point) (point-max))
557     ;; Now insert all the parts again where they fit in the structure.
558     (nnimap-insert-partial-structure structure parts)
559     t))
560
561 (defun nnimap-insert-partial-structure (structure parts &optional subp)
562   (let (type boundary)
563     (let ((bstruc structure))
564       (while (consp (car bstruc))
565         (pop bstruc))
566       (setq type (car bstruc))
567       (setq bstruc (car (cdr bstruc)))
568       (let ((has-boundary (member "boundary" bstruc)))
569         (when has-boundary
570           (setq boundary (cadr has-boundary)))))
571     (when subp
572       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
573                       (downcase type) boundary)))
574     (while (not (stringp (car structure)))
575       (insert "\n--" boundary "\n")
576       (if (consp (caar structure))
577           (nnimap-insert-partial-structure (pop structure) parts t)
578         (let ((bit (pop structure)))
579           (insert (format  "Content-type: %s/%s"
580                            (downcase (nth 0 bit))
581                            (downcase (nth 1 bit))))
582           (if (member "CHARSET" (nth 2 bit))
583               (insert (format
584                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
585             (insert "\n"))
586           (insert (format "Content-transfer-encoding: %s\n"
587                           (nth 5 bit)))
588           (insert "\n")
589           (when (assoc (nth 9 bit) parts)
590             (insert (cadr (assoc (nth 9 bit) parts)))))))
591     (insert "\n--" boundary "--\n")))
592
593 (defun nnimap-find-wanted-parts (structure)
594   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
595
596 (defun nnimap-find-wanted-parts-1 (structure prefix)
597   (let ((num 1)
598         parts)
599     (while (consp (car structure))
600       (let ((sub (pop structure)))
601         (if (consp (car sub))
602             (push (nnimap-find-wanted-parts-1
603                    sub (if (string= prefix "")
604                            (number-to-string num)
605                          (format "%s.%s" prefix num)))
606                   parts)
607           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
608                 (id (if (string= prefix "")
609                         (number-to-string num)
610                       (format "%s.%s" prefix num))))
611             (setcar (nthcdr 9 sub) id)
612             (when (if (eq nnimap-fetch-partial-articles t)
613                       (equal id "1")
614                     (string-match nnimap-fetch-partial-articles type))
615               (push id parts))))
616         (incf num)))
617     (nreverse parts)))
618
619 (deffoo nnimap-request-group (group &optional server dont-check info)
620   (let ((result (nnimap-possibly-change-group
621                  ;; Don't SELECT the group if we're going to select it
622                  ;; later, anyway.
623                  (if dont-check
624                      nil
625                    group)
626                  server))
627         articles active marks high low)
628     (with-current-buffer nntp-server-buffer
629       (when result
630         (if (and dont-check
631                  (setq active (nth 2 (assoc group nnimap-current-infos))))
632             (insert (format "211 %d %d %d %S\n"
633                             (- (cdr active) (car active))
634                             (car active)
635                             (cdr active)
636                             group))
637           (with-current-buffer (nnimap-buffer)
638             (erase-buffer)
639             (let ((group-sequence
640                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
641                   (flag-sequence
642                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
643               (setf (nnimap-group nnimap-object) group)
644               (nnimap-wait-for-response flag-sequence)
645               (setq marks
646                     (nnimap-flags-to-marks
647                      (nnimap-parse-flags
648                       (list (list group-sequence flag-sequence
649                                   1 group "SELECT")))))
650               (when (and info
651                          marks)
652                 (nnimap-update-infos marks (list info)))
653               (goto-char (point-max))
654               (let ((uidnext (nth 5 (car marks))))
655                 (setq high (or (if uidnext
656                                    (1- uidnext)
657                                  (nth 3 (car marks)))
658                                0)
659                       low (or (nth 4 (car marks)) uidnext 1)))))
660           (erase-buffer)
661           (insert
662            (format
663             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
664         t))))
665
666 (deffoo nnimap-request-create-group (group &optional server args)
667   (when (nnimap-possibly-change-group nil server)
668     (with-current-buffer (nnimap-buffer)
669       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
670
671 (deffoo nnimap-request-delete-group (group &optional force server)
672   (when (nnimap-possibly-change-group nil server)
673     (with-current-buffer (nnimap-buffer)
674       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
675
676 (deffoo nnimap-request-rename-group (group new-name &optional server)
677   (when (nnimap-possibly-change-group nil server)
678     (with-current-buffer (nnimap-buffer)
679       ;; Make sure we don't have this group open read/write by asking
680       ;; to examine a mailbox that doesn't exist.  This seems to be
681       ;; the only way that allows us to reliably go back to unselected
682       ;; state on Courier.
683       (nnimap-command "EXAMINE DOES.NOT.EXIST")
684       (setf (nnimap-group nnimap-object) nil)
685       (car (nnimap-command "RENAME %S %S"
686                            (utf7-encode group t) (utf7-encode new-name t))))))
687
688 (deffoo nnimap-request-expunge-group (group &optional server)
689   (when (nnimap-possibly-change-group group server)
690     (with-current-buffer (nnimap-buffer)
691       (car (nnimap-command "EXPUNGE")))))
692
693 (defun nnimap-get-flags (spec)
694   (let ((articles nil)
695         elems end)
696     (with-current-buffer (nnimap-buffer)
697       (erase-buffer)
698       (nnimap-wait-for-response (nnimap-send-command
699                                  "UID FETCH %s FLAGS" spec))
700       (setq end (point))
701       (subst-char-in-region (point-min) (point-max)
702                             ?\\ ?% t)
703       (goto-char (point-min))
704       (while (search-forward " FETCH " end t)
705         (setq elems (read (current-buffer)))
706         (push (cons (cadr (memq 'UID elems))
707                     (cadr (memq 'FLAGS elems)))
708               articles)))
709     (nreverse articles)))
710
711 (deffoo nnimap-close-group (group &optional server)
712   t)
713
714 (deffoo nnimap-request-move-article (article group server accept-form
715                                              &optional last internal-move-group)
716   (with-temp-buffer
717     (mm-disable-multibyte)
718     (when (nnimap-request-article article group server (current-buffer))
719       ;; If the move is internal (on the same server), just do it the easy
720       ;; way.
721       (let ((message-id (message-field-value "message-id")))
722         (if internal-move-group
723             (let ((result
724                    (with-current-buffer (nnimap-buffer)
725                      (nnimap-command "UID COPY %d %S"
726                                      article
727                                      (utf7-encode internal-move-group t)))))
728               (when (car result)
729                 (nnimap-delete-article article)
730                 (cons internal-move-group
731                       (nnimap-find-article-by-message-id
732                        internal-move-group message-id))))
733           ;; Move the article to a different method.
734           (let ((result (eval accept-form)))
735             (when result
736               (nnimap-delete-article article)
737               result)))))))
738
739 (deffoo nnimap-request-expire-articles (articles group &optional server force)
740   (cond
741    ((null articles)
742     nil)
743    ((not (nnimap-possibly-change-group group server))
744     articles)
745    ((and force
746          (eq nnmail-expiry-target 'delete))
747     (unless (nnimap-delete-article (gnus-compress-sequence articles))
748       (nnheader-message 7 "Article marked for deletion, but not expunged."))
749     nil)
750    (t
751     (let ((deletable-articles
752            (if (or force
753                    (eq nnmail-expiry-wait 'immediate))
754                articles
755              (gnus-sorted-intersection
756               articles
757               (nnimap-find-expired-articles group)))))
758       (if (null deletable-articles)
759           articles
760         (if (eq nnmail-expiry-target 'delete)
761             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
762           (setq deletable-articles
763                 (nnimap-process-expiry-targets
764                  deletable-articles group server)))
765         ;; Return the articles we didn't delete.
766         (gnus-sorted-complement articles deletable-articles))))))
767
768 (defun nnimap-process-expiry-targets (articles group server)
769   (let ((deleted-articles nil))
770     (dolist (article articles)
771       (let ((target nnmail-expiry-target))
772         (with-temp-buffer
773           (mm-disable-multibyte)
774           (when (nnimap-request-article article group server (current-buffer))
775             (nnheader-message 7 "Expiring article %s:%d" group article)
776             (when (functionp target)
777               (setq target (funcall target group)))
778             (when (and target
779                        (not (eq target 'delete)))
780               (if (or (gnus-request-group target t)
781                       (gnus-request-create-group target))
782                   (nnmail-expiry-target-group target group)
783                 (setq target nil)))
784             (when target
785               (push article deleted-articles))))))
786     ;; Change back to the current group again.
787     (nnimap-possibly-change-group group server)
788     (setq deleted-articles (nreverse deleted-articles))
789     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
790     deleted-articles))
791
792 (defun nnimap-find-expired-articles (group)
793   (let ((cutoff (nnmail-expired-article-p group nil nil)))
794     (with-current-buffer (nnimap-buffer)
795       (let ((result
796              (nnimap-command
797               "UID SEARCH SENTBEFORE %s"
798               (format-time-string
799                (format "%%d-%s-%%Y"
800                        (upcase
801                         (car (rassoc (nth 4 (decode-time cutoff))
802                                      parse-time-months))))
803                cutoff))))
804         (and (car result)
805              (delete 0 (mapcar #'string-to-number
806                                (cdr (assoc "SEARCH" (cdr result))))))))))
807
808
809 (defun nnimap-find-article-by-message-id (group message-id)
810   (with-current-buffer (nnimap-buffer)
811     (erase-buffer)
812     (setf (nnimap-group nnimap-object) nil)
813     (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
814     (let ((sequence
815            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
816           article result)
817       (setq result (nnimap-wait-for-response sequence))
818       (when (and result
819                  (car (setq result (nnimap-parse-response))))
820         ;; Select the last instance of the message in the group.
821         (and (setq article
822                    (car (last (assoc "SEARCH" (cdr result)))))
823              (string-to-number article))))))
824
825 (defun nnimap-delete-article (articles)
826   (with-current-buffer (nnimap-buffer)
827     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
828                     (nnimap-article-ranges articles))
829     (cond
830      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
831       (nnimap-command "UID EXPUNGE %s"
832                       (nnimap-article-ranges articles))
833       t)
834      (nnimap-expunge
835       (nnimap-command "EXPUNGE")
836       t)
837      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
838                                 "server doesn't support UIDPLUS, so we won't "
839                                 "delete this article now"))))))
840
841 (deffoo nnimap-request-scan (&optional group server)
842   (when (and (nnimap-possibly-change-group nil server)
843              nnimap-inbox
844              nnimap-split-methods)
845     (nnheader-message 7 "nnimap %s splitting mail..." server)
846     (nnimap-split-incoming-mail)))
847
848 (defun nnimap-marks-to-flags (marks)
849   (let (flags flag)
850     (dolist (mark marks)
851       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
852         (push flag flags)))
853     flags))
854
855 (deffoo nnimap-request-set-mark (group actions &optional server)
856   (when (nnimap-possibly-change-group group server)
857     (let (sequence)
858       (with-current-buffer (nnimap-buffer)
859         (erase-buffer)
860         ;; Just send all the STORE commands without waiting for
861         ;; response.  If they're successful, they're successful.
862         (dolist (action actions)
863           (destructuring-bind (range action marks) action
864             (let ((flags (nnimap-marks-to-flags marks)))
865               (when flags
866                 (setq sequence (nnimap-send-command
867                                 "UID STORE %s %sFLAGS.SILENT (%s)"
868                                 (nnimap-article-ranges range)
869                                 (if (eq action 'del)
870                                     "-"
871                                   "+")
872                                 (mapconcat #'identity flags " ")))))))
873         ;; Wait for the last command to complete to avoid later
874         ;; syncronisation problems with the stream.
875         (when sequence
876           (nnimap-wait-for-response sequence))))))
877
878 (deffoo nnimap-request-accept-article (group &optional server last)
879   (when (nnimap-possibly-change-group nil server)
880     (nnmail-check-syntax)
881     (let ((message-id (message-field-value "message-id"))
882           sequence message)
883       (nnimap-add-cr)
884       (setq message (buffer-substring-no-properties (point-min) (point-max)))
885       (with-current-buffer (nnimap-buffer)
886         (setq sequence (nnimap-send-command
887                         "APPEND %S {%d}" (utf7-encode group t)
888                         (length message)))
889         (process-send-string (get-buffer-process (current-buffer)) message)
890         (process-send-string (get-buffer-process (current-buffer))
891                              (if (nnimap-newlinep nnimap-object)
892                                  "\n"
893                                "\r\n"))
894         (let ((result (nnimap-get-response sequence)))
895           (if (not (car result))
896               (progn
897                 (nnheader-message 7 "%s" (nnheader-get-report-string 'nnimap))
898                 nil)
899             (cons group
900                   (nnimap-find-article-by-message-id group message-id))))))))
901
902 (deffoo nnimap-request-replace-article (article group buffer)
903   (let (group-art)
904     (when (and (nnimap-possibly-change-group group nil)
905                ;; Put the article into the group.
906                (with-current-buffer buffer
907                  (setq group-art
908                        (nnimap-request-accept-article group nil t))))
909       (nnimap-delete-article (list article))
910       ;; Return the new article number.
911       (cdr group-art))))
912
913 (defun nnimap-add-cr ()
914   (goto-char (point-min))
915   (while (re-search-forward "\r?\n" nil t)
916     (replace-match "\r\n" t t)))
917
918 (defun nnimap-get-groups ()
919   (let ((result (nnimap-command "LIST \"\" \"*\""))
920         groups)
921     (when (car result)
922       (dolist (line (cdr result))
923         (when (and (equal (car line) "LIST")
924                    (not (and (caadr line)
925                              (string-match "noselect" (caadr line)))))
926           (push (car (last line)) groups)))
927       (nreverse groups))))
928
929 (deffoo nnimap-request-list (&optional server)
930   (nnimap-possibly-change-group nil server)
931   (with-current-buffer nntp-server-buffer
932     (erase-buffer)
933     (let ((groups
934            (with-current-buffer (nnimap-buffer)
935              (nnimap-get-groups)))
936           sequences responses)
937       (when groups
938         (with-current-buffer (nnimap-buffer)
939           (setf (nnimap-group nnimap-object) nil)
940           (dolist (group groups)
941             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
942                         group)
943                   sequences))
944           (nnimap-wait-for-response (caar sequences))
945           (setq responses
946                 (nnimap-get-responses (mapcar #'car sequences))))
947         (dolist (response responses)
948           (let* ((sequence (car response))
949                  (response (cadr response))
950                  (group (cadr (assoc sequence sequences))))
951             (when (and group
952                        (equal (caar response) "OK"))
953               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
954                     highest exists)
955                 (dolist (elem response)
956                   (when (equal (cadr elem) "EXISTS")
957                     (setq exists (string-to-number (car elem)))))
958                 (when uidnext
959                   (setq highest (1- (string-to-number (car uidnext)))))
960                 (cond
961                  ((null highest)
962                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
963                  ((zerop exists)
964                   ;; Empty group.
965                   (insert (format "%S %d %d y\n"
966                                   (utf7-decode group t) highest (1+ highest))))
967                  (t
968                   ;; Return the widest possible range.
969                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
970                                   (or highest exists)))))))))
971         t))))
972
973 (deffoo nnimap-request-newgroups (date &optional server)
974   (nnimap-possibly-change-group nil server)
975   (with-current-buffer nntp-server-buffer
976     (erase-buffer)
977     (dolist (group (with-current-buffer (nnimap-buffer)
978                      (nnimap-get-groups)))
979       (unless (assoc group nnimap-current-infos)
980         ;; Insert dummy numbers here -- they don't matter.
981         (insert (format "%S 0 1 y\n" group))))
982     t))
983
984 (deffoo nnimap-retrieve-group-data-early (server infos)
985   (when (nnimap-possibly-change-group nil server)
986     (with-current-buffer (nnimap-buffer)
987       (erase-buffer)
988       (setf (nnimap-group nnimap-object) nil)
989       ;; QRESYNC handling isn't implemented.
990       (let ((qresyncp (member "QRESYNC" (nnimap-capabilities nnimap-object)))
991             params groups sequences active uidvalidity modseq group)
992         ;; Go through the infos and gather the data needed to know
993         ;; what and how to request the data.
994         (dolist (info infos)
995           (setq params (gnus-info-params info)
996                 group (gnus-group-real-name (gnus-info-group info))
997                 active (cdr (assq 'active params))
998                 uidvalidity (cdr (assq 'uidvalidity params))
999                 modseq (cdr (assq 'modseq params)))
1000           (if (and qresyncp
1001                    uidvalidity
1002                    modseq)
1003               (push
1004                (list (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
1005                                           (utf7-encode group t)
1006                                           uidvalidity modseq)
1007                      'qresync
1008                      nil group 'qresync)
1009                sequences)
1010             (let ((start
1011                    (if (and active uidvalidity)
1012                        ;; Fetch the last 100 flags.
1013                        (max 1 (- (cdr active) 100))
1014                      1))
1015                   (command
1016                    (if uidvalidity
1017                        "EXAMINE"
1018                      ;; If we don't have a UIDVALIDITY, then this is
1019                      ;; the first time we've seen the group, so we
1020                      ;; have to do a SELECT (which is slower than an
1021                      ;; examine), but will tell us whether the group
1022                      ;; is read-only or not.
1023                      "SELECT")))
1024               (push (list (nnimap-send-command "%s %S" command
1025                                                (utf7-encode group t))
1026                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1027                           start group command)
1028                     sequences)))
1029           ;; Some servers apparently can't have many outstanding
1030           ;; commands, so throttle them.
1031           (when (and (not nnimap-streaming)
1032                      (car sequences))
1033             (nnimap-wait-for-response (caar sequences))))
1034         sequences))))
1035
1036 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1037   (when (and sequences
1038              (nnimap-possibly-change-group nil server))
1039     (with-current-buffer (nnimap-buffer)
1040       ;; Wait for the final data to trickle in.
1041       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1042                                           (caar sequences)
1043                                         (cadar sequences))
1044                                       t)
1045         ;; Now we should have most of the data we need, no matter
1046         ;; whether we're QRESYNCING, fetching all the flags from
1047         ;; scratch, or just fetching the last 100 flags per group.
1048         (nnimap-update-infos (nnimap-flags-to-marks
1049                               (nnimap-parse-flags
1050                                (nreverse sequences)))
1051                              infos)
1052         ;; Finally, just return something resembling an active file in
1053         ;; the nntp buffer, so that the agent can save the info, too.
1054         (with-current-buffer nntp-server-buffer
1055           (erase-buffer)
1056           (dolist (info infos)
1057             (let* ((group (gnus-info-group info))
1058                    (active (gnus-active group)))
1059               (when active
1060                 (insert (format "%S %d %d y\n"
1061                                 (gnus-group-real-name group)
1062                                 (cdr active)
1063                                 (car active)))))))))))
1064
1065 (defun nnimap-update-infos (flags infos)
1066   (dolist (info infos)
1067     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1068            (marks (cdr (assoc group flags))))
1069       (when marks
1070         (nnimap-update-info info marks)))))
1071
1072 (defun nnimap-update-info (info marks)
1073   (destructuring-bind (existing flags high low uidnext start-article
1074                                 permanent-flags uidvalidity
1075                                 vanished highestmodseq) marks
1076     (cond
1077      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1078      ;; completely empty groups.
1079      ((and (not existing)
1080            (not uidnext))
1081       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1082         (when active
1083           (gnus-set-active (gnus-info-group info) active))))
1084      ;; We have a mismatch between the old and new UIDVALIDITY
1085      ;; identifiers, so we have to re-request the group info (the next
1086      ;; time).  This virtually never happens.
1087      ((let ((old-uidvalidity
1088              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1089         (and old-uidvalidity
1090              (not (equal old-uidvalidity uidvalidity))
1091              (> start-article 1)))
1092       (gnus-group-remove-parameter info 'uidvalidity)
1093       (gnus-group-remove-parameter info 'modseq))
1094      ;; We have the data needed to update.
1095      (t
1096       (let* ((group (gnus-info-group info))
1097              (completep (and start-article
1098                              (= start-article 1)))
1099              (active (or (gnus-active group)
1100                          (cdr (assq 'active (gnus-info-params info))))))
1101         (when uidnext
1102           (setq high (1- uidnext)))
1103         ;; First set the active ranges based on high/low.
1104         (if (or completep
1105                 (not (gnus-active group)))
1106             (gnus-set-active group
1107                              (cond
1108                               ((and low high)
1109                                (cons low high))
1110                               (uidnext
1111                                ;; No articles in this group.
1112                                (cons uidnext (1- uidnext)))
1113                               (active
1114                                active)
1115                               (start-article
1116                                (cons start-article (1- start-article)))
1117                               (t
1118                                ;; No articles and no uidnext.
1119                                nil)))
1120           (gnus-set-active
1121            group
1122            (cons (car active)
1123                  (or high (1- uidnext)))))
1124         ;; See whether this is a read-only group.
1125         (unless (eq permanent-flags 'not-scanned)
1126           (gnus-group-set-parameter
1127            info 'permanent-flags
1128            (and (or (memq '%* permanent-flags)
1129                     (memq '%Seen permanent-flags))
1130                 permanent-flags)))
1131         ;; Update marks and read articles if this isn't a
1132         ;; read-only IMAP group.
1133         (when (setq permanent-flags
1134                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1135           (if (and highestmodseq
1136                    (not start-article))
1137               ;; We've gotten the data by QRESYNCing.
1138               (nnimap-update-qresync-info
1139                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1140             ;; Do normal non-QRESYNC flag updates.
1141             ;; Update the list of read articles.
1142             (let* ((unread
1143                     (gnus-compress-sequence
1144                      (gnus-set-difference
1145                       (gnus-set-difference
1146                        existing
1147                        (cdr (assoc '%Seen flags)))
1148                       (cdr (assoc '%Flagged flags)))))
1149                    (read (gnus-range-difference
1150                           (cons start-article high) unread)))
1151               (when (> start-article 1)
1152                 (setq read
1153                       (gnus-range-nconcat
1154                        (if (> start-article 1)
1155                            (gnus-sorted-range-intersection
1156                             (cons 1 (1- start-article))
1157                             (gnus-info-read info))
1158                          (gnus-info-read info))
1159                        read)))
1160               (when (or (not (listp permanent-flags))
1161                         (memq '%Seen permanent-flags))
1162                 (gnus-info-set-read info read))
1163               ;; Update the marks.
1164               (setq marks (gnus-info-marks info))
1165               (dolist (type (cdr nnimap-mark-alist))
1166                 (when (or (not (listp permanent-flags))
1167                           (memq (assoc (caddr type) flags) permanent-flags)
1168                           (memq '%* permanent-flags))
1169                   (let ((old-marks (assoc (car type) marks))
1170                         (new-marks
1171                          (gnus-compress-sequence
1172                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1173                                    (assoc (intern (cadr type) obarray) flags)
1174                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1175                     (setq marks (delq old-marks marks))
1176                     (pop old-marks)
1177                     (when (and old-marks
1178                                (> start-article 1))
1179                       (setq old-marks (gnus-range-difference
1180                                        old-marks
1181                                        (cons start-article high)))
1182                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1183                     (when new-marks
1184                       (push (cons (car type) new-marks) marks)))))
1185               (gnus-info-set-marks info marks t))))
1186         ;; Note the active level for the next run-through.
1187         (gnus-group-set-parameter info 'active (gnus-active group))
1188         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1189         (gnus-group-set-parameter info 'modseq highestmodseq)
1190         (nnimap-store-info info (gnus-active group)))))))
1191
1192 (defun nnimap-update-qresync-info (info existing vanished flags)
1193   ;; Add all the vanished articles to the list of read articles.
1194   (gnus-info-set-read
1195    info
1196    (gnus-add-to-range
1197     (gnus-add-to-range
1198      (gnus-range-add (gnus-info-read info)
1199                      vanished)
1200      (cdr (assq '%Flagged flags)))
1201     (cdr (assq '%Seen flags))))
1202   (let ((marks (gnus-info-marks info)))
1203     (dolist (type (cdr nnimap-mark-alist))
1204       (let ((ticks (assoc (car type) marks))
1205             (new-marks
1206              (cdr (or (assoc (caddr type) flags) ; %Flagged
1207                       (assoc (intern (cadr type) obarray) flags)
1208                       (assoc (cadr type) flags))))) ; "\Flagged"
1209         (setq marks (delq ticks marks))
1210         (pop ticks)
1211         ;; Add the new marks we got.
1212         (setq ticks (gnus-add-to-range ticks new-marks))
1213         ;; Remove the marks from messages that don't have them.
1214         (setq ticks (gnus-remove-from-range
1215                      ticks
1216                      (gnus-compress-sequence
1217                       (gnus-sorted-complement existing new-marks))))
1218         (when ticks
1219           (push (cons (car type) ticks) marks)))
1220       (gnus-info-set-marks info marks t))))
1221
1222 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1223   (if (zerop (length irange))
1224       nil
1225     (let ((result nil))
1226       (dolist (elem (split-string irange ","))
1227         (push
1228          (if (string-match ":" elem)
1229              (let ((numbers (split-string elem ":")))
1230                (cons (string-to-number (car numbers))
1231                      (string-to-number (cadr numbers))))
1232            (string-to-number elem))
1233          result))
1234       (nreverse result))))
1235
1236 (defun nnimap-store-info (info active)
1237   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1238          (entry (assoc group nnimap-current-infos)))
1239     (if entry
1240         (setcdr entry (list info active))
1241       (push (list group info active) nnimap-current-infos))))
1242
1243 (defun nnimap-flags-to-marks (groups)
1244   (let (data group totalp uidnext articles start-article mark permanent-flags
1245              uidvalidity vanished highestmodseq)
1246     (dolist (elem groups)
1247       (setq group (car elem)
1248             uidnext (nth 1 elem)
1249             start-article (nth 2 elem)
1250             permanent-flags (nth 3 elem)
1251             uidvalidity (nth 4 elem)
1252             vanished (nth 5 elem)
1253             highestmodseq (nth 6 elem)
1254             articles (nthcdr 7 elem))
1255       (let ((high (caar articles))
1256             marks low existing)
1257         (dolist (article articles)
1258           (setq low (car article))
1259           (push (car article) existing)
1260           (dolist (flag (cdr article))
1261             (setq mark (assoc flag marks))
1262             (if (not mark)
1263                 (push (list flag (car article)) marks)
1264               (setcdr mark (cons (car article) (cdr mark))))))
1265         (push (list group existing marks high low uidnext start-article
1266                     permanent-flags uidvalidity vanished highestmodseq)
1267               data)))
1268     data))
1269
1270 (defun nnimap-parse-flags (sequences)
1271   (goto-char (point-min))
1272   ;; Change \Delete etc to %Delete, so that the reader can read it.
1273   (subst-char-in-region (point-min) (point-max)
1274                         ?\\ ?% t)
1275   (let (start end articles groups uidnext elems permanent-flags
1276               uidvalidity vanished highestmodseq)
1277     (dolist (elem sequences)
1278       (destructuring-bind (group-sequence flag-sequence totalp group command)
1279           elem
1280         (setq start (point))
1281         (when (and
1282                ;; The EXAMINE was successful.
1283                (search-forward (format "\n%d OK " group-sequence) nil t)
1284                (progn
1285                  (forward-line 1)
1286                  (setq end (point))
1287                  (goto-char start)
1288                  (setq permanent-flags
1289                        (if (equal command "SELECT")
1290                            (and (search-forward "PERMANENTFLAGS "
1291                                                 (or end (point-min)) t)
1292                                 (read (current-buffer)))
1293                          'not-scanned))
1294                  (goto-char start)
1295                  (setq uidnext
1296                        (and (search-forward "UIDNEXT "
1297                                             (or end (point-min)) t)
1298                             (read (current-buffer))))
1299                  (goto-char start)
1300                  (setq uidvalidity
1301                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1302                                                (or end (point-min)) t)
1303                             ;; Store UIDVALIDITY as a string, as it's
1304                             ;; too big for 32-bit Emacsen, usually.
1305                             (match-string 1)))
1306                  (goto-char start)
1307                  (setq vanished
1308                        (and (eq flag-sequence 'qresync)
1309                             (re-search-forward "VANISHED.* \\([0-9:,]+\\)"
1310                                                (or end (point-min)) t)
1311                             (match-string 1)))
1312                  (goto-char start)
1313                  (setq highestmodseq
1314                        (and (search-forward "HIGHESTMODSEQ "
1315                                             (or end (point-min)) t)
1316                             (read (current-buffer))))
1317                  (goto-char end)
1318                  (forward-line -1))
1319                ;; The UID FETCH FLAGS was successful.
1320                (or (eq flag-sequence 'qresync)
1321                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1322           (if (eq flag-sequence 'qresync)
1323               (progn
1324                 (goto-char start)
1325                 (setq start end))
1326             (setq start (point))
1327             (goto-char end))
1328           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1329             (setq elems (read (current-buffer)))
1330             (push (cons (cadr (memq 'UID elems))
1331                         (cadr (memq 'FLAGS elems)))
1332                   articles))
1333           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1334                              vanished highestmodseq)
1335                        articles)
1336                 groups)
1337           (goto-char end)
1338           (setq articles nil))))
1339     groups))
1340
1341 (defun nnimap-find-process-buffer (buffer)
1342   (cadr (assoc buffer nnimap-connection-alist)))
1343
1344 (deffoo nnimap-request-post (&optional server)
1345   (setq nnimap-status-string "Read-only server")
1346   nil)
1347
1348 (deffoo nnimap-request-thread (id)
1349     (let* ((refs (split-string
1350                (or (mail-header-references (gnus-summary-article-header))
1351                    "")))
1352            (cmd (let ((value
1353                        (format
1354                         "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1355                         id id)))
1356                   (dolist (refid refs value)
1357                     (setq value (format
1358                                  "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1359                                  refid refid value)))))
1360            (result
1361             (with-current-buffer (nnimap-buffer)
1362               (nnimap-command  "UID SEARCH %s" cmd))))
1363       (gnus-fetch-headers (and (car result)
1364            (delete 0 (mapcar #'string-to-number
1365                              (cdr (assoc "SEARCH" (cdr result)))))))))
1366
1367 (defun nnimap-possibly-change-group (group server)
1368   (let ((open-result t))
1369     (when (and server
1370                (not (nnimap-server-opened server)))
1371       (setq open-result (nnimap-open-server server)))
1372     (cond
1373      ((not open-result)
1374       nil)
1375      ((not group)
1376       t)
1377      (t
1378       (with-current-buffer (nnimap-buffer)
1379         (if (equal group (nnimap-group nnimap-object))
1380             t
1381           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1382             (when (car result)
1383               (setf (nnimap-group nnimap-object) group
1384                     (nnimap-select-result nnimap-object) result)
1385               result))))))))
1386
1387 (defun nnimap-find-connection (buffer)
1388   "Find the connection delivering to BUFFER."
1389   (let ((entry (assoc buffer nnimap-connection-alist)))
1390     (when entry
1391       (if (and (buffer-name (cadr entry))
1392                (get-buffer-process (cadr entry))
1393                (memq (process-status (get-buffer-process (cadr entry)))
1394                      '(open run)))
1395           (get-buffer-process (cadr entry))
1396         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1397         nil))))
1398
1399 (defvar nnimap-sequence 0)
1400
1401 (defun nnimap-send-command (&rest args)
1402   (process-send-string
1403    (get-buffer-process (current-buffer))
1404    (nnimap-log-command
1405     (format "%d %s%s\n"
1406             (incf nnimap-sequence)
1407             (apply #'format args)
1408             (if (nnimap-newlinep nnimap-object)
1409                 ""
1410               "\r"))))
1411   nnimap-sequence)
1412
1413 (defun nnimap-log-command (command)
1414   (with-current-buffer (get-buffer-create "*imap log*")
1415     (goto-char (point-max))
1416     (insert (format-time-string "%H:%M:%S") " " command))
1417   command)
1418
1419 (defun nnimap-command (&rest args)
1420   (erase-buffer)
1421   (setf (nnimap-last-command-time nnimap-object) (current-time))
1422   (let* ((sequence (apply #'nnimap-send-command args))
1423          (response (nnimap-get-response sequence)))
1424     (if (equal (caar response) "OK")
1425         (cons t response)
1426       (nnheader-report 'nnimap "%s"
1427                        (mapconcat (lambda (a)
1428                                     (format "%s" a))
1429                                   (car response) " "))
1430       nil)))
1431
1432 (defun nnimap-get-response (sequence)
1433   (nnimap-wait-for-response sequence)
1434   (nnimap-parse-response))
1435
1436 (defun nnimap-wait-for-connection ()
1437   (let ((process (get-buffer-process (current-buffer))))
1438     (goto-char (point-min))
1439     (while (and (memq (process-status process)
1440                       '(open run))
1441                 (not (re-search-forward "^[*.] .*\n" nil t)))
1442       (nnheader-accept-process-output process)
1443       (goto-char (point-min)))
1444     (forward-line -1)
1445     (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1446          (match-string 1))))
1447
1448 (defun nnimap-wait-for-response (sequence &optional messagep)
1449   (let ((process (get-buffer-process (current-buffer)))
1450         openp)
1451     (condition-case nil
1452         (progn
1453           (goto-char (point-max))
1454           (while (and (setq openp (memq (process-status process)
1455                                         '(open run)))
1456                       (not (re-search-backward
1457                             (format "^%d .*\n" sequence)
1458                             (if nnimap-streaming
1459                                 (max (point-min) (- (point) 500))
1460                               (point-min))
1461                             t)))
1462             (when messagep
1463               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1464             (nnheader-accept-process-output process)
1465             (goto-char (point-max)))
1466           openp)
1467       (quit
1468        ;; The user hit C-g while we were waiting: kill the process, in case
1469        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1470        ;; NAT routers).
1471        (delete-process process)
1472        nil))))
1473
1474 (defun nnimap-parse-response ()
1475   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1476         result)
1477     (dolist (line lines)
1478       (push (cdr (nnimap-parse-line line)) result))
1479     ;; Return the OK/error code first, and then all the "continuation
1480     ;; lines" afterwards.
1481     (cons (pop result)
1482           (nreverse result))))
1483
1484 ;; Parse an IMAP response line lightly.  They look like
1485 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1486 ;; the lines into a list of strings and lists of string.
1487 (defun nnimap-parse-line (line)
1488   (let (char result)
1489     (with-temp-buffer
1490       (mm-disable-multibyte)
1491       (insert line)
1492       (goto-char (point-min))
1493       (while (not (eobp))
1494         (if (eql (setq char (following-char)) ? )
1495             (forward-char 1)
1496           (push
1497            (cond
1498             ((eql char ?\[)
1499              (split-string
1500               (buffer-substring
1501                (1+ (point))
1502                (1- (search-forward "]" (line-end-position) 'move)))))
1503             ((eql char ?\()
1504              (split-string
1505               (buffer-substring
1506                (1+ (point))
1507                (1- (search-forward ")" (line-end-position) 'move)))))
1508             ((eql char ?\")
1509              (forward-char 1)
1510              (buffer-substring
1511               (point)
1512               (1- (or (search-forward "\"" (line-end-position) 'move)
1513                       (point)))))
1514             (t
1515              (buffer-substring (point) (if (search-forward " " nil t)
1516                                            (1- (point))
1517                                          (goto-char (point-max))))))
1518            result)))
1519       (nreverse result))))
1520
1521 (defun nnimap-last-response-string ()
1522   (save-excursion
1523     (forward-line 1)
1524     (let ((end (point)))
1525       (forward-line -1)
1526       (when (not (bobp))
1527         (forward-line -1)
1528         (while (and (not (bobp))
1529                     (eql (following-char) ?*))
1530           (forward-line -1))
1531         (unless (eql (following-char) ?*)
1532           (forward-line 1)))
1533       (buffer-substring (point) end))))
1534
1535 (defun nnimap-get-responses (sequences)
1536   (let (responses)
1537     (dolist (sequence sequences)
1538       (goto-char (point-min))
1539       (when (re-search-forward (format "^%d " sequence) nil t)
1540         (push (list sequence (nnimap-parse-response))
1541               responses)))
1542     responses))
1543
1544 (defvar nnimap-incoming-split-list nil)
1545
1546 (defun nnimap-fetch-inbox (articles)
1547   (erase-buffer)
1548   (nnimap-wait-for-response
1549    (nnimap-send-command
1550     "UID FETCH %s %s"
1551     (nnimap-article-ranges articles)
1552     (format "(UID %s%s)"
1553             (format
1554              (if (nnimap-ver4-p)
1555                  "BODY.PEEK[HEADER] BODY.PEEK"
1556                "RFC822.PEEK"))
1557             (if nnimap-split-download-body-default
1558                 "[]"
1559               "[1]")))
1560    t))
1561
1562 (defun nnimap-split-incoming-mail ()
1563   (with-current-buffer (nnimap-buffer)
1564     (let ((nnimap-incoming-split-list nil)
1565           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1566                                     nnmail-split-methods
1567                                   nnimap-split-methods))
1568           (nnmail-split-fancy (or nnimap-split-fancy
1569                                   nnmail-split-fancy))
1570           (nnmail-inhibit-default-split-group t)
1571           (groups (nnimap-get-groups))
1572           new-articles)
1573       (erase-buffer)
1574       (nnimap-command "SELECT %S" nnimap-inbox)
1575       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1576       (when new-articles
1577         (nnimap-fetch-inbox new-articles)
1578         (nnimap-transform-split-mail)
1579         (nnheader-ms-strip-cr)
1580         (nnmail-cache-open)
1581         (nnmail-split-incoming (current-buffer)
1582                                #'nnimap-save-mail-spec
1583                                nil nil
1584                                #'nnimap-dummy-active-number
1585                                #'nnimap-save-mail-spec)
1586         (when nnimap-incoming-split-list
1587           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1588                 sequences junk-articles)
1589             ;; Create any groups that doesn't already exist on the
1590             ;; server first.
1591             (dolist (spec specs)
1592               (when (and (not (member (car spec) groups))
1593                          (not (eq (car spec) 'junk)))
1594                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1595             ;; Then copy over all the messages.
1596             (erase-buffer)
1597             (dolist (spec specs)
1598               (let ((group (car spec))
1599                     (ranges (cdr spec)))
1600                 (if (eq group 'junk)
1601                     (setq junk-articles ranges)
1602                   (push (list (nnimap-send-command
1603                                "UID COPY %s %S"
1604                                (nnimap-article-ranges ranges)
1605                                (utf7-encode group t))
1606                               ranges)
1607                         sequences))))
1608             ;; Wait for the last COPY response...
1609             (when sequences
1610               (nnimap-wait-for-response (caar sequences))
1611               ;; And then mark the successful copy actions as deleted,
1612               ;; and possibly expunge them.
1613               (nnimap-mark-and-expunge-incoming
1614                (nnimap-parse-copied-articles sequences)))
1615             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1616
1617 (defun nnimap-mark-and-expunge-incoming (range)
1618   (when range
1619     (setq range (nnimap-article-ranges range))
1620     (erase-buffer)
1621     (let ((sequence
1622            (nnimap-send-command
1623             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1624       (cond
1625        ;; If the server supports it, we now delete the message we have
1626        ;; just copied over.
1627        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1628         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1629        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1630        ;; user has configured it.
1631        (nnimap-expunge
1632         (setq sequence (nnimap-send-command "EXPUNGE"))))
1633       (nnimap-wait-for-response sequence))))
1634
1635 (defun nnimap-parse-copied-articles (sequences)
1636   (let (sequence copied range)
1637     (goto-char (point-min))
1638     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1639       (setq sequence (string-to-number (match-string 1)))
1640       (when (setq range (cadr (assq sequence sequences)))
1641         (push (gnus-uncompress-range range) copied)))
1642     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1643
1644 (defun nnimap-new-articles (flags)
1645   (let (new)
1646     (dolist (elem flags)
1647       (when (or (null (cdr elem))
1648                 (and (not (memq '%Deleted (cdr elem)))
1649                      (not (memq '%Seen (cdr elem)))))
1650         (push (car elem) new)))
1651     (gnus-compress-sequence (nreverse new))))
1652
1653 (defun nnimap-make-split-specs (list)
1654   (let ((specs nil)
1655         entry)
1656     (dolist (elem list)
1657       (destructuring-bind (article spec) elem
1658         (dolist (group (delete nil (mapcar #'car spec)))
1659           (unless (setq entry (assoc group specs))
1660             (push (setq entry (list group)) specs))
1661           (setcdr entry (cons article (cdr entry))))))
1662     (dolist (entry specs)
1663       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1664     specs))
1665
1666 (defun nnimap-transform-split-mail ()
1667   (goto-char (point-min))
1668   (let (article bytes)
1669     (block nil
1670       (while (not (eobp))
1671         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1672           (delete-region (point) (progn (forward-line 1) (point)))
1673           (when (eobp)
1674             (return)))
1675         (setq article (match-string 1)
1676               bytes (nnimap-get-length))
1677         (delete-region (line-beginning-position) (line-end-position))
1678         ;; Insert MMDF separator, and a way to remember what this
1679         ;; article UID is.
1680         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1681         (forward-char (1+ bytes))
1682         (setq bytes (nnimap-get-length))
1683         (delete-region (line-beginning-position) (line-end-position))
1684         ;; There's a body; skip past that.
1685         (when bytes
1686           (forward-char (1+ bytes))
1687           (delete-region (line-beginning-position) (line-end-position)))))))
1688
1689 (defun nnimap-dummy-active-number (group &optional server)
1690   1)
1691
1692 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1693   (let (article)
1694     (goto-char (point-min))
1695     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1696         (error "Invalid nnimap mail")
1697       (setq article (string-to-number (match-string 1))))
1698     (push (list article
1699                 (if (eq group-art 'junk)
1700                     (list (cons 'junk 1))
1701                   group-art))
1702           nnimap-incoming-split-list)))
1703
1704 (provide 'nnimap)
1705
1706 ;;; nnimap.el ends here