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