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