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