1 ;;; nnimap.el --- IMAP interface for Gnus
3 ;; Copyright (C) 2010 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.
44 (autoload 'auth-source-forget-user-or-password "auth-source")
45 (autoload 'auth-source-user-or-password "auth-source")
49 (defvoo nnimap-address nil
50 "The address of the IMAP server.")
52 (defvoo nnimap-server-port nil
54 If nnimap-stream is `ssl', this will default to `imaps'. If not,
55 it will default to `imap'.")
57 (defvoo nnimap-stream 'ssl
58 "How nnimap will talk to the IMAP server.
59 Values are `ssl', `network', `starttls' or `shell'.")
61 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
62 (if (listp imap-shell-program)
63 (car imap-shell-program)
67 (defvoo nnimap-inbox nil
68 "The mail box where incoming mail arrives and should be split out of.")
70 (defvoo nnimap-split-methods nil
72 Uses the same syntax as nnmail-split-methods")
74 (defvoo nnimap-split-fancy nil
75 "Uses the same syntax as nnmail-split-fancy.")
77 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
80 (defvoo nnimap-authenticator nil
81 "How nnimap authenticate itself to the server.
82 Possible choices are nil (use default methods) or `anonymous'.")
84 (defvoo nnimap-expunge t
85 "If non-nil, expunge articles after deleting them.
86 This is always done if the server supports UID EXPUNGE, but it's
87 not done by default on servers that doesn't support that command.")
89 (defvoo nnimap-streaming t
90 "If non-nil, try to use streaming commands with IMAP servers.
91 Switching this off will make nnimap slower, but it helps with
94 (defvoo nnimap-connection-alist nil)
96 (defvoo nnimap-current-infos nil)
98 (defvoo nnimap-fetch-partial-articles nil
99 "If non-nil, Gnus will fetch partial articles.
100 If t, nnimap will fetch only the first part. If a string, it
101 will fetch all parts that have types that match that string. A
102 likely value would be \"text/\" to automatically fetch all
105 (defvar nnimap-process nil)
107 (defvar nnimap-status-string "")
109 (defvar nnimap-split-download-body-default nil
110 "Internal variable with default value for `nnimap-split-download-body'.")
112 (defvar nnimap-keepalive-timer nil)
113 (defvar nnimap-process-buffers nil)
116 group process commands capabilities select-result newlinep server
117 last-command-time greeting)
119 (defvar nnimap-object nil)
121 (defvar nnimap-mark-alist
122 '((read "\\Seen" %Seen)
123 (tick "\\Flagged" %Flagged)
124 (reply "\\Answered" %Answered)
125 (expire "gnus-expire")
126 (dormant "gnus-dormant")
129 (download "gnus-download")
130 (forward "gnus-forward")))
132 (defun nnimap-buffer ()
133 (nnimap-find-process-buffer nntp-server-buffer))
135 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
136 (with-current-buffer nntp-server-buffer
138 (when (nnimap-possibly-change-group group server)
139 (with-current-buffer (nnimap-buffer)
141 (nnimap-wait-for-response
144 (nnimap-article-ranges (gnus-compress-sequence articles))
145 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
148 "BODY.PEEK[HEADER.FIELDS %s]"
149 "RFC822.HEADER.LINES %s")
150 (append '(Subject From Date Message-Id
151 References In-Reply-To Xref)
152 nnmail-extra-headers))))
154 (nnimap-transform-headers))
155 (insert-buffer-substring
156 (nnimap-find-process-buffer (current-buffer))))
159 (defun nnimap-transform-headers ()
160 (goto-char (point-min))
161 (let (article bytes lines size string)
164 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
165 (delete-region (point) (progn (forward-line 1) (point)))
168 (setq article (match-string 1))
169 ;; Unfold quoted {number} strings.
170 (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
171 (1+ (line-end-position)) t)
172 (setq size (string-to-number (match-string 1)))
173 (delete-region (+ (match-beginning 0) 2) (point))
174 (setq string (delete-region (point) (+ (point) size)))
175 (insert (format "%S" string)))
176 (setq bytes (nnimap-get-length)
180 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
185 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
186 (let ((structure (ignore-errors
187 (read (current-buffer)))))
188 (while (and (consp structure)
189 (not (stringp (car structure))))
190 (setq structure (car structure)))
191 (setq lines (nth 7 structure))))
192 (delete-region (line-beginning-position) (line-end-position))
193 (insert (format "211 %s Article retrieved." article))
196 (insert (format "Chars: %s\n" size)))
198 (insert (format "Lines: %s\n" lines)))
199 (re-search-forward "^\r$")
200 (delete-region (line-beginning-position) (line-end-position))
204 (defun nnimap-get-length ()
205 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
206 (string-to-number (match-string 1))))
208 (defun nnimap-article-ranges (ranges)
212 (number-to-string ranges))
213 ((numberp (cdr ranges))
214 (format "%d:%d" (car ranges) (cdr ranges)))
216 (dolist (elem ranges)
219 (format "%d:%d" (car elem) (cdr elem))
220 (number-to-string elem))
222 (mapconcat #'identity (nreverse result) ",")))))
224 (deffoo nnimap-open-server (server &optional defs)
225 (if (nnimap-server-opened server)
227 (unless (assq 'nnimap-address defs)
228 (setq defs (append defs (list (list 'nnimap-address server)))))
229 (nnoo-change-server 'nnimap server defs)
230 (or (nnimap-find-connection nntp-server-buffer)
231 (nnimap-open-connection nntp-server-buffer))))
233 (defun nnimap-make-process-buffer (buffer)
235 (generate-new-buffer (format "*nnimap %s %s %s*"
236 nnimap-address nnimap-server-port
237 (gnus-buffer-exists-p buffer)))
238 (mm-disable-multibyte)
239 (buffer-disable-undo)
241 (set (make-local-variable 'after-change-functions) nil)
242 (set (make-local-variable 'nnimap-object)
243 (make-nnimap :server (nnoo-current-server 'nnimap)))
244 (push (list buffer (current-buffer)) nnimap-connection-alist)
245 (push (current-buffer) nnimap-process-buffers)
248 (defun nnimap-open-shell-stream (name buffer host port)
249 (let ((process-connection-type nil))
250 (start-process name buffer shell-file-name
258 (defun nnimap-credentials (address ports &optional inhibit-create)
259 (let (port credentials)
260 ;; Request the credentials from all ports, but only query on the
261 ;; last port if all the previous ones have failed.
262 (while (and (null credentials)
263 (setq port (pop ports)))
265 (auth-source-user-or-password
266 '("login" "password") address port nil
272 (defun nnimap-keepalive ()
273 (let ((now (current-time)))
274 (dolist (buffer nnimap-process-buffers)
275 (when (buffer-name buffer)
276 (with-current-buffer buffer
277 (when (and nnimap-object
278 (nnimap-last-command-time nnimap-object)
282 (nnimap-last-command-time nnimap-object)))
283 ;; More than five minutes since the last command.
285 (nnimap-send-command "NOOP")))))))
287 (defun nnimap-open-connection (buffer)
288 (unless nnimap-keepalive-timer
289 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
292 (with-current-buffer (nnimap-make-process-buffer buffer)
293 (let* ((coding-system-for-read 'binary)
294 (coding-system-for-write 'binary)
298 ((eq nnimap-stream 'network)
300 "*nnimap*" (current-buffer) nnimap-address
302 (or nnimap-server-port
303 (if (netrc-find-service-number "imap")
307 ((eq nnimap-stream 'shell)
308 (nnimap-open-shell-stream
309 "*nnimap*" (current-buffer) nnimap-address
310 (setq port (or nnimap-server-port "imap")))
312 ((eq nnimap-stream 'starttls)
313 (let ((tls-program (nnimap-extend-tls-programs)))
315 "*nnimap*" (current-buffer) nnimap-address
316 (setq port (or nnimap-server-port "imap"))
319 ((eq nnimap-stream 'ssl)
321 "*nnimap*" (current-buffer) nnimap-address
323 (or nnimap-server-port
324 (if (netrc-find-service-number "imaps")
327 '("143" "993" "imap" "imaps"))))
328 connection-result login-result credentials)
329 (setf (nnimap-process nnimap-object)
330 (get-buffer-process (current-buffer)))
331 (if (not (and (nnimap-process nnimap-object)
332 (memq (process-status (nnimap-process nnimap-object))
334 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
335 nnimap-address port nnimap-stream)
336 (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
337 (if (not (setq connection-result (nnimap-wait-for-connection)))
338 (nnheader-report 'nnimap
339 "%s" (buffer-substring
340 (point) (line-end-position)))
341 ;; Store the greeting (for debugging purposes).
342 (setf (nnimap-greeting nnimap-object)
343 (buffer-substring (line-beginning-position)
344 (line-end-position)))
345 ;; Store the capabilities.
346 (setf (nnimap-capabilities nnimap-object)
349 (nnimap-find-parameter
350 "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
351 (when nnimap-server-port
352 (push (format "%s" nnimap-server-port) ports))
353 ;; If this is a STARTTLS-capable server, then sever the
354 ;; connection and start a STARTTLS connection instead.
355 (when (and (eq nnimap-stream 'network)
356 (member "STARTTLS" (nnimap-capabilities nnimap-object)))
357 (let ((nnimap-stream 'starttls))
359 (nnimap-open-connection buffer)))
360 ;; If the STARTTLS connection was successful, we
361 ;; kill our first non-encrypted connection. If it
362 ;; wasn't successful, we just use our unencrypted
364 (when (memq (process-status tls-process) '(open run))
365 (delete-process (nnimap-process nnimap-object))
366 (kill-buffer (current-buffer))
367 (return tls-process)))))
368 (unless (equal connection-result "PREAUTH")
369 (if (not (setq credentials
370 (if (eq nnimap-authenticator 'anonymous)
372 (message-make-address))
374 ;; First look for the credentials based
375 ;; on the virtual server name.
377 (nnoo-current-server 'nnimap) ports t)
378 ;; Then look them up based on the
380 (nnimap-credentials nnimap-address ports)))))
381 (setq nnimap-object nil)
382 (setq login-result (nnimap-command "LOGIN %S %S"
385 (unless (car login-result)
386 ;; If the login failed, then forget the credentials
387 ;; that are now possibly cached.
388 (dolist (host (list (nnoo-current-server 'nnimap)
391 (dolist (element '("login" "password"))
392 (auth-source-forget-user-or-password
393 element host port))))
394 (delete-process (nnimap-process nnimap-object))
395 (setq nnimap-object nil))))
397 (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
398 (nnimap-command "ENABLE QRESYNC"))
399 (nnimap-process nnimap-object))))))))
401 (defun nnimap-extend-tls-programs ()
402 (let ((programs tls-program)
404 (unless (consp programs)
405 (setq programs (list programs)))
406 (dolist (program programs)
407 (push (concat program " " "%s") result))
410 (defun nnimap-find-parameter (parameter elems)
414 ((equal (car elem) parameter)
415 (setq result (cdr elem)))
416 ((and (equal (car elem) "OK")
418 (equal (caadr elem) parameter))
419 (setq result (cdr (cadr elem))))))
422 (deffoo nnimap-close-server (&optional server)
425 (deffoo nnimap-request-close ()
428 (deffoo nnimap-server-opened (&optional server)
429 (and (nnoo-current-server-p 'nnimap server)
431 (gnus-buffer-live-p nntp-server-buffer)
432 (nnimap-find-connection nntp-server-buffer)))
434 (deffoo nnimap-status-message (&optional server)
435 nnimap-status-string)
437 (deffoo nnimap-request-article (article &optional group server to-buffer)
438 (with-current-buffer nntp-server-buffer
439 (let ((result (nnimap-possibly-change-group group server))
441 (when (stringp article)
442 (setq article (nnimap-find-article-by-message-id group article)))
446 (with-current-buffer (nnimap-buffer)
448 (when nnimap-fetch-partial-articles
449 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
450 (goto-char (point-min))
451 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
452 (setq structure (ignore-errors
453 (let ((start (point)))
455 (downcase-region start (point))
457 (read (current-buffer))))
458 parts (nnimap-find-wanted-parts structure))))
460 (nnimap-get-partial-article article parts structure)
461 (nnimap-get-whole-article article))
462 (let ((buffer (current-buffer)))
463 (with-current-buffer (or to-buffer nntp-server-buffer)
465 (insert-buffer-substring buffer)
466 (nnheader-ms-strip-cr)
467 (cons group article)))))))))
469 (defun nnimap-get-whole-article (article)
473 "UID FETCH %d BODY.PEEK[]"
474 "UID FETCH %d RFC822.PEEK")
476 ;; Check that we really got an article.
477 (goto-char (point-min))
478 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
481 ;; Remove any data that may have arrived before the FETCH data.
484 (delete-region (point-min) (point)))
485 (let ((bytes (nnimap-get-length)))
486 (delete-region (line-beginning-position)
487 (progn (forward-line 1) (point)))
488 (goto-char (+ (point) bytes))
489 (delete-region (point) (point-max)))
492 (defun nnimap-ver4-p ()
493 (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
495 (defun nnimap-get-partial-article (article parts structure)
498 "UID FETCH %d (%s %s)"
504 (mapconcat (lambda (part)
505 (format "BODY.PEEK[%s]" part))
507 (mapconcat (lambda (part)
508 (format "RFC822.PEEK[%s]" part))
511 (nnimap-convert-partial-article structure))))
513 (defun nnimap-convert-partial-article (structure)
514 ;; First just skip past the headers.
515 (goto-char (point-min))
516 (let ((bytes (nnimap-get-length))
518 ;; Delete "FETCH" line.
519 (delete-region (line-beginning-position)
520 (progn (forward-line 1) (point)))
521 (goto-char (+ (point) bytes))
522 ;; Collect all the body parts.
523 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
524 (setq id (match-string 1)
525 bytes (nnimap-get-length))
527 (delete-region (point) (progn (forward-line 1) (point)))
528 (push (list id (buffer-substring (point) (+ (point) bytes)))
530 (delete-region (point) (+ (point) bytes)))
531 ;; Delete trailing junk.
532 (delete-region (point) (point-max))
533 ;; Now insert all the parts again where they fit in the structure.
534 (nnimap-insert-partial-structure structure parts)
537 (defun nnimap-insert-partial-structure (structure parts &optional subp)
539 (let ((bstruc structure))
540 (while (consp (car bstruc))
542 (setq type (car bstruc))
543 (setq bstruc (car (cdr bstruc)))
544 (when (and (stringp (car bstruc))
545 (string= (downcase (car bstruc)) "boundary"))
546 (setq boundary (cadr bstruc))))
548 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
549 (downcase type) boundary)))
550 (while (not (stringp (car structure)))
551 (insert "\n--" boundary "\n")
552 (if (consp (caar structure))
553 (nnimap-insert-partial-structure (pop structure) parts t)
554 (let ((bit (pop structure)))
555 (insert (format "Content-type: %s/%s"
556 (downcase (nth 0 bit))
557 (downcase (nth 1 bit))))
558 (if (member "CHARSET" (nth 2 bit))
560 "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
562 (insert (format "Content-transfer-encoding: %s\n"
565 (when (assoc (nth 9 bit) parts)
566 (insert (cadr (assoc (nth 9 bit) parts)))))))
567 (insert "\n--" boundary "--\n")))
569 (defun nnimap-find-wanted-parts (structure)
570 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
572 (defun nnimap-find-wanted-parts-1 (structure prefix)
575 (while (consp (car structure))
576 (let ((sub (pop structure)))
577 (if (consp (car sub))
578 (push (nnimap-find-wanted-parts-1
579 sub (if (string= prefix "")
580 (number-to-string num)
581 (format "%s.%s" prefix num)))
583 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
584 (id (if (string= prefix "")
585 (number-to-string num)
586 (format "%s.%s" prefix num))))
587 (setcar (nthcdr 9 sub) id)
588 (when (if (eq nnimap-fetch-partial-articles t)
590 (string-match nnimap-fetch-partial-articles type))
595 (deffoo nnimap-request-group (group &optional server dont-check info)
596 (let ((result (nnimap-possibly-change-group group server))
597 articles active marks high low)
598 (with-current-buffer nntp-server-buffer
601 (setq active (nth 2 (assoc group nnimap-current-infos))))
602 (insert (format "211 %d %d %d %S\n"
603 (- (cdr active) (car active))
607 (with-current-buffer (nnimap-buffer)
609 (let ((group-sequence
610 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
612 (nnimap-send-command "UID FETCH 1:* FLAGS")))
613 (nnimap-wait-for-response flag-sequence)
615 (nnimap-flags-to-marks
617 (list (list group-sequence flag-sequence 1 group)))))
619 (nnimap-update-infos marks (list info)))
620 (goto-char (point-max))
621 (let ((uidnext (nth 5 (car marks))))
622 (setq high (if uidnext
625 low (or (nth 4 (car marks)) uidnext)))))
629 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
632 (deffoo nnimap-request-create-group (group &optional server args)
633 (when (nnimap-possibly-change-group nil server)
634 (with-current-buffer (nnimap-buffer)
635 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
637 (deffoo nnimap-request-delete-group (group &optional force server)
638 (when (nnimap-possibly-change-group nil server)
639 (with-current-buffer (nnimap-buffer)
640 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
642 (deffoo nnimap-request-expunge-group (group &optional server)
643 (when (nnimap-possibly-change-group group server)
644 (with-current-buffer (nnimap-buffer)
645 (car (nnimap-command "EXPUNGE")))))
647 (defun nnimap-get-flags (spec)
650 (with-current-buffer (nnimap-buffer)
652 (nnimap-wait-for-response (nnimap-send-command
653 "UID FETCH %s FLAGS" spec))
654 (goto-char (point-min))
655 (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
656 (setq elems (nnimap-parse-line (match-string 1)))
657 (push (cons (string-to-number (cadr (member "UID" elems)))
658 (cadr (member "FLAGS" elems)))
660 (nreverse articles)))
662 (deffoo nnimap-close-group (group &optional server)
665 (deffoo nnimap-request-move-article (article group server accept-form
666 &optional last internal-move-group)
668 (when (nnimap-request-article article group server (current-buffer))
669 ;; If the move is internal (on the same server), just do it the easy
671 (let ((message-id (message-field-value "message-id")))
672 (if internal-move-group
674 (with-current-buffer (nnimap-buffer)
675 (nnimap-command "UID COPY %d %S"
677 (utf7-encode internal-move-group t)))))
679 (nnimap-delete-article article)
680 (cons internal-move-group
681 (nnimap-find-article-by-message-id
682 internal-move-group message-id))))
683 ;; Move the article to a different method.
684 (let ((result (eval accept-form)))
686 (nnimap-delete-article article)
689 (deffoo nnimap-request-expire-articles (articles group &optional server force)
693 ((not (nnimap-possibly-change-group group server))
696 (eq nnmail-expiry-target 'delete))
697 (unless (nnimap-delete-article (gnus-compress-sequence articles))
698 (message "Article marked for deletion, but not expunged."))
701 (let ((deletable-articles
703 (eq nnmail-expiry-wait 'immediate))
705 (gnus-sorted-intersection
707 (nnimap-find-expired-articles group)))))
708 (if (null deletable-articles)
710 (if (eq nnmail-expiry-target 'delete)
711 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
712 (setq deletable-articles
713 (nnimap-process-expiry-targets
714 deletable-articles group server)))
715 ;; Return the articles we didn't delete.
716 (gnus-sorted-complement articles deletable-articles))))))
718 (defun nnimap-process-expiry-targets (articles group server)
719 (let ((deleted-articles nil))
720 (dolist (article articles)
721 (let ((target nnmail-expiry-target))
723 (when (nnimap-request-article article group server (current-buffer))
724 (message "Expiring article %s:%d" group article)
725 (when (functionp target)
726 (setq target (funcall target group)))
728 (not (eq target 'delete)))
729 (if (or (gnus-request-group target t)
730 (gnus-request-create-group target))
731 (nnmail-expiry-target-group target group)
734 (push article deleted-articles))))))
735 ;; Change back to the current group again.
736 (nnimap-possibly-change-group group server)
737 (setq deleted-articles (nreverse deleted-articles))
738 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
741 (defun nnimap-find-expired-articles (group)
742 (let ((cutoff (nnmail-expired-article-p group nil nil)))
743 (with-current-buffer (nnimap-buffer)
746 "UID SEARCH SENTBEFORE %s"
750 (car (rassoc (nth 4 (decode-time cutoff))
751 parse-time-months))))
754 (delete 0 (mapcar #'string-to-number
755 (cdr (assoc "SEARCH" (cdr result))))))))))
758 (defun nnimap-find-article-by-message-id (group message-id)
759 (with-current-buffer (nnimap-buffer)
761 (setf (nnimap-group nnimap-object) nil)
762 (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
764 (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
766 (setq result (nnimap-wait-for-response sequence))
768 (car (setq result (nnimap-parse-response))))
769 ;; Select the last instance of the message in the group.
771 (car (last (assoc "SEARCH" (cdr result)))))
772 (string-to-number article))))))
774 (defun nnimap-delete-article (articles)
775 (with-current-buffer (nnimap-buffer)
776 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
777 (nnimap-article-ranges articles))
779 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
780 (nnimap-command "UID EXPUNGE %s"
781 (nnimap-article-ranges articles))
784 (nnimap-command "EXPUNGE")
786 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
787 "server doesn't support UIDPLUS, so we won't "
788 "delete this article now"))))))
790 (deffoo nnimap-request-scan (&optional group server)
791 (when (and (nnimap-possibly-change-group nil server)
793 nnimap-split-methods)
794 (message "nnimap %s splitting mail..." server)
795 (nnimap-split-incoming-mail)))
797 (defun nnimap-marks-to-flags (marks)
800 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
804 (deffoo nnimap-request-set-mark (group actions &optional server)
805 (when (nnimap-possibly-change-group group server)
807 (with-current-buffer (nnimap-buffer)
809 ;; Just send all the STORE commands without waiting for
810 ;; response. If they're successful, they're successful.
811 (dolist (action actions)
812 (destructuring-bind (range action marks) action
813 (let ((flags (nnimap-marks-to-flags marks)))
815 (setq sequence (nnimap-send-command
816 "UID STORE %s %sFLAGS.SILENT (%s)"
817 (nnimap-article-ranges range)
821 (mapconcat #'identity flags " ")))))))
822 ;; Wait for the last command to complete to avoid later
823 ;; syncronisation problems with the stream.
825 (nnimap-wait-for-response sequence))))))
827 (deffoo nnimap-request-accept-article (group &optional server last)
828 (when (nnimap-possibly-change-group nil server)
829 (nnmail-check-syntax)
830 (let ((message-id (message-field-value "message-id"))
833 (setq message (buffer-string))
834 (with-current-buffer (nnimap-buffer)
835 (setq sequence (nnimap-send-command
836 "APPEND %S {%d}" (utf7-encode group t)
838 (process-send-string (get-buffer-process (current-buffer)) message)
839 (process-send-string (get-buffer-process (current-buffer))
840 (if (nnimap-newlinep nnimap-object)
843 (let ((result (nnimap-get-response sequence)))
844 (if (not (car result))
846 (message "%s" (nnheader-get-report-string 'nnimap))
849 (nnimap-find-article-by-message-id group message-id))))))))
851 (defun nnimap-add-cr ()
852 (goto-char (point-min))
853 (while (re-search-forward "\r?\n" nil t)
854 (replace-match "\r\n" t t)))
856 (defun nnimap-get-groups ()
857 (let ((result (nnimap-command "LIST \"\" \"*\""))
860 (dolist (line (cdr result))
861 (when (and (equal (car line) "LIST")
862 (not (and (caadr line)
863 (string-match "noselect" (caadr line)))))
864 (push (car (last line)) groups)))
867 (deffoo nnimap-request-list (&optional server)
868 (nnimap-possibly-change-group nil server)
869 (with-current-buffer nntp-server-buffer
872 (with-current-buffer (nnimap-buffer)
873 (nnimap-get-groups)))
876 (with-current-buffer (nnimap-buffer)
877 (setf (nnimap-group nnimap-object) nil)
878 (dolist (group groups)
879 (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
882 (nnimap-wait-for-response (caar sequences))
884 (nnimap-get-responses (mapcar #'car sequences))))
885 (dolist (response responses)
886 (let* ((sequence (car response))
887 (response (cadr response))
888 (group (cadr (assoc sequence sequences))))
890 (equal (caar response) "OK"))
891 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
893 (dolist (elem response)
894 (when (equal (cadr elem) "EXISTS")
895 (setq exists (string-to-number (car elem)))))
897 (setq highest (1- (string-to-number (car uidnext)))))
900 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
903 (insert (format "%S %d %d y\n"
904 (utf7-decode group t) highest (1+ highest))))
906 ;; Return the widest possible range.
907 (insert (format "%S %d 1 y\n" (utf7-decode group t)
908 (or highest exists)))))))))
911 (deffoo nnimap-retrieve-group-data-early (server infos)
912 (when (nnimap-possibly-change-group nil server)
913 (with-current-buffer (nnimap-buffer)
914 ;; QRESYNC handling isn't implemented.
915 (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
916 marks groups sequences)
917 ;; Go through the infos and gather the data needed to know
918 ;; what and how to request the data.
920 (setq marks (gnus-info-marks info))
921 (push (list (gnus-group-real-name (gnus-info-group info))
922 (cdr (assq 'active marks))
923 (cdr (assq 'uid marks)))
925 ;; Then request the data.
927 (setf (nnimap-group nnimap-object) nil)
928 (dolist (elem groups)
933 (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
942 ;; Fetch the last 100 flags.
943 (max 1 (- (cdr (nth 1 elem)) 100))
945 (push (list (nnimap-send-command "EXAMINE %S" (car elem))
946 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
950 ;; Some servers apparently can't have many outstanding
951 ;; commands, so throttle them.
952 (when (and (not nnimap-streaming)
954 (nnimap-wait-for-response (caar sequences))))
957 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
959 (nnimap-possibly-change-group nil server))
960 (with-current-buffer (nnimap-buffer)
961 ;; Wait for the final data to trickle in.
962 (when (nnimap-wait-for-response (cadar sequences))
963 ;; Now we should have all the data we need, no matter whether
964 ;; we're QRESYNCING, fetching all the flags from scratch, or
965 ;; just fetching the last 100 flags per group.
966 (nnimap-update-infos (nnimap-flags-to-marks
968 (nreverse sequences)))
970 ;; Finally, just return something resembling an active file in
971 ;; the nntp buffer, so that the agent can save the info, too.
972 (with-current-buffer nntp-server-buffer
975 (let* ((group (gnus-info-group info))
976 (active (gnus-active group)))
978 (insert (format "%S %d %d y\n"
979 (gnus-group-real-name group)
981 (car active)))))))))))
983 (defun nnimap-update-infos (flags infos)
985 (let ((group (gnus-group-real-name (gnus-info-group info))))
986 (nnimap-update-info info (cdr (assoc group flags))))))
988 (defun nnimap-update-info (info marks)
990 (destructuring-bind (existing flags high low uidnext start-article
991 permanent-flags) marks
992 (let ((group (gnus-info-group info))
993 (completep (and start-article
994 (= start-article 1))))
996 (setq high (1- uidnext)))
997 ;; First set the active ranges based on high/low.
999 (not (gnus-active group)))
1000 (gnus-set-active group
1005 ;; No articles in this group.
1006 (cons uidnext (1- uidnext)))
1008 (cons start-article (1- start-article)))
1010 ;; No articles and no uidnext.
1014 (cons (car (gnus-active group))
1015 (or high (1- uidnext)))))
1016 (when (and (not high)
1018 (setq high (1- uidnext)))
1019 ;; Then update the list of read articles.
1021 (gnus-compress-sequence
1022 (gnus-set-difference
1023 (gnus-set-difference
1025 (cdr (assoc '%Seen flags)))
1026 (cdr (assoc '%Flagged flags)))))
1027 (read (gnus-range-difference
1028 (cons start-article high) unread)))
1029 (when (> start-article 1)
1032 (if (> start-article 1)
1033 (gnus-sorted-range-intersection
1034 (cons 1 (1- start-article))
1035 (gnus-info-read info))
1036 (gnus-info-read info))
1038 (gnus-info-set-read info read)
1039 ;; Update the marks.
1040 (setq marks (gnus-info-marks info))
1041 ;; Note the active level for the next run-through.
1042 (let ((active (assq 'active marks)))
1044 (setcdr active (gnus-active group))
1045 (push (cons 'active (gnus-active group)) marks)))
1046 (dolist (type (cdr nnimap-mark-alist))
1047 (let ((old-marks (assoc (car type) marks))
1049 (gnus-compress-sequence
1050 (cdr (or (assoc (caddr type) flags) ; %Flagged
1051 (assoc (intern (cadr type) obarray) flags)
1052 (assoc (cadr type) flags)))))) ; "\Flagged"
1053 (setq marks (delq old-marks marks))
1055 (when (and old-marks
1056 (> start-article 1))
1057 (setq old-marks (gnus-range-difference
1059 (cons start-article high)))
1060 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1062 (push (cons (car type) new-marks) marks)))
1063 (gnus-info-set-marks info marks t)
1064 (nnimap-store-info info (gnus-active group))))))))
1066 (defun nnimap-store-info (info active)
1067 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1068 (entry (assoc group nnimap-current-infos)))
1070 (setcdr entry (list info active))
1071 (push (list group info active) nnimap-current-infos))))
1073 (defun nnimap-flags-to-marks (groups)
1074 (let (data group totalp uidnext articles start-article mark permanent-flags)
1075 (dolist (elem groups)
1076 (setq group (car elem)
1077 uidnext (nth 1 elem)
1078 start-article (nth 2 elem)
1079 permanent-flags (nth 3 elem)
1080 articles (nthcdr 4 elem))
1081 (let ((high (caar articles))
1083 (dolist (article articles)
1084 (setq low (car article))
1085 (push (car article) existing)
1086 (dolist (flag (cdr article))
1087 (setq mark (assoc flag marks))
1089 (push (list flag (car article)) marks)
1090 (setcdr mark (cons (car article) (cdr mark))))))
1091 (push (list group existing marks high low uidnext start-article
1096 (defun nnimap-parse-flags (sequences)
1097 (goto-char (point-min))
1098 ;; Change \Delete etc to %Delete, so that the reader can read it.
1099 (subst-char-in-region (point-min) (point-max)
1101 (let (start end articles groups uidnext elems permanent-flags)
1102 (dolist (elem sequences)
1103 (destructuring-bind (group-sequence flag-sequence totalp group) elem
1104 (setq start (point))
1105 ;; The EXAMINE was successful.
1106 (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1111 (setq permanent-flags
1112 (and (search-forward "PERMANENTFLAGS "
1113 (or end (point-min)) t)
1114 (read (current-buffer))))
1117 (and (search-forward "UIDNEXT "
1118 (or end (point-min)) t)
1119 (read (current-buffer))))
1122 ;; The UID FETCH FLAGS was successful.
1123 (search-forward (format "\n%d OK " flag-sequence) nil t))
1124 (setq start (point))
1126 (while (search-forward " FETCH " start t)
1127 (setq elems (read (current-buffer)))
1128 (push (cons (cadr (memq 'UID elems))
1129 (cadr (memq 'FLAGS elems)))
1131 (push (nconc (list group uidnext totalp permanent-flags) articles)
1133 (setq articles nil))))
1136 (defun nnimap-find-process-buffer (buffer)
1137 (cadr (assoc buffer nnimap-connection-alist)))
1139 (deffoo nnimap-request-post (&optional server)
1140 (setq nnimap-status-string "Read-only server")
1143 (defun nnimap-possibly-change-group (group server)
1144 (let ((open-result t))
1146 (not (nnimap-server-opened server)))
1147 (setq open-result (nnimap-open-server server)))
1154 (with-current-buffer (nnimap-buffer)
1155 (if (equal group (nnimap-group nnimap-object))
1157 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1159 (setf (nnimap-group nnimap-object) group
1160 (nnimap-select-result nnimap-object) result)
1163 (defun nnimap-find-connection (buffer)
1164 "Find the connection delivering to BUFFER."
1165 (let ((entry (assoc buffer nnimap-connection-alist)))
1167 (if (and (buffer-name (cadr entry))
1168 (get-buffer-process (cadr entry))
1169 (memq (process-status (get-buffer-process (cadr entry)))
1171 (get-buffer-process (cadr entry))
1172 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1175 (defvar nnimap-sequence 0)
1177 (defun nnimap-send-command (&rest args)
1178 (process-send-string
1179 (get-buffer-process (current-buffer))
1182 (incf nnimap-sequence)
1183 (apply #'format args)
1184 (if (nnimap-newlinep nnimap-object)
1189 (defun nnimap-log-command (command)
1190 (with-current-buffer (get-buffer-create "*imap log*")
1191 (goto-char (point-max))
1192 (insert (format-time-string "%H:%M:%S") " " command))
1195 (defun nnimap-command (&rest args)
1197 (setf (nnimap-last-command-time nnimap-object) (current-time))
1198 (let* ((sequence (apply #'nnimap-send-command args))
1199 (response (nnimap-get-response sequence)))
1200 (if (equal (caar response) "OK")
1202 (nnheader-report 'nnimap "%s"
1203 (mapconcat (lambda (a)
1205 (car response) " "))
1208 (defun nnimap-get-response (sequence)
1209 (nnimap-wait-for-response sequence)
1210 (nnimap-parse-response))
1212 (defun nnimap-wait-for-connection ()
1213 (let ((process (get-buffer-process (current-buffer))))
1214 (goto-char (point-min))
1215 (while (and (memq (process-status process)
1217 (not (re-search-forward "^[*.] .*\n" nil t)))
1218 (nnheader-accept-process-output process)
1219 (goto-char (point-min)))
1221 (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1224 (defun nnimap-wait-for-response (sequence &optional messagep)
1225 (let ((process (get-buffer-process (current-buffer)))
1227 (goto-char (point-max))
1228 (while (and (setq openp (memq (process-status process)
1230 (not (re-search-backward
1231 (format "^%d .*\n" sequence)
1232 (if nnimap-streaming
1233 (max (point-min) (- (point) 500))
1237 (message "Read %dKB" (/ (buffer-size) 1000)))
1238 (nnheader-accept-process-output process)
1239 (goto-char (point-max)))
1242 (defun nnimap-parse-response ()
1243 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1245 (dolist (line lines)
1246 (push (cdr (nnimap-parse-line line)) result))
1247 ;; Return the OK/error code first, and then all the "continuation
1248 ;; lines" afterwards.
1250 (nreverse result))))
1252 ;; Parse an IMAP response line lightly. They look like
1253 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1254 ;; the lines into a list of strings and lists of string.
1255 (defun nnimap-parse-line (line)
1259 (goto-char (point-min))
1261 (if (eql (setq char (following-char)) ? )
1266 (split-string (buffer-substring
1268 (1- (search-forward "]" (line-end-position) 'move)))))
1270 (split-string (buffer-substring
1272 (1- (search-forward ")" (line-end-position) 'move)))))
1277 (1- (or (search-forward "\"" (line-end-position) 'move)
1280 (buffer-substring (point) (if (search-forward " " nil t)
1282 (goto-char (point-max))))))
1284 (nreverse result))))
1286 (defun nnimap-last-response-string ()
1289 (let ((end (point)))
1293 (while (and (not (bobp))
1294 (eql (following-char) ?*))
1296 (unless (eql (following-char) ?*)
1298 (buffer-substring (point) end))))
1300 (defun nnimap-get-responses (sequences)
1302 (dolist (sequence sequences)
1303 (goto-char (point-min))
1304 (when (re-search-forward (format "^%d " sequence) nil t)
1305 (push (list sequence (nnimap-parse-response))
1309 (defvar nnimap-incoming-split-list nil)
1311 (defun nnimap-fetch-inbox (articles)
1313 (nnimap-wait-for-response
1314 (nnimap-send-command
1316 (nnimap-article-ranges articles)
1317 (format "(UID %s%s)"
1320 "BODY.PEEK[HEADER] BODY.PEEK"
1322 (if nnimap-split-download-body-default
1327 (defun nnimap-split-incoming-mail ()
1328 (with-current-buffer (nnimap-buffer)
1329 (let ((nnimap-incoming-split-list nil)
1330 (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1331 nnmail-split-methods
1332 nnimap-split-methods))
1333 (nnmail-split-fancy (or nnimap-split-fancy
1334 nnmail-split-fancy))
1335 (nnmail-inhibit-default-split-group t)
1336 (groups (nnimap-get-groups))
1339 (nnimap-command "SELECT %S" nnimap-inbox)
1340 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1342 (nnimap-fetch-inbox new-articles)
1343 (nnimap-transform-split-mail)
1344 (nnheader-ms-strip-cr)
1346 (nnmail-split-incoming (current-buffer)
1347 #'nnimap-save-mail-spec
1349 #'nnimap-dummy-active-number
1350 #'nnimap-save-mail-spec)
1351 (when nnimap-incoming-split-list
1352 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1353 sequences junk-articles)
1354 ;; Create any groups that doesn't already exist on the
1356 (dolist (spec specs)
1357 (when (and (not (member (car spec) groups))
1358 (not (eq (car spec) 'junk)))
1359 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1360 ;; Then copy over all the messages.
1362 (dolist (spec specs)
1363 (let ((group (car spec))
1364 (ranges (cdr spec)))
1365 (if (eq group 'junk)
1366 (setq junk-articles ranges)
1367 (push (list (nnimap-send-command
1369 (nnimap-article-ranges ranges)
1370 (utf7-encode group t))
1373 ;; Wait for the last COPY response...
1375 (nnimap-wait-for-response (caar sequences))
1376 ;; And then mark the successful copy actions as deleted,
1377 ;; and possibly expunge them.
1378 (nnimap-mark-and-expunge-incoming
1379 (nnimap-parse-copied-articles sequences)))
1380 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1382 (defun nnimap-mark-and-expunge-incoming (range)
1384 (setq range (nnimap-article-ranges range))
1387 (nnimap-send-command
1388 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1390 ;; If the server supports it, we now delete the message we have
1391 ;; just copied over.
1392 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1393 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1394 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1395 ;; user has configured it.
1397 (setq sequence (nnimap-send-command "EXPUNGE"))))
1398 (nnimap-wait-for-response sequence))))
1400 (defun nnimap-parse-copied-articles (sequences)
1401 (let (sequence copied range)
1402 (goto-char (point-min))
1403 (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1404 (setq sequence (string-to-number (match-string 1)))
1405 (when (setq range (cadr (assq sequence sequences)))
1406 (push (gnus-uncompress-range range) copied)))
1407 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1409 (defun nnimap-new-articles (flags)
1411 (dolist (elem flags)
1412 (when (or (null (cdr elem))
1413 (and (not (memq '%Deleted (cdr elem)))
1414 (not (memq '%Seen (cdr elem)))))
1415 (push (car elem) new)))
1416 (gnus-compress-sequence (nreverse new))))
1418 (defun nnimap-make-split-specs (list)
1422 (destructuring-bind (article spec) elem
1423 (dolist (group (delete nil (mapcar #'car spec)))
1424 (unless (setq entry (assoc group specs))
1425 (push (setq entry (list group)) specs))
1426 (setcdr entry (cons article (cdr entry))))))
1427 (dolist (entry specs)
1428 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1431 (defun nnimap-transform-split-mail ()
1432 (goto-char (point-min))
1433 (let (article bytes)
1436 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1437 (delete-region (point) (progn (forward-line 1) (point)))
1440 (setq article (match-string 1)
1441 bytes (nnimap-get-length))
1442 (delete-region (line-beginning-position) (line-end-position))
1443 ;; Insert MMDF separator, and a way to remember what this
1445 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1446 (forward-char (1+ bytes))
1447 (setq bytes (nnimap-get-length))
1448 (delete-region (line-beginning-position) (line-end-position))
1449 (forward-char (1+ bytes))
1450 (delete-region (line-beginning-position) (line-end-position))))))
1452 (defun nnimap-dummy-active-number (group &optional server)
1455 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1457 (goto-char (point-min))
1458 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1459 (error "Invalid nnimap mail")
1460 (setq article (string-to-number (match-string 1))))
1462 (if (eq group-art 'junk)
1463 (list (cons 'junk 1))
1465 nnimap-incoming-split-list)))
1469 ;;; nnimap.el ends here