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