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