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