1 ;;; nnimap.el --- IMAP interface for Gnus
3 ;; Copyright (C) 2010-2012 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.
29 ;; For Emacs <22.2 and XEmacs.
31 (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
35 ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
36 ;; `make-network-stream'.
37 (unless (fboundp 'open-protocol-stream)
38 (require 'proto-stream)))
53 (autoload 'auth-source-forget+ "auth-source")
54 (autoload 'auth-source-search "auth-source")
58 (defvoo nnimap-address nil
59 "The address of the IMAP server.")
61 (defvoo nnimap-user nil
62 "Username to use for authentication to the IMAP server.")
64 (defvoo nnimap-server-port nil
66 If nnimap-stream is `ssl', this will default to `imaps'. If not,
67 it will default to `imap'.")
69 (defvoo nnimap-stream 'undecided
70 "How nnimap talks to the IMAP server.
71 The value should be either `undecided', `ssl' or `tls',
72 `network', `starttls', `plain', or `shell'.
74 If the value is `undecided', nnimap tries `ssl' first, then falls
77 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
78 (if (listp imap-shell-program)
79 (car imap-shell-program)
83 (defvoo nnimap-inbox nil
84 "The mail box where incoming mail arrives and should be split out of.
85 For example, \"INBOX\".")
87 (defvoo nnimap-split-methods nil
89 Uses the same syntax as `nnmail-split-methods'.")
91 (defvoo nnimap-split-fancy nil
92 "Uses the same syntax as `nnmail-split-fancy'.")
94 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
95 "Articles with the flags in the list will not be considered when splitting.")
97 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
100 (defvoo nnimap-authenticator nil
101 "How nnimap authenticate itself to the server.
102 Possible choices are nil (use default methods) or `anonymous'.")
104 (defvoo nnimap-expunge t
105 "If non-nil, expunge articles after deleting them.
106 This is always done if the server supports UID EXPUNGE, but it's
107 not done by default on servers that doesn't support that command.")
109 (defvoo nnimap-streaming t
110 "If non-nil, try to use streaming commands with IMAP servers.
111 Switching this off will make nnimap slower, but it helps with
114 (defvoo nnimap-connection-alist nil)
116 (defvoo nnimap-current-infos nil)
118 (defvoo nnimap-fetch-partial-articles nil
119 "If non-nil, Gnus will fetch partial articles.
120 If t, nnimap will fetch only the first part. If a string, it
121 will fetch all parts that have types that match that string. A
122 likely value would be \"text/\" to automatically fetch all
125 (defvar nnimap-process nil)
127 (defvar nnimap-status-string "")
129 (defvar nnimap-split-download-body-default nil
130 "Internal variable with default value for `nnimap-split-download-body'.")
132 (defvar nnimap-keepalive-timer nil)
133 (defvar nnimap-process-buffers nil)
136 group process commands capabilities select-result newlinep server
137 last-command-time greeting examined stream-type initial-resync)
139 (defvar nnimap-object nil)
141 (defvar nnimap-mark-alist
142 '((read "\\Seen" %Seen)
143 (tick "\\Flagged" %Flagged)
144 (reply "\\Answered" %Answered)
145 (expire "gnus-expire")
146 (dormant "gnus-dormant")
149 (download "gnus-download")
150 (forward "gnus-forward")))
152 (defvar nnimap-quirks
153 '(("QRESYNC" "Zimbra" "QRESYNC ")))
155 (defvar nnimap-inhibit-logging nil)
157 (defun nnimap-buffer ()
158 (nnimap-find-process-buffer nntp-server-buffer))
160 (defun nnimap-header-parameters ()
161 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
164 "BODY.PEEK[HEADER.FIELDS %s]"
165 "RFC822.HEADER.LINES %s")
166 (append '(Subject From Date Message-Id
167 References In-Reply-To Xref)
168 nnmail-extra-headers))))
170 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
172 (setq group (nnimap-decode-gnus-group group)))
173 (with-current-buffer nntp-server-buffer
175 (when (nnimap-possibly-change-group group server)
176 (with-current-buffer (nnimap-buffer)
178 (nnimap-wait-for-response
181 (nnimap-article-ranges (gnus-compress-sequence articles))
182 (nnimap-header-parameters))
184 (nnimap-transform-headers)
185 (nnheader-remove-cr-followed-by-lf))
186 (insert-buffer-substring
187 (nnimap-find-process-buffer (current-buffer))))
190 (defun nnimap-transform-headers ()
191 (goto-char (point-min))
192 (let (article lines size string)
195 (while (not (looking-at "\\* [0-9]+ FETCH"))
196 (delete-region (point) (progn (forward-line 1) (point)))
199 (goto-char (match-end 0))
200 ;; Unfold quoted {number} strings.
201 (while (re-search-forward
202 "[^]][ (]{\\([0-9]+\\)}\r?\n"
204 (or (re-search-forward "\\* [0-9]+ FETCH" nil t)
207 (setq size (string-to-number (match-string 1)))
208 (delete-region (+ (match-beginning 0) 2) (point))
209 (setq string (buffer-substring (point) (+ (point) size)))
210 (delete-region (point) (+ (point) size))
211 (insert (format "%S" (subst-char-in-string
215 (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
220 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
225 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
226 (let ((structure (ignore-errors
227 (read (current-buffer)))))
228 (while (and (consp structure)
229 (not (atom (car structure))))
230 (setq structure (car structure)))
232 (stringp (car structure))
233 (equal (upcase (nth 0 structure)) "MESSAGE")
234 (equal (upcase (nth 1 structure)) "RFC822"))
236 (nth 7 structure)))))
237 (delete-region (line-beginning-position) (line-end-position))
238 (insert (format "211 %s Article retrieved." article))
241 (insert (format "Chars: %s\n" size)))
243 (insert (format "Lines: %s\n" lines)))
244 (unless (re-search-forward "^\r$" nil t)
245 (goto-char (point-max)))
246 (delete-region (line-beginning-position) (line-end-position))
250 (defun nnimap-unfold-quoted-lines ()
251 ;; Unfold quoted {number} strings.
253 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
254 (setq size (string-to-number (match-string 1)))
255 (delete-region (1+ (match-beginning 0)) (point))
256 (setq string (buffer-substring (point) (+ (point) size)))
257 (delete-region (point) (+ (point) size))
258 (insert (format "%S" string)))))
260 (defun nnimap-get-length ()
261 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
262 (string-to-number (match-string 1))))
264 (defun nnimap-article-ranges (ranges)
268 (number-to-string ranges))
269 ((numberp (cdr ranges))
270 (format "%d:%d" (car ranges) (cdr ranges)))
272 (dolist (elem ranges)
275 (format "%d:%d" (car elem) (cdr elem))
276 (number-to-string elem))
278 (mapconcat #'identity (nreverse result) ",")))))
280 (deffoo nnimap-open-server (server &optional defs no-reconnect)
281 (if (nnimap-server-opened server)
283 (unless (assq 'nnimap-address defs)
284 (setq defs (append defs (list (list 'nnimap-address server)))))
285 (nnoo-change-server 'nnimap server defs)
287 (nnimap-find-connection nntp-server-buffer)
288 (or (nnimap-find-connection nntp-server-buffer)
289 (nnimap-open-connection nntp-server-buffer)))))
291 (defun nnimap-make-process-buffer (buffer)
293 (generate-new-buffer (format "*nnimap %s %s %s*"
294 nnimap-address nnimap-server-port
295 (gnus-buffer-exists-p buffer)))
296 (mm-disable-multibyte)
297 (buffer-disable-undo)
299 (set (make-local-variable 'after-change-functions) nil)
300 (set (make-local-variable 'nnimap-object)
301 (make-nnimap :server (nnoo-current-server 'nnimap)
303 (push (list buffer (current-buffer)) nnimap-connection-alist)
304 (push (current-buffer) nnimap-process-buffers)
307 (defun nnimap-credentials (address ports user)
308 (let* ((auth-source-creation-prompts
309 '((user . "IMAP user at %h: ")
310 (secret . "IMAP password for %u@%h: ")))
311 (found (nth 0 (auth-source-search :max 1
315 :require '(:user :secret)
318 (list (plist-get found :user)
319 (let ((secret (plist-get found :secret)))
320 (if (functionp secret)
323 (plist-get found :save-function))
326 (defun nnimap-keepalive ()
327 (let ((now (current-time)))
328 (dolist (buffer nnimap-process-buffers)
329 (when (buffer-name buffer)
330 (with-current-buffer buffer
331 (when (and nnimap-object
332 (nnimap-last-command-time nnimap-object)
336 (nnimap-last-command-time nnimap-object)))
337 ;; More than five minutes since the last command.
339 (nnimap-send-command "NOOP")))))))
341 (defun nnimap-open-connection (buffer)
342 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
343 ;; `ssl' when nnimap-server-port was nil. Sort of.
344 (when (and nnimap-server-port
345 (eq nnimap-stream 'undecided))
346 (setq nnimap-stream 'ssl))
348 (if (eq nnimap-stream 'undecided)
349 (loop for type in '(ssl network)
350 for stream = (let ((nnimap-stream type))
351 (nnimap-open-connection-1 buffer))
352 while (eq stream 'no-connect)
353 finally (return stream))
354 (nnimap-open-connection-1 buffer))))
355 (if (eq stream 'no-connect)
359 (defun nnimap-map-port (port)
360 (if (equal port "imaps")
364 (defun nnimap-open-connection-1 (buffer)
365 (unless nnimap-keepalive-timer
366 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
368 (with-current-buffer (nnimap-make-process-buffer buffer)
369 (let* ((coding-system-for-read 'binary)
370 (coding-system-for-write 'binary)
373 ((memq nnimap-stream '(network plain starttls))
374 (nnheader-message 7 "Opening connection to %s..."
377 ((eq nnimap-stream 'shell)
378 (nnheader-message 7 "Opening connection to %s via shell..."
381 ((memq nnimap-stream '(ssl tls))
382 (nnheader-message 7 "Opening connection to %s via tls..."
384 '("imaps" "imap" "993" "143"))
386 (error "Unknown stream type: %s" nnimap-stream))))
387 login-result credentials)
388 (when nnimap-server-port
389 (push nnimap-server-port ports))
391 (open-protocol-stream
392 "*nnimap*" (current-buffer) nnimap-address
393 (nnimap-map-port (car ports))
396 :shell-command nnimap-shell-program
397 :capability-command "1 CAPABILITY\r\n"
398 :end-of-command "\r\n"
401 (lambda (capabilities)
402 (when (gnus-string-match-p "STARTTLS" capabilities)
404 (stream (car stream-list))
405 (props (cdr stream-list))
406 (greeting (plist-get props :greeting))
407 (capabilities (plist-get props :capabilities))
408 (stream-type (plist-get props :type)))
409 (when (and stream (not (memq (process-status stream) '(open run))))
412 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
413 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
414 (eq (process-type stream) 'network))
415 ;; Use TCP-keepalive so that connections that pass through a NAT
416 ;; router don't hang when left idle.
417 (set-network-process-option stream :keepalive t))
419 (setf (nnimap-process nnimap-object) stream)
420 (setf (nnimap-stream-type nnimap-object) stream-type)
423 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
424 nnimap-address (car ports) nnimap-stream)
426 (gnus-set-process-query-on-exit-flag stream nil)
427 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
428 (nnheader-report 'nnimap "%s" greeting)
429 ;; Store the greeting (for debugging purposes).
430 (setf (nnimap-greeting nnimap-object) greeting)
431 (setf (nnimap-capabilities nnimap-object)
433 (split-string capabilities)))
434 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
435 (if (not (setq credentials
436 (if (eq nnimap-authenticator 'anonymous)
438 (message-make-address))
439 ;; Look for the credentials based on
440 ;; the virtual server name and the address
442 (gnus-delete-duplicates
445 (nnoo-current-server 'nnimap)))
448 (setq nnimap-object nil)
449 (let ((nnimap-inhibit-logging t))
451 (nnimap-login (car credentials) (cadr credentials))))
452 (if (car login-result)
454 ;; Save the credentials if a save function exists
455 ;; (such a function will only be passed if a new
456 ;; token was created).
457 (when (functionp (nth 2 credentials))
458 (funcall (nth 2 credentials)))
459 ;; See if CAPABILITY is set as part of login
461 (dolist (response (cddr login-result))
462 (when (string= "CAPABILITY" (upcase (car response)))
463 (setf (nnimap-capabilities nnimap-object)
464 (mapcar #'upcase (cdr response))))))
465 ;; If the login failed, then forget the credentials
466 ;; that are now possibly cached.
467 (dolist (host (list (nnoo-current-server 'nnimap)
470 (auth-source-forget+ :host host :port port)))
471 (delete-process (nnimap-process nnimap-object))
472 (setq nnimap-object nil))))
474 (when (nnimap-capability "QRESYNC")
475 (nnimap-command "ENABLE QRESYNC"))
476 (nnimap-process nnimap-object))))))))
478 (autoload 'rfc2104-hash "rfc2104")
480 (defun nnimap-login (user password)
482 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
483 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
484 ;; and we're using an encrypted connection.
485 ((and (not (nnimap-capability "LOGINDISABLED"))
486 (eq (nnimap-stream-type nnimap-object) 'tls))
487 (nnimap-command "LOGIN %S %S" user password))
488 ((nnimap-capability "AUTH=CRAM-MD5")
490 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
491 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
493 (get-buffer-process (current-buffer))
495 (base64-encode-string
497 (rfc2104-hash 'md5 64 16 password
498 (base64-decode-string challenge))))
500 (nnimap-wait-for-response sequence)))
501 ((not (nnimap-capability "LOGINDISABLED"))
502 (nnimap-command "LOGIN %S %S" user password))
503 ((nnimap-capability "AUTH=PLAIN")
505 "AUTHENTICATE PLAIN %s"
506 (base64-encode-string
507 (format "\000%s\000%s"
508 (nnimap-quote-specials user)
509 (nnimap-quote-specials password)))))))
511 (defun nnimap-quote-specials (string)
514 (goto-char (point-min))
515 (while (re-search-forward "[\\\"]" nil t)
521 (defun nnimap-find-parameter (parameter elems)
525 ((equal (car elem) parameter)
526 (setq result (cdr elem)))
527 ((and (equal (car elem) "OK")
529 (equal (caadr elem) parameter))
530 (setq result (cdr (cadr elem))))))
533 (deffoo nnimap-close-server (&optional server)
534 (when (nnoo-change-server 'nnimap server nil)
536 (delete-process (get-buffer-process (nnimap-buffer))))
537 (nnoo-close-server 'nnimap server)
540 (deffoo nnimap-request-close ()
543 (deffoo nnimap-server-opened (&optional server)
544 (and (nnoo-current-server-p 'nnimap server)
546 (gnus-buffer-live-p nntp-server-buffer)
547 (nnimap-find-connection nntp-server-buffer)))
549 (deffoo nnimap-status-message (&optional server)
550 nnimap-status-string)
552 (deffoo nnimap-request-article (article &optional group server to-buffer)
554 (setq group (nnimap-decode-gnus-group group)))
555 (with-current-buffer nntp-server-buffer
556 (let ((result (nnimap-possibly-change-group group server))
558 (when (stringp article)
559 (setq article (nnimap-find-article-by-message-id group article)))
563 (with-current-buffer (nnimap-buffer)
565 (when nnimap-fetch-partial-articles
566 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
567 (goto-char (point-min))
568 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
569 (setq structure (ignore-errors
570 (let ((start (point)))
572 (downcase-region start (point))
574 (read (current-buffer))))
575 parts (nnimap-find-wanted-parts structure))))
577 (nnimap-get-partial-article article parts structure)
578 (nnimap-get-whole-article article))
579 (let ((buffer (current-buffer)))
580 (with-current-buffer (or to-buffer nntp-server-buffer)
581 (nnheader-insert-buffer-substring buffer)
582 (nnheader-ms-strip-cr)))
583 (cons group article)))))))
585 (deffoo nnimap-request-head (article &optional group server to-buffer)
587 (setq group (nnimap-decode-gnus-group group)))
588 (when (nnimap-possibly-change-group group server)
589 (with-current-buffer (nnimap-buffer)
590 (when (stringp article)
591 (setq article (nnimap-find-article-by-message-id group article)))
594 (nnimap-get-whole-article
595 article (format "UID FETCH %%d %s"
596 (nnimap-header-parameters)))
597 (let ((buffer (current-buffer)))
598 (with-current-buffer (or to-buffer nntp-server-buffer)
600 (insert-buffer-substring buffer)
601 (nnheader-ms-strip-cr)
602 (cons group article)))))))
604 (defun nnimap-get-whole-article (article &optional command)
609 "UID FETCH %d BODY.PEEK[]"
610 "UID FETCH %d RFC822.PEEK"))
612 ;; Check that we really got an article.
613 (goto-char (point-min))
614 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
617 ;; Remove any data that may have arrived before the FETCH data.
620 (delete-region (point-min) (point)))
621 (let ((bytes (nnimap-get-length)))
622 (delete-region (line-beginning-position)
623 (progn (forward-line 1) (point)))
624 (goto-char (+ (point) bytes))
625 (delete-region (point) (point-max)))
628 (defun nnimap-capability (capability)
629 (member capability (nnimap-capabilities nnimap-object)))
631 (defun nnimap-ver4-p ()
632 (nnimap-capability "IMAP4REV1"))
634 (defun nnimap-get-partial-article (article parts structure)
637 "UID FETCH %d (%s %s)"
643 (mapconcat (lambda (part)
644 (format "BODY.PEEK[%s]" part))
646 (mapconcat (lambda (part)
647 (format "RFC822.PEEK[%s]" part))
650 (nnimap-convert-partial-article structure))))
652 (defun nnimap-convert-partial-article (structure)
653 ;; First just skip past the headers.
654 (goto-char (point-min))
655 (let ((bytes (nnimap-get-length))
657 ;; Delete "FETCH" line.
658 (delete-region (line-beginning-position)
659 (progn (forward-line 1) (point)))
660 (goto-char (+ (point) bytes))
661 ;; Collect all the body parts.
662 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
663 (setq id (match-string 1)
664 bytes (or (nnimap-get-length) 0))
666 (delete-region (point) (progn (forward-line 1) (point)))
667 (push (list id (buffer-substring (point) (+ (point) bytes)))
669 (delete-region (point) (+ (point) bytes)))
670 ;; Delete trailing junk.
671 (delete-region (point) (point-max))
672 ;; Now insert all the parts again where they fit in the structure.
673 (nnimap-insert-partial-structure structure parts)
676 (defun nnimap-insert-partial-structure (structure parts &optional subp)
678 (let ((bstruc structure))
679 (while (consp (car bstruc))
681 (setq type (car bstruc))
682 (setq bstruc (car (cdr bstruc)))
683 (let ((has-boundary (member "boundary" bstruc)))
685 (setq boundary (cadr has-boundary)))))
687 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
688 (downcase type) boundary)))
689 (while (not (stringp (car structure)))
690 (insert "\n--" boundary "\n")
691 (if (consp (caar structure))
692 (nnimap-insert-partial-structure (pop structure) parts t)
693 (let ((bit (pop structure)))
694 (insert (format "Content-type: %s/%s"
695 (downcase (nth 0 bit))
696 (downcase (nth 1 bit))))
697 (if (member-ignore-case "CHARSET" (nth 2 bit))
700 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
702 (insert (format "Content-transfer-encoding: %s\n"
705 (when (assoc (nth 9 bit) parts)
706 (insert (cadr (assoc (nth 9 bit) parts)))))))
707 (insert "\n--" boundary "--\n")))
709 (defun nnimap-find-wanted-parts (structure)
710 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
712 (defun nnimap-find-wanted-parts-1 (structure prefix)
715 (while (consp (car structure))
716 (let ((sub (pop structure)))
717 (if (consp (car sub))
718 (push (nnimap-find-wanted-parts-1
719 sub (if (string= prefix "")
720 (number-to-string num)
721 (format "%s.%s" prefix num)))
723 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
724 (id (if (string= prefix "")
725 (number-to-string num)
726 (format "%s.%s" prefix num))))
727 (setcar (nthcdr 9 sub) id)
728 (when (if (eq nnimap-fetch-partial-articles t)
730 (string-match nnimap-fetch-partial-articles type))
735 (defun nnimap-decode-gnus-group (group)
736 (decode-coding-string group 'utf-8))
738 (deffoo nnimap-request-group (group &optional server dont-check info)
739 (setq group (nnimap-decode-gnus-group group))
740 (let ((result (nnimap-possibly-change-group
741 ;; Don't SELECT the group if we're going to select it
743 (if (and (not dont-check)
744 (assoc group nnimap-current-infos))
748 articles active marks high low)
749 (with-current-buffer nntp-server-buffer
752 (setq active (nth 2 (assoc group nnimap-current-infos))))
753 (insert (format "211 %d %d %d %S\n"
754 (- (cdr active) (car active))
758 (with-current-buffer (nnimap-buffer)
760 (let ((group-sequence
761 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
763 (nnimap-send-command "UID FETCH 1:* FLAGS")))
764 (setf (nnimap-group nnimap-object) group)
765 (nnimap-wait-for-response flag-sequence)
767 (nnimap-flags-to-marks
769 (list (list group-sequence flag-sequence
770 1 group "SELECT")))))
773 (nnimap-update-infos marks (list info))
774 (nnimap-store-info info (gnus-active (gnus-info-group info))))
775 (goto-char (point-max))
776 (let ((uidnext (nth 5 (car marks))))
777 (setq high (or (if uidnext
781 low (or (nth 4 (car marks)) uidnext 1)))))
785 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
788 (deffoo nnimap-request-create-group (group &optional server args)
789 (setq group (nnimap-decode-gnus-group group))
790 (when (nnimap-possibly-change-group nil server)
791 (with-current-buffer (nnimap-buffer)
792 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
794 (deffoo nnimap-request-delete-group (group &optional force server)
795 (setq group (nnimap-decode-gnus-group group))
796 (when (nnimap-possibly-change-group nil server)
797 (with-current-buffer (nnimap-buffer)
798 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
800 (deffoo nnimap-request-rename-group (group new-name &optional server)
801 (setq group (nnimap-decode-gnus-group group))
802 (when (nnimap-possibly-change-group nil server)
803 (with-current-buffer (nnimap-buffer)
804 (nnimap-unselect-group)
805 (car (nnimap-command "RENAME %S %S"
806 (utf7-encode group t) (utf7-encode new-name t))))))
808 (defun nnimap-unselect-group ()
809 ;; Make sure we don't have this group open read/write by asking
810 ;; to examine a mailbox that doesn't exist. This seems to be
811 ;; the only way that allows us to reliably go back to unselected
813 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
815 (deffoo nnimap-request-expunge-group (group &optional server)
816 (setq group (nnimap-decode-gnus-group group))
817 (when (nnimap-possibly-change-group group server)
818 (with-current-buffer (nnimap-buffer)
819 (car (nnimap-command "EXPUNGE")))))
821 (defun nnimap-get-flags (spec)
824 (with-current-buffer (nnimap-buffer)
826 (nnimap-wait-for-response (nnimap-send-command
827 "UID FETCH %s FLAGS" spec))
829 (subst-char-in-region (point-min) (point-max)
831 (goto-char (point-min))
832 (while (search-forward " FETCH " end t)
833 (setq elems (read (current-buffer)))
834 (push (cons (cadr (memq 'UID elems))
835 (cadr (memq 'FLAGS elems)))
837 (nreverse articles)))
839 (deffoo nnimap-close-group (group &optional server)
842 (deffoo nnimap-request-move-article (article group server accept-form
843 &optional last internal-move-group)
844 (setq group (nnimap-decode-gnus-group group))
846 (mm-disable-multibyte)
847 (when (funcall (if internal-move-group
849 'nnimap-request-article)
850 article group server (current-buffer))
851 ;; If the move is internal (on the same server), just do it the easy
853 (let ((message-id (message-field-value "message-id")))
854 (if internal-move-group
856 (with-current-buffer (nnimap-buffer)
857 (nnimap-command "UID COPY %d %S"
859 (utf7-encode internal-move-group t)))))
861 (nnimap-delete-article article)
862 (cons internal-move-group
863 (or (nnimap-find-uid-response "COPYUID" (cadr result))
864 (nnimap-find-article-by-message-id
865 internal-move-group message-id)))))
866 ;; Move the article to a different method.
867 (let ((result (eval accept-form)))
869 (nnimap-delete-article article)
872 (deffoo nnimap-request-expire-articles (articles group &optional server force)
873 (setq group (nnimap-decode-gnus-group group))
877 ((not (nnimap-possibly-change-group group server))
880 (eq nnmail-expiry-target 'delete))
881 (unless (nnimap-delete-article (gnus-compress-sequence articles))
882 (nnheader-message 7 "Article marked for deletion, but not expunged."))
885 (let ((deletable-articles
887 (eq nnmail-expiry-wait 'immediate))
889 (gnus-sorted-intersection
891 (nnimap-find-expired-articles group)))))
892 (if (null deletable-articles)
894 (if (eq nnmail-expiry-target 'delete)
895 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
896 (setq deletable-articles
897 (nnimap-process-expiry-targets
898 deletable-articles group server)))
899 ;; Return the articles we didn't delete.
900 (gnus-sorted-complement articles deletable-articles))))))
902 (defun nnimap-process-expiry-targets (articles group server)
903 (let ((deleted-articles nil))
905 ;; shortcut further processing if we're going to delete the articles
906 ((eq nnmail-expiry-target 'delete)
907 (setq deleted-articles articles)
909 ;; or just move them to another folder on the same IMAP server
910 ((and (not (functionp nnmail-expiry-target))
911 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
912 (gnus-server-to-method
913 (format "nnimap:%s" server))))
914 (and (nnimap-possibly-change-group group server)
915 (with-current-buffer (nnimap-buffer)
916 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
919 (nnimap-article-ranges (gnus-compress-sequence articles))
920 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
921 (setq deleted-articles articles)))
924 (dolist (article articles)
925 (let ((target nnmail-expiry-target))
927 (mm-disable-multibyte)
928 (when (nnimap-request-article article group server (current-buffer))
929 (when (functionp target)
930 (setq target (funcall target group)))
932 (not (eq target 'delete)))
933 (if (or (gnus-request-group target t)
934 (gnus-request-create-group target))
936 (nnmail-expiry-target-group target group)
937 (nnheader-message 7 "Expiring article %s:%d to %s"
938 group article target))
940 (nnheader-message 7 "Expiring article %s:%d" group article))
942 (push article deleted-articles))))))))
943 ;; Change back to the current group again.
944 (nnimap-possibly-change-group group server)
945 (setq deleted-articles (nreverse deleted-articles))
946 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
949 (defun nnimap-find-expired-articles (group)
950 (let ((cutoff (nnmail-expired-article-p group nil nil)))
951 (with-current-buffer (nnimap-buffer)
954 "UID SEARCH SENTBEFORE %s"
958 (car (rassoc (nth 4 (decode-time cutoff))
959 parse-time-months))))
962 (delete 0 (mapcar #'string-to-number
963 (cdr (assoc "SEARCH" (cdr result))))))))))
966 (defun nnimap-find-article-by-message-id (group message-id)
967 (with-current-buffer (nnimap-buffer)
969 (unless (equal group (nnimap-group nnimap-object))
970 (setf (nnimap-group nnimap-object) nil)
971 (setf (nnimap-examined nnimap-object) group)
972 (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
974 (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
976 (setq result (nnimap-wait-for-response sequence))
978 (car (setq result (nnimap-parse-response))))
979 ;; Select the last instance of the message in the group.
981 (car (last (cdr (assoc "SEARCH" (cdr result))))))
982 (string-to-number article))))))
984 (defun nnimap-delete-article (articles)
985 (with-current-buffer (nnimap-buffer)
986 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
987 (nnimap-article-ranges articles))
989 ((nnimap-capability "UIDPLUS")
990 (nnimap-command "UID EXPUNGE %s"
991 (nnimap-article-ranges articles))
994 (nnimap-command "EXPUNGE")
996 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
997 "server doesn't support UIDPLUS, so we won't "
998 "delete this article now"))))))
1000 (deffoo nnimap-request-scan (&optional group server)
1002 (setq group (nnimap-decode-gnus-group group)))
1003 (when (and (nnimap-possibly-change-group nil server)
1005 nnimap-split-methods)
1006 (nnheader-message 7 "nnimap %s splitting mail..." server)
1007 (nnimap-split-incoming-mail)
1008 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1010 (defun nnimap-marks-to-flags (marks)
1012 (dolist (mark marks)
1013 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1017 (deffoo nnimap-request-update-group-status (group status &optional server)
1018 (setq group (nnimap-decode-gnus-group group))
1019 (when (nnimap-possibly-change-group nil server)
1020 (let ((command (assoc
1022 '((subscribe "SUBSCRIBE")
1023 (unsubscribe "UNSUBSCRIBE")))))
1025 (with-current-buffer (nnimap-buffer)
1026 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1028 (deffoo nnimap-request-set-mark (group actions &optional server)
1029 (setq group (nnimap-decode-gnus-group group))
1030 (when (nnimap-possibly-change-group group server)
1032 (with-current-buffer (nnimap-buffer)
1034 ;; Just send all the STORE commands without waiting for
1035 ;; response. If they're successful, they're successful.
1036 (dolist (action actions)
1037 (destructuring-bind (range action marks) action
1038 (let ((flags (nnimap-marks-to-flags marks)))
1040 (setq sequence (nnimap-send-command
1041 "UID STORE %s %sFLAGS.SILENT (%s)"
1042 (nnimap-article-ranges range)
1044 ((eq action 'del) "-")
1045 ((eq action 'add) "+")
1046 ((eq action 'set) ""))
1047 (mapconcat #'identity flags " ")))))))
1048 ;; Wait for the last command to complete to avoid later
1049 ;; synchronization problems with the stream.
1051 (nnimap-wait-for-response sequence))))))
1053 (deffoo nnimap-request-accept-article (group &optional server last)
1054 (setq group (nnimap-decode-gnus-group group))
1055 (when (nnimap-possibly-change-group nil server)
1056 (nnmail-check-syntax)
1057 (let ((message-id (message-field-value "message-id"))
1060 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1061 (with-current-buffer (nnimap-buffer)
1062 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1064 ;; If we have this group open read-only, then unselect it
1065 ;; before appending to it.
1066 (when (equal (nnimap-examined nnimap-object) group)
1067 (nnimap-unselect-group))
1069 (setq sequence (nnimap-send-command
1070 "APPEND %S {%d}" (utf7-encode group t)
1072 (unless nnimap-streaming
1073 (nnimap-wait-for-connection "^[+]"))
1074 (process-send-string (get-buffer-process (current-buffer)) message)
1075 (process-send-string (get-buffer-process (current-buffer))
1076 (if (nnimap-newlinep nnimap-object)
1079 (let ((result (nnimap-get-response sequence)))
1080 (if (not (nnimap-ok-p result))
1082 (nnheader-report 'nnimap "%s" result)
1085 (or (nnimap-find-uid-response "APPENDUID" (car result))
1086 (nnimap-find-article-by-message-id
1087 group message-id))))))))))
1089 (defun nnimap-process-quirk (greeting-match type data)
1090 (when (and (nnimap-greeting nnimap-object)
1091 (string-match greeting-match (nnimap-greeting nnimap-object))
1093 (string-match "\000" data))
1094 (let ((choice (gnus-multiple-choice
1095 "Message contains NUL characters. Delete, continue, abort? "
1096 '((?d "Delete NUL characters")
1097 (?c "Try to APPEND the message as is")
1101 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1107 (goto-char (point-min))
1108 (while (search-forward "\000" nil t)
1109 (replace-match "" t t))
1110 (buffer-string)))))))
1112 (defun nnimap-ok-p (value)
1115 (equal (caar value) "OK")))
1117 (defun nnimap-find-uid-response (name list)
1118 (let ((result (car (last (nnimap-find-response-element name list)))))
1120 (string-to-number result))))
1122 (defun nnimap-find-response-element (name list)
1125 (when (and (consp elem)
1126 (equal name (car elem)))
1127 (setq result elem)))
1130 (deffoo nnimap-request-replace-article (article group buffer)
1131 (setq group (nnimap-decode-gnus-group group))
1133 (when (and (nnimap-possibly-change-group group nil)
1134 ;; Put the article into the group.
1135 (with-current-buffer buffer
1137 (nnimap-request-accept-article group nil t))))
1138 (nnimap-delete-article (list article))
1139 ;; Return the new article number.
1142 (defun nnimap-add-cr ()
1143 (goto-char (point-min))
1144 (while (re-search-forward "\r?\n" nil t)
1145 (replace-match "\r\n" t t)))
1147 (defun nnimap-get-groups ()
1149 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1151 (nnimap-wait-for-response sequence)
1152 (subst-char-in-region (point-min) (point-max)
1154 (goto-char (point-min))
1155 (nnimap-unfold-quoted-lines)
1156 (goto-char (point-min))
1157 (while (search-forward "* LIST " nil t)
1158 (let ((flags (read (current-buffer)))
1159 (separator (read (current-buffer)))
1160 (group (read (current-buffer))))
1161 (unless (member '%NoSelect flags)
1162 (push (utf7-decode (if (stringp group)
1164 (format "%s" group)) t)
1168 (deffoo nnimap-request-list (&optional server)
1169 (when (nnimap-possibly-change-group nil server)
1170 (with-current-buffer nntp-server-buffer
1173 (with-current-buffer (nnimap-buffer)
1174 (nnimap-get-groups)))
1175 sequences responses)
1177 (with-current-buffer (nnimap-buffer)
1178 (setf (nnimap-group nnimap-object) nil)
1179 (dolist (group groups)
1180 (setf (nnimap-examined nnimap-object) group)
1181 (push (list (nnimap-send-command "EXAMINE %S"
1182 (utf7-encode group t))
1185 (nnimap-wait-for-response (caar sequences))
1187 (nnimap-get-responses (mapcar #'car sequences))))
1188 (dolist (response responses)
1189 (let* ((sequence (car response))
1190 (response (cadr response))
1191 (group (cadr (assoc sequence sequences))))
1193 (equal (caar response) "OK"))
1194 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1196 (dolist (elem response)
1197 (when (equal (cadr elem) "EXISTS")
1198 (setq exists (string-to-number (car elem)))))
1200 (setq highest (1- (string-to-number (car uidnext)))))
1203 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1206 (insert (format "%S %d %d y\n"
1207 (utf7-decode group t)
1208 highest (1+ highest))))
1210 ;; Return the widest possible range.
1211 (insert (format "%S %d 1 y\n" (utf7-decode group t)
1212 (or highest exists)))))))))
1215 (deffoo nnimap-request-newgroups (date &optional server)
1216 (when (nnimap-possibly-change-group nil server)
1217 (with-current-buffer nntp-server-buffer
1219 (dolist (group (with-current-buffer (nnimap-buffer)
1220 (nnimap-get-groups)))
1221 (unless (assoc group nnimap-current-infos)
1222 ;; Insert dummy numbers here -- they don't matter.
1223 (insert (format "%S 0 1 y\n" (utf7-encode group)))))
1226 (deffoo nnimap-retrieve-group-data-early (server infos)
1227 (when (and (nnimap-possibly-change-group nil server)
1229 (with-current-buffer (nnimap-buffer)
1231 (setf (nnimap-group nnimap-object) nil)
1232 (setf (nnimap-initial-resync nnimap-object) 0)
1233 (let ((qresyncp (nnimap-capability "QRESYNC"))
1234 params groups sequences active uidvalidity modseq group)
1235 ;; Go through the infos and gather the data needed to know
1236 ;; what and how to request the data.
1237 (dolist (info infos)
1238 (setq params (gnus-info-params info)
1239 group (nnimap-decode-gnus-group
1240 (gnus-group-real-name (gnus-info-group info)))
1241 active (cdr (assq 'active params))
1242 uidvalidity (cdr (assq 'uidvalidity params))
1243 modseq (cdr (assq 'modseq params)))
1244 (setf (nnimap-examined nnimap-object) group)
1250 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1251 (utf7-encode group t)
1252 (nnimap-quirk "QRESYNC")
1260 ;; If we don't have a UIDVALIDITY, then this is
1261 ;; the first time we've seen the group, so we
1262 ;; have to do a SELECT (which is slower than an
1263 ;; examine), but will tell us whether the group
1264 ;; is read-only or not.
1267 (if (and active uidvalidity)
1268 ;; Fetch the last 100 flags.
1269 (setq start (max 1 (- (cdr active) 100)))
1270 (setf (nnimap-initial-resync nnimap-object)
1271 (1+ (nnimap-initial-resync nnimap-object)))
1273 (push (list (nnimap-send-command "%s %S" command
1274 (utf7-encode group t))
1275 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1276 start group command)
1280 (defun nnimap-quirk (command)
1281 (let ((quirk (assoc command nnimap-quirks)))
1282 ;; If this server is of a type that matches a quirk, then return
1283 ;; the "quirked" command instead of the proper one.
1284 (if (or (null quirk)
1285 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1289 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1290 (when (and sequences
1291 (nnimap-possibly-change-group nil server t)
1292 ;; Check that the process is still alive.
1293 (get-buffer-process (nnimap-buffer))
1294 (memq (process-status (get-buffer-process (nnimap-buffer)))
1296 (with-current-buffer (nnimap-buffer)
1297 ;; Wait for the final data to trickle in.
1298 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1302 ;; Now we should have most of the data we need, no matter
1303 ;; whether we're QRESYNCING, fetching all the flags from
1304 ;; scratch, or just fetching the last 100 flags per group.
1305 (nnimap-update-infos (nnimap-flags-to-marks
1307 (nreverse sequences)))
1309 ;; Finally, just return something resembling an active file in
1310 ;; the nntp buffer, so that the agent can save the info, too.
1311 (with-current-buffer nntp-server-buffer
1313 (dolist (info infos)
1314 (let* ((group (gnus-info-group info))
1315 (active (gnus-active group)))
1317 (insert (format "%S %d %d y\n"
1318 (decode-coding-string
1319 (gnus-group-real-name group) 'utf-8)
1321 (car active)))))))))))
1323 (defun nnimap-update-infos (flags infos)
1324 (dolist (info infos)
1325 (let* ((group (nnimap-decode-gnus-group
1326 (gnus-group-real-name (gnus-info-group info))))
1327 (marks (cdr (assoc group flags))))
1329 (nnimap-update-info info marks)))))
1331 (defun nnimap-update-info (info marks)
1332 (destructuring-bind (existing flags high low uidnext start-article
1333 permanent-flags uidvalidity
1334 vanished highestmodseq) marks
1336 ;; Ignore groups with no UIDNEXT/marks. This happens for
1337 ;; completely empty groups.
1338 ((and (not existing)
1340 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1342 (gnus-set-active (gnus-info-group info) active))))
1343 ;; We have a mismatch between the old and new UIDVALIDITY
1344 ;; identifiers, so we have to re-request the group info (the next
1345 ;; time). This virtually never happens.
1346 ((let ((old-uidvalidity
1347 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1348 (and old-uidvalidity
1349 (not (equal old-uidvalidity uidvalidity))
1350 (or (not start-article)
1351 (> start-article 1))))
1352 (gnus-group-remove-parameter info 'uidvalidity)
1353 (gnus-group-remove-parameter info 'modseq))
1354 ;; We have the data needed to update.
1356 (let* ((group (gnus-info-group info))
1357 (completep (and start-article
1358 (= start-article 1)))
1359 (active (or (gnus-active group)
1360 (cdr (assq 'active (gnus-info-params info))))))
1362 (setq high (1- uidnext)))
1363 ;; First set the active ranges based on high/low.
1365 (not (gnus-active group)))
1366 (gnus-set-active group
1369 (cons (min (or low (car active))
1371 (max (or high (cdr active))
1376 ;; No articles in this group.
1377 (cons uidnext (1- uidnext)))
1379 (cons start-article (1- start-article)))
1381 ;; No articles and no uidnext.
1383 (gnus-set-active group
1385 (or high (1- uidnext)))))
1386 ;; See whether this is a read-only group.
1387 (unless (eq permanent-flags 'not-scanned)
1388 (gnus-group-set-parameter
1389 info 'permanent-flags
1390 (and (or (memq '%* permanent-flags)
1391 (memq '%Seen permanent-flags))
1393 ;; Update marks and read articles if this isn't a
1394 ;; read-only IMAP group.
1395 (when (setq permanent-flags
1396 (cdr (assq 'permanent-flags (gnus-info-params info))))
1397 (if (and highestmodseq
1398 (not start-article))
1399 ;; We've gotten the data by QRESYNCing.
1400 (nnimap-update-qresync-info
1401 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1402 ;; Do normal non-QRESYNC flag updates.
1403 ;; Update the list of read articles.
1405 (gnus-compress-sequence
1406 (gnus-set-difference
1407 (gnus-set-difference
1409 (cdr (assoc '%Seen flags)))
1410 (cdr (assoc '%Flagged flags)))))
1411 (read (gnus-range-difference
1412 (cons start-article high) unread)))
1413 (when (> start-article 1)
1416 (if (> start-article 1)
1417 (gnus-sorted-range-intersection
1418 (cons 1 (1- start-article))
1419 (gnus-info-read info))
1420 (gnus-info-read info))
1422 (when (or (not (listp permanent-flags))
1423 (memq '%Seen permanent-flags))
1424 (gnus-info-set-read info read))
1425 ;; Update the marks.
1426 (setq marks (gnus-info-marks info))
1427 (dolist (type (cdr nnimap-mark-alist))
1428 (when (or (not (listp permanent-flags))
1429 (memq (car (assoc (caddr type) flags))
1431 (memq '%* permanent-flags))
1432 (let ((old-marks (assoc (car type) marks))
1434 (gnus-compress-sequence
1435 (cdr (or (assoc (caddr type) flags) ; %Flagged
1436 (assoc (intern (cadr type) obarray) flags)
1437 (assoc (cadr type) flags)))))) ; "\Flagged"
1438 (setq marks (delq old-marks marks))
1440 (when (and old-marks
1441 (> start-article 1))
1442 (setq old-marks (gnus-range-difference
1444 (cons start-article high)))
1445 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1447 (push (cons (car type) new-marks) marks)))))
1448 (gnus-info-set-marks info marks t))))
1449 ;; Tell Gnus whether there are any \Recent messages in any of
1451 (let ((recent (cdr (assoc '%Recent flags))))
1454 (> (car (last recent)) (cdr active)))
1455 (push (list (cons (gnus-group-real-name group) 0))
1456 nnmail-split-history)))
1457 ;; Note the active level for the next run-through.
1458 (gnus-group-set-parameter info 'active (gnus-active group))
1459 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1460 (gnus-group-set-parameter info 'modseq highestmodseq)
1461 (nnimap-store-info info (gnus-active group)))))))
1463 (defun nnimap-update-qresync-info (info existing vanished flags)
1464 ;; Add all the vanished articles to the list of read articles.
1469 (gnus-range-add (gnus-info-read info)
1471 (cdr (assq '%Flagged flags)))
1472 (cdr (assq '%Seen flags))))
1473 (let ((marks (gnus-info-marks info)))
1474 (dolist (type (cdr nnimap-mark-alist))
1475 (let ((ticks (assoc (car type) marks))
1477 (cdr (or (assoc (caddr type) flags) ; %Flagged
1478 (assoc (intern (cadr type) obarray) flags)
1479 (assoc (cadr type) flags))))) ; "\Flagged"
1480 (setq marks (delq ticks marks))
1482 ;; Add the new marks we got.
1483 (setq ticks (gnus-add-to-range ticks new-marks))
1484 ;; Remove the marks from messages that don't have them.
1485 (setq ticks (gnus-remove-from-range
1487 (gnus-compress-sequence
1488 (gnus-sorted-complement existing new-marks))))
1490 (push (cons (car type) ticks) marks)))
1491 (gnus-info-set-marks info marks t))))
1493 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1494 (if (zerop (length irange))
1497 (dolist (elem (split-string irange ","))
1499 (if (string-match ":" elem)
1500 (let ((numbers (split-string elem ":")))
1501 (cons (string-to-number (car numbers))
1502 (string-to-number (cadr numbers))))
1503 (string-to-number elem))
1505 (nreverse result))))
1507 (defun nnimap-store-info (info active)
1508 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1509 (entry (assoc group nnimap-current-infos)))
1511 (setcdr entry (list info active))
1512 (push (list group info active) nnimap-current-infos))))
1514 (defun nnimap-flags-to-marks (groups)
1515 (let (data group totalp uidnext articles start-article mark permanent-flags
1516 uidvalidity vanished highestmodseq)
1517 (dolist (elem groups)
1518 (setq group (car elem)
1519 uidnext (nth 1 elem)
1520 start-article (nth 2 elem)
1521 permanent-flags (nth 3 elem)
1522 uidvalidity (nth 4 elem)
1523 vanished (nth 5 elem)
1524 highestmodseq (nth 6 elem)
1525 articles (nthcdr 7 elem))
1526 (let ((high (caar articles))
1528 (dolist (article articles)
1529 (setq low (car article))
1530 (push (car article) existing)
1531 (dolist (flag (cdr article))
1532 (setq mark (assoc flag marks))
1534 (push (list flag (car article)) marks)
1535 (setcdr mark (cons (car article) (cdr mark))))))
1536 (push (list group existing marks high low uidnext start-article
1537 permanent-flags uidvalidity vanished highestmodseq)
1541 (defun nnimap-parse-flags (sequences)
1542 (goto-char (point-min))
1543 ;; Change \Delete etc to %Delete, so that the reader can read it.
1544 (subst-char-in-region (point-min) (point-max)
1546 ;; Remove any MODSEQ entries in the buffer, because they may contain
1547 ;; numbers that are too large for 32-bit Emacsen.
1548 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1549 (replace-match "" t t))
1550 (goto-char (point-min))
1551 (let (start end articles groups uidnext elems permanent-flags
1552 uidvalidity vanished highestmodseq)
1553 (dolist (elem sequences)
1554 (destructuring-bind (group-sequence flag-sequence totalp group command)
1556 (setq start (point))
1558 ;; The EXAMINE was successful.
1559 (search-forward (format "\n%d OK " group-sequence) nil t)
1564 (setq permanent-flags
1565 (if (equal command "SELECT")
1566 (and (search-forward "PERMANENTFLAGS "
1567 (or end (point-min)) t)
1568 (read (current-buffer)))
1572 (and (search-forward "UIDNEXT "
1573 (or end (point-min)) t)
1574 (read (current-buffer))))
1577 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1578 (or end (point-min)) t)
1579 ;; Store UIDVALIDITY as a string, as it's
1580 ;; too big for 32-bit Emacsen, usually.
1584 (and (eq flag-sequence 'qresync)
1585 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1586 (or end (point-min)) t)
1590 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1591 (or end (point-min)) t)
1595 ;; The UID FETCH FLAGS was successful.
1596 (or (eq flag-sequence 'qresync)
1597 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1598 (if (eq flag-sequence 'qresync)
1602 (setq start (point))
1604 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1606 (setq elems (read (current-buffer)))
1607 (push (cons (cadr (memq 'UID elems))
1608 (cadr (memq 'FLAGS elems)))
1610 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1611 vanished highestmodseq)
1615 (setq articles nil))))
1618 (defun nnimap-find-process-buffer (buffer)
1619 (cadr (assoc buffer nnimap-connection-alist)))
1621 (deffoo nnimap-request-post (&optional server)
1622 (setq nnimap-status-string "Read-only server")
1625 (declare-function gnus-fetch-headers "gnus-sum"
1626 (articles &optional limit force-new dependencies))
1628 (autoload 'nnir-search-thread "nnir")
1630 (deffoo nnimap-request-thread (header &optional group server)
1632 (setq group (nnimap-decode-gnus-group group)))
1633 (if gnus-refer-thread-use-nnir
1634 (nnir-search-thread header)
1635 (when (nnimap-possibly-change-group group server)
1636 (let* ((cmd (nnimap-make-thread-query header))
1637 (result (with-current-buffer (nnimap-buffer)
1638 (nnimap-command "UID SEARCH %s" cmd))))
1642 (delete 0 (mapcar #'string-to-number
1643 (cdr (assoc "SEARCH" (cdr result))))))
1646 (defun nnimap-possibly-change-group (group server &optional no-reconnect)
1647 (let ((open-result t))
1649 (not (nnimap-server-opened server)))
1650 (setq open-result (nnimap-open-server server nil no-reconnect)))
1657 (with-current-buffer (nnimap-buffer)
1658 (if (equal group (nnimap-group nnimap-object))
1660 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1662 (setf (nnimap-group nnimap-object) group
1663 (nnimap-select-result nnimap-object) result)
1666 (defun nnimap-find-connection (buffer)
1667 "Find the connection delivering to BUFFER."
1668 (let ((entry (assoc buffer nnimap-connection-alist)))
1670 (if (and (buffer-name (cadr entry))
1671 (get-buffer-process (cadr entry))
1672 (memq (process-status (get-buffer-process (cadr entry)))
1674 (get-buffer-process (cadr entry))
1675 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1678 (defvar nnimap-sequence 0)
1680 (defun nnimap-send-command (&rest args)
1681 (setf (nnimap-last-command-time nnimap-object) (current-time))
1682 (process-send-string
1683 (get-buffer-process (current-buffer))
1686 (incf nnimap-sequence)
1687 (apply #'format args)
1688 (if (nnimap-newlinep nnimap-object)
1691 ;; Some servers apparently can't have many outstanding
1692 ;; commands, so throttle them.
1693 (unless nnimap-streaming
1694 (nnimap-wait-for-response nnimap-sequence))
1697 (defun nnimap-log-command (command)
1698 (with-current-buffer (get-buffer-create "*imap log*")
1699 (goto-char (point-max))
1700 (insert (format-time-string "%H:%M:%S") " "
1701 (if nnimap-inhibit-logging
1706 (defun nnimap-command (&rest args)
1708 (let* ((sequence (apply #'nnimap-send-command args))
1709 (response (nnimap-get-response sequence)))
1710 (if (equal (caar response) "OK")
1712 (nnheader-report 'nnimap "%s"
1713 (mapconcat (lambda (a)
1715 (car response) " "))
1718 (defun nnimap-get-response (sequence)
1719 (nnimap-wait-for-response sequence)
1720 (nnimap-parse-response))
1722 (defun nnimap-wait-for-connection (&optional regexp)
1723 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1725 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1726 (let ((process (get-buffer-process (current-buffer))))
1727 (goto-char (point-min))
1728 (while (and (memq (process-status process)
1730 (not (re-search-forward regexp nil t)))
1731 (nnheader-accept-process-output process)
1732 (goto-char (point-min)))
1734 (and (looking-at (or response-regexp regexp))
1737 (defun nnimap-wait-for-response (sequence &optional messagep)
1738 (let ((process (get-buffer-process (current-buffer)))
1742 (goto-char (point-max))
1743 (while (and (setq openp (memq (process-status process)
1746 ;; Skip past any "*" lines that the server has
1748 (while (and (not (bobp))
1751 (looking-at "\\*"))))
1752 (not (looking-at (format "%d .*\n" sequence)))))
1754 (nnheader-message-maybe
1755 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1757 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1758 (format " (initial sync of %d groups; please wait)"
1759 (nnimap-initial-resync nnimap-object))
1761 (nnheader-accept-process-output process)
1762 (goto-char (point-max)))
1763 (setf (nnimap-initial-resync nnimap-object) 0)
1768 ;; The user hit C-g while we were waiting: kill the process, in case
1769 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1771 (delete-process process)
1774 (defun nnimap-parse-response ()
1775 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1777 (dolist (line lines)
1778 (push (cdr (nnimap-parse-line line)) result))
1779 ;; Return the OK/error code first, and then all the "continuation
1780 ;; lines" afterwards.
1782 (nreverse result))))
1784 ;; Parse an IMAP response line lightly. They look like
1785 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1786 ;; the lines into a list of strings and lists of string.
1787 (defun nnimap-parse-line (line)
1790 (mm-disable-multibyte)
1792 (goto-char (point-min))
1794 (if (eql (setq char (following-char)) ? )
1802 (if (search-forward "]" (line-end-position) 'move)
1809 (if (search-forward ")" (line-end-position) 'move)
1816 (1- (or (search-forward "\"" (line-end-position) 'move)
1819 (buffer-substring (point) (if (search-forward " " nil t)
1821 (goto-char (point-max))))))
1823 (nreverse result))))
1825 (defun nnimap-last-response-string ()
1828 (let ((end (point)))
1832 (while (and (not (bobp))
1833 (eql (following-char) ?*))
1835 (unless (eql (following-char) ?*)
1837 (buffer-substring (point) end))))
1839 (defun nnimap-get-responses (sequences)
1841 (dolist (sequence sequences)
1842 (goto-char (point-min))
1843 (when (re-search-forward (format "^%d " sequence) nil t)
1844 (push (list sequence (nnimap-parse-response))
1848 (defvar nnimap-incoming-split-list nil)
1850 (defun nnimap-fetch-inbox (articles)
1852 (nnimap-wait-for-response
1853 (nnimap-send-command
1855 (nnimap-article-ranges articles)
1856 (format "(UID %s%s)"
1862 (nnimap-split-download-body-default
1870 (defun nnimap-split-incoming-mail ()
1871 (with-current-buffer (nnimap-buffer)
1872 (let ((nnimap-incoming-split-list nil)
1873 (nnmail-split-methods
1875 ((eq nnimap-split-methods 'default)
1876 nnmail-split-methods)
1877 (nnimap-split-methods
1878 nnimap-split-methods)
1880 'nnmail-split-fancy)))
1881 (nnmail-split-fancy (or nnimap-split-fancy
1882 nnmail-split-fancy))
1883 (nnmail-inhibit-default-split-group t)
1884 (groups (nnimap-get-groups))
1887 (nnimap-command "SELECT %S" nnimap-inbox)
1888 (setf (nnimap-group nnimap-object) nnimap-inbox)
1889 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1891 (nnimap-fetch-inbox new-articles)
1892 (nnimap-transform-split-mail)
1893 (nnheader-ms-strip-cr)
1895 (nnmail-split-incoming (current-buffer)
1896 #'nnimap-save-mail-spec
1898 #'nnimap-dummy-active-number
1899 #'nnimap-save-mail-spec)
1900 (when nnimap-incoming-split-list
1901 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1902 sequences junk-articles)
1903 ;; Create any groups that doesn't already exist on the
1905 (dolist (spec specs)
1906 (when (and (not (member (car spec) groups))
1907 (not (eq (car spec) 'junk)))
1908 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1909 ;; Then copy over all the messages.
1911 (dolist (spec specs)
1912 (let ((group (car spec))
1913 (ranges (cdr spec)))
1914 (if (eq group 'junk)
1915 (setq junk-articles ranges)
1916 (push (list (nnimap-send-command
1918 (nnimap-article-ranges ranges)
1919 (utf7-encode group t))
1922 ;; Wait for the last COPY response...
1924 (nnimap-wait-for-response (caar sequences))
1925 ;; And then mark the successful copy actions as deleted,
1926 ;; and possibly expunge them.
1927 (nnimap-mark-and-expunge-incoming
1928 (nnimap-parse-copied-articles sequences)))
1929 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1931 (defun nnimap-mark-and-expunge-incoming (range)
1933 (setq range (nnimap-article-ranges range))
1936 (nnimap-send-command
1937 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1939 ;; If the server supports it, we now delete the message we have
1940 ;; just copied over.
1941 ((nnimap-capability "UIDPLUS")
1942 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1943 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1944 ;; user has configured it.
1946 (setq sequence (nnimap-send-command "EXPUNGE"))))
1947 (nnimap-wait-for-response sequence))))
1949 (defun nnimap-parse-copied-articles (sequences)
1950 (let (sequence copied range)
1951 (goto-char (point-min))
1952 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1953 (setq sequence (string-to-number (match-string 1)))
1954 (when (setq range (cadr (assq sequence sequences)))
1955 (push (gnus-uncompress-range range) copied)))
1956 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1958 (defun nnimap-new-articles (flags)
1960 (dolist (elem flags)
1961 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1963 (push (car elem) new)))
1964 (gnus-compress-sequence (nreverse new))))
1966 (defun nnimap-make-split-specs (list)
1970 (destructuring-bind (article spec) elem
1971 (dolist (group (delete nil (mapcar #'car spec)))
1972 (unless (setq entry (assoc group specs))
1973 (push (setq entry (list group)) specs))
1974 (setcdr entry (cons article (cdr entry))))))
1975 (dolist (entry specs)
1976 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1979 (defun nnimap-transform-split-mail ()
1980 (goto-char (point-min))
1981 (let (article bytes)
1984 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
1985 (delete-region (point) (progn (forward-line 1) (point)))
1988 (setq article (match-string 1)
1989 bytes (nnimap-get-length))
1990 (delete-region (line-beginning-position) (line-end-position))
1991 ;; Insert MMDF separator, and a way to remember what this
1993 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1994 (forward-char (1+ bytes))
1995 (setq bytes (nnimap-get-length))
1996 (delete-region (line-beginning-position) (line-end-position))
1997 ;; There's a body; skip past that.
1999 (forward-char (1+ bytes))
2000 (delete-region (line-beginning-position) (line-end-position)))))))
2002 (defun nnimap-dummy-active-number (group &optional server)
2005 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2007 (goto-char (point-min))
2008 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2009 (error "Invalid nnimap mail")
2010 (setq article (string-to-number (match-string 1))))
2012 (if (eq group-art 'junk)
2013 (list (cons 'junk 1))
2015 nnimap-incoming-split-list)))
2017 (defun nnimap-make-thread-query (header)
2018 (let* ((id (mail-header-id header))
2020 (or (mail-header-references header)
2024 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2026 (dolist (refid refs value)
2028 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2029 refid refid value)))))
2034 ;;; nnimap.el ends here