Handle unquoted IMAP group names
[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 (buffer-substring-no-properties
1266                     (progn (skip-chars-forward " \"")
1267                            (point))
1268                     (progn (move-end-of-line 1)
1269                            (skip-chars-backward " \r\"")
1270                            (point)))))
1271         (unless (member '%NoSelect flags)
1272           (push (utf7-decode (if (stringp group)
1273                                  group
1274                                (format "%s" group)) t)
1275                 groups))))
1276     (nreverse groups)))
1277
1278 (defun nnimap-get-responses (sequences)
1279   (let (responses)
1280     (dolist (sequence sequences)
1281       (goto-char (point-min))
1282       (when (re-search-forward (format "^%d " sequence) nil t)
1283         (push (list sequence (nnimap-parse-response))
1284               responses)))
1285     responses))
1286
1287 (deffoo nnimap-request-list (&optional server)
1288   (when (nnimap-change-group nil server)
1289     (with-current-buffer nntp-server-buffer
1290       (erase-buffer)
1291       (let ((groups
1292              (with-current-buffer (nnimap-buffer)
1293                (nnimap-get-groups)))
1294             sequences responses)
1295         (when groups
1296           (with-current-buffer (nnimap-buffer)
1297             (setf (nnimap-group nnimap-object) nil)
1298             (dolist (group groups)
1299               (setf (nnimap-examined nnimap-object) group)
1300               (push (list (nnimap-send-command "EXAMINE %S"
1301                                                (utf7-encode group t))
1302                           group)
1303                     sequences))
1304             (nnimap-wait-for-response (caar sequences))
1305             (setq responses
1306                   (nnimap-get-responses (mapcar #'car sequences))))
1307           (dolist (response responses)
1308             (let* ((sequence (car response))
1309                    (response (cadr response))
1310                    (group (cadr (assoc sequence sequences)))
1311                    (egroup (encode-coding-string group 'utf-8)))
1312               (when (and group
1313                          (equal (caar response) "OK"))
1314                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1315                       highest exists)
1316                   (dolist (elem response)
1317                     (when (equal (cadr elem) "EXISTS")
1318                       (setq exists (string-to-number (car elem)))))
1319                   (when uidnext
1320                     (setq highest (1- (string-to-number (car uidnext)))))
1321                   (cond
1322                    ((null highest)
1323                     (insert (format "%S 0 1 y\n" egroup)))
1324                    ((zerop exists)
1325                     ;; Empty group.
1326                     (insert (format "%S %d %d y\n" egroup
1327                                     highest (1+ highest))))
1328                    (t
1329                     ;; Return the widest possible range.
1330                     (insert (format "%S %d 1 y\n" egroup
1331                                     (or highest exists)))))))))
1332           t)))))
1333
1334 (deffoo nnimap-request-newgroups (date &optional server)
1335   (when (nnimap-change-group nil server)
1336     (with-current-buffer nntp-server-buffer
1337       (erase-buffer)
1338       (dolist (group (with-current-buffer (nnimap-buffer)
1339                        (nnimap-get-groups)))
1340         (unless (assoc group nnimap-current-infos)
1341           ;; Insert dummy numbers here -- they don't matter.
1342           (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1343       t)))
1344
1345 (deffoo nnimap-retrieve-group-data-early (server infos)
1346   (when (and (nnimap-change-group nil server)
1347              infos)
1348     (with-current-buffer (nnimap-buffer)
1349       (erase-buffer)
1350       (setf (nnimap-group nnimap-object) nil)
1351       (setf (nnimap-initial-resync nnimap-object) 0)
1352       (let ((qresyncp (nnimap-capability "QRESYNC"))
1353             params groups sequences active uidvalidity modseq group
1354             unexist)
1355         ;; Go through the infos and gather the data needed to know
1356         ;; what and how to request the data.
1357         (dolist (info infos)
1358           (setq params (gnus-info-params info)
1359                 group (nnimap-decode-gnus-group
1360                        (gnus-group-real-name (gnus-info-group info)))
1361                 active (cdr (assq 'active params))
1362                 unexist (assq 'unexist (gnus-info-marks info))
1363                 uidvalidity (cdr (assq 'uidvalidity params))
1364                 modseq (cdr (assq 'modseq params)))
1365           (setf (nnimap-examined nnimap-object) group)
1366           (if (and qresyncp
1367                    uidvalidity
1368                    active
1369                    modseq
1370                    unexist)
1371               (push
1372                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1373                                           (utf7-encode group t)
1374                                           (nnimap-quirk "QRESYNC")
1375                                           uidvalidity modseq)
1376                      'qresync
1377                      nil group 'qresync)
1378                sequences)
1379             (let ((command
1380                    (if uidvalidity
1381                        "EXAMINE"
1382                      ;; If we don't have a UIDVALIDITY, then this is
1383                      ;; the first time we've seen the group, so we
1384                      ;; have to do a SELECT (which is slower than an
1385                      ;; examine), but will tell us whether the group
1386                      ;; is read-only or not.
1387                      "SELECT"))
1388                   start)
1389               (if (and active uidvalidity unexist)
1390                   ;; Fetch the last 100 flags.
1391                   (setq start (max 1 (- (cdr active) 100)))
1392                 (incf (nnimap-initial-resync nnimap-object))
1393                 (setq start 1))
1394               (push (list (nnimap-send-command "%s %S" command
1395                                                (utf7-encode group t))
1396                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1397                           start group command)
1398                     sequences))))
1399         sequences))))
1400
1401 (defun nnimap-quirk (command)
1402   (let ((quirk (assoc command nnimap-quirks)))
1403     ;; If this server is of a type that matches a quirk, then return
1404     ;; the "quirked" command instead of the proper one.
1405     (if (or (null quirk)
1406             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1407         command
1408       (nth 2 quirk))))
1409
1410 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences
1411                                                    &optional dont-insert)
1412   (when (and sequences
1413              (nnimap-change-group nil server t)
1414              ;; Check that the process is still alive.
1415              (get-buffer-process (nnimap-buffer))
1416              (memq (process-status (get-buffer-process (nnimap-buffer)))
1417                    '(open run)))
1418     (with-current-buffer (nnimap-buffer)
1419       ;; Wait for the final data to trickle in.
1420       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1421                                           (caar sequences)
1422                                         (cadar sequences))
1423                                       t)
1424         ;; Now we should have most of the data we need, no matter
1425         ;; whether we're QRESYNCING, fetching all the flags from
1426         ;; scratch, or just fetching the last 100 flags per group.
1427         (nnimap-update-infos (nnimap-flags-to-marks
1428                               (nnimap-parse-flags
1429                                (nreverse sequences)))
1430                              infos)
1431         (unless dont-insert
1432           ;; Finally, just return something resembling an active file in
1433           ;; the nntp buffer, so that the agent can save the info, too.
1434           (with-current-buffer nntp-server-buffer
1435             (erase-buffer)
1436             (dolist (info infos)
1437               (let* ((group (gnus-info-group info))
1438                      (active (gnus-active group)))
1439                 (when active
1440                   (insert (format "%S %d %d y\n"
1441                                   (decode-coding-string
1442                                    (gnus-group-real-name group) 'utf-8)
1443                                   (cdr active)
1444                                   (car active))))))))))))
1445
1446 (defun nnimap-update-infos (flags infos)
1447   (dolist (info infos)
1448     (let* ((group (nnimap-decode-gnus-group
1449                    (gnus-group-real-name (gnus-info-group info))))
1450            (marks (cdr (assoc group flags))))
1451       (when marks
1452         (nnimap-update-info info marks)))))
1453
1454 (defun nnimap-update-info (info marks)
1455   (destructuring-bind (existing flags high low uidnext start-article
1456                                 permanent-flags uidvalidity
1457                                 vanished highestmodseq) marks
1458     (cond
1459      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1460      ;; completely empty groups.
1461      ((and (not existing)
1462            (not uidnext))
1463       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1464         (when active
1465           (gnus-set-active (gnus-info-group info) active))))
1466      ;; We have a mismatch between the old and new UIDVALIDITY
1467      ;; identifiers, so we have to re-request the group info (the next
1468      ;; time).  This virtually never happens.
1469      ((let ((old-uidvalidity
1470              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1471         (and old-uidvalidity
1472              (not (equal old-uidvalidity uidvalidity))
1473              (or (not start-article)
1474                  (> start-article 1))))
1475       (gnus-group-remove-parameter info 'uidvalidity)
1476       (gnus-group-remove-parameter info 'modseq))
1477      ;; We have the data needed to update.
1478      (t
1479       (let* ((group (gnus-info-group info))
1480              (completep (and start-article
1481                              (= start-article 1)))
1482              (active (or (gnus-active group)
1483                          (cdr (assq 'active (gnus-info-params info))))))
1484         (when uidnext
1485           (setq high (1- uidnext)))
1486         ;; First set the active ranges based on high/low.
1487         (if (or completep
1488                 (not (gnus-active group)))
1489             (gnus-set-active group
1490                              (cond
1491                               (active
1492                                (cons (min (or low (car active))
1493                                           (car active))
1494                                      (max (or high (cdr active))
1495                                           (cdr active))))
1496                               ((and low high)
1497                                (cons low high))
1498                               (uidnext
1499                                ;; No articles in this group.
1500                                (cons uidnext (1- uidnext)))
1501                               (start-article
1502                                (cons start-article (1- start-article)))
1503                               (t
1504                                ;; No articles and no uidnext.
1505                                nil)))
1506           (gnus-set-active group
1507                            (cons (car active)
1508                                  (or high (1- uidnext)))))
1509         ;; See whether this is a read-only group.
1510         (unless (eq permanent-flags 'not-scanned)
1511           (gnus-group-set-parameter
1512            info 'permanent-flags
1513            (and (or (memq '%* permanent-flags)
1514                     (memq '%Seen permanent-flags))
1515                 permanent-flags)))
1516         ;; Update marks and read articles if this isn't a
1517         ;; read-only IMAP group.
1518         (when (setq permanent-flags
1519                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1520           (if (and highestmodseq
1521                    (not start-article))
1522               ;; We've gotten the data by QRESYNCing.
1523               (nnimap-update-qresync-info
1524                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1525             ;; Do normal non-QRESYNC flag updates.
1526             ;; Update the list of read articles.
1527             (let* ((unread
1528                     (gnus-compress-sequence
1529                      (gnus-set-difference
1530                       (gnus-set-difference
1531                        existing
1532                        (gnus-sorted-union
1533                         (cdr (assoc '%Seen flags))
1534                         (cdr (assoc '%Deleted flags))))
1535                       (cdr (assoc '%Flagged flags)))))
1536                    (read (gnus-range-difference
1537                           (cons start-article high) unread)))
1538               (when (> start-article 1)
1539                 (setq read
1540                       (gnus-range-nconcat
1541                        (if (> start-article 1)
1542                            (gnus-sorted-range-intersection
1543                             (cons 1 (1- start-article))
1544                             (gnus-info-read info))
1545                          (gnus-info-read info))
1546                        read)))
1547               (when (or (not (listp permanent-flags))
1548                         (memq '%Seen permanent-flags))
1549                 (gnus-info-set-read info read))
1550               ;; Update the marks.
1551               (setq marks (gnus-info-marks info))
1552               (dolist (type (cdr nnimap-mark-alist))
1553                 (when (or (not (listp permanent-flags))
1554                           (memq (car (assoc (caddr type) flags))
1555                                 permanent-flags)
1556                           (memq '%* permanent-flags))
1557                   (let ((old-marks (assoc (car type) marks))
1558                         (new-marks
1559                          (gnus-compress-sequence
1560                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1561                                    (assoc (intern (cadr type) obarray) flags)
1562                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1563                     (setq marks (delq old-marks marks))
1564                     (pop old-marks)
1565                     (when (and old-marks
1566                                (> start-article 1))
1567                       (setq old-marks (gnus-range-difference
1568                                        old-marks
1569                                        (cons start-article high)))
1570                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1571                     (when new-marks
1572                       (push (cons (car type) new-marks) marks)))))
1573               ;; Keep track of non-existing articles.
1574               (let* ((old-unexists (assq 'unexist marks))
1575                      (active (gnus-active group))
1576                      (unexists
1577                       (if completep
1578                           (gnus-range-difference
1579                            active
1580                            (gnus-compress-sequence existing))
1581                         (gnus-add-to-range
1582                          (cdr old-unexists)
1583                          (gnus-list-range-difference
1584                           existing (gnus-active group))))))
1585                 (when (> (car active) 1)
1586                   (setq unexists (gnus-range-add
1587                                   (cons 1 (1- (car active)))
1588                                   unexists)))
1589                 (if old-unexists
1590                     (setcdr old-unexists unexists)
1591                   (push (cons 'unexist unexists) marks)))
1592               (gnus-info-set-marks info marks t))))
1593         ;; Tell Gnus whether there are any \Recent messages in any of
1594         ;; the groups.
1595         (let ((recent (cdr (assoc '%Recent flags))))
1596           (when (and active
1597                      recent
1598                      (> (car (last recent)) (cdr active)))
1599             (push (list (cons (gnus-group-real-name group) 0))
1600                   nnmail-split-history)))
1601         ;; Note the active level for the next run-through.
1602         (gnus-group-set-parameter info 'active (gnus-active group))
1603         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1604         (gnus-group-set-parameter info 'modseq highestmodseq)
1605         (nnimap-store-info info (gnus-active group)))))))
1606
1607 (defun nnimap-update-qresync-info (info existing vanished flags)
1608   ;; Add all the vanished articles to the list of read articles.
1609   (gnus-info-set-read
1610    info
1611    (gnus-add-to-range
1612     (gnus-add-to-range
1613      (gnus-range-add (gnus-info-read info)
1614                      vanished)
1615      (cdr (assq '%Flagged flags)))
1616     (cdr (assq '%Seen flags))))
1617   (let ((marks (gnus-info-marks info)))
1618     (dolist (type (cdr nnimap-mark-alist))
1619       (let ((ticks (assoc (car type) marks))
1620             (new-marks
1621              (cdr (or (assoc (caddr type) flags) ; %Flagged
1622                       (assoc (intern (cadr type) obarray) flags)
1623                       (assoc (cadr type) flags))))) ; "\Flagged"
1624         (setq marks (delq ticks marks))
1625         (pop ticks)
1626         ;; Add the new marks we got.
1627         (setq ticks (gnus-add-to-range ticks new-marks))
1628         ;; Remove the marks from messages that don't have them.
1629         (setq ticks (gnus-remove-from-range
1630                      ticks
1631                      (gnus-compress-sequence
1632                       (gnus-sorted-complement existing new-marks))))
1633         (when ticks
1634           (push (cons (car type) ticks) marks)))
1635       (gnus-info-set-marks info marks t))
1636     ;; Add vanished to the list of unexisting articles.
1637     (when vanished
1638       (let* ((old-unexists (assq 'unexist marks))
1639              (unexists (gnus-range-add (cdr old-unexists) vanished)))
1640         (if old-unexists
1641             (setcdr old-unexists unexists)
1642           (push (cons 'unexist unexists) marks)))
1643       (gnus-info-set-marks info marks t))))
1644
1645 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1646   (if (zerop (length irange))
1647       nil
1648     (let ((result nil))
1649       (dolist (elem (split-string irange ","))
1650         (push
1651          (if (string-match ":" elem)
1652              (let ((numbers (split-string elem ":")))
1653                (cons (string-to-number (car numbers))
1654                      (string-to-number (cadr numbers))))
1655            (string-to-number elem))
1656          result))
1657       (nreverse result))))
1658
1659 (defun nnimap-store-info (info active)
1660   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1661          (entry (assoc group nnimap-current-infos)))
1662     (if entry
1663         (setcdr entry (list info active))
1664       (push (list group info active) nnimap-current-infos))))
1665
1666 (defun nnimap-flags-to-marks (groups)
1667   (let (data group totalp uidnext articles start-article mark permanent-flags
1668              uidvalidity vanished highestmodseq)
1669     (dolist (elem groups)
1670       (setq group (car elem)
1671             uidnext (nth 1 elem)
1672             start-article (nth 2 elem)
1673             permanent-flags (nth 3 elem)
1674             uidvalidity (nth 4 elem)
1675             vanished (nth 5 elem)
1676             highestmodseq (nth 6 elem)
1677             articles (nthcdr 7 elem))
1678       (let ((high (caar articles))
1679             marks low existing)
1680         (dolist (article articles)
1681           (setq low (car article))
1682           (push (car article) existing)
1683           (dolist (flag (cdr article))
1684             (setq mark (assoc flag marks))
1685             (if (not mark)
1686                 (push (list flag (car article)) marks)
1687               (setcdr mark (cons (car article) (cdr mark))))))
1688         (push (list group existing marks high low uidnext start-article
1689                     permanent-flags uidvalidity vanished highestmodseq)
1690               data)))
1691     data))
1692
1693 (defun nnimap-parse-flags (sequences)
1694   (goto-char (point-min))
1695   ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1696   ;; read it.
1697   (subst-char-in-region (point-min) (point-max)
1698                         ?\\ ?% t)
1699   ;; Remove any MODSEQ entries in the buffer, because they may contain
1700   ;; numbers that are too large for 32-bit Emacsen.
1701   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1702     (replace-match "" t t))
1703   (goto-char (point-min))
1704   (let (start end articles groups uidnext elems permanent-flags
1705               uidvalidity vanished highestmodseq)
1706     (dolist (elem sequences)
1707       (destructuring-bind (group-sequence flag-sequence totalp group command)
1708           elem
1709         (setq start (point))
1710         (when (and
1711                ;; The EXAMINE was successful.
1712                (search-forward (format "\n%d OK " group-sequence) nil t)
1713                (progn
1714                  (forward-line 1)
1715                  (setq end (point))
1716                  (goto-char start)
1717                  (setq permanent-flags
1718                        (if (equal command "SELECT")
1719                            (and (search-forward "PERMANENTFLAGS "
1720                                                 (or end (point-min)) t)
1721                                 (read (current-buffer)))
1722                          'not-scanned))
1723                  (goto-char start)
1724                  (setq uidnext
1725                        (and (search-forward "UIDNEXT "
1726                                             (or end (point-min)) t)
1727                             (read (current-buffer))))
1728                  (goto-char start)
1729                  (setq uidvalidity
1730                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1731                                                (or end (point-min)) t)
1732                             ;; Store UIDVALIDITY as a string, as it's
1733                             ;; too big for 32-bit Emacsen, usually.
1734                             (match-string 1)))
1735                  (goto-char start)
1736                  (setq vanished
1737                        (and (eq flag-sequence 'qresync)
1738                             (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1739                                                (or end (point-min)) t)
1740                             (match-string 1)))
1741                  (goto-char start)
1742                  (setq highestmodseq
1743                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1744                                             (or end (point-min)) t)
1745                             (match-string 1)))
1746                  (goto-char end)
1747                  (forward-line -1))
1748                ;; The UID FETCH FLAGS was successful.
1749                (or (eq flag-sequence 'qresync)
1750                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1751           (if (eq flag-sequence 'qresync)
1752               (progn
1753                 (goto-char start)
1754                 (setq start end))
1755             (setq start (point))
1756             (goto-char end))
1757           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1758             (let ((p (point)))
1759               (setq elems (read (current-buffer)))
1760               (push (cons (cadr (memq 'UID elems))
1761                           (cadr (memq 'FLAGS elems)))
1762                     articles)))
1763           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1764                              vanished highestmodseq)
1765                        articles)
1766                 groups)
1767           (if (eq flag-sequence 'qresync)
1768               (goto-char end)
1769             (setq end (point)))
1770           (setq articles nil))))
1771     groups))
1772
1773 (defun nnimap-find-process-buffer (buffer)
1774   (cadr (assoc buffer nnimap-connection-alist)))
1775
1776 (deffoo nnimap-request-post (&optional server)
1777   (setq nnimap-status-string "Read-only server")
1778   nil)
1779
1780 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1781 (declare-function gnus-fetch-headers "gnus-sum"
1782                   (articles &optional limit force-new dependencies))
1783
1784 (autoload 'nnir-search-thread "nnir")
1785
1786 (deffoo nnimap-request-thread (header &optional group server)
1787   (when group
1788     (setq group (nnimap-decode-gnus-group group)))
1789   (if gnus-refer-thread-use-nnir
1790       (nnir-search-thread header)
1791     (when (nnimap-change-group group server)
1792       (let* ((cmd (nnimap-make-thread-query header))
1793              (result (with-current-buffer (nnimap-buffer)
1794                        (nnimap-command  "UID SEARCH %s" cmd))))
1795         (when result
1796           (gnus-fetch-headers
1797            (and (car result)
1798                 (delete 0 (mapcar #'string-to-number
1799                                   (cdr (assoc "SEARCH" (cdr result))))))
1800            nil t))))))
1801
1802 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1803   "Change group to GROUP if non-nil.
1804 If SERVER is set, check that server is connected, otherwise retry
1805 to reconnect, unless NO-RECONNECT is set to t.  Return nil if
1806 unsuccessful in connecting.
1807 If GROUP is nil, return t.
1808 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1809 Return the server's response to the SELECT or EXAMINE command."
1810   (let ((open-result t))
1811     (when (and server
1812                (not (nnimap-server-opened server)))
1813       (setq open-result (nnimap-open-server server nil no-reconnect)))
1814     (cond
1815      ((not open-result)
1816       nil)
1817      ((not group)
1818       t)
1819      (t
1820       (with-current-buffer (nnimap-buffer)
1821         (let ((result (nnimap-command "%s %S"
1822                                       (if read-only
1823                                           "EXAMINE"
1824                                         "SELECT")
1825                                       (utf7-encode group t))))
1826           (when (car result)
1827             (setf (nnimap-group nnimap-object) group
1828                   (nnimap-select-result nnimap-object) result)
1829             result)))))))
1830
1831 (defun nnimap-find-connection (buffer)
1832   "Find the connection delivering to BUFFER."
1833   (let ((entry (assoc buffer nnimap-connection-alist)))
1834     (when entry
1835       (if (and (buffer-name (cadr entry))
1836                (get-buffer-process (cadr entry))
1837                (memq (process-status (get-buffer-process (cadr entry)))
1838                      '(open run)))
1839           (get-buffer-process (cadr entry))
1840         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1841         nil))))
1842
1843 (defvar nnimap-sequence 0)
1844
1845 (defun nnimap-send-command (&rest args)
1846   (setf (nnimap-last-command-time nnimap-object) (current-time))
1847   (process-send-string
1848    (get-buffer-process (current-buffer))
1849    (nnimap-log-command
1850     (format "%d %s%s\n"
1851             (incf nnimap-sequence)
1852             (apply #'format args)
1853             (if (nnimap-newlinep nnimap-object)
1854                 ""
1855               "\r"))))
1856   ;; Some servers apparently can't have many outstanding
1857   ;; commands, so throttle them.
1858   (unless nnimap-streaming
1859     (nnimap-wait-for-response nnimap-sequence))
1860   nnimap-sequence)
1861
1862 (defvar nnimap-record-commands nil
1863   "If non-nil, log commands to the \"*imap log*\" buffer.")
1864
1865 (defun nnimap-log-buffer ()
1866   (let ((name "*imap log*"))
1867     (or (get-buffer name)
1868         (with-current-buffer (get-buffer-create name)
1869           (when (boundp 'window-point-insertion-type)
1870             (make-local-variable 'window-point-insertion-type)
1871             (setq window-point-insertion-type t))
1872           (current-buffer)))))
1873
1874 (defun nnimap-log-command (command)
1875   (when nnimap-record-commands
1876     (with-current-buffer (nnimap-log-buffer)
1877       (goto-char (point-max))
1878       (insert (format-time-string "%H:%M:%S")
1879               " [" nnimap-address "] "
1880               (if nnimap-inhibit-logging
1881                   "(inhibited)\n"
1882                 command))))
1883   command)
1884
1885 (defun nnimap-command (&rest args)
1886   (erase-buffer)
1887   (let* ((sequence (apply #'nnimap-send-command args))
1888          (response (nnimap-get-response sequence)))
1889     (if (equal (caar response) "OK")
1890         (cons t response)
1891       (nnheader-report 'nnimap "%s"
1892                        (mapconcat (lambda (a)
1893                                     (format "%s" a))
1894                                   (car response) " "))
1895       nil)))
1896
1897 (defun nnimap-get-response (sequence)
1898   (nnimap-wait-for-response sequence)
1899   (nnimap-parse-response))
1900
1901 (defun nnimap-wait-for-connection (&optional regexp)
1902   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1903
1904 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1905   (let ((process (get-buffer-process (current-buffer))))
1906     (goto-char (point-min))
1907     (while (and (memq (process-status process)
1908                       '(open run))
1909                 (not (re-search-forward regexp nil t)))
1910       (nnheader-accept-process-output process)
1911       (goto-char (point-min)))
1912     (forward-line -1)
1913     (and (looking-at (or response-regexp regexp))
1914          (match-string 1))))
1915
1916 (defun nnimap-wait-for-response (sequence &optional messagep)
1917   (let ((process (get-buffer-process (current-buffer)))
1918         openp)
1919     (condition-case nil
1920         (progn
1921           (goto-char (point-max))
1922           (while (and (setq openp (memq (process-status process)
1923                                         '(open run)))
1924                       (progn
1925                         ;; Skip past any "*" lines that the server has
1926                         ;; output.
1927                         (while (and (not (bobp))
1928                                     (progn
1929                                       (forward-line -1)
1930                                       (looking-at "\\*\\|[0-9]+ OK NOOP"))))
1931                         (not (looking-at (format "%d .*\n" sequence)))))
1932             (when messagep
1933               (nnheader-message-maybe
1934                7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1935                nnimap-address
1936                (if (not (zerop (nnimap-initial-resync nnimap-object)))
1937                    (format " (initial sync of %d group%s; please wait)"
1938                            (nnimap-initial-resync nnimap-object)
1939                            (if (= (nnimap-initial-resync nnimap-object) 1)
1940                                ""
1941                              "s"))
1942                  "")))
1943             (nnheader-accept-process-output process)
1944             (goto-char (point-max)))
1945           (setf (nnimap-initial-resync nnimap-object) 0)
1946           openp)
1947       (quit
1948        (when debug-on-quit
1949          (debug "Quit"))
1950        ;; The user hit C-g while we were waiting: kill the process, in case
1951        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1952        ;; NAT routers).
1953        (delete-process process)
1954        nil))))
1955
1956 (defun nnimap-parse-response ()
1957   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1958         result)
1959     (dolist (line lines)
1960       (push (cdr (nnimap-parse-line line)) result))
1961     ;; Return the OK/error code first, and then all the "continuation
1962     ;; lines" afterwards.
1963     (cons (pop result)
1964           (nreverse result))))
1965
1966 ;; Parse an IMAP response line lightly.  They look like
1967 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1968 ;; the lines into a list of strings and lists of string.
1969 (defun nnimap-parse-line (line)
1970   (let (char result)
1971     (with-temp-buffer
1972       (mm-disable-multibyte)
1973       (insert line)
1974       (goto-char (point-min))
1975       (while (not (eobp))
1976         (if (eql (setq char (following-char)) ? )
1977             (forward-char 1)
1978           (push
1979            (cond
1980             ((eql char ?\[)
1981              (split-string
1982               (buffer-substring
1983                (1+ (point))
1984                (if (search-forward "]" (line-end-position) 'move)
1985                    (1- (point))
1986                  (point)))))
1987             ((eql char ?\()
1988              (split-string
1989               (buffer-substring
1990                (1+ (point))
1991                (if (search-forward ")" (line-end-position) 'move)
1992                    (1- (point))
1993                  (point)))))
1994             ((eql char ?\")
1995              (forward-char 1)
1996              (buffer-substring
1997               (point)
1998               (1- (or (search-forward "\"" (line-end-position) 'move)
1999                       (point)))))
2000             (t
2001              (buffer-substring (point) (if (search-forward " " nil t)
2002                                            (1- (point))
2003                                          (goto-char (point-max))))))
2004            result)))
2005       (nreverse result))))
2006
2007 (defun nnimap-last-response-string ()
2008   (save-excursion
2009     (forward-line 1)
2010     (let ((end (point)))
2011       (forward-line -1)
2012       (when (not (bobp))
2013         (forward-line -1)
2014         (while (and (not (bobp))
2015                     (eql (following-char) ?*))
2016           (forward-line -1))
2017         (unless (eql (following-char) ?*)
2018           (forward-line 1)))
2019       (buffer-substring (point) end))))
2020
2021 (defvar nnimap-incoming-split-list nil)
2022
2023 (defun nnimap-fetch-inbox (articles)
2024   (erase-buffer)
2025   (nnimap-wait-for-response
2026    (nnimap-send-command
2027     "UID FETCH %s %s"
2028     (nnimap-article-ranges articles)
2029     (format "(UID %s%s)"
2030             (format
2031              (if (nnimap-ver4-p)
2032                  "BODY.PEEK"
2033                "RFC822.PEEK"))
2034             (cond
2035              (nnimap-split-download-body-default
2036               "[]")
2037              ((nnimap-ver4-p)
2038               "[HEADER]")
2039              (t
2040               "[1]"))))
2041    t))
2042
2043 (defun nnimap-split-incoming-mail ()
2044   (with-current-buffer (nnimap-buffer)
2045     (let ((nnimap-incoming-split-list nil)
2046           (nnmail-split-methods
2047            (cond
2048             ((eq nnimap-split-methods 'default)
2049              nnmail-split-methods)
2050             (nnimap-split-methods
2051              nnimap-split-methods)
2052             (nnimap-split-fancy
2053              'nnmail-split-fancy)))
2054           (nnmail-split-fancy (or nnimap-split-fancy
2055                                   nnmail-split-fancy))
2056           (nnmail-inhibit-default-split-group t)
2057           (groups (nnimap-get-groups))
2058           new-articles)
2059       (erase-buffer)
2060       (nnimap-command "SELECT %S" nnimap-inbox)
2061       (setf (nnimap-group nnimap-object) nnimap-inbox)
2062       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2063       (when new-articles
2064         (nnimap-fetch-inbox new-articles)
2065         (nnimap-transform-split-mail)
2066         (nnheader-ms-strip-cr)
2067         (nnmail-cache-open)
2068         (nnmail-split-incoming (current-buffer)
2069                                #'nnimap-save-mail-spec
2070                                nil nil
2071                                #'nnimap-dummy-active-number
2072                                #'nnimap-save-mail-spec)
2073         (when nnimap-incoming-split-list
2074           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2075                 sequences junk-articles)
2076             ;; Create any groups that doesn't already exist on the
2077             ;; server first.
2078             (dolist (spec specs)
2079               (when (and (not (member (car spec) groups))
2080                          (not (eq (car spec) 'junk)))
2081                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2082             ;; Then copy over all the messages.
2083             (erase-buffer)
2084             (dolist (spec specs)
2085               (let ((group (car spec))
2086                     (ranges (cdr spec)))
2087                 (if (eq group 'junk)
2088                     (setq junk-articles ranges)
2089                   (push (list (nnimap-send-command
2090                                "UID COPY %s %S"
2091                                (nnimap-article-ranges ranges)
2092                                (utf7-encode group t))
2093                               ranges)
2094                         sequences))))
2095             ;; Wait for the last COPY response...
2096             (when sequences
2097               (nnimap-wait-for-response (caar sequences))
2098               ;; And then mark the successful copy actions as deleted,
2099               ;; and possibly expunge them.
2100               (nnimap-mark-and-expunge-incoming
2101                (nnimap-parse-copied-articles sequences)))
2102             (nnimap-mark-and-expunge-incoming junk-articles)))))))
2103
2104 (defun nnimap-mark-and-expunge-incoming (range)
2105   (when range
2106     (setq range (nnimap-article-ranges range))
2107     (erase-buffer)
2108     (let ((sequence
2109            (nnimap-send-command
2110             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2111       (cond
2112        ;; If the server supports it, we now delete the message we have
2113        ;; just copied over.
2114        ((nnimap-capability "UIDPLUS")
2115         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2116        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2117        ;; user has configured it.
2118        (nnimap-expunge
2119         (setq sequence (nnimap-send-command "EXPUNGE"))))
2120       (nnimap-wait-for-response sequence))))
2121
2122 (defun nnimap-parse-copied-articles (sequences)
2123   (let (sequence copied range)
2124     (goto-char (point-min))
2125     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2126       (setq sequence (string-to-number (match-string 1)))
2127       (when (setq range (cadr (assq sequence sequences)))
2128         (push (gnus-uncompress-range range) copied)))
2129     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2130
2131 (defun nnimap-new-articles (flags)
2132   (let (new)
2133     (dolist (elem flags)
2134       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2135                                       (cdr elem))
2136         (push (car elem) new)))
2137     (gnus-compress-sequence (nreverse new))))
2138
2139 (defun nnimap-make-split-specs (list)
2140   (let ((specs nil)
2141         entry)
2142     (dolist (elem list)
2143       (destructuring-bind (article spec) elem
2144         (dolist (group (delete nil (mapcar #'car spec)))
2145           (unless (setq entry (assoc group specs))
2146             (push (setq entry (list group)) specs))
2147           (setcdr entry (cons article (cdr entry))))))
2148     (dolist (entry specs)
2149       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2150     specs))
2151
2152 (defun nnimap-transform-split-mail ()
2153   (goto-char (point-min))
2154   (let (article bytes)
2155     (block nil
2156       (while (not (eobp))
2157         (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2158           (delete-region (point) (progn (forward-line 1) (point)))
2159           (when (eobp)
2160             (return)))
2161         (setq article (match-string 1)
2162               bytes (nnimap-get-length))
2163         (delete-region (line-beginning-position) (line-end-position))
2164         ;; Insert MMDF separator, and a way to remember what this
2165         ;; article UID is.
2166         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2167         (forward-char (1+ bytes))
2168         (setq bytes (nnimap-get-length))
2169         (delete-region (line-beginning-position) (line-end-position))
2170         ;; There's a body; skip past that.
2171         (when bytes
2172           (forward-char (1+ bytes))
2173           (delete-region (line-beginning-position) (line-end-position)))))))
2174
2175 (defun nnimap-dummy-active-number (group &optional server)
2176   1)
2177
2178 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2179   (let (article)
2180     (goto-char (point-min))
2181     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2182         (error "Invalid nnimap mail")
2183       (setq article (string-to-number (match-string 1))))
2184     (push (list article
2185                 (if (eq group-art 'junk)
2186                     (list (cons 'junk 1))
2187                   group-art))
2188           nnimap-incoming-split-list)))
2189
2190 (defun nnimap-make-thread-query (header)
2191   (let* ((id  (mail-header-id header))
2192          (refs (split-string
2193                 (or (mail-header-references header)
2194                     "")))
2195          (value
2196           (format
2197            "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2198            id id)))
2199     (dolist (refid refs value)
2200       (setq value (format
2201                    "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2202                    refid refid value)))))
2203
2204
2205 (provide 'nnimap)
2206
2207 ;;; nnimap.el ends here