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