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