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 bytes lines size string)
195 (while (not (looking-at "\\* [0-9]+ FETCH.+?UID \\([0-9]+\\)"))
196 (delete-region (point) (progn (forward-line 1) (point)))
199 (setq article (match-string 1))
200 ;; Unfold quoted {number} strings.
201 (while (re-search-forward "[^]][ (]{\\([0-9]+\\)}\r?\n"
202 (1+ (line-end-position)) t)
203 (setq size (string-to-number (match-string 1)))
204 (delete-region (+ (match-beginning 0) 2) (point))
205 (setq string (buffer-substring (point) (+ (point) size)))
206 (delete-region (point) (+ (point) size))
207 (insert (format "%S" string)))
208 (setq bytes (nnimap-get-length)
212 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
217 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
218 (let ((structure (ignore-errors
219 (read (current-buffer)))))
220 (while (and (consp structure)
221 (not (atom (car structure))))
222 (setq structure (car structure)))
224 (stringp (car structure))
225 (equal (upcase (nth 0 structure)) "MESSAGE")
226 (equal (upcase (nth 1 structure)) "RFC822"))
228 (nth 7 structure)))))
229 (delete-region (line-beginning-position) (line-end-position))
230 (insert (format "211 %s Article retrieved." article))
233 (insert (format "Chars: %s\n" size)))
235 (insert (format "Lines: %s\n" lines)))
236 (unless (re-search-forward "^\r$" nil t)
237 (goto-char (point-max)))
238 (delete-region (line-beginning-position) (line-end-position))
242 (defun nnimap-unfold-quoted-lines ()
243 ;; Unfold quoted {number} strings.
245 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
246 (setq size (string-to-number (match-string 1)))
247 (delete-region (1+ (match-beginning 0)) (point))
248 (setq string (buffer-substring (point) (+ (point) size)))
249 (delete-region (point) (+ (point) size))
250 (insert (format "%S" string)))))
252 (defun nnimap-get-length ()
253 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
254 (string-to-number (match-string 1))))
256 (defun nnimap-article-ranges (ranges)
260 (number-to-string ranges))
261 ((numberp (cdr ranges))
262 (format "%d:%d" (car ranges) (cdr ranges)))
264 (dolist (elem ranges)
267 (format "%d:%d" (car elem) (cdr elem))
268 (number-to-string elem))
270 (mapconcat #'identity (nreverse result) ",")))))
272 (deffoo nnimap-open-server (server &optional defs no-reconnect)
273 (if (nnimap-server-opened server)
275 (unless (assq 'nnimap-address defs)
276 (setq defs (append defs (list (list 'nnimap-address server)))))
277 (nnoo-change-server 'nnimap server defs)
279 (nnimap-find-connection nntp-server-buffer)
280 (or (nnimap-find-connection nntp-server-buffer)
281 (nnimap-open-connection nntp-server-buffer)))))
283 (defun nnimap-make-process-buffer (buffer)
285 (generate-new-buffer (format "*nnimap %s %s %s*"
286 nnimap-address nnimap-server-port
287 (gnus-buffer-exists-p buffer)))
288 (mm-disable-multibyte)
289 (buffer-disable-undo)
291 (set (make-local-variable 'after-change-functions) nil)
292 (set (make-local-variable 'nnimap-object)
293 (make-nnimap :server (nnoo-current-server 'nnimap)
295 (push (list buffer (current-buffer)) nnimap-connection-alist)
296 (push (current-buffer) nnimap-process-buffers)
299 (defun nnimap-credentials (address ports user)
300 (let* ((auth-source-creation-prompts
301 '((user . "IMAP user at %h: ")
302 (secret . "IMAP password for %u@%h: ")))
303 (found (nth 0 (auth-source-search :max 1
307 :require '(:user :secret)
310 (list (plist-get found :user)
311 (let ((secret (plist-get found :secret)))
312 (if (functionp secret)
315 (plist-get found :save-function))
318 (defun nnimap-keepalive ()
319 (let ((now (current-time)))
320 (dolist (buffer nnimap-process-buffers)
321 (when (buffer-name buffer)
322 (with-current-buffer buffer
323 (when (and nnimap-object
324 (nnimap-last-command-time nnimap-object)
328 (nnimap-last-command-time nnimap-object)))
329 ;; More than five minutes since the last command.
331 (nnimap-send-command "NOOP")))))))
333 (defun nnimap-open-connection (buffer)
334 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
335 ;; `ssl' when nnimap-server-port was nil. Sort of.
336 (when (and nnimap-server-port
337 (eq nnimap-stream 'undecided))
338 (setq nnimap-stream 'ssl))
340 (if (eq nnimap-stream 'undecided)
341 (loop for type in '(ssl network)
342 for stream = (let ((nnimap-stream type))
343 (nnimap-open-connection-1 buffer))
344 while (eq stream 'no-connect)
345 finally (return stream))
346 (nnimap-open-connection-1 buffer))))
347 (if (eq stream 'no-connect)
351 (defun nnimap-map-port (port)
352 (if (equal port "imaps")
356 (defun nnimap-open-connection-1 (buffer)
357 (unless nnimap-keepalive-timer
358 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
360 (with-current-buffer (nnimap-make-process-buffer buffer)
361 (let* ((coding-system-for-read 'binary)
362 (coding-system-for-write 'binary)
365 ((memq nnimap-stream '(network plain starttls))
366 (nnheader-message 7 "Opening connection to %s..."
369 ((eq nnimap-stream 'shell)
370 (nnheader-message 7 "Opening connection to %s via shell..."
373 ((memq nnimap-stream '(ssl tls))
374 (nnheader-message 7 "Opening connection to %s via tls..."
376 '("imaps" "imap" "993" "143"))
378 (error "Unknown stream type: %s" nnimap-stream))))
379 login-result credentials)
380 (when nnimap-server-port
381 (push nnimap-server-port ports))
383 (open-protocol-stream
384 "*nnimap*" (current-buffer) nnimap-address
385 (nnimap-map-port (car ports))
388 :shell-command nnimap-shell-program
389 :capability-command "1 CAPABILITY\r\n"
390 :end-of-command "\r\n"
393 (lambda (capabilities)
394 (when (gnus-string-match-p "STARTTLS" capabilities)
396 (stream (car stream-list))
397 (props (cdr stream-list))
398 (greeting (plist-get props :greeting))
399 (capabilities (plist-get props :capabilities))
400 (stream-type (plist-get props :type)))
401 (when (and stream (not (memq (process-status stream) '(open run))))
404 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
405 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
406 (eq (process-type stream) 'network))
407 ;; Use TCP-keepalive so that connections that pass through a NAT
408 ;; router don't hang when left idle.
409 (set-network-process-option stream :keepalive t))
411 (setf (nnimap-process nnimap-object) stream)
412 (setf (nnimap-stream-type nnimap-object) stream-type)
415 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
416 nnimap-address (car ports) nnimap-stream)
418 (gnus-set-process-query-on-exit-flag stream nil)
419 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
420 (nnheader-report 'nnimap "%s" greeting)
421 ;; Store the greeting (for debugging purposes).
422 (setf (nnimap-greeting nnimap-object) greeting)
423 (setf (nnimap-capabilities nnimap-object)
425 (split-string capabilities)))
426 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
427 (if (not (setq credentials
428 (if (eq nnimap-authenticator 'anonymous)
430 (message-make-address))
431 ;; Look for the credentials based on
432 ;; the virtual server name and the address
434 (gnus-delete-duplicates
437 (nnoo-current-server 'nnimap)))
440 (setq nnimap-object nil)
441 (let ((nnimap-inhibit-logging t))
443 (nnimap-login (car credentials) (cadr credentials))))
444 (if (car login-result)
446 ;; Save the credentials if a save function exists
447 ;; (such a function will only be passed if a new
448 ;; token was created).
449 (when (functionp (nth 2 credentials))
450 (funcall (nth 2 credentials)))
451 ;; See if CAPABILITY is set as part of login
453 (dolist (response (cddr login-result))
454 (when (string= "CAPABILITY" (upcase (car response)))
455 (setf (nnimap-capabilities nnimap-object)
456 (mapcar #'upcase (cdr response))))))
457 ;; If the login failed, then forget the credentials
458 ;; that are now possibly cached.
459 (dolist (host (list (nnoo-current-server 'nnimap)
462 (auth-source-forget+ :host host :port port)))
463 (delete-process (nnimap-process nnimap-object))
464 (setq nnimap-object nil))))
466 (when (nnimap-capability "QRESYNC")
467 (nnimap-command "ENABLE QRESYNC"))
468 (nnimap-process nnimap-object))))))))
470 (autoload 'rfc2104-hash "rfc2104")
472 (defun nnimap-login (user password)
474 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
475 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
476 ;; and we're using an encrypted connection.
477 ((and (not (nnimap-capability "LOGINDISABLED"))
478 (eq (nnimap-stream-type nnimap-object) 'tls))
479 (nnimap-command "LOGIN %S %S" user password))
480 ((nnimap-capability "AUTH=CRAM-MD5")
482 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
483 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
485 (get-buffer-process (current-buffer))
487 (base64-encode-string
489 (rfc2104-hash 'md5 64 16 password
490 (base64-decode-string challenge))))
492 (nnimap-wait-for-response sequence)))
493 ((not (nnimap-capability "LOGINDISABLED"))
494 (nnimap-command "LOGIN %S %S" user password))
495 ((nnimap-capability "AUTH=PLAIN")
497 "AUTHENTICATE PLAIN %s"
498 (base64-encode-string
499 (format "\000%s\000%s"
500 (nnimap-quote-specials user)
501 (nnimap-quote-specials password)))))))
503 (defun nnimap-quote-specials (string)
506 (goto-char (point-min))
507 (while (re-search-forward "[\\\"]" nil t)
513 (defun nnimap-find-parameter (parameter elems)
517 ((equal (car elem) parameter)
518 (setq result (cdr elem)))
519 ((and (equal (car elem) "OK")
521 (equal (caadr elem) parameter))
522 (setq result (cdr (cadr elem))))))
525 (deffoo nnimap-close-server (&optional server)
526 (when (nnoo-change-server 'nnimap server nil)
528 (delete-process (get-buffer-process (nnimap-buffer))))
529 (nnoo-close-server 'nnimap server)
532 (deffoo nnimap-request-close ()
535 (deffoo nnimap-server-opened (&optional server)
536 (and (nnoo-current-server-p 'nnimap server)
538 (gnus-buffer-live-p nntp-server-buffer)
539 (nnimap-find-connection nntp-server-buffer)))
541 (deffoo nnimap-status-message (&optional server)
542 nnimap-status-string)
544 (deffoo nnimap-request-article (article &optional group server to-buffer)
546 (setq group (nnimap-decode-gnus-group group)))
547 (with-current-buffer nntp-server-buffer
548 (let ((result (nnimap-possibly-change-group group server))
550 (when (stringp article)
551 (setq article (nnimap-find-article-by-message-id group article)))
555 (with-current-buffer (nnimap-buffer)
557 (when nnimap-fetch-partial-articles
558 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
559 (goto-char (point-min))
560 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
561 (setq structure (ignore-errors
562 (let ((start (point)))
564 (downcase-region start (point))
566 (read (current-buffer))))
567 parts (nnimap-find-wanted-parts structure))))
569 (nnimap-get-partial-article article parts structure)
570 (nnimap-get-whole-article article))
571 (let ((buffer (current-buffer)))
572 (with-current-buffer (or to-buffer nntp-server-buffer)
573 (nnheader-insert-buffer-substring buffer)
574 (nnheader-ms-strip-cr)))
575 (cons group article)))))))
577 (deffoo nnimap-request-head (article &optional group server to-buffer)
579 (setq group (nnimap-decode-gnus-group group)))
580 (when (nnimap-possibly-change-group group server)
581 (with-current-buffer (nnimap-buffer)
582 (when (stringp article)
583 (setq article (nnimap-find-article-by-message-id group article)))
586 (nnimap-get-whole-article
587 article (format "UID FETCH %%d %s"
588 (nnimap-header-parameters)))
589 (let ((buffer (current-buffer)))
590 (with-current-buffer (or to-buffer nntp-server-buffer)
592 (insert-buffer-substring buffer)
593 (nnheader-ms-strip-cr)
594 (cons group article)))))))
596 (defun nnimap-get-whole-article (article &optional command)
601 "UID FETCH %d BODY.PEEK[]"
602 "UID FETCH %d RFC822.PEEK"))
604 ;; Check that we really got an article.
605 (goto-char (point-min))
606 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
609 ;; Remove any data that may have arrived before the FETCH data.
612 (delete-region (point-min) (point)))
613 (let ((bytes (nnimap-get-length)))
614 (delete-region (line-beginning-position)
615 (progn (forward-line 1) (point)))
616 (goto-char (+ (point) bytes))
617 (delete-region (point) (point-max)))
620 (defun nnimap-capability (capability)
621 (member capability (nnimap-capabilities nnimap-object)))
623 (defun nnimap-ver4-p ()
624 (nnimap-capability "IMAP4REV1"))
626 (defun nnimap-get-partial-article (article parts structure)
629 "UID FETCH %d (%s %s)"
635 (mapconcat (lambda (part)
636 (format "BODY.PEEK[%s]" part))
638 (mapconcat (lambda (part)
639 (format "RFC822.PEEK[%s]" part))
642 (nnimap-convert-partial-article structure))))
644 (defun nnimap-convert-partial-article (structure)
645 ;; First just skip past the headers.
646 (goto-char (point-min))
647 (let ((bytes (nnimap-get-length))
649 ;; Delete "FETCH" line.
650 (delete-region (line-beginning-position)
651 (progn (forward-line 1) (point)))
652 (goto-char (+ (point) bytes))
653 ;; Collect all the body parts.
654 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
655 (setq id (match-string 1)
656 bytes (or (nnimap-get-length) 0))
658 (delete-region (point) (progn (forward-line 1) (point)))
659 (push (list id (buffer-substring (point) (+ (point) bytes)))
661 (delete-region (point) (+ (point) bytes)))
662 ;; Delete trailing junk.
663 (delete-region (point) (point-max))
664 ;; Now insert all the parts again where they fit in the structure.
665 (nnimap-insert-partial-structure structure parts)
668 (defun nnimap-insert-partial-structure (structure parts &optional subp)
670 (let ((bstruc structure))
671 (while (consp (car bstruc))
673 (setq type (car bstruc))
674 (setq bstruc (car (cdr bstruc)))
675 (let ((has-boundary (member "boundary" bstruc)))
677 (setq boundary (cadr has-boundary)))))
679 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
680 (downcase type) boundary)))
681 (while (not (stringp (car structure)))
682 (insert "\n--" boundary "\n")
683 (if (consp (caar structure))
684 (nnimap-insert-partial-structure (pop structure) parts t)
685 (let ((bit (pop structure)))
686 (insert (format "Content-type: %s/%s"
687 (downcase (nth 0 bit))
688 (downcase (nth 1 bit))))
689 (if (member-ignore-case "CHARSET" (nth 2 bit))
692 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
694 (insert (format "Content-transfer-encoding: %s\n"
697 (when (assoc (nth 9 bit) parts)
698 (insert (cadr (assoc (nth 9 bit) parts)))))))
699 (insert "\n--" boundary "--\n")))
701 (defun nnimap-find-wanted-parts (structure)
702 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
704 (defun nnimap-find-wanted-parts-1 (structure prefix)
707 (while (consp (car structure))
708 (let ((sub (pop structure)))
709 (if (consp (car sub))
710 (push (nnimap-find-wanted-parts-1
711 sub (if (string= prefix "")
712 (number-to-string num)
713 (format "%s.%s" prefix num)))
715 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
716 (id (if (string= prefix "")
717 (number-to-string num)
718 (format "%s.%s" prefix num))))
719 (setcar (nthcdr 9 sub) id)
720 (when (if (eq nnimap-fetch-partial-articles t)
722 (string-match nnimap-fetch-partial-articles type))
727 (defun nnimap-decode-gnus-group (group)
728 (decode-coding-string group 'utf-8))
730 (deffoo nnimap-request-group (group &optional server dont-check info)
731 (setq group (nnimap-decode-gnus-group group))
732 (let ((result (nnimap-possibly-change-group
733 ;; Don't SELECT the group if we're going to select it
735 (if (and (not dont-check)
736 (assoc group nnimap-current-infos))
740 articles active marks high low)
741 (with-current-buffer nntp-server-buffer
744 (setq active (nth 2 (assoc group nnimap-current-infos))))
745 (insert (format "211 %d %d %d %S\n"
746 (- (cdr active) (car active))
750 (with-current-buffer (nnimap-buffer)
752 (let ((group-sequence
753 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
755 (nnimap-send-command "UID FETCH 1:* FLAGS")))
756 (setf (nnimap-group nnimap-object) group)
757 (nnimap-wait-for-response flag-sequence)
759 (nnimap-flags-to-marks
761 (list (list group-sequence flag-sequence
762 1 group "SELECT")))))
765 (nnimap-update-infos marks (list info))
766 (nnimap-store-info info (gnus-active (gnus-info-group info))))
767 (goto-char (point-max))
768 (let ((uidnext (nth 5 (car marks))))
769 (setq high (or (if uidnext
773 low (or (nth 4 (car marks)) uidnext 1)))))
777 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
780 (deffoo nnimap-request-create-group (group &optional server args)
781 (setq group (nnimap-decode-gnus-group group))
782 (when (nnimap-possibly-change-group nil server)
783 (with-current-buffer (nnimap-buffer)
784 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
786 (deffoo nnimap-request-delete-group (group &optional force server)
787 (setq group (nnimap-decode-gnus-group group))
788 (when (nnimap-possibly-change-group nil server)
789 (with-current-buffer (nnimap-buffer)
790 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
792 (deffoo nnimap-request-rename-group (group new-name &optional server)
793 (setq group (nnimap-decode-gnus-group group))
794 (when (nnimap-possibly-change-group nil server)
795 (with-current-buffer (nnimap-buffer)
796 (nnimap-unselect-group)
797 (car (nnimap-command "RENAME %S %S"
798 (utf7-encode group t) (utf7-encode new-name t))))))
800 (defun nnimap-unselect-group ()
801 ;; Make sure we don't have this group open read/write by asking
802 ;; to examine a mailbox that doesn't exist. This seems to be
803 ;; the only way that allows us to reliably go back to unselected
805 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
807 (deffoo nnimap-request-expunge-group (group &optional server)
808 (setq group (nnimap-decode-gnus-group group))
809 (when (nnimap-possibly-change-group group server)
810 (with-current-buffer (nnimap-buffer)
811 (car (nnimap-command "EXPUNGE")))))
813 (defun nnimap-get-flags (spec)
816 (with-current-buffer (nnimap-buffer)
818 (nnimap-wait-for-response (nnimap-send-command
819 "UID FETCH %s FLAGS" spec))
821 (subst-char-in-region (point-min) (point-max)
823 (goto-char (point-min))
824 (while (search-forward " FETCH " end t)
825 (setq elems (read (current-buffer)))
826 (push (cons (cadr (memq 'UID elems))
827 (cadr (memq 'FLAGS elems)))
829 (nreverse articles)))
831 (deffoo nnimap-close-group (group &optional server)
834 (deffoo nnimap-request-move-article (article group server accept-form
835 &optional last internal-move-group)
836 (setq group (nnimap-decode-gnus-group group))
838 (mm-disable-multibyte)
839 (when (funcall (if internal-move-group
841 'nnimap-request-article)
842 article group server (current-buffer))
843 ;; If the move is internal (on the same server), just do it the easy
845 (let ((message-id (message-field-value "message-id")))
846 (if internal-move-group
848 (with-current-buffer (nnimap-buffer)
849 (nnimap-command "UID COPY %d %S"
851 (utf7-encode internal-move-group t)))))
853 (nnimap-delete-article article)
854 (cons internal-move-group
855 (or (nnimap-find-uid-response "COPYUID" (cadr result))
856 (nnimap-find-article-by-message-id
857 internal-move-group message-id)))))
858 ;; Move the article to a different method.
859 (let ((result (eval accept-form)))
861 (nnimap-delete-article article)
864 (deffoo nnimap-request-expire-articles (articles group &optional server force)
865 (setq group (nnimap-decode-gnus-group group))
869 ((not (nnimap-possibly-change-group group server))
872 (eq nnmail-expiry-target 'delete))
873 (unless (nnimap-delete-article (gnus-compress-sequence articles))
874 (nnheader-message 7 "Article marked for deletion, but not expunged."))
877 (let ((deletable-articles
879 (eq nnmail-expiry-wait 'immediate))
881 (gnus-sorted-intersection
883 (nnimap-find-expired-articles group)))))
884 (if (null deletable-articles)
886 (if (eq nnmail-expiry-target 'delete)
887 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
888 (setq deletable-articles
889 (nnimap-process-expiry-targets
890 deletable-articles group server)))
891 ;; Return the articles we didn't delete.
892 (gnus-sorted-complement articles deletable-articles))))))
894 (defun nnimap-process-expiry-targets (articles group server)
895 (let ((deleted-articles nil))
897 ;; shortcut further processing if we're going to delete the articles
898 ((eq nnmail-expiry-target 'delete)
899 (setq deleted-articles articles)
901 ;; or just move them to another folder on the same IMAP server
902 ((and (not (functionp nnmail-expiry-target))
903 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
904 (gnus-server-to-method
905 (format "nnimap:%s" server))))
906 (and (nnimap-possibly-change-group group server)
907 (with-current-buffer (nnimap-buffer)
908 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
911 (nnimap-article-ranges (gnus-compress-sequence articles))
912 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
913 (setq deleted-articles articles)))
916 (dolist (article articles)
917 (let ((target nnmail-expiry-target))
919 (mm-disable-multibyte)
920 (when (nnimap-request-article article group server (current-buffer))
921 (when (functionp target)
922 (setq target (funcall target group)))
924 (not (eq target 'delete)))
925 (if (or (gnus-request-group target t)
926 (gnus-request-create-group target))
928 (nnmail-expiry-target-group target group)
929 (nnheader-message 7 "Expiring article %s:%d to %s"
930 group article target))
932 (nnheader-message 7 "Expiring article %s:%d" group article))
934 (push article deleted-articles))))))))
935 ;; Change back to the current group again.
936 (nnimap-possibly-change-group group server)
937 (setq deleted-articles (nreverse deleted-articles))
938 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
941 (defun nnimap-find-expired-articles (group)
942 (let ((cutoff (nnmail-expired-article-p group nil nil)))
943 (with-current-buffer (nnimap-buffer)
946 "UID SEARCH SENTBEFORE %s"
950 (car (rassoc (nth 4 (decode-time cutoff))
951 parse-time-months))))
954 (delete 0 (mapcar #'string-to-number
955 (cdr (assoc "SEARCH" (cdr result))))))))))
958 (defun nnimap-find-article-by-message-id (group message-id)
959 (with-current-buffer (nnimap-buffer)
961 (unless (equal group (nnimap-group nnimap-object))
962 (setf (nnimap-group nnimap-object) nil)
963 (setf (nnimap-examined nnimap-object) group)
964 (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
966 (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
968 (setq result (nnimap-wait-for-response sequence))
970 (car (setq result (nnimap-parse-response))))
971 ;; Select the last instance of the message in the group.
973 (car (last (cdr (assoc "SEARCH" (cdr result))))))
974 (string-to-number article))))))
976 (defun nnimap-delete-article (articles)
977 (with-current-buffer (nnimap-buffer)
978 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
979 (nnimap-article-ranges articles))
981 ((nnimap-capability "UIDPLUS")
982 (nnimap-command "UID EXPUNGE %s"
983 (nnimap-article-ranges articles))
986 (nnimap-command "EXPUNGE")
988 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
989 "server doesn't support UIDPLUS, so we won't "
990 "delete this article now"))))))
992 (deffoo nnimap-request-scan (&optional group server)
994 (setq group (nnimap-decode-gnus-group group)))
995 (when (and (nnimap-possibly-change-group nil server)
997 nnimap-split-methods)
998 (nnheader-message 7 "nnimap %s splitting mail..." server)
999 (nnimap-split-incoming-mail)
1000 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1002 (defun nnimap-marks-to-flags (marks)
1004 (dolist (mark marks)
1005 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1009 (deffoo nnimap-request-update-group-status (group status &optional server)
1010 (setq group (nnimap-decode-gnus-group group))
1011 (when (nnimap-possibly-change-group nil server)
1012 (let ((command (assoc
1014 '((subscribe "SUBSCRIBE")
1015 (unsubscribe "UNSUBSCRIBE")))))
1017 (with-current-buffer (nnimap-buffer)
1018 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1020 (deffoo nnimap-request-set-mark (group actions &optional server)
1021 (setq group (nnimap-decode-gnus-group group))
1022 (when (nnimap-possibly-change-group group server)
1024 (with-current-buffer (nnimap-buffer)
1026 ;; Just send all the STORE commands without waiting for
1027 ;; response. If they're successful, they're successful.
1028 (dolist (action actions)
1029 (destructuring-bind (range action marks) action
1030 (let ((flags (nnimap-marks-to-flags marks)))
1032 (setq sequence (nnimap-send-command
1033 "UID STORE %s %sFLAGS.SILENT (%s)"
1034 (nnimap-article-ranges range)
1036 ((eq action 'del) "-")
1037 ((eq action 'add) "+")
1038 ((eq action 'set) ""))
1039 (mapconcat #'identity flags " ")))))))
1040 ;; Wait for the last command to complete to avoid later
1041 ;; synchronization problems with the stream.
1043 (nnimap-wait-for-response sequence))))))
1045 (deffoo nnimap-request-accept-article (group &optional server last)
1046 (setq group (nnimap-decode-gnus-group group))
1047 (when (nnimap-possibly-change-group nil server)
1048 (nnmail-check-syntax)
1049 (let ((message-id (message-field-value "message-id"))
1052 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1053 (with-current-buffer (nnimap-buffer)
1054 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1056 ;; If we have this group open read-only, then unselect it
1057 ;; before appending to it.
1058 (when (equal (nnimap-examined nnimap-object) group)
1059 (nnimap-unselect-group))
1061 (setq sequence (nnimap-send-command
1062 "APPEND %S {%d}" (utf7-encode group t)
1064 (unless nnimap-streaming
1065 (nnimap-wait-for-connection "^[+]"))
1066 (process-send-string (get-buffer-process (current-buffer)) message)
1067 (process-send-string (get-buffer-process (current-buffer))
1068 (if (nnimap-newlinep nnimap-object)
1071 (let ((result (nnimap-get-response sequence)))
1072 (if (not (nnimap-ok-p result))
1074 (nnheader-report 'nnimap "%s" result)
1077 (or (nnimap-find-uid-response "APPENDUID" (car result))
1078 (nnimap-find-article-by-message-id
1079 group message-id))))))))))
1081 (defun nnimap-process-quirk (greeting-match type data)
1082 (when (and (nnimap-greeting nnimap-object)
1083 (string-match greeting-match (nnimap-greeting nnimap-object))
1085 (string-match "\000" data))
1086 (let ((choice (gnus-multiple-choice
1087 "Message contains NUL characters. Delete, continue, abort? "
1088 '((?d "Delete NUL characters")
1089 (?c "Try to APPEND the message as is")
1093 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1099 (goto-char (point-min))
1100 (while (search-forward "\000" nil t)
1101 (replace-match "" t t))
1102 (buffer-string)))))))
1104 (defun nnimap-ok-p (value)
1107 (equal (caar value) "OK")))
1109 (defun nnimap-find-uid-response (name list)
1110 (let ((result (car (last (nnimap-find-response-element name list)))))
1112 (string-to-number result))))
1114 (defun nnimap-find-response-element (name list)
1117 (when (and (consp elem)
1118 (equal name (car elem)))
1119 (setq result elem)))
1122 (deffoo nnimap-request-replace-article (article group buffer)
1123 (setq group (nnimap-decode-gnus-group group))
1125 (when (and (nnimap-possibly-change-group group nil)
1126 ;; Put the article into the group.
1127 (with-current-buffer buffer
1129 (nnimap-request-accept-article group nil t))))
1130 (nnimap-delete-article (list article))
1131 ;; Return the new article number.
1134 (defun nnimap-add-cr ()
1135 (goto-char (point-min))
1136 (while (re-search-forward "\r?\n" nil t)
1137 (replace-match "\r\n" t t)))
1139 (defun nnimap-get-groups ()
1141 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1143 (nnimap-wait-for-response sequence)
1144 (subst-char-in-region (point-min) (point-max)
1146 (goto-char (point-min))
1147 (nnimap-unfold-quoted-lines)
1148 (goto-char (point-min))
1149 (while (search-forward "* LIST " nil t)
1150 (let ((flags (read (current-buffer)))
1151 (separator (read (current-buffer)))
1152 (group (read (current-buffer))))
1153 (unless (member '%NoSelect flags)
1154 (push (utf7-decode (if (stringp group)
1156 (format "%s" group)) t)
1160 (deffoo nnimap-request-list (&optional server)
1161 (when (nnimap-possibly-change-group nil server)
1162 (with-current-buffer nntp-server-buffer
1165 (with-current-buffer (nnimap-buffer)
1166 (nnimap-get-groups)))
1167 sequences responses)
1169 (with-current-buffer (nnimap-buffer)
1170 (setf (nnimap-group nnimap-object) nil)
1171 (dolist (group groups)
1172 (setf (nnimap-examined nnimap-object) group)
1173 (push (list (nnimap-send-command "EXAMINE %S"
1174 (utf7-encode group t))
1177 (nnimap-wait-for-response (caar sequences))
1179 (nnimap-get-responses (mapcar #'car sequences))))
1180 (dolist (response responses)
1181 (let* ((sequence (car response))
1182 (response (cadr response))
1183 (group (cadr (assoc sequence sequences))))
1185 (equal (caar response) "OK"))
1186 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1188 (dolist (elem response)
1189 (when (equal (cadr elem) "EXISTS")
1190 (setq exists (string-to-number (car elem)))))
1192 (setq highest (1- (string-to-number (car uidnext)))))
1195 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1198 (insert (format "%S %d %d y\n"
1199 (utf7-decode group t)
1200 highest (1+ highest))))
1202 ;; Return the widest possible range.
1203 (insert (format "%S %d 1 y\n" (utf7-decode group t)
1204 (or highest exists)))))))))
1207 (deffoo nnimap-request-newgroups (date &optional server)
1208 (when (nnimap-possibly-change-group nil server)
1209 (with-current-buffer nntp-server-buffer
1211 (dolist (group (with-current-buffer (nnimap-buffer)
1212 (nnimap-get-groups)))
1213 (unless (assoc group nnimap-current-infos)
1214 ;; Insert dummy numbers here -- they don't matter.
1215 (insert (format "%S 0 1 y\n" (utf7-encode group)))))
1218 (deffoo nnimap-retrieve-group-data-early (server infos)
1219 (when (and (nnimap-possibly-change-group nil server)
1221 (with-current-buffer (nnimap-buffer)
1223 (setf (nnimap-group nnimap-object) nil)
1224 (setf (nnimap-initial-resync nnimap-object) 0)
1225 (let ((qresyncp (nnimap-capability "QRESYNC"))
1226 params groups sequences active uidvalidity modseq group)
1227 ;; Go through the infos and gather the data needed to know
1228 ;; what and how to request the data.
1229 (dolist (info infos)
1230 (setq params (gnus-info-params info)
1231 group (nnimap-decode-gnus-group
1232 (gnus-group-real-name (gnus-info-group info)))
1233 active (cdr (assq 'active params))
1234 uidvalidity (cdr (assq 'uidvalidity params))
1235 modseq (cdr (assq 'modseq params)))
1236 (setf (nnimap-examined nnimap-object) group)
1242 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1243 (utf7-encode group t)
1244 (nnimap-quirk "QRESYNC")
1252 ;; If we don't have a UIDVALIDITY, then this is
1253 ;; the first time we've seen the group, so we
1254 ;; have to do a SELECT (which is slower than an
1255 ;; examine), but will tell us whether the group
1256 ;; is read-only or not.
1259 (if (and active uidvalidity)
1260 ;; Fetch the last 100 flags.
1261 (setq start (max 1 (- (cdr active) 100)))
1262 (setf (nnimap-initial-resync nnimap-object)
1263 (1+ (nnimap-initial-resync nnimap-object)))
1265 (push (list (nnimap-send-command "%s %S" command
1266 (utf7-encode group t))
1267 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1268 start group command)
1272 (defun nnimap-quirk (command)
1273 (let ((quirk (assoc command nnimap-quirks)))
1274 ;; If this server is of a type that matches a quirk, then return
1275 ;; the "quirked" command instead of the proper one.
1276 (if (or (null quirk)
1277 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1281 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1282 (when (and sequences
1283 (nnimap-possibly-change-group nil server t)
1284 ;; Check that the process is still alive.
1285 (get-buffer-process (nnimap-buffer))
1286 (memq (process-status (get-buffer-process (nnimap-buffer)))
1288 (with-current-buffer (nnimap-buffer)
1289 ;; Wait for the final data to trickle in.
1290 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1294 ;; Now we should have most of the data we need, no matter
1295 ;; whether we're QRESYNCING, fetching all the flags from
1296 ;; scratch, or just fetching the last 100 flags per group.
1297 (nnimap-update-infos (nnimap-flags-to-marks
1299 (nreverse sequences)))
1301 ;; Finally, just return something resembling an active file in
1302 ;; the nntp buffer, so that the agent can save the info, too.
1303 (with-current-buffer nntp-server-buffer
1305 (dolist (info infos)
1306 (let* ((group (gnus-info-group info))
1307 (active (gnus-active group)))
1309 (insert (format "%S %d %d y\n"
1310 (decode-coding-string
1311 (gnus-group-real-name group) 'utf-8)
1313 (car active)))))))))))
1315 (defun nnimap-update-infos (flags infos)
1316 (dolist (info infos)
1317 (let* ((group (nnimap-decode-gnus-group
1318 (gnus-group-real-name (gnus-info-group info))))
1319 (marks (cdr (assoc group flags))))
1321 (nnimap-update-info info marks)))))
1323 (defun nnimap-update-info (info marks)
1324 (destructuring-bind (existing flags high low uidnext start-article
1325 permanent-flags uidvalidity
1326 vanished highestmodseq) marks
1328 ;; Ignore groups with no UIDNEXT/marks. This happens for
1329 ;; completely empty groups.
1330 ((and (not existing)
1332 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1334 (gnus-set-active (gnus-info-group info) active))))
1335 ;; We have a mismatch between the old and new UIDVALIDITY
1336 ;; identifiers, so we have to re-request the group info (the next
1337 ;; time). This virtually never happens.
1338 ((let ((old-uidvalidity
1339 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1340 (and old-uidvalidity
1341 (not (equal old-uidvalidity uidvalidity))
1342 (or (not start-article)
1343 (> start-article 1))))
1344 (gnus-group-remove-parameter info 'uidvalidity)
1345 (gnus-group-remove-parameter info 'modseq))
1346 ;; We have the data needed to update.
1348 (let* ((group (gnus-info-group info))
1349 (completep (and start-article
1350 (= start-article 1)))
1351 (active (or (gnus-active group)
1352 (cdr (assq 'active (gnus-info-params info))))))
1354 (setq high (1- uidnext)))
1355 ;; First set the active ranges based on high/low.
1357 (not (gnus-active group)))
1358 (gnus-set-active group
1361 (cons (min (or low (car active))
1363 (max (or high (cdr active))
1368 ;; No articles in this group.
1369 (cons uidnext (1- uidnext)))
1371 (cons start-article (1- start-article)))
1373 ;; No articles and no uidnext.
1375 (gnus-set-active group
1377 (or high (1- uidnext)))))
1378 ;; See whether this is a read-only group.
1379 (unless (eq permanent-flags 'not-scanned)
1380 (gnus-group-set-parameter
1381 info 'permanent-flags
1382 (and (or (memq '%* permanent-flags)
1383 (memq '%Seen permanent-flags))
1385 ;; Update marks and read articles if this isn't a
1386 ;; read-only IMAP group.
1387 (when (setq permanent-flags
1388 (cdr (assq 'permanent-flags (gnus-info-params info))))
1389 (if (and highestmodseq
1390 (not start-article))
1391 ;; We've gotten the data by QRESYNCing.
1392 (nnimap-update-qresync-info
1393 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1394 ;; Do normal non-QRESYNC flag updates.
1395 ;; Update the list of read articles.
1397 (gnus-compress-sequence
1398 (gnus-set-difference
1399 (gnus-set-difference
1401 (cdr (assoc '%Seen flags)))
1402 (cdr (assoc '%Flagged flags)))))
1403 (read (gnus-range-difference
1404 (cons start-article high) unread)))
1405 (when (> start-article 1)
1408 (if (> start-article 1)
1409 (gnus-sorted-range-intersection
1410 (cons 1 (1- start-article))
1411 (gnus-info-read info))
1412 (gnus-info-read info))
1414 (when (or (not (listp permanent-flags))
1415 (memq '%Seen permanent-flags))
1416 (gnus-info-set-read info read))
1417 ;; Update the marks.
1418 (setq marks (gnus-info-marks info))
1419 (dolist (type (cdr nnimap-mark-alist))
1420 (when (or (not (listp permanent-flags))
1421 (memq (car (assoc (caddr type) flags))
1423 (memq '%* permanent-flags))
1424 (let ((old-marks (assoc (car type) marks))
1426 (gnus-compress-sequence
1427 (cdr (or (assoc (caddr type) flags) ; %Flagged
1428 (assoc (intern (cadr type) obarray) flags)
1429 (assoc (cadr type) flags)))))) ; "\Flagged"
1430 (setq marks (delq old-marks marks))
1432 (when (and old-marks
1433 (> start-article 1))
1434 (setq old-marks (gnus-range-difference
1436 (cons start-article high)))
1437 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1439 (push (cons (car type) new-marks) marks)))))
1440 (gnus-info-set-marks info marks t))))
1441 ;; Tell Gnus whether there are any \Recent messages in any of
1443 (let ((recent (cdr (assoc '%Recent flags))))
1446 (> (car (last recent)) (cdr active)))
1447 (push (list (cons (gnus-group-real-name group) 0))
1448 nnmail-split-history)))
1449 ;; Note the active level for the next run-through.
1450 (gnus-group-set-parameter info 'active (gnus-active group))
1451 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1452 (gnus-group-set-parameter info 'modseq highestmodseq)
1453 (nnimap-store-info info (gnus-active group)))))))
1455 (defun nnimap-update-qresync-info (info existing vanished flags)
1456 ;; Add all the vanished articles to the list of read articles.
1461 (gnus-range-add (gnus-info-read info)
1463 (cdr (assq '%Flagged flags)))
1464 (cdr (assq '%Seen flags))))
1465 (let ((marks (gnus-info-marks info)))
1466 (dolist (type (cdr nnimap-mark-alist))
1467 (let ((ticks (assoc (car type) marks))
1469 (cdr (or (assoc (caddr type) flags) ; %Flagged
1470 (assoc (intern (cadr type) obarray) flags)
1471 (assoc (cadr type) flags))))) ; "\Flagged"
1472 (setq marks (delq ticks marks))
1474 ;; Add the new marks we got.
1475 (setq ticks (gnus-add-to-range ticks new-marks))
1476 ;; Remove the marks from messages that don't have them.
1477 (setq ticks (gnus-remove-from-range
1479 (gnus-compress-sequence
1480 (gnus-sorted-complement existing new-marks))))
1482 (push (cons (car type) ticks) marks)))
1483 (gnus-info-set-marks info marks t))))
1485 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1486 (if (zerop (length irange))
1489 (dolist (elem (split-string irange ","))
1491 (if (string-match ":" elem)
1492 (let ((numbers (split-string elem ":")))
1493 (cons (string-to-number (car numbers))
1494 (string-to-number (cadr numbers))))
1495 (string-to-number elem))
1497 (nreverse result))))
1499 (defun nnimap-store-info (info active)
1500 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1501 (entry (assoc group nnimap-current-infos)))
1503 (setcdr entry (list info active))
1504 (push (list group info active) nnimap-current-infos))))
1506 (defun nnimap-flags-to-marks (groups)
1507 (let (data group totalp uidnext articles start-article mark permanent-flags
1508 uidvalidity vanished highestmodseq)
1509 (dolist (elem groups)
1510 (setq group (car elem)
1511 uidnext (nth 1 elem)
1512 start-article (nth 2 elem)
1513 permanent-flags (nth 3 elem)
1514 uidvalidity (nth 4 elem)
1515 vanished (nth 5 elem)
1516 highestmodseq (nth 6 elem)
1517 articles (nthcdr 7 elem))
1518 (let ((high (caar articles))
1520 (dolist (article articles)
1521 (setq low (car article))
1522 (push (car article) existing)
1523 (dolist (flag (cdr article))
1524 (setq mark (assoc flag marks))
1526 (push (list flag (car article)) marks)
1527 (setcdr mark (cons (car article) (cdr mark))))))
1528 (push (list group existing marks high low uidnext start-article
1529 permanent-flags uidvalidity vanished highestmodseq)
1533 (defun nnimap-parse-flags (sequences)
1534 (goto-char (point-min))
1535 ;; Change \Delete etc to %Delete, so that the reader can read it.
1536 (subst-char-in-region (point-min) (point-max)
1538 ;; Remove any MODSEQ entries in the buffer, because they may contain
1539 ;; numbers that are too large for 32-bit Emacsen.
1540 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1541 (replace-match "" t t))
1542 (goto-char (point-min))
1543 (let (start end articles groups uidnext elems permanent-flags
1544 uidvalidity vanished highestmodseq)
1545 (dolist (elem sequences)
1546 (destructuring-bind (group-sequence flag-sequence totalp group command)
1548 (setq start (point))
1550 ;; The EXAMINE was successful.
1551 (search-forward (format "\n%d OK " group-sequence) nil t)
1556 (setq permanent-flags
1557 (if (equal command "SELECT")
1558 (and (search-forward "PERMANENTFLAGS "
1559 (or end (point-min)) t)
1560 (read (current-buffer)))
1564 (and (search-forward "UIDNEXT "
1565 (or end (point-min)) t)
1566 (read (current-buffer))))
1569 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1570 (or end (point-min)) t)
1571 ;; Store UIDVALIDITY as a string, as it's
1572 ;; too big for 32-bit Emacsen, usually.
1576 (and (eq flag-sequence 'qresync)
1577 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1578 (or end (point-min)) t)
1582 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1583 (or end (point-min)) t)
1587 ;; The UID FETCH FLAGS was successful.
1588 (or (eq flag-sequence 'qresync)
1589 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1590 (if (eq flag-sequence 'qresync)
1594 (setq start (point))
1596 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1598 (setq elems (read (current-buffer)))
1599 (push (cons (cadr (memq 'UID elems))
1600 (cadr (memq 'FLAGS elems)))
1602 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1603 vanished highestmodseq)
1607 (setq articles nil))))
1610 (defun nnimap-find-process-buffer (buffer)
1611 (cadr (assoc buffer nnimap-connection-alist)))
1613 (deffoo nnimap-request-post (&optional server)
1614 (setq nnimap-status-string "Read-only server")
1617 (declare-function gnus-fetch-headers "gnus-sum"
1618 (articles &optional limit force-new dependencies))
1620 (autoload 'nnir-search-thread "nnir")
1622 (deffoo nnimap-request-thread (header &optional group server)
1624 (setq group (nnimap-decode-gnus-group group)))
1625 (if gnus-refer-thread-use-nnir
1626 (nnir-search-thread header)
1627 (when (nnimap-possibly-change-group group server)
1628 (let* ((cmd (nnimap-make-thread-query header))
1629 (result (with-current-buffer (nnimap-buffer)
1630 (nnimap-command "UID SEARCH %s" cmd))))
1634 (delete 0 (mapcar #'string-to-number
1635 (cdr (assoc "SEARCH" (cdr result))))))
1638 (defun nnimap-possibly-change-group (group server &optional no-reconnect)
1639 (let ((open-result t))
1641 (not (nnimap-server-opened server)))
1642 (setq open-result (nnimap-open-server server nil no-reconnect)))
1649 (with-current-buffer (nnimap-buffer)
1650 (if (equal group (nnimap-group nnimap-object))
1652 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1654 (setf (nnimap-group nnimap-object) group
1655 (nnimap-select-result nnimap-object) result)
1658 (defun nnimap-find-connection (buffer)
1659 "Find the connection delivering to BUFFER."
1660 (let ((entry (assoc buffer nnimap-connection-alist)))
1662 (if (and (buffer-name (cadr entry))
1663 (get-buffer-process (cadr entry))
1664 (memq (process-status (get-buffer-process (cadr entry)))
1666 (get-buffer-process (cadr entry))
1667 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1670 (defvar nnimap-sequence 0)
1672 (defun nnimap-send-command (&rest args)
1673 (setf (nnimap-last-command-time nnimap-object) (current-time))
1674 (process-send-string
1675 (get-buffer-process (current-buffer))
1678 (incf nnimap-sequence)
1679 (apply #'format args)
1680 (if (nnimap-newlinep nnimap-object)
1683 ;; Some servers apparently can't have many outstanding
1684 ;; commands, so throttle them.
1685 (unless nnimap-streaming
1686 (nnimap-wait-for-response nnimap-sequence))
1689 (defun nnimap-log-command (command)
1690 (with-current-buffer (get-buffer-create "*imap log*")
1691 (goto-char (point-max))
1692 (insert (format-time-string "%H:%M:%S") " "
1693 (if nnimap-inhibit-logging
1698 (defun nnimap-command (&rest args)
1700 (let* ((sequence (apply #'nnimap-send-command args))
1701 (response (nnimap-get-response sequence)))
1702 (if (equal (caar response) "OK")
1704 (nnheader-report 'nnimap "%s"
1705 (mapconcat (lambda (a)
1707 (car response) " "))
1710 (defun nnimap-get-response (sequence)
1711 (nnimap-wait-for-response sequence)
1712 (nnimap-parse-response))
1714 (defun nnimap-wait-for-connection (&optional regexp)
1715 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1717 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1718 (let ((process (get-buffer-process (current-buffer))))
1719 (goto-char (point-min))
1720 (while (and (memq (process-status process)
1722 (not (re-search-forward regexp nil t)))
1723 (nnheader-accept-process-output process)
1724 (goto-char (point-min)))
1726 (and (looking-at (or response-regexp regexp))
1729 (defun nnimap-wait-for-response (sequence &optional messagep)
1730 (let ((process (get-buffer-process (current-buffer)))
1734 (goto-char (point-max))
1735 (while (and (setq openp (memq (process-status process)
1738 ;; Skip past any "*" lines that the server has
1740 (while (and (not (bobp))
1743 (looking-at "\\*"))))
1744 (not (looking-at (format "%d .*\n" sequence)))))
1746 (nnheader-message-maybe
1747 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1749 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1750 (format " (initial sync of %d groups; please wait)"
1751 (nnimap-initial-resync nnimap-object))
1753 (nnheader-accept-process-output process)
1754 (goto-char (point-max)))
1755 (setf (nnimap-initial-resync nnimap-object) 0)
1760 ;; The user hit C-g while we were waiting: kill the process, in case
1761 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1763 (delete-process process)
1766 (defun nnimap-parse-response ()
1767 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1769 (dolist (line lines)
1770 (push (cdr (nnimap-parse-line line)) result))
1771 ;; Return the OK/error code first, and then all the "continuation
1772 ;; lines" afterwards.
1774 (nreverse result))))
1776 ;; Parse an IMAP response line lightly. They look like
1777 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1778 ;; the lines into a list of strings and lists of string.
1779 (defun nnimap-parse-line (line)
1782 (mm-disable-multibyte)
1784 (goto-char (point-min))
1786 (if (eql (setq char (following-char)) ? )
1794 (if (search-forward "]" (line-end-position) 'move)
1801 (if (search-forward ")" (line-end-position) 'move)
1808 (1- (or (search-forward "\"" (line-end-position) 'move)
1811 (buffer-substring (point) (if (search-forward " " nil t)
1813 (goto-char (point-max))))))
1815 (nreverse result))))
1817 (defun nnimap-last-response-string ()
1820 (let ((end (point)))
1824 (while (and (not (bobp))
1825 (eql (following-char) ?*))
1827 (unless (eql (following-char) ?*)
1829 (buffer-substring (point) end))))
1831 (defun nnimap-get-responses (sequences)
1833 (dolist (sequence sequences)
1834 (goto-char (point-min))
1835 (when (re-search-forward (format "^%d " sequence) nil t)
1836 (push (list sequence (nnimap-parse-response))
1840 (defvar nnimap-incoming-split-list nil)
1842 (defun nnimap-fetch-inbox (articles)
1844 (nnimap-wait-for-response
1845 (nnimap-send-command
1847 (nnimap-article-ranges articles)
1848 (format "(UID %s%s)"
1854 (nnimap-split-download-body-default
1862 (defun nnimap-split-incoming-mail ()
1863 (with-current-buffer (nnimap-buffer)
1864 (let ((nnimap-incoming-split-list nil)
1865 (nnmail-split-methods
1867 ((eq nnimap-split-methods 'default)
1868 nnmail-split-methods)
1869 (nnimap-split-methods
1870 nnimap-split-methods)
1872 'nnmail-split-fancy)))
1873 (nnmail-split-fancy (or nnimap-split-fancy
1874 nnmail-split-fancy))
1875 (nnmail-inhibit-default-split-group t)
1876 (groups (nnimap-get-groups))
1879 (nnimap-command "SELECT %S" nnimap-inbox)
1880 (setf (nnimap-group nnimap-object) nnimap-inbox)
1881 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1883 (nnimap-fetch-inbox new-articles)
1884 (nnimap-transform-split-mail)
1885 (nnheader-ms-strip-cr)
1887 (nnmail-split-incoming (current-buffer)
1888 #'nnimap-save-mail-spec
1890 #'nnimap-dummy-active-number
1891 #'nnimap-save-mail-spec)
1892 (when nnimap-incoming-split-list
1893 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1894 sequences junk-articles)
1895 ;; Create any groups that doesn't already exist on the
1897 (dolist (spec specs)
1898 (when (and (not (member (car spec) groups))
1899 (not (eq (car spec) 'junk)))
1900 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1901 ;; Then copy over all the messages.
1903 (dolist (spec specs)
1904 (let ((group (car spec))
1905 (ranges (cdr spec)))
1906 (if (eq group 'junk)
1907 (setq junk-articles ranges)
1908 (push (list (nnimap-send-command
1910 (nnimap-article-ranges ranges)
1911 (utf7-encode group t))
1914 ;; Wait for the last COPY response...
1916 (nnimap-wait-for-response (caar sequences))
1917 ;; And then mark the successful copy actions as deleted,
1918 ;; and possibly expunge them.
1919 (nnimap-mark-and-expunge-incoming
1920 (nnimap-parse-copied-articles sequences)))
1921 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1923 (defun nnimap-mark-and-expunge-incoming (range)
1925 (setq range (nnimap-article-ranges range))
1928 (nnimap-send-command
1929 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1931 ;; If the server supports it, we now delete the message we have
1932 ;; just copied over.
1933 ((nnimap-capability "UIDPLUS")
1934 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1935 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1936 ;; user has configured it.
1938 (setq sequence (nnimap-send-command "EXPUNGE"))))
1939 (nnimap-wait-for-response sequence))))
1941 (defun nnimap-parse-copied-articles (sequences)
1942 (let (sequence copied range)
1943 (goto-char (point-min))
1944 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1945 (setq sequence (string-to-number (match-string 1)))
1946 (when (setq range (cadr (assq sequence sequences)))
1947 (push (gnus-uncompress-range range) copied)))
1948 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1950 (defun nnimap-new-articles (flags)
1952 (dolist (elem flags)
1953 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1955 (push (car elem) new)))
1956 (gnus-compress-sequence (nreverse new))))
1958 (defun nnimap-make-split-specs (list)
1962 (destructuring-bind (article spec) elem
1963 (dolist (group (delete nil (mapcar #'car spec)))
1964 (unless (setq entry (assoc group specs))
1965 (push (setq entry (list group)) specs))
1966 (setcdr entry (cons article (cdr entry))))))
1967 (dolist (entry specs)
1968 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1971 (defun nnimap-transform-split-mail ()
1972 (goto-char (point-min))
1973 (let (article bytes)
1976 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
1977 (delete-region (point) (progn (forward-line 1) (point)))
1980 (setq article (match-string 1)
1981 bytes (nnimap-get-length))
1982 (delete-region (line-beginning-position) (line-end-position))
1983 ;; Insert MMDF separator, and a way to remember what this
1985 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1986 (forward-char (1+ bytes))
1987 (setq bytes (nnimap-get-length))
1988 (delete-region (line-beginning-position) (line-end-position))
1989 ;; There's a body; skip past that.
1991 (forward-char (1+ bytes))
1992 (delete-region (line-beginning-position) (line-end-position)))))))
1994 (defun nnimap-dummy-active-number (group &optional server)
1997 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1999 (goto-char (point-min))
2000 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2001 (error "Invalid nnimap mail")
2002 (setq article (string-to-number (match-string 1))))
2004 (if (eq group-art 'junk)
2005 (list (cons 'junk 1))
2007 nnimap-incoming-split-list)))
2009 (defun nnimap-make-thread-query (header)
2010 (let* ((id (mail-header-id header))
2012 (or (mail-header-references header)
2016 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2018 (dolist (refid refs value)
2020 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2021 refid refid value)))))
2026 ;;; nnimap.el ends here