* nnimap.el: Use nnheader-message throughout.
[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 (point))
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       (when (and (stringp (car bstruc))
569                  (string= (downcase (car bstruc)) "boundary"))
570         (setq boundary (cadr bstruc))))
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 group server))
621         articles active marks high low)
622     (with-current-buffer nntp-server-buffer
623       (when result
624         (if (and dont-check
625                  (setq active (nth 2 (assoc group nnimap-current-infos))))
626             (insert (format "211 %d %d %d %S\n"
627                             (- (cdr active) (car active))
628                             (car active)
629                             (cdr active)
630                             group))
631           (with-current-buffer (nnimap-buffer)
632             (erase-buffer)
633             (let ((group-sequence
634                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
635                   (flag-sequence
636                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
637               (nnimap-wait-for-response flag-sequence)
638               (setq marks
639                     (nnimap-flags-to-marks
640                      (nnimap-parse-flags
641                       (list (list group-sequence flag-sequence
642                                   1 group "SELECT")))))
643               (when (and info
644                          marks)
645                 (nnimap-update-infos marks (list info)))
646               (goto-char (point-max))
647               (let ((uidnext (nth 5 (car marks))))
648                 (setq high (or (if uidnext
649                                    (1- uidnext)
650                                  (nth 3 (car marks)))
651                                0)
652                       low (or (nth 4 (car marks)) uidnext 1)))))
653           (erase-buffer)
654           (insert
655            (format
656             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
657         t))))
658
659 (deffoo nnimap-request-create-group (group &optional server args)
660   (when (nnimap-possibly-change-group nil server)
661     (with-current-buffer (nnimap-buffer)
662       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
663
664 (deffoo nnimap-request-delete-group (group &optional force server)
665   (when (nnimap-possibly-change-group nil server)
666     (with-current-buffer (nnimap-buffer)
667       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
668
669 (deffoo nnimap-request-rename-group (group new-name &optional server)
670   (when (nnimap-possibly-change-group nil server)
671     (with-current-buffer (nnimap-buffer)
672       ;; Make sure we don't have this group open read/write by asking
673       ;; to examine a mailbox that doesn't exist.  This seems to be
674       ;; the only way that allows us to reliably go back to unselected
675       ;; state on Courier.
676       (nnimap-command "EXAMINE DOES.NOT.EXIST")
677       (setf (nnimap-group nnimap-object) nil)
678       (car (nnimap-command "RENAME %S %S"
679                            (utf7-encode group t) (utf7-encode new-name t))))))
680
681 (deffoo nnimap-request-expunge-group (group &optional server)
682   (when (nnimap-possibly-change-group group server)
683     (with-current-buffer (nnimap-buffer)
684       (car (nnimap-command "EXPUNGE")))))
685
686 (defun nnimap-get-flags (spec)
687   (let ((articles nil)
688         elems end)
689     (with-current-buffer (nnimap-buffer)
690       (erase-buffer)
691       (nnimap-wait-for-response (nnimap-send-command
692                                  "UID FETCH %s FLAGS" spec))
693       (setq end (point))
694       (subst-char-in-region (point-min) (point-max)
695                             ?\\ ?% t)
696       (goto-char (point-min))
697       (while (search-forward " FETCH " end t)
698         (setq elems (read (current-buffer)))
699         (push (cons (cadr (memq 'UID elems))
700                     (cadr (memq 'FLAGS elems)))
701               articles)))
702     (nreverse articles)))
703
704 (deffoo nnimap-close-group (group &optional server)
705   t)
706
707 (deffoo nnimap-request-move-article (article group server accept-form
708                                              &optional last internal-move-group)
709   (with-temp-buffer
710     (when (nnimap-request-article article group server (current-buffer))
711       ;; If the move is internal (on the same server), just do it the easy
712       ;; way.
713       (let ((message-id (message-field-value "message-id")))
714         (if internal-move-group
715             (let ((result
716                    (with-current-buffer (nnimap-buffer)
717                      (nnimap-command "UID COPY %d %S"
718                                      article
719                                      (utf7-encode internal-move-group t)))))
720               (when (car result)
721                 (nnimap-delete-article article)
722                 (cons internal-move-group
723                       (nnimap-find-article-by-message-id
724                        internal-move-group message-id))))
725           ;; Move the article to a different method.
726           (let ((result (eval accept-form)))
727             (when result
728               (nnimap-delete-article article)
729               result)))))))
730
731 (deffoo nnimap-request-expire-articles (articles group &optional server force)
732   (cond
733    ((null articles)
734     nil)
735    ((not (nnimap-possibly-change-group group server))
736     articles)
737    ((and force
738          (eq nnmail-expiry-target 'delete))
739     (unless (nnimap-delete-article (gnus-compress-sequence articles))
740       (nnheader-message 7 "Article marked for deletion, but not expunged."))
741     nil)
742    (t
743     (let ((deletable-articles
744            (if (or force
745                    (eq nnmail-expiry-wait 'immediate))
746                articles
747              (gnus-sorted-intersection
748               articles
749               (nnimap-find-expired-articles group)))))
750       (if (null deletable-articles)
751           articles
752         (if (eq nnmail-expiry-target 'delete)
753             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
754           (setq deletable-articles
755                 (nnimap-process-expiry-targets
756                  deletable-articles group server)))
757         ;; Return the articles we didn't delete.
758         (gnus-sorted-complement articles deletable-articles))))))
759
760 (defun nnimap-process-expiry-targets (articles group server)
761   (let ((deleted-articles nil))
762     (dolist (article articles)
763       (let ((target nnmail-expiry-target))
764         (with-temp-buffer
765           (when (nnimap-request-article article group server (current-buffer))
766             (nnheader-message 7 "Expiring article %s:%d" group article)
767             (when (functionp target)
768               (setq target (funcall target group)))
769             (when (and target
770                        (not (eq target 'delete)))
771               (if (or (gnus-request-group target t)
772                       (gnus-request-create-group target))
773                   (nnmail-expiry-target-group target group)
774                 (setq target nil)))
775             (when target
776               (push article deleted-articles))))))
777     ;; Change back to the current group again.
778     (nnimap-possibly-change-group group server)
779     (setq deleted-articles (nreverse deleted-articles))
780     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
781     deleted-articles))
782
783 (defun nnimap-find-expired-articles (group)
784   (let ((cutoff (nnmail-expired-article-p group nil nil)))
785     (with-current-buffer (nnimap-buffer)
786       (let ((result
787              (nnimap-command
788               "UID SEARCH SENTBEFORE %s"
789               (format-time-string
790                (format "%%d-%s-%%Y"
791                        (upcase
792                         (car (rassoc (nth 4 (decode-time cutoff))
793                                      parse-time-months))))
794                cutoff))))
795         (and (car result)
796              (delete 0 (mapcar #'string-to-number
797                                (cdr (assoc "SEARCH" (cdr result))))))))))
798
799
800 (defun nnimap-find-article-by-message-id (group message-id)
801   (with-current-buffer (nnimap-buffer)
802     (erase-buffer)
803     (setf (nnimap-group nnimap-object) nil)
804     (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
805     (let ((sequence
806            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
807           article result)
808       (setq result (nnimap-wait-for-response sequence))
809       (when (and result
810                  (car (setq result (nnimap-parse-response))))
811         ;; Select the last instance of the message in the group.
812         (and (setq article
813                    (car (last (assoc "SEARCH" (cdr result)))))
814              (string-to-number article))))))
815
816 (defun nnimap-delete-article (articles)
817   (with-current-buffer (nnimap-buffer)
818     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
819                     (nnimap-article-ranges articles))
820     (cond
821      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
822       (nnimap-command "UID EXPUNGE %s"
823                       (nnimap-article-ranges articles))
824       t)
825      (nnimap-expunge
826       (nnimap-command "EXPUNGE")
827       t)
828      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
829                                 "server doesn't support UIDPLUS, so we won't "
830                                 "delete this article now"))))))
831
832 (deffoo nnimap-request-scan (&optional group server)
833   (when (and (nnimap-possibly-change-group nil server)
834              nnimap-inbox
835              nnimap-split-methods)
836     (nnheader-message 7 "nnimap %s splitting mail..." server)
837     (nnimap-split-incoming-mail)))
838
839 (defun nnimap-marks-to-flags (marks)
840   (let (flags flag)
841     (dolist (mark marks)
842       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
843         (push flag flags)))
844     flags))
845
846 (deffoo nnimap-request-set-mark (group actions &optional server)
847   (when (nnimap-possibly-change-group group server)
848     (let (sequence)
849       (with-current-buffer (nnimap-buffer)
850         (erase-buffer)
851         ;; Just send all the STORE commands without waiting for
852         ;; response.  If they're successful, they're successful.
853         (dolist (action actions)
854           (destructuring-bind (range action marks) action
855             (let ((flags (nnimap-marks-to-flags marks)))
856               (when flags
857                 (setq sequence (nnimap-send-command
858                                 "UID STORE %s %sFLAGS.SILENT (%s)"
859                                 (nnimap-article-ranges range)
860                                 (if (eq action 'del)
861                                     "-"
862                                   "+")
863                                 (mapconcat #'identity flags " ")))))))
864         ;; Wait for the last command to complete to avoid later
865         ;; syncronisation problems with the stream.
866         (when sequence
867           (nnimap-wait-for-response sequence))))))
868
869 (deffoo nnimap-request-accept-article (group &optional server last)
870   (when (nnimap-possibly-change-group nil server)
871     (nnmail-check-syntax)
872     (let ((message-id (message-field-value "message-id"))
873           sequence message)
874       (nnimap-add-cr)
875       (setq message (buffer-string))
876       (with-current-buffer (nnimap-buffer)
877         (setq sequence (nnimap-send-command
878                         "APPEND %S {%d}" (utf7-encode group t)
879                         (length message)))
880         (process-send-string (get-buffer-process (current-buffer)) message)
881         (process-send-string (get-buffer-process (current-buffer))
882                              (if (nnimap-newlinep nnimap-object)
883                                  "\n"
884                                "\r\n"))
885         (let ((result (nnimap-get-response sequence)))
886           (if (not (car result))
887               (progn
888                 (nnheader-message 7 "%s" (nnheader-get-report-string 'nnimap))
889                 nil)
890             (cons group
891                   (nnimap-find-article-by-message-id group message-id))))))))
892
893 (defun nnimap-add-cr ()
894   (goto-char (point-min))
895   (while (re-search-forward "\r?\n" nil t)
896     (replace-match "\r\n" t t)))
897
898 (defun nnimap-get-groups ()
899   (let ((result (nnimap-command "LIST \"\" \"*\""))
900         groups)
901     (when (car result)
902       (dolist (line (cdr result))
903         (when (and (equal (car line) "LIST")
904                    (not (and (caadr line)
905                              (string-match "noselect" (caadr line)))))
906           (push (car (last line)) groups)))
907       (nreverse groups))))
908
909 (deffoo nnimap-request-list (&optional server)
910   (nnimap-possibly-change-group nil server)
911   (with-current-buffer nntp-server-buffer
912     (erase-buffer)
913     (let ((groups
914            (with-current-buffer (nnimap-buffer)
915              (nnimap-get-groups)))
916           sequences responses)
917       (when groups
918         (with-current-buffer (nnimap-buffer)
919           (setf (nnimap-group nnimap-object) nil)
920           (dolist (group groups)
921             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
922                         group)
923                   sequences))
924           (nnimap-wait-for-response (caar sequences))
925           (setq responses
926                 (nnimap-get-responses (mapcar #'car sequences))))
927         (dolist (response responses)
928           (let* ((sequence (car response))
929                  (response (cadr response))
930                  (group (cadr (assoc sequence sequences))))
931             (when (and group
932                        (equal (caar response) "OK"))
933               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
934                     highest exists)
935                 (dolist (elem response)
936                   (when (equal (cadr elem) "EXISTS")
937                     (setq exists (string-to-number (car elem)))))
938                 (when uidnext
939                   (setq highest (1- (string-to-number (car uidnext)))))
940                 (cond
941                  ((null highest)
942                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
943                  ((zerop exists)
944                   ;; Empty group.
945                   (insert (format "%S %d %d y\n"
946                                   (utf7-decode group t) highest (1+ highest))))
947                  (t
948                   ;; Return the widest possible range.
949                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
950                                   (or highest exists)))))))))
951         t))))
952
953 (deffoo nnimap-request-newgroups (date &optional server)
954   (nnimap-possibly-change-group nil server)
955   (with-current-buffer nntp-server-buffer
956     (erase-buffer)
957     (dolist (group (with-current-buffer (nnimap-buffer)
958                      (nnimap-get-groups)))
959       (unless (assoc group nnimap-current-infos)
960         ;; Insert dummy numbers here -- they don't matter.
961         (insert (format "%S 0 1 y\n" group))))
962     t))
963
964 (deffoo nnimap-retrieve-group-data-early (server infos)
965   (when (nnimap-possibly-change-group nil server)
966     (with-current-buffer (nnimap-buffer)
967       (erase-buffer)
968       (setf (nnimap-group nnimap-object) nil)
969       ;; QRESYNC handling isn't implemented.
970       (let ((qresyncp (member "QRESYNC" (nnimap-capabilities nnimap-object)))
971             params groups sequences active uidvalidity modseq group)
972         ;; Go through the infos and gather the data needed to know
973         ;; what and how to request the data.
974         (dolist (info infos)
975           (setq params (gnus-info-params info)
976                 group (gnus-group-real-name (gnus-info-group info))
977                 active (cdr (assq 'active params))
978                 uidvalidity (cdr (assq 'uidvalidity params))
979                 modseq (cdr (assq 'modseq params)))
980           (if (and qresyncp
981                    uidvalidity
982                    modseq)
983               (push
984                (list (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
985                                           (utf7-encode group t)
986                                           uidvalidity modseq)
987                      'qresync
988                      nil group 'qresync)
989                sequences)
990             (let ((start
991                    (if (and active uidvalidity)
992                        ;; Fetch the last 100 flags.
993                        (max 1 (- (cdr active) 100))
994                      1))
995                   (command
996                    (if uidvalidity
997                        "EXAMINE"
998                      ;; If we don't have a UIDVALIDITY, then this is
999                      ;; the first time we've seen the group, so we
1000                      ;; have to do a SELECT (which is slower than an
1001                      ;; examine), but will tell us whether the group
1002                      ;; is read-only or not.
1003                      "SELECT")))
1004               (push (list (nnimap-send-command "%s %S" command
1005                                                (utf7-encode group t))
1006                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1007                           start group command)
1008                     sequences)))
1009           ;; Some servers apparently can't have many outstanding
1010           ;; commands, so throttle them.
1011           (when (and (not nnimap-streaming)
1012                      (car sequences))
1013             (nnimap-wait-for-response (caar sequences))))
1014         sequences))))
1015
1016 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1017   (when (and sequences
1018              (nnimap-possibly-change-group nil server))
1019     (with-current-buffer (nnimap-buffer)
1020       ;; Wait for the final data to trickle in.
1021       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1022                                           (caar sequences)
1023                                         (cadar sequences))
1024                                       t)
1025         ;; Now we should have most of the data we need, no matter
1026         ;; whether we're QRESYNCING, fetching all the flags from
1027         ;; scratch, or just fetching the last 100 flags per group.
1028         (nnimap-update-infos (nnimap-flags-to-marks
1029                               (nnimap-parse-flags
1030                                (nreverse sequences)))
1031                              infos)
1032         ;; Finally, just return something resembling an active file in
1033         ;; the nntp buffer, so that the agent can save the info, too.
1034         (with-current-buffer nntp-server-buffer
1035           (erase-buffer)
1036           (dolist (info infos)
1037             (let* ((group (gnus-info-group info))
1038                    (active (gnus-active group)))
1039               (when active
1040                 (insert (format "%S %d %d y\n"
1041                                 (gnus-group-real-name group)
1042                                 (cdr active)
1043                                 (car active)))))))))))
1044
1045 (defun nnimap-update-infos (flags infos)
1046   (dolist (info infos)
1047     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1048            (marks (cdr (assoc group flags))))
1049       (when marks
1050         (nnimap-update-info info marks)))))
1051
1052 (defun nnimap-update-info (info marks)
1053   (destructuring-bind (existing flags high low uidnext start-article
1054                                 permanent-flags uidvalidity
1055                                 vanished highestmodseq) marks
1056     (cond
1057      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1058      ;; completely empty groups.
1059      ((and (not existing)
1060            (not uidnext))
1061       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1062         (when active
1063           (gnus-set-active (gnus-info-group info) active))))
1064      ;; We have a mismatch between the old and new UIDVALIDITY
1065      ;; identifiers, so we have to re-request the group info (the next
1066      ;; time).  This virtually never happens.
1067      ((let ((old-uidvalidity
1068              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1069         (and old-uidvalidity
1070              (not (equal old-uidvalidity uidvalidity))
1071              (> start-article 1)))
1072       (gnus-group-remove-parameter info 'uidvalidity)
1073       (gnus-group-remove-parameter info 'modseq))
1074      ;; We have the data needed to update.
1075      (t
1076       (let* ((group (gnus-info-group info))
1077              (completep (and start-article
1078                              (= start-article 1)))
1079              (active (or (gnus-active group)
1080                          (cdr (assq 'active (gnus-info-params info))))))
1081         (when uidnext
1082           (setq high (1- uidnext)))
1083         ;; First set the active ranges based on high/low.
1084         (if (or completep
1085                 (not (gnus-active group)))
1086             (gnus-set-active group
1087                              (cond
1088                               ((and low high)
1089                                (cons low high))
1090                               (uidnext
1091                                ;; No articles in this group.
1092                                (cons uidnext (1- uidnext)))
1093                               (active
1094                                active)
1095                               (start-article
1096                                (cons start-article (1- start-article)))
1097                               (t
1098                                ;; No articles and no uidnext.
1099                                nil)))
1100           (gnus-set-active
1101            group
1102            (cons (car active)
1103                  (or high (1- uidnext)))))
1104         ;; See whether this is a read-only group.
1105         (unless (eq permanent-flags 'not-scanned)
1106           (gnus-group-set-parameter
1107            info 'permanent-flags
1108            (if (memq '%* permanent-flags)
1109                t
1110              nil)))
1111         ;; Update marks and read articles if this isn't a
1112         ;; read-only IMAP group.
1113         (when (cdr (assq 'permanent-flags (gnus-info-params info)))
1114           (if (and highestmodseq
1115                    (not start-article))
1116               ;; We've gotten the data by QRESYNCing.
1117               (nnimap-update-qresync-info
1118                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1119             ;; Do normal non-QRESYNC flag updates.
1120             ;; Update the list of read articles.
1121             (let* ((unread
1122                     (gnus-compress-sequence
1123                      (gnus-set-difference
1124                       (gnus-set-difference
1125                        existing
1126                        (cdr (assoc '%Seen flags)))
1127                       (cdr (assoc '%Flagged flags)))))
1128                    (read (gnus-range-difference
1129                           (cons start-article high) unread)))
1130               (when (> start-article 1)
1131                 (setq read
1132                       (gnus-range-nconcat
1133                        (if (> start-article 1)
1134                            (gnus-sorted-range-intersection
1135                             (cons 1 (1- start-article))
1136                             (gnus-info-read info))
1137                          (gnus-info-read info))
1138                        read)))
1139               (gnus-info-set-read info read)
1140               ;; Update the marks.
1141               (setq marks (gnus-info-marks info))
1142               (dolist (type (cdr nnimap-mark-alist))
1143                 (let ((old-marks (assoc (car type) marks))
1144                       (new-marks
1145                        (gnus-compress-sequence
1146                         (cdr (or (assoc (caddr type) flags) ; %Flagged
1147                                  (assoc (intern (cadr type) obarray) flags)
1148                                  (assoc (cadr type) flags)))))) ; "\Flagged"
1149                   (setq marks (delq old-marks marks))
1150                   (pop old-marks)
1151                   (when (and old-marks
1152                              (> start-article 1))
1153                     (setq old-marks (gnus-range-difference
1154                                      old-marks
1155                                      (cons start-article high)))
1156                     (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1157                   (when new-marks
1158                     (push (cons (car type) new-marks) marks)))
1159                 (gnus-info-set-marks info marks t)))))
1160         ;; Note the active level for the next run-through.
1161         (gnus-group-set-parameter info 'active (gnus-active group))
1162         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1163         (gnus-group-set-parameter info 'modseq highestmodseq)
1164         (nnimap-store-info info (gnus-active group)))))))
1165
1166 (defun nnimap-update-qresync-info (info existing vanished flags)
1167   ;; Add all the vanished articles to the list of read articles.
1168   (gnus-info-set-read
1169    info
1170    (gnus-add-to-range
1171     (gnus-add-to-range
1172      (gnus-range-add (gnus-info-read info)
1173                      vanished)
1174      (cdr (assq '%Flagged flags)))
1175     (cdr (assq '%Seen flags))))
1176   (let ((marks (gnus-info-marks info)))
1177     (dolist (type (cdr nnimap-mark-alist))
1178       (let ((ticks (assoc (car type) marks))
1179             (new-marks
1180              (cdr (or (assoc (caddr type) flags) ; %Flagged
1181                       (assoc (intern (cadr type) obarray) flags)
1182                       (assoc (cadr type) flags))))) ; "\Flagged"
1183         (setq marks (delq ticks marks))
1184         (pop ticks)
1185         ;; Add the new marks we got.
1186         (setq ticks (gnus-add-to-range ticks new-marks))
1187         ;; Remove the marks from messages that don't have them.
1188         (setq ticks (gnus-remove-from-range
1189                      ticks
1190                      (gnus-compress-sequence
1191                       (gnus-sorted-complement existing new-marks))))
1192         (when ticks
1193           (push (cons (car type) ticks) marks)))
1194       (gnus-info-set-marks info marks t))))
1195
1196 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1197   (if (zerop (length irange))
1198       nil
1199     (let ((result nil))
1200       (dolist (elem (split-string irange ","))
1201         (push
1202          (if (string-match ":" elem)
1203              (let ((numbers (split-string elem ":")))
1204                (cons (string-to-number (car numbers))
1205                      (string-to-number (cadr numbers))))
1206            (string-to-number elem))
1207          result))
1208       (nreverse result))))
1209
1210 (defun nnimap-store-info (info active)
1211   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1212          (entry (assoc group nnimap-current-infos)))
1213     (if entry
1214         (setcdr entry (list info active))
1215       (push (list group info active) nnimap-current-infos))))
1216
1217 (defun nnimap-flags-to-marks (groups)
1218   (let (data group totalp uidnext articles start-article mark permanent-flags
1219              uidvalidity vanished highestmodseq)
1220     (dolist (elem groups)
1221       (setq group (car elem)
1222             uidnext (nth 1 elem)
1223             start-article (nth 2 elem)
1224             permanent-flags (nth 3 elem)
1225             uidvalidity (nth 4 elem)
1226             vanished (nth 5 elem)
1227             highestmodseq (nth 6 elem)
1228             articles (nthcdr 7 elem))
1229       (let ((high (caar articles))
1230             marks low existing)
1231         (dolist (article articles)
1232           (setq low (car article))
1233           (push (car article) existing)
1234           (dolist (flag (cdr article))
1235             (setq mark (assoc flag marks))
1236             (if (not mark)
1237                 (push (list flag (car article)) marks)
1238               (setcdr mark (cons (car article) (cdr mark))))))
1239         (push (list group existing marks high low uidnext start-article
1240                     permanent-flags uidvalidity vanished highestmodseq)
1241               data)))
1242     data))
1243
1244 (defun nnimap-parse-flags (sequences)
1245   (goto-char (point-min))
1246   ;; Change \Delete etc to %Delete, so that the reader can read it.
1247   (subst-char-in-region (point-min) (point-max)
1248                         ?\\ ?% t)
1249   (let (start end articles groups uidnext elems permanent-flags
1250               uidvalidity vanished highestmodseq)
1251     (dolist (elem sequences)
1252       (destructuring-bind (group-sequence flag-sequence totalp group command)
1253           elem
1254         (setq start (point))
1255         (when (and
1256                ;; The EXAMINE was successful.
1257                (search-forward (format "\n%d OK " group-sequence) nil t)
1258                (progn
1259                  (forward-line 1)
1260                  (setq end (point))
1261                  (goto-char start)
1262                  (setq permanent-flags
1263                        (if (equal command "SELECT")
1264                            (and (search-forward "PERMANENTFLAGS "
1265                                                 (or end (point-min)) t)
1266                                 (read (current-buffer)))
1267                          'not-scanned))
1268                  (goto-char start)
1269                  (setq uidnext
1270                        (and (search-forward "UIDNEXT "
1271                                             (or end (point-min)) t)
1272                             (read (current-buffer))))
1273                  (goto-char start)
1274                  (setq uidvalidity
1275                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1276                                                (or end (point-min)) t)
1277                             ;; Store UIDVALIDITY as a string, as it's
1278                             ;; too big for 32-bit Emacsen, usually.
1279                             (match-string 1)))
1280                  (goto-char start)
1281                  (setq vanished
1282                        (and (eq flag-sequence 'qresync)
1283                             (re-search-forward "VANISHED.* \\([0-9:,]+\\)"
1284                                                (or end (point-min)) t)
1285                             (match-string 1)))
1286                  (goto-char start)
1287                  (setq highestmodseq
1288                        (and (search-forward "HIGHESTMODSEQ "
1289                                             (or end (point-min)) t)
1290                             (read (current-buffer))))
1291                  (goto-char end)
1292                  (forward-line -1))
1293                ;; The UID FETCH FLAGS was successful.
1294                (or (eq flag-sequence 'qresync)
1295                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1296           (if (eq flag-sequence 'qresync)
1297               (progn
1298                 (goto-char start)
1299                 (setq start end))
1300             (setq start (point))
1301             (goto-char end))
1302           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1303             (setq elems (read (current-buffer)))
1304             (push (cons (cadr (memq 'UID elems))
1305                         (cadr (memq 'FLAGS elems)))
1306                   articles))
1307           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1308                              vanished highestmodseq)
1309                        articles)
1310                 groups)
1311           (goto-char end)
1312           (setq articles nil))))
1313     groups))
1314
1315 (defun nnimap-find-process-buffer (buffer)
1316   (cadr (assoc buffer nnimap-connection-alist)))
1317
1318 (deffoo nnimap-request-post (&optional server)
1319   (setq nnimap-status-string "Read-only server")
1320   nil)
1321
1322 (deffoo nnimap-request-thread (id)
1323     (let* ((refs (split-string
1324                (or (mail-header-references (gnus-summary-article-header))
1325                    "")))
1326            (cmd (let ((value
1327                        (format
1328                         "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1329                         id id)))
1330                   (dolist (refid refs value)
1331                     (setq value (format
1332                                  "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1333                                  refid refid value)))))
1334            (result
1335             (with-current-buffer (nnimap-buffer)
1336               (nnimap-command  "UID SEARCH %s" cmd))))
1337       (gnus-fetch-headers (and (car result)
1338            (delete 0 (mapcar #'string-to-number
1339                              (cdr (assoc "SEARCH" (cdr result)))))))))
1340
1341 (defun nnimap-possibly-change-group (group server)
1342   (let ((open-result t))
1343     (when (and server
1344                (not (nnimap-server-opened server)))
1345       (setq open-result (nnimap-open-server server)))
1346     (cond
1347      ((not open-result)
1348       nil)
1349      ((not group)
1350       t)
1351      (t
1352       (with-current-buffer (nnimap-buffer)
1353         (if (equal group (nnimap-group nnimap-object))
1354             t
1355           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1356             (when (car result)
1357               (setf (nnimap-group nnimap-object) group
1358                     (nnimap-select-result nnimap-object) result)
1359               result))))))))
1360
1361 (defun nnimap-find-connection (buffer)
1362   "Find the connection delivering to BUFFER."
1363   (let ((entry (assoc buffer nnimap-connection-alist)))
1364     (when entry
1365       (if (and (buffer-name (cadr entry))
1366                (get-buffer-process (cadr entry))
1367                (memq (process-status (get-buffer-process (cadr entry)))
1368                      '(open run)))
1369           (get-buffer-process (cadr entry))
1370         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1371         nil))))
1372
1373 (defvar nnimap-sequence 0)
1374
1375 (defun nnimap-send-command (&rest args)
1376   (process-send-string
1377    (get-buffer-process (current-buffer))
1378    (nnimap-log-command
1379     (format "%d %s%s\n"
1380             (incf nnimap-sequence)
1381             (apply #'format args)
1382             (if (nnimap-newlinep nnimap-object)
1383                 ""
1384               "\r"))))
1385   nnimap-sequence)
1386
1387 (defun nnimap-log-command (command)
1388   (with-current-buffer (get-buffer-create "*imap log*")
1389     (goto-char (point-max))
1390     (insert (format-time-string "%H:%M:%S") " " command))
1391   command)
1392
1393 (defun nnimap-command (&rest args)
1394   (erase-buffer)
1395   (setf (nnimap-last-command-time nnimap-object) (current-time))
1396   (let* ((sequence (apply #'nnimap-send-command args))
1397          (response (nnimap-get-response sequence)))
1398     (if (equal (caar response) "OK")
1399         (cons t response)
1400       (nnheader-report 'nnimap "%s"
1401                        (mapconcat (lambda (a)
1402                                     (format "%s" a))
1403                                   (car response) " "))
1404       nil)))
1405
1406 (defun nnimap-get-response (sequence)
1407   (nnimap-wait-for-response sequence)
1408   (nnimap-parse-response))
1409
1410 (defun nnimap-wait-for-connection ()
1411   (let ((process (get-buffer-process (current-buffer))))
1412     (goto-char (point-min))
1413     (while (and (memq (process-status process)
1414                       '(open run))
1415                 (not (re-search-forward "^[*.] .*\n" nil t)))
1416       (nnheader-accept-process-output process)
1417       (goto-char (point-min)))
1418     (forward-line -1)
1419     (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1420          (match-string 1))))
1421
1422 (defun nnimap-wait-for-response (sequence &optional messagep)
1423   (let ((process (get-buffer-process (current-buffer)))
1424         openp)
1425     (condition-case nil
1426         (progn
1427           (goto-char (point-max))
1428           (while (and (setq openp (memq (process-status process)
1429                                         '(open run)))
1430                       (not (re-search-backward
1431                             (format "^%d .*\n" sequence)
1432                             (if nnimap-streaming
1433                                 (max (point-min) (- (point) 500))
1434                               (point-min))
1435                             t)))
1436             (when messagep
1437               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1438             (nnheader-accept-process-output process)
1439             (goto-char (point-max)))
1440           openp)
1441       (quit
1442        ;; The user hit C-g while we were waiting: kill the process, in case
1443        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1444        ;; NAT routers).
1445        (delete-process process)
1446        nil))))
1447
1448 (defun nnimap-parse-response ()
1449   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1450         result)
1451     (dolist (line lines)
1452       (push (cdr (nnimap-parse-line line)) result))
1453     ;; Return the OK/error code first, and then all the "continuation
1454     ;; lines" afterwards.
1455     (cons (pop result)
1456           (nreverse result))))
1457
1458 ;; Parse an IMAP response line lightly.  They look like
1459 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1460 ;; the lines into a list of strings and lists of string.
1461 (defun nnimap-parse-line (line)
1462   (let (char result)
1463     (with-temp-buffer
1464       (insert line)
1465       (goto-char (point-min))
1466       (while (not (eobp))
1467         (if (eql (setq char (following-char)) ? )
1468             (forward-char 1)
1469           (push
1470            (cond
1471             ((eql char ?\[)
1472              (split-string
1473               (buffer-substring
1474                (1+ (point))
1475                (1- (search-forward "]" (line-end-position) 'move)))))
1476             ((eql char ?\()
1477              (split-string
1478               (buffer-substring
1479                (1+ (point))
1480                (1- (search-forward ")" (line-end-position) 'move)))))
1481             ((eql char ?\")
1482              (forward-char 1)
1483              (buffer-substring
1484               (point)
1485               (1- (or (search-forward "\"" (line-end-position) 'move)
1486                       (point)))))
1487             (t
1488              (buffer-substring (point) (if (search-forward " " nil t)
1489                                            (1- (point))
1490                                          (goto-char (point-max))))))
1491            result)))
1492       (nreverse result))))
1493
1494 (defun nnimap-last-response-string ()
1495   (save-excursion
1496     (forward-line 1)
1497     (let ((end (point)))
1498       (forward-line -1)
1499       (when (not (bobp))
1500         (forward-line -1)
1501         (while (and (not (bobp))
1502                     (eql (following-char) ?*))
1503           (forward-line -1))
1504         (unless (eql (following-char) ?*)
1505           (forward-line 1)))
1506       (buffer-substring (point) end))))
1507
1508 (defun nnimap-get-responses (sequences)
1509   (let (responses)
1510     (dolist (sequence sequences)
1511       (goto-char (point-min))
1512       (when (re-search-forward (format "^%d " sequence) nil t)
1513         (push (list sequence (nnimap-parse-response))
1514               responses)))
1515     responses))
1516
1517 (defvar nnimap-incoming-split-list nil)
1518
1519 (defun nnimap-fetch-inbox (articles)
1520   (erase-buffer)
1521   (nnimap-wait-for-response
1522    (nnimap-send-command
1523     "UID FETCH %s %s"
1524     (nnimap-article-ranges articles)
1525     (format "(UID %s%s)"
1526             (format
1527              (if (nnimap-ver4-p)
1528                  "BODY.PEEK[HEADER] BODY.PEEK"
1529                "RFC822.PEEK"))
1530             (if nnimap-split-download-body-default
1531                 "[]"
1532               "[1]")))
1533    t))
1534
1535 (defun nnimap-split-incoming-mail ()
1536   (with-current-buffer (nnimap-buffer)
1537     (let ((nnimap-incoming-split-list nil)
1538           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1539                                     nnmail-split-methods
1540                                   nnimap-split-methods))
1541           (nnmail-split-fancy (or nnimap-split-fancy
1542                                   nnmail-split-fancy))
1543           (nnmail-inhibit-default-split-group t)
1544           (groups (nnimap-get-groups))
1545           new-articles)
1546       (erase-buffer)
1547       (nnimap-command "SELECT %S" nnimap-inbox)
1548       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1549       (when new-articles
1550         (nnimap-fetch-inbox new-articles)
1551         (nnimap-transform-split-mail)
1552         (nnheader-ms-strip-cr)
1553         (nnmail-cache-open)
1554         (nnmail-split-incoming (current-buffer)
1555                                #'nnimap-save-mail-spec
1556                                nil nil
1557                                #'nnimap-dummy-active-number
1558                                #'nnimap-save-mail-spec)
1559         (when nnimap-incoming-split-list
1560           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1561                 sequences junk-articles)
1562             ;; Create any groups that doesn't already exist on the
1563             ;; server first.
1564             (dolist (spec specs)
1565               (when (and (not (member (car spec) groups))
1566                          (not (eq (car spec) 'junk)))
1567                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1568             ;; Then copy over all the messages.
1569             (erase-buffer)
1570             (dolist (spec specs)
1571               (let ((group (car spec))
1572                     (ranges (cdr spec)))
1573                 (if (eq group 'junk)
1574                     (setq junk-articles ranges)
1575                   (push (list (nnimap-send-command
1576                                "UID COPY %s %S"
1577                                (nnimap-article-ranges ranges)
1578                                (utf7-encode group t))
1579                               ranges)
1580                         sequences))))
1581             ;; Wait for the last COPY response...
1582             (when sequences
1583               (nnimap-wait-for-response (caar sequences))
1584               ;; And then mark the successful copy actions as deleted,
1585               ;; and possibly expunge them.
1586               (nnimap-mark-and-expunge-incoming
1587                (nnimap-parse-copied-articles sequences)))
1588             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1589
1590 (defun nnimap-mark-and-expunge-incoming (range)
1591   (when range
1592     (setq range (nnimap-article-ranges range))
1593     (erase-buffer)
1594     (let ((sequence
1595            (nnimap-send-command
1596             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1597       (cond
1598        ;; If the server supports it, we now delete the message we have
1599        ;; just copied over.
1600        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1601         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1602        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1603        ;; user has configured it.
1604        (nnimap-expunge
1605         (setq sequence (nnimap-send-command "EXPUNGE"))))
1606       (nnimap-wait-for-response sequence))))
1607
1608 (defun nnimap-parse-copied-articles (sequences)
1609   (let (sequence copied range)
1610     (goto-char (point-min))
1611     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1612       (setq sequence (string-to-number (match-string 1)))
1613       (when (setq range (cadr (assq sequence sequences)))
1614         (push (gnus-uncompress-range range) copied)))
1615     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1616
1617 (defun nnimap-new-articles (flags)
1618   (let (new)
1619     (dolist (elem flags)
1620       (when (or (null (cdr elem))
1621                 (and (not (memq '%Deleted (cdr elem)))
1622                      (not (memq '%Seen (cdr elem)))))
1623         (push (car elem) new)))
1624     (gnus-compress-sequence (nreverse new))))
1625
1626 (defun nnimap-make-split-specs (list)
1627   (let ((specs nil)
1628         entry)
1629     (dolist (elem list)
1630       (destructuring-bind (article spec) elem
1631         (dolist (group (delete nil (mapcar #'car spec)))
1632           (unless (setq entry (assoc group specs))
1633             (push (setq entry (list group)) specs))
1634           (setcdr entry (cons article (cdr entry))))))
1635     (dolist (entry specs)
1636       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1637     specs))
1638
1639 (defun nnimap-transform-split-mail ()
1640   (goto-char (point-min))
1641   (let (article bytes)
1642     (block nil
1643       (while (not (eobp))
1644         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1645           (delete-region (point) (progn (forward-line 1) (point)))
1646           (when (eobp)
1647             (return)))
1648         (setq article (match-string 1)
1649               bytes (nnimap-get-length))
1650         (delete-region (line-beginning-position) (line-end-position))
1651         ;; Insert MMDF separator, and a way to remember what this
1652         ;; article UID is.
1653         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1654         (forward-char (1+ bytes))
1655         (setq bytes (nnimap-get-length))
1656         (delete-region (line-beginning-position) (line-end-position))
1657         ;; There's a body; skip past that.
1658         (when bytes
1659           (forward-char (1+ bytes))
1660           (delete-region (line-beginning-position) (line-end-position)))))))
1661
1662 (defun nnimap-dummy-active-number (group &optional server)
1663   1)
1664
1665 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1666   (let (article)
1667     (goto-char (point-min))
1668     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1669         (error "Invalid nnimap mail")
1670       (setq article (string-to-number (match-string 1))))
1671     (push (list article
1672                 (if (eq group-art 'junk)
1673                     (list (cons 'junk 1))
1674                   group-art))
1675           nnimap-incoming-split-list)))
1676
1677 (provide 'nnimap)
1678
1679 ;;; nnimap.el ends here