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