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