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