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