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