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