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