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