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