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