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