Accept the moronic openssl s_client -starttls output, too.
[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 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40 (require 'utf7)
41 (require 'tls)
42 (require 'parse-time)
43
44 (autoload 'auth-source-forget-user-or-password "auth-source")
45 (autoload 'auth-source-user-or-password "auth-source")
46
47 (nnoo-declare nnimap)
48
49 (defvoo nnimap-address nil
50   "The address of the IMAP server.")
51
52 (defvoo nnimap-server-port nil
53   "The IMAP port used.
54 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
55 it will default to `imap'.")
56
57 (defvoo nnimap-stream 'ssl
58   "How nnimap will talk to the IMAP server.
59 Values are `ssl', `network', `starttls' or `shell'.")
60
61 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
62                                  (if (listp imap-shell-program)
63                                      (car imap-shell-program)
64                                    imap-shell-program)
65                                "ssh %s imapd"))
66
67 (defvoo nnimap-inbox nil
68   "The mail box where incoming mail arrives and should be split out of.")
69
70 (defvoo nnimap-split-methods nil
71   "How mail is split.
72 Uses the same syntax as nnmail-split-methods")
73
74 (defvoo nnimap-split-fancy nil
75   "Uses the same syntax as nnmail-split-fancy.")
76
77 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
78                         "Emacs 24.1")
79
80 (defvoo nnimap-authenticator nil
81   "How nnimap authenticate itself to the server.
82 Possible choices are nil (use default methods) or `anonymous'.")
83
84 (defvoo nnimap-expunge t
85   "If non-nil, expunge articles after deleting them.
86 This is always done if the server supports UID EXPUNGE, but it's
87 not done by default on servers that doesn't support that command.")
88
89 (defvoo nnimap-streaming t
90   "If non-nil, try to use streaming commands with IMAP servers.
91 Switching this off will make nnimap slower, but it helps with
92 some servers.")
93
94 (defvoo nnimap-connection-alist nil)
95
96 (defvoo nnimap-current-infos nil)
97
98 (defvoo nnimap-fetch-partial-articles nil
99   "If non-nil, Gnus will fetch partial articles.
100 If t, nnimap will fetch only the first part.  If a string, it
101 will fetch all parts that have types that match that string.  A
102 likely value would be \"text/\" to automatically fetch all
103 textual parts.")
104
105 (defvar nnimap-process nil)
106
107 (defvar nnimap-status-string "")
108
109 (defvar nnimap-split-download-body-default nil
110   "Internal variable with default value for `nnimap-split-download-body'.")
111
112 (defvar nnimap-keepalive-timer nil)
113 (defvar nnimap-process-buffers nil)
114
115 (defstruct nnimap
116   group process commands capabilities select-result newlinep server
117   last-command-time greeting)
118
119 (defvar nnimap-object nil)
120
121 (defvar nnimap-mark-alist
122   '((read "\\Seen" %Seen)
123     (tick "\\Flagged" %Flagged)
124     (reply "\\Answered" %Answered)
125     (expire "gnus-expire")
126     (dormant "gnus-dormant")
127     (score "gnus-score")
128     (save "gnus-save")
129     (download "gnus-download")
130     (forward "gnus-forward")))
131
132 (defun nnimap-buffer ()
133   (nnimap-find-process-buffer nntp-server-buffer))
134
135 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
136   (with-current-buffer nntp-server-buffer
137     (erase-buffer)
138     (when (nnimap-possibly-change-group group server)
139       (with-current-buffer (nnimap-buffer)
140         (erase-buffer)
141         (nnimap-wait-for-response
142          (nnimap-send-command
143           "UID FETCH %s %s"
144           (nnimap-article-ranges (gnus-compress-sequence articles))
145           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
146                   (format
147                    (if (nnimap-ver4-p)
148                        "BODY.PEEK[HEADER.FIELDS %s]"
149                      "RFC822.HEADER.LINES %s")
150                    (append '(Subject From Date Message-Id
151                                      References In-Reply-To Xref)
152                            nnmail-extra-headers))))
153          t)
154         (nnimap-transform-headers))
155       (insert-buffer-substring
156        (nnimap-find-process-buffer (current-buffer))))
157     'headers))
158
159 (defun nnimap-transform-headers ()
160   (goto-char (point-min))
161   (let (article bytes lines size string)
162     (block nil
163       (while (not (eobp))
164         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
165           (delete-region (point) (progn (forward-line 1) (point)))
166           (when (eobp)
167             (return)))
168         (setq article (match-string 1))
169         ;; Unfold quoted {number} strings.
170         (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
171                                   (1+ (line-end-position)) t)
172           (setq size (string-to-number (match-string 1)))
173           (delete-region (+ (match-beginning 0) 2) (point))
174           (setq string (delete-region (point) (+ (point) size)))
175           (insert (format "%S" string)))
176         (setq bytes (nnimap-get-length)
177               lines nil)
178         (beginning-of-line)
179         (setq size
180               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
181                                       (line-end-position)
182                                       t)
183                    (match-string 1)))
184         (beginning-of-line)
185         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
186           (let ((structure (ignore-errors
187                              (read (current-buffer)))))
188             (while (and (consp structure)
189                         (not (stringp (car structure))))
190               (setq structure (car structure)))
191             (setq lines (nth 7 structure))))
192         (delete-region (line-beginning-position) (line-end-position))
193         (insert (format "211 %s Article retrieved." article))
194         (forward-line 1)
195         (when size
196           (insert (format "Chars: %s\n" size)))
197         (when lines
198           (insert (format "Lines: %s\n" lines)))
199         (re-search-forward "^\r$")
200         (delete-region (line-beginning-position) (line-end-position))
201         (insert ".")
202         (forward-line 1)))))
203
204 (defun nnimap-get-length ()
205   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
206        (string-to-number (match-string 1))))
207
208 (defun nnimap-article-ranges (ranges)
209   (let (result)
210     (cond
211      ((numberp ranges)
212       (number-to-string ranges))
213      ((numberp (cdr ranges))
214       (format "%d:%d" (car ranges) (cdr ranges)))
215      (t
216       (dolist (elem ranges)
217         (push
218          (if (consp elem)
219              (format "%d:%d" (car elem) (cdr elem))
220            (number-to-string elem))
221          result))
222       (mapconcat #'identity (nreverse result) ",")))))
223
224 (deffoo nnimap-open-server (server &optional defs)
225   (if (nnimap-server-opened server)
226       t
227     (unless (assq 'nnimap-address defs)
228       (setq defs (append defs (list (list 'nnimap-address server)))))
229     (nnoo-change-server 'nnimap server defs)
230     (or (nnimap-find-connection nntp-server-buffer)
231         (nnimap-open-connection nntp-server-buffer))))
232
233 (defun nnimap-make-process-buffer (buffer)
234   (with-current-buffer
235       (generate-new-buffer (format "*nnimap %s %s %s*"
236                                    nnimap-address nnimap-server-port
237                                    (gnus-buffer-exists-p buffer)))
238     (mm-disable-multibyte)
239     (buffer-disable-undo)
240     (gnus-add-buffer)
241     (set (make-local-variable 'after-change-functions) nil)
242     (set (make-local-variable 'nnimap-object)
243          (make-nnimap :server (nnoo-current-server 'nnimap)))
244     (push (list buffer (current-buffer)) nnimap-connection-alist)
245     (push (current-buffer) nnimap-process-buffers)
246     (current-buffer)))
247
248 (defun nnimap-open-shell-stream (name buffer host port)
249   (let ((process-connection-type nil))
250     (start-process name buffer shell-file-name
251                    shell-command-switch
252                    (format-spec
253                     nnimap-shell-program
254                     (format-spec-make
255                      ?s host
256                      ?p port)))))
257
258 (defun nnimap-credentials (address ports &optional inhibit-create)
259   (let (port credentials)
260     ;; Request the credentials from all ports, but only query on the
261     ;; last port if all the previous ones have failed.
262     (while (and (null credentials)
263                 (setq port (pop ports)))
264       (setq credentials
265             (auth-source-user-or-password
266              '("login" "password") address port nil
267              (if inhibit-create
268                  nil
269                (null ports)))))
270     credentials))
271
272 (defun nnimap-keepalive ()
273   (let ((now (current-time)))
274     (dolist (buffer nnimap-process-buffers)
275       (when (buffer-name buffer)
276         (with-current-buffer buffer
277           (when (and nnimap-object
278                      (nnimap-last-command-time nnimap-object)
279                      (> (time-to-seconds
280                          (time-subtract
281                           now
282                           (nnimap-last-command-time nnimap-object)))
283                         ;; More than five minutes since the last command.
284                         (* 5 60)))
285             (nnimap-send-command "NOOP")))))))
286
287 (defun nnimap-open-connection (buffer)
288   (unless nnimap-keepalive-timer
289     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
290                                               'nnimap-keepalive)))
291   (block nil
292     (with-current-buffer (nnimap-make-process-buffer buffer)
293       (let* ((coding-system-for-read 'binary)
294              (coding-system-for-write 'binary)
295              (port nil)
296              (ports
297               (cond
298                ((eq nnimap-stream 'network)
299                 (open-network-stream
300                  "*nnimap*" (current-buffer) nnimap-address
301                  (setq port
302                        (or nnimap-server-port
303                            (if (netrc-find-service-number "imap")
304                                "imap"
305                              "143"))))
306                 '("143" "imap"))
307                ((eq nnimap-stream 'shell)
308                 (nnimap-open-shell-stream
309                  "*nnimap*" (current-buffer) nnimap-address
310                  (setq port (or nnimap-server-port "imap")))
311                 '("imap"))
312                ((eq nnimap-stream 'starttls)
313                 (let ((tls-program (nnimap-extend-tls-programs)))
314                   (open-tls-stream
315                    "*nnimap*" (current-buffer) nnimap-address
316                    (setq port (or nnimap-server-port "imap"))
317                    'starttls))
318                 '("imap"))
319                ((eq nnimap-stream 'ssl)
320                 (open-tls-stream
321                  "*nnimap*" (current-buffer) nnimap-address
322                  (setq port
323                        (or nnimap-server-port
324                            (if (netrc-find-service-number "imaps")
325                                "imaps"
326                              "993"))))
327                 '("143" "993" "imap" "imaps"))))
328              connection-result login-result credentials)
329         (setf (nnimap-process nnimap-object)
330               (get-buffer-process (current-buffer)))
331         (if (not (and (nnimap-process nnimap-object)
332                       (memq (process-status (nnimap-process nnimap-object))
333                             '(open run))))
334             (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
335                              nnimap-address port nnimap-stream)
336           (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
337           (if (not (setq connection-result (nnimap-wait-for-connection)))
338               (nnheader-report 'nnimap
339                                "%s" (buffer-substring
340                                      (point) (line-end-position)))
341             ;; Store the greeting (for debugging purposes).
342             (setf (nnimap-greeting nnimap-object)
343                   (buffer-substring (line-beginning-position)
344                                     (line-end-position)))
345             ;; Store the capabilities.
346             (setf (nnimap-capabilities nnimap-object)
347                   (mapcar
348                    #'upcase
349                    (nnimap-find-parameter
350                     "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
351             (when nnimap-server-port
352               (push (format "%s" nnimap-server-port) ports))
353             (unless (equal connection-result "PREAUTH")
354               (if (not (setq credentials
355                              (if (eq nnimap-authenticator 'anonymous)
356                                  (list "anonymous"
357                                        (message-make-address))
358                                (or
359                                 ;; First look for the credentials based
360                                 ;; on the virtual server name.
361                                 (nnimap-credentials
362                                  (nnoo-current-server 'nnimap) ports t)
363                                 ;; Then look them up based on the
364                                 ;; physical address.
365                                 (nnimap-credentials nnimap-address ports)))))
366                   (setq nnimap-object nil)
367                 (setq login-result (nnimap-command "LOGIN %S %S"
368                                                    (car credentials)
369                                                    (cadr credentials)))
370                 (unless (car login-result)
371                   ;; If the login failed, then forget the credentials
372                   ;; that are now possibly cached.
373                   (dolist (host (list (nnoo-current-server 'nnimap)
374                                       nnimap-address))
375                     (dolist (port ports)
376                       (dolist (element '("login" "password"))
377                         (auth-source-forget-user-or-password
378                          element host port))))
379                   (delete-process (nnimap-process nnimap-object))
380                   (setq nnimap-object nil))))
381             (when nnimap-object
382               (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
383                 (nnimap-command "ENABLE QRESYNC"))
384               t)))))))
385
386 (defun nnimap-extend-tls-programs ()
387   (let ((programs tls-program)
388         result)
389     (unless (consp programs)
390       (setq programs (list programs)))
391     (dolist (program programs)
392       (push (concat program " " "%s") result))
393     (nreverse result)))
394
395 (defun nnimap-find-parameter (parameter elems)
396   (let (result)
397     (dolist (elem elems)
398       (cond
399        ((equal (car elem) parameter)
400         (setq result (cdr elem)))
401        ((and (equal (car elem) "OK")
402              (consp (cadr elem))
403              (equal (caadr elem) parameter))
404         (setq result (cdr (cadr elem))))))
405     result))
406
407 (deffoo nnimap-close-server (&optional server)
408   t)
409
410 (deffoo nnimap-request-close ()
411   t)
412
413 (deffoo nnimap-server-opened (&optional server)
414   (and (nnoo-current-server-p 'nnimap server)
415        nntp-server-buffer
416        (gnus-buffer-live-p nntp-server-buffer)
417        (nnimap-find-connection nntp-server-buffer)))
418
419 (deffoo nnimap-status-message (&optional server)
420   nnimap-status-string)
421
422 (deffoo nnimap-request-article (article &optional group server to-buffer)
423   (with-current-buffer nntp-server-buffer
424     (let ((result (nnimap-possibly-change-group group server))
425           parts structure)
426       (when (stringp article)
427         (setq article (nnimap-find-article-by-message-id group article)))
428       (when (and result
429                  article)
430         (erase-buffer)
431         (with-current-buffer (nnimap-buffer)
432           (erase-buffer)
433           (when nnimap-fetch-partial-articles
434             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
435             (goto-char (point-min))
436             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
437               (setq structure (ignore-errors
438                                 (let ((start (point)))
439                                   (forward-sexp 1)
440                                   (downcase-region start (point))
441                                   (goto-char (point))
442                                   (read (current-buffer))))
443                     parts (nnimap-find-wanted-parts structure))))
444           (when (if parts
445                     (nnimap-get-partial-article article parts structure)
446                   (nnimap-get-whole-article article))
447             (let ((buffer (current-buffer)))
448               (with-current-buffer (or to-buffer nntp-server-buffer)
449                 (erase-buffer)
450                 (insert-buffer-substring buffer)
451                 (nnheader-ms-strip-cr)
452                 (cons group article)))))))))
453
454 (defun nnimap-get-whole-article (article)
455   (let ((result
456          (nnimap-command
457           (if (nnimap-ver4-p)
458               "UID FETCH %d BODY.PEEK[]"
459             "UID FETCH %d RFC822.PEEK")
460           article)))
461     ;; Check that we really got an article.
462     (goto-char (point-min))
463     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
464       (setq result nil))
465     (when result
466       ;; Remove any data that may have arrived before the FETCH data.
467       (beginning-of-line)
468       (unless (bobp)
469         (delete-region (point-min) (point)))
470       (let ((bytes (nnimap-get-length)))
471         (delete-region (line-beginning-position)
472                        (progn (forward-line 1) (point)))
473         (goto-char (+ (point) bytes))
474         (delete-region (point) (point-max)))
475       t)))
476
477 (defun nnimap-ver4-p ()
478   (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
479
480 (defun nnimap-get-partial-article (article parts structure)
481   (let ((result
482          (nnimap-command
483           "UID FETCH %d (%s %s)"
484           article
485           (if (nnimap-ver4-p)
486               "BODY.PEEK[HEADER]"
487             "RFC822.HEADER")
488           (if (nnimap-ver4-p)
489               (mapconcat (lambda (part)
490                            (format "BODY.PEEK[%s]" part))
491                          parts " ")
492             (mapconcat (lambda (part)
493                          (format "RFC822.PEEK[%s]" part))
494                        parts " ")))))
495     (when result
496       (nnimap-convert-partial-article structure))))
497
498 (defun nnimap-convert-partial-article (structure)
499   ;; First just skip past the headers.
500   (goto-char (point-min))
501   (let ((bytes (nnimap-get-length))
502         id parts)
503     ;; Delete "FETCH" line.
504     (delete-region (line-beginning-position)
505                    (progn (forward-line 1) (point)))
506     (goto-char (+ (point) bytes))
507     ;; Collect all the body parts.
508     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
509       (setq id (match-string 1)
510             bytes (nnimap-get-length))
511       (beginning-of-line)
512       (delete-region (point) (progn (forward-line 1) (point)))
513       (push (list id (buffer-substring (point) (+ (point) bytes)))
514             parts)
515       (delete-region (point) (+ (point) bytes)))
516     ;; Delete trailing junk.
517     (delete-region (point) (point-max))
518     ;; Now insert all the parts again where they fit in the structure.
519     (nnimap-insert-partial-structure structure parts)
520     t))
521
522 (defun nnimap-insert-partial-structure (structure parts &optional subp)
523   (let (type boundary)
524     (let ((bstruc structure))
525       (while (consp (car bstruc))
526         (pop bstruc))
527       (setq type (car bstruc))
528       (setq bstruc (car (cdr bstruc)))
529       (when (and (stringp (car bstruc))
530                  (string= (downcase (car bstruc)) "boundary"))
531         (setq boundary (cadr bstruc))))
532     (when subp
533       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
534                       (downcase type) boundary)))
535     (while (not (stringp (car structure)))
536       (insert "\n--" boundary "\n")
537       (if (consp (caar structure))
538           (nnimap-insert-partial-structure (pop structure) parts t)
539         (let ((bit (pop structure)))
540           (insert (format  "Content-type: %s/%s"
541                            (downcase (nth 0 bit))
542                            (downcase (nth 1 bit))))
543           (if (member "CHARSET" (nth 2 bit))
544               (insert (format
545                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
546             (insert "\n"))
547           (insert (format "Content-transfer-encoding: %s\n"
548                           (nth 5 bit)))
549           (insert "\n")
550           (when (assoc (nth 9 bit) parts)
551             (insert (cadr (assoc (nth 9 bit) parts)))))))
552     (insert "\n--" boundary "--\n")))
553
554 (defun nnimap-find-wanted-parts (structure)
555   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
556
557 (defun nnimap-find-wanted-parts-1 (structure prefix)
558   (let ((num 1)
559         parts)
560     (while (consp (car structure))
561       (let ((sub (pop structure)))
562         (if (consp (car sub))
563             (push (nnimap-find-wanted-parts-1
564                    sub (if (string= prefix "")
565                            (number-to-string num)
566                          (format "%s.%s" prefix num)))
567                   parts)
568           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
569                 (id (if (string= prefix "")
570                         (number-to-string num)
571                       (format "%s.%s" prefix num))))
572             (setcar (nthcdr 9 sub) id)
573             (when (if (eq nnimap-fetch-partial-articles t)
574                       (equal id "1")
575                     (string-match nnimap-fetch-partial-articles type))
576               (push id parts))))
577         (incf num)))
578     (nreverse parts)))
579
580 (deffoo nnimap-request-group (group &optional server dont-check info)
581   (let ((result (nnimap-possibly-change-group group server))
582         articles active marks high low)
583     (with-current-buffer nntp-server-buffer
584       (when result
585         (if (and dont-check
586                  (setq active (nth 2 (assoc group nnimap-current-infos))))
587             (insert (format "211 %d %d %d %S\n"
588                             (- (cdr active) (car active))
589                             (car active)
590                             (cdr active)
591                             group))
592           (with-current-buffer (nnimap-buffer)
593             (erase-buffer)
594             (let ((group-sequence
595                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
596                   (flag-sequence
597                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
598               (nnimap-wait-for-response flag-sequence)
599               (setq marks
600                     (nnimap-flags-to-marks
601                      (nnimap-parse-flags
602                       (list (list group-sequence flag-sequence 1 group)))))
603               (when info
604                 (nnimap-update-infos marks (list info)))
605               (goto-char (point-max))
606               (let ((uidnext (nth 5 (car marks))))
607                 (setq high (if uidnext
608                                (1- uidnext)
609                              (nth 3 (car marks)))
610                       low (or (nth 4 (car marks)) uidnext)))))
611           (erase-buffer)
612           (insert
613            (format
614             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
615         t))))
616
617 (deffoo nnimap-request-create-group (group &optional server args)
618   (when (nnimap-possibly-change-group nil server)
619     (with-current-buffer (nnimap-buffer)
620       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
621
622 (deffoo nnimap-request-delete-group (group &optional force server)
623   (when (nnimap-possibly-change-group nil server)
624     (with-current-buffer (nnimap-buffer)
625       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
626
627 (deffoo nnimap-request-expunge-group (group &optional server)
628   (when (nnimap-possibly-change-group group server)
629     (with-current-buffer (nnimap-buffer)
630       (car (nnimap-command "EXPUNGE")))))
631
632 (defun nnimap-get-flags (spec)
633   (let ((articles nil)
634         elems)
635     (with-current-buffer (nnimap-buffer)
636       (erase-buffer)
637       (nnimap-wait-for-response (nnimap-send-command
638                                  "UID FETCH %s FLAGS" spec))
639       (goto-char (point-min))
640       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
641         (setq elems (nnimap-parse-line (match-string 1)))
642         (push (cons (string-to-number (cadr (member "UID" elems)))
643                     (cadr (member "FLAGS" elems)))
644               articles)))
645     (nreverse articles)))
646
647 (deffoo nnimap-close-group (group &optional server)
648   t)
649
650 (deffoo nnimap-request-move-article (article group server accept-form
651                                              &optional last internal-move-group)
652   (with-temp-buffer
653     (when (nnimap-request-article article group server (current-buffer))
654       ;; If the move is internal (on the same server), just do it the easy
655       ;; way.
656       (let ((message-id (message-field-value "message-id")))
657         (if internal-move-group
658             (let ((result
659                    (with-current-buffer (nnimap-buffer)
660                      (nnimap-command "UID COPY %d %S"
661                                      article
662                                      (utf7-encode internal-move-group t)))))
663               (when (car result)
664                 (nnimap-delete-article article)
665                 (cons internal-move-group
666                       (nnimap-find-article-by-message-id
667                        internal-move-group message-id))))
668           ;; Move the article to a different method.
669           (let ((result (eval accept-form)))
670             (when result
671               (nnimap-delete-article article)
672               result)))))))
673
674 (deffoo nnimap-request-expire-articles (articles group &optional server force)
675   (cond
676    ((null articles)
677     nil)
678    ((not (nnimap-possibly-change-group group server))
679     articles)
680    ((and force
681          (eq nnmail-expiry-target 'delete))
682     (unless (nnimap-delete-article (gnus-compress-sequence articles))
683       (message "Article marked for deletion, but not expunged."))
684     nil)
685    (t
686     (let ((deletable-articles
687            (if (or force
688                    (eq nnmail-expiry-wait 'immediate))
689                articles
690              (gnus-sorted-intersection
691               articles
692               (nnimap-find-expired-articles group)))))
693       (if (null deletable-articles)
694           articles
695         (if (eq nnmail-expiry-target 'delete)
696             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
697           (setq deletable-articles
698                 (nnimap-process-expiry-targets
699                  deletable-articles group server)))
700         ;; Return the articles we didn't delete.
701         (gnus-sorted-complement articles deletable-articles))))))
702
703 (defun nnimap-process-expiry-targets (articles group server)
704   (let ((deleted-articles nil))
705     (dolist (article articles)
706       (let ((target nnmail-expiry-target))
707         (with-temp-buffer
708           (when (nnimap-request-article article group server (current-buffer))
709             (message "Expiring article %s:%d" group article)
710             (when (functionp target)
711               (setq target (funcall target group)))
712             (when (and target
713                        (not (eq target 'delete)))
714               (if (or (gnus-request-group target t)
715                       (gnus-request-create-group target))
716                   (nnmail-expiry-target-group target group)
717                 (setq target nil)))
718             (when target
719               (push article deleted-articles))))))
720     ;; Change back to the current group again.
721     (nnimap-possibly-change-group group server)
722     (setq deleted-articles (nreverse deleted-articles))
723     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
724     deleted-articles))
725
726 (defun nnimap-find-expired-articles (group)
727   (let ((cutoff (nnmail-expired-article-p group nil nil)))
728     (with-current-buffer (nnimap-buffer)
729       (let ((result
730              (nnimap-command
731               "UID SEARCH SENTBEFORE %s"
732               (format-time-string
733                (format "%%d-%s-%%Y"
734                        (upcase
735                         (car (rassoc (nth 4 (decode-time cutoff))
736                                      parse-time-months))))
737                cutoff))))
738         (and (car result)
739              (delete 0 (mapcar #'string-to-number
740                                (cdr (assoc "SEARCH" (cdr result))))))))))
741
742
743 (defun nnimap-find-article-by-message-id (group message-id)
744   (with-current-buffer (nnimap-buffer)
745     (erase-buffer)
746     (setf (nnimap-group nnimap-object) nil)
747     (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
748     (let ((sequence
749            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
750           article result)
751       (setq result (nnimap-wait-for-response sequence))
752       (when (and result
753                  (car (setq result (nnimap-parse-response))))
754         ;; Select the last instance of the message in the group.
755         (and (setq article
756                    (car (last (assoc "SEARCH" (cdr result)))))
757              (string-to-number article))))))
758
759 (defun nnimap-delete-article (articles)
760   (with-current-buffer (nnimap-buffer)
761     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
762                     (nnimap-article-ranges articles))
763     (cond
764      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
765       (nnimap-command "UID EXPUNGE %s"
766                       (nnimap-article-ranges articles))
767       t)
768      (nnimap-expunge
769       (nnimap-command "EXPUNGE")
770       t)
771      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
772                                 "server doesn't support UIDPLUS, so we won't "
773                                 "delete this article now"))))))
774
775 (deffoo nnimap-request-scan (&optional group server)
776   (when (and (nnimap-possibly-change-group nil server)
777              nnimap-inbox
778              nnimap-split-methods)
779     (message "nnimap %s splitting mail..." server)
780     (nnimap-split-incoming-mail)))
781
782 (defun nnimap-marks-to-flags (marks)
783   (let (flags flag)
784     (dolist (mark marks)
785       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
786         (push flag flags)))
787     flags))
788
789 (deffoo nnimap-request-set-mark (group actions &optional server)
790   (when (nnimap-possibly-change-group group server)
791     (let (sequence)
792       (with-current-buffer (nnimap-buffer)
793         (erase-buffer)
794         ;; Just send all the STORE commands without waiting for
795         ;; response.  If they're successful, they're successful.
796         (dolist (action actions)
797           (destructuring-bind (range action marks) action
798             (let ((flags (nnimap-marks-to-flags marks)))
799               (when flags
800                 (setq sequence (nnimap-send-command
801                                 "UID STORE %s %sFLAGS.SILENT (%s)"
802                                 (nnimap-article-ranges range)
803                                 (if (eq action 'del)
804                                     "-"
805                                   "+")
806                                 (mapconcat #'identity flags " ")))))))
807         ;; Wait for the last command to complete to avoid later
808         ;; syncronisation problems with the stream.
809         (when sequence
810           (nnimap-wait-for-response sequence))))))
811
812 (deffoo nnimap-request-accept-article (group &optional server last)
813   (when (nnimap-possibly-change-group nil server)
814     (nnmail-check-syntax)
815     (let ((message-id (message-field-value "message-id"))
816           sequence message)
817       (nnimap-add-cr)
818       (setq message (buffer-string))
819       (with-current-buffer (nnimap-buffer)
820         (setq sequence (nnimap-send-command
821                         "APPEND %S {%d}" (utf7-encode group t)
822                         (length message)))
823         (process-send-string (get-buffer-process (current-buffer)) message)
824         (process-send-string (get-buffer-process (current-buffer))
825                              (if (nnimap-newlinep nnimap-object)
826                                  "\n"
827                                "\r\n"))
828         (let ((result (nnimap-get-response sequence)))
829           (if (not (car result))
830               (progn
831                 (message "%s" (nnheader-get-report-string 'nnimap))
832                 nil)
833             (cons group
834                   (nnimap-find-article-by-message-id group message-id))))))))
835
836 (defun nnimap-add-cr ()
837   (goto-char (point-min))
838   (while (re-search-forward "\r?\n" nil t)
839     (replace-match "\r\n" t t)))
840
841 (defun nnimap-get-groups ()
842   (let ((result (nnimap-command "LIST \"\" \"*\""))
843         groups)
844     (when (car result)
845       (dolist (line (cdr result))
846         (when (and (equal (car line) "LIST")
847                    (not (and (caadr line)
848                              (string-match "noselect" (caadr line)))))
849           (push (car (last line)) groups)))
850       (nreverse groups))))
851
852 (deffoo nnimap-request-list (&optional server)
853   (nnimap-possibly-change-group nil server)
854   (with-current-buffer nntp-server-buffer
855     (erase-buffer)
856     (let ((groups
857            (with-current-buffer (nnimap-buffer)
858              (nnimap-get-groups)))
859           sequences responses)
860       (when groups
861         (with-current-buffer (nnimap-buffer)
862           (setf (nnimap-group nnimap-object) nil)
863           (dolist (group groups)
864             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
865                         group)
866                   sequences))
867           (nnimap-wait-for-response (caar sequences))
868           (setq responses
869                 (nnimap-get-responses (mapcar #'car sequences))))
870         (dolist (response responses)
871           (let* ((sequence (car response))
872                  (response (cadr response))
873                  (group (cadr (assoc sequence sequences))))
874             (when (and group
875                        (equal (caar response) "OK"))
876               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
877                     highest exists)
878                 (dolist (elem response)
879                   (when (equal (cadr elem) "EXISTS")
880                     (setq exists (string-to-number (car elem)))))
881                 (when uidnext
882                   (setq highest (1- (string-to-number (car uidnext)))))
883                 (cond
884                  ((null highest)
885                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
886                  ((zerop exists)
887                   ;; Empty group.
888                   (insert (format "%S %d %d y\n"
889                                   (utf7-decode group t) highest (1+ highest))))
890                  (t
891                   ;; Return the widest possible range.
892                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
893                                   (or highest exists)))))))))
894         t))))
895
896 (deffoo nnimap-retrieve-group-data-early (server infos)
897   (when (nnimap-possibly-change-group nil server)
898     (with-current-buffer (nnimap-buffer)
899       ;; QRESYNC handling isn't implemented.
900       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
901             marks groups sequences)
902         ;; Go through the infos and gather the data needed to know
903         ;; what and how to request the data.
904         (dolist (info infos)
905           (setq marks (gnus-info-marks info))
906           (push (list (gnus-group-real-name (gnus-info-group info))
907                       (cdr (assq 'active marks))
908                       (cdr (assq 'uid marks)))
909                 groups))
910         ;; Then request the data.
911         (erase-buffer)
912         (setf (nnimap-group nnimap-object) nil)
913         (dolist (elem groups)
914           (if (and qresyncp
915                    (nth 2 elem))
916               (push
917                (list 'qresync
918                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
919                                           (car elem)
920                                           (car (nth 2 elem))
921                                           (cdr (nth 2 elem)))
922                      nil
923                      (car elem))
924                sequences)
925             (let ((start
926                    (if (nth 1 elem)
927                        ;; Fetch the last 100 flags.
928                        (max 1 (- (cdr (nth 1 elem)) 100))
929                      1)))
930               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
931                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
932                           start
933                           (car elem))
934                     sequences)))
935           ;; Some servers apparently can't have many outstanding
936           ;; commands, so throttle them.
937           (when (and (not nnimap-streaming)
938                      (car sequences))
939             (nnimap-wait-for-response (caar sequences))))
940         sequences))))
941
942 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
943   (when (and sequences
944              (nnimap-possibly-change-group nil server))
945     (with-current-buffer (nnimap-buffer)
946       ;; Wait for the final data to trickle in.
947       (when (nnimap-wait-for-response (cadar sequences))
948         ;; Now we should have all the data we need, no matter whether
949         ;; we're QRESYNCING, fetching all the flags from scratch, or
950         ;; just fetching the last 100 flags per group.
951         (nnimap-update-infos (nnimap-flags-to-marks
952                               (nnimap-parse-flags
953                                (nreverse sequences)))
954                              infos)
955         ;; Finally, just return something resembling an active file in
956         ;; the nntp buffer, so that the agent can save the info, too.
957         (with-current-buffer nntp-server-buffer
958           (erase-buffer)
959           (dolist (info infos)
960             (let* ((group (gnus-info-group info))
961                    (active (gnus-active group)))
962               (when active
963                 (insert (format "%S %d %d y\n"
964                                 (gnus-group-real-name group)
965                                 (cdr active)
966                                 (car active)))))))))))
967
968 (defun nnimap-update-infos (flags infos)
969   (dolist (info infos)
970     (let ((group (gnus-group-real-name (gnus-info-group info))))
971       (nnimap-update-info info (cdr (assoc group flags))))))
972
973 (defun nnimap-update-info (info marks)
974   (when marks
975     (destructuring-bind (existing flags high low uidnext start-article
976                                   permanent-flags) marks
977       (let ((group (gnus-info-group info))
978             (completep (and start-article
979                             (= start-article 1))))
980         (when uidnext
981           (setq high (1- uidnext)))
982         ;; First set the active ranges based on high/low.
983         (if (or completep
984                 (not (gnus-active group)))
985             (gnus-set-active group
986                              (cond
987                               ((and low high)
988                                (cons low high))
989                               (uidnext
990                                ;; No articles in this group.
991                                (cons uidnext (1- uidnext)))
992                               (start-article
993                                (cons start-article (1- start-article)))
994                               (t
995                                ;; No articles and no uidnext.
996                                nil)))
997           (gnus-set-active
998            group
999            (cons (car (gnus-active group))
1000                  (or high (1- uidnext)))))
1001         (when (and (not high)
1002                    uidnext)
1003           (setq high (1- uidnext)))
1004         ;; Then update the list of read articles.
1005         (let* ((unread
1006                 (gnus-compress-sequence
1007                  (gnus-set-difference
1008                   (gnus-set-difference
1009                    existing
1010                    (cdr (assoc '%Seen flags)))
1011                   (cdr (assoc '%Flagged flags)))))
1012                (read (gnus-range-difference
1013                       (cons start-article high) unread)))
1014           (when (> start-article 1)
1015             (setq read
1016                   (gnus-range-nconcat
1017                    (if (> start-article 1)
1018                        (gnus-sorted-range-intersection
1019                         (cons 1 (1- start-article))
1020                         (gnus-info-read info))
1021                      (gnus-info-read info))
1022                    read)))
1023           (gnus-info-set-read info read)
1024           ;; Update the marks.
1025           (setq marks (gnus-info-marks info))
1026           ;; Note the active level for the next run-through.
1027           (let ((active (assq 'active marks)))
1028             (if active
1029                 (setcdr active (gnus-active group))
1030               (push (cons 'active (gnus-active group)) marks)))
1031           (dolist (type (cdr nnimap-mark-alist))
1032             (let ((old-marks (assoc (car type) marks))
1033                   (new-marks
1034                    (gnus-compress-sequence
1035                     (cdr (or (assoc (caddr type) flags)     ; %Flagged
1036                              (assoc (intern (cadr type) obarray) flags)
1037                              (assoc (cadr type) flags)))))) ; "\Flagged"
1038               (setq marks (delq old-marks marks))
1039               (pop old-marks)
1040               (when (and old-marks
1041                          (> start-article 1))
1042                 (setq old-marks (gnus-range-difference
1043                                  old-marks
1044                                  (cons start-article high)))
1045                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1046               (when new-marks
1047                 (push (cons (car type) new-marks) marks)))
1048             (gnus-info-set-marks info marks t)
1049             (nnimap-store-info info (gnus-active group))))))))
1050
1051 (defun nnimap-store-info (info active)
1052   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1053          (entry (assoc group nnimap-current-infos)))
1054     (if entry
1055         (setcdr entry (list info active))
1056       (push (list group info active) nnimap-current-infos))))
1057
1058 (defun nnimap-flags-to-marks (groups)
1059   (let (data group totalp uidnext articles start-article mark permanent-flags)
1060     (dolist (elem groups)
1061       (setq group (car elem)
1062             uidnext (nth 1 elem)
1063             start-article (nth 2 elem)
1064             permanent-flags (nth 3 elem)
1065             articles (nthcdr 4 elem))
1066       (let ((high (caar articles))
1067             marks low existing)
1068         (dolist (article articles)
1069           (setq low (car article))
1070           (push (car article) existing)
1071           (dolist (flag (cdr article))
1072             (setq mark (assoc flag marks))
1073             (if (not mark)
1074                 (push (list flag (car article)) marks)
1075               (setcdr mark (cons (car article) (cdr mark))))))
1076         (push (list group existing marks high low uidnext start-article
1077                     permanent-flags)
1078               data)))
1079     data))
1080
1081 (defun nnimap-parse-flags (sequences)
1082   (goto-char (point-min))
1083   ;; Change \Delete etc to %Delete, so that the reader can read it.
1084   (subst-char-in-region (point-min) (point-max)
1085                         ?\\ ?% t)
1086   (let (start end articles groups uidnext elems permanent-flags)
1087     (dolist (elem sequences)
1088       (destructuring-bind (group-sequence flag-sequence totalp group) elem
1089         (setq start (point))
1090         ;; The EXAMINE was successful.
1091         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1092                    (progn
1093                      (forward-line 1)
1094                      (setq end (point))
1095                      (goto-char start)
1096                      (setq permanent-flags
1097                            (and (search-forward "PERMANENTFLAGS "
1098                                                  (or end (point-min)) t)
1099                                 (read (current-buffer))))
1100                      (goto-char start)
1101                      (setq uidnext
1102                            (and (search-forward "UIDNEXT "
1103                                                  (or end (point-min)) t)
1104                                 (read (current-buffer))))
1105                      (goto-char end)
1106                      (forward-line -1))
1107                    ;; The UID FETCH FLAGS was successful.
1108                    (search-forward (format "\n%d OK " flag-sequence) nil t))
1109           (setq start (point))
1110           (goto-char end)
1111           (while (search-forward " FETCH " start t)
1112             (setq elems (read (current-buffer)))
1113             (push (cons (cadr (memq 'UID elems))
1114                         (cadr (memq 'FLAGS elems)))
1115                   articles))
1116           (push (nconc (list group uidnext totalp permanent-flags) articles)
1117                 groups)
1118           (setq articles nil))))
1119     groups))
1120
1121 (defun nnimap-find-process-buffer (buffer)
1122   (cadr (assoc buffer nnimap-connection-alist)))
1123
1124 (deffoo nnimap-request-post (&optional server)
1125   (setq nnimap-status-string "Read-only server")
1126   nil)
1127
1128 (defun nnimap-possibly-change-group (group server)
1129   (let ((open-result t))
1130     (when (and server
1131                (not (nnimap-server-opened server)))
1132       (setq open-result (nnimap-open-server server)))
1133     (cond
1134      ((not open-result)
1135       nil)
1136      ((not group)
1137       t)
1138      (t
1139       (with-current-buffer (nnimap-buffer)
1140         (if (equal group (nnimap-group nnimap-object))
1141             t
1142           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1143             (when (car result)
1144               (setf (nnimap-group nnimap-object) group
1145                     (nnimap-select-result nnimap-object) result)
1146               result))))))))
1147
1148 (defun nnimap-find-connection (buffer)
1149   "Find the connection delivering to BUFFER."
1150   (let ((entry (assoc buffer nnimap-connection-alist)))
1151     (when entry
1152       (if (and (buffer-name (cadr entry))
1153                (get-buffer-process (cadr entry))
1154                (memq (process-status (get-buffer-process (cadr entry)))
1155                      '(open run)))
1156           (get-buffer-process (cadr entry))
1157         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1158         nil))))
1159
1160 (defvar nnimap-sequence 0)
1161
1162 (defun nnimap-send-command (&rest args)
1163   (process-send-string
1164    (get-buffer-process (current-buffer))
1165    (nnimap-log-command
1166     (format "%d %s%s\n"
1167             (incf nnimap-sequence)
1168             (apply #'format args)
1169             (if (nnimap-newlinep nnimap-object)
1170                 ""
1171               "\r"))))
1172   nnimap-sequence)
1173
1174 (defun nnimap-log-command (command)
1175   (with-current-buffer (get-buffer-create "*imap log*")
1176     (goto-char (point-max))
1177     (insert (format-time-string "%H:%M:%S") " " command))
1178   command)
1179
1180 (defun nnimap-command (&rest args)
1181   (erase-buffer)
1182   (setf (nnimap-last-command-time nnimap-object) (current-time))
1183   (let* ((sequence (apply #'nnimap-send-command args))
1184          (response (nnimap-get-response sequence)))
1185     (if (equal (caar response) "OK")
1186         (cons t response)
1187       (nnheader-report 'nnimap "%s"
1188                        (mapconcat (lambda (a)
1189                                     (format "%s" a))
1190                                   (car response) " "))
1191       nil)))
1192
1193 (defun nnimap-get-response (sequence)
1194   (nnimap-wait-for-response sequence)
1195   (nnimap-parse-response))
1196
1197 (defun nnimap-wait-for-connection ()
1198   (let ((process (get-buffer-process (current-buffer))))
1199     (goto-char (point-min))
1200     (while (and (memq (process-status process)
1201                       '(open run))
1202                 (not (re-search-forward "^[*.] .*\n" nil t)))
1203       (nnheader-accept-process-output process)
1204       (goto-char (point-min)))
1205     (forward-line -1)
1206     (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1207          (match-string 1))))
1208
1209 (defun nnimap-wait-for-response (sequence &optional messagep)
1210   (let ((process (get-buffer-process (current-buffer)))
1211         openp)
1212     (goto-char (point-max))
1213     (while (and (setq openp (memq (process-status process)
1214                                   '(open run)))
1215                 (not (re-search-backward
1216                       (format "^%d .*\n" sequence)
1217                       (if nnimap-streaming
1218                           (max (point-min) (- (point) 500))
1219                         (point-min))
1220                       t)))
1221       (when messagep
1222         (message "Read %dKB" (/ (buffer-size) 1000)))
1223       (nnheader-accept-process-output process)
1224       (goto-char (point-max)))
1225     openp))
1226
1227 (defun nnimap-parse-response ()
1228   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1229         result)
1230     (dolist (line lines)
1231       (push (cdr (nnimap-parse-line line)) result))
1232     ;; Return the OK/error code first, and then all the "continuation
1233     ;; lines" afterwards.
1234     (cons (pop result)
1235           (nreverse result))))
1236
1237 ;; Parse an IMAP response line lightly.  They look like
1238 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1239 ;; the lines into a list of strings and lists of string.
1240 (defun nnimap-parse-line (line)
1241   (let (char result)
1242     (with-temp-buffer
1243       (insert line)
1244       (goto-char (point-min))
1245       (while (not (eobp))
1246         (if (eql (setq char (following-char)) ? )
1247             (forward-char 1)
1248           (push
1249            (cond
1250             ((eql char ?\[)
1251              (split-string (buffer-substring
1252                             (1+ (point))
1253                             (1- (search-forward "]" (line-end-position) 'move)))))
1254             ((eql char ?\()
1255              (split-string (buffer-substring
1256                             (1+ (point))
1257                             (1- (search-forward ")" (line-end-position) 'move)))))
1258             ((eql char ?\")
1259              (forward-char 1)
1260              (buffer-substring
1261               (point)
1262               (1- (or (search-forward "\"" (line-end-position) 'move)
1263                       (point)))))
1264             (t
1265              (buffer-substring (point) (if (search-forward " " nil t)
1266                                            (1- (point))
1267                                          (goto-char (point-max))))))
1268            result)))
1269       (nreverse result))))
1270
1271 (defun nnimap-last-response-string ()
1272   (save-excursion
1273     (forward-line 1)
1274     (let ((end (point)))
1275       (forward-line -1)
1276       (when (not (bobp))
1277         (forward-line -1)
1278         (while (and (not (bobp))
1279                     (eql (following-char) ?*))
1280           (forward-line -1))
1281         (unless (eql (following-char) ?*)
1282           (forward-line 1)))
1283       (buffer-substring (point) end))))
1284
1285 (defun nnimap-get-responses (sequences)
1286   (let (responses)
1287     (dolist (sequence sequences)
1288       (goto-char (point-min))
1289       (when (re-search-forward (format "^%d " sequence) nil t)
1290         (push (list sequence (nnimap-parse-response))
1291               responses)))
1292     responses))
1293
1294 (defvar nnimap-incoming-split-list nil)
1295
1296 (defun nnimap-fetch-inbox (articles)
1297   (erase-buffer)
1298   (nnimap-wait-for-response
1299    (nnimap-send-command
1300     "UID FETCH %s %s"
1301     (nnimap-article-ranges articles)
1302     (format "(UID %s%s)"
1303             (format
1304              (if (nnimap-ver4-p)
1305                  "BODY.PEEK[HEADER] BODY.PEEK"
1306                "RFC822.PEEK"))
1307             (if nnimap-split-download-body-default
1308                 "[]"
1309               "[1]")))
1310    t))
1311
1312 (defun nnimap-split-incoming-mail ()
1313   (with-current-buffer (nnimap-buffer)
1314     (let ((nnimap-incoming-split-list nil)
1315           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1316                                     nnmail-split-methods
1317                                   nnimap-split-methods))
1318           (nnmail-split-fancy (or nnimap-split-fancy
1319                                   nnmail-split-fancy))
1320           (nnmail-inhibit-default-split-group t)
1321           (groups (nnimap-get-groups))
1322           new-articles)
1323       (erase-buffer)
1324       (nnimap-command "SELECT %S" nnimap-inbox)
1325       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1326       (when new-articles
1327         (nnimap-fetch-inbox new-articles)
1328         (nnimap-transform-split-mail)
1329         (nnheader-ms-strip-cr)
1330         (nnmail-cache-open)
1331         (nnmail-split-incoming (current-buffer)
1332                                #'nnimap-save-mail-spec
1333                                nil nil
1334                                #'nnimap-dummy-active-number
1335                                #'nnimap-save-mail-spec)
1336         (when nnimap-incoming-split-list
1337           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1338                 sequences junk-articles)
1339             ;; Create any groups that doesn't already exist on the
1340             ;; server first.
1341             (dolist (spec specs)
1342               (when (and (not (member (car spec) groups))
1343                          (not (eq (car spec) 'junk)))
1344                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1345             ;; Then copy over all the messages.
1346             (erase-buffer)
1347             (dolist (spec specs)
1348               (let ((group (car spec))
1349                     (ranges (cdr spec)))
1350                 (if (eq group 'junk)
1351                     (setq junk-articles ranges)
1352                   (push (list (nnimap-send-command
1353                                "UID COPY %s %S"
1354                                (nnimap-article-ranges ranges)
1355                                (utf7-encode group t))
1356                               ranges)
1357                         sequences))))
1358             ;; Wait for the last COPY response...
1359             (when sequences
1360               (nnimap-wait-for-response (caar sequences))
1361               ;; And then mark the successful copy actions as deleted,
1362               ;; and possibly expunge them.
1363               (nnimap-mark-and-expunge-incoming
1364                (nnimap-parse-copied-articles sequences)))
1365             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1366
1367 (defun nnimap-mark-and-expunge-incoming (range)
1368   (when range
1369     (setq range (nnimap-article-ranges range))
1370     (erase-buffer)
1371     (let ((sequence
1372            (nnimap-send-command
1373             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1374       (cond
1375        ;; If the server supports it, we now delete the message we have
1376        ;; just copied over.
1377        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1378         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1379        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1380        ;; user has configured it.
1381        (nnimap-expunge
1382         (setq sequence (nnimap-send-command "EXPUNGE"))))
1383       (nnimap-wait-for-response sequence))))
1384
1385 (defun nnimap-parse-copied-articles (sequences)
1386   (let (sequence copied range)
1387     (goto-char (point-min))
1388     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1389       (setq sequence (string-to-number (match-string 1)))
1390       (when (setq range (cadr (assq sequence sequences)))
1391         (push (gnus-uncompress-range range) copied)))
1392     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1393
1394 (defun nnimap-new-articles (flags)
1395   (let (new)
1396     (dolist (elem flags)
1397       (when (or (null (cdr elem))
1398                 (and (not (memq '%Deleted (cdr elem)))
1399                      (not (memq '%Seen (cdr elem)))))
1400         (push (car elem) new)))
1401     (gnus-compress-sequence (nreverse new))))
1402
1403 (defun nnimap-make-split-specs (list)
1404   (let ((specs nil)
1405         entry)
1406     (dolist (elem list)
1407       (destructuring-bind (article spec) elem
1408         (dolist (group (delete nil (mapcar #'car spec)))
1409           (unless (setq entry (assoc group specs))
1410             (push (setq entry (list group)) specs))
1411           (setcdr entry (cons article (cdr entry))))))
1412     (dolist (entry specs)
1413       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1414     specs))
1415
1416 (defun nnimap-transform-split-mail ()
1417   (goto-char (point-min))
1418   (let (article bytes)
1419     (block nil
1420       (while (not (eobp))
1421         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1422           (delete-region (point) (progn (forward-line 1) (point)))
1423           (when (eobp)
1424             (return)))
1425         (setq article (match-string 1)
1426               bytes (nnimap-get-length))
1427         (delete-region (line-beginning-position) (line-end-position))
1428         ;; Insert MMDF separator, and a way to remember what this
1429         ;; article UID is.
1430         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1431         (forward-char (1+ bytes))
1432         (setq bytes (nnimap-get-length))
1433         (delete-region (line-beginning-position) (line-end-position))
1434         (forward-char (1+ bytes))
1435         (delete-region (line-beginning-position) (line-end-position))))))
1436
1437 (defun nnimap-dummy-active-number (group &optional server)
1438   1)
1439
1440 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1441   (let (article)
1442     (goto-char (point-min))
1443     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1444         (error "Invalid nnimap mail")
1445       (setq article (string-to-number (match-string 1))))
1446     (push (list article
1447                 (if (eq group-art 'junk)
1448                     (list (cons 'junk 1))
1449                   group-art))
1450           nnimap-incoming-split-list)))
1451
1452 (provide 'nnimap)
1453
1454 ;;; nnimap.el ends here