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