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