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