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