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