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