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