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