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