1 ;;; nnimap.el --- IMAP interface for Gnus
3 ;; Copyright (C) 2010-2014 Free Software Foundation, Inc.
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;; Simon Josefsson <simon@josefsson.org>
8 ;; This file is part of GNU Emacs.
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.
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.
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/>.
25 ;; nnimap interfaces Gnus with IMAP servers.
31 ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
32 ;; `make-network-stream'.
33 (unless (fboundp 'open-protocol-stream)
34 (require 'proto-stream)))
49 (autoload 'auth-source-forget+ "auth-source")
50 (autoload 'auth-source-search "auth-source")
54 (defvoo nnimap-address nil
55 "The address of the IMAP server.")
57 (defvoo nnimap-user nil
58 "Username to use for authentication to the IMAP server.")
60 (defvoo nnimap-server-port nil
62 If nnimap-stream is `ssl', this will default to `imaps'. If not,
63 it will default to `imap'.")
65 (defvoo nnimap-stream 'undecided
66 "How nnimap talks to the IMAP server.
67 The value should be either `undecided', `ssl' or `tls',
68 `network', `starttls', `plain', or `shell'.
70 If the value is `undecided', nnimap tries `ssl' first, then falls
73 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
74 (if (listp imap-shell-program)
75 (car imap-shell-program)
79 (defvoo nnimap-inbox nil
80 "The mail box where incoming mail arrives and should be split out of.
81 This can be a string or a list of strings
82 For example, \"INBOX\" or (\"INBOX\" \"SENT\").")
84 (defvoo nnimap-split-methods nil
86 Uses the same syntax as `nnmail-split-methods'.")
88 (defvoo nnimap-split-fancy nil
89 "Uses the same syntax as `nnmail-split-fancy'.")
91 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
92 "Articles with the flags in the list will not be considered when splitting.")
94 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
97 (defvoo nnimap-authenticator nil
98 "How nnimap authenticate itself to the server.
99 Possible choices are nil (use default methods), `anonymous',
100 `login', `plain' and `cram-md5'.")
102 (defvoo nnimap-expunge t
103 "If non-nil, expunge articles after deleting them.
104 This is always done if the server supports UID EXPUNGE, but it's
105 not done by default on servers that doesn't support that command.")
107 (defvoo nnimap-streaming t
108 "If non-nil, try to use streaming commands with IMAP servers.
109 Switching this off will make nnimap slower, but it helps with
112 (defvoo nnimap-connection-alist nil)
114 (defvoo nnimap-current-infos nil)
116 (defvoo nnimap-fetch-partial-articles nil
117 "If non-nil, Gnus will fetch partial articles.
118 If t, Gnus will fetch only the first part. If a string, it
119 will fetch all parts that have types that match that string. A
120 likely value would be \"text/\" to automatically fetch all
127 (defcustom nnimap-request-articles-find-limit nil
128 "Limit the number of articles to look for after moving an article."
129 :type '(choice (const nil) integer)
133 (defvar nnimap-process nil)
135 (defvar nnimap-status-string "")
137 (defvar nnimap-split-download-body-default nil
138 "Internal variable with default value for `nnimap-split-download-body'.")
140 (defvar nnimap-keepalive-timer nil)
141 (defvar nnimap-process-buffers nil)
144 group process commands capabilities select-result newlinep server
145 last-command-time greeting examined stream-type initial-resync)
147 (defvar nnimap-object nil)
149 (defvar nnimap-mark-alist
150 '((read "\\Seen" %Seen)
151 (tick "\\Flagged" %Flagged)
152 (reply "\\Answered" %Answered)
153 (expire "gnus-expire")
154 (dormant "gnus-dormant")
157 (download "gnus-download")
158 (forward "gnus-forward")))
160 (defvar nnimap-quirks
161 '(("QRESYNC" "Zimbra" "QRESYNC ")))
163 (defvar nnimap-inhibit-logging nil)
165 (defun nnimap-buffer ()
166 (nnimap-find-process-buffer nntp-server-buffer))
168 (defun nnimap-header-parameters ()
169 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
172 "BODY.PEEK[HEADER.FIELDS %s]"
173 "RFC822.HEADER.LINES %s")
174 (append '(Subject From Date Message-Id
175 References In-Reply-To Xref)
176 nnmail-extra-headers))))
178 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
180 (setq group (nnimap-decode-gnus-group group)))
181 (with-current-buffer nntp-server-buffer
183 (when (nnimap-change-group group server)
184 (with-current-buffer (nnimap-buffer)
186 (nnimap-wait-for-response
189 (nnimap-article-ranges (gnus-compress-sequence articles))
190 (nnimap-header-parameters))
192 (nnimap-transform-headers)
193 (nnheader-remove-cr-followed-by-lf))
194 (insert-buffer-substring
195 (nnimap-find-process-buffer (current-buffer))))
198 (defun nnimap-transform-headers ()
199 (goto-char (point-min))
200 (let (article lines size string)
203 (while (not (looking-at "\\* [0-9]+ FETCH"))
204 (delete-region (point) (progn (forward-line 1) (point)))
207 (goto-char (match-end 0))
208 ;; Unfold quoted {number} strings.
209 (while (re-search-forward
210 "[^]][ (]{\\([0-9]+\\)}\r?\n"
212 ;; Start of the header section.
213 (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
214 ;; Start of the next FETCH.
215 (re-search-forward "\\* [0-9]+ FETCH" nil t)
218 (setq size (string-to-number (match-string 1)))
219 (delete-region (+ (match-beginning 0) 2) (point))
220 (setq string (buffer-substring (point) (+ (point) size)))
221 (delete-region (point) (+ (point) size))
222 (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
225 (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
230 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
235 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
236 (let ((structure (ignore-errors
237 (read (current-buffer)))))
238 (while (and (consp structure)
239 (not (atom (car structure))))
240 (setq structure (car structure)))
242 (stringp (car structure))
243 (equal (upcase (nth 0 structure)) "MESSAGE")
244 (equal (upcase (nth 1 structure)) "RFC822"))
246 (nth 7 structure)))))
247 (delete-region (line-beginning-position) (line-end-position))
248 (insert (format "211 %s Article retrieved." article))
251 (insert (format "Chars: %s\n" size)))
253 (insert (format "Lines: %s\n" lines)))
254 ;; Most servers have a blank line after the headers, but
256 (unless (re-search-forward "^\r$\\|^)\r?$" nil t)
257 (goto-char (point-max)))
258 (delete-region (line-beginning-position) (line-end-position))
262 (defun nnimap-unfold-quoted-lines ()
263 ;; Unfold quoted {number} strings.
265 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
266 (setq size (string-to-number (match-string 1)))
267 (delete-region (1+ (match-beginning 0)) (point))
268 (setq string (buffer-substring (point) (+ (point) size)))
269 (delete-region (point) (+ (point) size))
270 (insert (format "%S" string)))))
272 (defun nnimap-get-length ()
273 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
274 (string-to-number (match-string 1))))
276 (defun nnimap-article-ranges (ranges)
280 (number-to-string ranges))
281 ((numberp (cdr ranges))
282 (format "%d:%d" (car ranges) (cdr ranges)))
284 (dolist (elem ranges)
287 (format "%d:%d" (car elem) (cdr elem))
288 (number-to-string elem))
290 (mapconcat #'identity (nreverse result) ",")))))
292 (deffoo nnimap-open-server (server &optional defs no-reconnect)
293 (if (nnimap-server-opened server)
295 (unless (assq 'nnimap-address defs)
296 (setq defs (append defs (list (list 'nnimap-address server)))))
297 (nnoo-change-server 'nnimap server defs)
299 (nnimap-find-connection nntp-server-buffer)
300 (or (nnimap-find-connection nntp-server-buffer)
301 (nnimap-open-connection nntp-server-buffer)))))
303 (defun nnimap-make-process-buffer (buffer)
305 (generate-new-buffer (format " *nnimap %s %s %s*"
306 nnimap-address nnimap-server-port
307 (gnus-buffer-exists-p buffer)))
308 (mm-disable-multibyte)
309 (buffer-disable-undo)
311 (set (make-local-variable 'after-change-functions) nil)
312 (set (make-local-variable 'nnimap-object)
313 (make-nnimap :server (nnoo-current-server 'nnimap)
315 (push (list buffer (current-buffer)) nnimap-connection-alist)
316 (push (current-buffer) nnimap-process-buffers)
319 (defun nnimap-credentials (address ports user)
320 (let* ((auth-source-creation-prompts
321 '((user . "IMAP user at %h: ")
322 (secret . "IMAP password for %u@%h: ")))
323 (found (nth 0 (auth-source-search :max 1
327 :require '(:user :secret)
330 (list (plist-get found :user)
331 (let ((secret (plist-get found :secret)))
332 (if (functionp secret)
335 (plist-get found :save-function))
338 (defun nnimap-keepalive ()
339 (let ((now (current-time)))
340 (dolist (buffer nnimap-process-buffers)
341 (when (buffer-name buffer)
342 (with-current-buffer buffer
343 (when (and nnimap-object
344 (nnimap-last-command-time nnimap-object)
348 (nnimap-last-command-time nnimap-object)))
349 ;; More than five minutes since the last command.
351 (ignore-errors ;E.g. "buffer foo has no process".
352 (nnimap-send-command "NOOP"))))))))
354 (defun nnimap-open-connection (buffer)
355 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
356 ;; `ssl' when nnimap-server-port was nil. Sort of.
357 (when (and nnimap-server-port
358 (eq nnimap-stream 'undecided))
359 (setq nnimap-stream 'ssl))
361 (if (eq nnimap-stream 'undecided)
362 (loop for type in '(ssl network)
363 for stream = (let ((nnimap-stream type))
364 (nnimap-open-connection-1 buffer))
365 while (eq stream 'no-connect)
366 finally (return stream))
367 (nnimap-open-connection-1 buffer))))
368 (if (eq stream 'no-connect)
372 (defun nnimap-map-port (port)
373 (if (equal port "imaps")
377 (defun nnimap-open-connection-1 (buffer)
378 (unless nnimap-keepalive-timer
379 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
380 #'nnimap-keepalive)))
381 (with-current-buffer (nnimap-make-process-buffer buffer)
382 (let* ((coding-system-for-read 'binary)
383 (coding-system-for-write 'binary)
386 ((memq nnimap-stream '(network plain starttls))
387 (nnheader-message 7 "Opening connection to %s..."
390 ((eq nnimap-stream 'shell)
391 (nnheader-message 7 "Opening connection to %s via shell..."
394 ((memq nnimap-stream '(ssl tls))
395 (nnheader-message 7 "Opening connection to %s via tls..."
397 '("imaps" "imap" "993" "143"))
399 (error "Unknown stream type: %s" nnimap-stream))))
400 login-result credentials)
401 (when nnimap-server-port
402 (push nnimap-server-port ports))
404 (open-protocol-stream
405 "*nnimap*" (current-buffer) nnimap-address
406 (nnimap-map-port (car ports))
409 :shell-command nnimap-shell-program
410 :capability-command "1 CAPABILITY\r\n"
411 :end-of-command "\r\n"
414 (lambda (capabilities)
415 (when (gnus-string-match-p "STARTTLS" capabilities)
417 (stream (car stream-list))
418 (props (cdr stream-list))
419 (greeting (plist-get props :greeting))
420 (capabilities (plist-get props :capabilities))
421 (stream-type (plist-get props :type)))
422 (when (and stream (not (memq (process-status stream) '(open run))))
425 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
426 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
427 (eq (process-type stream) 'network))
428 ;; Use TCP-keepalive so that connections that pass through a NAT
429 ;; router don't hang when left idle.
430 (set-network-process-option stream :keepalive t))
432 (setf (nnimap-process nnimap-object) stream)
433 (setf (nnimap-stream-type nnimap-object) stream-type)
436 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
437 nnimap-address (car ports) nnimap-stream)
439 (gnus-set-process-query-on-exit-flag stream nil)
440 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
441 (nnheader-report 'nnimap "%s" greeting)
442 ;; Store the greeting (for debugging purposes).
443 (setf (nnimap-greeting nnimap-object) greeting)
444 (setf (nnimap-capabilities nnimap-object)
446 (split-string capabilities)))
447 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
448 (if (not (setq credentials
449 (if (eq nnimap-authenticator 'anonymous)
451 (message-make-address))
452 ;; Look for the credentials based on
453 ;; the virtual server name and the address
455 (gnus-delete-duplicates
457 (nnoo-current-server 'nnimap)
461 (setq nnimap-object nil)
462 (let ((nnimap-inhibit-logging t))
464 (nnimap-login (car credentials) (cadr credentials))))
465 (if (car login-result)
467 ;; Save the credentials if a save function exists
468 ;; (such a function will only be passed if a new
469 ;; token was created).
470 (when (functionp (nth 2 credentials))
471 (funcall (nth 2 credentials)))
472 ;; See if CAPABILITY is set as part of login
474 (dolist (response (cddr login-result))
475 (when (string= "CAPABILITY" (upcase (car response)))
476 (setf (nnimap-capabilities nnimap-object)
477 (mapcar #'upcase (cdr response))))))
478 ;; If the login failed, then forget the credentials
479 ;; that are now possibly cached.
480 (dolist (host (list (nnoo-current-server 'nnimap)
483 (auth-source-forget+ :host host :port port)))
484 (delete-process (nnimap-process nnimap-object))
485 (setq nnimap-object nil))))
487 (when (nnimap-capability "QRESYNC")
488 (nnimap-command "ENABLE QRESYNC"))
489 (nnheader-message 7 "Opening connection to %s...done"
491 (nnimap-process nnimap-object))))))))
493 (autoload 'rfc2104-hash "rfc2104")
495 (defun nnimap-login (user password)
497 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
498 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
499 ;; and we're using an encrypted connection.
500 ((and (not (nnimap-capability "LOGINDISABLED"))
501 (eq (nnimap-stream-type nnimap-object) 'tls)
502 (or (null nnimap-authenticator)
503 (eq nnimap-authenticator 'login)))
504 (nnimap-command "LOGIN %S %S" user password))
505 ((and (nnimap-capability "AUTH=CRAM-MD5")
506 (or (null nnimap-authenticator)
507 (eq nnimap-authenticator 'cram-md5)))
509 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
510 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
512 (get-buffer-process (current-buffer))
514 (base64-encode-string
516 (rfc2104-hash 'md5 64 16 password
517 (base64-decode-string challenge))))
519 (nnimap-wait-for-response sequence)))
520 ((and (not (nnimap-capability "LOGINDISABLED"))
521 (or (null nnimap-authenticator)
522 (eq nnimap-authenticator 'login)))
523 (nnimap-command "LOGIN %S %S" user password))
524 ((and (nnimap-capability "AUTH=PLAIN")
525 (or (null nnimap-authenticator)
526 (eq nnimap-authenticator 'plain)))
528 "AUTHENTICATE PLAIN %s"
529 (base64-encode-string
530 (format "\000%s\000%s"
531 (nnimap-quote-specials user)
532 (nnimap-quote-specials password)))))))
534 (defun nnimap-quote-specials (string)
537 (goto-char (point-min))
538 (while (re-search-forward "[\\\"]" nil t)
544 (defun nnimap-find-parameter (parameter elems)
548 ((equal (car elem) parameter)
549 (setq result (cdr elem)))
550 ((and (equal (car elem) "OK")
552 (equal (caadr elem) parameter))
553 (setq result (cdr (cadr elem))))))
556 (deffoo nnimap-close-server (&optional server)
557 (when (nnoo-change-server 'nnimap server nil)
559 (delete-process (get-buffer-process (nnimap-buffer))))
560 (nnoo-close-server 'nnimap server)
563 (deffoo nnimap-request-close ()
566 (deffoo nnimap-server-opened (&optional server)
567 (and (nnoo-current-server-p 'nnimap server)
569 (gnus-buffer-live-p nntp-server-buffer)
570 (nnimap-find-connection nntp-server-buffer)))
572 (deffoo nnimap-status-message (&optional server)
573 nnimap-status-string)
575 (deffoo nnimap-request-article (article &optional group server to-buffer)
577 (setq group (nnimap-decode-gnus-group group)))
578 (with-current-buffer nntp-server-buffer
579 (let ((result (nnimap-change-group group server))
581 (when (stringp article)
582 (setq article (nnimap-find-article-by-message-id group server article)))
586 (with-current-buffer (nnimap-buffer)
588 (when nnimap-fetch-partial-articles
589 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
590 (goto-char (point-min))
591 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
592 (setq structure (ignore-errors
593 (let ((start (point)))
595 (downcase-region start (point))
597 (read (current-buffer))))
598 parts (nnimap-find-wanted-parts structure))))
600 (nnimap-get-partial-article article parts structure)
601 (nnimap-get-whole-article article))
602 (let ((buffer (current-buffer)))
603 (with-current-buffer (or to-buffer nntp-server-buffer)
604 (nnheader-insert-buffer-substring buffer)
605 (nnheader-ms-strip-cr)))
606 (cons group article)))))))
608 (deffoo nnimap-request-head (article &optional group server to-buffer)
610 (setq group (nnimap-decode-gnus-group group)))
611 (when (nnimap-change-group group server)
612 (with-current-buffer (nnimap-buffer)
613 (when (stringp article)
614 (setq article (nnimap-find-article-by-message-id group server article)))
617 (nnimap-get-whole-article
618 article (format "UID FETCH %%d %s"
619 (nnimap-header-parameters)))
620 (let ((buffer (current-buffer)))
621 (with-current-buffer (or to-buffer nntp-server-buffer)
623 (insert-buffer-substring buffer)
624 (nnheader-ms-strip-cr)
625 (cons group article)))))))
627 (defun nnimap-get-whole-article (article &optional command)
632 "UID FETCH %d BODY.PEEK[]"
633 "UID FETCH %d RFC822.PEEK"))
635 ;; Check that we really got an article.
636 (goto-char (point-min))
637 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
640 ;; Remove any data that may have arrived before the FETCH data.
643 (delete-region (point-min) (point)))
644 (let ((bytes (nnimap-get-length)))
645 (delete-region (line-beginning-position)
646 (progn (forward-line 1) (point)))
647 (goto-char (+ (point) bytes))
648 (delete-region (point) (point-max)))
651 (defun nnimap-capability (capability)
652 (member capability (nnimap-capabilities nnimap-object)))
654 (defun nnimap-ver4-p ()
655 (nnimap-capability "IMAP4REV1"))
657 (defun nnimap-get-partial-article (article parts structure)
660 "UID FETCH %d (%s %s)"
666 (mapconcat (lambda (part)
667 (format "BODY.PEEK[%s]" part))
669 (mapconcat (lambda (part)
670 (format "RFC822.PEEK[%s]" part))
673 (nnimap-convert-partial-article structure))))
675 (defun nnimap-convert-partial-article (structure)
676 ;; First just skip past the headers.
677 (goto-char (point-min))
678 (let ((bytes (nnimap-get-length))
680 ;; Delete "FETCH" line.
681 (delete-region (line-beginning-position)
682 (progn (forward-line 1) (point)))
683 (goto-char (+ (point) bytes))
684 ;; Collect all the body parts.
685 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
686 (setq id (match-string 1)
687 bytes (or (nnimap-get-length) 0))
689 (delete-region (point) (progn (forward-line 1) (point)))
690 (push (list id (buffer-substring (point) (+ (point) bytes)))
692 (delete-region (point) (+ (point) bytes)))
693 ;; Delete trailing junk.
694 (delete-region (point) (point-max))
695 ;; Now insert all the parts again where they fit in the structure.
696 (nnimap-insert-partial-structure structure parts)
699 (defun nnimap-insert-partial-structure (structure parts &optional subp)
701 (let ((bstruc structure))
702 (while (consp (car bstruc))
704 (setq type (car bstruc))
705 (setq bstruc (car (cdr bstruc)))
706 (let ((has-boundary (member "boundary" bstruc)))
708 (setq boundary (cadr has-boundary)))))
710 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
711 (downcase type) boundary)))
712 (while (not (stringp (car structure)))
713 (insert "\n--" boundary "\n")
714 (if (consp (caar structure))
715 (nnimap-insert-partial-structure (pop structure) parts t)
716 (let ((bit (pop structure)))
717 (insert (format "Content-type: %s/%s"
718 (downcase (nth 0 bit))
719 (downcase (nth 1 bit))))
720 (if (member-ignore-case "CHARSET" (nth 2 bit))
723 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
725 (insert (format "Content-transfer-encoding: %s\n"
728 (when (assoc (nth 9 bit) parts)
729 (insert (cadr (assoc (nth 9 bit) parts)))))))
730 (insert "\n--" boundary "--\n")))
732 (defun nnimap-find-wanted-parts (structure)
733 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
735 (defun nnimap-find-wanted-parts-1 (structure prefix)
738 (while (consp (car structure))
739 (let ((sub (pop structure)))
740 (if (consp (car sub))
741 (push (nnimap-find-wanted-parts-1
742 sub (if (string= prefix "")
743 (number-to-string num)
744 (format "%s.%s" prefix num)))
746 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
747 (id (if (string= prefix "")
748 (number-to-string num)
749 (format "%s.%s" prefix num))))
750 (setcar (nthcdr 9 sub) id)
751 (when (if (eq nnimap-fetch-partial-articles t)
753 (string-match nnimap-fetch-partial-articles type))
758 (defun nnimap-decode-gnus-group (group)
759 (decode-coding-string group 'utf-8))
761 (deffoo nnimap-request-group (group &optional server dont-check info)
762 (setq group (nnimap-decode-gnus-group group))
763 (let ((result (nnimap-change-group
764 ;; Don't SELECT the group if we're going to select it
766 (if (and (not dont-check)
767 (assoc group nnimap-current-infos))
771 articles active marks high low)
772 (with-current-buffer nntp-server-buffer
775 (setq active (nth 2 (assoc group nnimap-current-infos))))
776 (insert (format "211 %d %d %d %S\n"
777 (- (cdr active) (car active))
781 (with-current-buffer (nnimap-buffer)
783 (let ((group-sequence
784 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
786 (nnimap-send-command "UID FETCH 1:* FLAGS")))
787 (setf (nnimap-group nnimap-object) group)
788 (nnimap-wait-for-response flag-sequence)
790 (nnimap-flags-to-marks
792 (list (list group-sequence flag-sequence
793 1 group "SELECT")))))
796 (nnimap-update-infos marks (list info))
797 (nnimap-store-info info (gnus-active (gnus-info-group info))))
798 (goto-char (point-max))
799 (let ((uidnext (nth 5 (car marks))))
800 (setq high (or (if uidnext
804 low (or (nth 4 (car marks)) uidnext 1)))))
808 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
811 (deffoo nnimap-request-create-group (group &optional server args)
812 (setq group (nnimap-decode-gnus-group group))
813 (when (nnimap-change-group nil server)
814 (with-current-buffer (nnimap-buffer)
815 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
817 (deffoo nnimap-request-delete-group (group &optional force server)
818 (setq group (nnimap-decode-gnus-group group))
819 (when (nnimap-change-group nil server)
820 (with-current-buffer (nnimap-buffer)
821 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
823 (deffoo nnimap-request-rename-group (group new-name &optional server)
824 (setq group (nnimap-decode-gnus-group group))
825 (when (nnimap-change-group nil server)
826 (with-current-buffer (nnimap-buffer)
827 (nnimap-unselect-group)
828 (car (nnimap-command "RENAME %S %S"
829 (utf7-encode group t) (utf7-encode new-name t))))))
831 (defun nnimap-unselect-group ()
832 ;; Make sure we don't have this group open read/write by asking
833 ;; to examine a mailbox that doesn't exist. This seems to be
834 ;; the only way that allows us to reliably go back to unselected
836 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
838 (deffoo nnimap-request-expunge-group (group &optional server)
839 (setq group (nnimap-decode-gnus-group group))
840 (when (nnimap-change-group group server)
841 (with-current-buffer (nnimap-buffer)
842 (car (nnimap-command "EXPUNGE")))))
844 (defun nnimap-get-flags (spec)
847 (with-current-buffer (nnimap-buffer)
849 (nnimap-wait-for-response (nnimap-send-command
850 "UID FETCH %s FLAGS" spec))
852 (subst-char-in-region (point-min) (point-max)
854 (goto-char (point-min))
855 (while (search-forward " FETCH " end t)
856 (setq elems (read (current-buffer)))
857 (push (cons (cadr (memq 'UID elems))
858 (cadr (memq 'FLAGS elems)))
860 (nreverse articles)))
862 (deffoo nnimap-close-group (group &optional server)
865 (deffoo nnimap-request-move-article (article group server accept-form
866 &optional last internal-move-group)
867 (setq group (nnimap-decode-gnus-group group))
868 (when internal-move-group
869 (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
871 (mm-disable-multibyte)
872 (when (funcall (if internal-move-group
874 'nnimap-request-article)
875 article group server (current-buffer))
876 ;; If the move is internal (on the same server), just do it the easy
878 (let ((message-id (message-field-value "message-id")))
879 (if internal-move-group
881 (with-current-buffer (nnimap-buffer)
882 (nnimap-command "UID COPY %d %S"
884 (utf7-encode internal-move-group t)))))
886 (nnimap-delete-article article)
887 (cons internal-move-group
888 (or (nnimap-find-uid-response "COPYUID" (cadr result))
889 (nnimap-find-article-by-message-id
890 internal-move-group server message-id
891 nnimap-request-articles-find-limit)))))
892 ;; Move the article to a different method.
893 (let ((result (eval accept-form)))
895 (nnimap-change-group group server)
896 (nnimap-delete-article article)
899 (deffoo nnimap-request-expire-articles (articles group &optional server force)
900 (setq group (nnimap-decode-gnus-group group))
904 ((not (nnimap-change-group group server))
907 (eq nnmail-expiry-target 'delete))
908 (unless (nnimap-delete-article (gnus-compress-sequence articles))
909 (nnheader-message 7 "Article marked for deletion, but not expunged."))
912 (let ((deletable-articles
914 (eq nnmail-expiry-wait 'immediate))
916 (gnus-sorted-intersection
918 (nnimap-find-expired-articles group)))))
919 (if (null deletable-articles)
921 (if (eq nnmail-expiry-target 'delete)
922 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
923 (setq deletable-articles
924 (nnimap-process-expiry-targets
925 deletable-articles group server)))
926 ;; Return the articles we didn't delete.
927 (gnus-sorted-complement articles deletable-articles))))))
929 (defun nnimap-process-expiry-targets (articles group server)
930 (let ((deleted-articles nil))
932 ;; shortcut further processing if we're going to delete the articles
933 ((eq nnmail-expiry-target 'delete)
934 (setq deleted-articles articles)
936 ;; or just move them to another folder on the same IMAP server
937 ((and (not (functionp nnmail-expiry-target))
938 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
939 (gnus-server-to-method
940 (format "nnimap:%s" server))))
941 (and (nnimap-change-group group server)
942 (with-current-buffer (nnimap-buffer)
943 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
946 (nnimap-article-ranges (gnus-compress-sequence articles))
947 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
948 (setq deleted-articles articles)))
951 (dolist (article articles)
952 (let ((target nnmail-expiry-target))
954 (mm-disable-multibyte)
955 (when (nnimap-request-article article group server (current-buffer))
956 (when (functionp target)
957 (setq target (funcall target group)))
959 (not (eq target 'delete)))
960 (if (or (gnus-request-group target t)
961 (gnus-request-create-group target))
963 (nnmail-expiry-target-group target group)
964 (nnheader-message 7 "Expiring article %s:%d to %s"
965 group article target))
967 (nnheader-message 7 "Expiring article %s:%d" group article))
969 (push article deleted-articles))))))))
970 ;; Change back to the current group again.
971 (nnimap-change-group group server)
972 (setq deleted-articles (nreverse deleted-articles))
973 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
976 (defun nnimap-find-expired-articles (group)
977 (let ((cutoff (nnmail-expired-article-p group nil nil)))
978 (with-current-buffer (nnimap-buffer)
981 "UID SEARCH SENTBEFORE %s"
985 (car (rassoc (nth 4 (decode-time cutoff))
986 parse-time-months))))
989 (delete 0 (mapcar #'string-to-number
990 (cdr (assoc "SEARCH" (cdr result))))))))))
993 (defun nnimap-find-article-by-message-id (group server message-id
995 "Search for message with MESSAGE-ID in GROUP from SERVER.
996 If LIMIT, first try to limit the search to the N last articles."
997 (with-current-buffer (nnimap-buffer)
999 (let* ((change-group-result (nnimap-change-group group server nil t))
1001 (and (listp change-group-result)
1003 (dolist (result (cdr change-group-result))
1004 (when (equal "EXISTS" (cadr result))
1005 (throw 'found (car result)))))))
1007 (nnimap-send-command
1008 "UID SEARCH%s HEADER Message-Id %S"
1009 (if (and limit number-of-article)
1010 ;; The -1 is because IMAP message
1011 ;; numbers are one-based rather than
1013 (format " %s:*" (- (string-to-number number-of-article)
1017 (when (nnimap-wait-for-response sequence)
1018 (let ((article (car (last (cdr (assoc "SEARCH"
1019 (nnimap-parse-response)))))))
1021 (string-to-number article)
1022 (when (and limit number-of-article)
1023 (nnimap-find-article-by-message-id group server message-id))))))))
1025 (defun nnimap-delete-article (articles)
1026 (with-current-buffer (nnimap-buffer)
1027 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1028 (nnimap-article-ranges articles))
1030 ((nnimap-capability "UIDPLUS")
1031 (nnimap-command "UID EXPUNGE %s"
1032 (nnimap-article-ranges articles))
1035 (nnimap-command "EXPUNGE")
1037 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1038 "server doesn't support UIDPLUS, so we won't "
1039 "delete this article now"))))))
1041 (deffoo nnimap-request-scan (&optional group server)
1043 (setq group (nnimap-decode-gnus-group group)))
1044 (when (and (nnimap-change-group nil server)
1046 nnimap-split-methods)
1047 (nnheader-message 7 "nnimap %s splitting mail..." server)
1048 (if (listp nnimap-inbox)
1049 (dolist (nnimap-inbox nnimap-inbox)
1050 (nnimap-split-incoming-mail))
1051 (nnimap-split-incoming-mail))
1052 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1054 (defun nnimap-marks-to-flags (marks)
1056 (dolist (mark marks)
1057 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1061 (deffoo nnimap-request-update-group-status (group status &optional server)
1062 (setq group (nnimap-decode-gnus-group group))
1063 (when (nnimap-change-group nil server)
1064 (let ((command (assoc
1066 '((subscribe "SUBSCRIBE")
1067 (unsubscribe "UNSUBSCRIBE")))))
1069 (with-current-buffer (nnimap-buffer)
1070 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1072 (deffoo nnimap-request-set-mark (group actions &optional server)
1073 (setq group (nnimap-decode-gnus-group group))
1074 (when (nnimap-change-group group server)
1076 (with-current-buffer (nnimap-buffer)
1078 ;; Just send all the STORE commands without waiting for
1079 ;; response. If they're successful, they're successful.
1080 (dolist (action actions)
1081 (destructuring-bind (range action marks) action
1082 (let ((flags (nnimap-marks-to-flags marks)))
1084 (setq sequence (nnimap-send-command
1085 "UID STORE %s %sFLAGS.SILENT (%s)"
1086 (nnimap-article-ranges range)
1088 ((eq action 'del) "-")
1089 ((eq action 'add) "+")
1090 ((eq action 'set) ""))
1091 (mapconcat #'identity flags " ")))))))
1092 ;; Wait for the last command to complete to avoid later
1093 ;; synchronization problems with the stream.
1095 (nnimap-wait-for-response sequence))))))
1097 (deffoo nnimap-request-accept-article (group &optional server last)
1098 (setq group (nnimap-decode-gnus-group group))
1099 (when (nnimap-change-group nil server)
1100 (nnmail-check-syntax)
1101 (let ((message-id (message-field-value "message-id"))
1104 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1105 (with-current-buffer (nnimap-buffer)
1106 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1108 ;; If we have this group open read-only, then unselect it
1109 ;; before appending to it.
1110 (when (equal (nnimap-examined nnimap-object) group)
1111 (nnimap-unselect-group))
1113 (setq sequence (nnimap-send-command
1114 "APPEND %S {%d}" (utf7-encode group t)
1116 (unless nnimap-streaming
1117 (nnimap-wait-for-connection "^[+]"))
1118 (process-send-string (get-buffer-process (current-buffer)) message)
1119 (process-send-string (get-buffer-process (current-buffer))
1120 (if (nnimap-newlinep nnimap-object)
1123 (let ((result (nnimap-get-response sequence)))
1124 (if (not (nnimap-ok-p result))
1126 (nnheader-report 'nnimap "%s" result)
1129 (or (nnimap-find-uid-response "APPENDUID" (car result))
1130 (nnimap-find-article-by-message-id
1131 group server message-id
1132 nnimap-request-articles-find-limit))))))))))
1134 (defun nnimap-process-quirk (greeting-match type data)
1135 (when (and (nnimap-greeting nnimap-object)
1136 (string-match greeting-match (nnimap-greeting nnimap-object))
1138 (string-match "\000" data))
1139 (let ((choice (gnus-multiple-choice
1140 "Message contains NUL characters. Delete, continue, abort? "
1141 '((?d "Delete NUL characters")
1142 (?c "Try to APPEND the message as is")
1146 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1152 (goto-char (point-min))
1153 (while (search-forward "\000" nil t)
1154 (replace-match "" t t))
1155 (buffer-string)))))))
1157 (defun nnimap-ok-p (value)
1160 (equal (caar value) "OK")))
1162 (defun nnimap-find-uid-response (name list)
1163 (let ((result (car (last (nnimap-find-response-element name list)))))
1165 (string-to-number result))))
1167 (defun nnimap-find-response-element (name list)
1170 (when (and (consp elem)
1171 (equal name (car elem)))
1172 (setq result elem)))
1175 (deffoo nnimap-request-replace-article (article group buffer)
1176 (setq group (nnimap-decode-gnus-group group))
1178 (when (and (nnimap-change-group group)
1179 ;; Put the article into the group.
1180 (with-current-buffer buffer
1182 (nnimap-request-accept-article group nil t))))
1183 (nnimap-delete-article (list article))
1184 ;; Return the new article number.
1187 (defun nnimap-add-cr ()
1188 (goto-char (point-min))
1189 (while (re-search-forward "\r?\n" nil t)
1190 (replace-match "\r\n" t t)))
1192 (defun nnimap-get-groups ()
1194 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1196 (nnimap-wait-for-response sequence)
1197 (subst-char-in-region (point-min) (point-max)
1199 (goto-char (point-min))
1200 (nnimap-unfold-quoted-lines)
1201 (goto-char (point-min))
1202 (while (search-forward "* LIST " nil t)
1203 (let ((flags (read (current-buffer)))
1204 (separator (read (current-buffer)))
1205 (group (read (current-buffer))))
1206 (unless (member '%NoSelect flags)
1207 (push (utf7-decode (if (stringp group)
1209 (format "%s" group)) t)
1213 (defun nnimap-get-responses (sequences)
1215 (dolist (sequence sequences)
1216 (goto-char (point-min))
1217 (when (re-search-forward (format "^%d " sequence) nil t)
1218 (push (list sequence (nnimap-parse-response))
1222 (deffoo nnimap-request-list (&optional server)
1223 (when (nnimap-change-group nil server)
1224 (with-current-buffer nntp-server-buffer
1227 (with-current-buffer (nnimap-buffer)
1228 (nnimap-get-groups)))
1229 sequences responses)
1231 (with-current-buffer (nnimap-buffer)
1232 (setf (nnimap-group nnimap-object) nil)
1233 (dolist (group groups)
1234 (setf (nnimap-examined nnimap-object) group)
1235 (push (list (nnimap-send-command "EXAMINE %S"
1236 (utf7-encode group t))
1239 (nnimap-wait-for-response (caar sequences))
1241 (nnimap-get-responses (mapcar #'car sequences))))
1242 (dolist (response responses)
1243 (let* ((sequence (car response))
1244 (response (cadr response))
1245 (group (cadr (assoc sequence sequences)))
1246 (egroup (encode-coding-string group 'utf-8)))
1248 (equal (caar response) "OK"))
1249 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1251 (dolist (elem response)
1252 (when (equal (cadr elem) "EXISTS")
1253 (setq exists (string-to-number (car elem)))))
1255 (setq highest (1- (string-to-number (car uidnext)))))
1258 (insert (format "%S 0 1 y\n" egroup)))
1261 (insert (format "%S %d %d y\n" egroup
1262 highest (1+ highest))))
1264 ;; Return the widest possible range.
1265 (insert (format "%S %d 1 y\n" egroup
1266 (or highest exists)))))))))
1269 (deffoo nnimap-request-newgroups (date &optional server)
1270 (when (nnimap-change-group nil server)
1271 (with-current-buffer nntp-server-buffer
1273 (dolist (group (with-current-buffer (nnimap-buffer)
1274 (nnimap-get-groups)))
1275 (unless (assoc group nnimap-current-infos)
1276 ;; Insert dummy numbers here -- they don't matter.
1277 (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1280 (deffoo nnimap-retrieve-group-data-early (server infos)
1281 (when (and (nnimap-change-group nil server)
1283 (with-current-buffer (nnimap-buffer)
1285 (setf (nnimap-group nnimap-object) nil)
1286 (setf (nnimap-initial-resync nnimap-object) 0)
1287 (let ((qresyncp (nnimap-capability "QRESYNC"))
1288 params groups sequences active uidvalidity modseq group
1290 ;; Go through the infos and gather the data needed to know
1291 ;; what and how to request the data.
1292 (dolist (info infos)
1293 (setq params (gnus-info-params info)
1294 group (nnimap-decode-gnus-group
1295 (gnus-group-real-name (gnus-info-group info)))
1296 active (cdr (assq 'active params))
1297 unexist (assq 'unexist (gnus-info-marks info))
1298 uidvalidity (cdr (assq 'uidvalidity params))
1299 modseq (cdr (assq 'modseq params)))
1300 (setf (nnimap-examined nnimap-object) group)
1307 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1308 (utf7-encode group t)
1309 (nnimap-quirk "QRESYNC")
1317 ;; If we don't have a UIDVALIDITY, then this is
1318 ;; the first time we've seen the group, so we
1319 ;; have to do a SELECT (which is slower than an
1320 ;; examine), but will tell us whether the group
1321 ;; is read-only or not.
1324 (if (and active uidvalidity unexist)
1325 ;; Fetch the last 100 flags.
1326 (setq start (max 1 (- (cdr active) 100)))
1327 (incf (nnimap-initial-resync nnimap-object))
1329 (push (list (nnimap-send-command "%s %S" command
1330 (utf7-encode group t))
1331 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1332 start group command)
1336 (defun nnimap-quirk (command)
1337 (let ((quirk (assoc command nnimap-quirks)))
1338 ;; If this server is of a type that matches a quirk, then return
1339 ;; the "quirked" command instead of the proper one.
1340 (if (or (null quirk)
1341 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1345 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1346 (when (and sequences
1347 (nnimap-change-group nil server t)
1348 ;; Check that the process is still alive.
1349 (get-buffer-process (nnimap-buffer))
1350 (memq (process-status (get-buffer-process (nnimap-buffer)))
1352 (with-current-buffer (nnimap-buffer)
1353 ;; Wait for the final data to trickle in.
1354 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1358 ;; Now we should have most of the data we need, no matter
1359 ;; whether we're QRESYNCING, fetching all the flags from
1360 ;; scratch, or just fetching the last 100 flags per group.
1361 (nnimap-update-infos (nnimap-flags-to-marks
1363 (nreverse sequences)))
1365 ;; Finally, just return something resembling an active file in
1366 ;; the nntp buffer, so that the agent can save the info, too.
1367 (with-current-buffer nntp-server-buffer
1369 (dolist (info infos)
1370 (let* ((group (gnus-info-group info))
1371 (active (gnus-active group)))
1373 (insert (format "%S %d %d y\n"
1374 (decode-coding-string
1375 (gnus-group-real-name group) 'utf-8)
1377 (car active)))))))))))
1379 (defun nnimap-update-infos (flags infos)
1380 (dolist (info infos)
1381 (let* ((group (nnimap-decode-gnus-group
1382 (gnus-group-real-name (gnus-info-group info))))
1383 (marks (cdr (assoc group flags))))
1385 (nnimap-update-info info marks)))))
1387 (defun nnimap-update-info (info marks)
1388 (destructuring-bind (existing flags high low uidnext start-article
1389 permanent-flags uidvalidity
1390 vanished highestmodseq) marks
1392 ;; Ignore groups with no UIDNEXT/marks. This happens for
1393 ;; completely empty groups.
1394 ((and (not existing)
1396 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1398 (gnus-set-active (gnus-info-group info) active))))
1399 ;; We have a mismatch between the old and new UIDVALIDITY
1400 ;; identifiers, so we have to re-request the group info (the next
1401 ;; time). This virtually never happens.
1402 ((let ((old-uidvalidity
1403 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1404 (and old-uidvalidity
1405 (not (equal old-uidvalidity uidvalidity))
1406 (or (not start-article)
1407 (> start-article 1))))
1408 (gnus-group-remove-parameter info 'uidvalidity)
1409 (gnus-group-remove-parameter info 'modseq))
1410 ;; We have the data needed to update.
1412 (let* ((group (gnus-info-group info))
1413 (completep (and start-article
1414 (= start-article 1)))
1415 (active (or (gnus-active group)
1416 (cdr (assq 'active (gnus-info-params info))))))
1418 (setq high (1- uidnext)))
1419 ;; First set the active ranges based on high/low.
1421 (not (gnus-active group)))
1422 (gnus-set-active group
1425 (cons (min (or low (car active))
1427 (max (or high (cdr active))
1432 ;; No articles in this group.
1433 (cons uidnext (1- uidnext)))
1435 (cons start-article (1- start-article)))
1437 ;; No articles and no uidnext.
1439 (gnus-set-active group
1441 (or high (1- uidnext)))))
1442 ;; See whether this is a read-only group.
1443 (unless (eq permanent-flags 'not-scanned)
1444 (gnus-group-set-parameter
1445 info 'permanent-flags
1446 (and (or (memq '%* permanent-flags)
1447 (memq '%Seen permanent-flags))
1449 ;; Update marks and read articles if this isn't a
1450 ;; read-only IMAP group.
1451 (when (setq permanent-flags
1452 (cdr (assq 'permanent-flags (gnus-info-params info))))
1453 (if (and highestmodseq
1454 (not start-article))
1455 ;; We've gotten the data by QRESYNCing.
1456 (nnimap-update-qresync-info
1457 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1458 ;; Do normal non-QRESYNC flag updates.
1459 ;; Update the list of read articles.
1461 (gnus-compress-sequence
1462 (gnus-set-difference
1463 (gnus-set-difference
1466 (cdr (assoc '%Seen flags))
1467 (cdr (assoc '%Deleted flags))))
1468 (cdr (assoc '%Flagged flags)))))
1469 (read (gnus-range-difference
1470 (cons start-article high) unread)))
1471 (when (> start-article 1)
1474 (if (> start-article 1)
1475 (gnus-sorted-range-intersection
1476 (cons 1 (1- start-article))
1477 (gnus-info-read info))
1478 (gnus-info-read info))
1480 (when (or (not (listp permanent-flags))
1481 (memq '%Seen permanent-flags))
1482 (gnus-info-set-read info read))
1483 ;; Update the marks.
1484 (setq marks (gnus-info-marks info))
1485 (dolist (type (cdr nnimap-mark-alist))
1486 (when (or (not (listp permanent-flags))
1487 (memq (car (assoc (caddr type) flags))
1489 (memq '%* permanent-flags))
1490 (let ((old-marks (assoc (car type) marks))
1492 (gnus-compress-sequence
1493 (cdr (or (assoc (caddr type) flags) ; %Flagged
1494 (assoc (intern (cadr type) obarray) flags)
1495 (assoc (cadr type) flags)))))) ; "\Flagged"
1496 (setq marks (delq old-marks marks))
1498 (when (and old-marks
1499 (> start-article 1))
1500 (setq old-marks (gnus-range-difference
1502 (cons start-article high)))
1503 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1505 (push (cons (car type) new-marks) marks)))))
1506 ;; Keep track of non-existing articles.
1507 (let* ((old-unexists (assq 'unexist marks))
1508 (active (gnus-active group))
1511 (gnus-range-difference
1513 (gnus-compress-sequence existing))
1516 (gnus-list-range-difference
1517 existing (gnus-active group))))))
1518 (when (> (car active) 1)
1519 (setq unexists (gnus-range-add
1520 (cons 1 (1- (car active)))
1523 (setcdr old-unexists unexists)
1524 (push (cons 'unexist unexists) marks)))
1525 (gnus-info-set-marks info marks t))))
1526 ;; Tell Gnus whether there are any \Recent messages in any of
1528 (let ((recent (cdr (assoc '%Recent flags))))
1531 (> (car (last recent)) (cdr active)))
1532 (push (list (cons (gnus-group-real-name group) 0))
1533 nnmail-split-history)))
1534 ;; Note the active level for the next run-through.
1535 (gnus-group-set-parameter info 'active (gnus-active group))
1536 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1537 (gnus-group-set-parameter info 'modseq highestmodseq)
1538 (nnimap-store-info info (gnus-active group)))))))
1540 (defun nnimap-update-qresync-info (info existing vanished flags)
1541 ;; Add all the vanished articles to the list of read articles.
1546 (gnus-range-add (gnus-info-read info)
1548 (cdr (assq '%Flagged flags)))
1549 (cdr (assq '%Seen flags))))
1550 (let ((marks (gnus-info-marks info)))
1551 (dolist (type (cdr nnimap-mark-alist))
1552 (let ((ticks (assoc (car type) marks))
1554 (cdr (or (assoc (caddr type) flags) ; %Flagged
1555 (assoc (intern (cadr type) obarray) flags)
1556 (assoc (cadr type) flags))))) ; "\Flagged"
1557 (setq marks (delq ticks marks))
1559 ;; Add the new marks we got.
1560 (setq ticks (gnus-add-to-range ticks new-marks))
1561 ;; Remove the marks from messages that don't have them.
1562 (setq ticks (gnus-remove-from-range
1564 (gnus-compress-sequence
1565 (gnus-sorted-complement existing new-marks))))
1567 (push (cons (car type) ticks) marks)))
1568 (gnus-info-set-marks info marks t))
1569 ;; Add vanished to the list of unexisting articles.
1571 (let* ((old-unexists (assq 'unexist marks))
1572 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1574 (setcdr old-unexists unexists)
1575 (push (cons 'unexist unexists) marks)))
1576 (gnus-info-set-marks info marks t))))
1578 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1579 (if (zerop (length irange))
1582 (dolist (elem (split-string irange ","))
1584 (if (string-match ":" elem)
1585 (let ((numbers (split-string elem ":")))
1586 (cons (string-to-number (car numbers))
1587 (string-to-number (cadr numbers))))
1588 (string-to-number elem))
1590 (nreverse result))))
1592 (defun nnimap-store-info (info active)
1593 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1594 (entry (assoc group nnimap-current-infos)))
1596 (setcdr entry (list info active))
1597 (push (list group info active) nnimap-current-infos))))
1599 (defun nnimap-flags-to-marks (groups)
1600 (let (data group totalp uidnext articles start-article mark permanent-flags
1601 uidvalidity vanished highestmodseq)
1602 (dolist (elem groups)
1603 (setq group (car elem)
1604 uidnext (nth 1 elem)
1605 start-article (nth 2 elem)
1606 permanent-flags (nth 3 elem)
1607 uidvalidity (nth 4 elem)
1608 vanished (nth 5 elem)
1609 highestmodseq (nth 6 elem)
1610 articles (nthcdr 7 elem))
1611 (let ((high (caar articles))
1613 (dolist (article articles)
1614 (setq low (car article))
1615 (push (car article) existing)
1616 (dolist (flag (cdr article))
1617 (setq mark (assoc flag marks))
1619 (push (list flag (car article)) marks)
1620 (setcdr mark (cons (car article) (cdr mark))))))
1621 (push (list group existing marks high low uidnext start-article
1622 permanent-flags uidvalidity vanished highestmodseq)
1626 (defun nnimap-parse-flags (sequences)
1627 (goto-char (point-min))
1628 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1630 (subst-char-in-region (point-min) (point-max)
1632 ;; Remove any MODSEQ entries in the buffer, because they may contain
1633 ;; numbers that are too large for 32-bit Emacsen.
1634 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1635 (replace-match "" t t))
1636 (goto-char (point-min))
1637 (let (start end articles groups uidnext elems permanent-flags
1638 uidvalidity vanished highestmodseq)
1639 (dolist (elem sequences)
1640 (destructuring-bind (group-sequence flag-sequence totalp group command)
1642 (setq start (point))
1644 ;; The EXAMINE was successful.
1645 (search-forward (format "\n%d OK " group-sequence) nil t)
1650 (setq permanent-flags
1651 (if (equal command "SELECT")
1652 (and (search-forward "PERMANENTFLAGS "
1653 (or end (point-min)) t)
1654 (read (current-buffer)))
1658 (and (search-forward "UIDNEXT "
1659 (or end (point-min)) t)
1660 (read (current-buffer))))
1663 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1664 (or end (point-min)) t)
1665 ;; Store UIDVALIDITY as a string, as it's
1666 ;; too big for 32-bit Emacsen, usually.
1670 (and (eq flag-sequence 'qresync)
1671 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1672 (or end (point-min)) t)
1676 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1677 (or end (point-min)) t)
1681 ;; The UID FETCH FLAGS was successful.
1682 (or (eq flag-sequence 'qresync)
1683 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1684 (if (eq flag-sequence 'qresync)
1688 (setq start (point))
1690 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1692 (setq elems (read (current-buffer)))
1693 (push (cons (cadr (memq 'UID elems))
1694 (cadr (memq 'FLAGS elems)))
1696 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1697 vanished highestmodseq)
1700 (if (eq flag-sequence 'qresync)
1703 (setq articles nil))))
1706 (defun nnimap-find-process-buffer (buffer)
1707 (cadr (assoc buffer nnimap-connection-alist)))
1709 (deffoo nnimap-request-post (&optional server)
1710 (setq nnimap-status-string "Read-only server")
1713 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1714 (declare-function gnus-fetch-headers "gnus-sum"
1715 (articles &optional limit force-new dependencies))
1717 (autoload 'nnir-search-thread "nnir")
1719 (deffoo nnimap-request-thread (header &optional group server)
1721 (setq group (nnimap-decode-gnus-group group)))
1722 (if gnus-refer-thread-use-nnir
1723 (nnir-search-thread header)
1724 (when (nnimap-change-group group server)
1725 (let* ((cmd (nnimap-make-thread-query header))
1726 (result (with-current-buffer (nnimap-buffer)
1727 (nnimap-command "UID SEARCH %s" cmd))))
1731 (delete 0 (mapcar #'string-to-number
1732 (cdr (assoc "SEARCH" (cdr result))))))
1735 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1736 "Change group to GROUP if non-nil.
1737 If SERVER is set, check that server is connected, otherwise retry
1738 to reconnect, unless NO-RECONNECT is set to t. Return nil if
1739 unsuccessful in connecting.
1740 If GROUP is nil, return t.
1741 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1742 Return the server's response to the SELECT or EXAMINE command."
1743 (let ((open-result t))
1745 (not (nnimap-server-opened server)))
1746 (setq open-result (nnimap-open-server server nil no-reconnect)))
1753 (with-current-buffer (nnimap-buffer)
1754 (let ((result (nnimap-command "%s %S"
1758 (utf7-encode group t))))
1760 (setf (nnimap-group nnimap-object) group
1761 (nnimap-select-result nnimap-object) result)
1764 (defun nnimap-find-connection (buffer)
1765 "Find the connection delivering to BUFFER."
1766 (let ((entry (assoc buffer nnimap-connection-alist)))
1768 (if (and (buffer-name (cadr entry))
1769 (get-buffer-process (cadr entry))
1770 (memq (process-status (get-buffer-process (cadr entry)))
1772 (get-buffer-process (cadr entry))
1773 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1776 (defvar nnimap-sequence 0)
1778 (defun nnimap-send-command (&rest args)
1779 (setf (nnimap-last-command-time nnimap-object) (current-time))
1780 (process-send-string
1781 (get-buffer-process (current-buffer))
1784 (incf nnimap-sequence)
1785 (apply #'format args)
1786 (if (nnimap-newlinep nnimap-object)
1789 ;; Some servers apparently can't have many outstanding
1790 ;; commands, so throttle them.
1791 (unless nnimap-streaming
1792 (nnimap-wait-for-response nnimap-sequence))
1795 (defvar nnimap-record-commands nil
1796 "If non-nil, log commands to the \"*imap log*\" buffer.")
1798 (defun nnimap-log-buffer ()
1799 (let ((name "*imap log*"))
1800 (or (get-buffer name)
1801 (with-current-buffer (get-buffer-create name)
1802 (when (boundp 'window-point-insertion-type)
1803 (make-local-variable 'window-point-insertion-type)
1804 (setq window-point-insertion-type t))
1805 (current-buffer)))))
1807 (defun nnimap-log-command (command)
1808 (when nnimap-record-commands
1809 (with-current-buffer (nnimap-log-buffer)
1810 (goto-char (point-max))
1811 (insert (format-time-string "%H:%M:%S")
1812 " [" nnimap-address "] "
1813 (if nnimap-inhibit-logging
1818 (defun nnimap-command (&rest args)
1820 (let* ((sequence (apply #'nnimap-send-command args))
1821 (response (nnimap-get-response sequence)))
1822 (if (equal (caar response) "OK")
1824 (nnheader-report 'nnimap "%s"
1825 (mapconcat (lambda (a)
1827 (car response) " "))
1830 (defun nnimap-get-response (sequence)
1831 (nnimap-wait-for-response sequence)
1832 (nnimap-parse-response))
1834 (defun nnimap-wait-for-connection (&optional regexp)
1835 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1837 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1838 (let ((process (get-buffer-process (current-buffer))))
1839 (goto-char (point-min))
1840 (while (and (memq (process-status process)
1842 (not (re-search-forward regexp nil t)))
1843 (nnheader-accept-process-output process)
1844 (goto-char (point-min)))
1846 (and (looking-at (or response-regexp regexp))
1849 (defun nnimap-wait-for-response (sequence &optional messagep)
1850 (let ((process (get-buffer-process (current-buffer)))
1854 (goto-char (point-max))
1855 (while (and (setq openp (memq (process-status process)
1858 ;; Skip past any "*" lines that the server has
1860 (while (and (not (bobp))
1863 (looking-at "\\*"))))
1864 (not (looking-at (format "%d .*\n" sequence)))))
1866 (nnheader-message-maybe
1867 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1869 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1870 (format " (initial sync of %d group%s; please wait)"
1871 (nnimap-initial-resync nnimap-object)
1872 (if (= (nnimap-initial-resync nnimap-object) 1)
1876 (nnheader-accept-process-output process)
1877 (goto-char (point-max)))
1878 (setf (nnimap-initial-resync nnimap-object) 0)
1883 ;; The user hit C-g while we were waiting: kill the process, in case
1884 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1886 (delete-process process)
1889 (defun nnimap-parse-response ()
1890 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1892 (dolist (line lines)
1893 (push (cdr (nnimap-parse-line line)) result))
1894 ;; Return the OK/error code first, and then all the "continuation
1895 ;; lines" afterwards.
1897 (nreverse result))))
1899 ;; Parse an IMAP response line lightly. They look like
1900 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1901 ;; the lines into a list of strings and lists of string.
1902 (defun nnimap-parse-line (line)
1905 (mm-disable-multibyte)
1907 (goto-char (point-min))
1909 (if (eql (setq char (following-char)) ? )
1917 (if (search-forward "]" (line-end-position) 'move)
1924 (if (search-forward ")" (line-end-position) 'move)
1931 (1- (or (search-forward "\"" (line-end-position) 'move)
1934 (buffer-substring (point) (if (search-forward " " nil t)
1936 (goto-char (point-max))))))
1938 (nreverse result))))
1940 (defun nnimap-last-response-string ()
1943 (let ((end (point)))
1947 (while (and (not (bobp))
1948 (eql (following-char) ?*))
1950 (unless (eql (following-char) ?*)
1952 (buffer-substring (point) end))))
1954 (defvar nnimap-incoming-split-list nil)
1956 (defun nnimap-fetch-inbox (articles)
1958 (nnimap-wait-for-response
1959 (nnimap-send-command
1961 (nnimap-article-ranges articles)
1962 (format "(UID %s%s)"
1968 (nnimap-split-download-body-default
1976 (defun nnimap-split-incoming-mail ()
1977 (with-current-buffer (nnimap-buffer)
1978 (let ((nnimap-incoming-split-list nil)
1979 (nnmail-split-methods
1981 ((eq nnimap-split-methods 'default)
1982 nnmail-split-methods)
1983 (nnimap-split-methods
1984 nnimap-split-methods)
1986 'nnmail-split-fancy)))
1987 (nnmail-split-fancy (or nnimap-split-fancy
1988 nnmail-split-fancy))
1989 (nnmail-inhibit-default-split-group t)
1990 (groups (nnimap-get-groups))
1993 (nnimap-command "SELECT %S" nnimap-inbox)
1994 (setf (nnimap-group nnimap-object) nnimap-inbox)
1995 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1997 (nnimap-fetch-inbox new-articles)
1998 (nnimap-transform-split-mail)
1999 (nnheader-ms-strip-cr)
2001 (nnmail-split-incoming (current-buffer)
2002 #'nnimap-save-mail-spec
2004 #'nnimap-dummy-active-number
2005 #'nnimap-save-mail-spec)
2006 (when nnimap-incoming-split-list
2007 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2008 sequences junk-articles)
2009 ;; Create any groups that doesn't already exist on the
2011 (dolist (spec specs)
2012 (when (and (not (member (car spec) groups))
2013 (not (eq (car spec) 'junk)))
2014 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2015 ;; Then copy over all the messages.
2017 (dolist (spec specs)
2018 (let ((group (car spec))
2019 (ranges (cdr spec)))
2020 (if (eq group 'junk)
2021 (setq junk-articles ranges)
2022 (push (list (nnimap-send-command
2024 (nnimap-article-ranges ranges)
2025 (utf7-encode group t))
2028 ;; Wait for the last COPY response...
2030 (nnimap-wait-for-response (caar sequences))
2031 ;; And then mark the successful copy actions as deleted,
2032 ;; and possibly expunge them.
2033 (nnimap-mark-and-expunge-incoming
2034 (nnimap-parse-copied-articles sequences)))
2035 (nnimap-mark-and-expunge-incoming junk-articles)))))))
2037 (defun nnimap-mark-and-expunge-incoming (range)
2039 (setq range (nnimap-article-ranges range))
2042 (nnimap-send-command
2043 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2045 ;; If the server supports it, we now delete the message we have
2046 ;; just copied over.
2047 ((nnimap-capability "UIDPLUS")
2048 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2049 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2050 ;; user has configured it.
2052 (setq sequence (nnimap-send-command "EXPUNGE"))))
2053 (nnimap-wait-for-response sequence))))
2055 (defun nnimap-parse-copied-articles (sequences)
2056 (let (sequence copied range)
2057 (goto-char (point-min))
2058 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2059 (setq sequence (string-to-number (match-string 1)))
2060 (when (setq range (cadr (assq sequence sequences)))
2061 (push (gnus-uncompress-range range) copied)))
2062 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2064 (defun nnimap-new-articles (flags)
2066 (dolist (elem flags)
2067 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2069 (push (car elem) new)))
2070 (gnus-compress-sequence (nreverse new))))
2072 (defun nnimap-make-split-specs (list)
2076 (destructuring-bind (article spec) elem
2077 (dolist (group (delete nil (mapcar #'car spec)))
2078 (unless (setq entry (assoc group specs))
2079 (push (setq entry (list group)) specs))
2080 (setcdr entry (cons article (cdr entry))))))
2081 (dolist (entry specs)
2082 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2085 (defun nnimap-transform-split-mail ()
2086 (goto-char (point-min))
2087 (let (article bytes)
2090 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2091 (delete-region (point) (progn (forward-line 1) (point)))
2094 (setq article (match-string 1)
2095 bytes (nnimap-get-length))
2096 (delete-region (line-beginning-position) (line-end-position))
2097 ;; Insert MMDF separator, and a way to remember what this
2099 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2100 (forward-char (1+ bytes))
2101 (setq bytes (nnimap-get-length))
2102 (delete-region (line-beginning-position) (line-end-position))
2103 ;; There's a body; skip past that.
2105 (forward-char (1+ bytes))
2106 (delete-region (line-beginning-position) (line-end-position)))))))
2108 (defun nnimap-dummy-active-number (group &optional server)
2111 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2113 (goto-char (point-min))
2114 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2115 (error "Invalid nnimap mail")
2116 (setq article (string-to-number (match-string 1))))
2118 (if (eq group-art 'junk)
2119 (list (cons 'junk 1))
2121 nnimap-incoming-split-list)))
2123 (defun nnimap-make-thread-query (header)
2124 (let* ((id (mail-header-id header))
2126 (or (mail-header-references header)
2130 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2132 (dolist (refid refs value)
2134 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2135 refid refid value)))))
2140 ;;; nnimap.el ends here