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