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 (deffoo nnimap-request-articles (articles &optional group server)
629 (setq group (nnimap-decode-gnus-group group)))
630 (with-current-buffer nntp-server-buffer
631 (let ((result (nnimap-change-group group server)))
634 (with-current-buffer (nnimap-buffer)
636 (when (nnimap-command
638 "UID FETCH %s BODY.PEEK[]"
639 "UID FETCH %s RFC822.PEEK")
640 (nnimap-article-ranges (gnus-compress-sequence articles)))
641 (let ((buffer (current-buffer)))
642 (with-current-buffer nntp-server-buffer
643 (nnheader-insert-buffer-substring buffer)
644 (nnheader-ms-strip-cr)))
647 (defun nnimap-get-whole-article (article &optional command)
652 "UID FETCH %d BODY.PEEK[]"
653 "UID FETCH %d RFC822.PEEK"))
655 ;; Check that we really got an article.
656 (goto-char (point-min))
657 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
660 ;; Remove any data that may have arrived before the FETCH data.
663 (delete-region (point-min) (point)))
664 (let ((bytes (nnimap-get-length)))
665 (delete-region (line-beginning-position)
666 (progn (forward-line 1) (point)))
667 (goto-char (+ (point) bytes))
668 (delete-region (point) (point-max)))
671 (defun nnimap-capability (capability)
672 (member capability (nnimap-capabilities nnimap-object)))
674 (defun nnimap-ver4-p ()
675 (nnimap-capability "IMAP4REV1"))
677 (defun nnimap-get-partial-article (article parts structure)
680 "UID FETCH %d (%s %s)"
686 (mapconcat (lambda (part)
687 (format "BODY.PEEK[%s]" part))
689 (mapconcat (lambda (part)
690 (format "RFC822.PEEK[%s]" part))
693 (nnimap-convert-partial-article structure))))
695 (defun nnimap-convert-partial-article (structure)
696 ;; First just skip past the headers.
697 (goto-char (point-min))
698 (let ((bytes (nnimap-get-length))
700 ;; Delete "FETCH" line.
701 (delete-region (line-beginning-position)
702 (progn (forward-line 1) (point)))
703 (goto-char (+ (point) bytes))
704 ;; Collect all the body parts.
705 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
706 (setq id (match-string 1)
707 bytes (or (nnimap-get-length) 0))
709 (delete-region (point) (progn (forward-line 1) (point)))
710 (push (list id (buffer-substring (point) (+ (point) bytes)))
712 (delete-region (point) (+ (point) bytes)))
713 ;; Delete trailing junk.
714 (delete-region (point) (point-max))
715 ;; Now insert all the parts again where they fit in the structure.
716 (nnimap-insert-partial-structure structure parts)
719 (defun nnimap-insert-partial-structure (structure parts &optional subp)
721 (let ((bstruc structure))
722 (while (consp (car bstruc))
724 (setq type (car bstruc))
725 (setq bstruc (car (cdr bstruc)))
726 (let ((has-boundary (member "boundary" bstruc)))
728 (setq boundary (cadr has-boundary)))))
730 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
731 (downcase type) boundary)))
732 (while (not (stringp (car structure)))
733 (insert "\n--" boundary "\n")
734 (if (consp (caar structure))
735 (nnimap-insert-partial-structure (pop structure) parts t)
736 (let ((bit (pop structure)))
737 (insert (format "Content-type: %s/%s"
738 (downcase (nth 0 bit))
739 (downcase (nth 1 bit))))
740 (if (member-ignore-case "CHARSET" (nth 2 bit))
743 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
745 (insert (format "Content-transfer-encoding: %s\n"
748 (when (assoc (nth 9 bit) parts)
749 (insert (cadr (assoc (nth 9 bit) parts)))))))
750 (insert "\n--" boundary "--\n")))
752 (defun nnimap-find-wanted-parts (structure)
753 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
755 (defun nnimap-find-wanted-parts-1 (structure prefix)
758 (while (consp (car structure))
759 (let ((sub (pop structure)))
760 (if (consp (car sub))
761 (push (nnimap-find-wanted-parts-1
762 sub (if (string= prefix "")
763 (number-to-string num)
764 (format "%s.%s" prefix num)))
766 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
767 (id (if (string= prefix "")
768 (number-to-string num)
769 (format "%s.%s" prefix num))))
770 (setcar (nthcdr 9 sub) id)
771 (when (if (eq nnimap-fetch-partial-articles t)
773 (string-match nnimap-fetch-partial-articles type))
778 (defun nnimap-decode-gnus-group (group)
779 (decode-coding-string group 'utf-8))
781 (deffoo nnimap-request-group (group &optional server dont-check info)
782 (setq group (nnimap-decode-gnus-group group))
783 (let ((result (nnimap-change-group
784 ;; Don't SELECT the group if we're going to select it
786 (if (and (not dont-check)
787 (assoc group nnimap-current-infos))
791 articles active marks high low)
792 (with-current-buffer nntp-server-buffer
795 (setq active (nth 2 (assoc group nnimap-current-infos))))
796 (insert (format "211 %d %d %d %S\n"
797 (- (cdr active) (car active))
801 (with-current-buffer (nnimap-buffer)
803 (let ((group-sequence
804 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
806 (nnimap-send-command "UID FETCH 1:* FLAGS")))
807 (setf (nnimap-group nnimap-object) group)
808 (nnimap-wait-for-response flag-sequence)
810 (nnimap-flags-to-marks
812 (list (list group-sequence flag-sequence
813 1 group "SELECT")))))
816 (nnimap-update-infos marks (list info))
817 (nnimap-store-info info (gnus-active (gnus-info-group info))))
818 (goto-char (point-max))
819 (let ((uidnext (nth 5 (car marks))))
820 (setq high (or (if uidnext
824 low (or (nth 4 (car marks)) uidnext 1)))))
828 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
831 (deffoo nnimap-request-create-group (group &optional server args)
832 (setq group (nnimap-decode-gnus-group group))
833 (when (nnimap-change-group nil server)
834 (with-current-buffer (nnimap-buffer)
835 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
837 (deffoo nnimap-request-delete-group (group &optional force server)
838 (setq group (nnimap-decode-gnus-group group))
839 (when (nnimap-change-group nil server)
840 (with-current-buffer (nnimap-buffer)
841 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
843 (deffoo nnimap-request-rename-group (group new-name &optional server)
844 (setq group (nnimap-decode-gnus-group group))
845 (when (nnimap-change-group nil server)
846 (with-current-buffer (nnimap-buffer)
847 (nnimap-unselect-group)
848 (car (nnimap-command "RENAME %S %S"
849 (utf7-encode group t) (utf7-encode new-name t))))))
851 (defun nnimap-unselect-group ()
852 ;; Make sure we don't have this group open read/write by asking
853 ;; to examine a mailbox that doesn't exist. This seems to be
854 ;; the only way that allows us to reliably go back to unselected
856 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
858 (deffoo nnimap-request-expunge-group (group &optional server)
859 (setq group (nnimap-decode-gnus-group group))
860 (when (nnimap-change-group group server)
861 (with-current-buffer (nnimap-buffer)
862 (car (nnimap-command "EXPUNGE")))))
864 (defun nnimap-get-flags (spec)
867 (with-current-buffer (nnimap-buffer)
869 (nnimap-wait-for-response (nnimap-send-command
870 "UID FETCH %s FLAGS" spec))
872 (subst-char-in-region (point-min) (point-max)
874 (goto-char (point-min))
875 (while (search-forward " FETCH " end t)
876 (setq elems (read (current-buffer)))
877 (push (cons (cadr (memq 'UID elems))
878 (cadr (memq 'FLAGS elems)))
880 (nreverse articles)))
882 (deffoo nnimap-close-group (group &optional server)
885 (deffoo nnimap-request-move-article (article group server accept-form
886 &optional last internal-move-group)
887 (setq group (nnimap-decode-gnus-group group))
888 (when internal-move-group
889 (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
891 (mm-disable-multibyte)
892 (when (funcall (if internal-move-group
894 'nnimap-request-article)
895 article group server (current-buffer))
896 ;; If the move is internal (on the same server), just do it the easy
898 (let ((message-id (message-field-value "message-id")))
899 (if internal-move-group
901 (with-current-buffer (nnimap-buffer)
902 (nnimap-command "UID COPY %d %S"
904 (utf7-encode internal-move-group t)))))
906 (nnimap-delete-article article)
907 (cons internal-move-group
908 (or (nnimap-find-uid-response "COPYUID" (cadr result))
909 (nnimap-find-article-by-message-id
910 internal-move-group server message-id
911 nnimap-request-articles-find-limit)))))
912 ;; Move the article to a different method.
913 (let ((result (eval accept-form)))
915 (nnimap-change-group group server)
916 (nnimap-delete-article article)
919 (deffoo nnimap-request-expire-articles (articles group &optional server force)
920 (setq group (nnimap-decode-gnus-group group))
924 ((not (nnimap-change-group group server))
927 (eq nnmail-expiry-target 'delete))
928 (unless (nnimap-delete-article (gnus-compress-sequence articles))
929 (nnheader-message 7 "Article marked for deletion, but not expunged."))
932 (let ((deletable-articles
934 (eq nnmail-expiry-wait 'immediate))
936 (gnus-sorted-intersection
938 (nnimap-find-expired-articles group)))))
939 (if (null deletable-articles)
941 (if (eq nnmail-expiry-target 'delete)
942 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
943 (setq deletable-articles
944 (nnimap-process-expiry-targets
945 deletable-articles group server)))
946 ;; Return the articles we didn't delete.
947 (gnus-sorted-complement articles deletable-articles))))))
949 (defun nnimap-process-expiry-targets (articles group server)
950 (let ((deleted-articles nil))
952 ;; shortcut further processing if we're going to delete the articles
953 ((eq nnmail-expiry-target 'delete)
954 (setq deleted-articles articles)
956 ;; or just move them to another folder on the same IMAP server
957 ((and (not (functionp nnmail-expiry-target))
958 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
959 (gnus-server-to-method
960 (format "nnimap:%s" server))))
961 (and (nnimap-change-group group server)
962 (with-current-buffer (nnimap-buffer)
963 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
966 (nnimap-article-ranges (gnus-compress-sequence articles))
967 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
968 (setq deleted-articles articles)))
971 (dolist (article articles)
972 (let ((target nnmail-expiry-target))
974 (mm-disable-multibyte)
975 (when (nnimap-request-article article group server (current-buffer))
976 (when (functionp target)
977 (setq target (funcall target group)))
979 (not (eq target 'delete)))
980 (if (or (gnus-request-group target t)
981 (gnus-request-create-group target))
983 (nnmail-expiry-target-group target group)
984 (nnheader-message 7 "Expiring article %s:%d to %s"
985 group article target))
987 (nnheader-message 7 "Expiring article %s:%d" group article))
989 (push article deleted-articles))))))))
990 ;; Change back to the current group again.
991 (nnimap-change-group group server)
992 (setq deleted-articles (nreverse deleted-articles))
993 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
996 (defun nnimap-find-expired-articles (group)
997 (let ((cutoff (nnmail-expired-article-p group nil nil)))
998 (with-current-buffer (nnimap-buffer)
1001 "UID SEARCH SENTBEFORE %s"
1003 (format "%%d-%s-%%Y"
1005 (car (rassoc (nth 4 (decode-time cutoff))
1006 parse-time-months))))
1009 (delete 0 (mapcar #'string-to-number
1010 (cdr (assoc "SEARCH" (cdr result))))))))))
1013 (defun nnimap-find-article-by-message-id (group server message-id
1015 "Search for message with MESSAGE-ID in GROUP from SERVER.
1016 If LIMIT, first try to limit the search to the N last articles."
1017 (with-current-buffer (nnimap-buffer)
1019 (let* ((change-group-result (nnimap-change-group group server nil t))
1021 (and (listp change-group-result)
1023 (dolist (result (cdr change-group-result))
1024 (when (equal "EXISTS" (cadr result))
1025 (throw 'found (car result)))))))
1027 (nnimap-send-command
1028 "UID SEARCH%s HEADER Message-Id %S"
1029 (if (and limit number-of-article)
1030 ;; The -1 is because IMAP message
1031 ;; numbers are one-based rather than
1033 (format " %s:*" (- (string-to-number number-of-article)
1037 (when (nnimap-wait-for-response sequence)
1038 (let ((article (car (last (cdr (assoc "SEARCH"
1039 (nnimap-parse-response)))))))
1041 (string-to-number article)
1042 (when (and limit number-of-article)
1043 (nnimap-find-article-by-message-id group server message-id))))))))
1045 (defun nnimap-delete-article (articles)
1046 (with-current-buffer (nnimap-buffer)
1047 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1048 (nnimap-article-ranges articles))
1050 ((nnimap-capability "UIDPLUS")
1051 (nnimap-command "UID EXPUNGE %s"
1052 (nnimap-article-ranges articles))
1055 (nnimap-command "EXPUNGE")
1057 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1058 "server doesn't support UIDPLUS, so we won't "
1059 "delete this article now"))))))
1061 (deffoo nnimap-request-scan (&optional group server)
1063 (setq group (nnimap-decode-gnus-group group)))
1064 (when (and (nnimap-change-group nil server)
1066 nnimap-split-methods)
1067 (nnheader-message 7 "nnimap %s splitting mail..." server)
1068 (if (listp nnimap-inbox)
1069 (dolist (nnimap-inbox nnimap-inbox)
1070 (nnimap-split-incoming-mail))
1071 (nnimap-split-incoming-mail))
1072 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1074 (defun nnimap-marks-to-flags (marks)
1076 (dolist (mark marks)
1077 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1081 (deffoo nnimap-request-update-group-status (group status &optional server)
1082 (setq group (nnimap-decode-gnus-group group))
1083 (when (nnimap-change-group nil server)
1084 (let ((command (assoc
1086 '((subscribe "SUBSCRIBE")
1087 (unsubscribe "UNSUBSCRIBE")))))
1089 (with-current-buffer (nnimap-buffer)
1090 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1092 (deffoo nnimap-request-set-mark (group actions &optional server)
1093 (setq group (nnimap-decode-gnus-group group))
1094 (when (nnimap-change-group group server)
1096 (with-current-buffer (nnimap-buffer)
1098 ;; Just send all the STORE commands without waiting for
1099 ;; response. If they're successful, they're successful.
1100 (dolist (action actions)
1101 (destructuring-bind (range action marks) action
1102 (let ((flags (nnimap-marks-to-flags marks)))
1104 (setq sequence (nnimap-send-command
1105 "UID STORE %s %sFLAGS.SILENT (%s)"
1106 (nnimap-article-ranges range)
1108 ((eq action 'del) "-")
1109 ((eq action 'add) "+")
1110 ((eq action 'set) ""))
1111 (mapconcat #'identity flags " ")))))))
1112 ;; Wait for the last command to complete to avoid later
1113 ;; synchronization problems with the stream.
1115 (nnimap-wait-for-response sequence))))))
1117 (deffoo nnimap-request-accept-article (group &optional server last)
1119 ;; We're respooling. Find out where mail splitting would place
1123 (nnmail-article-group
1125 (nnml-active-number group ,server))))))
1126 (setq group (nnimap-decode-gnus-group group))
1127 (when (nnimap-change-group nil server)
1128 (nnmail-check-syntax)
1129 (let ((message-id (message-field-value "message-id"))
1132 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1133 (with-current-buffer (nnimap-buffer)
1134 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1136 ;; If we have this group open read-only, then unselect it
1137 ;; before appending to it.
1138 (when (equal (nnimap-examined nnimap-object) group)
1139 (nnimap-unselect-group))
1141 (setq sequence (nnimap-send-command
1142 "APPEND %S {%d}" (utf7-encode group t)
1144 (unless nnimap-streaming
1145 (nnimap-wait-for-connection "^[+]"))
1146 (process-send-string (get-buffer-process (current-buffer)) message)
1147 (process-send-string (get-buffer-process (current-buffer))
1148 (if (nnimap-newlinep nnimap-object)
1151 (let ((result (nnimap-get-response sequence)))
1152 (if (not (nnimap-ok-p result))
1154 (nnheader-report 'nnimap "%s" result)
1157 (or (nnimap-find-uid-response "APPENDUID" (car result))
1158 (nnimap-find-article-by-message-id
1159 group server message-id
1160 nnimap-request-articles-find-limit))))))))))
1162 (defun nnimap-process-quirk (greeting-match type data)
1163 (when (and (nnimap-greeting nnimap-object)
1164 (string-match greeting-match (nnimap-greeting nnimap-object))
1166 (string-match "\000" data))
1167 (let ((choice (gnus-multiple-choice
1168 "Message contains NUL characters. Delete, continue, abort? "
1169 '((?d "Delete NUL characters")
1170 (?c "Try to APPEND the message as is")
1174 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1180 (goto-char (point-min))
1181 (while (search-forward "\000" nil t)
1182 (replace-match "" t t))
1183 (buffer-string)))))))
1185 (defun nnimap-ok-p (value)
1188 (equal (caar value) "OK")))
1190 (defun nnimap-find-uid-response (name list)
1191 (let ((result (car (last (nnimap-find-response-element name list)))))
1193 (string-to-number result))))
1195 (defun nnimap-find-response-element (name list)
1198 (when (and (consp elem)
1199 (equal name (car elem)))
1200 (setq result elem)))
1203 (deffoo nnimap-request-replace-article (article group buffer)
1204 (setq group (nnimap-decode-gnus-group group))
1206 (when (and (nnimap-change-group group)
1207 ;; Put the article into the group.
1208 (with-current-buffer buffer
1210 (nnimap-request-accept-article group nil t))))
1211 (nnimap-delete-article (list article))
1212 ;; Return the new article number.
1215 (defun nnimap-add-cr ()
1216 (goto-char (point-min))
1217 (while (re-search-forward "\r?\n" nil t)
1218 (replace-match "\r\n" t t)))
1220 (defun nnimap-get-groups ()
1222 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1224 (nnimap-wait-for-response sequence)
1225 (subst-char-in-region (point-min) (point-max)
1227 (goto-char (point-min))
1228 (nnimap-unfold-quoted-lines)
1229 (goto-char (point-min))
1230 (while (search-forward "* LIST " nil t)
1231 (let ((flags (read (current-buffer)))
1232 (separator (read (current-buffer)))
1233 (group (read (current-buffer))))
1234 (unless (member '%NoSelect flags)
1235 (push (utf7-decode (if (stringp group)
1237 (format "%s" group)) t)
1241 (defun nnimap-get-responses (sequences)
1243 (dolist (sequence sequences)
1244 (goto-char (point-min))
1245 (when (re-search-forward (format "^%d " sequence) nil t)
1246 (push (list sequence (nnimap-parse-response))
1250 (deffoo nnimap-request-list (&optional server)
1251 (when (nnimap-change-group nil server)
1252 (with-current-buffer nntp-server-buffer
1255 (with-current-buffer (nnimap-buffer)
1256 (nnimap-get-groups)))
1257 sequences responses)
1259 (with-current-buffer (nnimap-buffer)
1260 (setf (nnimap-group nnimap-object) nil)
1261 (dolist (group groups)
1262 (setf (nnimap-examined nnimap-object) group)
1263 (push (list (nnimap-send-command "EXAMINE %S"
1264 (utf7-encode group t))
1267 (nnimap-wait-for-response (caar sequences))
1269 (nnimap-get-responses (mapcar #'car sequences))))
1270 (dolist (response responses)
1271 (let* ((sequence (car response))
1272 (response (cadr response))
1273 (group (cadr (assoc sequence sequences)))
1274 (egroup (encode-coding-string group 'utf-8)))
1276 (equal (caar response) "OK"))
1277 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1279 (dolist (elem response)
1280 (when (equal (cadr elem) "EXISTS")
1281 (setq exists (string-to-number (car elem)))))
1283 (setq highest (1- (string-to-number (car uidnext)))))
1286 (insert (format "%S 0 1 y\n" egroup)))
1289 (insert (format "%S %d %d y\n" egroup
1290 highest (1+ highest))))
1292 ;; Return the widest possible range.
1293 (insert (format "%S %d 1 y\n" egroup
1294 (or highest exists)))))))))
1297 (deffoo nnimap-request-newgroups (date &optional server)
1298 (when (nnimap-change-group nil server)
1299 (with-current-buffer nntp-server-buffer
1301 (dolist (group (with-current-buffer (nnimap-buffer)
1302 (nnimap-get-groups)))
1303 (unless (assoc group nnimap-current-infos)
1304 ;; Insert dummy numbers here -- they don't matter.
1305 (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1308 (deffoo nnimap-retrieve-group-data-early (server infos)
1309 (when (and (nnimap-change-group nil server)
1311 (with-current-buffer (nnimap-buffer)
1313 (setf (nnimap-group nnimap-object) nil)
1314 (setf (nnimap-initial-resync nnimap-object) 0)
1315 (let ((qresyncp (nnimap-capability "QRESYNC"))
1316 params groups sequences active uidvalidity modseq group
1318 ;; Go through the infos and gather the data needed to know
1319 ;; what and how to request the data.
1320 (dolist (info infos)
1321 (setq params (gnus-info-params info)
1322 group (nnimap-decode-gnus-group
1323 (gnus-group-real-name (gnus-info-group info)))
1324 active (cdr (assq 'active params))
1325 unexist (assq 'unexist (gnus-info-marks info))
1326 uidvalidity (cdr (assq 'uidvalidity params))
1327 modseq (cdr (assq 'modseq params)))
1328 (setf (nnimap-examined nnimap-object) group)
1335 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1336 (utf7-encode group t)
1337 (nnimap-quirk "QRESYNC")
1345 ;; If we don't have a UIDVALIDITY, then this is
1346 ;; the first time we've seen the group, so we
1347 ;; have to do a SELECT (which is slower than an
1348 ;; examine), but will tell us whether the group
1349 ;; is read-only or not.
1352 (if (and active uidvalidity unexist)
1353 ;; Fetch the last 100 flags.
1354 (setq start (max 1 (- (cdr active) 100)))
1355 (incf (nnimap-initial-resync nnimap-object))
1357 (push (list (nnimap-send-command "%s %S" command
1358 (utf7-encode group t))
1359 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1360 start group command)
1364 (defun nnimap-quirk (command)
1365 (let ((quirk (assoc command nnimap-quirks)))
1366 ;; If this server is of a type that matches a quirk, then return
1367 ;; the "quirked" command instead of the proper one.
1368 (if (or (null quirk)
1369 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1373 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1374 (when (and sequences
1375 (nnimap-change-group nil server t)
1376 ;; Check that the process is still alive.
1377 (get-buffer-process (nnimap-buffer))
1378 (memq (process-status (get-buffer-process (nnimap-buffer)))
1380 (with-current-buffer (nnimap-buffer)
1381 ;; Wait for the final data to trickle in.
1382 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1386 ;; Now we should have most of the data we need, no matter
1387 ;; whether we're QRESYNCING, fetching all the flags from
1388 ;; scratch, or just fetching the last 100 flags per group.
1389 (nnimap-update-infos (nnimap-flags-to-marks
1391 (nreverse sequences)))
1393 ;; Finally, just return something resembling an active file in
1394 ;; the nntp buffer, so that the agent can save the info, too.
1395 (with-current-buffer nntp-server-buffer
1397 (dolist (info infos)
1398 (let* ((group (gnus-info-group info))
1399 (active (gnus-active group)))
1401 (insert (format "%S %d %d y\n"
1402 (decode-coding-string
1403 (gnus-group-real-name group) 'utf-8)
1405 (car active)))))))))))
1407 (defun nnimap-update-infos (flags infos)
1408 (dolist (info infos)
1409 (let* ((group (nnimap-decode-gnus-group
1410 (gnus-group-real-name (gnus-info-group info))))
1411 (marks (cdr (assoc group flags))))
1413 (nnimap-update-info info marks)))))
1415 (defun nnimap-update-info (info marks)
1416 (destructuring-bind (existing flags high low uidnext start-article
1417 permanent-flags uidvalidity
1418 vanished highestmodseq) marks
1420 ;; Ignore groups with no UIDNEXT/marks. This happens for
1421 ;; completely empty groups.
1422 ((and (not existing)
1424 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1426 (gnus-set-active (gnus-info-group info) active))))
1427 ;; We have a mismatch between the old and new UIDVALIDITY
1428 ;; identifiers, so we have to re-request the group info (the next
1429 ;; time). This virtually never happens.
1430 ((let ((old-uidvalidity
1431 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1432 (and old-uidvalidity
1433 (not (equal old-uidvalidity uidvalidity))
1434 (or (not start-article)
1435 (> start-article 1))))
1436 (gnus-group-remove-parameter info 'uidvalidity)
1437 (gnus-group-remove-parameter info 'modseq))
1438 ;; We have the data needed to update.
1440 (let* ((group (gnus-info-group info))
1441 (completep (and start-article
1442 (= start-article 1)))
1443 (active (or (gnus-active group)
1444 (cdr (assq 'active (gnus-info-params info))))))
1446 (setq high (1- uidnext)))
1447 ;; First set the active ranges based on high/low.
1449 (not (gnus-active group)))
1450 (gnus-set-active group
1453 (cons (min (or low (car active))
1455 (max (or high (cdr active))
1460 ;; No articles in this group.
1461 (cons uidnext (1- uidnext)))
1463 (cons start-article (1- start-article)))
1465 ;; No articles and no uidnext.
1467 (gnus-set-active group
1469 (or high (1- uidnext)))))
1470 ;; See whether this is a read-only group.
1471 (unless (eq permanent-flags 'not-scanned)
1472 (gnus-group-set-parameter
1473 info 'permanent-flags
1474 (and (or (memq '%* permanent-flags)
1475 (memq '%Seen permanent-flags))
1477 ;; Update marks and read articles if this isn't a
1478 ;; read-only IMAP group.
1479 (when (setq permanent-flags
1480 (cdr (assq 'permanent-flags (gnus-info-params info))))
1481 (if (and highestmodseq
1482 (not start-article))
1483 ;; We've gotten the data by QRESYNCing.
1484 (nnimap-update-qresync-info
1485 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1486 ;; Do normal non-QRESYNC flag updates.
1487 ;; Update the list of read articles.
1489 (gnus-compress-sequence
1490 (gnus-set-difference
1491 (gnus-set-difference
1494 (cdr (assoc '%Seen flags))
1495 (cdr (assoc '%Deleted flags))))
1496 (cdr (assoc '%Flagged flags)))))
1497 (read (gnus-range-difference
1498 (cons start-article high) unread)))
1499 (when (> start-article 1)
1502 (if (> start-article 1)
1503 (gnus-sorted-range-intersection
1504 (cons 1 (1- start-article))
1505 (gnus-info-read info))
1506 (gnus-info-read info))
1508 (when (or (not (listp permanent-flags))
1509 (memq '%Seen permanent-flags))
1510 (gnus-info-set-read info read))
1511 ;; Update the marks.
1512 (setq marks (gnus-info-marks info))
1513 (dolist (type (cdr nnimap-mark-alist))
1514 (when (or (not (listp permanent-flags))
1515 (memq (car (assoc (caddr type) flags))
1517 (memq '%* permanent-flags))
1518 (let ((old-marks (assoc (car type) marks))
1520 (gnus-compress-sequence
1521 (cdr (or (assoc (caddr type) flags) ; %Flagged
1522 (assoc (intern (cadr type) obarray) flags)
1523 (assoc (cadr type) flags)))))) ; "\Flagged"
1524 (setq marks (delq old-marks marks))
1526 (when (and old-marks
1527 (> start-article 1))
1528 (setq old-marks (gnus-range-difference
1530 (cons start-article high)))
1531 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1533 (push (cons (car type) new-marks) marks)))))
1534 ;; Keep track of non-existing articles.
1535 (let* ((old-unexists (assq 'unexist marks))
1536 (active (gnus-active group))
1539 (gnus-range-difference
1541 (gnus-compress-sequence existing))
1544 (gnus-list-range-difference
1545 existing (gnus-active group))))))
1546 (when (> (car active) 1)
1547 (setq unexists (gnus-range-add
1548 (cons 1 (1- (car active)))
1551 (setcdr old-unexists unexists)
1552 (push (cons 'unexist unexists) marks)))
1553 (gnus-info-set-marks info marks t))))
1554 ;; Tell Gnus whether there are any \Recent messages in any of
1556 (let ((recent (cdr (assoc '%Recent flags))))
1559 (> (car (last recent)) (cdr active)))
1560 (push (list (cons (gnus-group-real-name group) 0))
1561 nnmail-split-history)))
1562 ;; Note the active level for the next run-through.
1563 (gnus-group-set-parameter info 'active (gnus-active group))
1564 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1565 (gnus-group-set-parameter info 'modseq highestmodseq)
1566 (nnimap-store-info info (gnus-active group)))))))
1568 (defun nnimap-update-qresync-info (info existing vanished flags)
1569 ;; Add all the vanished articles to the list of read articles.
1574 (gnus-range-add (gnus-info-read info)
1576 (cdr (assq '%Flagged flags)))
1577 (cdr (assq '%Seen flags))))
1578 (let ((marks (gnus-info-marks info)))
1579 (dolist (type (cdr nnimap-mark-alist))
1580 (let ((ticks (assoc (car type) marks))
1582 (cdr (or (assoc (caddr type) flags) ; %Flagged
1583 (assoc (intern (cadr type) obarray) flags)
1584 (assoc (cadr type) flags))))) ; "\Flagged"
1585 (setq marks (delq ticks marks))
1587 ;; Add the new marks we got.
1588 (setq ticks (gnus-add-to-range ticks new-marks))
1589 ;; Remove the marks from messages that don't have them.
1590 (setq ticks (gnus-remove-from-range
1592 (gnus-compress-sequence
1593 (gnus-sorted-complement existing new-marks))))
1595 (push (cons (car type) ticks) marks)))
1596 (gnus-info-set-marks info marks t))
1597 ;; Add vanished to the list of unexisting articles.
1599 (let* ((old-unexists (assq 'unexist marks))
1600 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1602 (setcdr old-unexists unexists)
1603 (push (cons 'unexist unexists) marks)))
1604 (gnus-info-set-marks info marks t))))
1606 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1607 (if (zerop (length irange))
1610 (dolist (elem (split-string irange ","))
1612 (if (string-match ":" elem)
1613 (let ((numbers (split-string elem ":")))
1614 (cons (string-to-number (car numbers))
1615 (string-to-number (cadr numbers))))
1616 (string-to-number elem))
1618 (nreverse result))))
1620 (defun nnimap-store-info (info active)
1621 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1622 (entry (assoc group nnimap-current-infos)))
1624 (setcdr entry (list info active))
1625 (push (list group info active) nnimap-current-infos))))
1627 (defun nnimap-flags-to-marks (groups)
1628 (let (data group totalp uidnext articles start-article mark permanent-flags
1629 uidvalidity vanished highestmodseq)
1630 (dolist (elem groups)
1631 (setq group (car elem)
1632 uidnext (nth 1 elem)
1633 start-article (nth 2 elem)
1634 permanent-flags (nth 3 elem)
1635 uidvalidity (nth 4 elem)
1636 vanished (nth 5 elem)
1637 highestmodseq (nth 6 elem)
1638 articles (nthcdr 7 elem))
1639 (let ((high (caar articles))
1641 (dolist (article articles)
1642 (setq low (car article))
1643 (push (car article) existing)
1644 (dolist (flag (cdr article))
1645 (setq mark (assoc flag marks))
1647 (push (list flag (car article)) marks)
1648 (setcdr mark (cons (car article) (cdr mark))))))
1649 (push (list group existing marks high low uidnext start-article
1650 permanent-flags uidvalidity vanished highestmodseq)
1654 (defun nnimap-parse-flags (sequences)
1655 (goto-char (point-min))
1656 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1658 (subst-char-in-region (point-min) (point-max)
1660 ;; Remove any MODSEQ entries in the buffer, because they may contain
1661 ;; numbers that are too large for 32-bit Emacsen.
1662 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1663 (replace-match "" t t))
1664 (goto-char (point-min))
1665 (let (start end articles groups uidnext elems permanent-flags
1666 uidvalidity vanished highestmodseq)
1667 (dolist (elem sequences)
1668 (destructuring-bind (group-sequence flag-sequence totalp group command)
1670 (setq start (point))
1672 ;; The EXAMINE was successful.
1673 (search-forward (format "\n%d OK " group-sequence) nil t)
1678 (setq permanent-flags
1679 (if (equal command "SELECT")
1680 (and (search-forward "PERMANENTFLAGS "
1681 (or end (point-min)) t)
1682 (read (current-buffer)))
1686 (and (search-forward "UIDNEXT "
1687 (or end (point-min)) t)
1688 (read (current-buffer))))
1691 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1692 (or end (point-min)) t)
1693 ;; Store UIDVALIDITY as a string, as it's
1694 ;; too big for 32-bit Emacsen, usually.
1698 (and (eq flag-sequence 'qresync)
1699 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1700 (or end (point-min)) t)
1704 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1705 (or end (point-min)) t)
1709 ;; The UID FETCH FLAGS was successful.
1710 (or (eq flag-sequence 'qresync)
1711 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1712 (if (eq flag-sequence 'qresync)
1716 (setq start (point))
1718 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1720 (setq elems (read (current-buffer)))
1721 (push (cons (cadr (memq 'UID elems))
1722 (cadr (memq 'FLAGS elems)))
1724 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1725 vanished highestmodseq)
1728 (if (eq flag-sequence 'qresync)
1731 (setq articles nil))))
1734 (defun nnimap-find-process-buffer (buffer)
1735 (cadr (assoc buffer nnimap-connection-alist)))
1737 (deffoo nnimap-request-post (&optional server)
1738 (setq nnimap-status-string "Read-only server")
1741 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1742 (declare-function gnus-fetch-headers "gnus-sum"
1743 (articles &optional limit force-new dependencies))
1745 (autoload 'nnir-search-thread "nnir")
1747 (deffoo nnimap-request-thread (header &optional group server)
1749 (setq group (nnimap-decode-gnus-group group)))
1750 (if gnus-refer-thread-use-nnir
1751 (nnir-search-thread header)
1752 (when (nnimap-change-group group server)
1753 (let* ((cmd (nnimap-make-thread-query header))
1754 (result (with-current-buffer (nnimap-buffer)
1755 (nnimap-command "UID SEARCH %s" cmd))))
1759 (delete 0 (mapcar #'string-to-number
1760 (cdr (assoc "SEARCH" (cdr result))))))
1763 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1764 "Change group to GROUP if non-nil.
1765 If SERVER is set, check that server is connected, otherwise retry
1766 to reconnect, unless NO-RECONNECT is set to t. Return nil if
1767 unsuccessful in connecting.
1768 If GROUP is nil, return t.
1769 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1770 Return the server's response to the SELECT or EXAMINE command."
1771 (let ((open-result t))
1773 (not (nnimap-server-opened server)))
1774 (setq open-result (nnimap-open-server server nil no-reconnect)))
1781 (with-current-buffer (nnimap-buffer)
1782 (let ((result (nnimap-command "%s %S"
1786 (utf7-encode group t))))
1788 (setf (nnimap-group nnimap-object) group
1789 (nnimap-select-result nnimap-object) result)
1792 (defun nnimap-find-connection (buffer)
1793 "Find the connection delivering to BUFFER."
1794 (let ((entry (assoc buffer nnimap-connection-alist)))
1796 (if (and (buffer-name (cadr entry))
1797 (get-buffer-process (cadr entry))
1798 (memq (process-status (get-buffer-process (cadr entry)))
1800 (get-buffer-process (cadr entry))
1801 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1804 (defvar nnimap-sequence 0)
1806 (defun nnimap-send-command (&rest args)
1807 (setf (nnimap-last-command-time nnimap-object) (current-time))
1808 (process-send-string
1809 (get-buffer-process (current-buffer))
1812 (incf nnimap-sequence)
1813 (apply #'format args)
1814 (if (nnimap-newlinep nnimap-object)
1817 ;; Some servers apparently can't have many outstanding
1818 ;; commands, so throttle them.
1819 (unless nnimap-streaming
1820 (nnimap-wait-for-response nnimap-sequence))
1823 (defvar nnimap-record-commands nil
1824 "If non-nil, log commands to the \"*imap log*\" buffer.")
1826 (defun nnimap-log-buffer ()
1827 (let ((name "*imap log*"))
1828 (or (get-buffer name)
1829 (with-current-buffer (get-buffer-create name)
1830 (when (boundp 'window-point-insertion-type)
1831 (make-local-variable 'window-point-insertion-type)
1832 (setq window-point-insertion-type t))
1833 (current-buffer)))))
1835 (defun nnimap-log-command (command)
1836 (when nnimap-record-commands
1837 (with-current-buffer (nnimap-log-buffer)
1838 (goto-char (point-max))
1839 (insert (format-time-string "%H:%M:%S")
1840 " [" nnimap-address "] "
1841 (if nnimap-inhibit-logging
1846 (defun nnimap-command (&rest args)
1848 (let* ((sequence (apply #'nnimap-send-command args))
1849 (response (nnimap-get-response sequence)))
1850 (if (equal (caar response) "OK")
1852 (nnheader-report 'nnimap "%s"
1853 (mapconcat (lambda (a)
1855 (car response) " "))
1858 (defun nnimap-get-response (sequence)
1859 (nnimap-wait-for-response sequence)
1860 (nnimap-parse-response))
1862 (defun nnimap-wait-for-connection (&optional regexp)
1863 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1865 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1866 (let ((process (get-buffer-process (current-buffer))))
1867 (goto-char (point-min))
1868 (while (and (memq (process-status process)
1870 (not (re-search-forward regexp nil t)))
1871 (nnheader-accept-process-output process)
1872 (goto-char (point-min)))
1874 (and (looking-at (or response-regexp regexp))
1877 (defun nnimap-wait-for-response (sequence &optional messagep)
1878 (let ((process (get-buffer-process (current-buffer)))
1882 (goto-char (point-max))
1883 (while (and (setq openp (memq (process-status process)
1886 ;; Skip past any "*" lines that the server has
1888 (while (and (not (bobp))
1891 (looking-at "\\*"))))
1892 (not (looking-at (format "%d .*\n" sequence)))))
1894 (nnheader-message-maybe
1895 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1897 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1898 (format " (initial sync of %d group%s; please wait)"
1899 (nnimap-initial-resync nnimap-object)
1900 (if (= (nnimap-initial-resync nnimap-object) 1)
1904 (nnheader-accept-process-output process)
1905 (goto-char (point-max)))
1906 (setf (nnimap-initial-resync nnimap-object) 0)
1911 ;; The user hit C-g while we were waiting: kill the process, in case
1912 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1914 (delete-process process)
1917 (defun nnimap-parse-response ()
1918 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1920 (dolist (line lines)
1921 (push (cdr (nnimap-parse-line line)) result))
1922 ;; Return the OK/error code first, and then all the "continuation
1923 ;; lines" afterwards.
1925 (nreverse result))))
1927 ;; Parse an IMAP response line lightly. They look like
1928 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1929 ;; the lines into a list of strings and lists of string.
1930 (defun nnimap-parse-line (line)
1933 (mm-disable-multibyte)
1935 (goto-char (point-min))
1937 (if (eql (setq char (following-char)) ? )
1945 (if (search-forward "]" (line-end-position) 'move)
1952 (if (search-forward ")" (line-end-position) 'move)
1959 (1- (or (search-forward "\"" (line-end-position) 'move)
1962 (buffer-substring (point) (if (search-forward " " nil t)
1964 (goto-char (point-max))))))
1966 (nreverse result))))
1968 (defun nnimap-last-response-string ()
1971 (let ((end (point)))
1975 (while (and (not (bobp))
1976 (eql (following-char) ?*))
1978 (unless (eql (following-char) ?*)
1980 (buffer-substring (point) end))))
1982 (defvar nnimap-incoming-split-list nil)
1984 (defun nnimap-fetch-inbox (articles)
1986 (nnimap-wait-for-response
1987 (nnimap-send-command
1989 (nnimap-article-ranges articles)
1990 (format "(UID %s%s)"
1996 (nnimap-split-download-body-default
2004 (defun nnimap-split-incoming-mail ()
2005 (with-current-buffer (nnimap-buffer)
2006 (let ((nnimap-incoming-split-list nil)
2007 (nnmail-split-methods
2009 ((eq nnimap-split-methods 'default)
2010 nnmail-split-methods)
2011 (nnimap-split-methods
2012 nnimap-split-methods)
2014 'nnmail-split-fancy)))
2015 (nnmail-split-fancy (or nnimap-split-fancy
2016 nnmail-split-fancy))
2017 (nnmail-inhibit-default-split-group t)
2018 (groups (nnimap-get-groups))
2021 (nnimap-command "SELECT %S" nnimap-inbox)
2022 (setf (nnimap-group nnimap-object) nnimap-inbox)
2023 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2025 (nnimap-fetch-inbox new-articles)
2026 (nnimap-transform-split-mail)
2027 (nnheader-ms-strip-cr)
2029 (nnmail-split-incoming (current-buffer)
2030 #'nnimap-save-mail-spec
2032 #'nnimap-dummy-active-number
2033 #'nnimap-save-mail-spec)
2034 (when nnimap-incoming-split-list
2035 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2036 sequences junk-articles)
2037 ;; Create any groups that doesn't already exist on the
2039 (dolist (spec specs)
2040 (when (and (not (member (car spec) groups))
2041 (not (eq (car spec) 'junk)))
2042 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2043 ;; Then copy over all the messages.
2045 (dolist (spec specs)
2046 (let ((group (car spec))
2047 (ranges (cdr spec)))
2048 (if (eq group 'junk)
2049 (setq junk-articles ranges)
2050 (push (list (nnimap-send-command
2052 (nnimap-article-ranges ranges)
2053 (utf7-encode group t))
2056 ;; Wait for the last COPY response...
2058 (nnimap-wait-for-response (caar sequences))
2059 ;; And then mark the successful copy actions as deleted,
2060 ;; and possibly expunge them.
2061 (nnimap-mark-and-expunge-incoming
2062 (nnimap-parse-copied-articles sequences)))
2063 (nnimap-mark-and-expunge-incoming junk-articles)))))))
2065 (defun nnimap-mark-and-expunge-incoming (range)
2067 (setq range (nnimap-article-ranges range))
2070 (nnimap-send-command
2071 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2073 ;; If the server supports it, we now delete the message we have
2074 ;; just copied over.
2075 ((nnimap-capability "UIDPLUS")
2076 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2077 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2078 ;; user has configured it.
2080 (setq sequence (nnimap-send-command "EXPUNGE"))))
2081 (nnimap-wait-for-response sequence))))
2083 (defun nnimap-parse-copied-articles (sequences)
2084 (let (sequence copied range)
2085 (goto-char (point-min))
2086 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2087 (setq sequence (string-to-number (match-string 1)))
2088 (when (setq range (cadr (assq sequence sequences)))
2089 (push (gnus-uncompress-range range) copied)))
2090 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2092 (defun nnimap-new-articles (flags)
2094 (dolist (elem flags)
2095 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2097 (push (car elem) new)))
2098 (gnus-compress-sequence (nreverse new))))
2100 (defun nnimap-make-split-specs (list)
2104 (destructuring-bind (article spec) elem
2105 (dolist (group (delete nil (mapcar #'car spec)))
2106 (unless (setq entry (assoc group specs))
2107 (push (setq entry (list group)) specs))
2108 (setcdr entry (cons article (cdr entry))))))
2109 (dolist (entry specs)
2110 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2113 (defun nnimap-transform-split-mail ()
2114 (goto-char (point-min))
2115 (let (article bytes)
2118 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2119 (delete-region (point) (progn (forward-line 1) (point)))
2122 (setq article (match-string 1)
2123 bytes (nnimap-get-length))
2124 (delete-region (line-beginning-position) (line-end-position))
2125 ;; Insert MMDF separator, and a way to remember what this
2127 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2128 (forward-char (1+ bytes))
2129 (setq bytes (nnimap-get-length))
2130 (delete-region (line-beginning-position) (line-end-position))
2131 ;; There's a body; skip past that.
2133 (forward-char (1+ bytes))
2134 (delete-region (line-beginning-position) (line-end-position)))))))
2136 (defun nnimap-dummy-active-number (group &optional server)
2139 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2141 (goto-char (point-min))
2142 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2143 (error "Invalid nnimap mail")
2144 (setq article (string-to-number (match-string 1))))
2146 (if (eq group-art 'junk)
2147 (list (cons 'junk 1))
2149 nnimap-incoming-split-list)))
2151 (defun nnimap-make-thread-query (header)
2152 (let* ((id (mail-header-id header))
2154 (or (mail-header-references header)
2158 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2160 (dolist (refid refs value)
2162 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2163 refid refid value)))))
2168 ;;; nnimap.el ends here