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