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