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