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 (defvoo nnimap-authenticator nil
74 "How nnimap authenticate itself to the server.
75 Possible choices are nil (use default methods) or `anonymous'.")
77 (defvoo nnimap-expunge t
78 "If non-nil, expunge articles after deleting them.
79 This is always done if the server supports UID EXPUNGE, but it's
80 not done by default on servers that doesn't support that command.")
82 (defvoo nnimap-streaming t
83 "If non-nil, try to use streaming commands with IMAP servers.
84 Switching this off will make nnimap slower, but it helps with
87 (defvoo nnimap-connection-alist nil)
89 (defvoo nnimap-current-infos nil)
91 (defvoo nnimap-fetch-partial-articles nil
92 "If non-nil, Gnus will fetch partial articles.
93 If t, nnimap will fetch only the first part. If a string, it
94 will fetch all parts that have types that match that string. A
95 likely value would be \"text/\" to automatically fetch all
98 (defvar nnimap-process nil)
100 (defvar nnimap-status-string "")
102 (defvar nnimap-split-download-body-default nil
103 "Internal variable with default value for `nnimap-split-download-body'.")
105 (defvar nnimap-keepalive-timer nil)
106 (defvar nnimap-process-buffers nil)
109 group process commands capabilities select-result newlinep server
110 last-command-time greeting)
112 (defvar nnimap-object nil)
114 (defvar nnimap-mark-alist
115 '((read "\\Seen" %Seen)
116 (tick "\\Flagged" %Flagged)
117 (reply "\\Answered" %Answered)
118 (expire "gnus-expire")
119 (dormant "gnus-dormant")
122 (download "gnus-download")
123 (forward "gnus-forward")))
125 (defun nnimap-buffer ()
126 (nnimap-find-process-buffer nntp-server-buffer))
128 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
129 (with-current-buffer nntp-server-buffer
131 (when (nnimap-possibly-change-group group server)
132 (with-current-buffer (nnimap-buffer)
134 (nnimap-wait-for-response
137 (nnimap-article-ranges (gnus-compress-sequence articles))
138 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
141 "BODY.PEEK[HEADER.FIELDS %s]"
142 "RFC822.HEADER.LINES %s")
143 (append '(Subject From Date Message-Id
144 References In-Reply-To Xref)
145 nnmail-extra-headers))))
147 (nnimap-transform-headers))
148 (insert-buffer-substring
149 (nnimap-find-process-buffer (current-buffer))))
152 (defun nnimap-transform-headers ()
153 (goto-char (point-min))
154 (let (article bytes lines size string)
157 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
158 (delete-region (point) (progn (forward-line 1) (point)))
161 (setq article (match-string 1))
162 ;; Unfold quoted {number} strings.
163 (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
164 (1+ (line-end-position)) t)
165 (setq size (string-to-number (match-string 1)))
166 (delete-region (+ (match-beginning 0) 2) (point))
167 (setq string (delete-region (point) (+ (point) size)))
168 (insert (format "%S" string)))
169 (setq bytes (nnimap-get-length)
173 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
178 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
179 (let ((structure (ignore-errors
180 (read (current-buffer)))))
181 (while (and (consp structure)
182 (not (stringp (car structure))))
183 (setq structure (car structure)))
184 (setq lines (nth 7 structure))))
185 (delete-region (line-beginning-position) (line-end-position))
186 (insert (format "211 %s Article retrieved." article))
189 (insert (format "Chars: %s\n" size)))
191 (insert (format "Lines: %s\n" lines)))
192 (re-search-forward "^\r$")
193 (delete-region (line-beginning-position) (line-end-position))
197 (defun nnimap-get-length ()
198 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
199 (string-to-number (match-string 1))))
201 (defun nnimap-article-ranges (ranges)
205 (number-to-string ranges))
206 ((numberp (cdr ranges))
207 (format "%d:%d" (car ranges) (cdr ranges)))
209 (dolist (elem ranges)
212 (format "%d:%d" (car elem) (cdr elem))
213 (number-to-string elem))
215 (mapconcat #'identity (nreverse result) ",")))))
217 (deffoo nnimap-open-server (server &optional defs)
218 (if (nnimap-server-opened server)
220 (unless (assq 'nnimap-address defs)
221 (setq defs (append defs (list (list 'nnimap-address server)))))
222 (nnoo-change-server 'nnimap server defs)
223 (or (nnimap-find-connection nntp-server-buffer)
224 (nnimap-open-connection nntp-server-buffer))))
226 (defun nnimap-make-process-buffer (buffer)
228 (generate-new-buffer (format "*nnimap %s %s %s*"
229 nnimap-address nnimap-server-port
230 (gnus-buffer-exists-p buffer)))
231 (mm-disable-multibyte)
232 (buffer-disable-undo)
234 (set (make-local-variable 'after-change-functions) nil)
235 (set (make-local-variable 'nnimap-object)
236 (make-nnimap :server (nnoo-current-server 'nnimap)))
237 (push (list buffer (current-buffer)) nnimap-connection-alist)
238 (push (current-buffer) nnimap-process-buffers)
241 (defun nnimap-open-shell-stream (name buffer host port)
242 (let ((process-connection-type nil))
243 (start-process name buffer shell-file-name
251 (defun nnimap-credentials (address ports &optional inhibit-create)
252 (let (port credentials)
253 ;; Request the credentials from all ports, but only query on the
254 ;; last port if all the previous ones have failed.
255 (while (and (null credentials)
256 (setq port (pop ports)))
258 (auth-source-user-or-password
259 '("login" "password") address port nil
265 (defun nnimap-keepalive ()
266 (let ((now (current-time)))
267 (dolist (buffer nnimap-process-buffers)
268 (when (buffer-name buffer)
269 (with-current-buffer buffer
270 (when (and nnimap-object
271 (nnimap-last-command-time nnimap-object)
275 (nnimap-last-command-time nnimap-object)))
276 ;; More than five minutes since the last command.
278 (nnimap-send-command "NOOP")))))))
280 (defun nnimap-open-connection (buffer)
281 (unless nnimap-keepalive-timer
282 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
285 (with-current-buffer (nnimap-make-process-buffer buffer)
286 (let* ((coding-system-for-read 'binary)
287 (coding-system-for-write 'binary)
291 ((eq nnimap-stream 'network)
293 "*nnimap*" (current-buffer) nnimap-address
295 (or nnimap-server-port
296 (if (netrc-find-service-number "imap")
300 ((eq nnimap-stream 'shell)
301 (nnimap-open-shell-stream
302 "*nnimap*" (current-buffer) nnimap-address
303 (setq port (or nnimap-server-port "imap")))
305 ((eq nnimap-stream 'starttls)
306 (starttls-open-stream
307 "*nnimap*" (current-buffer) nnimap-address
308 (setq port (or nnimap-server-port "imap")))
310 ((eq nnimap-stream 'ssl)
312 "*nnimap*" (current-buffer) nnimap-address
314 (or nnimap-server-port
315 (if (netrc-find-service-number "imaps")
318 '("143" "993" "imap" "imaps"))))
319 connection-result login-result credentials)
320 (setf (nnimap-process nnimap-object)
321 (get-buffer-process (current-buffer)))
322 (if (not (and (nnimap-process nnimap-object)
323 (memq (process-status (nnimap-process nnimap-object))
325 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
326 nnimap-address port nnimap-stream)
327 (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
328 (if (not (setq connection-result (nnimap-wait-for-connection)))
329 (nnheader-report 'nnimap
330 "%s" (buffer-substring
331 (point) (line-end-position)))
332 ;; Store the greeting (for debugging purposes).
333 (setf (nnimap-greeting nnimap-object)
334 (buffer-substring (line-beginning-position)
335 (line-end-position)))
336 ;; Store the capabilities.
337 (setf (nnimap-capabilities nnimap-object)
340 (nnimap-find-parameter
341 "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
342 (when (eq nnimap-stream 'starttls)
343 (nnimap-command "STARTTLS")
344 (starttls-negotiate (nnimap-process nnimap-object)))
345 (when nnimap-server-port
346 (push (format "%s" nnimap-server-port) ports))
347 (unless (equal connection-result "PREAUTH")
348 (if (not (setq credentials
349 (if (eq nnimap-authenticator 'anonymous)
351 (message-make-address))
353 ;; First look for the credentials based
354 ;; on the virtual server name.
356 (nnoo-current-server 'nnimap) ports t)
357 ;; Then look them up based on the
359 (nnimap-credentials nnimap-address ports)))))
360 (setq nnimap-object nil)
361 (setq login-result (nnimap-command "LOGIN %S %S"
364 (unless (car login-result)
365 ;; If the login failed, then forget the credentials
366 ;; that are now possibly cached.
367 (dolist (host (list (nnoo-current-server 'nnimap)
370 (dolist (element '("login" "password"))
371 (auth-source-forget-user-or-password
372 element host port))))
373 (delete-process (nnimap-process nnimap-object))
374 (setq nnimap-object nil))))
376 (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
377 (nnimap-command "ENABLE QRESYNC"))
380 (defun nnimap-find-parameter (parameter elems)
384 ((equal (car elem) parameter)
385 (setq result (cdr elem)))
386 ((and (equal (car elem) "OK")
388 (equal (caadr elem) parameter))
389 (setq result (cdr (cadr elem))))))
392 (deffoo nnimap-close-server (&optional server)
395 (deffoo nnimap-request-close ()
398 (deffoo nnimap-server-opened (&optional server)
399 (and (nnoo-current-server-p 'nnimap server)
401 (gnus-buffer-live-p nntp-server-buffer)
402 (nnimap-find-connection nntp-server-buffer)))
404 (deffoo nnimap-status-message (&optional server)
405 nnimap-status-string)
407 (deffoo nnimap-request-article (article &optional group server to-buffer)
408 (with-current-buffer nntp-server-buffer
409 (let ((result (nnimap-possibly-change-group group server))
411 (when (stringp article)
412 (setq article (nnimap-find-article-by-message-id group article)))
416 (with-current-buffer (nnimap-buffer)
418 (when nnimap-fetch-partial-articles
419 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
420 (goto-char (point-min))
421 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
422 (setq structure (ignore-errors (read (current-buffer)))
423 parts (nnimap-find-wanted-parts structure))))
425 (nnimap-get-partial-article article parts structure)
426 (nnimap-get-whole-article article))
427 (let ((buffer (current-buffer)))
428 (with-current-buffer (or to-buffer nntp-server-buffer)
430 (insert-buffer-substring buffer)
431 (nnheader-ms-strip-cr)
432 (cons group article)))))))))
434 (defun nnimap-get-whole-article (article)
438 "UID FETCH %d BODY.PEEK[]"
439 "UID FETCH %d RFC822.PEEK")
441 ;; Check that we really got an article.
442 (goto-char (point-min))
443 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
446 ;; Remove any data that may have arrived before the FETCH data.
449 (delete-region (point-min) (point)))
450 (let ((bytes (nnimap-get-length)))
451 (delete-region (line-beginning-position)
452 (progn (forward-line 1) (point)))
453 (goto-char (+ (point) bytes))
454 (delete-region (point) (point-max)))
457 (defun nnimap-ver4-p ()
458 (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
460 (defun nnimap-get-partial-article (article parts structure)
463 "UID FETCH %d (%s %s)"
469 (mapconcat (lambda (part)
470 (format "BODY.PEEK[%s]" part))
472 (mapconcat (lambda (part)
473 (format "RFC822.PEEK[%s]" part))
476 (nnimap-convert-partial-article structure))))
478 (defun nnimap-convert-partial-article (structure)
479 ;; First just skip past the headers.
480 (goto-char (point-min))
481 (let ((bytes (nnimap-get-length))
483 ;; Delete "FETCH" line.
484 (delete-region (line-beginning-position)
485 (progn (forward-line 1) (point)))
486 (goto-char (+ (point) bytes))
487 ;; Collect all the body parts.
488 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
489 (setq id (match-string 1)
490 bytes (nnimap-get-length))
492 (delete-region (point) (progn (forward-line 1) (point)))
493 (push (list id (buffer-substring (point) (+ (point) bytes)))
495 (delete-region (point) (+ (point) bytes)))
496 ;; Delete trailing junk.
497 (delete-region (point) (point-max))
498 ;; Now insert all the parts again where they fit in the structure.
499 (nnimap-insert-partial-structure structure parts)
502 (defun nnimap-insert-partial-structure (structure parts &optional subp)
504 (let ((bstruc structure))
505 (while (consp (car bstruc))
507 (setq type (car bstruc))
508 (setq bstruc (car (cdr bstruc)))
509 (when (and (stringp (car bstruc))
510 (string= (downcase (car bstruc)) "boundary"))
511 (setq boundary (cadr bstruc))))
513 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
514 (downcase type) boundary)))
515 (while (not (stringp (car structure)))
516 (insert "\n--" boundary "\n")
517 (if (consp (caar structure))
518 (nnimap-insert-partial-structure (pop structure) parts t)
519 (let ((bit (pop structure)))
520 (insert (format "Content-type: %s/%s"
521 (downcase (nth 0 bit))
522 (downcase (nth 1 bit))))
523 (if (member "CHARSET" (nth 2 bit))
525 "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
527 (insert (format "Content-transfer-encoding: %s\n"
530 (when (assoc (nth 9 bit) parts)
531 (insert (cadr (assoc (nth 9 bit) parts)))))))
532 (insert "\n--" boundary "--\n")))
534 (defun nnimap-find-wanted-parts (structure)
535 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
537 (defun nnimap-find-wanted-parts-1 (structure prefix)
540 (while (consp (car structure))
541 (let ((sub (pop structure)))
542 (if (consp (car sub))
543 (push (nnimap-find-wanted-parts-1
544 sub (if (string= prefix "")
545 (number-to-string num)
546 (format "%s.%s" prefix num)))
548 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
549 (id (if (string= prefix "")
550 (number-to-string num)
551 (format "%s.%s" prefix num))))
552 (setcar (nthcdr 9 sub) id)
553 (when (if (eq nnimap-fetch-partial-articles t)
555 (string-match nnimap-fetch-partial-articles type))
560 (deffoo nnimap-request-group (group &optional server dont-check info)
561 (let ((result (nnimap-possibly-change-group group server))
562 articles active marks high low)
563 (with-current-buffer nntp-server-buffer
566 (setq active (nth 2 (assoc group nnimap-current-infos))))
567 (insert (format "211 %d %d %d %S\n"
568 (- (cdr active) (car active))
572 (with-current-buffer (nnimap-buffer)
574 (let ((group-sequence
575 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
577 (nnimap-send-command "UID FETCH 1:* FLAGS")))
578 (nnimap-wait-for-response flag-sequence)
580 (nnimap-flags-to-marks
582 (list (list group-sequence flag-sequence 1 group)))))
584 (nnimap-update-infos marks (list info)))
585 (goto-char (point-max))
586 (let ((uidnext (nth 5 (car marks))))
587 (setq high (if uidnext
590 low (or (nth 4 (car marks)) uidnext)))))
594 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
597 (deffoo nnimap-request-create-group (group &optional server args)
598 (when (nnimap-possibly-change-group nil server)
599 (with-current-buffer (nnimap-buffer)
600 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
602 (deffoo nnimap-request-delete-group (group &optional force server)
603 (when (nnimap-possibly-change-group nil server)
604 (with-current-buffer (nnimap-buffer)
605 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
607 (deffoo nnimap-request-expunge-group (group &optional server)
608 (when (nnimap-possibly-change-group group server)
609 (with-current-buffer (nnimap-buffer)
610 (car (nnimap-command "EXPUNGE")))))
612 (defun nnimap-get-flags (spec)
615 (with-current-buffer (nnimap-buffer)
617 (nnimap-wait-for-response (nnimap-send-command
618 "UID FETCH %s FLAGS" spec))
619 (goto-char (point-min))
620 (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
621 (setq elems (nnimap-parse-line (match-string 1)))
622 (push (cons (string-to-number (cadr (member "UID" elems)))
623 (cadr (member "FLAGS" elems)))
625 (nreverse articles)))
627 (deffoo nnimap-close-group (group &optional server)
630 (deffoo nnimap-request-move-article (article group server accept-form
631 &optional last internal-move-group)
633 (when (nnimap-request-article article group server (current-buffer))
634 ;; If the move is internal (on the same server), just do it the easy
636 (let ((message-id (message-field-value "message-id")))
637 (if internal-move-group
639 (with-current-buffer (nnimap-buffer)
640 (nnimap-command "UID COPY %d %S"
642 (utf7-encode internal-move-group t)))))
644 (nnimap-delete-article article)
645 (cons internal-move-group
646 (nnimap-find-article-by-message-id
647 internal-move-group message-id))))
648 ;; Move the article to a different method.
649 (let ((result (eval accept-form)))
651 (nnimap-delete-article article)
654 (deffoo nnimap-request-expire-articles (articles group &optional server force)
658 ((not (nnimap-possibly-change-group group server))
661 (eq nnmail-expiry-target 'delete))
662 (unless (nnimap-delete-article (gnus-compress-sequence articles))
663 (message "Article marked for deletion, but not expunged."))
666 (let ((deletable-articles
668 (eq nnmail-expiry-wait 'immediate))
670 (gnus-sorted-intersection
672 (nnimap-find-expired-articles group)))))
673 (if (null deletable-articles)
675 (if (eq nnmail-expiry-target 'delete)
676 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
677 (setq deletable-articles
678 (nnimap-process-expiry-targets
679 deletable-articles group server)))
680 ;; Return the articles we didn't delete.
681 (gnus-sorted-complement articles deletable-articles))))))
683 (defun nnimap-process-expiry-targets (articles group server)
684 (let ((deleted-articles nil))
685 (dolist (article articles)
686 (let ((target nnmail-expiry-target))
688 (when (nnimap-request-article article group server (current-buffer))
689 (message "Expiring article %s:%d" group article)
690 (when (functionp target)
691 (setq target (funcall target group)))
693 (not (eq target 'delete)))
694 (if (or (gnus-request-group target t)
695 (gnus-request-create-group target))
696 (nnmail-expiry-target-group target group)
699 (push article deleted-articles))))))
700 ;; Change back to the current group again.
701 (nnimap-possibly-change-group group server)
702 (setq deleted-articles (nreverse deleted-articles))
703 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
706 (defun nnimap-find-expired-articles (group)
707 (let ((cutoff (nnmail-expired-article-p group nil nil)))
708 (with-current-buffer (nnimap-buffer)
711 "UID SEARCH SENTBEFORE %s"
715 (car (rassoc (nth 4 (decode-time cutoff))
716 parse-time-months))))
719 (delete 0 (mapcar #'string-to-number
720 (cdr (assoc "SEARCH" (cdr result))))))))))
723 (defun nnimap-find-article-by-message-id (group message-id)
724 (when (nnimap-possibly-change-group group nil)
725 (with-current-buffer (nnimap-buffer)
727 (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
730 ;; Select the last instance of the message in the group.
732 (car (last (assoc "SEARCH" (cdr result)))))
733 (string-to-number article)))))))
735 (defun nnimap-delete-article (articles)
736 (with-current-buffer (nnimap-buffer)
737 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
738 (nnimap-article-ranges articles))
740 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
741 (nnimap-command "UID EXPUNGE %s"
742 (nnimap-article-ranges articles))
745 (nnimap-command "EXPUNGE")
747 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
748 "server doesn't support UIDPLUS, so we won't "
749 "delete this article now"))))))
751 (deffoo nnimap-request-scan (&optional group server)
752 (when (and (nnimap-possibly-change-group nil server)
754 nnimap-split-methods)
755 (message "nnimap %s splitting mail..." server)
756 (nnimap-split-incoming-mail)))
758 (defun nnimap-marks-to-flags (marks)
761 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
765 (deffoo nnimap-request-set-mark (group actions &optional server)
766 (when (nnimap-possibly-change-group group server)
768 (with-current-buffer (nnimap-buffer)
770 ;; Just send all the STORE commands without waiting for
771 ;; response. If they're successful, they're successful.
772 (dolist (action actions)
773 (destructuring-bind (range action marks) action
774 (let ((flags (nnimap-marks-to-flags marks)))
776 (setq sequence (nnimap-send-command
777 "UID STORE %s %sFLAGS.SILENT (%s)"
778 (nnimap-article-ranges range)
782 (mapconcat #'identity flags " ")))))))
783 ;; Wait for the last command to complete to avoid later
784 ;; syncronisation problems with the stream.
786 (nnimap-wait-for-response sequence))))))
788 (deffoo nnimap-request-accept-article (group &optional server last)
789 (when (nnimap-possibly-change-group nil server)
790 (nnmail-check-syntax)
792 (let ((message (buffer-string))
793 (message-id (message-field-value "message-id"))
795 (with-current-buffer (nnimap-buffer)
796 (setq sequence (nnimap-send-command
797 "APPEND %S {%d}" (utf7-encode group t)
799 (process-send-string (get-buffer-process (current-buffer)) message)
800 (process-send-string (get-buffer-process (current-buffer))
801 (if (nnimap-newlinep nnimap-object)
804 (let ((result (nnimap-get-response sequence)))
805 (if (not (car result))
807 (message "%s" (nnheader-get-report-string 'nnimap))
810 (nnimap-find-article-by-message-id group message-id))))))))
812 (defun nnimap-add-cr ()
813 (goto-char (point-min))
814 (while (re-search-forward "\r?\n" nil t)
815 (replace-match "\r\n" t t)))
817 (defun nnimap-get-groups ()
818 (let ((result (nnimap-command "LIST \"\" \"*\""))
821 (dolist (line (cdr result))
822 (when (and (equal (car line) "LIST")
823 (not (and (caadr line)
824 (string-match "noselect" (caadr line)))))
825 (push (car (last line)) groups)))
828 (deffoo nnimap-request-list (&optional server)
829 (nnimap-possibly-change-group nil server)
830 (with-current-buffer nntp-server-buffer
833 (with-current-buffer (nnimap-buffer)
834 (nnimap-get-groups)))
837 (with-current-buffer (nnimap-buffer)
838 (setf (nnimap-group nnimap-object) nil)
839 (dolist (group groups)
840 (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
843 (nnimap-wait-for-response (caar sequences))
845 (nnimap-get-responses (mapcar #'car sequences))))
846 (dolist (response responses)
847 (let* ((sequence (car response))
848 (response (cadr response))
849 (group (cadr (assoc sequence sequences))))
851 (equal (caar response) "OK"))
852 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
854 (dolist (elem response)
855 (when (equal (cadr elem) "EXISTS")
856 (setq exists (string-to-number (car elem)))))
858 (setq highest (1- (string-to-number (car uidnext)))))
861 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
864 (insert (format "%S %d %d y\n"
865 (utf7-decode group t) highest (1+ highest))))
867 ;; Return the widest possible range.
868 (insert (format "%S %d 1 y\n" (utf7-decode group t)
869 (or highest exists)))))))))
872 (deffoo nnimap-retrieve-group-data-early (server infos)
873 (when (nnimap-possibly-change-group nil server)
874 (with-current-buffer (nnimap-buffer)
875 ;; QRESYNC handling isn't implemented.
876 (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
877 marks groups sequences)
878 ;; Go through the infos and gather the data needed to know
879 ;; what and how to request the data.
881 (setq marks (gnus-info-marks info))
882 (push (list (gnus-group-real-name (gnus-info-group info))
883 (cdr (assq 'active marks))
884 (cdr (assq 'uid marks)))
886 ;; Then request the data.
888 (setf (nnimap-group nnimap-object) nil)
889 (dolist (elem groups)
894 (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
903 ;; Fetch the last 100 flags.
904 (max 1 (- (cdr (nth 1 elem)) 100))
906 (push (list (nnimap-send-command "EXAMINE %S" (car elem))
907 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
911 ;; Some servers apparently can't have many outstanding
912 ;; commands, so throttle them.
913 (when (and (not nnimap-streaming)
915 (nnimap-wait-for-response (caar sequences))))
918 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
920 (nnimap-possibly-change-group nil server))
921 (with-current-buffer (nnimap-buffer)
922 ;; Wait for the final data to trickle in.
923 (when (nnimap-wait-for-response (cadar sequences))
924 ;; Now we should have all the data we need, no matter whether
925 ;; we're QRESYNCING, fetching all the flags from scratch, or
926 ;; just fetching the last 100 flags per group.
927 (nnimap-update-infos (nnimap-flags-to-marks
929 (nreverse sequences)))
931 ;; Finally, just return something resembling an active file in
932 ;; the nntp buffer, so that the agent can save the info, too.
933 (with-current-buffer nntp-server-buffer
936 (let* ((group (gnus-info-group info))
937 (active (gnus-active group)))
939 (insert (format "%S %d %d y\n"
940 (gnus-group-real-name group)
942 (car active)))))))))))
944 (defun nnimap-update-infos (flags infos)
946 (let ((group (gnus-group-real-name (gnus-info-group info))))
947 (nnimap-update-info info (cdr (assoc group flags))))))
949 (defun nnimap-update-info (info marks)
951 (destructuring-bind (existing flags high low uidnext start-article
952 permanent-flags) marks
953 (let ((group (gnus-info-group info))
954 (completep (and start-article
955 (= start-article 1))))
957 (setq high (1- uidnext)))
958 ;; First set the active ranges based on high/low.
960 (not (gnus-active group)))
961 (gnus-set-active group
966 ;; No articles in this group.
967 (cons uidnext (1- uidnext)))
969 (cons start-article (1- start-article)))
971 ;; No articles and no uidnext.
975 (cons (car (gnus-active group))
976 (or high (1- uidnext)))))
977 (when (and (not high)
979 (setq high (1- uidnext)))
980 ;; Then update the list of read articles.
982 (gnus-compress-sequence
986 (cdr (assoc '%Seen flags)))
987 (cdr (assoc '%Flagged flags)))))
988 (read (gnus-range-difference
989 (cons start-article high) unread)))
990 (when (> start-article 1)
993 (if (> start-article 1)
994 (gnus-sorted-range-intersection
995 (cons 1 (1- start-article))
996 (gnus-info-read info))
997 (gnus-info-read info))
999 (gnus-info-set-read info read)
1000 ;; Update the marks.
1001 (setq marks (gnus-info-marks info))
1002 ;; Note the active level for the next run-through.
1003 (let ((active (assq 'active marks)))
1005 (setcdr active (gnus-active group))
1006 (push (cons 'active (gnus-active group)) marks)))
1007 (dolist (type (cdr nnimap-mark-alist))
1008 (let ((old-marks (assoc (car type) marks))
1010 (gnus-compress-sequence
1011 (cdr (or (assoc (caddr type) flags) ; %Flagged
1012 (assoc (intern (cadr type) obarray) flags)
1013 (assoc (cadr type) flags)))))) ; "\Flagged"
1014 (setq marks (delq old-marks marks))
1016 (when (and old-marks
1017 (> start-article 1))
1018 (setq old-marks (gnus-range-difference
1020 (cons start-article high)))
1021 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1023 (push (cons (car type) new-marks) marks)))
1024 (gnus-info-set-marks info marks t)
1025 (nnimap-store-info info (gnus-active group))))))))
1027 (defun nnimap-store-info (info active)
1028 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1029 (entry (assoc group nnimap-current-infos)))
1031 (setcdr entry (list info active))
1032 (push (list group info active) nnimap-current-infos))))
1034 (defun nnimap-flags-to-marks (groups)
1035 (let (data group totalp uidnext articles start-article mark permanent-flags)
1036 (dolist (elem groups)
1037 (setq group (car elem)
1038 uidnext (nth 1 elem)
1039 start-article (nth 2 elem)
1040 permanent-flags (nth 3 elem)
1041 articles (nthcdr 4 elem))
1042 (let ((high (caar articles))
1044 (dolist (article articles)
1045 (setq low (car article))
1046 (push (car article) existing)
1047 (dolist (flag (cdr article))
1048 (setq mark (assoc flag marks))
1050 (push (list flag (car article)) marks)
1051 (setcdr mark (cons (car article) (cdr mark))))))
1052 (push (list group existing marks high low uidnext start-article
1057 (defun nnimap-parse-flags (sequences)
1058 (goto-char (point-min))
1059 ;; Change \Delete etc to %Delete, so that the reader can read it.
1060 (subst-char-in-region (point-min) (point-max)
1062 (let (start end articles groups uidnext elems permanent-flags)
1063 (dolist (elem sequences)
1064 (destructuring-bind (group-sequence flag-sequence totalp group) elem
1065 (setq start (point))
1066 ;; The EXAMINE was successful.
1067 (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1072 (setq permanent-flags
1073 (and (search-forward "PERMANENTFLAGS "
1074 (or end (point-min)) t)
1075 (read (current-buffer))))
1078 (and (search-forward "UIDNEXT "
1079 (or end (point-min)) t)
1080 (read (current-buffer))))
1083 ;; The UID FETCH FLAGS was successful.
1084 (search-forward (format "\n%d OK " flag-sequence) nil t))
1085 (setq start (point))
1087 (while (search-forward " FETCH " start t)
1088 (setq elems (read (current-buffer)))
1089 (push (cons (cadr (memq 'UID elems))
1090 (cadr (memq 'FLAGS elems)))
1092 (push (nconc (list group uidnext totalp permanent-flags) articles)
1094 (setq articles nil))))
1097 (defun nnimap-find-process-buffer (buffer)
1098 (cadr (assoc buffer nnimap-connection-alist)))
1100 (deffoo nnimap-request-post (&optional server)
1101 (setq nnimap-status-string "Read-only server")
1104 (defun nnimap-possibly-change-group (group server)
1105 (let ((open-result t))
1107 (not (nnimap-server-opened server)))
1108 (setq open-result (nnimap-open-server server)))
1115 (with-current-buffer (nnimap-buffer)
1116 (if (equal group (nnimap-group nnimap-object))
1118 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1120 (setf (nnimap-group nnimap-object) group
1121 (nnimap-select-result nnimap-object) result)
1124 (defun nnimap-find-connection (buffer)
1125 "Find the connection delivering to BUFFER."
1126 (let ((entry (assoc buffer nnimap-connection-alist)))
1128 (if (and (buffer-name (cadr entry))
1129 (get-buffer-process (cadr entry))
1130 (memq (process-status (get-buffer-process (cadr entry)))
1132 (get-buffer-process (cadr entry))
1133 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1136 (defvar nnimap-sequence 0)
1138 (defun nnimap-send-command (&rest args)
1139 (process-send-string
1140 (get-buffer-process (current-buffer))
1143 (incf nnimap-sequence)
1144 (apply #'format args)
1145 (if (nnimap-newlinep nnimap-object)
1150 (defun nnimap-log-command (command)
1151 (with-current-buffer (get-buffer-create "*imap log*")
1152 (goto-char (point-max))
1153 (insert (format-time-string "%H:%M:%S") " " command))
1156 (defun nnimap-command (&rest args)
1158 (setf (nnimap-last-command-time nnimap-object) (current-time))
1159 (let* ((sequence (apply #'nnimap-send-command args))
1160 (response (nnimap-get-response sequence)))
1161 (if (equal (caar response) "OK")
1163 (nnheader-report 'nnimap "%s"
1164 (mapconcat (lambda (a)
1166 (car response) " "))
1169 (defun nnimap-get-response (sequence)
1170 (nnimap-wait-for-response sequence)
1171 (nnimap-parse-response))
1173 (defun nnimap-wait-for-connection ()
1174 (let ((process (get-buffer-process (current-buffer))))
1175 (goto-char (point-min))
1176 (while (and (memq (process-status process)
1178 (not (re-search-forward "^\\* .*\n" nil t)))
1179 (nnheader-accept-process-output process)
1180 (goto-char (point-min)))
1182 (and (looking-at "\\* \\([A-Z0-9]+\\)")
1185 (defun nnimap-wait-for-response (sequence &optional messagep)
1186 (let ((process (get-buffer-process (current-buffer)))
1188 (goto-char (point-max))
1189 (while (and (setq openp (memq (process-status process)
1191 (not (re-search-backward
1192 (format "^%d .*\n" sequence)
1193 (if nnimap-streaming
1194 (max (point-min) (- (point) 500))
1198 (message "Read %dKB" (/ (buffer-size) 1000)))
1199 (nnheader-accept-process-output process)
1200 (goto-char (point-max)))
1203 (defun nnimap-parse-response ()
1204 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1206 (dolist (line lines)
1207 (push (cdr (nnimap-parse-line line)) result))
1208 ;; Return the OK/error code first, and then all the "continuation
1209 ;; lines" afterwards.
1211 (nreverse result))))
1213 ;; Parse an IMAP response line lightly. They look like
1214 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1215 ;; the lines into a list of strings and lists of string.
1216 (defun nnimap-parse-line (line)
1220 (goto-char (point-min))
1222 (if (eql (setq char (following-char)) ? )
1227 (split-string (buffer-substring
1229 (1- (search-forward "]" (line-end-position) 'move)))))
1231 (split-string (buffer-substring
1233 (1- (search-forward ")" (line-end-position) 'move)))))
1238 (1- (or (search-forward "\"" (line-end-position) 'move)
1241 (buffer-substring (point) (if (search-forward " " nil t)
1243 (goto-char (point-max))))))
1245 (nreverse result))))
1247 (defun nnimap-last-response-string ()
1250 (let ((end (point)))
1254 (while (and (not (bobp))
1255 (eql (following-char) ?*))
1257 (unless (eql (following-char) ?*)
1259 (buffer-substring (point) end))))
1261 (defun nnimap-get-responses (sequences)
1263 (dolist (sequence sequences)
1264 (goto-char (point-min))
1265 (when (re-search-forward (format "^%d " sequence) nil t)
1266 (push (list sequence (nnimap-parse-response))
1270 (defvar nnimap-incoming-split-list nil)
1272 (defun nnimap-fetch-inbox (articles)
1274 (nnimap-wait-for-response
1275 (nnimap-send-command
1277 (nnimap-article-ranges articles)
1278 (format "(UID %s%s)"
1281 "BODY.PEEK[HEADER] BODY.PEEK"
1283 (if nnimap-split-download-body-default
1288 (defun nnimap-split-incoming-mail ()
1289 (with-current-buffer (nnimap-buffer)
1290 (let ((nnimap-incoming-split-list nil)
1291 (nnmail-split-methods nnimap-split-methods)
1292 (nnmail-inhibit-default-split-group t)
1293 (groups (nnimap-get-groups))
1296 (nnimap-command "SELECT %S" nnimap-inbox)
1297 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1299 (nnimap-fetch-inbox new-articles)
1300 (nnimap-transform-split-mail)
1301 (nnheader-ms-strip-cr)
1303 (nnmail-split-incoming (current-buffer)
1304 #'nnimap-save-mail-spec
1306 #'nnimap-dummy-active-number
1307 #'nnimap-save-mail-spec)
1308 (when nnimap-incoming-split-list
1309 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1310 sequences junk-articles)
1311 ;; Create any groups that doesn't already exist on the
1313 (dolist (spec specs)
1314 (when (and (not (member (car spec) groups))
1315 (not (eq (car spec) 'junk)))
1316 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1317 ;; Then copy over all the messages.
1319 (dolist (spec specs)
1320 (let ((group (car spec))
1321 (ranges (cdr spec)))
1322 (if (eq group 'junk)
1323 (setq junk-articles ranges)
1324 (push (list (nnimap-send-command
1326 (nnimap-article-ranges ranges)
1327 (utf7-encode group t))
1330 ;; Wait for the last COPY response...
1332 (nnimap-wait-for-response (caar sequences))
1333 ;; And then mark the successful copy actions as deleted,
1334 ;; and possibly expunge them.
1335 (nnimap-mark-and-expunge-incoming
1336 (nnimap-parse-copied-articles sequences)))
1337 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1339 (defun nnimap-mark-and-expunge-incoming (range)
1341 (setq range (nnimap-article-ranges range))
1344 (nnimap-send-command
1345 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1347 ;; If the server supports it, we now delete the message we have
1348 ;; just copied over.
1349 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1350 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1351 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1352 ;; user has configured it.
1354 (setq sequence (nnimap-send-command "EXPUNGE"))))
1355 (nnimap-wait-for-response sequence))))
1357 (defun nnimap-parse-copied-articles (sequences)
1358 (let (sequence copied range)
1359 (goto-char (point-min))
1360 (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1361 (setq sequence (string-to-number (match-string 1)))
1362 (when (setq range (cadr (assq sequence sequences)))
1363 (push (gnus-uncompress-range range) copied)))
1364 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1366 (defun nnimap-new-articles (flags)
1368 (dolist (elem flags)
1369 (when (or (null (cdr elem))
1370 (and (not (memq '%Deleted (cdr elem)))
1371 (not (memq '%Seen (cdr elem)))))
1372 (push (car elem) new)))
1373 (gnus-compress-sequence (nreverse new))))
1375 (defun nnimap-make-split-specs (list)
1379 (destructuring-bind (article spec) elem
1380 (dolist (group (delete nil (mapcar #'car spec)))
1381 (unless (setq entry (assoc group specs))
1382 (push (setq entry (list group)) specs))
1383 (setcdr entry (cons article (cdr entry))))))
1384 (dolist (entry specs)
1385 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1388 (defun nnimap-transform-split-mail ()
1389 (goto-char (point-min))
1390 (let (article bytes)
1393 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1394 (delete-region (point) (progn (forward-line 1) (point)))
1397 (setq article (match-string 1)
1398 bytes (nnimap-get-length))
1399 (delete-region (line-beginning-position) (line-end-position))
1400 ;; Insert MMDF separator, and a way to remember what this
1402 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1403 (forward-char (1+ bytes))
1404 (setq bytes (nnimap-get-length))
1405 (delete-region (line-beginning-position) (line-end-position))
1406 (forward-char (1+ bytes))
1407 (delete-region (line-beginning-position) (line-end-position))))))
1409 (defun nnimap-dummy-active-number (group &optional server)
1412 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1414 (goto-char (point-min))
1415 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1416 (error "Invalid nnimap mail")
1417 (setq article (string-to-number (match-string 1))))
1419 (if (eq group-art 'junk)
1420 (list (cons 'junk 1))
1422 nnimap-incoming-split-list)))
1426 ;;; nnimap.el ends here