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.
43 (autoload 'auth-source-forget-user-or-password "auth-source")
44 (autoload 'auth-source-user-or-password "auth-source")
48 (defvoo nnimap-address nil
49 "The address of the IMAP server.")
51 (defvoo nnimap-server-port nil
53 If nnimap-stream is `ssl', this will default to `imaps'. If not,
54 it will default to `imap'.")
56 (defvoo nnimap-stream 'ssl
57 "How nnimap will talk to the IMAP server.
58 Values are `ssl', `network', `starttls' or `shell'.")
60 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
61 (if (listp imap-shell-program)
62 (car imap-shell-program)
66 (defvoo nnimap-inbox nil
67 "The mail box where incoming mail arrives and should be split out of.")
69 (defvoo nnimap-split-methods nil
71 Uses the same syntax as nnmail-split-methods")
73 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
76 (defvoo nnimap-authenticator nil
77 "How nnimap authenticate itself to the server.
78 Possible choices are nil (use default methods) or `anonymous'.")
80 (defvoo nnimap-expunge t
81 "If non-nil, expunge articles after deleting them.
82 This is always done if the server supports UID EXPUNGE, but it's
83 not done by default on servers that doesn't support that command.")
85 (defvoo nnimap-streaming t
86 "If non-nil, try to use streaming commands with IMAP servers.
87 Switching this off will make nnimap slower, but it helps with
90 (defvoo nnimap-connection-alist nil)
92 (defvoo nnimap-current-infos nil)
94 (defvoo nnimap-fetch-partial-articles nil
95 "If non-nil, Gnus will fetch partial articles.
96 If t, nnimap will fetch only the first part. If a string, it
97 will fetch all parts that have types that match that string. A
98 likely value would be \"text/\" to automatically fetch all
101 (defvar nnimap-process nil)
103 (defvar nnimap-status-string "")
105 (defvar nnimap-split-download-body-default nil
106 "Internal variable with default value for `nnimap-split-download-body'.")
108 (defvar nnimap-keepalive-timer nil)
109 (defvar nnimap-process-buffers nil)
112 group process commands capabilities select-result newlinep server
113 last-command-time greeting)
115 (defvar nnimap-object nil)
117 (defvar nnimap-mark-alist
118 '((read "\\Seen" %Seen)
119 (tick "\\Flagged" %Flagged)
120 (reply "\\Answered" %Answered)
121 (expire "gnus-expire")
122 (dormant "gnus-dormant")
125 (download "gnus-download")
126 (forward "gnus-forward")))
128 (defun nnimap-buffer ()
129 (nnimap-find-process-buffer nntp-server-buffer))
131 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
132 (with-current-buffer nntp-server-buffer
134 (when (nnimap-possibly-change-group group server)
135 (with-current-buffer (nnimap-buffer)
137 (nnimap-wait-for-response
140 (nnimap-article-ranges (gnus-compress-sequence articles))
141 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
144 "BODY.PEEK[HEADER.FIELDS %s]"
145 "RFC822.HEADER.LINES %s")
146 (append '(Subject From Date Message-Id
147 References In-Reply-To Xref)
148 nnmail-extra-headers))))
150 (nnimap-transform-headers))
151 (insert-buffer-substring
152 (nnimap-find-process-buffer (current-buffer))))
155 (defun nnimap-transform-headers ()
156 (goto-char (point-min))
157 (let (article bytes lines size string)
160 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
161 (delete-region (point) (progn (forward-line 1) (point)))
164 (setq article (match-string 1))
165 ;; Unfold quoted {number} strings.
166 (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
167 (1+ (line-end-position)) t)
168 (setq size (string-to-number (match-string 1)))
169 (delete-region (+ (match-beginning 0) 2) (point))
170 (setq string (delete-region (point) (+ (point) size)))
171 (insert (format "%S" string)))
172 (setq bytes (nnimap-get-length)
176 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
181 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
182 (let ((structure (ignore-errors
183 (read (current-buffer)))))
184 (while (and (consp structure)
185 (not (stringp (car structure))))
186 (setq structure (car structure)))
187 (setq lines (nth 7 structure))))
188 (delete-region (line-beginning-position) (line-end-position))
189 (insert (format "211 %s Article retrieved." article))
192 (insert (format "Chars: %s\n" size)))
194 (insert (format "Lines: %s\n" lines)))
195 (re-search-forward "^\r$")
196 (delete-region (line-beginning-position) (line-end-position))
200 (defun nnimap-get-length ()
201 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
202 (string-to-number (match-string 1))))
204 (defun nnimap-article-ranges (ranges)
208 (number-to-string ranges))
209 ((numberp (cdr ranges))
210 (format "%d:%d" (car ranges) (cdr ranges)))
212 (dolist (elem ranges)
215 (format "%d:%d" (car elem) (cdr elem))
216 (number-to-string elem))
218 (mapconcat #'identity (nreverse result) ",")))))
220 (deffoo nnimap-open-server (server &optional defs)
221 (if (nnimap-server-opened server)
223 (unless (assq 'nnimap-address defs)
224 (setq defs (append defs (list (list 'nnimap-address server)))))
225 (nnoo-change-server 'nnimap server defs)
226 (or (nnimap-find-connection nntp-server-buffer)
227 (nnimap-open-connection nntp-server-buffer))))
229 (defun nnimap-make-process-buffer (buffer)
231 (generate-new-buffer (format "*nnimap %s %s %s*"
232 nnimap-address nnimap-server-port
233 (gnus-buffer-exists-p buffer)))
234 (mm-disable-multibyte)
235 (buffer-disable-undo)
237 (set (make-local-variable 'after-change-functions) nil)
238 (set (make-local-variable 'nnimap-object)
239 (make-nnimap :server (nnoo-current-server 'nnimap)))
240 (push (list buffer (current-buffer)) nnimap-connection-alist)
241 (push (current-buffer) nnimap-process-buffers)
244 (defun nnimap-open-shell-stream (name buffer host port)
245 (let ((process-connection-type nil))
246 (start-process name buffer shell-file-name
254 (defun nnimap-credentials (address ports &optional inhibit-create)
255 (let (port credentials)
256 ;; Request the credentials from all ports, but only query on the
257 ;; last port if all the previous ones have failed.
258 (while (and (null credentials)
259 (setq port (pop ports)))
261 (auth-source-user-or-password
262 '("login" "password") address port nil
268 (defun nnimap-keepalive ()
269 (let ((now (current-time)))
270 (dolist (buffer nnimap-process-buffers)
271 (when (buffer-name buffer)
272 (with-current-buffer buffer
273 (when (and nnimap-object
274 (nnimap-last-command-time nnimap-object)
278 (nnimap-last-command-time nnimap-object)))
279 ;; More than five minutes since the last command.
281 (nnimap-send-command "NOOP")))))))
283 (defun nnimap-open-connection (buffer)
284 (unless nnimap-keepalive-timer
285 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
288 (with-current-buffer (nnimap-make-process-buffer buffer)
289 (let* ((coding-system-for-read 'binary)
290 (coding-system-for-write 'binary)
294 ((eq nnimap-stream 'network)
296 "*nnimap*" (current-buffer) nnimap-address
298 (or nnimap-server-port
299 (if (netrc-find-service-number "imap")
303 ((eq nnimap-stream 'shell)
304 (nnimap-open-shell-stream
305 "*nnimap*" (current-buffer) nnimap-address
306 (setq port (or nnimap-server-port "imap")))
308 ((eq nnimap-stream 'starttls)
309 (starttls-open-stream
310 "*nnimap*" (current-buffer) nnimap-address
311 (setq port (or nnimap-server-port "imap")))
313 ((eq nnimap-stream 'ssl)
315 "*nnimap*" (current-buffer) nnimap-address
317 (or nnimap-server-port
318 (if (netrc-find-service-number "imaps")
321 '("143" "993" "imap" "imaps"))))
322 connection-result login-result credentials)
323 (setf (nnimap-process nnimap-object)
324 (get-buffer-process (current-buffer)))
325 (if (not (and (nnimap-process nnimap-object)
326 (memq (process-status (nnimap-process nnimap-object))
328 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
329 nnimap-address port nnimap-stream)
330 (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
331 (if (not (setq connection-result (nnimap-wait-for-connection)))
332 (nnheader-report 'nnimap
333 "%s" (buffer-substring
334 (point) (line-end-position)))
335 ;; Store the greeting (for debugging purposes).
336 (setf (nnimap-greeting nnimap-object)
337 (buffer-substring (line-beginning-position)
338 (line-end-position)))
339 ;; Store the capabilities.
340 (setf (nnimap-capabilities nnimap-object)
343 (nnimap-find-parameter
344 "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
345 (when (eq nnimap-stream 'starttls)
346 (nnimap-command "STARTTLS")
347 (starttls-negotiate (nnimap-process nnimap-object)))
348 (when nnimap-server-port
349 (push (format "%s" nnimap-server-port) ports))
350 (unless (equal connection-result "PREAUTH")
351 (if (not (setq credentials
352 (if (eq nnimap-authenticator 'anonymous)
354 (message-make-address))
356 ;; First look for the credentials based
357 ;; on the virtual server name.
359 (nnoo-current-server 'nnimap) ports t)
360 ;; Then look them up based on the
362 (nnimap-credentials nnimap-address ports)))))
363 (setq nnimap-object nil)
364 (setq login-result (nnimap-command "LOGIN %S %S"
367 (unless (car login-result)
368 ;; If the login failed, then forget the credentials
369 ;; that are now possibly cached.
370 (dolist (host (list (nnoo-current-server 'nnimap)
373 (dolist (element '("login" "password"))
374 (auth-source-forget-user-or-password
375 element host port))))
376 (delete-process (nnimap-process nnimap-object))
377 (setq nnimap-object nil))))
379 (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
380 (nnimap-command "ENABLE QRESYNC"))
383 (defun nnimap-find-parameter (parameter elems)
387 ((equal (car elem) parameter)
388 (setq result (cdr elem)))
389 ((and (equal (car elem) "OK")
391 (equal (caadr elem) parameter))
392 (setq result (cdr (cadr elem))))))
395 (deffoo nnimap-close-server (&optional server)
398 (deffoo nnimap-request-close ()
401 (deffoo nnimap-server-opened (&optional server)
402 (and (nnoo-current-server-p 'nnimap server)
404 (gnus-buffer-live-p nntp-server-buffer)
405 (nnimap-find-connection nntp-server-buffer)))
407 (deffoo nnimap-status-message (&optional server)
408 nnimap-status-string)
410 (deffoo nnimap-request-article (article &optional group server to-buffer)
411 (with-current-buffer nntp-server-buffer
412 (let ((result (nnimap-possibly-change-group group server))
414 (when (stringp article)
415 (setq article (nnimap-find-article-by-message-id group article)))
419 (with-current-buffer (nnimap-buffer)
421 (when nnimap-fetch-partial-articles
422 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
423 (goto-char (point-min))
424 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
425 (setq structure (ignore-errors
426 (let ((start (point)))
428 (downcase-region start (point))
430 (read (current-buffer))))
431 parts (nnimap-find-wanted-parts structure))))
433 (nnimap-get-partial-article article parts structure)
434 (nnimap-get-whole-article article))
435 (let ((buffer (current-buffer)))
436 (with-current-buffer (or to-buffer nntp-server-buffer)
438 (insert-buffer-substring buffer)
439 (nnheader-ms-strip-cr)
440 (cons group article)))))))))
442 (defun nnimap-get-whole-article (article)
446 "UID FETCH %d BODY.PEEK[]"
447 "UID FETCH %d RFC822.PEEK")
449 ;; Check that we really got an article.
450 (goto-char (point-min))
451 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
454 ;; Remove any data that may have arrived before the FETCH data.
457 (delete-region (point-min) (point)))
458 (let ((bytes (nnimap-get-length)))
459 (delete-region (line-beginning-position)
460 (progn (forward-line 1) (point)))
461 (goto-char (+ (point) bytes))
462 (delete-region (point) (point-max)))
465 (defun nnimap-ver4-p ()
466 (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
468 (defun nnimap-get-partial-article (article parts structure)
471 "UID FETCH %d (%s %s)"
477 (mapconcat (lambda (part)
478 (format "BODY.PEEK[%s]" part))
480 (mapconcat (lambda (part)
481 (format "RFC822.PEEK[%s]" part))
484 (nnimap-convert-partial-article structure))))
486 (defun nnimap-convert-partial-article (structure)
487 ;; First just skip past the headers.
488 (goto-char (point-min))
489 (let ((bytes (nnimap-get-length))
491 ;; Delete "FETCH" line.
492 (delete-region (line-beginning-position)
493 (progn (forward-line 1) (point)))
494 (goto-char (+ (point) bytes))
495 ;; Collect all the body parts.
496 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
497 (setq id (match-string 1)
498 bytes (nnimap-get-length))
500 (delete-region (point) (progn (forward-line 1) (point)))
501 (push (list id (buffer-substring (point) (+ (point) bytes)))
503 (delete-region (point) (+ (point) bytes)))
504 ;; Delete trailing junk.
505 (delete-region (point) (point-max))
506 ;; Now insert all the parts again where they fit in the structure.
507 (nnimap-insert-partial-structure structure parts)
510 (defun nnimap-insert-partial-structure (structure parts &optional subp)
512 (let ((bstruc structure))
513 (while (consp (car bstruc))
515 (setq type (car bstruc))
516 (setq bstruc (car (cdr bstruc)))
517 (when (and (stringp (car bstruc))
518 (string= (downcase (car bstruc)) "boundary"))
519 (setq boundary (cadr bstruc))))
521 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
522 (downcase type) boundary)))
523 (while (not (stringp (car structure)))
524 (insert "\n--" boundary "\n")
525 (if (consp (caar structure))
526 (nnimap-insert-partial-structure (pop structure) parts t)
527 (let ((bit (pop structure)))
528 (insert (format "Content-type: %s/%s"
529 (downcase (nth 0 bit))
530 (downcase (nth 1 bit))))
531 (if (member "CHARSET" (nth 2 bit))
533 "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
535 (insert (format "Content-transfer-encoding: %s\n"
538 (when (assoc (nth 9 bit) parts)
539 (insert (cadr (assoc (nth 9 bit) parts)))))))
540 (insert "\n--" boundary "--\n")))
542 (defun nnimap-find-wanted-parts (structure)
543 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
545 (defun nnimap-find-wanted-parts-1 (structure prefix)
548 (while (consp (car structure))
549 (let ((sub (pop structure)))
550 (if (consp (car sub))
551 (push (nnimap-find-wanted-parts-1
552 sub (if (string= prefix "")
553 (number-to-string num)
554 (format "%s.%s" prefix num)))
556 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
557 (id (if (string= prefix "")
558 (number-to-string num)
559 (format "%s.%s" prefix num))))
560 (setcar (nthcdr 9 sub) id)
561 (when (if (eq nnimap-fetch-partial-articles t)
563 (string-match nnimap-fetch-partial-articles type))
568 (deffoo nnimap-request-group (group &optional server dont-check info)
569 (let ((result (nnimap-possibly-change-group group server))
570 articles active marks high low)
571 (with-current-buffer nntp-server-buffer
574 (setq active (nth 2 (assoc group nnimap-current-infos))))
575 (insert (format "211 %d %d %d %S\n"
576 (- (cdr active) (car active))
580 (with-current-buffer (nnimap-buffer)
582 (let ((group-sequence
583 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
585 (nnimap-send-command "UID FETCH 1:* FLAGS")))
586 (nnimap-wait-for-response flag-sequence)
588 (nnimap-flags-to-marks
590 (list (list group-sequence flag-sequence 1 group)))))
592 (nnimap-update-infos marks (list info)))
593 (goto-char (point-max))
594 (let ((uidnext (nth 5 (car marks))))
595 (setq high (if uidnext
598 low (or (nth 4 (car marks)) uidnext)))))
602 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
605 (deffoo nnimap-request-create-group (group &optional server args)
606 (when (nnimap-possibly-change-group nil server)
607 (with-current-buffer (nnimap-buffer)
608 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
610 (deffoo nnimap-request-delete-group (group &optional force server)
611 (when (nnimap-possibly-change-group nil server)
612 (with-current-buffer (nnimap-buffer)
613 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
615 (deffoo nnimap-request-expunge-group (group &optional server)
616 (when (nnimap-possibly-change-group group server)
617 (with-current-buffer (nnimap-buffer)
618 (car (nnimap-command "EXPUNGE")))))
620 (defun nnimap-get-flags (spec)
623 (with-current-buffer (nnimap-buffer)
625 (nnimap-wait-for-response (nnimap-send-command
626 "UID FETCH %s FLAGS" spec))
627 (goto-char (point-min))
628 (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
629 (setq elems (nnimap-parse-line (match-string 1)))
630 (push (cons (string-to-number (cadr (member "UID" elems)))
631 (cadr (member "FLAGS" elems)))
633 (nreverse articles)))
635 (deffoo nnimap-close-group (group &optional server)
638 (deffoo nnimap-request-move-article (article group server accept-form
639 &optional last internal-move-group)
641 (when (nnimap-request-article article group server (current-buffer))
642 ;; If the move is internal (on the same server), just do it the easy
644 (let ((message-id (message-field-value "message-id")))
645 (if internal-move-group
647 (with-current-buffer (nnimap-buffer)
648 (nnimap-command "UID COPY %d %S"
650 (utf7-encode internal-move-group t)))))
652 (nnimap-delete-article article)
653 (cons internal-move-group
654 (nnimap-find-article-by-message-id
655 internal-move-group message-id))))
656 ;; Move the article to a different method.
657 (let ((result (eval accept-form)))
659 (nnimap-delete-article article)
662 (deffoo nnimap-request-expire-articles (articles group &optional server force)
666 ((not (nnimap-possibly-change-group group server))
669 (eq nnmail-expiry-target 'delete))
670 (unless (nnimap-delete-article (gnus-compress-sequence articles))
671 (message "Article marked for deletion, but not expunged."))
674 (let ((deletable-articles
676 (eq nnmail-expiry-wait 'immediate))
678 (gnus-sorted-intersection
680 (nnimap-find-expired-articles group)))))
681 (if (null deletable-articles)
683 (if (eq nnmail-expiry-target 'delete)
684 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
685 (setq deletable-articles
686 (nnimap-process-expiry-targets
687 deletable-articles group server)))
688 ;; Return the articles we didn't delete.
689 (gnus-sorted-complement articles deletable-articles))))))
691 (defun nnimap-process-expiry-targets (articles group server)
692 (let ((deleted-articles nil))
693 (dolist (article articles)
694 (let ((target nnmail-expiry-target))
696 (when (nnimap-request-article article group server (current-buffer))
697 (message "Expiring article %s:%d" group article)
698 (when (functionp target)
699 (setq target (funcall target group)))
701 (not (eq target 'delete)))
702 (if (or (gnus-request-group target t)
703 (gnus-request-create-group target))
704 (nnmail-expiry-target-group target group)
707 (push article deleted-articles))))))
708 ;; Change back to the current group again.
709 (nnimap-possibly-change-group group server)
710 (setq deleted-articles (nreverse deleted-articles))
711 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
714 (defun nnimap-find-expired-articles (group)
715 (let ((cutoff (nnmail-expired-article-p group nil nil)))
716 (with-current-buffer (nnimap-buffer)
719 "UID SEARCH SENTBEFORE %s"
723 (car (rassoc (nth 4 (decode-time cutoff))
724 parse-time-months))))
727 (delete 0 (mapcar #'string-to-number
728 (cdr (assoc "SEARCH" (cdr result))))))))))
731 (defun nnimap-find-article-by-message-id (group message-id)
732 (when (nnimap-possibly-change-group group nil)
733 (with-current-buffer (nnimap-buffer)
735 (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
738 ;; Select the last instance of the message in the group.
740 (car (last (assoc "SEARCH" (cdr result)))))
741 (string-to-number article)))))))
743 (defun nnimap-delete-article (articles)
744 (with-current-buffer (nnimap-buffer)
745 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
746 (nnimap-article-ranges articles))
748 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
749 (nnimap-command "UID EXPUNGE %s"
750 (nnimap-article-ranges articles))
753 (nnimap-command "EXPUNGE")
755 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
756 "server doesn't support UIDPLUS, so we won't "
757 "delete this article now"))))))
759 (deffoo nnimap-request-scan (&optional group server)
760 (when (and (nnimap-possibly-change-group nil server)
762 nnimap-split-methods)
763 (message "nnimap %s splitting mail..." server)
764 (nnimap-split-incoming-mail)))
766 (defun nnimap-marks-to-flags (marks)
769 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
773 (deffoo nnimap-request-set-mark (group actions &optional server)
774 (when (nnimap-possibly-change-group group server)
776 (with-current-buffer (nnimap-buffer)
778 ;; Just send all the STORE commands without waiting for
779 ;; response. If they're successful, they're successful.
780 (dolist (action actions)
781 (destructuring-bind (range action marks) action
782 (let ((flags (nnimap-marks-to-flags marks)))
784 (setq sequence (nnimap-send-command
785 "UID STORE %s %sFLAGS.SILENT (%s)"
786 (nnimap-article-ranges range)
790 (mapconcat #'identity flags " ")))))))
791 ;; Wait for the last command to complete to avoid later
792 ;; syncronisation problems with the stream.
794 (nnimap-wait-for-response sequence))))))
796 (deffoo nnimap-request-accept-article (group &optional server last)
797 (when (nnimap-possibly-change-group nil server)
798 (nnmail-check-syntax)
799 (let ((message-id (message-field-value "message-id"))
802 (setq message (buffer-string))
803 (with-current-buffer (nnimap-buffer)
804 (setq sequence (nnimap-send-command
805 "APPEND %S {%d}" (utf7-encode group t)
807 (process-send-string (get-buffer-process (current-buffer)) message)
808 (process-send-string (get-buffer-process (current-buffer))
809 (if (nnimap-newlinep nnimap-object)
812 (let ((result (nnimap-get-response sequence)))
813 (if (not (car result))
815 (message "%s" (nnheader-get-report-string 'nnimap))
818 (nnimap-find-article-by-message-id group message-id))))))))
820 (defun nnimap-add-cr ()
821 (goto-char (point-min))
822 (while (re-search-forward "\r?\n" nil t)
823 (replace-match "\r\n" t t)))
825 (defun nnimap-get-groups ()
826 (let ((result (nnimap-command "LIST \"\" \"*\""))
829 (dolist (line (cdr result))
830 (when (and (equal (car line) "LIST")
831 (not (and (caadr line)
832 (string-match "noselect" (caadr line)))))
833 (push (car (last line)) groups)))
836 (deffoo nnimap-request-list (&optional server)
837 (nnimap-possibly-change-group nil server)
838 (with-current-buffer nntp-server-buffer
841 (with-current-buffer (nnimap-buffer)
842 (nnimap-get-groups)))
845 (with-current-buffer (nnimap-buffer)
846 (setf (nnimap-group nnimap-object) nil)
847 (dolist (group groups)
848 (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
851 (nnimap-wait-for-response (caar sequences))
853 (nnimap-get-responses (mapcar #'car sequences))))
854 (dolist (response responses)
855 (let* ((sequence (car response))
856 (response (cadr response))
857 (group (cadr (assoc sequence sequences))))
859 (equal (caar response) "OK"))
860 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
862 (dolist (elem response)
863 (when (equal (cadr elem) "EXISTS")
864 (setq exists (string-to-number (car elem)))))
866 (setq highest (1- (string-to-number (car uidnext)))))
869 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
872 (insert (format "%S %d %d y\n"
873 (utf7-decode group t) highest (1+ highest))))
875 ;; Return the widest possible range.
876 (insert (format "%S %d 1 y\n" (utf7-decode group t)
877 (or highest exists)))))))))
880 (deffoo nnimap-retrieve-group-data-early (server infos)
881 (when (nnimap-possibly-change-group nil server)
882 (with-current-buffer (nnimap-buffer)
883 ;; QRESYNC handling isn't implemented.
884 (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
885 marks groups sequences)
886 ;; Go through the infos and gather the data needed to know
887 ;; what and how to request the data.
889 (setq marks (gnus-info-marks info))
890 (push (list (gnus-group-real-name (gnus-info-group info))
891 (cdr (assq 'active marks))
892 (cdr (assq 'uid marks)))
894 ;; Then request the data.
896 (setf (nnimap-group nnimap-object) nil)
897 (dolist (elem groups)
902 (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
911 ;; Fetch the last 100 flags.
912 (max 1 (- (cdr (nth 1 elem)) 100))
914 (push (list (nnimap-send-command "EXAMINE %S" (car elem))
915 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
919 ;; Some servers apparently can't have many outstanding
920 ;; commands, so throttle them.
921 (when (and (not nnimap-streaming)
923 (nnimap-wait-for-response (caar sequences))))
926 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
928 (nnimap-possibly-change-group nil server))
929 (with-current-buffer (nnimap-buffer)
930 ;; Wait for the final data to trickle in.
931 (when (nnimap-wait-for-response (cadar sequences))
932 ;; Now we should have all the data we need, no matter whether
933 ;; we're QRESYNCING, fetching all the flags from scratch, or
934 ;; just fetching the last 100 flags per group.
935 (nnimap-update-infos (nnimap-flags-to-marks
937 (nreverse sequences)))
939 ;; Finally, just return something resembling an active file in
940 ;; the nntp buffer, so that the agent can save the info, too.
941 (with-current-buffer nntp-server-buffer
944 (let* ((group (gnus-info-group info))
945 (active (gnus-active group)))
947 (insert (format "%S %d %d y\n"
948 (gnus-group-real-name group)
950 (car active)))))))))))
952 (defun nnimap-update-infos (flags infos)
954 (let ((group (gnus-group-real-name (gnus-info-group info))))
955 (nnimap-update-info info (cdr (assoc group flags))))))
957 (defun nnimap-update-info (info marks)
959 (destructuring-bind (existing flags high low uidnext start-article
960 permanent-flags) marks
961 (let ((group (gnus-info-group info))
962 (completep (and start-article
963 (= start-article 1))))
965 (setq high (1- uidnext)))
966 ;; First set the active ranges based on high/low.
968 (not (gnus-active group)))
969 (gnus-set-active group
974 ;; No articles in this group.
975 (cons uidnext (1- uidnext)))
977 (cons start-article (1- start-article)))
979 ;; No articles and no uidnext.
983 (cons (car (gnus-active group))
984 (or high (1- uidnext)))))
985 (when (and (not high)
987 (setq high (1- uidnext)))
988 ;; Then update the list of read articles.
990 (gnus-compress-sequence
994 (cdr (assoc '%Seen flags)))
995 (cdr (assoc '%Flagged flags)))))
996 (read (gnus-range-difference
997 (cons start-article high) unread)))
998 (when (> start-article 1)
1001 (if (> start-article 1)
1002 (gnus-sorted-range-intersection
1003 (cons 1 (1- start-article))
1004 (gnus-info-read info))
1005 (gnus-info-read info))
1007 (gnus-info-set-read info read)
1008 ;; Update the marks.
1009 (setq marks (gnus-info-marks info))
1010 ;; Note the active level for the next run-through.
1011 (let ((active (assq 'active marks)))
1013 (setcdr active (gnus-active group))
1014 (push (cons 'active (gnus-active group)) marks)))
1015 (dolist (type (cdr nnimap-mark-alist))
1016 (let ((old-marks (assoc (car type) marks))
1018 (gnus-compress-sequence
1019 (cdr (or (assoc (caddr type) flags) ; %Flagged
1020 (assoc (intern (cadr type) obarray) flags)
1021 (assoc (cadr type) flags)))))) ; "\Flagged"
1022 (setq marks (delq old-marks marks))
1024 (when (and old-marks
1025 (> start-article 1))
1026 (setq old-marks (gnus-range-difference
1028 (cons start-article high)))
1029 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1031 (push (cons (car type) new-marks) marks)))
1032 (gnus-info-set-marks info marks t)
1033 (nnimap-store-info info (gnus-active group))))))))
1035 (defun nnimap-store-info (info active)
1036 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1037 (entry (assoc group nnimap-current-infos)))
1039 (setcdr entry (list info active))
1040 (push (list group info active) nnimap-current-infos))))
1042 (defun nnimap-flags-to-marks (groups)
1043 (let (data group totalp uidnext articles start-article mark permanent-flags)
1044 (dolist (elem groups)
1045 (setq group (car elem)
1046 uidnext (nth 1 elem)
1047 start-article (nth 2 elem)
1048 permanent-flags (nth 3 elem)
1049 articles (nthcdr 4 elem))
1050 (let ((high (caar articles))
1052 (dolist (article articles)
1053 (setq low (car article))
1054 (push (car article) existing)
1055 (dolist (flag (cdr article))
1056 (setq mark (assoc flag marks))
1058 (push (list flag (car article)) marks)
1059 (setcdr mark (cons (car article) (cdr mark))))))
1060 (push (list group existing marks high low uidnext start-article
1065 (defun nnimap-parse-flags (sequences)
1066 (goto-char (point-min))
1067 ;; Change \Delete etc to %Delete, so that the reader can read it.
1068 (subst-char-in-region (point-min) (point-max)
1070 (let (start end articles groups uidnext elems permanent-flags)
1071 (dolist (elem sequences)
1072 (destructuring-bind (group-sequence flag-sequence totalp group) elem
1073 (setq start (point))
1074 ;; The EXAMINE was successful.
1075 (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1080 (setq permanent-flags
1081 (and (search-forward "PERMANENTFLAGS "
1082 (or end (point-min)) t)
1083 (read (current-buffer))))
1086 (and (search-forward "UIDNEXT "
1087 (or end (point-min)) t)
1088 (read (current-buffer))))
1091 ;; The UID FETCH FLAGS was successful.
1092 (search-forward (format "\n%d OK " flag-sequence) nil t))
1093 (setq start (point))
1095 (while (search-forward " FETCH " start t)
1096 (setq elems (read (current-buffer)))
1097 (push (cons (cadr (memq 'UID elems))
1098 (cadr (memq 'FLAGS elems)))
1100 (push (nconc (list group uidnext totalp permanent-flags) articles)
1102 (setq articles nil))))
1105 (defun nnimap-find-process-buffer (buffer)
1106 (cadr (assoc buffer nnimap-connection-alist)))
1108 (deffoo nnimap-request-post (&optional server)
1109 (setq nnimap-status-string "Read-only server")
1112 (defun nnimap-possibly-change-group (group server)
1113 (let ((open-result t))
1115 (not (nnimap-server-opened server)))
1116 (setq open-result (nnimap-open-server server)))
1123 (with-current-buffer (nnimap-buffer)
1124 (if (equal group (nnimap-group nnimap-object))
1126 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1128 (setf (nnimap-group nnimap-object) group
1129 (nnimap-select-result nnimap-object) result)
1132 (defun nnimap-find-connection (buffer)
1133 "Find the connection delivering to BUFFER."
1134 (let ((entry (assoc buffer nnimap-connection-alist)))
1136 (if (and (buffer-name (cadr entry))
1137 (get-buffer-process (cadr entry))
1138 (memq (process-status (get-buffer-process (cadr entry)))
1140 (get-buffer-process (cadr entry))
1141 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1144 (defvar nnimap-sequence 0)
1146 (defun nnimap-send-command (&rest args)
1147 (process-send-string
1148 (get-buffer-process (current-buffer))
1151 (incf nnimap-sequence)
1152 (apply #'format args)
1153 (if (nnimap-newlinep nnimap-object)
1158 (defun nnimap-log-command (command)
1159 (with-current-buffer (get-buffer-create "*imap log*")
1160 (goto-char (point-max))
1161 (insert (format-time-string "%H:%M:%S") " " command))
1164 (defun nnimap-command (&rest args)
1166 (setf (nnimap-last-command-time nnimap-object) (current-time))
1167 (let* ((sequence (apply #'nnimap-send-command args))
1168 (response (nnimap-get-response sequence)))
1169 (if (equal (caar response) "OK")
1171 (nnheader-report 'nnimap "%s"
1172 (mapconcat (lambda (a)
1174 (car response) " "))
1177 (defun nnimap-get-response (sequence)
1178 (nnimap-wait-for-response sequence)
1179 (nnimap-parse-response))
1181 (defun nnimap-wait-for-connection ()
1182 (let ((process (get-buffer-process (current-buffer))))
1183 (goto-char (point-min))
1184 (while (and (memq (process-status process)
1186 (not (re-search-forward "^\\* .*\n" nil t)))
1187 (nnheader-accept-process-output process)
1188 (goto-char (point-min)))
1190 (and (looking-at "\\* \\([A-Z0-9]+\\)")
1193 (defun nnimap-wait-for-response (sequence &optional messagep)
1194 (let ((process (get-buffer-process (current-buffer)))
1196 (goto-char (point-max))
1197 (while (and (setq openp (memq (process-status process)
1199 (not (re-search-backward
1200 (format "^%d .*\n" sequence)
1201 (if nnimap-streaming
1202 (max (point-min) (- (point) 500))
1206 (message "Read %dKB" (/ (buffer-size) 1000)))
1207 (nnheader-accept-process-output process)
1208 (goto-char (point-max)))
1211 (defun nnimap-parse-response ()
1212 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1214 (dolist (line lines)
1215 (push (cdr (nnimap-parse-line line)) result))
1216 ;; Return the OK/error code first, and then all the "continuation
1217 ;; lines" afterwards.
1219 (nreverse result))))
1221 ;; Parse an IMAP response line lightly. They look like
1222 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1223 ;; the lines into a list of strings and lists of string.
1224 (defun nnimap-parse-line (line)
1228 (goto-char (point-min))
1230 (if (eql (setq char (following-char)) ? )
1235 (split-string (buffer-substring
1237 (1- (search-forward "]" (line-end-position) 'move)))))
1239 (split-string (buffer-substring
1241 (1- (search-forward ")" (line-end-position) 'move)))))
1246 (1- (or (search-forward "\"" (line-end-position) 'move)
1249 (buffer-substring (point) (if (search-forward " " nil t)
1251 (goto-char (point-max))))))
1253 (nreverse result))))
1255 (defun nnimap-last-response-string ()
1258 (let ((end (point)))
1262 (while (and (not (bobp))
1263 (eql (following-char) ?*))
1265 (unless (eql (following-char) ?*)
1267 (buffer-substring (point) end))))
1269 (defun nnimap-get-responses (sequences)
1271 (dolist (sequence sequences)
1272 (goto-char (point-min))
1273 (when (re-search-forward (format "^%d " sequence) nil t)
1274 (push (list sequence (nnimap-parse-response))
1278 (defvar nnimap-incoming-split-list nil)
1280 (defun nnimap-fetch-inbox (articles)
1282 (nnimap-wait-for-response
1283 (nnimap-send-command
1285 (nnimap-article-ranges articles)
1286 (format "(UID %s%s)"
1289 "BODY.PEEK[HEADER] BODY.PEEK"
1291 (if nnimap-split-download-body-default
1296 (defun nnimap-split-incoming-mail ()
1297 (with-current-buffer (nnimap-buffer)
1298 (let ((nnimap-incoming-split-list nil)
1299 (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1300 nnmail-split-methods
1301 nnimap-split-methods))
1302 (nnmail-inhibit-default-split-group t)
1303 (groups (nnimap-get-groups))
1306 (nnimap-command "SELECT %S" nnimap-inbox)
1307 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1309 (nnimap-fetch-inbox new-articles)
1310 (nnimap-transform-split-mail)
1311 (nnheader-ms-strip-cr)
1313 (nnmail-split-incoming (current-buffer)
1314 #'nnimap-save-mail-spec
1316 #'nnimap-dummy-active-number
1317 #'nnimap-save-mail-spec)
1318 (when nnimap-incoming-split-list
1319 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1320 sequences junk-articles)
1321 ;; Create any groups that doesn't already exist on the
1323 (dolist (spec specs)
1324 (when (and (not (member (car spec) groups))
1325 (not (eq (car spec) 'junk)))
1326 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1327 ;; Then copy over all the messages.
1329 (dolist (spec specs)
1330 (let ((group (car spec))
1331 (ranges (cdr spec)))
1332 (if (eq group 'junk)
1333 (setq junk-articles ranges)
1334 (push (list (nnimap-send-command
1336 (nnimap-article-ranges ranges)
1337 (utf7-encode group t))
1340 ;; Wait for the last COPY response...
1342 (nnimap-wait-for-response (caar sequences))
1343 ;; And then mark the successful copy actions as deleted,
1344 ;; and possibly expunge them.
1345 (nnimap-mark-and-expunge-incoming
1346 (nnimap-parse-copied-articles sequences)))
1347 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1349 (defun nnimap-mark-and-expunge-incoming (range)
1351 (setq range (nnimap-article-ranges range))
1354 (nnimap-send-command
1355 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1357 ;; If the server supports it, we now delete the message we have
1358 ;; just copied over.
1359 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1360 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1361 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1362 ;; user has configured it.
1364 (setq sequence (nnimap-send-command "EXPUNGE"))))
1365 (nnimap-wait-for-response sequence))))
1367 (defun nnimap-parse-copied-articles (sequences)
1368 (let (sequence copied range)
1369 (goto-char (point-min))
1370 (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1371 (setq sequence (string-to-number (match-string 1)))
1372 (when (setq range (cadr (assq sequence sequences)))
1373 (push (gnus-uncompress-range range) copied)))
1374 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1376 (defun nnimap-new-articles (flags)
1378 (dolist (elem flags)
1379 (when (or (null (cdr elem))
1380 (and (not (memq '%Deleted (cdr elem)))
1381 (not (memq '%Seen (cdr elem)))))
1382 (push (car elem) new)))
1383 (gnus-compress-sequence (nreverse new))))
1385 (defun nnimap-make-split-specs (list)
1389 (destructuring-bind (article spec) elem
1390 (dolist (group (delete nil (mapcar #'car spec)))
1391 (unless (setq entry (assoc group specs))
1392 (push (setq entry (list group)) specs))
1393 (setcdr entry (cons article (cdr entry))))))
1394 (dolist (entry specs)
1395 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1398 (defun nnimap-transform-split-mail ()
1399 (goto-char (point-min))
1400 (let (article bytes)
1403 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1404 (delete-region (point) (progn (forward-line 1) (point)))
1407 (setq article (match-string 1)
1408 bytes (nnimap-get-length))
1409 (delete-region (line-beginning-position) (line-end-position))
1410 ;; Insert MMDF separator, and a way to remember what this
1412 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1413 (forward-char (1+ bytes))
1414 (setq bytes (nnimap-get-length))
1415 (delete-region (line-beginning-position) (line-end-position))
1416 (forward-char (1+ bytes))
1417 (delete-region (line-beginning-position) (line-end-position))))))
1419 (defun nnimap-dummy-active-number (group &optional server)
1422 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1424 (goto-char (point-min))
1425 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1426 (error "Invalid nnimap mail")
1427 (setq article (string-to-number (match-string 1))))
1429 (if (eq group-art 'junk)
1430 (list (cons 'junk 1))
1432 nnimap-incoming-split-list)))
1436 ;;; nnimap.el ends here