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