Merge remote-tracking branch 'origin/no-gnus'
[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             unexist)
1238         ;; Go through the infos and gather the data needed to know
1239         ;; what and how to request the data.
1240         (dolist (info infos)
1241           (setq params (gnus-info-params info)
1242                 group (nnimap-decode-gnus-group
1243                        (gnus-group-real-name (gnus-info-group info)))
1244                 active (cdr (assq 'active params))
1245                 unexist (assq 'unexist (gnus-info-marks info))
1246                 uidvalidity (cdr (assq 'uidvalidity params))
1247                 modseq (cdr (assq 'modseq params)))
1248           (setf (nnimap-examined nnimap-object) group)
1249           (if (and qresyncp
1250                    uidvalidity
1251                    active
1252                    modseq
1253                    unexist)
1254               (push
1255                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1256                                           (utf7-encode group t)
1257                                           (nnimap-quirk "QRESYNC")
1258                                           uidvalidity modseq)
1259                      'qresync
1260                      nil group 'qresync)
1261                sequences)
1262             (let ((command
1263                    (if uidvalidity
1264                        "EXAMINE"
1265                      ;; If we don't have a UIDVALIDITY, then this is
1266                      ;; the first time we've seen the group, so we
1267                      ;; have to do a SELECT (which is slower than an
1268                      ;; examine), but will tell us whether the group
1269                      ;; is read-only or not.
1270                      "SELECT"))
1271                   start)
1272               (if (and active uidvalidity unexist)
1273                   ;; Fetch the last 100 flags.
1274                   (setq start (max 1 (- (cdr active) 100)))
1275                 (incf (nnimap-initial-resync nnimap-object))
1276                 (setq start 1))
1277               (push (list (nnimap-send-command "%s %S" command
1278                                                (utf7-encode group t))
1279                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1280                           start group command)
1281                     sequences))))
1282         sequences))))
1283
1284 (defun nnimap-quirk (command)
1285   (let ((quirk (assoc command nnimap-quirks)))
1286     ;; If this server is of a type that matches a quirk, then return
1287     ;; the "quirked" command instead of the proper one.
1288     (if (or (null quirk)
1289             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1290         command
1291       (nth 2 quirk))))
1292
1293 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1294   (when (and sequences
1295              (nnimap-possibly-change-group nil server t)
1296              ;; Check that the process is still alive.
1297              (get-buffer-process (nnimap-buffer))
1298              (memq (process-status (get-buffer-process (nnimap-buffer)))
1299                    '(open run)))
1300     (with-current-buffer (nnimap-buffer)
1301       ;; Wait for the final data to trickle in.
1302       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1303                                           (caar sequences)
1304                                         (cadar sequences))
1305                                       t)
1306         ;; Now we should have most of the data we need, no matter
1307         ;; whether we're QRESYNCING, fetching all the flags from
1308         ;; scratch, or just fetching the last 100 flags per group.
1309         (nnimap-update-infos (nnimap-flags-to-marks
1310                               (nnimap-parse-flags
1311                                (nreverse sequences)))
1312                              infos)
1313         ;; Finally, just return something resembling an active file in
1314         ;; the nntp buffer, so that the agent can save the info, too.
1315         (with-current-buffer nntp-server-buffer
1316           (erase-buffer)
1317           (dolist (info infos)
1318             (let* ((group (gnus-info-group info))
1319                    (active (gnus-active group)))
1320               (when active
1321                 (insert (format "%S %d %d y\n"
1322                                 (decode-coding-string
1323                                  (gnus-group-real-name group) 'utf-8)
1324                                 (cdr active)
1325                                 (car active)))))))))))
1326
1327 (defun nnimap-update-infos (flags infos)
1328   (dolist (info infos)
1329     (let* ((group (nnimap-decode-gnus-group
1330                    (gnus-group-real-name (gnus-info-group info))))
1331            (marks (cdr (assoc group flags))))
1332       (when marks
1333         (nnimap-update-info info marks)))))
1334
1335 (defun nnimap-update-info (info marks)
1336   (destructuring-bind (existing flags high low uidnext start-article
1337                                 permanent-flags uidvalidity
1338                                 vanished highestmodseq) marks
1339     (cond
1340      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1341      ;; completely empty groups.
1342      ((and (not existing)
1343            (not uidnext))
1344       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1345         (when active
1346           (gnus-set-active (gnus-info-group info) active))))
1347      ;; We have a mismatch between the old and new UIDVALIDITY
1348      ;; identifiers, so we have to re-request the group info (the next
1349      ;; time).  This virtually never happens.
1350      ((let ((old-uidvalidity
1351              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1352         (and old-uidvalidity
1353              (not (equal old-uidvalidity uidvalidity))
1354              (or (not start-article)
1355                  (> start-article 1))))
1356       (gnus-group-remove-parameter info 'uidvalidity)
1357       (gnus-group-remove-parameter info 'modseq))
1358      ;; We have the data needed to update.
1359      (t
1360       (let* ((group (gnus-info-group info))
1361              (completep (and start-article
1362                              (= start-article 1)))
1363              (active (or (gnus-active group)
1364                          (cdr (assq 'active (gnus-info-params info))))))
1365         (when uidnext
1366           (setq high (1- uidnext)))
1367         ;; First set the active ranges based on high/low.
1368         (if (or completep
1369                 (not (gnus-active group)))
1370             (gnus-set-active group
1371                              (cond
1372                               (active
1373                                (cons (min (or low (car active))
1374                                           (car active))
1375                                      (max (or high (cdr active))
1376                                           (cdr active))))
1377                               ((and low high)
1378                                (cons low high))
1379                               (uidnext
1380                                ;; No articles in this group.
1381                                (cons uidnext (1- uidnext)))
1382                               (start-article
1383                                (cons start-article (1- start-article)))
1384                               (t
1385                                ;; No articles and no uidnext.
1386                                nil)))
1387           (gnus-set-active group
1388                            (cons (car active)
1389                                  (or high (1- uidnext)))))
1390         ;; See whether this is a read-only group.
1391         (unless (eq permanent-flags 'not-scanned)
1392           (gnus-group-set-parameter
1393            info 'permanent-flags
1394            (and (or (memq '%* permanent-flags)
1395                     (memq '%Seen permanent-flags))
1396                 permanent-flags)))
1397         ;; Update marks and read articles if this isn't a
1398         ;; read-only IMAP group.
1399         (when (setq permanent-flags
1400                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1401           (if (and highestmodseq
1402                    (not start-article))
1403               ;; We've gotten the data by QRESYNCing.
1404               (nnimap-update-qresync-info
1405                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1406             ;; Do normal non-QRESYNC flag updates.
1407             ;; Update the list of read articles.
1408             (let* ((unread
1409                     (gnus-compress-sequence
1410                      (gnus-set-difference
1411                       (gnus-set-difference
1412                        existing
1413                        (cdr (assoc '%Seen flags)))
1414                       (cdr (assoc '%Flagged flags)))))
1415                    (read (gnus-range-difference
1416                           (cons start-article high) unread)))
1417               (when (> start-article 1)
1418                 (setq read