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