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