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)
1118 (setq group (nnimap-decode-gnus-group group))
1119 (when (nnimap-change-group nil server)
1120 (nnmail-check-syntax)
1121 (let ((message-id (message-field-value "message-id"))
1124 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1125 (with-current-buffer (nnimap-buffer)
1126 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1128 ;; If we have this group open read-only, then unselect it
1129 ;; before appending to it.
1130 (when (equal (nnimap-examined nnimap-object) group)
1131 (nnimap-unselect-group))
1133 (setq sequence (nnimap-send-command
1134 "APPEND %S {%d}" (utf7-encode group t)
1136 (unless nnimap-streaming
1137 (nnimap-wait-for-connection "^[+]"))
1138 (process-send-string (get-buffer-process (current-buffer)) message)
1139 (process-send-string (get-buffer-process (current-buffer))
1140 (if (nnimap-newlinep nnimap-object)
1143 (let ((result (nnimap-get-response sequence)))
1144 (if (not (nnimap-ok-p result))
1146 (nnheader-report 'nnimap "%s" result)
1149 (or (nnimap-find-uid-response "APPENDUID" (car result))
1150 (nnimap-find-article-by-message-id
1151 group server message-id
1152 nnimap-request-articles-find-limit))))))))))
1154 (defun nnimap-process-quirk (greeting-match type data)
1155 (when (and (nnimap-greeting nnimap-object)
1156 (string-match greeting-match (nnimap-greeting nnimap-object))
1158 (string-match "\000" data))
1159 (let ((choice (gnus-multiple-choice
1160 "Message contains NUL characters. Delete, continue, abort? "
1161 '((?d "Delete NUL characters")
1162 (?c "Try to APPEND the message as is")
1166 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1172 (goto-char (point-min))
1173 (while (search-forward "\000" nil t)
1174 (replace-match "" t t))
1175 (buffer-string)))))))
1177 (defun nnimap-ok-p (value)
1180 (equal (caar value) "OK")))
1182 (defun nnimap-find-uid-response (name list)
1183 (let ((result (car (last (nnimap-find-response-element name list)))))
1185 (string-to-number result))))
1187 (defun nnimap-find-response-element (name list)
1190 (when (and (consp elem)
1191 (equal name (car elem)))
1192 (setq result elem)))
1195 (deffoo nnimap-request-replace-article (article group buffer)
1196 (setq group (nnimap-decode-gnus-group group))
1198 (when (and (nnimap-change-group group)
1199 ;; Put the article into the group.
1200 (with-current-buffer buffer
1202 (nnimap-request-accept-article group nil t))))
1203 (nnimap-delete-article (list article))
1204 ;; Return the new article number.
1207 (defun nnimap-add-cr ()
1208 (goto-char (point-min))
1209 (while (re-search-forward "\r?\n" nil t)
1210 (replace-match "\r\n" t t)))
1212 (defun nnimap-get-groups ()
1214 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1216 (nnimap-wait-for-response sequence)
1217 (subst-char-in-region (point-min) (point-max)
1219 (goto-char (point-min))
1220 (nnimap-unfold-quoted-lines)
1221 (goto-char (point-min))
1222 (while (search-forward "* LIST " nil t)
1223 (let ((flags (read (current-buffer)))
1224 (separator (read (current-buffer)))
1225 (group (read (current-buffer))))
1226 (unless (member '%NoSelect flags)
1227 (push (utf7-decode (if (stringp group)
1229 (format "%s" group)) t)
1233 (defun nnimap-get-responses (sequences)
1235 (dolist (sequence sequences)
1236 (goto-char (point-min))
1237 (when (re-search-forward (format "^%d " sequence) nil t)
1238 (push (list sequence (nnimap-parse-response))
1242 (deffoo nnimap-request-list (&optional server)
1243 (when (nnimap-change-group nil server)
1244 (with-current-buffer nntp-server-buffer
1247 (with-current-buffer (nnimap-buffer)
1248 (nnimap-get-groups)))
1249 sequences responses)
1251 (with-current-buffer (nnimap-buffer)
1252 (setf (nnimap-group nnimap-object) nil)
1253 (dolist (group groups)
1254 (setf (nnimap-examined nnimap-object) group)
1255 (push (list (nnimap-send-command "EXAMINE %S"
1256 (utf7-encode group t))
1259 (nnimap-wait-for-response (caar sequences))
1261 (nnimap-get-responses (mapcar #'car sequences))))
1262 (dolist (response responses)
1263 (let* ((sequence (car response))
1264 (response (cadr response))
1265 (group (cadr (assoc sequence sequences)))
1266 (egroup (encode-coding-string group 'utf-8)))
1268 (equal (caar response) "OK"))
1269 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1271 (dolist (elem response)
1272 (when (equal (cadr elem) "EXISTS")
1273 (setq exists (string-to-number (car elem)))))
1275 (setq highest (1- (string-to-number (car uidnext)))))
1278 (insert (format "%S 0 1 y\n" egroup)))
1281 (insert (format "%S %d %d y\n" egroup
1282 highest (1+ highest))))
1284 ;; Return the widest possible range.
1285 (insert (format "%S %d 1 y\n" egroup
1286 (or highest exists)))))))))
1289 (deffoo nnimap-request-newgroups (date &optional server)
1290 (when (nnimap-change-group nil server)
1291 (with-current-buffer nntp-server-buffer
1293 (dolist (group (with-current-buffer (nnimap-buffer)
1294 (nnimap-get-groups)))
1295 (unless (assoc group nnimap-current-infos)
1296 ;; Insert dummy numbers here -- they don't matter.
1297 (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1300 (deffoo nnimap-retrieve-group-data-early (server infos)
1301 (when (and (nnimap-change-group nil server)
1303 (with-current-buffer (nnimap-buffer)
1305 (setf (nnimap-group nnimap-object) nil)
1306 (setf (nnimap-initial-resync nnimap-object) 0)
1307 (let ((qresyncp (nnimap-capability "QRESYNC"))
1308 params groups sequences active uidvalidity modseq group
1310 ;; Go through the infos and gather the data needed to know
1311 ;; what and how to request the data.
1312 (dolist (info infos)
1313 (setq params (gnus-info-params info)
1314 group (nnimap-decode-gnus-group
1315 (gnus-group-real-name (gnus-info-group info)))
1316 active (cdr (assq 'active params))
1317 unexist (assq 'unexist (gnus-info-marks info))
1318 uidvalidity (cdr (assq 'uidvalidity params))
1319 modseq (cdr (assq 'modseq params)))
1320 (setf (nnimap-examined nnimap-object) group)
1327 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1328 (utf7-encode group t)
1329 (nnimap-quirk "QRESYNC")
1337 ;; If we don't have a UIDVALIDITY, then this is
1338 ;; the first time we've seen the group, so we
1339 ;; have to do a SELECT (which is slower than an
1340 ;; examine), but will tell us whether the group
1341 ;; is read-only or not.
1344 (if (and active uidvalidity unexist)
1345 ;; Fetch the last 100 flags.
1346 (setq start (max 1 (- (cdr active) 100)))
1347 (incf (nnimap-initial-resync nnimap-object))
1349 (push (list (nnimap-send-command "%s %S" command
1350 (utf7-encode group t))
1351 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1352 start group command)
1356 (defun nnimap-quirk (command)
1357 (let ((quirk (assoc command nnimap-quirks)))
1358 ;; If this server is of a type that matches a quirk, then return
1359 ;; the "quirked" command instead of the proper one.
1360 (if (or (null quirk)
1361 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1365 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1366 (when (and sequences
1367 (nnimap-change-group nil server t)
1368 ;; Check that the process is still alive.
1369 (get-buffer-process (nnimap-buffer))
1370 (memq (process-status (get-buffer-process (nnimap-buffer)))
1372 (with-current-buffer (nnimap-buffer)
1373 ;; Wait for the final data to trickle in.
1374 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1378 ;; Now we should have most of the data we need, no matter
1379 ;; whether we're QRESYNCING, fetching all the flags from
1380 ;; scratch, or just fetching the last 100 flags per group.
1381 (nnimap-update-infos (nnimap-flags-to-marks
1383 (nreverse sequences)))
1385 ;; Finally, just return something resembling an active file in
1386 ;; the nntp buffer, so that the agent can save the info, too.
1387 (with-current-buffer nntp-server-buffer
1389 (dolist (info infos)
1390 (let* ((group (gnus-info-group info))
1391 (active (gnus-active group)))
1393 (insert (format "%S %d %d y\n"
1394 (decode-coding-string
1395 (gnus-group-real-name group) 'utf-8)
1397 (car active)))))))))))
1399 (defun nnimap-update-infos (flags infos)
1400 (dolist (info infos)
1401 (let* ((group (nnimap-decode-gnus-group
1402 (gnus-group-real-name (gnus-info-group info))))
1403 (marks (cdr (assoc group flags))))
1405 (nnimap-update-info info marks)))))
1407 (defun nnimap-update-info (info marks)
1408 (destructuring-bind (existing flags high low uidnext start-article
1409 permanent-flags uidvalidity
1410 vanished highestmodseq) marks
1412 ;; Ignore groups with no UIDNEXT/marks. This happens for
1413 ;; completely empty groups.
1414 ((and (not existing)
1416 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1418 (gnus-set-active (gnus-info-group info) active))))
1419 ;; We have a mismatch between the old and new UIDVALIDITY
1420 ;; identifiers, so we have to re-request the group info (the next
1421 ;; time). This virtually never happens.
1422 ((let ((old-uidvalidity
1423 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1424 (and old-uidvalidity
1425 (not (equal old-uidvalidity uidvalidity))
1426 (or (not start-article)
1427 (> start-article 1))))
1428 (gnus-group-remove-parameter info 'uidvalidity)
1429 (gnus-group-remove-parameter info 'modseq))
1430 ;; We have the data needed to update.
1432 (let* ((group (gnus-info-group info))
1433 (completep (and start-article
1434 (= start-article 1)))
1435 (active (or (gnus-active group)
1436 (cdr (assq 'active (gnus-info-params info))))))
1438 (setq high (1- uidnext)))
1439 ;; First set the active ranges based on high/low.
1441 (not (gnus-active group)))
1442 (gnus-set-active group
1445 (cons (min (or low (car active))
1447 (max (or high (cdr active))
1452 ;; No articles in this group.
1453 (cons uidnext (1- uidnext)))
1455 (cons start-article (1- start-article)))
1457 ;; No articles and no uidnext.
1459 (gnus-set-active group
1461 (or high (1- uidnext)))))
1462 ;; See whether this is a read-only group.
1463 (unless (eq permanent-flags 'not-scanned)
1464 (gnus-group-set-parameter
1465 info 'permanent-flags
1466 (and (or (memq '%* permanent-flags)
1467 (memq '%Seen permanent-flags))
1469 ;; Update marks and read articles if this isn't a
1470 ;; read-only IMAP group.
1471 (when (setq permanent-flags
1472 (cdr (assq 'permanent-flags (gnus-info-params info))))
1473 (if (and highestmodseq
1474 (not start-article))
1475 ;; We've gotten the data by QRESYNCing.
1476 (nnimap-update-qresync-info
1477 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1478 ;; Do normal non-QRESYNC flag updates.
1479 ;; Update the list of read articles.
1481 (gnus-compress-sequence
1482 (gnus-set-difference
1483 (gnus-set-difference
1486 (cdr (assoc '%Seen flags))
1487 (cdr (assoc '%Deleted flags))))
1488 (cdr (assoc '%Flagged flags)))))
1489 (read (gnus-range-difference
1490 (cons start-article high) unread)))
1491 (when (> start-article 1)
1494 (if (> start-article 1)
1495 (gnus-sorted-range-intersection
1496 (cons 1 (1- start-article))
1497 (gnus-info-read info))
1498 (gnus-info-read info))
1500 (when (or (not (listp permanent-flags))
1501 (memq '%Seen permanent-flags))
1502 (gnus-info-set-read info read))
1503 ;; Update the marks.
1504 (setq marks (gnus-info-marks info))
1505 (dolist (type (cdr nnimap-mark-alist))
1506 (when (or (not (listp permanent-flags))
1507 (memq (car (assoc (caddr type) flags))
1509 (memq '%* permanent-flags))
1510 (let ((old-marks (assoc (car type) marks))
1512 (gnus-compress-sequence
1513 (cdr (or (assoc (caddr type) flags) ; %Flagged
1514 (assoc (intern (cadr type) obarray) flags)
1515 (assoc (cadr type) flags)))))) ; "\Flagged"
1516 (setq marks (delq old-marks marks))
1518 (when (and old-marks
1519 (> start-article 1))
1520 (setq old-marks (gnus-range-difference
1522 (cons start-article high)))
1523 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1525 (push (cons (car type) new-marks) marks)))))
1526 ;; Keep track of non-existing articles.
1527 (let* ((old-unexists (assq 'unexist marks))
1528 (active (gnus-active group))
1531 (gnus-range-difference
1533 (gnus-compress-sequence existing))
1536 (gnus-list-range-difference
1537 existing (gnus-active group))))))
1538 (when (> (car active) 1)
1539 (setq unexists (gnus-range-add
1540 (cons 1 (1- (car active)))
1543 (setcdr old-unexists unexists)
1544 (push (cons 'unexist unexists) marks)))
1545 (gnus-info-set-marks info marks t))))
1546 ;; Tell Gnus whether there are any \Recent messages in any of
1548 (let ((recent (cdr (assoc '%Recent flags))))
1551 (> (car (last recent)) (cdr active)))
1552 (push (list (cons (gnus-group-real-name group) 0))
1553 nnmail-split-history)))
1554 ;; Note the active level for the next run-through.
1555 (gnus-group-set-parameter info 'active (gnus-active group))
1556 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1557 (gnus-group-set-parameter info 'modseq highestmodseq)
1558 (nnimap-store-info info (gnus-active group)))))))
1560 (defun nnimap-update-qresync-info (info existing vanished flags)
1561 ;; Add all the vanished articles to the list of read articles.
1566 (gnus-range-add (gnus-info-read info)
1568 (cdr (assq '%Flagged flags)))
1569 (cdr (assq '%Seen flags))))
1570 (let ((marks (gnus-info-marks info)))
1571 (dolist (type (cdr nnimap-mark-alist))
1572 (let ((ticks (assoc (car type) marks))
1574 (cdr (or (assoc (caddr type) flags) ; %Flagged
1575 (assoc (intern (cadr type) obarray) flags)
1576 (assoc (cadr type) flags))))) ; "\Flagged"
1577 (setq marks (delq ticks marks))
1579 ;; Add the new marks we got.
1580 (setq ticks (gnus-add-to-range ticks new-marks))
1581 ;; Remove the marks from messages that don't have them.
1582 (setq ticks (gnus-remove-from-range
1584 (gnus-compress-sequence
1585 (gnus-sorted-complement existing new-marks))))
1587 (push (cons (car type) ticks) marks)))
1588 (gnus-info-set-marks info marks t))
1589 ;; Add vanished to the list of unexisting articles.
1591 (let* ((old-unexists (assq 'unexist marks))
1592 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1594 (setcdr old-unexists unexists)
1595 (push (cons 'unexist unexists) marks)))
1596 (gnus-info-set-marks info marks t))))
1598 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1599 (if (zerop (length irange))
1602 (dolist (elem (split-string irange ","))
1604 (if (string-match ":" elem)
1605 (let ((numbers (split-string elem ":")))
1606 (cons (string-to-number (car numbers))
1607 (string-to-number (cadr numbers))))
1608 (string-to-number elem))
1610 (nreverse result))))
1612 (defun nnimap-store-info (info active)
1613 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1614 (entry (assoc group nnimap-current-infos)))
1616 (setcdr entry (list info active))
1617 (push (list group info active) nnimap-current-infos))))
1619 (defun nnimap-flags-to-marks (groups)
1620 (let (data group totalp uidnext articles start-article mark permanent-flags
1621 uidvalidity vanished highestmodseq)
1622 (dolist (elem groups)
1623 (setq group (car elem)
1624 uidnext (nth 1 elem)
1625 start-article (nth 2 elem)
1626 permanent-flags (nth 3 elem)
1627 uidvalidity (nth 4 elem)
1628 vanished (nth 5 elem)
1629 highestmodseq (nth 6 elem)
1630 articles (nthcdr 7 elem))
1631 (let ((high (caar articles))
1633 (dolist (article articles)
1634 (setq low (car article))
1635 (push (car article) existing)
1636 (dolist (flag (cdr article))
1637 (setq mark (assoc flag marks))
1639 (push (list flag (car article)) marks)
1640 (setcdr mark (cons (car article) (cdr mark))))))
1641 (push (list group existing marks high low uidnext start-article
1642 permanent-flags uidvalidity vanished highestmodseq)
1646 (defun nnimap-parse-flags (sequences)
1647 (goto-char (point-min))
1648 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1650 (subst-char-in-region (point-min) (point-max)
1652 ;; Remove any MODSEQ entries in the buffer, because they may contain
1653 ;; numbers that are too large for 32-bit Emacsen.
1654 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1655 (replace-match "" t t))
1656 (goto-char (point-min))
1657 (let (start end articles groups uidnext elems permanent-flags
1658 uidvalidity vanished highestmodseq)
1659 (dolist (elem sequences)
1660 (destructuring-bind (group-sequence flag-sequence totalp group command)
1662 (setq start (point))
1664 ;; The EXAMINE was successful.
1665 (search-forward (format "\n%d OK " group-sequence) nil t)
1670 (setq permanent-flags
1671 (if (equal command "SELECT")
1672 (and (search-forward "PERMANENTFLAGS "
1673 (or end (point-min)) t)
1674 (read (current-buffer)))
1678 (and (search-forward "UIDNEXT "
1679 (or end (point-min)) t)
1680 (read (current-buffer))))
1683 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1684 (or end (point-min)) t)
1685 ;; Store UIDVALIDITY as a string, as it's
1686 ;; too big for 32-bit Emacsen, usually.
1690 (and (eq flag-sequence 'qresync)
1691 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1692 (or end (point-min)) t)
1696 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1697 (or end (point-min)) t)
1701 ;; The UID FETCH FLAGS was successful.
1702 (or (eq flag-sequence 'qresync)
1703 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1704 (if (eq flag-sequence 'qresync)
1708 (setq start (point))
1710 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1712 (setq elems (read (current-buffer)))
1713 (push (cons (cadr (memq 'UID elems))
1714 (cadr (memq 'FLAGS elems)))
1716 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1717 vanished highestmodseq)
1720 (if (eq flag-sequence 'qresync)
1723 (setq articles nil))))
1726 (defun nnimap-find-process-buffer (buffer)
1727 (cadr (assoc buffer nnimap-connection-alist)))
1729 (deffoo nnimap-request-post (&optional server)
1730 (setq nnimap-status-string "Read-only server")
1733 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1734 (declare-function gnus-fetch-headers "gnus-sum"
1735 (articles &optional limit force-new dependencies))
1737 (autoload 'nnir-search-thread "nnir")
1739 (deffoo nnimap-request-thread (header &optional group server)
1741 (setq group (nnimap-decode-gnus-group group)))
1742 (if gnus-refer-thread-use-nnir
1743 (nnir-search-thread header)
1744 (when (nnimap-change-group group server)
1745 (let* ((cmd (nnimap-make-thread-query header))
1746 (result (with-current-buffer (nnimap-buffer)
1747 (nnimap-command "UID SEARCH %s" cmd))))
1751 (delete 0 (mapcar #'string-to-number
1752 (cdr (assoc "SEARCH" (cdr result))))))
1755 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1756 "Change group to GROUP if non-nil.
1757 If SERVER is set, check that server is connected, otherwise retry
1758 to reconnect, unless NO-RECONNECT is set to t. Return nil if
1759 unsuccessful in connecting.
1760 If GROUP is nil, return t.
1761 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1762 Return the server's response to the SELECT or EXAMINE command."
1763 (let ((open-result t))
1765 (not (nnimap-server-opened server)))
1766 (setq open-result (nnimap-open-server server nil no-reconnect)))
1773 (with-current-buffer (nnimap-buffer)
1774 (let ((result (nnimap-command "%s %S"
1778 (utf7-encode group t))))
1780 (setf (nnimap-group nnimap-object) group
1781 (nnimap-select-result nnimap-object) result)
1784 (defun nnimap-find-connection (buffer)
1785 "Find the connection delivering to BUFFER."
1786 (let ((entry (assoc buffer nnimap-connection-alist)))
1788 (if (and (buffer-name (cadr entry))
1789 (get-buffer-process (cadr entry))
1790 (memq (process-status (get-buffer-process (cadr entry)))
1792 (get-buffer-process (cadr entry))
1793 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1796 (defvar nnimap-sequence 0)
1798 (defun nnimap-send-command (&rest args)
1799 (setf (nnimap-last-command-time nnimap-object) (current-time))
1800 (process-send-string
1801 (get-buffer-process (current-buffer))
1804 (incf nnimap-sequence)
1805 (apply #'format args)
1806 (if (nnimap-newlinep nnimap-object)
1809 ;; Some servers apparently can't have many outstanding
1810 ;; commands, so throttle them.
1811 (unless nnimap-streaming
1812 (nnimap-wait-for-response nnimap-sequence))
1815 (defvar nnimap-record-commands nil
1816 "If non-nil, log commands to the \"*imap log*\" buffer.")
1818 (defun nnimap-log-buffer ()
1819 (let ((name "*imap log*"))
1820 (or (get-buffer name)
1821 (with-current-buffer (get-buffer-create name)
1822 (when (boundp 'window-point-insertion-type)
1823 (make-local-variable 'window-point-insertion-type)
1824 (setq window-point-insertion-type t))
1825 (current-buffer)))))
1827 (defun nnimap-log-command (command)
1828 (when nnimap-record-commands
1829 (with-current-buffer (nnimap-log-buffer)
1830 (goto-char (point-max))
1831 (insert (format-time-string "%H:%M:%S")
1832 " [" nnimap-address "] "
1833 (if nnimap-inhibit-logging
1838 (defun nnimap-command (&rest args)
1840 (let* ((sequence (apply #'nnimap-send-command args))
1841 (response (nnimap-get-response sequence)))
1842 (if (equal (caar response) "OK")
1844 (nnheader-report 'nnimap "%s"
1845 (mapconcat (lambda (a)
1847 (car response) " "))
1850 (defun nnimap-get-response (sequence)
1851 (nnimap-wait-for-response sequence)
1852 (nnimap-parse-response))
1854 (defun nnimap-wait-for-connection (&optional regexp)
1855 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1857 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1858 (let ((process (get-buffer-process (current-buffer))))
1859 (goto-char (point-min))
1860 (while (and (memq (process-status process)
1862 (not (re-search-forward regexp nil t)))
1863 (nnheader-accept-process-output process)
1864 (goto-char (point-min)))
1866 (and (looking-at (or response-regexp regexp))
1869 (defun nnimap-wait-for-response (sequence &optional messagep)
1870 (let ((process (get-buffer-process (current-buffer)))
1874 (goto-char (point-max))
1875 (while (and (setq openp (memq (process-status process)
1878 ;; Skip past any "*" lines that the server has
1880 (while (and (not (bobp))
1883 (looking-at "\\*"))))
1884 (not (looking-at (format "%d .*\n" sequence)))))
1886 (nnheader-message-maybe
1887 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1889 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1890 (format " (initial sync of %d group%s; please wait)"
1891 (nnimap-initial-resync nnimap-object)
1892 (if (= (nnimap-initial-resync nnimap-object) 1)
1896 (nnheader-accept-process-output process)
1897 (goto-char (point-max)))
1898 (setf (nnimap-initial-resync nnimap-object) 0)
1903 ;; The user hit C-g while we were waiting: kill the process, in case
1904 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1906 (delete-process process)
1909 (defun nnimap-parse-response ()
1910 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1912 (dolist (line lines)
1913 (push (cdr (nnimap-parse-line line)) result))
1914 ;; Return the OK/error code first, and then all the "continuation
1915 ;; lines" afterwards.
1917 (nreverse result))))
1919 ;; Parse an IMAP response line lightly. They look like
1920 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1921 ;; the lines into a list of strings and lists of string.
1922 (defun nnimap-parse-line (line)
1925 (mm-disable-multibyte)
1927 (goto-char (point-min))
1929 (if (eql (setq char (following-char)) ? )
1937 (if (search-forward "]" (line-end-position) 'move)
1944 (if (search-forward ")" (line-end-position) 'move)
1951 (1- (or (search-forward "\"" (line-end-position) 'move)
1954 (buffer-substring (point) (if (search-forward " " nil t)
1956 (goto-char (point-max))))))
1958 (nreverse result))))
1960 (defun nnimap-last-response-string ()
1963 (let ((end (point)))
1967 (while (and (not (bobp))
1968 (eql (following-char) ?*))
1970 (unless (eql (following-char) ?*)
1972 (buffer-substring (point) end))))
1974 (defvar nnimap-incoming-split-list nil)
1976 (defun nnimap-fetch-inbox (articles)
1978 (nnimap-wait-for-response
1979 (nnimap-send-command
1981 (nnimap-article-ranges articles)
1982 (format "(UID %s%s)"
1988 (nnimap-split-download-body-default
1996 (defun nnimap-split-incoming-mail ()
1997 (with-current-buffer (nnimap-buffer)
1998 (let ((nnimap-incoming-split-list nil)
1999 (nnmail-split-methods
2001 ((eq nnimap-split-methods 'default)
2002 nnmail-split-methods)
2003 (nnimap-split-methods
2004 nnimap-split-methods)
2006 'nnmail-split-fancy)))
2007 (nnmail-split-fancy (or nnimap-split-fancy
2008 nnmail-split-fancy))
2009 (nnmail-inhibit-default-split-group t)
2010 (groups (nnimap-get-groups))
2013 (nnimap-command "SELECT %S" nnimap-inbox)
2014 (setf (nnimap-group nnimap-object) nnimap-inbox)
2015 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2017 (nnimap-fetch-inbox new-articles)
2018 (nnimap-transform-split-mail)
2019 (nnheader-ms-strip-cr)
2021 (nnmail-split-incoming (current-buffer)
2022 #'nnimap-save-mail-spec
2024 #'nnimap-dummy-active-number
2025 #'nnimap-save-mail-spec)
2026 (when nnimap-incoming-split-list
2027 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2028 sequences junk-articles)
2029 ;; Create any groups that doesn't already exist on the
2031 (dolist (spec specs)
2032 (when (and (not (member (car spec) groups))
2033 (not (eq (car spec) 'junk)))
2034 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2035 ;; Then copy over all the messages.
2037 (dolist (spec specs)
2038 (let ((group (car spec))
2039 (ranges (cdr spec)))
2040 (if (eq group 'junk)
2041 (setq junk-articles ranges)
2042 (push (list (nnimap-send-command
2044 (nnimap-article-ranges ranges)
2045 (utf7-encode group t))
2048 ;; Wait for the last COPY response...
2050 (nnimap-wait-for-response (caar sequences))
2051 ;; And then mark the successful copy actions as deleted,
2052 ;; and possibly expunge them.
2053 (nnimap-mark-and-expunge-incoming
2054 (nnimap-parse-copied-articles sequences)))
2055 (nnimap-mark-and-expunge-incoming junk-articles)))))))
2057 (defun nnimap-mark-and-expunge-incoming (range)
2059 (setq range (nnimap-article-ranges range))
2062 (nnimap-send-command
2063 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2065 ;; If the server supports it, we now delete the message we have
2066 ;; just copied over.
2067 ((nnimap-capability "UIDPLUS")
2068 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2069 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2070 ;; user has configured it.
2072 (setq sequence (nnimap-send-command "EXPUNGE"))))
2073 (nnimap-wait-for-response sequence))))
2075 (defun nnimap-parse-copied-articles (sequences)
2076 (let (sequence copied range)
2077 (goto-char (point-min))
2078 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2079 (setq sequence (string-to-number (match-string 1)))
2080 (when (setq range (cadr (assq sequence sequences)))
2081 (push (gnus-uncompress-range range) copied)))
2082 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2084 (defun nnimap-new-articles (flags)
2086 (dolist (elem flags)
2087 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2089 (push (car elem) new)))
2090 (gnus-compress-sequence (nreverse new))))
2092 (defun nnimap-make-split-specs (list)
2096 (destructuring-bind (article spec) elem
2097 (dolist (group (delete nil (mapcar #'car spec)))
2098 (unless (setq entry (assoc group specs))
2099 (push (setq entry (list group)) specs))
2100 (setcdr entry (cons article (cdr entry))))))
2101 (dolist (entry specs)
2102 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2105 (defun nnimap-transform-split-mail ()
2106 (goto-char (point-min))
2107 (let (article bytes)
2110 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2111 (delete-region (point) (progn (forward-line 1) (point)))
2114 (setq article (match-string 1)
2115 bytes (nnimap-get-length))
2116 (delete-region (line-beginning-position) (line-end-position))
2117 ;; Insert MMDF separator, and a way to remember what this
2119 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2120 (forward-char (1+ bytes))
2121 (setq bytes (nnimap-get-length))
2122 (delete-region (line-beginning-position) (line-end-position))
2123 ;; There's a body; skip past that.
2125 (forward-char (1+ bytes))
2126 (delete-region (line-beginning-position) (line-end-position)))))))
2128 (defun nnimap-dummy-active-number (group &optional server)
2131 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2133 (goto-char (point-min))
2134 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2135 (error "Invalid nnimap mail")
2136 (setq article (string-to-number (match-string 1))))
2138 (if (eq group-art 'junk)
2139 (list (cons 'junk 1))
2141 nnimap-incoming-split-list)))
2143 (defun nnimap-make-thread-query (header)
2144 (let* ((id (mail-header-id header))
2146 (or (mail-header-references header)
2150 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2152 (dolist (refid refs value)
2154 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2155 refid refid value)))))
2160 ;;; nnimap.el ends here