nnimap.el, pop3.el: Make IMAP and POP3 warn unless encrypted
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2014 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   ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
32   ;; `make-network-stream'.
33   (unless (fboundp 'open-protocol-stream)
34     (require 'proto-stream)))
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 (require 'nnmail)
48
49 (autoload 'auth-source-forget+ "auth-source")
50 (autoload 'auth-source-search "auth-source")
51
52 (nnoo-declare nnimap)
53
54 (defvoo nnimap-address nil
55   "The address of the IMAP server.")
56
57 (defvoo nnimap-user nil
58   "Username to use for authentication to the IMAP server.")
59
60 (defvoo nnimap-server-port nil
61   "The IMAP port used.
62 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
63 it will default to `imap'.")
64
65 (defvoo nnimap-stream 'undecided
66   "How nnimap talks to the IMAP server.
67 The value should be either `undecided', `ssl' or `tls',
68 `network', `starttls', `plain', or `shell'.
69
70 If the value is `undecided', nnimap tries `ssl' first, then falls
71 back on `network'.")
72
73 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
74                                  (if (listp imap-shell-program)
75                                      (car imap-shell-program)
76                                    imap-shell-program)
77                                "ssh %s imapd"))
78
79 (defvoo nnimap-inbox nil
80   "The mail box where incoming mail arrives and should be split out of.
81 This can be a string or a list of strings
82 For example, \"INBOX\" or (\"INBOX\" \"SENT\").")
83
84 (defvoo nnimap-split-methods nil
85   "How mail is split.
86 Uses the same syntax as `nnmail-split-methods'.")
87
88 (defvoo nnimap-split-fancy nil
89   "Uses the same syntax as `nnmail-split-fancy'.")
90
91 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
92   "Articles with the flags in the list will not be considered when splitting.")
93
94 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'."
95                         "Emacs 24.1")
96
97 (defvoo nnimap-authenticator nil
98   "How nnimap authenticate itself to the server.
99 Possible choices are nil (use default methods), `anonymous',
100 `login', `plain' and `cram-md5'.")
101
102 (defvoo nnimap-expunge t
103   "If non-nil, expunge articles after deleting them.
104 This is always done if the server supports UID EXPUNGE, but it's
105 not done by default on servers that doesn't support that command.")
106
107 (defvoo nnimap-streaming t
108   "If non-nil, try to use streaming commands with IMAP servers.
109 Switching this off will make nnimap slower, but it helps with
110 some servers.")
111
112 (defvoo nnimap-connection-alist nil)
113
114 (defvoo nnimap-current-infos nil)
115
116 (defvoo nnimap-fetch-partial-articles nil
117   "If non-nil, Gnus will fetch partial articles.
118 If t, Gnus will fetch only the first part.  If a string, it
119 will fetch all parts that have types that match that string.  A
120 likely value would be \"text/\" to automatically fetch all
121 textual parts.")
122
123 (defgroup nnimap nil
124   "IMAP for Gnus."
125   :group 'gnus)
126
127 (defcustom nnimap-request-articles-find-limit nil
128   "Limit the number of articles to look for after moving an article."
129   :type '(choice (const nil) integer)
130   :version "24.4"
131   :group 'nnimap)
132
133 (defvar nnimap-process nil)
134
135 (defvar nnimap-status-string "")
136
137 (defvar nnimap-split-download-body-default nil
138   "Internal variable with default value for `nnimap-split-download-body'.")
139
140 (defvar nnimap-keepalive-timer nil)
141 (defvar nnimap-process-buffers nil)
142
143 (defstruct nnimap
144   group process commands capabilities select-result newlinep server
145   last-command-time greeting examined stream-type initial-resync)
146
147 (defvar nnimap-object nil)
148
149 (defvar nnimap-mark-alist
150   '((read "\\Seen" %Seen)
151     (tick "\\Flagged" %Flagged)
152     (reply "\\Answered" %Answered)
153     (expire "gnus-expire")
154     (dormant "gnus-dormant")
155     (score "gnus-score")
156     (save "gnus-save")
157     (download "gnus-download")
158     (forward "gnus-forward")))
159
160 (defvar nnimap-quirks
161   '(("QRESYNC" "Zimbra" "QRESYNC ")))
162
163 (defvar nnimap-inhibit-logging nil)
164
165 (defun nnimap-buffer ()
166   (nnimap-find-process-buffer nntp-server-buffer))
167
168 (defun nnimap-header-parameters ()
169   (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
170           (format
171            (if (nnimap-ver4-p)
172                "BODY.PEEK[HEADER.FIELDS %s]"
173              "RFC822.HEADER.LINES %s")
174            (append '(Subject From Date Message-Id
175                              References In-Reply-To Xref)
176                    nnmail-extra-headers))))
177
178 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
179   (when group
180     (setq group (nnimap-decode-gnus-group group)))
181   (with-current-buffer nntp-server-buffer
182     (erase-buffer)
183     (when (nnimap-change-group group server)
184       (with-current-buffer (nnimap-buffer)
185         (erase-buffer)
186         (nnimap-wait-for-response
187          (nnimap-send-command
188           "UID FETCH %s %s"
189           (nnimap-article-ranges (gnus-compress-sequence articles))
190           (nnimap-header-parameters))
191          t)
192         (nnimap-transform-headers)
193         (nnheader-remove-cr-followed-by-lf))
194       (insert-buffer-substring
195        (nnimap-find-process-buffer (current-buffer))))
196     'headers))
197
198 (defun nnimap-transform-headers ()
199   (goto-char (point-min))
200   (let (article lines size string)
201     (block nil
202       (while (not (eobp))
203         (while (not (looking-at "\\* [0-9]+ FETCH"))
204           (delete-region (point) (progn (forward-line 1) (point)))
205           (when (eobp)
206             (return)))
207         (goto-char (match-end 0))
208         ;; Unfold quoted {number} strings.
209         (while (re-search-forward
210                 "[^]][ (]{\\([0-9]+\\)}\r?\n"
211                 (save-excursion
212                   ;; Start of the header section.
213                   (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
214                       ;; Start of the next FETCH.
215                       (re-search-forward "\\* [0-9]+ FETCH" nil t)
216                       (point-max)))
217                 t)
218           (setq size (string-to-number (match-string 1)))
219           (delete-region (+ (match-beginning 0) 2) (point))
220           (setq string (buffer-substring (point) (+ (point) size)))
221           (delete-region (point) (+ (point) size))
222           (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
223         (beginning-of-line)
224         (setq article
225               (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
226                                       t)
227                    (match-string 1)))
228         (setq lines nil)
229         (setq size
230               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
231                                       (line-end-position)
232                                       t)
233                    (match-string 1)))
234         (beginning-of-line)
235         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
236           (let ((structure (ignore-errors
237                              (read (current-buffer)))))
238             (while (and (consp structure)
239                         (not (atom (car structure))))
240               (setq structure (car structure)))
241             (setq lines (if (and
242                              (stringp (car structure))
243                              (equal (upcase (nth 0 structure)) "MESSAGE")
244                              (equal (upcase (nth 1 structure)) "RFC822"))
245                             (nth 9 structure)
246                           (nth 7 structure)))))
247         (delete-region (line-beginning-position) (line-end-position))
248         (insert (format "211 %s Article retrieved." article))
249         (forward-line 1)
250         (when size
251           (insert (format "Chars: %s\n" size)))
252         (when lines
253           (insert (format "Lines: %s\n" lines)))
254         ;; Most servers have a blank line after the headers, but
255         ;; Davmail doesn't.
256         (unless (re-search-forward "^\r$\\|^)\r?$" nil t)
257           (goto-char (point-max)))
258         (delete-region (line-beginning-position) (line-end-position))
259         (insert ".")
260         (forward-line 1)))))
261
262 (defun nnimap-unfold-quoted-lines ()
263   ;; Unfold quoted {number} strings.
264   (let (size string)
265     (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
266       (setq size (string-to-number (match-string 1)))
267       (delete-region (1+ (match-beginning 0)) (point))
268       (setq string (buffer-substring (point) (+ (point) size)))
269       (delete-region (point) (+ (point) size))
270       (insert (format "%S" string)))))
271
272 (defun nnimap-get-length ()
273   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
274        (string-to-number (match-string 1))))
275
276 (defun nnimap-article-ranges (ranges)
277   (let (result)
278     (cond
279      ((numberp ranges)
280       (number-to-string ranges))
281      ((numberp (cdr ranges))
282       (format "%d:%d" (car ranges) (cdr ranges)))
283      (t
284       (dolist (elem ranges)
285         (push
286          (if (consp elem)
287              (format "%d:%d" (car elem) (cdr elem))
288            (number-to-string elem))
289          result))
290       (mapconcat #'identity (nreverse result) ",")))))
291
292 (deffoo nnimap-open-server (server &optional defs no-reconnect)
293   (if (nnimap-server-opened server)
294       t
295     (unless (assq 'nnimap-address defs)
296       (setq defs (append defs (list (list 'nnimap-address server)))))
297     (nnoo-change-server 'nnimap server defs)
298     (if no-reconnect
299         (nnimap-find-connection nntp-server-buffer)
300       (or (nnimap-find-connection nntp-server-buffer)
301           (nnimap-open-connection nntp-server-buffer)))))
302
303 (defun nnimap-make-process-buffer (buffer)
304   (with-current-buffer
305       (generate-new-buffer (format " *nnimap %s %s %s*"
306                                    nnimap-address nnimap-server-port
307                                    (gnus-buffer-exists-p buffer)))
308     (mm-disable-multibyte)
309     (buffer-disable-undo)
310     (gnus-add-buffer)
311     (set (make-local-variable 'after-change-functions) nil)
312     (set (make-local-variable 'nnimap-object)
313          (make-nnimap :server (nnoo-current-server 'nnimap)
314                       :initial-resync 0))
315     (push (list buffer (current-buffer)) nnimap-connection-alist)
316     (push (current-buffer) nnimap-process-buffers)
317     (current-buffer)))
318
319 (defun nnimap-credentials (address ports user)
320   (let* ((auth-source-creation-prompts
321           '((user  . "IMAP user at %h: ")
322             (secret . "IMAP password for %u@%h: ")))
323          (found (nth 0 (auth-source-search :max 1
324                                            :host address
325                                            :port ports
326                                            :user user
327                                            :require '(:user :secret)
328                                            :create t))))
329     (if found
330         (list (plist-get found :user)
331               (let ((secret (plist-get found :secret)))
332                 (if (functionp secret)
333                     (funcall secret)
334                   secret))
335               (plist-get found :save-function))
336       nil)))
337
338 (defun nnimap-keepalive ()
339   (let ((now (current-time)))
340     (dolist (buffer nnimap-process-buffers)
341       (when (buffer-name buffer)
342         (with-current-buffer buffer
343           (when (and nnimap-object
344                      (nnimap-last-command-time nnimap-object)
345                      (> (gnus-float-time
346                          (time-subtract
347                           now
348                           (nnimap-last-command-time nnimap-object)))
349                         ;; More than five minutes since the last command.
350                         (* 5 60)))
351             (ignore-errors              ;E.g. "buffer foo has no process".
352               (nnimap-send-command "NOOP"))))))))
353
354 (defun nnimap-open-connection (buffer)
355   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
356   ;; `ssl' when nnimap-server-port was nil.  Sort of.
357   (when (and nnimap-server-port
358              (eq nnimap-stream 'undecided))
359     (setq nnimap-stream 'ssl))
360   (let ((stream
361          (if (eq nnimap-stream 'undecided)
362              (loop for type in '(ssl network)
363                    for stream = (let ((nnimap-stream type))
364                                   (nnimap-open-connection-1 buffer))
365                    while (eq stream 'no-connect)
366                    finally (return stream))
367            (nnimap-open-connection-1 buffer))))
368     (if (eq stream 'no-connect)
369         nil
370       stream)))
371
372 (defun nnimap-map-port (port)
373   (if (equal port "imaps")
374       "993"
375     port))
376
377 (defun nnimap-open-connection-1 (buffer)
378   (unless nnimap-keepalive-timer
379     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
380                                               #'nnimap-keepalive)))
381   (with-current-buffer (nnimap-make-process-buffer buffer)
382     (let* ((coding-system-for-read 'binary)
383            (coding-system-for-write 'binary)
384            (ports
385             (cond
386              ((memq nnimap-stream '(network plain starttls))
387               (nnheader-message 7 "Opening connection to %s..."
388                                 nnimap-address)
389               '("imap" "143"))
390              ((eq nnimap-stream 'shell)
391               (nnheader-message 7 "Opening connection to %s via shell..."
392                                 nnimap-address)
393               '("imap"))
394              ((memq nnimap-stream '(ssl tls))
395               (nnheader-message 7 "Opening connection to %s via tls..."
396                                 nnimap-address)
397               '("imaps" "imap" "993" "143"))
398              (t
399               (error "Unknown stream type: %s" nnimap-stream))))
400            login-result credentials)
401       (when nnimap-server-port
402         (push nnimap-server-port ports))
403       (let* ((stream-list
404               (open-protocol-stream
405                "*nnimap*" (current-buffer) nnimap-address
406                (nnimap-map-port (car ports))
407                :type nnimap-stream
408                :warn-unless-encrypted t
409                :return-list t
410                :shell-command nnimap-shell-program
411                :capability-command "1 CAPABILITY\r\n"
412                :end-of-command "\r\n"
413                :success " OK "
414                :starttls-function
415                (lambda (capabilities)
416                  (when (gnus-string-match-p "STARTTLS" capabilities)
417                    "1 STARTTLS\r\n"))))
418              (stream (car stream-list))
419              (props (cdr stream-list))
420              (greeting (plist-get props :greeting))
421              (capabilities (plist-get props :capabilities))
422              (stream-type (plist-get props :type)))
423         (when (and stream (not (memq (process-status stream) '(open run))))
424           (setq stream nil))
425
426         (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
427                    (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
428                    (eq (process-type stream) 'network))
429           ;; Use TCP-keepalive so that connections that pass through a NAT
430           ;; router don't hang when left idle.
431           (set-network-process-option stream :keepalive t))
432
433         (setf (nnimap-process nnimap-object) stream)
434         (setf (nnimap-stream-type nnimap-object) stream-type)
435         (if (not stream)
436             (progn
437               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
438                                nnimap-address (car ports) nnimap-stream)
439               'no-connect)
440           (gnus-set-process-query-on-exit-flag stream nil)
441           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
442               (nnheader-report 'nnimap "%s" greeting)
443             ;; Store the greeting (for debugging purposes).
444             (setf (nnimap-greeting nnimap-object) greeting)
445             (setf (nnimap-capabilities nnimap-object)
446                   (mapcar #'upcase
447                           (split-string capabilities)))
448             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
449               (if (not (setq credentials
450                              (if (eq nnimap-authenticator 'anonymous)
451                                  (list "anonymous"
452                                        (message-make-address))
453                                ;; Look for the credentials based on
454                                ;; the virtual server name and the address
455                                (nnimap-credentials
456                                 (gnus-delete-duplicates
457                                  (list
458                                   (nnoo-current-server 'nnimap)
459                                   nnimap-address))
460                                 ports
461                                 nnimap-user))))
462                   (setq nnimap-object nil)
463                 (let ((nnimap-inhibit-logging t))
464                   (setq login-result
465                         (nnimap-login (car credentials) (cadr credentials))))
466                 (if (car login-result)
467                     (progn
468                       ;; Save the credentials if a save function exists
469                       ;; (such a function will only be passed if a new
470                       ;; token was created).
471                       (when (functionp (nth 2 credentials))
472                         (funcall (nth 2 credentials)))
473                       ;; See if CAPABILITY is set as part of login
474                       ;; response.
475                       (dolist (response (cddr login-result))
476                         (when (string= "CAPABILITY" (upcase (car response)))
477                           (setf (nnimap-capabilities nnimap-object)
478                                 (mapcar #'upcase (cdr response))))))
479                   ;; If the login failed, then forget the credentials
480                   ;; that are now possibly cached.
481                   (dolist (host (list (nnoo-current-server 'nnimap)
482                                       nnimap-address))
483                     (dolist (port ports)
484                       (auth-source-forget+ :host host :port port)))
485                   (delete-process (nnimap-process nnimap-object))
486                   (setq nnimap-object nil))))
487             (when nnimap-object
488               (when (nnimap-capability "QRESYNC")
489                 (nnimap-command "ENABLE QRESYNC"))
490               (nnheader-message 7 "Opening connection to %s...done"
491                                 nnimap-address)
492               (nnimap-process nnimap-object))))))))
493
494 (autoload 'rfc2104-hash "rfc2104")
495
496 (defun nnimap-login (user password)
497   (cond
498    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
499    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
500    ;; and we're using an encrypted connection.
501    ((and (not (nnimap-capability "LOGINDISABLED"))
502          (eq (nnimap-stream-type nnimap-object) 'tls)
503          (or (null nnimap-authenticator)
504              (eq nnimap-authenticator 'login)))
505     (nnimap-command "LOGIN %S %S" user password))
506    ((and (nnimap-capability "AUTH=CRAM-MD5")
507          (or (null nnimap-authenticator)
508              (eq nnimap-authenticator 'cram-md5)))
509     (erase-buffer)
510     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
511           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
512       (process-send-string
513        (get-buffer-process (current-buffer))
514        (concat
515         (base64-encode-string
516          (concat user " "
517                  (rfc2104-hash 'md5 64 16 password
518                                (base64-decode-string challenge))))
519         "\r\n"))
520       (nnimap-wait-for-response sequence)))
521    ((and (not (nnimap-capability "LOGINDISABLED"))
522          (or (null nnimap-authenticator)
523              (eq nnimap-authenticator 'login)))
524     (nnimap-command "LOGIN %S %S" user password))
525    ((and (nnimap-capability "AUTH=PLAIN")
526          (or (null nnimap-authenticator)
527              (eq nnimap-authenticator 'plain)))
528     (nnimap-command
529      "AUTHENTICATE PLAIN %s"
530      (base64-encode-string
531       (format "\000%s\000%s"
532               (nnimap-quote-specials user)
533               (nnimap-quote-specials password)))))))
534
535 (defun nnimap-quote-specials (string)
536   (with-temp-buffer
537     (insert string)
538     (goto-char (point-min))
539     (while (re-search-forward "[\\\"]" nil t)
540       (forward-char -1)
541       (insert "\\")
542       (forward-char 1))
543     (buffer-string)))
544
545 (defun nnimap-find-parameter (parameter elems)
546   (let (result)
547     (dolist (elem elems)
548       (cond
549        ((equal (car elem) parameter)
550         (setq result (cdr elem)))
551        ((and (equal (car elem) "OK")
552              (consp (cadr elem))
553              (equal (caadr elem) parameter))
554         (setq result (cdr (cadr elem))))))
555     result))
556
557 (deffoo nnimap-close-server (&optional server)
558   (when (nnoo-change-server 'nnimap server nil)
559     (ignore-errors
560       (delete-process (get-buffer-process (nnimap-buffer))))
561     (nnoo-close-server 'nnimap server)
562     t))
563
564 (deffoo nnimap-request-close ()
565   t)
566
567 (deffoo nnimap-server-opened (&optional server)
568   (and (nnoo-current-server-p 'nnimap server)
569        nntp-server-buffer
570        (gnus-buffer-live-p nntp-server-buffer)
571        (nnimap-find-connection nntp-server-buffer)))
572
573 (deffoo nnimap-status-message (&optional server)
574   nnimap-status-string)
575
576 (deffoo nnimap-request-article (article &optional group server to-buffer)
577   (when group
578     (setq group (nnimap-decode-gnus-group group)))
579   (with-current-buffer nntp-server-buffer
580     (let ((result (nnimap-change-group group server))
581           parts structure)
582       (when (stringp article)
583         (setq article (nnimap-find-article-by-message-id group server article)))
584       (when (and result
585                  article)
586         (erase-buffer)
587         (with-current-buffer (nnimap-buffer)
588           (erase-buffer)
589           (when nnimap-fetch-partial-articles
590             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
591             (goto-char (point-min))
592             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
593               (setq structure (ignore-errors
594                                 (let ((start (point)))
595                                   (forward-sexp 1)
596                                   (downcase-region start (point))
597                                   (goto-char start)
598                                   (read (current-buffer))))
599                     parts (nnimap-find-wanted-parts structure))))
600           (when (if parts
601                     (nnimap-get-partial-article article parts structure)
602                   (nnimap-get-whole-article article))
603             (let ((buffer (current-buffer)))
604               (with-current-buffer (or to-buffer nntp-server-buffer)
605                 (nnheader-insert-buffer-substring buffer)
606                 (nnheader-ms-strip-cr)))
607             (cons group article)))))))
608
609 (deffoo nnimap-request-head (article &optional group server to-buffer)
610   (when group
611     (setq group (nnimap-decode-gnus-group group)))
612   (when (nnimap-change-group group server)
613     (with-current-buffer (nnimap-buffer)
614       (when (stringp article)
615         (setq article (nnimap-find-article-by-message-id group server article)))
616       (if (null article)
617           nil
618         (nnimap-get-whole-article
619          article (format "UID FETCH %%d %s"
620                          (nnimap-header-parameters)))
621         (let ((buffer (current-buffer)))
622           (with-current-buffer (or to-buffer nntp-server-buffer)
623             (erase-buffer)
624             (insert-buffer-substring buffer)
625             (nnheader-ms-strip-cr)
626             (cons group article)))))))
627
628 (deffoo nnimap-request-articles (articles &optional group server)
629   (when group
630     (setq group (nnimap-decode-gnus-group group)))
631   (with-current-buffer nntp-server-buffer
632     (let ((result (nnimap-change-group group server)))
633       (when result
634         (erase-buffer)
635         (with-current-buffer (nnimap-buffer)
636           (erase-buffer)
637           (when (nnimap-command
638                  (if (nnimap-ver4-p)
639                      "UID FETCH %s BODY.PEEK[]"
640                    "UID FETCH %s RFC822.PEEK")
641                  (nnimap-article-ranges (gnus-compress-sequence articles)))
642             (let ((buffer (current-buffer)))
643               (with-current-buffer nntp-server-buffer
644                 (nnheader-insert-buffer-substring buffer)
645                 (nnheader-ms-strip-cr)))
646             t))))))
647
648 (defun nnimap-get-whole-article (article &optional command)
649   (let ((result
650          (nnimap-command
651           (or command
652               (if (nnimap-ver4-p)
653                   "UID FETCH %d BODY.PEEK[]"
654                 "UID FETCH %d RFC822.PEEK"))
655           article)))
656     ;; Check that we really got an article.
657     (goto-char (point-min))
658     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
659       (setq result nil))
660     (when result
661       ;; Remove any data that may have arrived before the FETCH data.
662       (beginning-of-line)
663       (unless (bobp)
664         (delete-region (point-min) (point)))
665       (let ((bytes (nnimap-get-length)))
666         (delete-region (line-beginning-position)
667                        (progn (forward-line 1) (point)))
668         (goto-char (+ (point) bytes))
669         (delete-region (point) (point-max)))
670       t)))
671
672 (defun nnimap-capability (capability)
673   (member capability (nnimap-capabilities nnimap-object)))
674
675 (defun nnimap-ver4-p ()
676   (nnimap-capability "IMAP4REV1"))
677
678 (defun nnimap-get-partial-article (article parts structure)
679   (let ((result
680          (nnimap-command
681           "UID FETCH %d (%s %s)"
682           article
683           (if (nnimap-ver4-p)
684               "BODY.PEEK[HEADER]"
685             "RFC822.HEADER")
686           (if (nnimap-ver4-p)
687               (mapconcat (lambda (part)
688                            (format "BODY.PEEK[%s]" part))
689                          parts " ")
690             (mapconcat (lambda (part)
691                          (format "RFC822.PEEK[%s]" part))
692                        parts " ")))))
693     (when result
694       (nnimap-convert-partial-article structure))))
695
696 (defun nnimap-convert-partial-article (structure)
697   ;; First just skip past the headers.
698   (goto-char (point-min))
699   (let ((bytes (nnimap-get-length))
700         id parts)
701     ;; Delete "FETCH" line.
702     (delete-region (line-beginning-position)
703                    (progn (forward-line 1) (point)))
704     (goto-char (+ (point) bytes))
705     ;; Collect all the body parts.
706     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
707       (setq id (match-string 1)
708             bytes (or (nnimap-get-length) 0))
709       (beginning-of-line)
710       (delete-region (point) (progn (forward-line 1) (point)))
711       (push (list id (buffer-substring (point) (+ (point) bytes)))
712             parts)
713       (delete-region (point) (+ (point) bytes)))
714     ;; Delete trailing junk.
715     (delete-region (point) (point-max))
716     ;; Now insert all the parts again where they fit in the structure.
717     (nnimap-insert-partial-structure structure parts)
718     t))
719
720 (defun nnimap-insert-partial-structure (structure parts &optional subp)
721   (let (type boundary)
722     (let ((bstruc structure))
723       (while (consp (car bstruc))
724         (pop bstruc))
725       (setq type (car bstruc))
726       (setq bstruc (car (cdr bstruc)))
727       (let ((has-boundary (member "boundary" bstruc)))
728         (when has-boundary
729           (setq boundary (cadr has-boundary)))))
730     (when subp
731       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
732                       (downcase type) boundary)))
733     (while (not (stringp (car structure)))
734       (insert "\n--" boundary "\n")
735       (if (consp (caar structure))
736           (nnimap-insert-partial-structure (pop structure) parts t)
737         (let ((bit (pop structure)))
738           (insert (format "Content-type: %s/%s"
739                           (downcase (nth 0 bit))
740                           (downcase (nth 1 bit))))
741           (if (member-ignore-case "CHARSET" (nth 2 bit))
742               (insert (format
743                        "; charset=%S\n"
744                        (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
745             (insert "\n"))
746           (insert (format "Content-transfer-encoding: %s\n"
747                           (nth 5 bit)))
748           (insert "\n")
749           (when (assoc (nth 9 bit) parts)
750             (insert (cadr (assoc (nth 9 bit) parts)))))))
751     (insert "\n--" boundary "--\n")))
752
753 (defun nnimap-find-wanted-parts (structure)
754   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
755
756 (defun nnimap-find-wanted-parts-1 (structure prefix)
757   (let ((num 1)
758         parts)
759     (while (consp (car structure))
760       (let ((sub (pop structure)))
761         (if (consp (car sub))
762             (push (nnimap-find-wanted-parts-1
763                    sub (if (string= prefix "")
764                            (number-to-string num)
765                          (format "%s.%s" prefix num)))
766                   parts)
767           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
768                 (id (if (string= prefix "")
769                         (number-to-string num)
770                       (format "%s.%s" prefix num))))
771             (setcar (nthcdr 9 sub) id)
772             (when (if (eq nnimap-fetch-partial-articles t)
773                       (equal id "1")
774                     (string-match nnimap-fetch-partial-articles type))
775               (push id parts))))
776         (incf num)))
777     (nreverse parts)))
778
779 (defun nnimap-decode-gnus-group (group)
780   (decode-coding-string group 'utf-8))
781
782 (deffoo nnimap-request-group (group &optional server dont-check info)
783   (setq group (nnimap-decode-gnus-group group))
784   (let ((result (nnimap-change-group
785                  ;; Don't SELECT the group if we're going to select it
786                  ;; later, anyway.
787                  (if (and (not dont-check)
788                           (assoc group nnimap-current-infos))
789                      nil
790                    group)
791                  server))
792         articles active marks high low)
793     (with-current-buffer nntp-server-buffer
794       (when result
795         (if (and dont-check
796                  (setq active (nth 2 (assoc group nnimap-current-infos))))
797             (insert (format "211 %d %d %d %S\n"
798                             (- (cdr active) (car active))
799                             (car active)
800                             (cdr active)
801                             group))
802           (with-current-buffer (nnimap-buffer)
803             (erase-buffer)
804             (let ((group-sequence
805                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
806                   (flag-sequence
807                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
808               (setf (nnimap-group nnimap-object) group)
809               (nnimap-wait-for-response flag-sequence)
810               (setq marks
811                     (nnimap-flags-to-marks
812                      (nnimap-parse-flags
813                       (list (list group-sequence flag-sequence
814                                   1 group "SELECT")))))
815               (when (and info
816                          marks)
817                 (nnimap-update-infos marks (list info))
818                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
819               (goto-char (point-max))
820               (let ((uidnext (nth 5 (car marks))))
821                 (setq high (or (if uidnext
822                                    (1- uidnext)
823                                  (nth 3 (car marks)))
824                                0)
825                       low (or (nth 4 (car marks)) uidnext 1)))))
826           (erase-buffer)
827           (insert
828            (format
829             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
830         t))))
831
832 (deffoo nnimap-request-create-group (group &optional server args)
833   (setq group (nnimap-decode-gnus-group group))
834   (when (nnimap-change-group nil server)
835     (with-current-buffer (nnimap-buffer)
836       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
837
838 (deffoo nnimap-request-delete-group (group &optional force server)
839   (setq group (nnimap-decode-gnus-group group))
840   (when (nnimap-change-group nil server)
841     (with-current-buffer (nnimap-buffer)
842       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
843
844 (deffoo nnimap-request-rename-group (group new-name &optional server)
845   (setq group (nnimap-decode-gnus-group group))
846   (when (nnimap-change-group nil server)
847     (with-current-buffer (nnimap-buffer)
848       (nnimap-unselect-group)
849       (car (nnimap-command "RENAME %S %S"
850                            (utf7-encode group t) (utf7-encode new-name t))))))
851
852 (defun nnimap-unselect-group ()
853   ;; Make sure we don't have this group open read/write by asking
854   ;; to examine a mailbox that doesn't exist.  This seems to be
855   ;; the only way that allows us to reliably go back to unselected
856   ;; state on Courier.
857   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
858
859 (deffoo nnimap-request-expunge-group (group &optional server)
860   (setq group (nnimap-decode-gnus-group group))
861   (when (nnimap-change-group group server)
862     (with-current-buffer (nnimap-buffer)
863       (car (nnimap-command "EXPUNGE")))))
864
865 (defun nnimap-get-flags (spec)
866   (let ((articles nil)
867         elems end)
868     (with-current-buffer (nnimap-buffer)
869       (erase-buffer)
870       (nnimap-wait-for-response (nnimap-send-command
871                                  "UID FETCH %s FLAGS" spec))
872       (setq end (point))
873       (subst-char-in-region (point-min) (point-max)
874                             ?\\ ?% t)
875       (goto-char (point-min))
876       (while (search-forward " FETCH " end t)
877         (setq elems (read (current-buffer)))
878         (push (cons (cadr (memq 'UID elems))
879                     (cadr (memq 'FLAGS elems)))
880               articles)))
881     (nreverse articles)))
882
883 (deffoo nnimap-close-group (group &optional server)
884   t)
885
886 (deffoo nnimap-request-move-article (article group server accept-form
887                                              &optional last internal-move-group)
888   (setq group (nnimap-decode-gnus-group group))
889   (when internal-move-group
890     (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
891   (with-temp-buffer
892     (mm-disable-multibyte)
893     (when (funcall (if internal-move-group
894                        'nnimap-request-head
895                      'nnimap-request-article)
896                    article group server (current-buffer))
897       ;; If the move is internal (on the same server), just do it the easy
898       ;; way.
899       (let ((message-id (message-field-value "message-id")))
900         (if internal-move-group
901             (let ((result
902                    (with-current-buffer (nnimap-buffer)
903                      (nnimap-command "UID COPY %d %S"
904                                      article
905                                      (utf7-encode internal-move-group t)))))
906               (when (car result)
907                 (nnimap-delete-article article)
908                 (cons internal-move-group
909                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
910                           (nnimap-find-article-by-message-id
911                            internal-move-group server message-id
912                            nnimap-request-articles-find-limit)))))
913           ;; Move the article to a different method.
914           (let ((result (eval accept-form)))
915             (when result
916               (nnimap-change-group group server)
917               (nnimap-delete-article article)
918               result)))))))
919
920 (deffoo nnimap-request-expire-articles (articles group &optional server force)
921   (setq group (nnimap-decode-gnus-group group))
922   (cond
923    ((null articles)
924     nil)
925    ((not (nnimap-change-group group server))
926     articles)
927    ((and force
928          (eq nnmail-expiry-target 'delete))
929     (unless (nnimap-delete-article (gnus-compress-sequence articles))
930       (nnheader-message 7 "Article marked for deletion, but not expunged."))
931     nil)
932    (t
933     (let ((deletable-articles
934            (if (or force
935                    (eq nnmail-expiry-wait 'immediate))
936                articles
937              (gnus-sorted-intersection
938               articles
939               (nnimap-find-expired-articles group)))))
940       (if (null deletable-articles)
941           articles
942         (if (eq nnmail-expiry-target 'delete)
943             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
944           (setq deletable-articles
945                 (nnimap-process-expiry-targets
946                  deletable-articles group server)))
947         ;; Return the articles we didn't delete.
948         (gnus-sorted-complement articles deletable-articles))))))
949
950 (defun nnimap-process-expiry-targets (articles group server)
951   (let ((deleted-articles nil))
952     (cond
953      ;; shortcut further processing if we're going to delete the articles
954      ((eq nnmail-expiry-target 'delete)
955       (setq deleted-articles articles)
956       t)
957      ;; or just move them to another folder on the same IMAP server
958      ((and (not (functionp nnmail-expiry-target))
959            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
960                               (gnus-server-to-method
961                                (format "nnimap:%s" server))))
962       (and (nnimap-change-group group server)
963            (with-current-buffer (nnimap-buffer)
964              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
965              (nnimap-command
966               "UID COPY %s %S"
967               (nnimap-article-ranges (gnus-compress-sequence articles))
968               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
969              (setq deleted-articles articles)))
970       t)
971      (t
972       (dolist (article articles)
973         (let ((target nnmail-expiry-target))
974           (with-temp-buffer
975             (mm-disable-multibyte)
976             (when (nnimap-request-article article group server (current-buffer))
977               (when (functionp target)
978                 (setq target (funcall target group)))
979               (if (and target
980                        (not (eq target 'delete)))
981                   (if (or (gnus-request-group target t)
982                           (gnus-request-create-group target))
983                       (progn
984                         (nnmail-expiry-target-group target group)
985                         (nnheader-message 7 "Expiring article %s:%d to %s"
986                                           group article target))
987                     (setq target nil))
988                 (nnheader-message 7 "Expiring article %s:%d" group article))
989               (when target
990                 (push article deleted-articles))))))
991       (setq deleted-articles (nreverse deleted-articles))))
992     ;; Change back to the current group again.
993     (nnimap-change-group group server)
994     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
995     deleted-articles))
996
997 (defun nnimap-find-expired-articles (group)
998   (let ((cutoff (nnmail-expired-article-p group nil nil)))
999     (with-current-buffer (nnimap-buffer)
1000       (let ((result
1001              (nnimap-command
1002               "UID SEARCH SENTBEFORE %s"
1003               (format-time-string
1004                (format "%%d-%s-%%Y"
1005                        (upcase
1006                         (car (rassoc (nth 4 (decode-time cutoff))
1007                                      parse-time-months))))
1008                cutoff))))
1009         (and (car result)
1010              (delete 0 (mapcar #'string-to-number
1011                                (cdr (assoc "SEARCH" (cdr result))))))))))
1012
1013
1014 (defun nnimap-find-article-by-message-id (group server message-id
1015                                                 &optional limit)
1016   "Search for message with MESSAGE-ID in GROUP from SERVER.
1017 If LIMIT, first try to limit the search to the N last articles."
1018   (with-current-buffer (nnimap-buffer)
1019     (erase-buffer)
1020     (let* ((change-group-result (nnimap-change-group group server nil t))
1021            (number-of-article
1022             (and (listp change-group-result)
1023                  (catch 'found
1024                    (dolist (result (cdr change-group-result))
1025                      (when (equal "EXISTS" (cadr result))
1026                        (throw 'found (car result)))))))
1027            (sequence
1028             (nnimap-send-command
1029              "UID SEARCH%s HEADER Message-Id %S"
1030              (if (and limit number-of-article)
1031                  ;; The -1 is because IMAP message
1032                  ;; numbers are one-based rather than
1033                  ;; zero-based.
1034                  (format " %s:*" (- (string-to-number number-of-article)
1035                                     limit -1))
1036                "")
1037              message-id)))
1038       (when (nnimap-wait-for-response sequence)
1039         (let ((article (car (last (cdr (assoc "SEARCH"
1040                                               (nnimap-parse-response)))))))
1041           (if article
1042               (string-to-number article)
1043             (when (and limit number-of-article)
1044               (nnimap-find-article-by-message-id group server message-id))))))))
1045
1046 (defun nnimap-delete-article (articles)
1047   (with-current-buffer (nnimap-buffer)
1048     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1049                     (nnimap-article-ranges articles))
1050     (cond
1051      ((nnimap-capability "UIDPLUS")
1052       (nnimap-command "UID EXPUNGE %s"
1053                       (nnimap-article-ranges articles))
1054       t)
1055      (nnimap-expunge
1056       (nnimap-command "EXPUNGE")
1057       t)
1058      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1059                                 "server doesn't support UIDPLUS, so we won't "
1060                                 "delete this article now"))))))
1061
1062 (deffoo nnimap-request-scan (&optional group server)
1063   (when group
1064     (setq group (nnimap-decode-gnus-group group)))
1065   (when (and (nnimap-change-group nil server)
1066              nnimap-inbox
1067              nnimap-split-methods)
1068     (nnheader-message 7 "nnimap %s splitting mail..." server)
1069     (if (listp nnimap-inbox)
1070        (dolist (nnimap-inbox nnimap-inbox)
1071          (nnimap-split-incoming-mail))
1072       (nnimap-split-incoming-mail))
1073     (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1074
1075 (defun nnimap-marks-to-flags (marks)
1076   (let (flags flag)
1077     (dolist (mark marks)
1078       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1079         (push flag flags)))
1080     flags))
1081
1082 (deffoo nnimap-request-update-group-status (group status &optional server)
1083   (setq group (nnimap-decode-gnus-group group))
1084   (when (nnimap-change-group nil server)
1085     (let ((command (assoc
1086                     status
1087                     '((subscribe "SUBSCRIBE")
1088                       (unsubscribe "UNSUBSCRIBE")))))
1089       (when command
1090         (with-current-buffer (nnimap-buffer)
1091           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1092
1093 (deffoo nnimap-request-set-mark (group actions &optional server)
1094   (setq group (nnimap-decode-gnus-group group))
1095   (when (nnimap-change-group group server)
1096     (let (sequence)
1097       (with-current-buffer (nnimap-buffer)
1098         (erase-buffer)
1099         ;; Just send all the STORE commands without waiting for
1100         ;; response.  If they're successful, they're successful.
1101         (dolist (action actions)
1102           (destructuring-bind (range action marks) action
1103             (let ((flags (nnimap-marks-to-flags marks)))
1104               (when flags
1105                 (setq sequence (nnimap-send-command
1106                                 "UID STORE %s %sFLAGS.SILENT (%s)"
1107                                 (nnimap-article-ranges range)
1108                                 (cond
1109                                  ((eq action 'del) "-")
1110                                  ((eq action 'add) "+")
1111                                  ((eq action 'set) ""))
1112                                 (mapconcat #'identity flags " ")))))))
1113         ;; Wait for the last command to complete to avoid later
1114         ;; synchronization problems with the stream.
1115         (when sequence
1116           (nnimap-wait-for-response sequence))))))
1117
1118 (deffoo nnimap-request-accept-article (group &optional server last)
1119   (unless group
1120     ;; We're respooling.  Find out where mail splitting would place
1121     ;; this article.
1122     (setq group
1123           (caar
1124            (nnmail-article-group
1125             `(lambda (group)
1126                (nnml-active-number group ,server))))))
1127   (setq group (nnimap-decode-gnus-group group))
1128   (when (nnimap-change-group nil server)
1129     (nnmail-check-syntax)
1130     (let ((message-id (message-field-value "message-id"))
1131           sequence message)
1132       (nnimap-add-cr)
1133       (setq message (buffer-substring-no-properties (point-min) (point-max)))
1134       (with-current-buffer (nnimap-buffer)
1135         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1136                                 message))
1137           ;; If we have this group open read-only, then unselect it
1138           ;; before appending to it.
1139           (when (equal (nnimap-examined nnimap-object) group)
1140             (nnimap-unselect-group))
1141           (erase-buffer)
1142           (setq sequence (nnimap-send-command
1143                           "APPEND %S {%d}" (utf7-encode group t)
1144                           (length message)))
1145           (unless nnimap-streaming
1146             (nnimap-wait-for-connection "^[+]"))
1147           (process-send-string (get-buffer-process (current-buffer)) message)
1148           (process-send-string (get-buffer-process (current-buffer))
1149                                (if (nnimap-newlinep nnimap-object)
1150                                    "\n"
1151                                  "\r\n"))
1152           (let ((result (nnimap-get-response sequence)))
1153             (if (not (nnimap-ok-p result))
1154                 (progn
1155                   (nnheader-report 'nnimap "%s" result)
1156                   nil)
1157               (cons group
1158                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1159                         (nnimap-find-article-by-message-id
1160                          group server message-id
1161                          nnimap-request-articles-find-limit))))))))))
1162
1163 (defun nnimap-process-quirk (greeting-match type data)
1164   (when (and (nnimap-greeting nnimap-object)
1165              (string-match greeting-match (nnimap-greeting nnimap-object))
1166              (eq type 'append)
1167              (string-match "\000" data))
1168     (let ((choice (gnus-multiple-choice
1169                    "Message contains NUL characters.  Delete, continue, abort? "
1170                    '((?d "Delete NUL characters")
1171                      (?c "Try to APPEND the message as is")
1172                      (?a "Abort")))))
1173       (cond
1174        ((eq choice ?a)
1175         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1176        ((eq choice ?c)
1177         data)
1178        (t
1179         (with-temp-buffer
1180           (insert data)
1181           (goto-char (point-min))
1182           (while (search-forward "\000" nil t)
1183             (replace-match "" t t))
1184           (buffer-string)))))))
1185
1186 (defun nnimap-ok-p (value)
1187   (and (consp value)
1188        (consp (car value))
1189        (equal (caar value) "OK")))
1190
1191 (defun nnimap-find-uid-response (name list)
1192   (let ((result (car (last (nnimap-find-response-element name list)))))
1193     (and result
1194          (string-to-number result))))
1195
1196 (defun nnimap-find-response-element (name list)
1197   (let (result)
1198     (dolist (elem list)
1199       (when (and (consp elem)
1200                  (equal name (car elem)))
1201         (setq result elem)))
1202     result))
1203
1204 (deffoo nnimap-request-replace-article (article group buffer)
1205   (setq group (nnimap-decode-gnus-group group))
1206   (let (group-art)
1207     (when (and (nnimap-change-group group)
1208                ;; Put the article into the group.
1209                (with-current-buffer buffer
1210                  (setq group-art
1211                        (nnimap-request-accept-article group nil t))))
1212       (nnimap-delete-article (list article))
1213       ;; Return the new article number.
1214       (cdr group-art))))
1215
1216 (defun nnimap-add-cr ()
1217   (goto-char (point-min))
1218   (while (re-search-forward "\r?\n" nil t)
1219     (replace-match "\r\n" t t)))
1220
1221 (defun nnimap-get-groups ()
1222   (erase-buffer)
1223   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1224         groups)
1225     (nnimap-wait-for-response sequence)
1226     (subst-char-in-region (point-min) (point-max)
1227                           ?\\ ?% t)
1228     (goto-char (point-min))
1229     (nnimap-unfold-quoted-lines)
1230     (goto-char (point-min))
1231     (while (search-forward "* LIST " nil t)
1232       (let ((flags (read (current-buffer)))
1233             (separator (read (current-buffer)))
1234             (group (read (current-buffer))))
1235         (unless (member '%NoSelect flags)
1236           (push (utf7-decode (if (stringp group)
1237                                  group
1238                                (format "%s" group)) t)
1239                 groups))))
1240     (nreverse groups)))
1241
1242 (defun nnimap-get-responses (sequences)
1243   (let (responses)
1244     (dolist (sequence sequences)
1245       (goto-char (point-min))
1246       (when (re-search-forward (format "^%d " sequence) nil t)
1247         (push (list sequence (nnimap-parse-response))
1248               responses)))
1249     responses))
1250
1251 (deffoo nnimap-request-list (&optional server)
1252   (when (nnimap-change-group nil server)
1253     (with-current-buffer nntp-server-buffer
1254       (erase-buffer)
1255       (let ((groups
1256              (with-current-buffer (nnimap-buffer)
1257                (nnimap-get-groups)))
1258             sequences responses)
1259         (when groups
1260           (with-current-buffer (nnimap-buffer)
1261             (setf (nnimap-group nnimap-object) nil)
1262             (dolist (group groups)
1263               (setf (nnimap-examined nnimap-object) group)
1264               (push (list (nnimap-send-command "EXAMINE %S"
1265                                                (utf7-encode group t))
1266                           group)
1267                     sequences))
1268             (nnimap-wait-for-response (caar sequences))
1269             (setq responses
1270                   (nnimap-get-responses (mapcar #'car sequences))))
1271           (dolist (response responses)
1272             (let* ((sequence (car response))
1273                    (response (cadr response))
1274                    (group (cadr (assoc sequence sequences)))
1275                    (egroup (encode-coding-string group 'utf-8)))
1276               (when (and group
1277                          (equal (caar response) "OK"))
1278                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1279                       highest exists)
1280                   (dolist (elem response)
1281                     (when (equal (cadr elem) "EXISTS")
1282                       (setq exists (string-to-number (car elem)))))
1283                   (when uidnext
1284                     (setq highest (1- (string-to-number (car uidnext)))))
1285                   (cond
1286                    ((null highest)
1287                     (insert (format "%S 0 1 y\n" egroup)))
1288                    ((zerop exists)
1289                     ;; Empty group.
1290                     (insert (format "%S %d %d y\n" egroup
1291                                     highest (1+ highest))))
1292                    (t
1293                     ;; Return the widest possible range.
1294                     (insert (format "%S %d 1 y\n" egroup
1295                                     (or highest exists)))))))))
1296           t)))))
1297
1298 (deffoo nnimap-request-newgroups (date &optional server)
1299   (when (nnimap-change-group nil server)
1300     (with-current-buffer nntp-server-buffer
1301       (erase-buffer)
1302       (dolist (group (with-current-buffer (nnimap-buffer)
1303                        (nnimap-get-groups)))
1304         (unless (assoc group nnimap-current-infos)
1305           ;; Insert dummy numbers here -- they don't matter.
1306           (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1307       t)))
1308
1309 (deffoo nnimap-retrieve-group-data-early (server infos)
1310   (when (and (nnimap-change-group nil server)
1311              infos)
1312     (with-current-buffer (nnimap-buffer)
1313       (erase-buffer)
1314       (setf (nnimap-group nnimap-object) nil)
1315       (setf (nnimap-initial-resync nnimap-object) 0)
1316       (let ((qresyncp (nnimap-capability "QRESYNC"))
1317             params groups sequences active uidvalidity modseq group
1318             unexist)
1319         ;; Go through the infos and gather the data needed to know
1320         ;; what and how to request the data.
1321         (dolist (info infos)
1322           (setq params (gnus-info-params info)
1323                 group (nnimap-decode-gnus-group
1324                        (gnus-group-real-name (gnus-info-group info)))
1325                 active (cdr (assq 'active params))
1326                 unexist (assq 'unexist (gnus-info-marks info))
1327                 uidvalidity (cdr (assq 'uidvalidity params))
1328                 modseq (cdr (assq 'modseq params)))
1329           (setf (nnimap-examined nnimap-object) group)
1330           (if (and qresyncp
1331                    uidvalidity
1332                    active
1333                    modseq
1334                    unexist)
1335               (push
1336                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1337                                           (utf7-encode group t)
1338                                           (nnimap-quirk "QRESYNC")
1339                                           uidvalidity modseq)
1340                      'qresync
1341                      nil group 'qresync)
1342                sequences)
1343             (let ((command
1344                    (if uidvalidity
1345                        "EXAMINE"
1346                      ;; If we don't have a UIDVALIDITY, then this is
1347                      ;; the first time we've seen the group, so we
1348                      ;; have to do a SELECT (which is slower than an
1349                      ;; examine), but will tell us whether the group
1350                      ;; is read-only or not.
1351                      "SELECT"))
1352                   start)
1353               (if (and active uidvalidity unexist)
1354                   ;; Fetch the last 100 flags.
1355                   (setq start (max 1 (- (cdr active) 100)))
1356                 (incf (nnimap-initial-resync nnimap-object))
1357                 (setq start 1))
1358               (push (list (nnimap-send-command "%s %S" command
1359                                                (utf7-encode group t))
1360                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1361                           start group command)
1362                     sequences))))
1363         sequences))))
1364
1365 (defun nnimap-quirk (command)
1366   (let ((quirk (assoc command nnimap-quirks)))
1367     ;; If this server is of a type that matches a quirk, then return
1368     ;; the "quirked" command instead of the proper one.
1369     (if (or (null quirk)
1370             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1371         command
1372       (nth 2 quirk))))
1373
1374 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1375   (when (and sequences
1376              (nnimap-change-group nil server t)
1377              ;; Check that the process is still alive.
1378              (get-buffer-process (nnimap-buffer))
1379              (memq (process-status (get-buffer-process (nnimap-buffer)))
1380                    '(open run)))
1381     (with-current-buffer (nnimap-buffer)
1382       ;; Wait for the final data to trickle in.
1383       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1384                                           (caar sequences)
1385                                         (cadar sequences))
1386                                       t)
1387         ;; Now we should have most of the data we need, no matter
1388         ;; whether we're QRESYNCING, fetching all the flags from
1389         ;; scratch, or just fetching the last 100 flags per group.
1390         (nnimap-update-infos (nnimap-flags-to-marks
1391                               (nnimap-parse-flags
1392                                (nreverse sequences)))
1393                              infos)
1394         ;; Finally, just return something resembling an active file in
1395         ;; the nntp buffer, so that the agent can save the info, too.
1396         (with-current-buffer nntp-server-buffer
1397           (erase-buffer)
1398           (dolist (info infos)
1399             (let* ((group (gnus-info-group info))
1400                    (active (gnus-active group)))
1401               (when active
1402                 (insert (format "%S %d %d y\n"
1403                                 (decode-coding-string
1404                                  (gnus-group-real-name group) 'utf-8)
1405                                 (cdr active)
1406                                 (car active)))))))))))
1407
1408 (defun nnimap-update-infos (flags infos)
1409   (dolist (info infos)
1410     (let* ((group (nnimap-decode-gnus-group
1411                    (gnus-group-real-name (gnus-info-group info))))
1412            (marks (cdr (assoc group flags))))
1413       (when marks
1414         (nnimap-update-info info marks)))))
1415
1416 (defun nnimap-update-info (info marks)
1417   (destructuring-bind (existing flags high low uidnext start-article
1418                                 permanent-flags uidvalidity
1419                                 vanished highestmodseq) marks
1420     (cond
1421      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1422      ;; completely empty groups.
1423      ((and (not existing)
1424            (not uidnext))
1425       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1426         (when active
1427           (gnus-set-active (gnus-info-group info) active))))
1428      ;; We have a mismatch between the old and new UIDVALIDITY
1429      ;; identifiers, so we have to re-request the group info (the next
1430      ;; time).  This virtually never happens.
1431      ((let ((old-uidvalidity
1432              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1433         (and old-uidvalidity
1434              (not (equal old-uidvalidity uidvalidity))
1435              (or (not start-article)
1436                  (> start-article 1))))
1437       (gnus-group-remove-parameter info 'uidvalidity)
1438       (gnus-group-remove-parameter info 'modseq))
1439      ;; We have the data needed to update.
1440      (t
1441       (let* ((group (gnus-info-group info))
1442              (completep (and start-article
1443                              (= start-article 1)))
1444              (active (or (gnus-active group)
1445                          (cdr (assq 'active (gnus-info-params info))))))
1446         (when uidnext
1447           (setq high (1- uidnext)))
1448         ;; First set the active ranges based on high/low.
1449         (if (or completep
1450                 (not (gnus-active group)))
1451             (gnus-set-active group
1452                              (cond
1453                               (active
1454                                (cons (min (or low (car active))
1455                                           (car active))
1456                                      (max (or high (cdr active))
1457                                           (cdr active))))
1458                               ((and low high)
1459                                (cons low high))
1460                               (uidnext
1461                                ;; No articles in this group.
1462                                (cons uidnext (1- uidnext)))
1463                               (start-article
1464                                (cons start-article (1- start-article)))
1465                               (t
1466                                ;; No articles and no uidnext.
1467                                nil)))
1468           (gnus-set-active group
1469                            (cons (car active)
1470                                  (or high (1- uidnext)))))
1471         ;; See whether this is a read-only group.
1472         (unless (eq permanent-flags 'not-scanned)
1473           (gnus-group-set-parameter
1474            info 'permanent-flags
1475            (and (or (memq '%* permanent-flags)
1476                     (memq '%Seen permanent-flags))
1477                 permanent-flags)))
1478         ;; Update marks and read articles if this isn't a
1479         ;; read-only IMAP group.
1480         (when (setq permanent-flags
1481                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1482           (if (and highestmodseq
1483                    (not start-article))
1484               ;; We've gotten the data by QRESYNCing.
1485               (nnimap-update-qresync-info
1486                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1487             ;; Do normal non-QRESYNC flag updates.
1488             ;; Update the list of read articles.
1489             (let* ((unread
1490                     (gnus-compress-sequence
1491                      (gnus-set-difference
1492                       (gnus-set-difference
1493                        existing
1494                        (gnus-sorted-union
1495                         (cdr (assoc '%Seen flags))
1496                         (cdr (assoc '%Deleted flags))))
1497                       (cdr (assoc '%Flagged flags)))))
1498                    (read (gnus-range-difference
1499                           (cons start-article high) unread)))
1500               (when (> start-article 1)
1501                 (setq read
1502                       (gnus-range-nconcat
1503                        (if (> start-article 1)
1504                            (gnus-sorted-range-intersection
1505                             (cons 1 (1- start-article))
1506                             (gnus-info-read info))
1507                          (gnus-info-read info))
1508                        read)))
1509               (when (or (not (listp permanent-flags))
1510                         (memq '%Seen permanent-flags))
1511                 (gnus-info-set-read info read))
1512               ;; Update the marks.
1513               (setq marks (gnus-info-marks info))
1514               (dolist (type (cdr nnimap-mark-alist))
1515                 (when (or (not (listp permanent-flags))
1516                           (memq (car (assoc (caddr type) flags))
1517                                 permanent-flags)
1518                           (memq '%* permanent-flags))
1519                   (let ((old-marks (assoc (car type) marks))
1520                         (new-marks
1521                          (gnus-compress-sequence
1522                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1523                                    (assoc (intern (cadr type) obarray) flags)
1524                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1525                     (setq marks (delq old-marks marks))
1526                     (pop old-marks)
1527                     (when (and old-marks
1528                                (> start-article 1))
1529                       (setq old-marks (gnus-range-difference
1530                                        old-marks
1531                                        (cons start-article high)))
1532                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1533                     (when new-marks
1534                       (push (cons (car type) new-marks) marks)))))
1535               ;; Keep track of non-existing articles.
1536               (let* ((old-unexists (assq 'unexist marks))
1537                      (active (gnus-active group))
1538                      (unexists
1539                       (if completep
1540                           (gnus-range-difference
1541                            active
1542                            (gnus-compress-sequence existing))
1543                         (gnus-add-to-range
1544                          (cdr old-unexists)
1545                          (gnus-list-range-difference
1546                           existing (gnus-active group))))))
1547                 (when (> (car active) 1)
1548                   (setq unexists (gnus-range-add
1549                                   (cons 1 (1- (car active)))
1550                                   unexists)))
1551                 (if old-unexists
1552                     (setcdr old-unexists unexists)
1553                   (push (cons 'unexist unexists) marks)))
1554               (gnus-info-set-marks info marks t))))
1555         ;; Tell Gnus whether there are any \Recent messages in any of
1556         ;; the groups.
1557         (let ((recent (cdr (assoc '%Recent flags))))
1558           (when (and active
1559                      recent
1560                      (> (car (last recent)) (cdr active)))
1561             (push (list (cons (gnus-group-real-name group) 0))
1562                   nnmail-split-history)))
1563         ;; Note the active level for the next run-through.
1564         (gnus-group-set-parameter info 'active (gnus-active group))
1565         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1566         (gnus-group-set-parameter info 'modseq highestmodseq)
1567         (nnimap-store-info info (gnus-active group)))))))
1568
1569 (defun nnimap-update-qresync-info (info existing vanished flags)
1570   ;; Add all the vanished articles to the list of read articles.
1571   (gnus-info-set-read
1572    info
1573    (gnus-add-to-range
1574     (gnus-add-to-range
1575      (gnus-range-add (gnus-info-read info)
1576                      vanished)
1577      (cdr (assq '%Flagged flags)))
1578     (cdr (assq '%Seen flags))))
1579   (let ((marks (gnus-info-marks info)))
1580     (dolist (type (cdr nnimap-mark-alist))
1581       (let ((ticks (assoc (car type) marks))
1582             (new-marks
1583              (cdr (or (assoc (caddr type) flags) ; %Flagged
1584                       (assoc (intern (cadr type) obarray) flags)
1585                       (assoc (cadr type) flags))))) ; "\Flagged"
1586         (setq marks (delq ticks marks))
1587         (pop ticks)
1588         ;; Add the new marks we got.
1589         (setq ticks (gnus-add-to-range ticks new-marks))
1590         ;; Remove the marks from messages that don't have them.
1591         (setq ticks (gnus-remove-from-range
1592                      ticks
1593                      (gnus-compress-sequence
1594                       (gnus-sorted-complement existing new-marks))))
1595         (when ticks
1596           (push (cons (car type) ticks) marks)))
1597       (gnus-info-set-marks info marks t))
1598     ;; Add vanished to the list of unexisting articles.
1599     (when vanished
1600       (let* ((old-unexists (assq 'unexist marks))
1601              (unexists (gnus-range-add (cdr old-unexists) vanished)))
1602         (if old-unexists
1603             (setcdr old-unexists unexists)
1604           (push (cons 'unexist unexists) marks)))
1605       (gnus-info-set-marks info marks t))))
1606
1607 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1608   (if (zerop (length irange))
1609       nil
1610     (let ((result nil))
1611       (dolist (elem (split-string irange ","))
1612         (push
1613          (if (string-match ":" elem)
1614              (let ((numbers (split-string elem ":")))
1615                (cons (string-to-number (car numbers))
1616                      (string-to-number (cadr numbers))))
1617            (string-to-number elem))
1618          result))
1619       (nreverse result))))
1620
1621 (defun nnimap-store-info (info active)
1622   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1623          (entry (assoc group nnimap-current-infos)))
1624     (if entry
1625         (setcdr entry (list info active))
1626       (push (list group info active) nnimap-current-infos))))
1627
1628 (defun nnimap-flags-to-marks (groups)
1629   (let (data group totalp uidnext articles start-article mark permanent-flags
1630              uidvalidity vanished highestmodseq)
1631     (dolist (elem groups)
1632       (setq group (car elem)
1633             uidnext (nth 1 elem)
1634             start-article (nth 2 elem)
1635             permanent-flags (nth 3 elem)
1636             uidvalidity (nth 4 elem)
1637             vanished (nth 5 elem)
1638             highestmodseq (nth 6 elem)
1639             articles (nthcdr 7 elem))
1640       (let ((high (caar articles))
1641             marks low existing)
1642         (dolist (article articles)
1643           (setq low (car article))
1644           (push (car article) existing)
1645           (dolist (flag (cdr article))
1646             (setq mark (assoc flag marks))
1647             (if (not mark)
1648                 (push (list flag (car article)) marks)
1649               (setcdr mark (cons (car article) (cdr mark))))))
1650         (push (list group existing marks high low uidnext start-article
1651                     permanent-flags uidvalidity vanished highestmodseq)
1652               data)))
1653     data))
1654
1655 (defun nnimap-parse-flags (sequences)
1656   (goto-char (point-min))
1657   ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1658   ;; read it.
1659   (subst-char-in-region (point-min) (point-max)
1660                         ?\\ ?% t)
1661   ;; Remove any MODSEQ entries in the buffer, because they may contain
1662   ;; numbers that are too large for 32-bit Emacsen.
1663   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1664     (replace-match "" t t))
1665   (goto-char (point-min))
1666   (let (start end articles groups uidnext elems permanent-flags
1667               uidvalidity vanished highestmodseq)
1668     (dolist (elem sequences)
1669       (destructuring-bind (group-sequence flag-sequence totalp group command)
1670           elem
1671         (setq start (point))
1672         (when (and
1673                ;; The EXAMINE was successful.
1674                (search-forward (format "\n%d OK " group-sequence) nil t)
1675                (progn
1676                  (forward-line 1)
1677                  (setq end (point))
1678                  (goto-char start)
1679                  (setq permanent-flags
1680                        (if (equal command "SELECT")
1681                            (and (search-forward "PERMANENTFLAGS "
1682                                                 (or end (point-min)) t)
1683                                 (read (current-buffer)))
1684                          'not-scanned))
1685                  (goto-char start)
1686                  (setq uidnext
1687                        (and (search-forward "UIDNEXT "
1688                                             (or end (point-min)) t)
1689                             (read (current-buffer))))
1690                  (goto-char start)
1691                  (setq uidvalidity
1692                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1693                                                (or end (point-min)) t)
1694                             ;; Store UIDVALIDITY as a string, as it's
1695                             ;; too big for 32-bit Emacsen, usually.
1696                             (match-string 1)))
1697                  (goto-char start)
1698                  (setq vanished
1699                        (and (eq flag-sequence 'qresync)
1700                             (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1701                                                (or end (point-min)) t)
1702                             (match-string 1)))
1703                  (goto-char start)
1704                  (setq highestmodseq
1705                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1706                                             (or end (point-min)) t)
1707                             (match-string 1)))
1708                  (goto-char end)
1709                  (forward-line -1))
1710                ;; The UID FETCH FLAGS was successful.
1711                (or (eq flag-sequence 'qresync)
1712                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1713           (if (eq flag-sequence 'qresync)
1714               (progn
1715                 (goto-char start)
1716                 (setq start end))
1717             (setq start (point))
1718             (goto-char end))
1719           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1720             (let ((p (point)))
1721               (setq elems (read (current-buffer)))
1722               (push (cons (cadr (memq 'UID elems))
1723                           (cadr (memq 'FLAGS elems)))
1724                     articles)))
1725           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1726                              vanished highestmodseq)
1727                        articles)
1728                 groups)
1729           (if (eq flag-sequence 'qresync)
1730               (goto-char end)
1731             (setq end (point)))
1732           (setq articles nil))))
1733     groups))
1734
1735 (defun nnimap-find-process-buffer (buffer)
1736   (cadr (assoc buffer nnimap-connection-alist)))
1737
1738 (deffoo nnimap-request-post (&optional server)
1739   (setq nnimap-status-string "Read-only server")
1740   nil)
1741
1742 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1743 (declare-function gnus-fetch-headers "gnus-sum"
1744                   (articles &optional limit force-new dependencies))
1745
1746 (autoload 'nnir-search-thread "nnir")
1747
1748 (deffoo nnimap-request-thread (header &optional group server)
1749   (when group
1750     (setq group (nnimap-decode-gnus-group group)))
1751   (if gnus-refer-thread-use-nnir
1752       (nnir-search-thread header)
1753     (when (nnimap-change-group group server)
1754       (let* ((cmd (nnimap-make-thread-query header))
1755              (result (with-current-buffer (nnimap-buffer)
1756                        (nnimap-command  "UID SEARCH %s" cmd))))
1757         (when result
1758           (gnus-fetch-headers
1759            (and (car result)
1760                 (delete 0 (mapcar #'string-to-number
1761                                   (cdr (assoc "SEARCH" (cdr result))))))
1762            nil t))))))
1763
1764 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1765   "Change group to GROUP if non-nil.
1766 If SERVER is set, check that server is connected, otherwise retry
1767 to reconnect, unless NO-RECONNECT is set to t.  Return nil if
1768 unsuccessful in connecting.
1769 If GROUP is nil, return t.
1770 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1771 Return the server's response to the SELECT or EXAMINE command."
1772   (let ((open-result t))
1773     (when (and server
1774                (not (nnimap-server-opened server)))
1775       (setq open-result (nnimap-open-server server nil no-reconnect)))
1776     (cond
1777      ((not open-result)
1778       nil)
1779      ((not group)
1780       t)
1781      (t
1782       (with-current-buffer (nnimap-buffer)
1783         (let ((result (nnimap-command "%s %S"
1784                                       (if read-only
1785                                           "EXAMINE"
1786                                         "SELECT")
1787                                       (utf7-encode group t))))
1788           (when (car result)
1789             (setf (nnimap-group nnimap-object) group
1790                   (nnimap-select-result nnimap-object) result)
1791             result)))))))
1792
1793 (defun nnimap-find-connection (buffer)
1794   "Find the connection delivering to BUFFER."
1795   (let ((entry (assoc buffer nnimap-connection-alist)))
1796     (when entry
1797       (if (and (buffer-name (cadr entry))
1798                (get-buffer-process (cadr entry))
1799                (memq (process-status (get-buffer-process (cadr entry)))
1800                      '(open run)))
1801           (get-buffer-process (cadr entry))
1802         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1803         nil))))
1804
1805 (defvar nnimap-sequence 0)
1806
1807 (defun nnimap-send-command (&rest args)
1808   (setf (nnimap-last-command-time nnimap-object) (current-time))
1809   (process-send-string
1810    (get-buffer-process (current-buffer))
1811    (nnimap-log-command
1812     (format "%d %s%s\n"
1813             (incf nnimap-sequence)
1814             (apply #'format args)
1815             (if (nnimap-newlinep nnimap-object)
1816                 ""
1817               "\r"))))
1818   ;; Some servers apparently can't have many outstanding
1819   ;; commands, so throttle them.
1820   (unless nnimap-streaming
1821     (nnimap-wait-for-response nnimap-sequence))
1822   nnimap-sequence)
1823
1824 (defvar nnimap-record-commands nil
1825   "If non-nil, log commands to the \"*imap log*\" buffer.")
1826
1827 (defun nnimap-log-buffer ()
1828   (let ((name "*imap log*"))
1829     (or (get-buffer name)
1830         (with-current-buffer (get-buffer-create name)
1831           (when (boundp 'window-point-insertion-type)
1832             (make-local-variable 'window-point-insertion-type)
1833             (setq window-point-insertion-type t))
1834           (current-buffer)))))
1835
1836 (defun nnimap-log-command (command)
1837   (when nnimap-record-commands
1838     (with-current-buffer (nnimap-log-buffer)
1839       (goto-char (point-max))
1840       (insert (format-time-string "%H:%M:%S")
1841               " [" nnimap-address "] "
1842               (if nnimap-inhibit-logging
1843                   "(inhibited)\n"
1844                 command))))
1845   command)
1846
1847 (defun nnimap-command (&rest args)
1848   (erase-buffer)
1849   (let* ((sequence (apply #'nnimap-send-command args))
1850          (response (nnimap-get-response sequence)))
1851     (if (equal (caar response) "OK")
1852         (cons t response)
1853       (nnheader-report 'nnimap "%s"
1854                        (mapconcat (lambda (a)
1855                                     (format "%s" a))
1856                                   (car response) " "))
1857       nil)))
1858
1859 (defun nnimap-get-response (sequence)
1860   (nnimap-wait-for-response sequence)
1861   (nnimap-parse-response))
1862
1863 (defun nnimap-wait-for-connection (&optional regexp)
1864   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1865
1866 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1867   (let ((process (get-buffer-process (current-buffer))))
1868     (goto-char (point-min))
1869     (while (and (memq (process-status process)
1870                       '(open run))
1871                 (not (re-search-forward regexp nil t)))
1872       (nnheader-accept-process-output process)
1873       (goto-char (point-min)))
1874     (forward-line -1)
1875     (and (looking-at (or response-regexp regexp))
1876          (match-string 1))))
1877
1878 (defun nnimap-wait-for-response (sequence &optional messagep)
1879   (let ((process (get-buffer-process (current-buffer)))
1880         openp)
1881     (condition-case nil
1882         (progn
1883           (goto-char (point-max))
1884           (while (and (setq openp (memq (process-status process)
1885                                         '(open run)))
1886                       (progn
1887                         ;; Skip past any "*" lines that the server has
1888                         ;; output.
1889                         (while (and (not (bobp))
1890                                     (progn
1891                                       (forward-line -1)
1892                                       (looking-at "\\*\\|[0-9]+ OK NOOP"))))
1893                         (not (looking-at (format "%d .*\n" sequence)))))
1894             (when messagep
1895               (nnheader-message-maybe
1896                7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1897                nnimap-address
1898                (if (not (zerop (nnimap-initial-resync nnimap-object)))
1899                    (format " (initial sync of %d group%s; please wait)"
1900                            (nnimap-initial-resync nnimap-object)
1901                            (if (= (nnimap-initial-resync nnimap-object) 1)
1902                                ""
1903                              "s"))
1904                  "")))
1905             (nnheader-accept-process-output process)
1906             (goto-char (point-max)))
1907           (setf (nnimap-initial-resync nnimap-object) 0)
1908           openp)
1909       (quit
1910        (when debug-on-quit
1911          (debug "Quit"))
1912        ;; The user hit C-g while we were waiting: kill the process, in case
1913        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1914        ;; NAT routers).
1915        (delete-process process)
1916        nil))))
1917
1918 (defun nnimap-parse-response ()
1919   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1920         result)
1921     (dolist (line lines)
1922       (push (cdr (nnimap-parse-line line)) result))
1923     ;; Return the OK/error code first, and then all the "continuation
1924     ;; lines" afterwards.
1925     (cons (pop result)
1926           (nreverse result))))
1927
1928 ;; Parse an IMAP response line lightly.  They look like
1929 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1930 ;; the lines into a list of strings and lists of string.
1931 (defun nnimap-parse-line (line)
1932   (let (char result)
1933     (with-temp-buffer
1934       (mm-disable-multibyte)
1935       (insert line)
1936       (goto-char (point-min))
1937       (while (not (eobp))
1938         (if (eql (setq char (following-char)) ? )
1939             (forward-char 1)
1940           (push
1941            (cond
1942             ((eql char ?\[)
1943              (split-string
1944               (buffer-substring
1945                (1+ (point))
1946                (if (search-forward "]" (line-end-position) 'move)
1947                    (1- (point))
1948                  (point)))))
1949             ((eql char ?\()
1950              (split-string
1951               (buffer-substring
1952                (1+ (point))
1953                (if (search-forward ")" (line-end-position) 'move)
1954                    (1- (point))
1955                  (point)))))
1956             ((eql char ?\")
1957              (forward-char 1)
1958              (buffer-substring
1959               (point)
1960               (1- (or (search-forward "\"" (line-end-position) 'move)
1961                       (point)))))
1962             (t
1963              (buffer-substring (point) (if (search-forward " " nil t)
1964                                            (1- (point))
1965                                          (goto-char (point-max))))))
1966            result)))
1967       (nreverse result))))
1968
1969 (defun nnimap-last-response-string ()
1970   (save-excursion
1971     (forward-line 1)
1972     (let ((end (point)))
1973       (forward-line -1)
1974       (when (not (bobp))
1975         (forward-line -1)
1976         (while (and (not (bobp))
1977                     (eql (following-char) ?*))
1978           (forward-line -1))
1979         (unless (eql (following-char) ?*)
1980           (forward-line 1)))
1981       (buffer-substring (point) end))))
1982
1983 (defvar nnimap-incoming-split-list nil)
1984
1985 (defun nnimap-fetch-inbox (articles)
1986   (erase-buffer)
1987   (nnimap-wait-for-response
1988    (nnimap-send-command
1989     "UID FETCH %s %s"
1990     (nnimap-article-ranges articles)
1991     (format "(UID %s%s)"
1992             (format
1993              (if (nnimap-ver4-p)
1994                  "BODY.PEEK"
1995                "RFC822.PEEK"))
1996             (cond
1997              (nnimap-split-download-body-default
1998               "[]")
1999              ((nnimap-ver4-p)
2000               "[HEADER]")
2001              (t
2002               "[1]"))))
2003    t))
2004
2005 (defun nnimap-split-incoming-mail ()
2006   (with-current-buffer (nnimap-buffer)
2007     (let ((nnimap-incoming-split-list nil)
2008           (nnmail-split-methods
2009            (cond
2010             ((eq nnimap-split-methods 'default)
2011              nnmail-split-methods)
2012             (nnimap-split-methods
2013              nnimap-split-methods)
2014             (nnimap-split-fancy
2015              'nnmail-split-fancy)))
2016           (nnmail-split-fancy (or nnimap-split-fancy
2017                                   nnmail-split-fancy))
2018           (nnmail-inhibit-default-split-group t)
2019           (groups (nnimap-get-groups))
2020           new-articles)
2021       (erase-buffer)
2022       (nnimap-command "SELECT %S" nnimap-inbox)
2023       (setf (nnimap-group nnimap-object) nnimap-inbox)
2024       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2025       (when new-articles
2026         (nnimap-fetch-inbox new-articles)
2027         (nnimap-transform-split-mail)
2028         (nnheader-ms-strip-cr)
2029         (nnmail-cache-open)
2030         (nnmail-split-incoming (current-buffer)
2031                                #'nnimap-save-mail-spec
2032                                nil nil
2033                                #'nnimap-dummy-active-number
2034                                #'nnimap-save-mail-spec)
2035         (when nnimap-incoming-split-list
2036           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2037                 sequences junk-articles)
2038             ;; Create any groups that doesn't already exist on the
2039             ;; server first.
2040             (dolist (spec specs)
2041               (when (and (not (member (car spec) groups))
2042                          (not (eq (car spec) 'junk)))
2043                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2044             ;; Then copy over all the messages.
2045             (erase-buffer)
2046             (dolist (spec specs)
2047               (let ((group (car spec))
2048                     (ranges (cdr spec)))
2049                 (if (eq group 'junk)
2050                     (setq junk-articles ranges)
2051                   (push (list (nnimap-send-command
2052                                "UID COPY %s %S"
2053                                (nnimap-article-ranges ranges)
2054                                (utf7-encode group t))
2055                               ranges)
2056                         sequences))))
2057             ;; Wait for the last COPY response...
2058             (when sequences
2059               (nnimap-wait-for-response (caar sequences))
2060               ;; And then mark the successful copy actions as deleted,
2061               ;; and possibly expunge them.
2062               (nnimap-mark-and-expunge-incoming
2063                (nnimap-parse-copied-articles sequences)))
2064             (nnimap-mark-and-expunge-incoming junk-articles)))))))
2065
2066 (defun nnimap-mark-and-expunge-incoming (range)
2067   (when range
2068     (setq range (nnimap-article-ranges range))
2069     (erase-buffer)
2070     (let ((sequence
2071            (nnimap-send-command
2072             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2073       (cond
2074        ;; If the server supports it, we now delete the message we have
2075        ;; just copied over.
2076        ((nnimap-capability "UIDPLUS")
2077         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2078        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2079        ;; user has configured it.
2080        (nnimap-expunge
2081         (setq sequence (nnimap-send-command "EXPUNGE"))))
2082       (nnimap-wait-for-response sequence))))
2083
2084 (defun nnimap-parse-copied-articles (sequences)
2085   (let (sequence copied range)
2086     (goto-char (point-min))
2087     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2088       (setq sequence (string-to-number (match-string 1)))
2089       (when (setq range (cadr (assq sequence sequences)))
2090         (push (gnus-uncompress-range range) copied)))
2091     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2092
2093 (defun nnimap-new-articles (flags)
2094   (let (new)
2095     (dolist (elem flags)
2096       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2097                                       (cdr elem))
2098         (push (car elem) new)))
2099     (gnus-compress-sequence (nreverse new))))
2100
2101 (defun nnimap-make-split-specs (list)
2102   (let ((specs nil)
2103         entry)
2104     (dolist (elem list)
2105       (destructuring-bind (article spec) elem
2106         (dolist (group (delete nil (mapcar #'car spec)))
2107           (unless (setq entry (assoc group specs))
2108             (push (setq entry (list group)) specs))
2109           (setcdr entry (cons article (cdr entry))))))
2110     (dolist (entry specs)
2111       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2112     specs))
2113
2114 (defun nnimap-transform-split-mail ()
2115   (goto-char (point-min))
2116   (let (article bytes)
2117     (block nil
2118       (while (not (eobp))
2119         (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2120           (delete-region (point) (progn (forward-line 1) (point)))
2121           (when (eobp)
2122             (return)))
2123         (setq article (match-string 1)
2124               bytes (nnimap-get-length))
2125         (delete-region (line-beginning-position) (line-end-position))
2126         ;; Insert MMDF separator, and a way to remember what this
2127         ;; article UID is.
2128         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2129         (forward-char (1+ bytes))
2130         (setq bytes (nnimap-get-length))
2131         (delete-region (line-beginning-position) (line-end-position))
2132         ;; There's a body; skip past that.
2133         (when bytes
2134           (forward-char (1+ bytes))
2135           (delete-region (line-beginning-position) (line-end-position)))))))
2136
2137 (defun nnimap-dummy-active-number (group &optional server)
2138   1)
2139
2140 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2141   (let (article)
2142     (goto-char (point-min))
2143     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2144         (error "Invalid nnimap mail")
2145       (setq article (string-to-number (match-string 1))))
2146     (push (list article
2147                 (if (eq group-art 'junk)
2148                     (list (cons 'junk 1))
2149                   group-art))
2150           nnimap-incoming-split-list)))
2151
2152 (defun nnimap-make-thread-query (header)
2153   (let* ((id  (mail-header-id header))
2154          (refs (split-string
2155                 (or (mail-header-references header)
2156                     "")))
2157          (value
2158           (format
2159            "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2160            id id)))
2161     (dolist (refid refs value)
2162       (setq value (format
2163                    "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2164                    refid refid value)))))
2165
2166
2167 (provide 'nnimap)
2168
2169 ;;; nnimap.el ends here