(nnimap-request-group): Don't SELECT the group twice on `M-g'.
[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 (point))
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       (when (and (stringp (car bstruc))
569                  (string= (downcase (car bstruc)) "boundary"))
570         (setq boundary (cadr bstruc))))
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     (when (nnimap-request-article article group server (current-buffer))
718       ;; If the move is internal (on the same server), just do it the easy
719       ;; way.
720       (let ((message-id (message-field-value "message-id")))
721         (if internal-move-group
722             (let ((result
723                    (with-current-buffer (nnimap-buffer)
724                      (nnimap-command "UID COPY %d %S"
725                                      article
726                                      (utf7-encode internal-move-group t)))))
727               (when (car result)
728                 (nnimap-delete-article article)
729                 (cons internal-move-group
730                       (nnimap-find-article-by-message-id
731                        internal-move-group message-id))))
732           ;; Move the article to a different method.
733           (let ((result (eval accept-form)))
734             (when result
735               (nnimap-delete-article article)
736               result)))))))
737
738 (deffoo nnimap-request-expire-articles (articles group &optional server force)
739   (cond
740    ((null articles)
741     nil)
742    ((not (nnimap-possibly-change-group group server))
743     articles)
744    ((and force
745          (eq nnmail-expiry-target 'delete))
746     (unless (nnimap-delete-article (gnus-compress-sequence articles))
747       (nnheader-message 7 "Article marked for deletion, but not expunged."))
748     nil)
749    (t
750     (let ((deletable-articles
751            (if (or force
752                    (eq nnmail-expiry-wait 'immediate))
753                articles
754              (gnus-sorted-intersection
755               articles
756               (nnimap-find-expired-articles group)))))
757       (if (null deletable-articles)
758           articles
759         (if (eq nnmail-expiry-target 'delete)
760             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
761           (setq deletable-articles
762                 (nnimap-process-expiry-targets
763                  deletable-articles group server)))
764         ;; Return the articles we didn't delete.
765         (gnus-sorted-complement articles deletable-articles))))))
766
767 (defun nnimap-process-expiry-targets (articles group server)
768   (let ((deleted-articles nil))
769     (dolist (article articles)
770       (let ((target nnmail-expiry-target))
771         (with-temp-buffer
772           (when (nnimap-request-article article group server (current-buffer))
773             (nnheader-message 7 "Expiring article %s:%d" group article)
774             (when (functionp target)
775               (setq target (funcall target group)))
776             (when (and target
777                        (not (eq target 'delete)))
778               (if (or (gnus-request-group target t)
779                       (gnus-request-create-group target))
780                   (nnmail-expiry-target-group target group)
781                 (setq target nil)))
782             (when target
783               (push article deleted-articles))))))
784     ;; Change back to the current group again.
785     (nnimap-possibly-change-group group server)
786     (setq deleted-articles (nreverse deleted-articles))
787     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
788     deleted-articles))
789
790 (defun nnimap-find-expired-articles (group)
791   (let ((cutoff (nnmail-expired-article-p group nil nil)))
792     (with-current-buffer (nnimap-buffer)
793       (let ((result
794              (nnimap-command
795               "UID SEARCH SENTBEFORE %s"
796               (format-time-string
797                (format "%%d-%s-%%Y"
798                        (upcase
799                         (car (rassoc (nth 4 (decode-time cutoff))
800                                      parse-time-months))))
801                cutoff))))
802         (and (car result)
803              (delete 0 (mapcar #'string-to-number
804                                (cdr (assoc "SEARCH" (cdr result))))))))))
805
806
807 (defun nnimap-find-article-by-message-id (group message-id)
808   (with-current-buffer (nnimap-buffer)
809     (erase-buffer)
810     (setf (nnimap-group nnimap-object) nil)
811     (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
812     (let ((sequence
813            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
814           article result)
815       (setq result (nnimap-wait-for-response sequence))
816       (when (and result
817                  (car (setq result (nnimap-parse-response))))
818         ;; Select the last instance of the message in the group.
819         (and (setq article
820                    (car (last (assoc "SEARCH" (cdr result)))))
821              (string-to-number article))))))
822
823 (defun nnimap-delete-article (articles)
824   (with-current-buffer (nnimap-buffer)
825     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
826                     (nnimap-article-ranges articles))
827     (cond
828      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
829       (nnimap-command "UID EXPUNGE %s"
830                       (nnimap-article-ranges articles))
831       t)
832      (nnimap-expunge
833       (nnimap-command "EXPUNGE")
834       t)
835      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
836                                 "server doesn't support UIDPLUS, so we won't "
837                                 "delete this article now"))))))
838
839 (deffoo nnimap-request-scan (&optional group server)
840   (when (and (nnimap-possibly-change-group nil server)
841              nnimap-inbox
842              nnimap-split-methods)
843     (nnheader-message 7 "nnimap %s splitting mail..." server)
844     (nnimap-split-incoming-mail)))
845
846 (defun nnimap-marks-to-flags (marks)
847   (let (flags flag)
848     (dolist (mark marks)
849       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
850         (push flag flags)))
851     flags))
852
853 (deffoo nnimap-request-set-mark (group actions &optional server)
854   (when (nnimap-possibly-change-group group server)
855     (let (sequence)
856       (with-current-buffer (nnimap-buffer)
857         (erase-buffer)
858         ;; Just send all the STORE commands without waiting for
859         ;; response.  If they're successful, they're successful.
860         (dolist (action actions)
861           (destructuring-bind (range action marks) action
862             (let ((flags (nnimap-marks-to-flags marks)))
863               (when flags
864                 (setq sequence (nnimap-send-command
865                                 "UID STORE %s %sFLAGS.SILENT (%s)"
866                                 (nnimap-article-ranges range)
867                                 (if (eq action 'del)
868                                     "-"
869                                   "+")
870                                 (mapconcat #'identity flags " ")))))))
871         ;; Wait for the last command to complete to avoid later
872         ;; syncronisation problems with the stream.
873         (when sequence
874           (nnimap-wait-for-response sequence))))))
875
876 (deffoo nnimap-request-accept-article (group &optional server last)
877   (when (nnimap-possibly-change-group nil server)
878     (nnmail-check-syntax)
879     (let ((message-id (message-field-value "message-id"))
880           sequence message)
881       (nnimap-add-cr)
882       (setq message (buffer-string))
883       (with-current-buffer (nnimap-buffer)
884         (setq sequence (nnimap-send-command
885                         "APPEND %S {%d}" (utf7-encode group t)
886                         (length message)))
887         (process-send-string (get-buffer-process (current-buffer)) message)
888         (process-send-string (get-buffer-process (current-buffer))
889                              (if (nnimap-newlinep nnimap-object)
890                                  "\n"
891                                "\r\n"))
892         (let ((result (nnimap-get-response sequence)))
893           (if (not (car result))
894               (progn
895                 (nnheader-message 7 "%s" (nnheader-get-report-string 'nnimap))
896                 nil)
897             (cons group
898                   (nnimap-find-article-by-message-id group message-id))))))))
899
900 (defun nnimap-add-cr ()
901   (goto-char (point-min))
902   (while (re-search-forward "\r?\n" nil t)
903     (replace-match "\r\n" t t)))
904
905 (defun nnimap-get-groups ()
906   (let ((result (nnimap-command "LIST \"\" \"*\""))
907         groups)
908     (when (car result)
909       (dolist (line (cdr result))
910         (when (and (equal (car line) "LIST")
911                    (not (and (caadr line)
912                              (string-match "noselect" (caadr line)))))
913           (push (car (last line)) groups)))
914       (nreverse groups))))
915
916 (deffoo nnimap-request-list (&optional server)
917   (nnimap-possibly-change-group nil server)
918   (with-current-buffer nntp-server-buffer
919     (erase-buffer)
920     (let ((groups
921            (with-current-buffer (nnimap-buffer)
922              (nnimap-get-groups)))
923           sequences responses)
924       (when groups
925         (with-current-buffer (nnimap-buffer)
926           (setf (nnimap-group nnimap-object) nil)
927           (dolist (group groups)
928             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
929                         group)
930                   sequences))
931           (nnimap-wait-for-response (caar sequences))
932           (setq responses
933                 (nnimap-get-responses (mapcar #'car sequences))))
934         (dolist (response responses)
935           (let* ((sequence (car response))
936                  (response (cadr response))
937                  (group (cadr (assoc sequence sequences))))
938             (when (and group
939                        (equal (caar response) "OK"))
940               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
941                     highest exists)
942                 (dolist (elem response)
943                   (when (equal (cadr elem) "EXISTS")
944                     (setq exists (string-to-number (car elem)))))
945                 (when uidnext
946                   (setq highest (1- (string-to-number (car uidnext)))))
947                 (cond
948                  ((null highest)
949                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
950                  ((zerop exists)
951                   ;; Empty group.
952                   (insert (format "%S %d %d y\n"
953                                   (utf7-decode group t) highest (1+ highest))))
954                  (t
955                   ;; Return the widest possible range.
956                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
957                                   (or highest exists)))))))))
958         t))))
959
960 (deffoo nnimap-request-newgroups (date &optional server)
961   (nnimap-possibly-change-group nil server)
962   (with-current-buffer nntp-server-buffer
963     (erase-buffer)
964     (dolist (group (with-current-buffer (nnimap-buffer)
965                      (nnimap-get-groups)))
966       (unless (assoc group nnimap-current-infos)
967         ;; Insert dummy numbers here -- they don't matter.
968         (insert (format "%S 0 1 y\n" group))))
969     t))
970
971 (deffoo nnimap-retrieve-group-data-early (server infos)
972   (when (nnimap-possibly-change-group nil server)
973     (with-current-buffer (nnimap-buffer)
974       (erase-buffer)
975       (setf (nnimap-group nnimap-object) nil)
976       ;; QRESYNC handling isn't implemented.
977       (let ((qresyncp (member "QRESYNC" (nnimap-capabilities nnimap-object)))
978             params groups sequences active uidvalidity modseq group)
979         ;; Go through the infos and gather the data needed to know
980         ;; what and how to request the data.
981         (dolist (info infos)
982           (setq params (gnus-info-params info)
983                 group (gnus-group-real-name (gnus-info-group info))
984                 active (cdr (assq 'active params))
985                 uidvalidity (cdr (assq 'uidvalidity params))
986                 modseq (cdr (assq 'modseq params)))
987           (if (and qresyncp
988                    uidvalidity
989                    modseq)
990               (push
991                (list (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
992                                           (utf7-encode group t)
993                                           uidvalidity modseq)
994                      'qresync
995                      nil group 'qresync)
996                sequences)
997             (let ((start
998                    (if (and active uidvalidity)
999                        ;; Fetch the last 100 flags.
1000                        (max 1 (- (cdr active) 100))
1001                      1))
1002                   (command
1003                    (if uidvalidity
1004                        "EXAMINE"
1005                      ;; If we don't have a UIDVALIDITY, then this is
1006                      ;; the first time we've seen the group, so we
1007                      ;; have to do a SELECT (which is slower than an
1008                      ;; examine), but will tell us whether the group
1009                      ;; is read-only or not.
1010                      "SELECT")))
1011               (push (list (nnimap-send-command "%s %S" command
1012                                                (utf7-encode group t))
1013                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1014                           start group command)
1015                     sequences)))
1016           ;; Some servers apparently can't have many outstanding
1017           ;; commands, so throttle them.
1018           (when (and (not nnimap-streaming)
1019                      (car sequences))
1020             (nnimap-wait-for-response (caar sequences))))
1021         sequences))))
1022
1023 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1024   (when (and sequences
1025              (nnimap-possibly-change-group nil server))
1026     (with-current-buffer (nnimap-buffer)
1027       ;; Wait for the final data to trickle in.
1028       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1029                                           (caar sequences)
1030                                         (cadar sequences))
1031                                       t)
1032         ;; Now we should have most of the data we need, no matter
1033         ;; whether we're QRESYNCING, fetching all the flags from
1034         ;; scratch, or just fetching the last 100 flags per group.
1035         (nnimap-update-infos (nnimap-flags-to-marks
1036                               (nnimap-parse-flags
1037                                (nreverse sequences)))
1038                              infos)
1039         ;; Finally, just return something resembling an active file in
1040         ;; the nntp buffer, so that the agent can save the info, too.
1041         (with-current-buffer nntp-server-buffer
1042           (erase-buffer)
1043           (dolist (info infos)
1044             (let* ((group (gnus-info-group info))
1045                    (active (gnus-active group)))
1046               (when active
1047                 (insert (format "%S %d %d y\n"
1048                                 (gnus-group-real-name group)
1049                                 (cdr active)
1050                                 (car active)))))))))))
1051
1052 (defun nnimap-update-infos (flags infos)
1053   (dolist (info infos)
1054     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1055            (marks (cdr (assoc group flags))))
1056       (when marks
1057         (nnimap-update-info info marks)))))
1058
1059 (defun nnimap-update-info (info marks)
1060   (destructuring-bind (existing flags high low uidnext start-article
1061                                 permanent-flags uidvalidity
1062                                 vanished highestmodseq) marks
1063     (cond
1064      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1065      ;; completely empty groups.
1066      ((and (not existing)
1067            (not uidnext))
1068       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1069         (when active
1070           (gnus-set-active (gnus-info-group info) active))))
1071      ;; We have a mismatch between the old and new UIDVALIDITY
1072      ;; identifiers, so we have to re-request the group info (the next
1073      ;; time).  This virtually never happens.
1074      ((let ((old-uidvalidity
1075              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1076         (and old-uidvalidity
1077              (not (equal old-uidvalidity uidvalidity))
1078              (> start-article 1)))
1079       (gnus-group-remove-parameter info 'uidvalidity)
1080       (gnus-group-remove-parameter info 'modseq))
1081      ;; We have the data needed to update.
1082      (t
1083       (let* ((group (gnus-info-group info))
1084              (completep (and start-article
1085                              (= start-article 1)))
1086              (active (or (gnus-active group)
1087                          (cdr (assq 'active (gnus-info-params info))))))
1088         (when uidnext
1089           (setq high (1- uidnext)))
1090         ;; First set the active ranges based on high/low.
1091         (if (or completep
1092                 (not (gnus-active group)))
1093             (gnus-set-active group
1094                              (cond
1095                               ((and low high)
1096                                (cons low high))
1097                               (uidnext
1098                                ;; No articles in this group.
1099                                (cons uidnext (1- uidnext)))
1100                               (active
1101                                active)
1102                               (start-article
1103                                (cons start-article (1- start-article)))
1104                               (t
1105                                ;; No articles and no uidnext.
1106                                nil)))
1107           (gnus-set-active
1108            group
1109            (cons (car active)
1110                  (or high (1- uidnext)))))
1111         ;; See whether this is a read-only group.
1112         (unless (eq permanent-flags 'not-scanned)
1113           (gnus-group-set-parameter
1114            info 'permanent-flags
1115            (if (memq '%* permanent-flags)
1116                t
1117              nil)))
1118         ;; Update marks and read articles if this isn't a
1119         ;; read-only IMAP group.
1120         (when (cdr (assq 'permanent-flags (gnus-info-params info)))
1121           (if (and highestmodseq
1122                    (not start-article))
1123               ;; We've gotten the data by QRESYNCing.
1124               (nnimap-update-qresync-info
1125                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1126             ;; Do normal non-QRESYNC flag updates.
1127             ;; Update the list of read articles.
1128             (let* ((unread
1129                     (gnus-compress-sequence
1130                      (gnus-set-difference
1131                       (gnus-set-difference
1132                        existing
1133                        (cdr (assoc '%Seen flags)))
1134                       (cdr (assoc '%Flagged flags)))))
1135                    (read (gnus-range-difference
1136                           (cons start-article high) unread)))
1137               (when (> start-article 1)
1138                 (setq read
1139                       (gnus-range-nconcat
1140                        (if (> start-article 1)
1141                            (gnus-sorted-range-intersection
1142                             (cons 1 (1- start-article))
1143                             (gnus-info-read info))
1144                          (gnus-info-read info))
1145                        read)))
1146               (gnus-info-set-read info read)
1147               ;; Update the marks.
1148               (setq marks (gnus-info-marks info))
1149               (dolist (type (cdr nnimap-mark-alist))
1150                 (let ((old-marks (assoc (car type) marks))
1151                       (new-marks
1152                        (gnus-compress-sequence
1153                         (cdr (or (assoc (caddr type) flags) ; %Flagged
1154                                  (assoc (intern (cadr type) obarray) flags)
1155                                  (assoc (cadr type) flags)))))) ; "\Flagged"
1156                   (setq marks (delq old-marks marks))
1157                   (pop old-marks)
1158                   (when (and old-marks
1159                              (> start-article 1))
1160                     (setq old-marks (gnus-range-difference
1161                                      old-marks
1162                                      (cons start-article high)))
1163                     (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1164                   (when new-marks
1165                     (push (cons (car type) new-marks) marks)))
1166                 (gnus-info-set-marks info marks t)))))
1167         ;; Note the active level for the next run-through.
1168         (gnus-group-set-parameter info 'active (gnus-active group))
1169         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1170         (gnus-group-set-parameter info 'modseq highestmodseq)
1171         (nnimap-store-info info (gnus-active group)))))))
1172
1173 (defun nnimap-update-qresync-info (info existing vanished flags)
1174   ;; Add all the vanished articles to the list of read articles.
1175   (gnus-info-set-read
1176    info
1177    (gnus-add-to-range
1178     (gnus-add-to-range
1179      (gnus-range-add (gnus-info-read info)
1180                      vanished)
1181      (cdr (assq '%Flagged flags)))
1182     (cdr (assq '%Seen flags))))
1183   (let ((marks (gnus-info-marks info)))
1184     (dolist (type (cdr nnimap-mark-alist))
1185       (let ((ticks (assoc (car type) marks))
1186             (new-marks
1187              (cdr (or (assoc (caddr type) flags) ; %Flagged
1188                       (assoc (intern (cadr type) obarray) flags)
1189                       (assoc (cadr type) flags))))) ; "\Flagged"
1190         (setq marks (delq ticks marks))
1191         (pop ticks)
1192         ;; Add the new marks we got.
1193         (setq ticks (gnus-add-to-range ticks new-marks))
1194         ;; Remove the marks from messages that don't have them.
1195         (setq ticks (gnus-remove-from-range
1196                      ticks
1197                      (gnus-compress-sequence
1198                       (gnus-sorted-complement existing new-marks))))
1199         (when ticks
1200           (push (cons (car type) ticks) marks)))
1201       (gnus-info-set-marks info marks t))))
1202
1203 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1204   (if (zerop (length irange))
1205       nil
1206     (let ((result nil))
1207       (dolist (elem (split-string irange ","))
1208         (push
1209          (if (string-match ":" elem)
1210              (let ((numbers (split-string elem ":")))
1211                (cons (string-to-number (car numbers))
1212                      (string-to-number (cadr numbers))))
1213            (string-to-number elem))
1214          result))
1215       (nreverse result))))
1216
1217 (defun nnimap-store-info (info active)
1218   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1219          (entry (assoc group nnimap-current-infos)))
1220     (if entry
1221         (setcdr entry (list info active))
1222       (push (list group info active) nnimap-current-infos))))
1223
1224 (defun nnimap-flags-to-marks (groups)
1225   (let (data group totalp uidnext articles start-article mark permanent-flags
1226              uidvalidity vanished highestmodseq)
1227     (dolist (elem groups)
1228       (setq group (car elem)
1229             uidnext (nth 1 elem)
1230             start-article (nth 2 elem)
1231             permanent-flags (nth 3 elem)
1232             uidvalidity (nth 4 elem)
1233             vanished (nth 5 elem)
1234             highestmodseq (nth 6 elem)
1235             articles (nthcdr 7 elem))
1236       (let ((high (caar articles))
1237             marks low existing)
1238         (dolist (article articles)
1239           (setq low (car article))
1240           (push (car article) existing)
1241           (dolist (flag (cdr article))
1242             (setq mark (assoc flag marks))
1243             (if (not mark)
1244                 (push (list flag (car article)) marks)
1245               (setcdr mark (cons (car article) (cdr mark))))))
1246         (push (list group existing marks high low uidnext start-article
1247                     permanent-flags uidvalidity vanished highestmodseq)
1248               data)))
1249     data))
1250
1251 (defun nnimap-parse-flags (sequences)
1252   (goto-char (point-min))
1253   ;; Change \Delete etc to %Delete, so that the reader can read it.
1254   (subst-char-in-region (point-min) (point-max)
1255                         ?\\ ?% t)
1256   (let (start end articles groups uidnext elems permanent-flags
1257               uidvalidity vanished highestmodseq)
1258     (dolist (elem sequences)
1259       (destructuring-bind (group-sequence flag-sequence totalp group command)
1260           elem
1261         (setq start (point))
1262         (when (and
1263                ;; The EXAMINE was successful.
1264                (search-forward (format "\n%d OK " group-sequence) nil t)
1265                (progn
1266                  (forward-line 1)
1267                  (setq end (point))
1268                  (goto-char start)
1269                  (setq permanent-flags
1270                        (if (equal command "SELECT")
1271                            (and (search-forward "PERMANENTFLAGS "
1272                                                 (or end (point-min)) t)
1273                                 (read (current-buffer)))
1274                          'not-scanned))
1275                  (goto-char start)
1276                  (setq uidnext
1277                        (and (search-forward "UIDNEXT "
1278                                             (or end (point-min)) t)
1279                             (read (current-buffer))))
1280                  (goto-char start)
1281                  (setq uidvalidity
1282                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1283                                                (or end (point-min)) t)
1284                             ;; Store UIDVALIDITY as a string, as it's
1285                             ;; too big for 32-bit Emacsen, usually.
1286                             (match-string 1)))
1287                  (goto-char start)
1288                  (setq vanished
1289                        (and (eq flag-sequence 'qresync)
1290                             (re-search-forward "VANISHED.* \\([0-9:,]+\\)"
1291                                                (or end (point-min)) t)
1292                             (match-string 1)))
1293                  (goto-char start)
1294                  (setq highestmodseq
1295                        (and (search-forward "HIGHESTMODSEQ "
1296                                             (or end (point-min)) t)
1297                             (read (current-buffer))))
1298                  (goto-char end)
1299                  (forward-line -1))
1300                ;; The UID FETCH FLAGS was successful.
1301                (or (eq flag-sequence 'qresync)
1302                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1303           (if (eq flag-sequence 'qresync)
1304               (progn
1305                 (goto-char start)
1306                 (setq start end))
1307             (setq start (point))
1308             (goto-char end))
1309           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1310             (setq elems (read (current-buffer)))
1311             (push (cons (cadr (memq 'UID elems))
1312                         (cadr (memq 'FLAGS elems)))
1313                   articles))
1314           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1315                              vanished highestmodseq)
1316                        articles)
1317                 groups)
1318           (goto-char end)
1319           (setq articles nil))))
1320     groups))
1321
1322 (defun nnimap-find-process-buffer (buffer)
1323   (cadr (assoc buffer nnimap-connection-alist)))
1324
1325 (deffoo nnimap-request-post (&optional server)
1326   (setq nnimap-status-string "Read-only server")
1327   nil)
1328
1329 (deffoo nnimap-request-thread (id)
1330     (let* ((refs (split-string
1331                (or (mail-header-references (gnus-summary-article-header))
1332                    "")))
1333            (cmd (let ((value
1334                        (format
1335                         "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1336                         id id)))
1337                   (dolist (refid refs value)
1338                     (setq value (format
1339                                  "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1340                                  refid refid value)))))
1341            (result
1342             (with-current-buffer (nnimap-buffer)
1343               (nnimap-command  "UID SEARCH %s" cmd))))
1344       (gnus-fetch-headers (and (car result)
1345            (delete 0 (mapcar #'string-to-number
1346                              (cdr (assoc "SEARCH" (cdr result)))))))))
1347
1348 (defun nnimap-possibly-change-group (group server)
1349   (let ((open-result t))
1350     (when (and server
1351                (not (nnimap-server-opened server)))
1352       (setq open-result (nnimap-open-server server)))
1353     (cond
1354      ((not open-result)
1355       nil)
1356      ((not group)
1357       t)
1358      (t
1359       (with-current-buffer (nnimap-buffer)
1360         (if (equal group (nnimap-group nnimap-object))
1361             t
1362           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1363             (when (car result)
1364               (setf (nnimap-group nnimap-object) group
1365                     (nnimap-select-result nnimap-object) result)
1366               result))))))))
1367
1368 (defun nnimap-find-connection (buffer)
1369   "Find the connection delivering to BUFFER."
1370   (let ((entry (assoc buffer nnimap-connection-alist)))
1371     (when entry
1372       (if (and (buffer-name (cadr entry))
1373                (get-buffer-process (cadr entry))
1374                (memq (process-status (get-buffer-process (cadr entry)))
1375                      '(open run)))
1376           (get-buffer-process (cadr entry))
1377         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1378         nil))))
1379
1380 (defvar nnimap-sequence 0)
1381
1382 (defun nnimap-send-command (&rest args)
1383   (process-send-string
1384    (get-buffer-process (current-buffer))
1385    (nnimap-log-command
1386     (format "%d %s%s\n"
1387             (incf nnimap-sequence)
1388             (apply #'format args)
1389             (if (nnimap-newlinep nnimap-object)
1390                 ""
1391               "\r"))))
1392   nnimap-sequence)
1393
1394 (defun nnimap-log-command (command)
1395   (with-current-buffer (get-buffer-create "*imap log*")
1396     (goto-char (point-max))
1397     (insert (format-time-string "%H:%M:%S") " " command))
1398   command)
1399
1400 (defun nnimap-command (&rest args)
1401   (erase-buffer)
1402   (setf (nnimap-last-command-time nnimap-object) (current-time))
1403   (let* ((sequence (apply #'nnimap-send-command args))
1404          (response (nnimap-get-response sequence)))
1405     (if (equal (caar response) "OK")
1406         (cons t response)
1407       (nnheader-report 'nnimap "%s"
1408                        (mapconcat (lambda (a)
1409                                     (format "%s" a))
1410                                   (car response) " "))
1411       nil)))
1412
1413 (defun nnimap-get-response (sequence)
1414   (nnimap-wait-for-response sequence)
1415   (nnimap-parse-response))
1416
1417 (defun nnimap-wait-for-connection ()
1418   (let ((process (get-buffer-process (current-buffer))))
1419     (goto-char (point-min))
1420     (while (and (memq (process-status process)
1421                       '(open run))
1422                 (not (re-search-forward "^[*.] .*\n" nil t)))
1423       (nnheader-accept-process-output process)
1424       (goto-char (point-min)))
1425     (forward-line -1)
1426     (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1427          (match-string 1))))
1428
1429 (defun nnimap-wait-for-response (sequence &optional messagep)
1430   (let ((process (get-buffer-process (current-buffer)))
1431         openp)
1432     (condition-case nil
1433         (progn
1434           (goto-char (point-max))
1435           (while (and (setq openp (memq (process-status process)
1436                                         '(open run)))
1437                       (not (re-search-backward
1438                             (format "^%d .*\n" sequence)
1439                             (if nnimap-streaming
1440                                 (max (point-min) (- (point) 500))
1441                               (point-min))
1442                             t)))
1443             (when messagep
1444               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1445             (nnheader-accept-process-output process)
1446             (goto-char (point-max)))
1447           openp)
1448       (quit
1449        ;; The user hit C-g while we were waiting: kill the process, in case
1450        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1451        ;; NAT routers).
1452        (delete-process process)
1453        nil))))
1454
1455 (defun nnimap-parse-response ()
1456   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1457         result)
1458     (dolist (line lines)
1459       (push (cdr (nnimap-parse-line line)) result))
1460     ;; Return the OK/error code first, and then all the "continuation
1461     ;; lines" afterwards.
1462     (cons (pop result)
1463           (nreverse result))))
1464
1465 ;; Parse an IMAP response line lightly.  They look like
1466 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1467 ;; the lines into a list of strings and lists of string.
1468 (defun nnimap-parse-line (line)
1469   (let (char result)
1470     (with-temp-buffer
1471       (insert line)
1472       (goto-char (point-min))
1473       (while (not (eobp))
1474         (if (eql (setq char (following-char)) ? )
1475             (forward-char 1)
1476           (push
1477            (cond
1478             ((eql char ?\[)
1479              (split-string
1480               (buffer-substring
1481                (1+ (point))
1482                (1- (search-forward "]" (line-end-position) 'move)))))
1483             ((eql char ?\()
1484              (split-string
1485               (buffer-substring
1486                (1+ (point))
1487                (1- (search-forward ")" (line-end-position) 'move)))))
1488             ((eql char ?\")
1489              (forward-char 1)
1490              (buffer-substring
1491               (point)
1492               (1- (or (search-forward "\"" (line-end-position) 'move)
1493                       (point)))))
1494             (t
1495              (buffer-substring (point) (if (search-forward " " nil t)
1496                                            (1- (point))
1497                                          (goto-char (point-max))))))
1498            result)))
1499       (nreverse result))))
1500
1501 (defun nnimap-last-response-string ()
1502   (save-excursion
1503     (forward-line 1)
1504     (let ((end (point)))
1505       (forward-line -1)
1506       (when (not (bobp))
1507         (forward-line -1)
1508         (while (and (not (bobp))
1509                     (eql (following-char) ?*))
1510           (forward-line -1))
1511         (unless (eql (following-char) ?*)
1512           (forward-line 1)))
1513       (buffer-substring (point) end))))
1514
1515 (defun nnimap-get-responses (sequences)
1516   (let (responses)
1517     (dolist (sequence sequences)
1518       (goto-char (point-min))
1519       (when (re-search-forward (format "^%d " sequence) nil t)
1520         (push (list sequence (nnimap-parse-response))
1521               responses)))
1522     responses))
1523
1524 (defvar nnimap-incoming-split-list nil)
1525
1526 (defun nnimap-fetch-inbox (articles)
1527   (erase-buffer)
1528   (nnimap-wait-for-response
1529    (nnimap-send-command
1530     "UID FETCH %s %s"
1531     (nnimap-article-ranges articles)
1532     (format "(UID %s%s)"
1533             (format
1534              (if (nnimap-ver4-p)
1535                  "BODY.PEEK[HEADER] BODY.PEEK"
1536                "RFC822.PEEK"))
1537             (if nnimap-split-download-body-default
1538                 "[]"
1539               "[1]")))
1540    t))
1541
1542 (defun nnimap-split-incoming-mail ()
1543   (with-current-buffer (nnimap-buffer)
1544     (let ((nnimap-incoming-split-list nil)
1545           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1546                                     nnmail-split-methods
1547                                   nnimap-split-methods))
1548           (nnmail-split-fancy (or nnimap-split-fancy
1549                                   nnmail-split-fancy))
1550           (nnmail-inhibit-default-split-group t)
1551           (groups (nnimap-get-groups))
1552           new-articles)
1553       (erase-buffer)
1554       (nnimap-command "SELECT %S" nnimap-inbox)
1555       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1556       (when new-articles
1557         (nnimap-fetch-inbox new-articles)
1558         (nnimap-transform-split-mail)
1559         (nnheader-ms-strip-cr)
1560         (nnmail-cache-open)
1561         (nnmail-split-incoming (current-buffer)
1562                                #'nnimap-save-mail-spec
1563                                nil nil
1564                                #'nnimap-dummy-active-number
1565                                #'nnimap-save-mail-spec)
1566         (when nnimap-incoming-split-list
1567           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1568                 sequences junk-articles)
1569             ;; Create any groups that doesn't already exist on the
1570             ;; server first.
1571             (dolist (spec specs)
1572               (when (and (not (member (car spec) groups))
1573                          (not (eq (car spec) 'junk)))
1574                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1575             ;; Then copy over all the messages.
1576             (erase-buffer)
1577             (dolist (spec specs)
1578               (let ((group (car spec))
1579                     (ranges (cdr spec)))
1580                 (if (eq group 'junk)
1581                     (setq junk-articles ranges)
1582                   (push (list (nnimap-send-command
1583                                "UID COPY %s %S"
1584                                (nnimap-article-ranges ranges)
1585                                (utf7-encode group t))
1586                               ranges)
1587                         sequences))))
1588             ;; Wait for the last COPY response...
1589             (when sequences
1590               (nnimap-wait-for-response (caar sequences))
1591               ;; And then mark the successful copy actions as deleted,
1592               ;; and possibly expunge them.
1593               (nnimap-mark-and-expunge-incoming
1594                (nnimap-parse-copied-articles sequences)))
1595             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1596
1597 (defun nnimap-mark-and-expunge-incoming (range)
1598   (when range
1599     (setq range (nnimap-article-ranges range))
1600     (erase-buffer)
1601     (let ((sequence
1602            (nnimap-send-command
1603             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1604       (cond
1605        ;; If the server supports it, we now delete the message we have
1606        ;; just copied over.
1607        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1608         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1609        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1610        ;; user has configured it.
1611        (nnimap-expunge
1612         (setq sequence (nnimap-send-command "EXPUNGE"))))
1613       (nnimap-wait-for-response sequence))))
1614
1615 (defun nnimap-parse-copied-articles (sequences)
1616   (let (sequence copied range)
1617     (goto-char (point-min))
1618     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1619       (setq sequence (string-to-number (match-string 1)))
1620       (when (setq range (cadr (assq sequence sequences)))
1621         (push (gnus-uncompress-range range) copied)))
1622     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1623
1624 (defun nnimap-new-articles (flags)
1625   (let (new)
1626     (dolist (elem flags)
1627       (when (or (null (cdr elem))
1628                 (and (not (memq '%Deleted (cdr elem)))
1629                      (not (memq '%Seen (cdr elem)))))
1630         (push (car elem) new)))
1631     (gnus-compress-sequence (nreverse new))))
1632
1633 (defun nnimap-make-split-specs (list)
1634   (let ((specs nil)
1635         entry)
1636     (dolist (elem list)
1637       (destructuring-bind (article spec) elem
1638         (dolist (group (delete nil (mapcar #'car spec)))
1639           (unless (setq entry (assoc group specs))
1640             (push (setq entry (list group)) specs))
1641           (setcdr entry (cons article (cdr entry))))))
1642     (dolist (entry specs)
1643       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1644     specs))
1645
1646 (defun nnimap-transform-split-mail ()
1647   (goto-char (point-min))
1648   (let (article bytes)
1649     (block nil
1650       (while (not (eobp))
1651         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1652           (delete-region (point) (progn (forward-line 1) (point)))
1653           (when (eobp)
1654             (return)))
1655         (setq article (match-string 1)
1656               bytes (nnimap-get-length))
1657         (delete-region (line-beginning-position) (line-end-position))
1658         ;; Insert MMDF separator, and a way to remember what this
1659         ;; article UID is.
1660         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1661         (forward-char (1+ bytes))
1662         (setq bytes (nnimap-get-length))
1663         (delete-region (line-beginning-position) (line-end-position))
1664         ;; There's a body; skip past that.
1665         (when bytes
1666           (forward-char (1+ bytes))
1667           (delete-region (line-beginning-position) (line-end-position)))))))
1668
1669 (defun nnimap-dummy-active-number (group &optional server)
1670   1)
1671
1672 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1673   (let (article)
1674     (goto-char (point-min))
1675     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1676         (error "Invalid nnimap mail")
1677       (setq article (string-to-number (match-string 1))))
1678     (push (list article
1679                 (if (eq group-art 'junk)
1680                     (list (cons 'junk 1))
1681                   group-art))
1682           nnimap-incoming-split-list)))
1683
1684 (provide 'nnimap)
1685
1686 ;;; nnimap.el ends here