Fixups when displaying certain attachments
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2015 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         (when (or (not dont-check)
796                   (not (setq active
797                              (nth 2 (assoc group nnimap-current-infos)))))
798           (let ((sequences (nnimap-retrieve-group-data-early
799                             server (list info))))
800             (nnimap-finish-retrieve-group-infos server (list info) sequences
801                                                 t)
802             (setq active (nth 2 (assoc group nnimap-current-infos)))))
803         (insert (format "211 %d %d %d %S\n"
804                         (- (cdr active) (car active))
805                         (car active)
806                         (cdr active)
807                         group))
808         t))))
809
810 (deffoo nnimap-request-scan-group (group &optional server info)
811   (setq group (nnimap-decode-gnus-group group))
812   (let (marks high low)
813     (with-current-buffer (nnimap-buffer)
814       (erase-buffer)
815       (let ((group-sequence
816              (nnimap-send-command "SELECT %S" (utf7-encode group t)))
817             (flag-sequence
818              (nnimap-send-command "UID FETCH 1:* FLAGS")))
819         (setf (nnimap-group nnimap-object) group)
820         (nnimap-wait-for-response flag-sequence)
821         (setq marks
822               (nnimap-flags-to-marks
823                (nnimap-parse-flags
824                 (list (list group-sequence flag-sequence
825                             1 group "SELECT")))))
826         (when (and info
827                    marks)
828           (nnimap-update-infos marks (list info))
829           (nnimap-store-info info (gnus-active (gnus-info-group info))))
830         (goto-char (point-max))
831         (let ((uidnext (nth 5 (car marks))))
832           (setq high (or (if uidnext
833                              (1- uidnext)
834                            (nth 3 (car marks)))
835                          0)
836                 low (or (nth 4 (car marks)) uidnext 1)))))
837     (with-current-buffer nntp-server-buffer
838       (erase-buffer)
839       (insert
840        (format
841         "211 %d %d %d %S\n" (1+ (- high low)) low high group))
842       t)))
843
844 (deffoo nnimap-request-create-group (group &optional server args)
845   (setq group (nnimap-decode-gnus-group group))
846   (when (nnimap-change-group nil server)
847     (with-current-buffer (nnimap-buffer)
848       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
849
850 (deffoo nnimap-request-delete-group (group &optional force server)
851   (setq group (nnimap-decode-gnus-group group))
852   (when (nnimap-change-group nil server)
853     (with-current-buffer (nnimap-buffer)
854       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
855
856 (deffoo nnimap-request-rename-group (group new-name &optional server)
857   (setq group (nnimap-decode-gnus-group group))
858   (when (nnimap-change-group nil server)
859     (with-current-buffer (nnimap-buffer)
860       (nnimap-unselect-group)
861       (car (nnimap-command "RENAME %S %S"
862                            (utf7-encode group t) (utf7-encode new-name t))))))
863
864 (defun nnimap-unselect-group ()
865   ;; Make sure we don't have this group open read/write by asking
866   ;; to examine a mailbox that doesn't exist.  This seems to be
867   ;; the only way that allows us to reliably go back to unselected
868   ;; state on Courier.
869   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
870
871 (deffoo nnimap-request-expunge-group (group &optional server)
872   (setq group (nnimap-decode-gnus-group group))
873   (when (nnimap-change-group group server)
874     (with-current-buffer (nnimap-buffer)
875       (car (nnimap-command "EXPUNGE")))))
876
877 (defun nnimap-get-flags (spec)
878   (let ((articles nil)
879         elems end)
880     (with-current-buffer (nnimap-buffer)
881       (erase-buffer)
882       (nnimap-wait-for-response (nnimap-send-command
883                                  "UID FETCH %s FLAGS" spec))
884       (setq end (point))
885       (subst-char-in-region (point-min) (point-max)
886                             ?\\ ?% t)
887       (goto-char (point-min))
888       (while (search-forward " FETCH " end t)
889         (setq elems (read (current-buffer)))
890         (push (cons (cadr (memq 'UID elems))
891                     (cadr (memq 'FLAGS elems)))
892               articles)))
893     (nreverse articles)))
894
895 (deffoo nnimap-close-group (group &optional server)
896   t)
897
898 (deffoo nnimap-request-move-article (article group server accept-form
899                                              &optional last internal-move-group)
900   (setq group (nnimap-decode-gnus-group group))
901   (when internal-move-group
902     (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
903   (with-temp-buffer
904     (mm-disable-multibyte)
905     (when (funcall (if internal-move-group
906                        'nnimap-request-head
907                      'nnimap-request-article)
908                    article group server (current-buffer))
909       ;; If the move is internal (on the same server), just do it the easy
910       ;; way.
911       (let ((message-id (message-field-value "message-id")))
912         (if internal-move-group
913             (let ((result
914                    (with-current-buffer (nnimap-buffer)
915                      (nnimap-command "UID COPY %d %S"
916                                      article
917                                      (utf7-encode internal-move-group t)))))
918               (when (car result)
919                 (nnimap-delete-article article)
920                 (cons internal-move-group
921                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
922                           (nnimap-find-article-by-message-id
923                            internal-move-group server message-id
924                            nnimap-request-articles-find-limit)))))
925           ;; Move the article to a different method.
926           (let ((result (eval accept-form)))
927             (when result
928               (nnimap-change-group group server)
929               (nnimap-delete-article article)
930               result)))))))
931
932 (deffoo nnimap-request-expire-articles (articles group &optional server force)
933   (setq group (nnimap-decode-gnus-group group))
934   (cond
935    ((null articles)
936     nil)
937    ((not (nnimap-change-group group server))
938     articles)
939    ((and force
940          (eq nnmail-expiry-target 'delete))
941     (unless (nnimap-delete-article (gnus-compress-sequence articles))
942       (nnheader-message 7 "Article marked for deletion, but not expunged."))
943     nil)
944    (t
945     (let ((deletable-articles
946            (if (or force
947                    (eq nnmail-expiry-wait 'immediate))
948                articles
949              (gnus-sorted-intersection
950               articles
951               (nnimap-find-expired-articles group)))))
952       (if (null deletable-articles)
953           articles
954         (if (eq nnmail-expiry-target 'delete)
955             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
956           (setq deletable-articles
957                 (nnimap-process-expiry-targets
958                  deletable-articles group server)))
959         ;; Return the articles we didn't delete.
960         (gnus-sorted-complement articles deletable-articles))))))
961
962 (defun nnimap-process-expiry-targets (articles group server)
963   (let ((deleted-articles nil))
964     (cond
965      ;; shortcut further processing if we're going to delete the articles
966      ((eq nnmail-expiry-target 'delete)
967       (setq deleted-articles articles)
968       t)
969      ;; or just move them to another folder on the same IMAP server
970      ((and (not (functionp nnmail-expiry-target))
971            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
972                               (gnus-server-to-method
973                                (format "nnimap:%s" server))))
974       (and (nnimap-change-group group server)
975            (with-current-buffer (nnimap-buffer)
976              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
977              (nnimap-command
978               "UID COPY %s %S"
979               (nnimap-article-ranges (gnus-compress-sequence articles))
980               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
981              (setq deleted-articles articles)))
982       t)
983      (t
984       (dolist (article articles)
985         (let ((target nnmail-expiry-target))
986           (with-temp-buffer
987             (mm-disable-multibyte)
988             (when (nnimap-request-article article group server (current-buffer))
989               (when (functionp target)
990                 (setq target (funcall target group)))
991               (if (and target
992                        (not (eq target 'delete)))
993                   (if (or (gnus-request-group target t)
994                           (gnus-request-create-group target))
995                       (progn
996                         (nnmail-expiry-target-group target group)
997                         (nnheader-message 7 "Expiring article %s:%d to %s"
998                                           group article target))
999                     (setq target nil))
1000                 (nnheader-message 7 "Expiring article %s:%d" group article))
1001               (when target
1002                 (push article deleted-articles))))))
1003       (setq deleted-articles (nreverse deleted-articles))))
1004     ;; Change back to the current group again.
1005     (nnimap-change-group group server)
1006     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
1007     deleted-articles))
1008
1009 (defun nnimap-find-expired-articles (group)
1010   (let ((cutoff (nnmail-expired-article-p group nil nil)))
1011     (with-current-buffer (nnimap-buffer)
1012       (let ((result
1013              (nnimap-command
1014               "UID SEARCH SENTBEFORE %s"
1015               (format-time-string
1016                (format "%%d-%s-%%Y"
1017                        (upcase
1018                         (car (rassoc (nth 4 (decode-time cutoff))
1019                                      parse-time-months))))
1020                cutoff))))
1021         (and (car result)
1022              (delete 0 (mapcar #'string-to-number
1023                                (cdr (assoc "SEARCH" (cdr result))))))))))
1024
1025
1026 (defun nnimap-find-article-by-message-id (group server message-id
1027                                                 &optional limit)
1028   "Search for message with MESSAGE-ID in GROUP from SERVER.
1029 If LIMIT, first try to limit the search to the N last articles."
1030   (with-current-buffer (nnimap-buffer)
1031     (erase-buffer)
1032     (let* ((change-group-result (nnimap-change-group group server nil t))
1033            (number-of-article
1034             (and (listp change-group-result)
1035                  (catch 'found
1036                    (dolist (result (cdr change-group-result))
1037                      (when (equal "EXISTS" (cadr result))
1038                        (throw 'found (car result)))))))
1039            (sequence
1040             (nnimap-send-command
1041              "UID SEARCH%s HEADER Message-Id %S"
1042              (if (and limit number-of-article)
1043                  ;; The -1 is because IMAP message
1044                  ;; numbers are one-based rather than
1045                  ;; zero-based.
1046                  (format " %s:*" (- (string-to-number number-of-article)
1047                                     limit -1))
1048                "")
1049              message-id)))
1050       (when (nnimap-wait-for-response sequence)
1051         (let ((article (car (last (cdr (assoc "SEARCH"
1052                                               (nnimap-parse-response)))))))
1053           (if article
1054               (string-to-number article)
1055             (when (and limit number-of-article)
1056               (nnimap-find-article-by-message-id group server message-id))))))))
1057
1058 (defun nnimap-delete-article (articles)
1059   (with-current-buffer (nnimap-buffer)
1060     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1061                     (nnimap-article-ranges articles))
1062     (cond
1063      ((nnimap-capability "UIDPLUS")
1064       (nnimap-command "UID EXPUNGE %s"
1065                       (nnimap-article-ranges articles))
1066       t)
1067      (nnimap-expunge
1068       (nnimap-command "EXPUNGE")
1069       t)
1070      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1071                                 "server doesn't support UIDPLUS, so we won't "
1072                                 "delete this article now"))))))
1073
1074 (deffoo nnimap-request-scan (&optional group server)
1075   (when group
1076     (setq group (nnimap-decode-gnus-group group)))
1077   (when (and (nnimap-change-group nil server)
1078              nnimap-inbox
1079              nnimap-split-methods)
1080     (nnheader-message 7 "nnimap %s splitting mail..." server)
1081     (if (listp nnimap-inbox)
1082        (dolist (nnimap-inbox nnimap-inbox)
1083          (nnimap-split-incoming-mail))
1084       (nnimap-split-incoming-mail))
1085     (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1086
1087 (defun nnimap-marks-to-flags (marks)
1088   (let (flags flag)
1089     (dolist (mark marks)
1090       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1091         (push flag flags)))
1092     flags))
1093
1094 (deffoo nnimap-request-update-group-status (group status &optional server)
1095   (setq group (nnimap-decode-gnus-group group))
1096   (when (nnimap-change-group nil server)
1097     (let ((command (assoc
1098                     status
1099                     '((subscribe "SUBSCRIBE")
1100                       (unsubscribe "UNSUBSCRIBE")))))
1101       (when command
1102         (with-current-buffer (nnimap-buffer)
1103           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1104
1105 (deffoo nnimap-request-set-mark (group actions &optional server)
1106   (setq group (nnimap-decode-gnus-group group))
1107   (when (nnimap-change-group group server)
1108     (let (sequence)
1109       (with-current-buffer (nnimap-buffer)
1110         (erase-buffer)
1111         ;; Just send all the STORE commands without waiting for
1112         ;; response.  If they're successful, they're successful.
1113         (dolist (action actions)
1114           (destructuring-bind (range action marks) action
1115             (let ((flags (nnimap-marks-to-flags marks)))
1116               (when flags
1117                 (setq sequence (nnimap-send-command
1118                                 "UID STORE %s %sFLAGS.SILENT (%s)"
1119                                 (nnimap-article-ranges range)
1120                                 (cond
1121                                  ((eq action 'del) "-")
1122                                  ((eq action 'add) "+")
1123                                  ((eq action 'set) ""))
1124                                 (mapconcat #'identity flags " ")))))))
1125         ;; Wait for the last command to complete to avoid later
1126         ;; synchronization problems with the stream.
1127         (when sequence
1128           (nnimap-wait-for-response sequence))))))
1129
1130 (deffoo nnimap-request-accept-article (group &optional server last)
1131   (unless group
1132     ;; We're respooling.  Find out where mail splitting would place
1133     ;; this article.
1134     (setq group
1135           (caar
1136            (nnmail-article-group
1137             ;; We don't really care about the article number, because
1138             ;; that's determined by the IMAP server later.  So just
1139             ;; return the group name.
1140             `(lambda (group)
1141                (list (list group)))))))
1142   (setq group (nnimap-decode-gnus-group group))
1143   (when (nnimap-change-group nil server)
1144     (nnmail-check-syntax)
1145     (let ((message-id (message-field-value "message-id"))
1146           sequence message)
1147       (nnimap-add-cr)
1148       (setq message (buffer-substring-no-properties (point-min) (point-max)))
1149       (with-current-buffer (nnimap-buffer)
1150         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1151                                 message))
1152           ;; If we have this group open read-only, then unselect it
1153           ;; before appending to it.
1154           (when (equal (nnimap-examined nnimap-object) group)
1155             (nnimap-unselect-group))
1156           (erase-buffer)
1157           (setq sequence (nnimap-send-command
1158                           "APPEND %S {%d}" (utf7-encode group t)
1159                           (length message)))
1160           (unless nnimap-streaming
1161             (nnimap-wait-for-connection "^[+]"))
1162           (process-send-string (get-buffer-process (current-buffer)) message)
1163           (process-send-string (get-buffer-process (current-buffer))
1164                                (if (nnimap-newlinep nnimap-object)
1165                                    "\n"
1166                                  "\r\n"))
1167           (let ((result (nnimap-get-response sequence)))
1168             (if (not (nnimap-ok-p result))
1169                 (progn
1170                   (nnheader-report 'nnimap "%s" result)
1171                   nil)
1172               (cons group
1173                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1174                         (nnimap-find-article-by-message-id
1175                          group server message-id
1176                          nnimap-request-articles-find-limit))))))))))
1177
1178 (defun nnimap-process-quirk (greeting-match type data)
1179   (when (and (nnimap-greeting nnimap-object)
1180              (string-match greeting-match (nnimap-greeting nnimap-object))
1181              (eq type 'append)
1182              (string-match "\000" data))
1183     (let ((choice (gnus-multiple-choice
1184                    "Message contains NUL characters.  Delete, continue, abort? "
1185                    '((?d "Delete NUL characters")
1186                      (?c "Try to APPEND the message as is")
1187                      (?a "Abort")))))
1188       (cond
1189        ((eq choice ?a)
1190         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1191        ((eq choice ?c)
1192         data)
1193        (t
1194         (with-temp-buffer
1195           (insert data)
1196           (goto-char (point-min))
1197           (while (search-forward "\000" nil t)
1198             (replace-match "" t t))
1199           (buffer-string)))))))
1200
1201 (defun nnimap-ok-p (value)
1202   (and (consp value)
1203        (consp (car value))
1204        (equal (caar value) "OK")))
1205
1206 (defun nnimap-find-uid-response (name list)
1207   (let ((result (car (last (nnimap-find-response-element name list)))))
1208     (and result
1209          (string-to-number result))))
1210
1211 (defun nnimap-find-response-element (name list)
1212   (let (result)
1213     (dolist (elem list)
1214       (when (and (consp elem)
1215                  (equal name (car elem)))
1216         (setq result elem)))
1217     result))
1218
1219 (deffoo nnimap-request-replace-article (article group buffer)
1220   (setq group (nnimap-decode-gnus-group group))
1221   (let (group-art)
1222     (when (and (nnimap-change-group group)
1223                ;; Put the article into the group.
1224                (with-current-buffer buffer
1225                  (setq group-art
1226                        (nnimap-request-accept-article group nil t))))
1227       (nnimap-delete-article (list article))
1228       ;; Return the new article number.
1229       (cdr group-art))))
1230
1231 (defun nnimap-add-cr ()
1232   (goto-char (point-min))
1233   (while (re-search-forward "\r?\n" nil t)
1234     (replace-match "\r\n" t t)))
1235
1236 (defun nnimap-get-groups ()
1237   (erase-buffer)
1238   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1239         groups)
1240     (nnimap-wait-for-response sequence)
1241     (subst-char-in-region (point-min) (point-max)
1242                           ?\\ ?% t)
1243     (goto-char (point-min))
1244     (nnimap-unfold-quoted-lines)
1245     (goto-char (point-min))
1246     (while (search-forward "* LIST " nil t)
1247       (let ((flags (read (current-buffer)))
1248             (separator (read (current-buffer)))
1249             (group (read (current-buffer))))
1250         (unless (member '%NoSelect flags)
1251           (push (utf7-decode (if (stringp group)
1252                                  group
1253                                (format "%s" group)) t)
1254                 groups))))
1255     (nreverse groups)))
1256
1257 (defun nnimap-get-responses (sequences)
1258   (let (responses)
1259     (dolist (sequence sequences)
1260       (goto-char (point-min))
1261       (when (re-search-forward (format "^%d " sequence) nil t)
1262         (push (list sequence (nnimap-parse-response))
1263               responses)))
1264     responses))
1265
1266 (deffoo nnimap-request-list (&optional server)
1267   (when (nnimap-change-group nil server)
1268     (with-current-buffer nntp-server-buffer
1269       (erase-buffer)
1270       (let ((groups
1271              (with-current-buffer (nnimap-buffer)
1272                (nnimap-get-groups)))
1273             sequences responses)
1274         (when groups
1275           (with-current-buffer (nnimap-buffer)
1276             (setf (nnimap-group nnimap-object) nil)
1277             (dolist (group groups)
1278               (setf (nnimap-examined nnimap-object) group)
1279               (push (list (nnimap-send-command "EXAMINE %S"
1280                                                (utf7-encode group t))
1281                           group)
1282                     sequences))
1283             (nnimap-wait-for-response (caar sequences))
1284             (setq responses
1285                   (nnimap-get-responses (mapcar #'car sequences))))
1286           (dolist (response responses)
1287             (let* ((sequence (car response))
1288                    (response (cadr response))
1289                    (group (cadr (assoc sequence sequences)))
1290                    (egroup (encode-coding-string group 'utf-8)))
1291               (when (and group
1292                          (equal (caar response) "OK"))
1293                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1294                       highest exists)
1295                   (dolist (elem response)
1296                     (when (equal (cadr elem) "EXISTS")
1297                       (setq exists (string-to-number (car elem)))))
1298                   (when uidnext
1299                     (setq highest (1- (string-to-number (car uidnext)))))
1300                   (cond
1301                    ((null highest)
1302                     (insert (format "%S 0 1 y\n" egroup)))
1303                    ((zerop exists)
1304                     ;; Empty group.
1305                     (insert (format "%S %d %d y\n" egroup
1306                                     highest (1+ highest))))
1307                    (t
1308                     ;; Return the widest possible range.
1309                     (insert (format "%S %d 1 y\n" egroup
1310                                     (or highest exists)))))))))
1311           t)))))
1312
1313 (deffoo nnimap-request-newgroups (date &optional server)
1314   (when (nnimap-change-group nil server)
1315     (with-current-buffer nntp-server-buffer
1316       (erase-buffer)
1317       (dolist (group (with-current-buffer (nnimap-buffer)
1318                        (nnimap-get-groups)))
1319         (unless (assoc group nnimap-current-infos)
1320           ;; Insert dummy numbers here -- they don't matter.
1321           (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1322       t)))
1323
1324 (deffoo nnimap-retrieve-group-data-early (server infos)
1325   (when (and (nnimap-change-group nil server)
1326              infos)
1327     (with-current-buffer (nnimap-buffer)
1328       (erase-buffer)
1329       (setf (nnimap-group nnimap-object) nil)
1330       (setf (nnimap-initial-resync nnimap-object) 0)
1331       (let ((qresyncp (nnimap-capability "QRESYNC"))
1332             params groups sequences active uidvalidity modseq group
1333             unexist)
1334         ;; Go through the infos and gather the data needed to know
1335         ;; what and how to request the data.
1336         (dolist (info infos)
1337           (setq params (gnus-info-params info)
1338                 group (nnimap-decode-gnus-group
1339                        (gnus-group-real-name (gnus-info-group info)))
1340                 active (cdr (assq 'active params))
1341                 unexist (assq 'unexist (gnus-info-marks info))
1342                 uidvalidity (cdr (assq 'uidvalidity params))
1343                 modseq (cdr (assq 'modseq params)))
1344           (setf (nnimap-examined nnimap-object) group)
1345           (if (and qresyncp
1346                    uidvalidity
1347                    active
1348                    modseq
1349                    unexist)
1350               (push
1351                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1352                                           (utf7-encode group t)
1353                                           (nnimap-quirk "QRESYNC")
1354                                           uidvalidity modseq)
1355                      'qresync
1356                      nil group 'qresync)
1357                sequences)
1358             (let ((command
1359                    (if uidvalidity
1360                        "EXAMINE"
1361                      ;; If we don't have a UIDVALIDITY, then this is
1362                      ;; the first time we've seen the group, so we
1363                      ;; have to do a SELECT (which is slower than an
1364                      ;; examine), but will tell us whether the group
1365                      ;; is read-only or not.
1366                      "SELECT"))
1367                   start)
1368               (if (and active uidvalidity unexist)
1369                   ;; Fetch the last 100 flags.
1370                   (setq start (max 1 (- (cdr active) 100)))
1371                 (incf (nnimap-initial-resync nnimap-object))
1372                 (setq start 1))
1373               (push (list (nnimap-send-command "%s %S" command
1374                                                (utf7-encode group t))
1375                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1376                           start group command)
1377                     sequences))))
1378         sequences))))
1379
1380 (defun nnimap-quirk (command)
1381   (let ((quirk (assoc command nnimap-quirks)))
1382     ;; If this server is of a type that matches a quirk, then return
1383     ;; the "quirked" command instead of the proper one.
1384     (if (or (null quirk)
1385             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1386         command
1387       (nth 2 quirk))))
1388
1389 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences
1390                                                    &optional dont-insert)
1391   (when (and sequences
1392              (nnimap-change-group nil server t)
1393              ;; Check that the process is still alive.
1394              (get-buffer-process (nnimap-buffer))
1395              (memq (process-status (get-buffer-process (nnimap-buffer)))
1396                    '(open run)))
1397     (with-current-buffer (nnimap-buffer)
1398       ;; Wait for the final data to trickle in.
1399       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1400                                           (caar sequences)
1401                                         (cadar sequences))
1402                                       t)
1403         ;; Now we should have most of the data we need, no matter
1404         ;; whether we're QRESYNCING, fetching all the flags from
1405         ;; scratch, or just fetching the last 100 flags per group.
1406         (nnimap-update-infos (nnimap-flags-to-marks
1407                               (nnimap-parse-flags
1408                                (nreverse sequences)))
1409                              infos)
1410         (unless dont-insert
1411           ;; Finally, just return something resembling an active file in
1412           ;; the nntp buffer, so that the agent can save the info, too.
1413           (with-current-buffer nntp-server-buffer
1414             (erase-buffer)
1415             (dolist (info infos)
1416               (let* ((group (gnus-info-group info))
1417                      (active (gnus-active group)))
1418                 (when active
1419                   (insert (format "%S %d %d y\n"
1420                                   (decode-coding-string
1421                                    (gnus-group-real-name group) 'utf-8)
1422                                   (cdr active)
1423                                   (car active))))))))))))
1424
1425 (defun nnimap-update-infos (flags infos)
1426   (dolist (info infos)
1427     (let* ((group (nnimap-decode-gnus-group
1428                    (gnus-group-real-name (gnus-info-group info))))
1429            (marks (cdr (assoc group flags))))
1430       (when marks
1431         (nnimap-update-info info marks)))))
1432
1433 (defun nnimap-update-info (info marks)
1434   (destructuring-bind (existing flags high low uidnext start-article
1435                                 permanent-flags uidvalidity
1436                                 vanished highestmodseq) marks
1437     (cond
1438      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1439      ;; completely empty groups.
1440      ((and (not existing)
1441            (not uidnext))
1442       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1443         (when active
1444           (gnus-set-active (gnus-info-group info) active))))
1445      ;; We have a mismatch between the old and new UIDVALIDITY
1446      ;; identifiers, so we have to re-request the group info (the next
1447      ;; time).  This virtually never happens.
1448      ((let ((old-uidvalidity
1449              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1450         (and old-uidvalidity
1451              (not (equal old-uidvalidity uidvalidity))
1452              (or (not start-article)
1453                  (> start-article 1))))
1454       (gnus-group-remove-parameter info 'uidvalidity)
1455       (gnus-group-remove-parameter info 'modseq))
1456      ;; We have the data needed to update.
1457      (t
1458       (let* ((group (gnus-info-group info))
1459              (completep (and start-article
1460                              (= start-article 1)))
1461              (active (or (gnus-active group)
1462                          (cdr (assq 'active (gnus-info-params info))))))
1463         (when uidnext
1464           (setq high (1- uidnext)))
1465         ;; First set the active ranges based on high/low.
1466         (if (or completep
1467                 (not (gnus-active group)))
1468             (gnus-set-active group
1469                              (cond
1470                               (active
1471                                (cons (min (or low (car active))
1472                                           (car active))
1473                                      (max (or high (cdr active))
1474                                           (cdr active))))
1475                               ((and low high)
1476                                (cons low high))
1477                               (uidnext
1478                                ;; No articles in this group.
1479                                (cons uidnext (1- uidnext)))
1480                               (start-article
1481                                (cons start-article (1- start-article)))
1482                               (t
1483                                ;; No articles and no uidnext.
1484                                nil)))
1485           (gnus-set-active group
1486                            (cons (car active)
1487                                  (or high (1- uidnext)))))
1488         ;; See whether this is a read-only group.
1489         (unless (eq permanent-flags 'not-scanned)
1490           (gnus-group-set-parameter
1491            info 'permanent-flags
1492            (and (or (memq '%* permanent-flags)
1493                     (memq '%Seen permanent-flags))
1494                 permanent-flags)))
1495         ;; Update marks and read articles if this isn't a
1496         ;; read-only IMAP group.
1497         (when (setq permanent-flags
1498                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1499           (if (and highestmodseq
1500                    (not start-article))
1501               ;; We've gotten the data by QRESYNCing.
1502               (nnimap-update-qresync-info
1503                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1504             ;; Do normal non-QRESYNC flag updates.
1505             ;; Update the list of read articles.
1506             (let* ((unread
1507                     (gnus-compress-sequence
1508                      (gnus-set-difference
1509                       (gnus-set-difference
1510                        existing
1511                        (gnus-sorted-union
1512                         (cdr (assoc '%Seen flags))
1513                         (cdr (assoc '%Deleted flags))))
1514                       (cdr (assoc '%Flagged flags)))))
1515                    (read (gnus-range-difference
1516                           (cons start-article high) unread)))
1517               (when (> start-article 1)
1518                 (setq read
1519                       (gnus-range-nconcat
1520                        (if (> start-article 1)
1521                            (gnus-sorted-range-intersection
1522                             (cons 1 (1- start-article))
1523                             (gnus-info-read info))
1524                          (gnus-info-read info))
1525                        read)))
1526               (when (or (not (listp permanent-flags))
1527                         (memq '%Seen permanent-flags))
1528                 (gnus-info-set-read info read))
1529               ;; Update the marks.
1530               (setq marks (gnus-info-marks info))
1531               (dolist (type (cdr nnimap-mark-alist))
1532                 (when (or (not (listp permanent-flags))
1533                           (memq (car (assoc (caddr type) flags))
1534                                 permanent-flags)
1535                           (memq '%* permanent-flags))
1536                   (let ((old-marks (assoc (car type) marks))
1537                         (new-marks
1538                          (gnus-compress-sequence
1539                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1540                                    (assoc (intern (cadr type) obarray) flags)
1541                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1542                     (setq marks (delq old-marks marks))
1543                     (pop old-marks)
1544                     (when (and old-marks
1545                                (> start-article 1))
1546                       (setq old-marks (gnus-range-difference
1547                                        old-marks
1548                                        (cons start-article high)))
1549                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1550                     (when new-marks
1551                       (push (cons (car type) new-marks) marks)))))
1552               ;; Keep track of non-existing articles.
1553               (let* ((old-unexists (assq 'unexist marks))
1554                      (active (gnus-active group))
1555                      (unexists
1556                       (if completep
1557                           (gnus-range-difference
1558                            active
1559                            (gnus-compress-sequence existing))
1560                         (gnus-add-to-range
1561                          (cdr old-unexists)
1562                          (gnus-list-range-difference
1563                           existing (gnus-active group))))))
1564                 (when (> (car active) 1)
1565                   (setq unexists (gnus-range-add
1566                                   (cons 1 (1- (car active)))
1567                                   unexists)))
1568                 (if old-unexists
1569                     (setcdr old-unexists unexists)
1570                   (push (cons 'unexist unexists) marks)))
1571               (gnus-info-set-marks info marks t))))
1572         ;; Tell Gnus whether there are any \Recent messages in any of
1573         ;; the groups.
1574         (let ((recent (cdr (assoc '%Recent flags))))
1575           (when (and active
1576                      recent
1577                      (> (car (last recent)) (cdr active)))
1578             (push (list (cons (gnus-group-real-name group) 0))
1579                   nnmail-split-history)))
1580         ;; Note the active level for the next run-through.
1581         (gnus-group-set-parameter info 'active (gnus-active group))
1582         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1583         (gnus-group-set-parameter info 'modseq highestmodseq)
1584         (nnimap-store-info info (gnus-active group)))))))
1585
1586 (defun nnimap-update-qresync-info (info existing vanished flags)
1587   ;; Add all the vanished articles to the list of read articles.
1588   (gnus-info-set-read
1589    info
1590    (gnus-add-to-range
1591     (gnus-add-to-range
1592      (gnus-range-add (gnus-info-read info)
1593                      vanished)
1594      (cdr (assq '%Flagged flags)))
1595     (cdr (assq '%Seen flags))))
1596   (let ((marks (gnus-info-marks info)))
1597     (dolist (type (cdr nnimap-mark-alist))
1598       (let ((ticks (assoc (car type) marks))
1599             (new-marks
1600              (cdr (or (assoc (caddr type) flags) ; %Flagged
1601                       (assoc (intern (cadr type) obarray) flags)
1602                       (assoc (cadr type) flags))))) ; "\Flagged"
1603         (setq marks (delq ticks marks))
1604         (pop ticks)
1605         ;; Add the new marks we got.
1606         (setq ticks (gnus-add-to-range ticks new-marks))
1607         ;; Remove the marks from messages that don't have them.
1608         (setq ticks (gnus-remove-from-range
1609                      ticks
1610                      (gnus-compress-sequence
1611                       (gnus-sorted-complement existing new-marks))))
1612         (when ticks
1613           (push (cons (car type) ticks) marks)))
1614       (gnus-info-set-marks info marks t))
1615     ;; Add vanished to the list of unexisting articles.
1616     (when vanished
1617       (let* ((old-unexists (assq 'unexist marks))
1618              (unexists (gnus-range-add (cdr old-unexists) vanished)))
1619         (if old-unexists
1620             (setcdr old-unexists unexists)
1621           (push (cons 'unexist unexists) marks)))
1622       (gnus-info-set-marks info marks t))))
1623
1624 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1625   (if (zerop (length irange))
1626       nil
1627     (let ((result nil))
1628       (dolist (elem (split-string irange ","))
1629         (push
1630          (if (string-match ":" elem)
1631              (let ((numbers (split-string elem ":")))
1632                (cons (string-to-number (car numbers))
1633                      (string-to-number (cadr numbers))))
1634            (string-to-number elem))
1635          result))
1636       (nreverse result))))
1637
1638 (defun nnimap-store-info (info active)
1639   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1640          (entry (assoc group nnimap-current-infos)))
1641     (if entry
1642         (setcdr entry (list info active))
1643       (push (list group info active) nnimap-current-infos))))
1644
1645 (defun nnimap-flags-to-marks (groups)
1646   (let (data group totalp uidnext articles start-article mark permanent-flags
1647              uidvalidity vanished highestmodseq)
1648     (dolist (elem groups)
1649       (setq group (car elem)
1650             uidnext (nth 1 elem)
1651             start-article (nth 2 elem)
1652             permanent-flags (nth 3 elem)
1653             uidvalidity (nth 4 elem)
1654             vanished (nth 5 elem)
1655             highestmodseq (nth 6 elem)
1656             articles (nthcdr 7 elem))
1657       (let ((high (caar articles))
1658             marks low existing)
1659         (dolist (article articles)
1660           (setq low (car article))
1661           (push (car article) existing)
1662           (dolist (flag (cdr article))
1663             (setq mark (assoc flag marks))
1664             (if (not mark)
1665                 (push (list flag (car article)) marks)
1666               (setcdr mark (cons (car article) (cdr mark))))))
1667         (push (list group existing marks high low uidnext start-article
1668                     permanent-flags uidvalidity vanished highestmodseq)
1669               data)))
1670     data))
1671
1672 (defun nnimap-parse-flags (sequences)
1673   (goto-char (point-min))
1674   ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1675   ;; read it.
1676   (subst-char-in-region (point-min) (point-max)
1677                         ?\\ ?% t)
1678   ;; Remove any MODSEQ entries in the buffer, because they may contain
1679   ;; numbers that are too large for 32-bit Emacsen.
1680   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1681     (replace-match "" t t))
1682   (goto-char (point-min))
1683   (let (start end articles groups uidnext elems permanent-flags
1684               uidvalidity vanished highestmodseq)
1685     (dolist (elem sequences)
1686       (destructuring-bind (group-sequence flag-sequence totalp group command)
1687           elem
1688         (setq start (point))
1689         (when (and
1690                ;; The EXAMINE was successful.
1691                (search-forward (format "\n%d OK " group-sequence) nil t)
1692                (progn
1693                  (forward-line 1)
1694                  (setq end (point))
1695                  (goto-char start)
1696                  (setq permanent-flags
1697                        (if (equal command "SELECT")
1698                            (and (search-forward "PERMANENTFLAGS "
1699                                                 (or end (point-min)) t)
1700                                 (read (current-buffer)))
1701                          'not-scanned))
1702                  (goto-char start)
1703                  (setq uidnext
1704                        (and (search-forward "UIDNEXT "
1705                                             (or end (point-min)) t)
1706                             (read (current-buffer))))
1707                  (goto-char start)
1708                  (setq uidvalidity
1709                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1710                                                (or end (point-min)) t)
1711                             ;; Store UIDVALIDITY as a string, as it's
1712                             ;; too big for 32-bit Emacsen, usually.
1713                             (match-string 1)))
1714                  (goto-char start)
1715                  (setq vanished
1716                        (and (eq flag-sequence 'qresync)
1717                             (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1718                                                (or end (point-min)) t)
1719                             (match-string 1)))
1720                  (goto-char start)
1721                  (setq highestmodseq
1722                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1723                                             (or end (point-min)) t)
1724                             (match-string 1)))
1725                  (goto-char end)
1726                  (forward-line -1))
1727                ;; The UID FETCH FLAGS was successful.
1728                (or (eq flag-sequence 'qresync)
1729                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1730           (if (eq flag-sequence 'qresync)
1731               (progn
1732                 (goto-char start)
1733                 (setq start end))
1734             (setq start (point))
1735             (goto-char end))
1736           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1737             (let ((p (point)))
1738               (setq elems (read (current-buffer)))
1739               (push (cons (cadr (memq 'UID elems))
1740                           (cadr (memq 'FLAGS elems)))
1741                     articles)))
1742           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1743                              vanished highestmodseq)
1744                        articles)
1745                 groups)
1746           (if (eq flag-sequence 'qresync)
1747               (goto-char end)
1748             (setq end (point)))
1749           (setq articles nil))))
1750     groups))
1751
1752 (defun nnimap-find-process-buffer (buffer)
1753   (cadr (assoc buffer nnimap-connection-alist)))
1754
1755 (deffoo nnimap-request-post (&optional server)
1756   (setq nnimap-status-string "Read-only server")
1757   nil)
1758
1759 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1760 (declare-function gnus-fetch-headers "gnus-sum"
1761                   (articles &optional limit force-new dependencies))
1762
1763 (autoload 'nnir-search-thread "nnir")
1764
1765 (deffoo nnimap-request-thread (header &optional group server)
1766   (when group
1767     (setq group (nnimap-decode-gnus-group group)))
1768   (if gnus-refer-thread-use-nnir
1769       (nnir-search-thread header)
1770     (when (nnimap-change-group group server)
1771       (let* ((cmd (nnimap-make-thread-query header))
1772              (result (with-current-buffer (nnimap-buffer)
1773                        (nnimap-command  "UID SEARCH %s" cmd))))
1774         (when result
1775           (gnus-fetch-headers
1776            (and (car result)
1777                 (delete 0 (mapcar #'string-to-number
1778                                   (cdr (assoc "SEARCH" (cdr result))))))
1779            nil t))))))
1780
1781 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1782   "Change group to GROUP if non-nil.
1783 If SERVER is set, check that server is connected, otherwise retry
1784 to reconnect, unless NO-RECONNECT is set to t.  Return nil if
1785 unsuccessful in connecting.
1786 If GROUP is nil, return t.
1787 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1788 Return the server's response to the SELECT or EXAMINE command."
1789   (let ((open-result t))
1790     (when (and server
1791                (not (nnimap-server-opened server)))
1792       (setq open-result (nnimap-open-server server nil no-reconnect)))
1793     (cond
1794      ((not open-result)
1795       nil)
1796      ((not group)
1797       t)
1798      (t
1799       (with-current-buffer (nnimap-buffer)
1800         (let ((result (nnimap-command "%s %S"
1801                                       (if read-only
1802                                           "EXAMINE"
1803                                         "SELECT")
1804                                       (utf7-encode group t))))
1805           (when (car result)
1806             (setf (nnimap-group nnimap-object) group
1807                   (nnimap-select-result nnimap-object) result)
1808             result)))))))
1809
1810 (defun nnimap-find-connection (buffer)
1811   "Find the connection delivering to BUFFER."
1812   (let ((entry (assoc buffer nnimap-connection-alist)))
1813     (when entry
1814       (if (and (buffer-name (cadr entry))
1815                (get-buffer-process (cadr entry))
1816                (memq (process-status (get-buffer-process (cadr entry)))
1817                      '(open run)))
1818           (get-buffer-process (cadr entry))
1819         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1820         nil))))
1821
1822 (defvar nnimap-sequence 0)
1823
1824 (defun nnimap-send-command (&rest args)
1825   (setf (nnimap-last-command-time nnimap-object) (current-time))
1826   (process-send-string
1827    (get-buffer-process (current-buffer))
1828    (nnimap-log-command
1829     (format "%d %s%s\n"
1830             (incf nnimap-sequence)
1831             (apply #'format args)
1832             (if (nnimap-newlinep nnimap-object)
1833                 ""
1834               "\r"))))
1835   ;; Some servers apparently can't have many outstanding
1836   ;; commands, so throttle them.
1837   (unless nnimap-streaming
1838     (nnimap-wait-for-response nnimap-sequence))
1839   nnimap-sequence)
1840
1841 (defvar nnimap-record-commands nil
1842   "If non-nil, log commands to the \"*imap log*\" buffer.")
1843
1844 (defun nnimap-log-buffer ()
1845   (let ((name "*imap log*"))
1846     (or (get-buffer name)
1847         (with-current-buffer (get-buffer-create name)
1848           (when (boundp 'window-point-insertion-type)
1849             (make-local-variable 'window-point-insertion-type)
1850             (setq window-point-insertion-type t))
1851           (current-buffer)))))
1852
1853 (defun nnimap-log-command (command)
1854   (when nnimap-record-commands
1855     (with-current-buffer (nnimap-log-buffer)
1856       (goto-char (point-max))
1857       (insert (format-time-string "%H:%M:%S")
1858               " [" nnimap-address "] "
1859               (if nnimap-inhibit-logging
1860                   "(inhibited)\n"
1861                 command))))
1862   command)
1863
1864 (defun nnimap-command (&rest args)
1865   (erase-buffer)
1866   (let* ((sequence (apply #'nnimap-send-command args))
1867          (response (nnimap-get-response sequence)))
1868     (if (equal (caar response) "OK")
1869         (cons t response)
1870       (nnheader-report 'nnimap "%s"
1871                        (mapconcat (lambda (a)
1872                                     (format "%s" a))
1873                                   (car response) " "))
1874       nil)))
1875
1876 (defun nnimap-get-response (sequence)
1877   (nnimap-wait-for-response sequence)
1878   (nnimap-parse-response))
1879
1880 (defun nnimap-wait-for-connection (&optional regexp)
1881   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1882
1883 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1884   (let ((process (get-buffer-process (current-buffer))))
1885     (goto-char (point-min))
1886     (while (and (memq (process-status process)
1887                       '(open run))
1888                 (not (re-search-forward regexp nil t)))
1889       (nnheader-accept-process-output process)
1890       (goto-char (point-min)))
1891     (forward-line -1)
1892     (and (looking-at (or response-regexp regexp))
1893          (match-string 1))))
1894
1895 (defun nnimap-wait-for-response (sequence &optional messagep)
1896   (let ((process (get-buffer-process (current-buffer)))
1897         openp)
1898     (condition-case nil
1899         (progn
1900           (goto-char (point-max))
1901           (while (and (setq openp (memq (process-status process)
1902                                         '(open run)))
1903                       (progn
1904                         ;; Skip past any "*" lines that the server has
1905                         ;; output.
1906                         (while (and (not (bobp))
1907                                     (progn
1908                                       (forward-line -1)
1909                                       (looking-at "\\*\\|[0-9]+ OK NOOP"))))
1910                         (not (looking-at (format "%d .*\n" sequence)))))
1911             (when messagep
1912               (nnheader-message-maybe
1913                7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1914                nnimap-address
1915                (if (not (zerop (nnimap-initial-resync nnimap-object)))
1916                    (format " (initial sync of %d group%s; please wait)"
1917                            (nnimap-initial-resync nnimap-object)
1918                            (if (= (nnimap-initial-resync nnimap-object) 1)
1919                                ""
1920                              "s"))
1921                  "")))
1922             (nnheader-accept-process-output process)
1923             (goto-char (point-max)))
1924           (setf (nnimap-initial-resync nnimap-object) 0)
1925           openp)
1926       (quit
1927        (when debug-on-quit
1928          (debug "Quit"))
1929        ;; The user hit C-g while we were waiting: kill the process, in case
1930        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1931        ;; NAT routers).
1932        (delete-process process)
1933        nil))))
1934
1935 (defun nnimap-parse-response ()
1936   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1937         result)
1938     (dolist (line lines)
1939       (push (cdr (nnimap-parse-line line)) result))
1940     ;; Return the OK/error code first, and then all the "continuation
1941     ;; lines" afterwards.
1942     (cons (pop result)
1943           (nreverse result))))
1944
1945 ;; Parse an IMAP response line lightly.  They look like
1946 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1947 ;; the lines into a list of strings and lists of string.
1948 (defun nnimap-parse-line (line)
1949   (let (char result)
1950     (with-temp-buffer
1951       (mm-disable-multibyte)
1952       (insert line)
1953       (goto-char (point-min))
1954       (while (not (eobp))
1955         (if (eql (setq char (following-char)) ? )
1956             (forward-char 1)
1957           (push
1958            (cond
1959             ((eql char ?\[)
1960              (split-string
1961               (buffer-substring
1962                (1+ (point))
1963                (if (search-forward "]" (line-end-position) 'move)
1964                    (1- (point))
1965                  (point)))))
1966             ((eql char ?\()
1967              (split-string
1968               (buffer-substring
1969                (1+ (point))
1970                (if (search-forward ")" (line-end-position) 'move)
1971                    (1- (point))
1972                  (point)))))
1973             ((eql char ?\")
1974              (forward-char 1)
1975              (buffer-substring
1976               (point)
1977               (1- (or (search-forward "\"" (line-end-position) 'move)
1978                       (point)))))
1979             (t
1980              (buffer-substring (point) (if (search-forward " " nil t)
1981                                            (1- (point))
1982                                          (goto-char (point-max))))))
1983            result)))
1984       (nreverse result))))
1985
1986 (defun nnimap-last-response-string ()
1987   (save-excursion
1988     (forward-line 1)
1989     (let ((end (point)))
1990       (forward-line -1)
1991       (when (not (bobp))
1992         (forward-line -1)
1993         (while (and (not (bobp))
1994                     (eql (following-char) ?*))
1995           (forward-line -1))
1996         (unless (eql (following-char) ?*)
1997           (forward-line 1)))
1998       (buffer-substring (point) end))))
1999
2000 (defvar nnimap-incoming-split-list nil)
2001
2002 (defun nnimap-fetch-inbox (articles)
2003   (erase-buffer)
2004   (nnimap-wait-for-response
2005    (nnimap-send-command
2006     "UID FETCH %s %s"
2007     (nnimap-article-ranges articles)
2008     (format "(UID %s%s)"
2009             (format
2010              (if (nnimap-ver4-p)
2011                  "BODY.PEEK"
2012                "RFC822.PEEK"))
2013             (cond
2014              (nnimap-split-download-body-default
2015               "[]")
2016              ((nnimap-ver4-p)
2017               "[HEADER]")
2018              (t
2019               "[1]"))))
2020    t))
2021
2022 (defun nnimap-split-incoming-mail ()
2023   (with-current-buffer (nnimap-buffer)
2024     (let ((nnimap-incoming-split-list nil)
2025           (nnmail-split-methods
2026            (cond
2027             ((eq nnimap-split-methods 'default)
2028              nnmail-split-methods)
2029             (nnimap-split-methods
2030              nnimap-split-methods)
2031             (nnimap-split-fancy
2032              'nnmail-split-fancy)))
2033           (nnmail-split-fancy (or nnimap-split-fancy
2034                                   nnmail-split-fancy))
2035           (nnmail-inhibit-default-split-group t)
2036           (groups (nnimap-get-groups))
2037           new-articles)
2038       (erase-buffer)
2039       (nnimap-command "SELECT %S" nnimap-inbox)
2040       (setf (nnimap-group nnimap-object) nnimap-inbox)
2041       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2042       (when new-articles
2043         (nnimap-fetch-inbox new-articles)
2044         (nnimap-transform-split-mail)
2045         (nnheader-ms-strip-cr)
2046         (nnmail-cache-open)
2047         (nnmail-split-incoming (current-buffer)
2048                                #'nnimap-save-mail-spec
2049                                nil nil
2050                                #'nnimap-dummy-active-number
2051                                #'nnimap-save-mail-spec)
2052         (when nnimap-incoming-split-list
2053           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2054                 sequences junk-articles)
2055             ;; Create any groups that doesn't already exist on the
2056             ;; server first.
2057             (dolist (spec specs)
2058               (when (and (not (member (car spec) groups))
2059                          (not (eq (car spec) 'junk)))
2060                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2061             ;; Then copy over all the messages.
2062             (erase-buffer)
2063             (dolist (spec specs)
2064               (let ((group (car spec))
2065                     (ranges (cdr spec)))
2066                 (if (eq group 'junk)
2067                     (setq junk-articles ranges)
2068                   (push (list (nnimap-send-command
2069                                "UID COPY %s %S"
2070                                (nnimap-article-ranges ranges)
2071                                (utf7-encode group t))
2072                               ranges)
2073                         sequences))))
2074             ;; Wait for the last COPY response...
2075             (when sequences
2076               (nnimap-wait-for-response (caar sequences))
2077               ;; And then mark the successful copy actions as deleted,
2078               ;; and possibly expunge them.
2079               (nnimap-mark-and-expunge-incoming
2080                (nnimap-parse-copied-articles sequences)))
2081             (nnimap-mark-and-expunge-incoming junk-articles)))))))
2082
2083 (defun nnimap-mark-and-expunge-incoming (range)
2084   (when range
2085     (setq range (nnimap-article-ranges range))
2086     (erase-buffer)
2087     (let ((sequence
2088            (nnimap-send-command
2089             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2090       (cond
2091        ;; If the server supports it, we now delete the message we have
2092        ;; just copied over.
2093        ((nnimap-capability "UIDPLUS")
2094         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2095        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2096        ;; user has configured it.
2097        (nnimap-expunge
2098         (setq sequence (nnimap-send-command "EXPUNGE"))))
2099       (nnimap-wait-for-response sequence))))
2100
2101 (defun nnimap-parse-copied-articles (sequences)
2102   (let (sequence copied range)
2103     (goto-char (point-min))
2104     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2105       (setq sequence (string-to-number (match-string 1)))
2106       (when (setq range (cadr (assq sequence sequences)))
2107         (push (gnus-uncompress-range range) copied)))
2108     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2109
2110 (defun nnimap-new-articles (flags)
2111   (let (new)
2112     (dolist (elem flags)
2113       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2114                                       (cdr elem))
2115         (push (car elem) new)))
2116     (gnus-compress-sequence (nreverse new))))
2117
2118 (defun nnimap-make-split-specs (list)
2119   (let ((specs nil)
2120         entry)
2121     (dolist (elem list)
2122       (destructuring-bind (article spec) elem
2123         (dolist (group (delete nil (mapcar #'car spec)))
2124           (unless (setq entry (assoc group specs))
2125             (push (setq entry (list group)) specs))
2126           (setcdr entry (cons article (cdr entry))))))
2127     (dolist (entry specs)
2128       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2129     specs))
2130
2131 (defun nnimap-transform-split-mail ()
2132   (goto-char (point-min))
2133   (let (article bytes)
2134     (block nil
2135       (while (not (eobp))
2136         (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2137           (delete-region (point) (progn (forward-line 1) (point)))
2138           (when (eobp)
2139             (return)))
2140         (setq article (match-string 1)
2141               bytes (nnimap-get-length))
2142         (delete-region (line-beginning-position) (line-end-position))
2143         ;; Insert MMDF separator, and a way to remember what this
2144         ;; article UID is.
2145         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2146         (forward-char (1+ bytes))
2147         (setq bytes (nnimap-get-length))
2148         (delete-region (line-beginning-position) (line-end-position))
2149         ;; There's a body; skip past that.
2150         (when bytes
2151           (forward-char (1+ bytes))
2152           (delete-region (line-beginning-position) (line-end-position)))))))
2153
2154 (defun nnimap-dummy-active-number (group &optional server)
2155   1)
2156
2157 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2158   (let (article)
2159     (goto-char (point-min))
2160     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2161         (error "Invalid nnimap mail")
2162       (setq article (string-to-number (match-string 1))))
2163     (push (list article
2164                 (if (eq group-art 'junk)
2165                     (list (cons 'junk 1))
2166                   group-art))
2167           nnimap-incoming-split-list)))
2168
2169 (defun nnimap-make-thread-query (header)
2170   (let* ((id  (mail-header-id header))
2171          (refs (split-string
2172                 (or (mail-header-references header)
2173                     "")))
2174          (value
2175           (format
2176            "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2177            id id)))
2178     (dolist (refid refs value)
2179       (setq value (format
2180                    "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2181                    refid refid value)))))
2182
2183
2184 (provide 'nnimap)
2185
2186 ;;; nnimap.el ends here