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