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