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