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