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