1 ;;; nnimap.el --- IMAP interface for Gnus
3 ;; Copyright (C) 2010-2015 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 ()
171 (push "RFC822.SIZE" params)
172 (when (nnimap-capability "X-GM-EXT-1")
173 (push "X-GM-LABELS" params))
174 (push "BODYSTRUCTURE" params)
177 "BODY.PEEK[HEADER.FIELDS %s]"
178 "RFC822.HEADER.LINES %s")
179 (append '(Subject From Date Message-Id
180 References In-Reply-To Xref)
181 nnmail-extra-headers))
183 (format "%s" (nreverse params))))
185 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
187 (setq group (nnimap-decode-gnus-group group)))
188 (with-current-buffer nntp-server-buffer
190 (when (nnimap-change-group group server)
191 (with-current-buffer (nnimap-buffer)
193 (nnimap-wait-for-response
196 (nnimap-article-ranges (gnus-compress-sequence articles))
197 (nnimap-header-parameters))
199 (nnimap-transform-headers)
200 (nnheader-remove-cr-followed-by-lf))
201 (insert-buffer-substring
202 (nnimap-find-process-buffer (current-buffer))))
205 (defun nnimap-transform-headers ()
206 (goto-char (point-min))
207 (let (article lines size string labels)
210 (while (not (looking-at "\\* [0-9]+ FETCH"))
211 (delete-region (point) (progn (forward-line 1) (point)))
214 (goto-char (match-end 0))
215 ;; Unfold quoted {number} strings.
216 (while (re-search-forward
217 "[^]][ (]{\\([0-9]+\\)}\r?\n"
219 ;; Start of the header section.
220 (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
221 ;; Start of the next FETCH.
222 (re-search-forward "\\* [0-9]+ FETCH" nil t)
225 (setq size (string-to-number (match-string 1)))
226 (delete-region (+ (match-beginning 0) 2) (point))
227 (setq string (buffer-substring (point) (+ (point) size)))
228 (delete-region (point) (+ (point) size))
229 (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
232 (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
237 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
242 (when (search-forward "X-GM-LABELS" (line-end-position) t)
243 (setq labels (ignore-errors (read (current-buffer)))))
245 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
246 (let ((structure (ignore-errors
247 (read (current-buffer)))))
248 (while (and (consp structure)
249 (not (atom (car structure))))
250 (setq structure (car structure)))
252 (stringp (car structure))
253 (equal (upcase (nth 0 structure)) "MESSAGE")
254 (equal (upcase (nth 1 structure)) "RFC822"))
256 (nth 7 structure)))))
257 (delete-region (line-beginning-position) (line-end-position))
258 (insert (format "211 %s Article retrieved." article))
261 (insert (format "Chars: %s\n" size)))
263 (insert (format "Lines: %s\n" lines)))
265 (insert (format "X-GM-LABELS: %s\n" labels)))
266 ;; Most servers have a blank line after the headers, but
268 (unless (re-search-forward "^\r$\\|^)\r?$" nil t)
269 (goto-char (point-max)))
270 (delete-region (line-beginning-position) (line-end-position))
274 (defun nnimap-unfold-quoted-lines ()
275 ;; Unfold quoted {number} strings.
277 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
278 (setq size (string-to-number (match-string 1)))
279 (delete-region (1+ (match-beginning 0)) (point))
280 (setq string (buffer-substring (point) (+ (point) size)))
281 (delete-region (point) (+ (point) size))
282 (insert (format "%S" string)))))
284 (defun nnimap-get-length ()
285 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
286 (string-to-number (match-string 1))))
288 (defun nnimap-article-ranges (ranges)
292 (number-to-string ranges))
293 ((numberp (cdr ranges))
294 (format "%d:%d" (car ranges) (cdr ranges)))
296 (dolist (elem ranges)
299 (format "%d:%d" (car elem) (cdr elem))
300 (number-to-string elem))
302 (mapconcat #'identity (nreverse result) ",")))))
304 (deffoo nnimap-open-server (server &optional defs no-reconnect)
305 (if (nnimap-server-opened server)
307 (unless (assq 'nnimap-address defs)
308 (setq defs (append defs (list (list 'nnimap-address server)))))
309 (nnoo-change-server 'nnimap server defs)
311 (nnimap-find-connection nntp-server-buffer)
312 (or (nnimap-find-connection nntp-server-buffer)
313 (nnimap-open-connection nntp-server-buffer)))))
315 (defun nnimap-make-process-buffer (buffer)
317 (generate-new-buffer (format " *nnimap %s %s %s*"
318 nnimap-address nnimap-server-port
319 (gnus-buffer-exists-p buffer)))
320 (mm-disable-multibyte)
321 (buffer-disable-undo)
323 (set (make-local-variable 'after-change-functions) nil)
324 (set (make-local-variable 'nnimap-object)
325 (make-nnimap :server (nnoo-current-server 'nnimap)
327 (push (list buffer (current-buffer)) nnimap-connection-alist)
328 (push (current-buffer) nnimap-process-buffers)
331 (defun nnimap-credentials (address ports user)
332 (let* ((auth-source-creation-prompts
333 '((user . "IMAP user at %h: ")
334 (secret . "IMAP password for %u@%h: ")))
335 (found (nth 0 (auth-source-search :max 1
339 :require '(:user :secret)
342 (list (plist-get found :user)
343 (let ((secret (plist-get found :secret)))
344 (if (functionp secret)
347 (plist-get found :save-function))
350 (defun nnimap-keepalive ()
351 (let ((now (current-time)))
352 (dolist (buffer nnimap-process-buffers)
353 (when (buffer-name buffer)
354 (with-current-buffer buffer
355 (when (and nnimap-object
356 (nnimap-last-command-time nnimap-object)
360 (nnimap-last-command-time nnimap-object)))
361 ;; More than five minutes since the last command.
363 (ignore-errors ;E.g. "buffer foo has no process".
364 (nnimap-send-command "NOOP"))))))))
366 (defun nnimap-open-connection (buffer)
367 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
368 ;; `ssl' when nnimap-server-port was nil. Sort of.
369 (when (and nnimap-server-port
370 (eq nnimap-stream 'undecided))
371 (setq nnimap-stream 'ssl))
373 (if (eq nnimap-stream 'undecided)
374 (loop for type in '(ssl network)
375 for stream = (let ((nnimap-stream type))
376 (nnimap-open-connection-1 buffer))
377 while (eq stream 'no-connect)
378 finally (return stream))
379 (nnimap-open-connection-1 buffer))))
380 (if (eq stream 'no-connect)
384 (defun nnimap-map-port (port)
385 (if (equal port "imaps")
389 (defun nnimap-open-connection-1 (buffer)
390 (unless nnimap-keepalive-timer
391 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
392 #'nnimap-keepalive)))
393 (with-current-buffer (nnimap-make-process-buffer buffer)
394 (let* ((coding-system-for-read 'binary)
395 (coding-system-for-write 'binary)
398 ((memq nnimap-stream '(network plain starttls))
399 (nnheader-message 7 "Opening connection to %s..."
402 ((eq nnimap-stream 'shell)
403 (nnheader-message 7 "Opening connection to %s via shell..."
406 ((memq nnimap-stream '(ssl tls))
407 (nnheader-message 7 "Opening connection to %s via tls..."
409 '("imaps" "imap" "993" "143"))
411 (error "Unknown stream type: %s" nnimap-stream))))
412 login-result credentials)
413 (when nnimap-server-port
414 (push nnimap-server-port ports))
416 (open-protocol-stream
417 "*nnimap*" (current-buffer) nnimap-address
418 (nnimap-map-port (car ports))
420 :warn-unless-encrypted t
422 :shell-command nnimap-shell-program
423 :capability-command "1 CAPABILITY\r\n"
424 :end-of-command "\r\n"
427 (lambda (capabilities)
428 (when (gnus-string-match-p "STARTTLS" capabilities)
430 (stream (car stream-list))
431 (props (cdr stream-list))
432 (greeting (plist-get props :greeting))
433 (capabilities (plist-get props :capabilities))
434 (stream-type (plist-get props :type)))
435 (when (and stream (not (memq (process-status stream) '(open run))))
438 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
439 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
440 (eq (process-type stream) 'network))
441 ;; Use TCP-keepalive so that connections that pass through a NAT
442 ;; router don't hang when left idle.
443 (set-network-process-option stream :keepalive t))
445 (setf (nnimap-process nnimap-object) stream)
446 (setf (nnimap-stream-type nnimap-object) stream-type)
449 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
450 nnimap-address (car ports) nnimap-stream)
452 (gnus-set-process-query-on-exit-flag stream nil)
453 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
454 (nnheader-report 'nnimap "%s" greeting)
455 ;; Store the greeting (for debugging purposes).
456 (setf (nnimap-greeting nnimap-object) greeting)
457 (setf (nnimap-capabilities nnimap-object)
459 (split-string capabilities)))
460 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
461 (if (not (setq credentials
462 (if (eq nnimap-authenticator 'anonymous)
464 (message-make-address))
465 ;; Look for the credentials based on
466 ;; the virtual server name and the address
468 (gnus-delete-duplicates
470 (nnoo-current-server 'nnimap)
474 (setq nnimap-object nil)
475 (let ((nnimap-inhibit-logging t))
477 (nnimap-login (car credentials) (cadr credentials))))
478 (if (car login-result)
480 ;; Save the credentials if a save function exists
481 ;; (such a function will only be passed if a new
482 ;; token was created).
483 (when (functionp (nth 2 credentials))
484 (funcall (nth 2 credentials)))
485 ;; See if CAPABILITY is set as part of login
487 (dolist (response (cddr login-result))
488 (when (string= "CAPABILITY" (upcase (car response)))
489 (setf (nnimap-capabilities nnimap-object)
490 (mapcar #'upcase (cdr response))))))
491 ;; If the login failed, then forget the credentials
492 ;; that are now possibly cached.
493 (dolist (host (list (nnoo-current-server 'nnimap)
496 (auth-source-forget+ :host host :port port)))
497 (delete-process (nnimap-process nnimap-object))
498 (setq nnimap-object nil))))
500 (when (nnimap-capability "QRESYNC")
501 (nnimap-command "ENABLE QRESYNC"))
502 (nnheader-message 7 "Opening connection to %s...done"
504 (nnimap-process nnimap-object))))))))
506 (autoload 'rfc2104-hash "rfc2104")
508 (defun nnimap-login (user password)
510 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
511 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
512 ;; and we're using an encrypted connection.
513 ((and (not (nnimap-capability "LOGINDISABLED"))
514 (eq (nnimap-stream-type nnimap-object) 'tls)
515 (or (null nnimap-authenticator)
516 (eq nnimap-authenticator 'login)))
517 (nnimap-command "LOGIN %S %S" user password))
518 ((and (nnimap-capability "AUTH=CRAM-MD5")
519 (or (null nnimap-authenticator)
520 (eq nnimap-authenticator 'cram-md5)))
522 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
523 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
525 (get-buffer-process (current-buffer))
527 (base64-encode-string
529 (rfc2104-hash 'md5 64 16 password
530 (base64-decode-string challenge))))
532 (nnimap-wait-for-response sequence)))
533 ((and (not (nnimap-capability "LOGINDISABLED"))
534 (or (null nnimap-authenticator)
535 (eq nnimap-authenticator 'login)))
536 (nnimap-command "LOGIN %S %S" user password))
537 ((and (nnimap-capability "AUTH=PLAIN")
538 (or (null nnimap-authenticator)
539 (eq nnimap-authenticator 'plain)))
541 "AUTHENTICATE PLAIN %s"
542 (base64-encode-string
543 (format "\000%s\000%s"
544 (nnimap-quote-specials user)
545 (nnimap-quote-specials password)))))))
547 (defun nnimap-quote-specials (string)
550 (goto-char (point-min))
551 (while (re-search-forward "[\\\"]" nil t)
557 (defun nnimap-find-parameter (parameter elems)
561 ((equal (car elem) parameter)
562 (setq result (cdr elem)))
563 ((and (equal (car elem) "OK")
565 (equal (caadr elem) parameter))
566 (setq result (cdr (cadr elem))))))
569 (deffoo nnimap-close-server (&optional server)
570 (when (nnoo-change-server 'nnimap server nil)
572 (delete-process (get-buffer-process (nnimap-buffer))))
573 (nnoo-close-server 'nnimap server)
576 (deffoo nnimap-request-close ()
579 (deffoo nnimap-server-opened (&optional server)
580 (and (nnoo-current-server-p 'nnimap server)
582 (gnus-buffer-live-p nntp-server-buffer)
583 (nnimap-find-connection nntp-server-buffer)))
585 (deffoo nnimap-status-message (&optional server)
586 nnimap-status-string)
588 (deffoo nnimap-request-article (article &optional group server to-buffer)
590 (setq group (nnimap-decode-gnus-group group)))
591 (with-current-buffer nntp-server-buffer
592 (let ((result (nnimap-change-group group server))
594 (when (stringp article)
595 (setq article (nnimap-find-article-by-message-id group server article)))
599 (with-current-buffer (nnimap-buffer)
601 (when nnimap-fetch-partial-articles
602 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
603 (goto-char (point-min))
604 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
605 (setq structure (ignore-errors
606 (let ((start (point)))
608 (downcase-region start (point))
610 (read (current-buffer))))
611 parts (nnimap-find-wanted-parts structure))))
613 (nnimap-get-partial-article article parts structure)
614 (nnimap-get-whole-article article))
615 (let ((buffer (current-buffer)))
616 (with-current-buffer (or to-buffer nntp-server-buffer)
617 (nnheader-insert-buffer-substring buffer)
618 (nnheader-ms-strip-cr)))
619 (cons group article)))))))
621 (deffoo nnimap-request-head (article &optional group server to-buffer)
623 (setq group (nnimap-decode-gnus-group group)))
624 (when (nnimap-change-group group server)
625 (with-current-buffer (nnimap-buffer)
626 (when (stringp article)
627 (setq article (nnimap-find-article-by-message-id group server article)))
630 (nnimap-get-whole-article
631 article (format "UID FETCH %%d %s"
632 (nnimap-header-parameters)))
633 (let ((buffer (current-buffer)))
634 (with-current-buffer (or to-buffer nntp-server-buffer)
636 (insert-buffer-substring buffer)
637 (nnheader-ms-strip-cr)
638 (cons group article)))))))
640 (deffoo nnimap-request-articles (articles &optional group server)
642 (setq group (nnimap-decode-gnus-group group)))
643 (with-current-buffer nntp-server-buffer
644 (let ((result (nnimap-change-group group server)))
647 (with-current-buffer (nnimap-buffer)
649 (when (nnimap-command
651 "UID FETCH %s BODY.PEEK[]"
652 "UID FETCH %s RFC822.PEEK")
653 (nnimap-article-ranges (gnus-compress-sequence articles)))
654 (let ((buffer (current-buffer)))
655 (with-current-buffer nntp-server-buffer
656 (nnheader-insert-buffer-substring buffer)
657 (nnheader-ms-strip-cr)))
660 (defun nnimap-get-whole-article (article &optional command)
665 "UID FETCH %d BODY.PEEK[]"
666 "UID FETCH %d RFC822.PEEK"))
668 ;; Check that we really got an article.
669 (goto-char (point-min))
670 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
673 ;; Remove any data that may have arrived before the FETCH data.
676 (delete-region (point-min) (point)))
677 (let ((bytes (nnimap-get-length)))
678 (delete-region (line-beginning-position)
679 (progn (forward-line 1) (point)))
680 (goto-char (+ (point) bytes))
681 (delete-region (point) (point-max)))
684 (defun nnimap-capability (capability)
685 (member capability (nnimap-capabilities nnimap-object)))
687 (defun nnimap-ver4-p ()
688 (nnimap-capability "IMAP4REV1"))
690 (defun nnimap-get-partial-article (article parts structure)
693 "UID FETCH %d (%s %s)"
699 (mapconcat (lambda (part)
700 (format "BODY.PEEK[%s]" part))
702 (mapconcat (lambda (part)
703 (format "RFC822.PEEK[%s]" part))
706 (nnimap-convert-partial-article structure))))
708 (defun nnimap-convert-partial-article (structure)
709 ;; First just skip past the headers.
710 (goto-char (point-min))
711 (let ((bytes (nnimap-get-length))
713 ;; Delete "FETCH" line.
714 (delete-region (line-beginning-position)
715 (progn (forward-line 1) (point)))
716 (goto-char (+ (point) bytes))
717 ;; Collect all the body parts.
718 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
719 (setq id (match-string 1)
720 bytes (or (nnimap-get-length) 0))
722 (delete-region (point) (progn (forward-line 1) (point)))
723 (push (list id (buffer-substring (point) (+ (point) bytes)))
725 (delete-region (point) (+ (point) bytes)))
726 ;; Delete trailing junk.
727 (delete-region (point) (point-max))
728 ;; Now insert all the parts again where they fit in the structure.
729 (nnimap-insert-partial-structure structure parts)
732 (defun nnimap-insert-partial-structure (structure parts &optional subp)
734 (let ((bstruc structure))
735 (while (consp (car bstruc))
737 (setq type (car bstruc))
738 (setq bstruc (car (cdr bstruc)))
739 (let ((has-boundary (member "boundary" bstruc)))
741 (setq boundary (cadr has-boundary)))))
743 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
744 (downcase type) boundary)))
745 (while (not (stringp (car structure)))
746 (insert "\n--" boundary "\n")
747 (if (consp (caar structure))
748 (nnimap-insert-partial-structure (pop structure) parts t)
749 (let ((bit (pop structure)))
750 (insert (format "Content-type: %s/%s"
751 (downcase (nth 0 bit))
752 (downcase (nth 1 bit))))
753 (if (member-ignore-case "CHARSET" (nth 2 bit))
756 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
758 (insert (format "Content-transfer-encoding: %s\n"
761 (when (assoc (nth 9 bit) parts)
762 (insert (cadr (assoc (nth 9 bit) parts)))))))
763 (insert "\n--" boundary "--\n")))
765 (defun nnimap-find-wanted-parts (structure)
766 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
768 (defun nnimap-find-wanted-parts-1 (structure prefix)
771 (while (consp (car structure))
772 (let ((sub (pop structure)))
773 (if (consp (car sub))
774 (push (nnimap-find-wanted-parts-1
775 sub (if (string= prefix "")
776 (number-to-string num)
777 (format "%s.%s" prefix num)))
779 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
780 (id (if (string= prefix "")
781 (number-to-string num)
782 (format "%s.%s" prefix num))))
783 (setcar (nthcdr 9 sub) id)
784 (when (if (eq nnimap-fetch-partial-articles t)
786 (string-match nnimap-fetch-partial-articles type))
791 (defun nnimap-decode-gnus-group (group)
792 (decode-coding-string group 'utf-8))
794 (deffoo nnimap-request-group (group &optional server dont-check info)
795 (setq group (nnimap-decode-gnus-group group))
796 (let ((result (nnimap-change-group
797 ;; Don't SELECT the group if we're going to select it
799 (if (and (not dont-check)
800 (assoc group nnimap-current-infos))
804 articles active marks high low)
805 (with-current-buffer nntp-server-buffer
807 (when (or (not dont-check)
809 (nth 2 (assoc group nnimap-current-infos)))))
810 (let ((sequences (nnimap-retrieve-group-data-early
811 server (list info))))
812 (nnimap-finish-retrieve-group-infos server (list info) sequences
814 (setq active (nth 2 (assoc group nnimap-current-infos)))))
816 (insert (format "211 %d %d %d %S\n"
817 (- (cdr active) (car active))
823 (deffoo nnimap-request-scan-group (group &optional server info)
824 (setq group (nnimap-decode-gnus-group group))
825 (let (marks high low)
826 (with-current-buffer (nnimap-buffer)
828 (let ((group-sequence
829 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
831 (nnimap-send-command "UID FETCH 1:* FLAGS")))
832 (setf (nnimap-group nnimap-object) group)
833 (nnimap-wait-for-response flag-sequence)
835 (nnimap-flags-to-marks
837 (list (list group-sequence flag-sequence
838 1 group "SELECT")))))
841 (nnimap-update-infos marks (list info))
842 (nnimap-store-info info (gnus-active (gnus-info-group info))))
843 (goto-char (point-max))
844 (let ((uidnext (nth 5 (car marks))))
845 (setq high (or (if uidnext
849 low (or (nth 4 (car marks)) uidnext 1)))))
850 (with-current-buffer nntp-server-buffer
854 "211 %d %d %d %S\n" (1+ (- high low)) low high group))
857 (deffoo nnimap-request-create-group (group &optional server args)
858 (setq group (nnimap-decode-gnus-group group))
859 (when (nnimap-change-group nil server)
860 (with-current-buffer (nnimap-buffer)
861 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
863 (deffoo nnimap-request-delete-group (group &optional force server)
864 (setq group (nnimap-decode-gnus-group group))
865 (when (nnimap-change-group nil server)
866 (with-current-buffer (nnimap-buffer)
867 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
869 (deffoo nnimap-request-rename-group (group new-name &optional server)
870 (setq group (nnimap-decode-gnus-group group))
871 (when (nnimap-change-group nil server)
872 (with-current-buffer (nnimap-buffer)
873 (nnimap-unselect-group)
874 (car (nnimap-command "RENAME %S %S"
875 (utf7-encode group t) (utf7-encode new-name t))))))
877 (defun nnimap-unselect-group ()
878 ;; Make sure we don't have this group open read/write by asking
879 ;; to examine a mailbox that doesn't exist. This seems to be
880 ;; the only way that allows us to reliably go back to unselected
882 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
884 (deffoo nnimap-request-expunge-group (group &optional server)
885 (setq group (nnimap-decode-gnus-group group))
886 (when (nnimap-change-group group server)
887 (with-current-buffer (nnimap-buffer)
888 (car (nnimap-command "EXPUNGE")))))
890 (defun nnimap-get-flags (spec)
893 (with-current-buffer (nnimap-buffer)
895 (nnimap-wait-for-response (nnimap-send-command
896 "UID FETCH %s FLAGS" spec))
898 (subst-char-in-region (point-min) (point-max)
900 (goto-char (point-min))
901 (while (search-forward " FETCH " end t)
902 (setq elems (read (current-buffer)))
903 (push (cons (cadr (memq 'UID elems))
904 (cadr (memq 'FLAGS elems)))
906 (nreverse articles)))
908 (deffoo nnimap-close-group (group &optional server)
911 (deffoo nnimap-request-move-article (article group server accept-form
912 &optional last internal-move-group)
913 (setq group (nnimap-decode-gnus-group group))
914 (when internal-move-group
915 (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
917 (mm-disable-multibyte)
918 (when (funcall (if internal-move-group
920 'nnimap-request-article)
921 article group server (current-buffer))
922 ;; If the move is internal (on the same server), just do it the easy
924 (let ((message-id (message-field-value "message-id")))
925 (if internal-move-group
927 (with-current-buffer (nnimap-buffer)
928 (nnimap-command "UID COPY %d %S"
930 (utf7-encode internal-move-group t)))))
932 (nnimap-delete-article article)
933 (cons internal-move-group
934 (or (nnimap-find-uid-response "COPYUID" (cadr result))
935 (nnimap-find-article-by-message-id
936 internal-move-group server message-id
937 nnimap-request-articles-find-limit)))))
938 ;; Move the article to a different method.
939 (let ((result (eval accept-form)))
941 (nnimap-change-group group server)
942 (nnimap-delete-article article)
945 (deffoo nnimap-request-expire-articles (articles group &optional server force)
946 (setq group (nnimap-decode-gnus-group group))
950 ((not (nnimap-change-group group server))
953 (eq nnmail-expiry-target 'delete))
954 (unless (nnimap-delete-article (gnus-compress-sequence articles))
955 (nnheader-message 7 "Article marked for deletion, but not expunged."))
958 (let ((deletable-articles
960 (eq nnmail-expiry-wait 'immediate))
962 (gnus-sorted-intersection
964 (nnimap-find-expired-articles group)))))
965 (if (null deletable-articles)
967 (if (eq nnmail-expiry-target 'delete)
968 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
969 (setq deletable-articles
970 (nnimap-process-expiry-targets
971 deletable-articles group server)))
972 ;; Return the articles we didn't delete.
973 (gnus-sorted-complement articles deletable-articles))))))
975 (defun nnimap-process-expiry-targets (articles group server)
976 (let ((deleted-articles nil))
978 ;; shortcut further processing if we're going to delete the articles
979 ((eq nnmail-expiry-target 'delete)
980 (setq deleted-articles articles)
982 ;; or just move them to another folder on the same IMAP server
983 ((and (not (functionp nnmail-expiry-target))
984 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
985 (gnus-server-to-method
986 (format "nnimap:%s" server))))
987 (and (nnimap-change-group group server)
988 (with-current-buffer (nnimap-buffer)
989 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
992 (nnimap-article-ranges (gnus-compress-sequence articles))
993 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
994 (setq deleted-articles articles)))
997 (dolist (article articles)
998 (let ((target nnmail-expiry-target))
1000 (mm-disable-multibyte)
1001 (when (nnimap-request-article article group server (current-buffer))
1002 (when (functionp target)
1003 (setq target (funcall target group)))
1005 (not (eq target 'delete)))
1006 (if (or (gnus-request-group target t)
1007 (gnus-request-create-group target))
1009 (nnmail-expiry-target-group target group)
1010 (nnheader-message 7 "Expiring article %s:%d to %s"
1011 group article target))
1013 (nnheader-message 7 "Expiring article %s:%d" group article))
1015 (push article deleted-articles))))))
1016 (setq deleted-articles (nreverse deleted-articles))))
1017 ;; Change back to the current group again.
1018 (nnimap-change-group group server)
1019 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
1022 (defun nnimap-find-expired-articles (group)
1023 (let ((cutoff (nnmail-expired-article-p group nil nil)))
1024 (with-current-buffer (nnimap-buffer)
1027 "UID SEARCH SENTBEFORE %s"
1029 (format "%%d-%s-%%Y"
1031 (car (rassoc (nth 4 (decode-time cutoff))
1032 parse-time-months))))
1035 (delete 0 (mapcar #'string-to-number
1036 (cdr (assoc "SEARCH" (cdr result))))))))))
1039 (defun nnimap-find-article-by-message-id (group server message-id
1041 "Search for message with MESSAGE-ID in GROUP from SERVER.
1042 If LIMIT, first try to limit the search to the N last articles."
1043 (with-current-buffer (nnimap-buffer)
1045 (let* ((change-group-result (nnimap-change-group group server nil t))
1047 (and (listp change-group-result)
1049 (dolist (result (cdr change-group-result))
1050 (when (equal "EXISTS" (cadr result))
1051 (throw 'found (car result)))))))
1053 (nnimap-send-command
1054 "UID SEARCH%s HEADER Message-Id %S"
1055 (if (and limit number-of-article)
1056 ;; The -1 is because IMAP message
1057 ;; numbers are one-based rather than
1059 (format " %s:*" (- (string-to-number number-of-article)
1063 (when (nnimap-wait-for-response sequence)
1064 (let ((article (car (last (cdr (assoc "SEARCH"
1065 (nnimap-parse-response)))))))
1067 (string-to-number article)
1068 (when (and limit number-of-article)
1069 (nnimap-find-article-by-message-id group server message-id))))))))
1071 (defun nnimap-delete-article (articles)
1072 (with-current-buffer (nnimap-buffer)
1073 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1074 (nnimap-article-ranges articles))
1076 ((nnimap-capability "UIDPLUS")
1077 (nnimap-command "UID EXPUNGE %s"
1078 (nnimap-article-ranges articles))
1081 (nnimap-command "EXPUNGE")
1083 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1084 "server doesn't support UIDPLUS, so we won't "
1085 "delete this article now"))))))
1087 (deffoo nnimap-request-scan (&optional group server)
1089 (setq group (nnimap-decode-gnus-group group)))
1090 (when (and (nnimap-change-group nil server)
1092 nnimap-split-methods)
1093 (nnheader-message 7 "nnimap %s splitting mail..." server)
1094 (if (listp nnimap-inbox)
1095 (dolist (nnimap-inbox nnimap-inbox)
1096 (nnimap-split-incoming-mail))
1097 (nnimap-split-incoming-mail))
1098 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1100 (defun nnimap-marks-to-flags (marks)
1102 (dolist (mark marks)
1103 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1107 (deffoo nnimap-request-update-group-status (group status &optional server)
1108 (setq group (nnimap-decode-gnus-group group))
1109 (when (nnimap-change-group nil server)
1110 (let ((command (assoc
1112 '((subscribe "SUBSCRIBE")
1113 (unsubscribe "UNSUBSCRIBE")))))
1115 (with-current-buffer (nnimap-buffer)
1116 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1118 (deffoo nnimap-request-set-mark (group actions &optional server)
1119 (setq group (nnimap-decode-gnus-group group))
1120 (when (nnimap-change-group group server)
1122 (with-current-buffer (nnimap-buffer)
1124 ;; Just send all the STORE commands without waiting for
1125 ;; response. If they're successful, they're successful.
1126 (dolist (action actions)
1127 (destructuring-bind (range action marks) action
1128 (let ((flags (nnimap-marks-to-flags marks)))
1130 (setq sequence (nnimap-send-command
1131 "UID STORE %s %sFLAGS.SILENT (%s)"
1132 (nnimap-article-ranges range)
1134 ((eq action 'del) "-")
1135 ((eq action 'add) "+")
1136 ((eq action 'set) ""))
1137 (mapconcat #'identity flags " ")))))))
1138 ;; Wait for the last command to complete to avoid later
1139 ;; synchronization problems with the stream.
1141 (nnimap-wait-for-response sequence))))))
1143 (deffoo nnimap-request-accept-article (group &optional server last)
1145 ;; We're respooling. Find out where mail splitting would place
1149 (nnmail-article-group
1150 ;; We don't really care about the article number, because
1151 ;; that's determined by the IMAP server later. So just
1152 ;; return the group name.
1154 (list (list group)))))))
1155 (setq group (nnimap-decode-gnus-group group))
1156 (when (nnimap-change-group nil server)
1157 (nnmail-check-syntax)
1158 (let ((message-id (message-field-value "message-id"))
1161 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1162 (with-current-buffer (nnimap-buffer)
1163 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1165 ;; If we have this group open read-only, then unselect it
1166 ;; before appending to it.
1167 (when (equal (nnimap-examined nnimap-object) group)
1168 (nnimap-unselect-group))
1170 (setq sequence (nnimap-send-command
1171 "APPEND %S {%d}" (utf7-encode group t)
1173 (unless nnimap-streaming
1174 (nnimap-wait-for-connection "^[+]"))
1175 (process-send-string (get-buffer-process (current-buffer)) message)
1176 (process-send-string (get-buffer-process (current-buffer))
1177 (if (nnimap-newlinep nnimap-object)
1180 (let ((result (nnimap-get-response sequence)))
1181 (if (not (nnimap-ok-p result))
1183 (nnheader-report 'nnimap "%s" result)
1186 (or (nnimap-find-uid-response "APPENDUID" (car result))
1187 (nnimap-find-article-by-message-id
1188 group server message-id
1189 nnimap-request-articles-find-limit))))))))))
1191 (defun nnimap-process-quirk (greeting-match type data)
1192 (when (and (nnimap-greeting nnimap-object)
1193 (string-match greeting-match (nnimap-greeting nnimap-object))
1195 (string-match "\000" data))
1196 (let ((choice (gnus-multiple-choice
1197 "Message contains NUL characters. Delete, continue, abort? "
1198 '((?d "Delete NUL characters")
1199 (?c "Try to APPEND the message as is")
1203 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1209 (goto-char (point-min))
1210 (while (search-forward "\000" nil t)
1211 (replace-match "" t t))
1212 (buffer-string)))))))
1214 (defun nnimap-ok-p (value)
1217 (equal (caar value) "OK")))
1219 (defun nnimap-find-uid-response (name list)
1220 (let ((result (car (last (nnimap-find-response-element name list)))))
1222 (string-to-number result))))
1224 (defun nnimap-find-response-element (name list)
1227 (when (and (consp elem)
1228 (equal name (car elem)))
1229 (setq result elem)))
1232 (deffoo nnimap-request-replace-article (article group buffer)
1233 (setq group (nnimap-decode-gnus-group group))
1235 (when (and (nnimap-change-group group)
1236 ;; Put the article into the group.
1237 (with-current-buffer buffer
1239 (nnimap-request-accept-article group nil t))))
1240 (nnimap-delete-article (list article))
1241 ;; Return the new article number.
1244 (defun nnimap-add-cr ()
1245 (goto-char (point-min))
1246 (while (re-search-forward "\r?\n" nil t)
1247 (replace-match "\r\n" t t)))
1249 (defun nnimap-get-groups ()
1251 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1253 (nnimap-wait-for-response sequence)
1254 (subst-char-in-region (point-min) (point-max)
1256 (goto-char (point-min))
1257 (nnimap-unfold-quoted-lines)
1258 (goto-char (point-min))
1259 (while (search-forward "* LIST " nil t)
1260 (let ((flags (read (current-buffer)))
1261 (separator (read (current-buffer)))
1262 (group (read (current-buffer))))
1263 (unless (member '%NoSelect flags)
1264 (push (utf7-decode (if (stringp group)
1266 (format "%s" group)) t)
1270 (defun nnimap-get-responses (sequences)
1272 (dolist (sequence sequences)
1273 (goto-char (point-min))
1274 (when (re-search-forward (format "^%d " sequence) nil t)
1275 (push (list sequence (nnimap-parse-response))
1279 (deffoo nnimap-request-list (&optional server)
1280 (when (nnimap-change-group nil server)
1281 (with-current-buffer nntp-server-buffer
1284 (with-current-buffer (nnimap-buffer)
1285 (nnimap-get-groups)))
1286 sequences responses)
1288 (with-current-buffer (nnimap-buffer)
1289 (setf (nnimap-group nnimap-object) nil)
1290 (dolist (group groups)
1291 (setf (nnimap-examined nnimap-object) group)
1292 (push (list (nnimap-send-command "EXAMINE %S"
1293 (utf7-encode group t))
1296 (nnimap-wait-for-response (caar sequences))
1298 (nnimap-get-responses (mapcar #'car sequences))))
1299 (dolist (response responses)
1300 (let* ((sequence (car response))
1301 (response (cadr response))
1302 (group (cadr (assoc sequence sequences)))
1303 (egroup (encode-coding-string group 'utf-8)))
1305 (equal (caar response) "OK"))
1306 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1308 (dolist (elem response)
1309 (when (equal (cadr elem) "EXISTS")
1310 (setq exists (string-to-number (car elem)))))
1312 (setq highest (1- (string-to-number (car uidnext)))))
1315 (insert (format "%S 0 1 y\n" egroup)))
1318 (insert (format "%S %d %d y\n" egroup
1319 highest (1+ highest))))
1321 ;; Return the widest possible range.
1322 (insert (format "%S %d 1 y\n" egroup
1323 (or highest exists)))))))))
1326 (deffoo nnimap-request-newgroups (date &optional server)
1327 (when (nnimap-change-group nil server)
1328 (with-current-buffer nntp-server-buffer
1330 (dolist (group (with-current-buffer (nnimap-buffer)
1331 (nnimap-get-groups)))
1332 (unless (assoc group nnimap-current-infos)
1333 ;; Insert dummy numbers here -- they don't matter.
1334 (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1337 (deffoo nnimap-retrieve-group-data-early (server infos)
1338 (when (and (nnimap-change-group nil server)
1340 (with-current-buffer (nnimap-buffer)
1342 (setf (nnimap-group nnimap-object) nil)
1343 (setf (nnimap-initial-resync nnimap-object) 0)
1344 (let ((qresyncp (nnimap-capability "QRESYNC"))
1345 params groups sequences active uidvalidity modseq group
1347 ;; Go through the infos and gather the data needed to know
1348 ;; what and how to request the data.
1349 (dolist (info infos)
1350 (setq params (gnus-info-params info)
1351 group (nnimap-decode-gnus-group
1352 (gnus-group-real-name (gnus-info-group info)))
1353 active (cdr (assq 'active params))
1354 unexist (assq 'unexist (gnus-info-marks info))
1355 uidvalidity (cdr (assq 'uidvalidity params))
1356 modseq (cdr (assq 'modseq params)))
1357 (setf (nnimap-examined nnimap-object) group)
1364 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1365 (utf7-encode group t)
1366 (nnimap-quirk "QRESYNC")
1374 ;; If we don't have a UIDVALIDITY, then this is
1375 ;; the first time we've seen the group, so we
1376 ;; have to do a SELECT (which is slower than an
1377 ;; examine), but will tell us whether the group
1378 ;; is read-only or not.
1381 (if (and active uidvalidity unexist)
1382 ;; Fetch the last 100 flags.
1383 (setq start (max 1 (- (cdr active) 100)))
1384 (incf (nnimap-initial-resync nnimap-object))
1386 (push (list (nnimap-send-command "%s %S" command
1387 (utf7-encode group t))
1388 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1389 start group command)
1393 (defun nnimap-quirk (command)
1394 (let ((quirk (assoc command nnimap-quirks)))
1395 ;; If this server is of a type that matches a quirk, then return
1396 ;; the "quirked" command instead of the proper one.
1397 (if (or (null quirk)
1398 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1402 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences
1403 &optional dont-insert)
1404 (when (and sequences
1405 (nnimap-change-group nil server t)
1406 ;; Check that the process is still alive.
1407 (get-buffer-process (nnimap-buffer))
1408 (memq (process-status (get-buffer-process (nnimap-buffer)))
1410 (with-current-buffer (nnimap-buffer)
1411 ;; Wait for the final data to trickle in.
1412 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1416 ;; Now we should have most of the data we need, no matter
1417 ;; whether we're QRESYNCING, fetching all the flags from
1418 ;; scratch, or just fetching the last 100 flags per group.
1419 (nnimap-update-infos (nnimap-flags-to-marks
1421 (nreverse sequences)))
1424 ;; Finally, just return something resembling an active file in
1425 ;; the nntp buffer, so that the agent can save the info, too.
1426 (with-current-buffer nntp-server-buffer
1428 (dolist (info infos)
1429 (let* ((group (gnus-info-group info))
1430 (active (gnus-active group)))
1432 (insert (format "%S %d %d y\n"
1433 (decode-coding-string
1434 (gnus-group-real-name group) 'utf-8)
1436 (car active))))))))))))
1438 (defun nnimap-update-infos (flags infos)
1439 (dolist (info infos)
1440 (let* ((group (nnimap-decode-gnus-group
1441 (gnus-group-real-name (gnus-info-group info))))
1442 (marks (cdr (assoc group flags))))
1444 (nnimap-update-info info marks)))))
1446 (defun nnimap-update-info (info marks)
1447 (destructuring-bind (existing flags high low uidnext start-article
1448 permanent-flags uidvalidity
1449 vanished highestmodseq) marks
1451 ;; Ignore groups with no UIDNEXT/marks. This happens for
1452 ;; completely empty groups.
1453 ((and (not existing)
1455 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1457 (gnus-set-active (gnus-info-group info) active))))
1458 ;; We have a mismatch between the old and new UIDVALIDITY
1459 ;; identifiers, so we have to re-request the group info (the next
1460 ;; time). This virtually never happens.
1461 ((let ((old-uidvalidity
1462 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1463 (and old-uidvalidity
1464 (not (equal old-uidvalidity uidvalidity))
1465 (or (not start-article)
1466 (> start-article 1))))
1467 (gnus-group-remove-parameter info 'uidvalidity)
1468 (gnus-group-remove-parameter info 'modseq))
1469 ;; We have the data needed to update.
1471 (let* ((group (gnus-info-group info))
1472 (completep (and start-article
1473 (= start-article 1)))
1474 (active (or (gnus-active group)
1475 (cdr (assq 'active (gnus-info-params info))))))
1477 (setq high (1- uidnext)))
1478 ;; First set the active ranges based on high/low.
1480 (not (gnus-active group)))
1481 (gnus-set-active group
1484 (cons (min (or low (car active))
1486 (max (or high (cdr active))
1491 ;; No articles in this group.
1492 (cons uidnext (1- uidnext)))
1494 (cons start-article (1- start-article)))
1496 ;; No articles and no uidnext.
1498 (gnus-set-active group
1500 (or high (1- uidnext)))))
1501 ;; See whether this is a read-only group.
1502 (unless (eq permanent-flags 'not-scanned)
1503 (gnus-group-set-parameter
1504 info 'permanent-flags
1505 (and (or (memq '%* permanent-flags)
1506 (memq '%Seen permanent-flags))
1508 ;; Update marks and read articles if this isn't a
1509 ;; read-only IMAP group.
1510 (when (setq permanent-flags
1511 (cdr (assq 'permanent-flags (gnus-info-params info))))
1512 (if (and highestmodseq
1513 (not start-article))
1514 ;; We've gotten the data by QRESYNCing.
1515 (nnimap-update-qresync-info
1516 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1517 ;; Do normal non-QRESYNC flag updates.
1518 ;; Update the list of read articles.
1520 (gnus-compress-sequence
1521 (gnus-set-difference
1522 (gnus-set-difference
1525 (cdr (assoc '%Seen flags))
1526 (cdr (assoc '%Deleted flags))))
1527 (cdr (assoc '%Flagged flags)))))
1528 (read (gnus-range-difference
1529 (cons start-article high) unread)))
1530 (when (> start-article 1)
1533 (if (> start-article 1)
1534 (gnus-sorted-range-intersection
1535 (cons 1 (1- start-article))
1536 (gnus-info-read info))
1537 (gnus-info-read info))
1539 (when (or (not (listp permanent-flags))
1540 (memq '%Seen permanent-flags))
1541 (gnus-info-set-read info read))
1542 ;; Update the marks.
1543 (setq marks (gnus-info-marks info))
1544 (dolist (type (cdr nnimap-mark-alist))
1545 (when (or (not (listp permanent-flags))
1546 (memq (car (assoc (caddr type) flags))
1548 (memq '%* permanent-flags))
1549 (let ((old-marks (assoc (car type) marks))
1551 (gnus-compress-sequence
1552 (cdr (or (assoc (caddr type) flags) ; %Flagged
1553 (assoc (intern (cadr type) obarray) flags)
1554 (assoc (cadr type) flags)))))) ; "\Flagged"
1555 (setq marks (delq old-marks marks))
1557 (when (and old-marks
1558 (> start-article 1))
1559 (setq old-marks (gnus-range-difference
1561 (cons start-article high)))
1562 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1564 (push (cons (car type) new-marks) marks)))))
1565 ;; Keep track of non-existing articles.
1566 (let* ((old-unexists (assq 'unexist marks))
1567 (active (gnus-active group))
1570 (gnus-range-difference
1572 (gnus-compress-sequence existing))
1575 (gnus-list-range-difference
1576 existing (gnus-active group))))))
1577 (when (> (car active) 1)
1578 (setq unexists (gnus-range-add
1579 (cons 1 (1- (car active)))
1582 (setcdr old-unexists unexists)
1583 (push (cons 'unexist unexists) marks)))
1584 (gnus-info-set-marks info marks t))))
1585 ;; Tell Gnus whether there are any \Recent messages in any of
1587 (let ((recent (cdr (assoc '%Recent flags))))
1590 (> (car (last recent)) (cdr active)))
1591 (push (list (cons (gnus-group-real-name group) 0))
1592 nnmail-split-history)))
1593 ;; Note the active level for the next run-through.
1594 (gnus-group-set-parameter info 'active (gnus-active group))
1595 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1596 (gnus-group-set-parameter info 'modseq highestmodseq)
1597 (nnimap-store-info info (gnus-active group)))))))
1599 (defun nnimap-update-qresync-info (info existing vanished flags)
1600 ;; Add all the vanished articles to the list of read articles.
1605 (gnus-range-add (gnus-info-read info)
1607 (cdr (assq '%Flagged flags)))
1608 (cdr (assq '%Seen flags))))
1609 (let ((marks (gnus-info-marks info)))
1610 (dolist (type (cdr nnimap-mark-alist))
1611 (let ((ticks (assoc (car type) marks))
1613 (cdr (or (assoc (caddr type) flags) ; %Flagged
1614 (assoc (intern (cadr type) obarray) flags)
1615 (assoc (cadr type) flags))))) ; "\Flagged"
1616 (setq marks (delq ticks marks))
1618 ;; Add the new marks we got.
1619 (setq ticks (gnus-add-to-range ticks new-marks))
1620 ;; Remove the marks from messages that don't have them.
1621 (setq ticks (gnus-remove-from-range
1623 (gnus-compress-sequence
1624 (gnus-sorted-complement existing new-marks))))
1626 (push (cons (car type) ticks) marks)))
1627 (gnus-info-set-marks info marks t))
1628 ;; Add vanished to the list of unexisting articles.
1630 (let* ((old-unexists (assq 'unexist marks))
1631 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1633 (setcdr old-unexists unexists)
1634 (push (cons 'unexist unexists) marks)))
1635 (gnus-info-set-marks info marks t))))
1637 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1638 (if (zerop (length irange))
1641 (dolist (elem (split-string irange ","))
1643 (if (string-match ":" elem)
1644 (let ((numbers (split-string elem ":")))
1645 (cons (string-to-number (car numbers))
1646 (string-to-number (cadr numbers))))
1647 (string-to-number elem))
1649 (nreverse result))))
1651 (defun nnimap-store-info (info active)
1652 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1653 (entry (assoc group nnimap-current-infos)))
1655 (setcdr entry (list info active))
1656 (push (list group info active) nnimap-current-infos))))
1658 (defun nnimap-flags-to-marks (groups)
1659 (let (data group totalp uidnext articles start-article mark permanent-flags
1660 uidvalidity vanished highestmodseq)
1661 (dolist (elem groups)
1662 (setq group (car elem)
1663 uidnext (nth 1 elem)
1664 start-article (nth 2 elem)
1665 permanent-flags (nth 3 elem)
1666 uidvalidity (nth 4 elem)
1667 vanished (nth 5 elem)
1668 highestmodseq (nth 6 elem)
1669 articles (nthcdr 7 elem))
1670 (let ((high (caar articles))
1672 (dolist (article articles)
1673 (setq low (car article))
1674 (push (car article) existing)
1675 (dolist (flag (cdr article))
1676 (setq mark (assoc flag marks))
1678 (push (list flag (car article)) marks)
1679 (setcdr mark (cons (car article) (cdr mark))))))
1680 (push (list group existing marks high low uidnext start-article
1681 permanent-flags uidvalidity vanished highestmodseq)
1685 (defun nnimap-parse-flags (sequences)
1686 (goto-char (point-min))
1687 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1689 (subst-char-in-region (point-min) (point-max)
1691 ;; Remove any MODSEQ entries in the buffer, because they may contain
1692 ;; numbers that are too large for 32-bit Emacsen.
1693 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1694 (replace-match "" t t))
1695 (goto-char (point-min))
1696 (let (start end articles groups uidnext elems permanent-flags
1697 uidvalidity vanished highestmodseq)
1698 (dolist (elem sequences)
1699 (destructuring-bind (group-sequence flag-sequence totalp group command)
1701 (setq start (point))
1703 ;; The EXAMINE was successful.
1704 (search-forward (format "\n%d OK " group-sequence) nil t)
1709 (setq permanent-flags
1710 (if (equal command "SELECT")
1711 (and (search-forward "PERMANENTFLAGS "
1712 (or end (point-min)) t)
1713 (read (current-buffer)))
1717 (and (search-forward "UIDNEXT "
1718 (or end (point-min)) t)
1719 (read (current-buffer))))
1722 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1723 (or end (point-min)) t)
1724 ;; Store UIDVALIDITY as a string, as it's
1725 ;; too big for 32-bit Emacsen, usually.
1729 (and (eq flag-sequence 'qresync)
1730 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1731 (or end (point-min)) t)
1735 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1736 (or end (point-min)) t)
1740 ;; The UID FETCH FLAGS was successful.
1741 (or (eq flag-sequence 'qresync)
1742 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1743 (if (eq flag-sequence 'qresync)
1747 (setq start (point))
1749 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1751 (setq elems (read (current-buffer)))
1752 (push (cons (cadr (memq 'UID elems))
1753 (cadr (memq 'FLAGS elems)))
1755 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1756 vanished highestmodseq)
1759 (if (eq flag-sequence 'qresync)
1762 (setq articles nil))))
1765 (defun nnimap-find-process-buffer (buffer)
1766 (cadr (assoc buffer nnimap-connection-alist)))
1768 (deffoo nnimap-request-post (&optional server)
1769 (setq nnimap-status-string "Read-only server")
1772 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1773 (declare-function gnus-fetch-headers "gnus-sum"
1774 (articles &optional limit force-new dependencies))
1776 (autoload 'nnir-search-thread "nnir")
1778 (deffoo nnimap-request-thread (header &optional group server)
1780 (setq group (nnimap-decode-gnus-group group)))
1781 (if gnus-refer-thread-use-nnir
1782 (nnir-search-thread header)
1783 (when (nnimap-change-group group server)
1784 (let* ((cmd (nnimap-make-thread-query header))
1785 (result (with-current-buffer (nnimap-buffer)
1786 (nnimap-command "UID SEARCH %s" cmd))))
1790 (delete 0 (mapcar #'string-to-number
1791 (cdr (assoc "SEARCH" (cdr result))))))
1794 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1795 "Change group to GROUP if non-nil.
1796 If SERVER is set, check that server is connected, otherwise retry
1797 to reconnect, unless NO-RECONNECT is set to t. Return nil if
1798 unsuccessful in connecting.
1799 If GROUP is nil, return t.
1800 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1801 Return the server's response to the SELECT or EXAMINE command."
1802 (let ((open-result t))
1804 (not (nnimap-server-opened server)))
1805 (setq open-result (nnimap-open-server server nil no-reconnect)))
1812 (with-current-buffer (nnimap-buffer)
1813 (let ((result (nnimap-command "%s %S"
1817 (utf7-encode group t))))
1819 (setf (nnimap-group nnimap-object) group
1820 (nnimap-select-result nnimap-object) result)
1823 (defun nnimap-find-connection (buffer)
1824 "Find the connection delivering to BUFFER."
1825 (let ((entry (assoc buffer nnimap-connection-alist)))
1827 (if (and (buffer-name (cadr entry))
1828 (get-buffer-process (cadr entry))
1829 (memq (process-status (get-buffer-process (cadr entry)))
1831 (get-buffer-process (cadr entry))
1832 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1835 (defvar nnimap-sequence 0)
1837 (defun nnimap-send-command (&rest args)
1838 (setf (nnimap-last-command-time nnimap-object) (current-time))
1839 (process-send-string
1840 (get-buffer-process (current-buffer))
1843 (incf nnimap-sequence)
1844 (apply #'format args)
1845 (if (nnimap-newlinep nnimap-object)
1848 ;; Some servers apparently can't have many outstanding
1849 ;; commands, so throttle them.
1850 (unless nnimap-streaming
1851 (nnimap-wait-for-response nnimap-sequence))
1854 (defvar nnimap-record-commands nil
1855 "If non-nil, log commands to the \"*imap log*\" buffer.")
1857 (defun nnimap-log-buffer ()
1858 (let ((name "*imap log*"))
1859 (or (get-buffer name)
1860 (with-current-buffer (get-buffer-create name)
1861 (when (boundp 'window-point-insertion-type)
1862 (make-local-variable 'window-point-insertion-type)
1863 (setq window-point-insertion-type t))
1864 (current-buffer)))))
1866 (defun nnimap-log-command (command)
1867 (when nnimap-record-commands
1868 (with-current-buffer (nnimap-log-buffer)
1869 (goto-char (point-max))
1870 (insert (format-time-string "%H:%M:%S")
1871 " [" nnimap-address "] "
1872 (if nnimap-inhibit-logging
1877 (defun nnimap-command (&rest args)
1879 (let* ((sequence (apply #'nnimap-send-command args))
1880 (response (nnimap-get-response sequence)))
1881 (if (equal (caar response) "OK")
1883 (nnheader-report 'nnimap "%s"
1884 (mapconcat (lambda (a)
1886 (car response) " "))
1889 (defun nnimap-get-response (sequence)
1890 (nnimap-wait-for-response sequence)
1891 (nnimap-parse-response))
1893 (defun nnimap-wait-for-connection (&optional regexp)
1894 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1896 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1897 (let ((process (get-buffer-process (current-buffer))))
1898 (goto-char (point-min))
1899 (while (and (memq (process-status process)
1901 (not (re-search-forward regexp nil t)))
1902 (nnheader-accept-process-output process)
1903 (goto-char (point-min)))
1905 (and (looking-at (or response-regexp regexp))
1908 (defun nnimap-wait-for-response (sequence &optional messagep)
1909 (let ((process (get-buffer-process (current-buffer)))
1913 (goto-char (point-max))
1914 (while (and (setq openp (memq (process-status process)
1917 ;; Skip past any "*" lines that the server has
1919 (while (and (not (bobp))
1922 (looking-at "\\*\\|[0-9]+ OK NOOP"))))
1923 (not (looking-at (format "%d .*\n" sequence)))))
1925 (nnheader-message-maybe
1926 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1928 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1929 (format " (initial sync of %d group%s; please wait)"
1930 (nnimap-initial-resync nnimap-object)
1931 (if (= (nnimap-initial-resync nnimap-object) 1)
1935 (nnheader-accept-process-output process)
1936 (goto-char (point-max)))
1937 (setf (nnimap-initial-resync nnimap-object) 0)
1942 ;; The user hit C-g while we were waiting: kill the process, in case
1943 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1945 (delete-process process)
1948 (defun nnimap-parse-response ()
1949 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1951 (dolist (line lines)
1952 (push (cdr (nnimap-parse-line line)) result))
1953 ;; Return the OK/error code first, and then all the "continuation
1954 ;; lines" afterwards.
1956 (nreverse result))))
1958 ;; Parse an IMAP response line lightly. They look like
1959 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1960 ;; the lines into a list of strings and lists of string.
1961 (defun nnimap-parse-line (line)
1964 (mm-disable-multibyte)
1966 (goto-char (point-min))
1968 (if (eql (setq char (following-char)) ? )
1976 (if (search-forward "]" (line-end-position) 'move)
1983 (if (search-forward ")" (line-end-position) 'move)
1990 (1- (or (search-forward "\"" (line-end-position) 'move)
1993 (buffer-substring (point) (if (search-forward " " nil t)
1995 (goto-char (point-max))))))
1997 (nreverse result))))
1999 (defun nnimap-last-response-string ()
2002 (let ((end (point)))
2006 (while (and (not (bobp))
2007 (eql (following-char) ?*))
2009 (unless (eql (following-char) ?*)
2011 (buffer-substring (point) end))))
2013 (defvar nnimap-incoming-split-list nil)
2015 (defun nnimap-fetch-inbox (articles)
2017 (nnimap-wait-for-response
2018 (nnimap-send-command
2020 (nnimap-article-ranges articles)
2021 (format "(UID %s%s)"
2027 (nnimap-split-download-body-default
2035 (defun nnimap-split-incoming-mail ()
2036 (with-current-buffer (nnimap-buffer)
2037 (let ((nnimap-incoming-split-list nil)
2038 (nnmail-split-methods
2040 ((eq nnimap-split-methods 'default)
2041 nnmail-split-methods)
2042 (nnimap-split-methods
2043 nnimap-split-methods)
2045 'nnmail-split-fancy)))
2046 (nnmail-split-fancy (or nnimap-split-fancy
2047 nnmail-split-fancy))
2048 (nnmail-inhibit-default-split-group t)
2049 (groups (nnimap-get-groups))
2052 (nnimap-command "SELECT %S" nnimap-inbox)
2053 (setf (nnimap-group nnimap-object) nnimap-inbox)
2054 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2056 (nnimap-fetch-inbox new-articles)
2057 (nnimap-transform-split-mail)
2058 (nnheader-ms-strip-cr)
2060 (nnmail-split-incoming (current-buffer)
2061 #'nnimap-save-mail-spec
2063 #'nnimap-dummy-active-number
2064 #'nnimap-save-mail-spec)
2065 (when nnimap-incoming-split-list
2066 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2067 sequences junk-articles)
2068 ;; Create any groups that doesn't already exist on the
2070 (dolist (spec specs)
2071 (when (and (not (member (car spec) groups))
2072 (not (eq (car spec) 'junk)))
2073 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2074 ;; Then copy over all the messages.
2076 (dolist (spec specs)
2077 (let ((group (car spec))
2078 (ranges (cdr spec)))
2079 (if (eq group 'junk)
2080 (setq junk-articles ranges)
2081 (push (list (nnimap-send-command
2083 (nnimap-article-ranges ranges)
2084 (utf7-encode group t))
2087 ;; Wait for the last COPY response...
2089 (nnimap-wait-for-response (caar sequences))
2090 ;; And then mark the successful copy actions as deleted,
2091 ;; and possibly expunge them.
2092 (nnimap-mark-and-expunge-incoming
2093 (nnimap-parse-copied-articles sequences)))
2094 (nnimap-mark-and-expunge-incoming junk-articles)))))))
2096 (defun nnimap-mark-and-expunge-incoming (range)
2098 (setq range (nnimap-article-ranges range))
2101 (nnimap-send-command
2102 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2104 ;; If the server supports it, we now delete the message we have
2105 ;; just copied over.
2106 ((nnimap-capability "UIDPLUS")
2107 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2108 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2109 ;; user has configured it.
2111 (setq sequence (nnimap-send-command "EXPUNGE"))))
2112 (nnimap-wait-for-response sequence))))
2114 (defun nnimap-parse-copied-articles (sequences)
2115 (let (sequence copied range)
2116 (goto-char (point-min))
2117 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2118 (setq sequence (string-to-number (match-string 1)))
2119 (when (setq range (cadr (assq sequence sequences)))
2120 (push (gnus-uncompress-range range) copied)))
2121 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2123 (defun nnimap-new-articles (flags)
2125 (dolist (elem flags)
2126 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2128 (push (car elem) new)))
2129 (gnus-compress-sequence (nreverse new))))
2131 (defun nnimap-make-split-specs (list)
2135 (destructuring-bind (article spec) elem
2136 (dolist (group (delete nil (mapcar #'car spec)))
2137 (unless (setq entry (assoc group specs))
2138 (push (setq entry (list group)) specs))
2139 (setcdr entry (cons article (cdr entry))))))
2140 (dolist (entry specs)
2141 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2144 (defun nnimap-transform-split-mail ()
2145 (goto-char (point-min))
2146 (let (article bytes)
2149 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2150 (delete-region (point) (progn (forward-line 1) (point)))
2153 (setq article (match-string 1)
2154 bytes (nnimap-get-length))
2155 (delete-region (line-beginning-position) (line-end-position))
2156 ;; Insert MMDF separator, and a way to remember what this
2158 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2159 (forward-char (1+ bytes))
2160 (setq bytes (nnimap-get-length))
2161 (delete-region (line-beginning-position) (line-end-position))
2162 ;; There's a body; skip past that.
2164 (forward-char (1+ bytes))
2165 (delete-region (line-beginning-position) (line-end-position)))))))
2167 (defun nnimap-dummy-active-number (group &optional server)
2170 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2172 (goto-char (point-min))
2173 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2174 (error "Invalid nnimap mail")
2175 (setq article (string-to-number (match-string 1))))
2177 (if (eq group-art 'junk)
2178 (list (cons 'junk 1))
2180 nnimap-incoming-split-list)))
2182 (defun nnimap-make-thread-query (header)
2183 (let* ((id (mail-header-id header))
2185 (or (mail-header-references header)
2189 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2191 (dolist (refid refs value)
2193 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2194 refid refid value)))))
2199 ;;; nnimap.el ends here