Merge from origin/emacs-24
[emacs.git] / lisp / gnus / nnimap.el
blob8e81abcf9c012a53c6b47e26baf239f400fa250c
1 ;;; nnimap.el --- IMAP interface for Gnus
3 ;; Copyright (C) 2010-2015 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/>.
23 ;;; Commentary:
25 ;; nnimap interfaces Gnus with IMAP servers.
27 ;;; Code:
29 (eval-and-compile
30 (require 'nnheader)
31 ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
32 ;; `make-network-stream'.
33 (unless (fboundp 'open-protocol-stream)
34 (require 'proto-stream)))
36 (eval-when-compile
37 (require 'cl))
39 (require 'nnheader)
40 (require 'gnus-util)
41 (require 'gnus)
42 (require 'nnoo)
43 (require 'netrc)
44 (require 'utf7)
45 (require 'tls)
46 (require 'parse-time)
47 (require 'nnmail)
49 (autoload 'auth-source-forget+ "auth-source")
50 (autoload 'auth-source-search "auth-source")
52 (nnoo-declare nnimap)
54 (defvoo nnimap-address nil
55 "The address of the IMAP server.")
57 (defvoo nnimap-user nil
58 "Username to use for authentication to the IMAP server.")
60 (defvoo nnimap-server-port nil
61 "The IMAP port used.
62 If nnimap-stream is `ssl', this will default to `imaps'. If not,
63 it will default to `imap'.")
65 (defvoo nnimap-stream 'undecided
66 "How nnimap talks to the IMAP server.
67 The value should be either `undecided', `ssl' or `tls',
68 `network', `starttls', `plain', or `shell'.
70 If the value is `undecided', nnimap tries `ssl' first, then falls
71 back on `network'.")
73 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
74 (if (listp imap-shell-program)
75 (car imap-shell-program)
76 imap-shell-program)
77 "ssh %s imapd"))
79 (defvoo nnimap-inbox nil
80 "The mail box where incoming mail arrives and should be split out of.
81 This can be a string or a list of strings
82 For example, \"INBOX\" or (\"INBOX\" \"SENT\").")
84 (defvoo nnimap-split-methods nil
85 "How mail is split.
86 Uses the same syntax as `nnmail-split-methods'.")
88 (defvoo nnimap-split-fancy nil
89 "Uses the same syntax as `nnmail-split-fancy'.")
91 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
92 "Articles with the flags in the list will not be considered when splitting.")
94 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'."
95 "Emacs 24.1")
97 (defvoo nnimap-authenticator nil
98 "How nnimap authenticate itself to the server.
99 Possible choices are nil (use default methods), `anonymous',
100 `login', `plain' and `cram-md5'.")
102 (defvoo nnimap-expunge t
103 "If non-nil, expunge articles after deleting them.
104 This is always done if the server supports UID EXPUNGE, but it's
105 not done by default on servers that doesn't support that command.")
107 (defvoo nnimap-streaming t
108 "If non-nil, try to use streaming commands with IMAP servers.
109 Switching this off will make nnimap slower, but it helps with
110 some servers.")
112 (defvoo nnimap-connection-alist nil)
114 (defvoo nnimap-current-infos nil)
116 (defvoo nnimap-fetch-partial-articles nil
117 "If non-nil, Gnus will fetch partial articles.
118 If t, Gnus will fetch only the first part. If a string, it
119 will fetch all parts that have types that match that string. A
120 likely value would be \"text/\" to automatically fetch all
121 textual parts.")
123 (defgroup nnimap nil
124 "IMAP for Gnus."
125 :group 'gnus)
127 (defcustom nnimap-request-articles-find-limit nil
128 "Limit the number of articles to look for after moving an article."
129 :type '(choice (const nil) integer)
130 :version "24.4"
131 :group 'nnimap)
133 (defvar nnimap-process nil)
135 (defvar nnimap-status-string "")
137 (defvar nnimap-split-download-body-default nil
138 "Internal variable with default value for `nnimap-split-download-body'.")
140 (defvar nnimap-keepalive-timer nil)
141 (defvar nnimap-process-buffers nil)
143 (defstruct nnimap
144 group process commands capabilities select-result newlinep server
145 last-command-time greeting examined stream-type initial-resync)
147 (defvar nnimap-object nil)
149 (defvar nnimap-mark-alist
150 '((read "\\Seen" %Seen)
151 (tick "\\Flagged" %Flagged)
152 (reply "\\Answered" %Answered)
153 (expire "gnus-expire")
154 (dormant "gnus-dormant")
155 (score "gnus-score")
156 (save "gnus-save")
157 (download "gnus-download")
158 (forward "gnus-forward")))
160 (defvar nnimap-quirks
161 '(("QRESYNC" "Zimbra" "QRESYNC ")))
163 (defvar nnimap-inhibit-logging nil)
165 (defun nnimap-buffer ()
166 (nnimap-find-process-buffer nntp-server-buffer))
168 (defun nnimap-header-parameters ()
169 (let (params)
170 (push "UID" params)
171 (push "RFC822.SIZE" params)
172 (when (nnimap-capability "X-GM-EXT-1")
173 (push "X-GM-LABELS" params))
174 (push "BODYSTRUCTURE" params)
175 (push (format
176 (if (nnimap-ver4-p)
177 "BODY.PEEK[HEADER.FIELDS %s]"
178 "RFC822.HEADER.LINES %s")
179 (append '(Subject From Date Message-Id
180 References In-Reply-To Xref)
181 nnmail-extra-headers))
182 params)
183 (format "%s" (nreverse params))))
185 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
186 (when group
187 (setq group (nnimap-decode-gnus-group group)))
188 (with-current-buffer nntp-server-buffer
189 (erase-buffer)
190 (when (nnimap-change-group group server)
191 (with-current-buffer (nnimap-buffer)
192 (erase-buffer)
193 (nnimap-wait-for-response
194 (nnimap-send-command
195 "UID FETCH %s %s"
196 (nnimap-article-ranges (gnus-compress-sequence articles))
197 (nnimap-header-parameters))
199 (nnimap-transform-headers)
200 (nnheader-remove-cr-followed-by-lf))
201 (insert-buffer-substring
202 (nnimap-find-process-buffer (current-buffer))))
203 'headers))
205 (defun nnimap-transform-headers ()
206 (goto-char (point-min))
207 (let (article lines size string labels)
208 (block nil
209 (while (not (eobp))
210 (while (not (looking-at "\\* [0-9]+ FETCH"))
211 (delete-region (point) (progn (forward-line 1) (point)))
212 (when (eobp)
213 (return)))
214 (goto-char (match-end 0))
215 ;; Unfold quoted {number} strings.
216 (while (re-search-forward
217 "[^]][ (]{\\([0-9]+\\)}\r?\n"
218 (save-excursion
219 ;; Start of the header section.
220 (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
221 ;; Start of the next FETCH.
222 (re-search-forward "\\* [0-9]+ FETCH" nil t)
223 (point-max)))
225 (setq size (string-to-number (match-string 1)))
226 (delete-region (+ (match-beginning 0) 2) (point))
227 (setq string (buffer-substring (point) (+ (point) size)))
228 (delete-region (point) (+ (point) size))
229 (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
230 (beginning-of-line)
231 (setq article
232 (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
234 (match-string 1)))
235 (setq lines nil)
236 (setq size
237 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
238 (line-end-position)
240 (match-string 1)))
241 (beginning-of-line)
242 (when (search-forward "X-GM-LABELS" (line-end-position) t)
243 (setq labels (ignore-errors (read (current-buffer)))))
244 (beginning-of-line)
245 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
246 (let ((structure (ignore-errors
247 (read (current-buffer)))))
248 (while (and (consp structure)
249 (not (atom (car structure))))
250 (setq structure (car structure)))
251 (setq lines (if (and
252 (stringp (car structure))
253 (equal (upcase (nth 0 structure)) "MESSAGE")
254 (equal (upcase (nth 1 structure)) "RFC822"))
255 (nth 9 structure)
256 (nth 7 structure)))))
257 (delete-region (line-beginning-position) (line-end-position))
258 (insert (format "211 %s Article retrieved." article))
259 (forward-line 1)
260 (when size
261 (insert (format "Chars: %s\n" size)))
262 (when lines
263 (insert (format "Lines: %s\n" lines)))
264 (when labels
265 (insert (format "X-GM-LABELS: %s\n" labels)))
266 ;; Most servers have a blank line after the headers, but
267 ;; Davmail doesn't.
268 (unless (re-search-forward "^\r$\\|^)\r?$" nil t)
269 (goto-char (point-max)))
270 (delete-region (line-beginning-position) (line-end-position))
271 (insert ".")
272 (forward-line 1)))))
274 (defun nnimap-unfold-quoted-lines ()
275 ;; Unfold quoted {number} strings.
276 (let (size string)
277 (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
278 (setq size (string-to-number (match-string 1)))
279 (delete-region (1+ (match-beginning 0)) (point))
280 (setq string (buffer-substring (point) (+ (point) size)))
281 (delete-region (point) (+ (point) size))
282 (insert (format "%S" string)))))
284 (defun nnimap-get-length ()
285 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
286 (string-to-number (match-string 1))))
288 (defun nnimap-article-ranges (ranges)
289 (let (result)
290 (cond
291 ((numberp ranges)
292 (number-to-string ranges))
293 ((numberp (cdr ranges))
294 (format "%d:%d" (car ranges) (cdr ranges)))
296 (dolist (elem ranges)
297 (push
298 (if (consp elem)
299 (format "%d:%d" (car elem) (cdr elem))
300 (number-to-string elem))
301 result))
302 (mapconcat #'identity (nreverse result) ",")))))
304 (deffoo nnimap-open-server (server &optional defs no-reconnect)
305 (if (nnimap-server-opened server)
307 (unless (assq 'nnimap-address defs)
308 (setq defs (append defs (list (list 'nnimap-address server)))))
309 (nnoo-change-server 'nnimap server defs)
310 (if no-reconnect
311 (nnimap-find-connection nntp-server-buffer)
312 (or (nnimap-find-connection nntp-server-buffer)
313 (nnimap-open-connection nntp-server-buffer)))))
315 (defun nnimap-make-process-buffer (buffer)
316 (with-current-buffer
317 (generate-new-buffer (format " *nnimap %s %s %s*"
318 nnimap-address nnimap-server-port
319 (gnus-buffer-exists-p buffer)))
320 (mm-disable-multibyte)
321 (buffer-disable-undo)
322 (gnus-add-buffer)
323 (set (make-local-variable 'after-change-functions) nil)
324 (set (make-local-variable 'nnimap-object)
325 (make-nnimap :server (nnoo-current-server 'nnimap)
326 :initial-resync 0))
327 (push (list buffer (current-buffer)) nnimap-connection-alist)
328 (push (current-buffer) nnimap-process-buffers)
329 (current-buffer)))
331 (defun nnimap-credentials (address ports user)
332 (let* ((auth-source-creation-prompts
333 '((user . "IMAP user at %h: ")
334 (secret . "IMAP password for %u@%h: ")))
335 (found (nth 0 (auth-source-search :max 1
336 :host address
337 :port ports
338 :user user
339 :require '(:user :secret)
340 :create t))))
341 (if found
342 (list (plist-get found :user)
343 (let ((secret (plist-get found :secret)))
344 (if (functionp secret)
345 (funcall secret)
346 secret))
347 (plist-get found :save-function))
348 nil)))
350 (defun nnimap-keepalive ()
351 (let ((now (current-time)))
352 (dolist (buffer nnimap-process-buffers)
353 (when (buffer-name buffer)
354 (with-current-buffer buffer
355 (when (and nnimap-object
356 (nnimap-last-command-time nnimap-object)
357 (> (gnus-float-time
358 (time-subtract
360 (nnimap-last-command-time nnimap-object)))
361 ;; More than five minutes since the last command.
362 (* 5 60)))
363 (ignore-errors ;E.g. "buffer foo has no process".
364 (nnimap-send-command "NOOP"))))))))
366 (defun nnimap-open-connection (buffer)
367 ;; Be backwards-compatible -- the earlier value of nnimap-stream was
368 ;; `ssl' when nnimap-server-port was nil. Sort of.
369 (when (and nnimap-server-port
370 (eq nnimap-stream 'undecided))
371 (setq nnimap-stream 'ssl))
372 (let ((stream
373 (if (eq nnimap-stream 'undecided)
374 (loop for type in '(ssl network)
375 for stream = (let ((nnimap-stream type))
376 (nnimap-open-connection-1 buffer))
377 while (eq stream 'no-connect)
378 finally (return stream))
379 (nnimap-open-connection-1 buffer))))
380 (if (eq stream 'no-connect)
382 stream)))
384 (defun nnimap-map-port (port)
385 (if (equal port "imaps")
386 "993"
387 port))
389 (defun nnimap-open-connection-1 (buffer)
390 (unless nnimap-keepalive-timer
391 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
392 #'nnimap-keepalive)))
393 (with-current-buffer (nnimap-make-process-buffer buffer)
394 (let* ((coding-system-for-read 'binary)
395 (coding-system-for-write 'binary)
396 (ports
397 (cond
398 ((memq nnimap-stream '(network plain starttls))
399 (nnheader-message 7 "Opening connection to %s..."
400 nnimap-address)
401 '("imap" "143"))
402 ((eq nnimap-stream 'shell)
403 (nnheader-message 7 "Opening connection to %s via shell..."
404 nnimap-address)
405 '("imap"))
406 ((memq nnimap-stream '(ssl tls))
407 (nnheader-message 7 "Opening connection to %s via tls..."
408 nnimap-address)
409 '("imaps" "imap" "993" "143"))
411 (error "Unknown stream type: %s" nnimap-stream))))
412 login-result credentials)
413 (when nnimap-server-port
414 (push nnimap-server-port ports))
415 (let* ((stream-list
416 (open-protocol-stream
417 "*nnimap*" (current-buffer) nnimap-address
418 (nnimap-map-port (car ports))
419 :type nnimap-stream
420 :warn-unless-encrypted t
421 :return-list t
422 :shell-command nnimap-shell-program
423 :capability-command "1 CAPABILITY\r\n"
424 :end-of-command "\r\n"
425 :success " OK "
426 :starttls-function
427 (lambda (capabilities)
428 (when (gnus-string-match-p "STARTTLS" capabilities)
429 "1 STARTTLS\r\n"))))
430 (stream (car stream-list))
431 (props (cdr stream-list))
432 (greeting (plist-get props :greeting))
433 (capabilities (plist-get props :capabilities))
434 (stream-type (plist-get props :type)))
435 (when (and stream (not (memq (process-status stream) '(open run))))
436 (setq stream nil))
438 (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
439 (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
440 (eq (process-type stream) 'network))
441 ;; Use TCP-keepalive so that connections that pass through a NAT
442 ;; router don't hang when left idle.
443 (set-network-process-option stream :keepalive t))
445 (setf (nnimap-process nnimap-object) stream)
446 (setf (nnimap-stream-type nnimap-object) stream-type)
447 (if (not stream)
448 (progn
449 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
450 nnimap-address (car ports) nnimap-stream)
451 'no-connect)
452 (gnus-set-process-query-on-exit-flag stream nil)
453 (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
454 (nnheader-report 'nnimap "%s" greeting)
455 ;; Store the greeting (for debugging purposes).
456 (setf (nnimap-greeting nnimap-object) greeting)
457 (setf (nnimap-capabilities nnimap-object)
458 (mapcar #'upcase
459 (split-string capabilities)))
460 (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
461 (if (not (setq credentials
462 (if (eq nnimap-authenticator 'anonymous)
463 (list "anonymous"
464 (message-make-address))
465 ;; Look for the credentials based on
466 ;; the virtual server name and the address
467 (nnimap-credentials
468 (gnus-delete-duplicates
469 (list
470 (nnoo-current-server 'nnimap)
471 nnimap-address))
472 ports
473 nnimap-user))))
474 (setq nnimap-object nil)
475 (let ((nnimap-inhibit-logging t))
476 (setq login-result
477 (nnimap-login (car credentials) (cadr credentials))))
478 (if (car login-result)
479 (progn
480 ;; Save the credentials if a save function exists
481 ;; (such a function will only be passed if a new
482 ;; token was created).
483 (when (functionp (nth 2 credentials))
484 (funcall (nth 2 credentials)))
485 ;; See if CAPABILITY is set as part of login
486 ;; response.
487 (dolist (response (cddr login-result))
488 (when (string= "CAPABILITY" (upcase (car response)))
489 (setf (nnimap-capabilities nnimap-object)
490 (mapcar #'upcase (cdr response))))))
491 ;; If the login failed, then forget the credentials
492 ;; that are now possibly cached.
493 (dolist (host (list (nnoo-current-server 'nnimap)
494 nnimap-address))
495 (dolist (port ports)
496 (auth-source-forget+ :host host :port port)))
497 (delete-process (nnimap-process nnimap-object))
498 (setq nnimap-object nil))))
499 (when nnimap-object
500 (when (nnimap-capability "QRESYNC")
501 (nnimap-command "ENABLE QRESYNC"))
502 (nnheader-message 7 "Opening connection to %s...done"
503 nnimap-address)
504 (nnimap-process nnimap-object))))))))
506 (autoload 'rfc2104-hash "rfc2104")
508 (defun nnimap-login (user password)
509 (cond
510 ;; Prefer plain LOGIN if it's enabled (since it requires fewer
511 ;; round trips than CRAM-MD5, and it's less likely to be buggy),
512 ;; and we're using an encrypted connection.
513 ((and (not (nnimap-capability "LOGINDISABLED"))
514 (eq (nnimap-stream-type nnimap-object) 'tls)
515 (or (null nnimap-authenticator)
516 (eq nnimap-authenticator 'login)))
517 (nnimap-command "LOGIN %S %S" user password))
518 ((and (nnimap-capability "AUTH=CRAM-MD5")
519 (or (null nnimap-authenticator)
520 (eq nnimap-authenticator 'cram-md5)))
521 (erase-buffer)
522 (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
523 (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
524 (process-send-string
525 (get-buffer-process (current-buffer))
526 (concat
527 (base64-encode-string
528 (concat user " "
529 (rfc2104-hash 'md5 64 16 password
530 (base64-decode-string challenge))))
531 "\r\n"))
532 (nnimap-wait-for-response sequence)))
533 ((and (not (nnimap-capability "LOGINDISABLED"))
534 (or (null nnimap-authenticator)
535 (eq nnimap-authenticator 'login)))
536 (nnimap-command "LOGIN %S %S" user password))
537 ((and (nnimap-capability "AUTH=PLAIN")
538 (or (null nnimap-authenticator)
539 (eq nnimap-authenticator 'plain)))
540 (nnimap-command
541 "AUTHENTICATE PLAIN %s"
542 (base64-encode-string
543 (format "\000%s\000%s"
544 (nnimap-quote-specials user)
545 (nnimap-quote-specials password)))))))
547 (defun nnimap-quote-specials (string)
548 (with-temp-buffer
549 (insert string)
550 (goto-char (point-min))
551 (while (re-search-forward "[\\\"]" nil t)
552 (forward-char -1)
553 (insert "\\")
554 (forward-char 1))
555 (buffer-string)))
557 (defun nnimap-find-parameter (parameter elems)
558 (let (result)
559 (dolist (elem elems)
560 (cond
561 ((equal (car elem) parameter)
562 (setq result (cdr elem)))
563 ((and (equal (car elem) "OK")
564 (consp (cadr elem))
565 (equal (caadr elem) parameter))
566 (setq result (cdr (cadr elem))))))
567 result))
569 (deffoo nnimap-close-server (&optional server)
570 (when (nnoo-change-server 'nnimap server nil)
571 (ignore-errors
572 (delete-process (get-buffer-process (nnimap-buffer))))
573 (nnoo-close-server 'nnimap server)
576 (deffoo nnimap-request-close ()
579 (deffoo nnimap-server-opened (&optional server)
580 (and (nnoo-current-server-p 'nnimap server)
581 nntp-server-buffer
582 (gnus-buffer-live-p nntp-server-buffer)
583 (nnimap-find-connection nntp-server-buffer)))
585 (deffoo nnimap-status-message (&optional server)
586 nnimap-status-string)
588 (deffoo nnimap-request-article (article &optional group server to-buffer)
589 (when group
590 (setq group (nnimap-decode-gnus-group group)))
591 (with-current-buffer nntp-server-buffer
592 (let ((result (nnimap-change-group group server))
593 parts structure)
594 (when (stringp article)
595 (setq article (nnimap-find-article-by-message-id group server article)))
596 (when (and result
597 article)
598 (erase-buffer)
599 (with-current-buffer (nnimap-buffer)
600 (erase-buffer)
601 (when nnimap-fetch-partial-articles
602 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
603 (goto-char (point-min))
604 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
605 (setq structure (ignore-errors
606 (let ((start (point)))
607 (forward-sexp 1)
608 (downcase-region start (point))
609 (goto-char start)
610 (read (current-buffer))))
611 parts (nnimap-find-wanted-parts structure))))
612 (when (if parts
613 (nnimap-get-partial-article article parts structure)
614 (nnimap-get-whole-article article))
615 (let ((buffer (current-buffer)))
616 (with-current-buffer (or to-buffer nntp-server-buffer)
617 (nnheader-insert-buffer-substring buffer)
618 (nnheader-ms-strip-cr)))
619 (cons group article)))))))
621 (deffoo nnimap-request-head (article &optional group server to-buffer)
622 (when group
623 (setq group (nnimap-decode-gnus-group group)))
624 (when (nnimap-change-group group server)
625 (with-current-buffer (nnimap-buffer)
626 (when (stringp article)
627 (setq article (nnimap-find-article-by-message-id group server article)))
628 (if (null article)
630 (nnimap-get-whole-article
631 article (format "UID FETCH %%d %s"
632 (nnimap-header-parameters)))
633 (let ((buffer (current-buffer)))
634 (with-current-buffer (or to-buffer nntp-server-buffer)
635 (erase-buffer)
636 (insert-buffer-substring buffer)
637 (nnheader-ms-strip-cr)
638 (cons group article)))))))
640 (deffoo nnimap-request-articles (articles &optional group server)
641 (when group
642 (setq group (nnimap-decode-gnus-group group)))
643 (with-current-buffer nntp-server-buffer
644 (let ((result (nnimap-change-group group server)))
645 (when result
646 (erase-buffer)
647 (with-current-buffer (nnimap-buffer)
648 (erase-buffer)
649 (when (nnimap-command
650 (if (nnimap-ver4-p)
651 "UID FETCH %s BODY.PEEK[]"
652 "UID FETCH %s RFC822.PEEK")
653 (nnimap-article-ranges (gnus-compress-sequence articles)))
654 (let ((buffer (current-buffer)))
655 (with-current-buffer nntp-server-buffer
656 (nnheader-insert-buffer-substring buffer)
657 (nnheader-ms-strip-cr)))
658 t))))))
660 (defun nnimap-get-whole-article (article &optional command)
661 (let ((result
662 (nnimap-command
663 (or command
664 (if (nnimap-ver4-p)
665 "UID FETCH %d BODY.PEEK[]"
666 "UID FETCH %d RFC822.PEEK"))
667 article)))
668 ;; Check that we really got an article.
669 (goto-char (point-min))
670 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
671 (setq result nil))
672 (when result
673 ;; Remove any data that may have arrived before the FETCH data.
674 (beginning-of-line)
675 (unless (bobp)
676 (delete-region (point-min) (point)))
677 (let ((bytes (nnimap-get-length)))
678 (delete-region (line-beginning-position)
679 (progn (forward-line 1) (point)))
680 (goto-char (+ (point) bytes))
681 (delete-region (point) (point-max)))
682 t)))
684 (defun nnimap-capability (capability)
685 (member capability (nnimap-capabilities nnimap-object)))
687 (defun nnimap-ver4-p ()
688 (nnimap-capability "IMAP4REV1"))
690 (defun nnimap-get-partial-article (article parts structure)
691 (let ((result
692 (nnimap-command
693 "UID FETCH %d (%s %s)"
694 article
695 (if (nnimap-ver4-p)
696 "BODY.PEEK[HEADER]"
697 "RFC822.HEADER")
698 (if (nnimap-ver4-p)
699 (mapconcat (lambda (part)
700 (format "BODY.PEEK[%s]" part))
701 parts " ")
702 (mapconcat (lambda (part)
703 (format "RFC822.PEEK[%s]" part))
704 parts " ")))))
705 (when result
706 (nnimap-convert-partial-article structure))))
708 (defun nnimap-convert-partial-article (structure)
709 ;; First just skip past the headers.
710 (goto-char (point-min))
711 (let ((bytes (nnimap-get-length))
712 id parts)
713 ;; Delete "FETCH" line.
714 (delete-region (line-beginning-position)
715 (progn (forward-line 1) (point)))
716 (goto-char (+ (point) bytes))
717 ;; Collect all the body parts.
718 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
719 (setq id (match-string 1)
720 bytes (or (nnimap-get-length) 0))
721 (beginning-of-line)
722 (delete-region (point) (progn (forward-line 1) (point)))
723 (push (list id (buffer-substring (point) (+ (point) bytes)))
724 parts)
725 (delete-region (point) (+ (point) bytes)))
726 ;; Delete trailing junk.
727 (delete-region (point) (point-max))
728 ;; Now insert all the parts again where they fit in the structure.
729 (nnimap-insert-partial-structure structure parts)
732 (defun nnimap-insert-partial-structure (structure parts &optional subp)
733 (let (type boundary)
734 (let ((bstruc structure))
735 (while (consp (car bstruc))
736 (pop bstruc))
737 (setq type (car bstruc))
738 (setq bstruc (car (cdr bstruc)))
739 (let ((has-boundary (member "boundary" bstruc)))
740 (when has-boundary
741 (setq boundary (cadr has-boundary)))))
742 (when subp
743 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
744 (downcase type) boundary)))
745 (while (not (stringp (car structure)))
746 (insert "\n--" boundary "\n")
747 (if (consp (caar structure))
748 (nnimap-insert-partial-structure (pop structure) parts t)
749 (let ((bit (pop structure)))
750 (insert (format "Content-type: %s/%s"
751 (downcase (nth 0 bit))
752 (downcase (nth 1 bit))))
753 (if (member-ignore-case "CHARSET" (nth 2 bit))
754 (insert (format
755 "; charset=%S\n"
756 (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
757 (insert "\n"))
758 (insert (format "Content-transfer-encoding: %s\n"
759 (nth 5 bit)))
760 (insert "\n")
761 (when (assoc (nth 9 bit) parts)
762 (insert (cadr (assoc (nth 9 bit) parts)))))))
763 (insert "\n--" boundary "--\n")))
765 (defun nnimap-find-wanted-parts (structure)
766 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
768 (defun nnimap-find-wanted-parts-1 (structure prefix)
769 (let ((num 1)
770 parts)
771 (while (consp (car structure))
772 (let ((sub (pop structure)))
773 (if (consp (car sub))
774 (push (nnimap-find-wanted-parts-1
775 sub (if (string= prefix "")
776 (number-to-string num)
777 (format "%s.%s" prefix num)))
778 parts)
779 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
780 (id (if (string= prefix "")
781 (number-to-string num)
782 (format "%s.%s" prefix num))))
783 (setcar (nthcdr 9 sub) id)
784 (when (if (eq nnimap-fetch-partial-articles t)
785 (equal id "1")
786 (string-match nnimap-fetch-partial-articles type))
787 (push id parts))))
788 (incf num)))
789 (nreverse parts)))
791 (defun nnimap-decode-gnus-group (group)
792 (decode-coding-string group 'utf-8))
794 (deffoo nnimap-request-group (group &optional server dont-check info)
795 (setq group (nnimap-decode-gnus-group group))
796 (let ((result (nnimap-change-group
797 ;; Don't SELECT the group if we're going to select it
798 ;; later, anyway.
799 (if (and (not dont-check)
800 (assoc group nnimap-current-infos))
802 group)
803 server))
804 articles active marks high low)
805 (with-current-buffer nntp-server-buffer
806 (when result
807 (when (or (not dont-check)
808 (not (setq active
809 (nth 2 (assoc group nnimap-current-infos)))))
810 (let ((sequences (nnimap-retrieve-group-data-early
811 server (list info))))
812 (nnimap-finish-retrieve-group-infos server (list info) sequences
814 (setq active (nth 2 (assoc group nnimap-current-infos)))))
815 (insert (format "211 %d %d %d %S\n"
816 (- (cdr active) (car active))
817 (car active)
818 (cdr active)
819 group))
820 t))))
822 (deffoo nnimap-request-scan-group (group &optional server info)
823 (setq group (nnimap-decode-gnus-group group))
824 (let (marks high low)
825 (with-current-buffer (nnimap-buffer)
826 (erase-buffer)
827 (let ((group-sequence
828 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
829 (flag-sequence
830 (nnimap-send-command "UID FETCH 1:* FLAGS")))
831 (setf (nnimap-group nnimap-object) group)
832 (nnimap-wait-for-response flag-sequence)
833 (setq marks
834 (nnimap-flags-to-marks
835 (nnimap-parse-flags
836 (list (list group-sequence flag-sequence
837 1 group "SELECT")))))
838 (when (and info
839 marks)
840 (nnimap-update-infos marks (list info))
841 (nnimap-store-info info (gnus-active (gnus-info-group info))))
842 (goto-char (point-max))
843 (let ((uidnext (nth 5 (car marks))))
844 (setq high (or (if uidnext
845 (1- uidnext)
846 (nth 3 (car marks)))
848 low (or (nth 4 (car marks)) uidnext 1)))))
849 (with-current-buffer nntp-server-buffer
850 (erase-buffer)
851 (insert
852 (format
853 "211 %d %d %d %S\n" (1+ (- high low)) low high group))
854 t)))
856 (deffoo nnimap-request-create-group (group &optional server args)
857 (setq group (nnimap-decode-gnus-group group))
858 (when (nnimap-change-group nil server)
859 (with-current-buffer (nnimap-buffer)
860 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
862 (deffoo nnimap-request-delete-group (group &optional force server)
863 (setq group (nnimap-decode-gnus-group group))
864 (when (nnimap-change-group nil server)
865 (with-current-buffer (nnimap-buffer)
866 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
868 (deffoo nnimap-request-rename-group (group new-name &optional server)
869 (setq group (nnimap-decode-gnus-group group))
870 (when (nnimap-change-group nil server)
871 (with-current-buffer (nnimap-buffer)
872 (nnimap-unselect-group)
873 (car (nnimap-command "RENAME %S %S"
874 (utf7-encode group t) (utf7-encode new-name t))))))
876 (defun nnimap-unselect-group ()
877 ;; Make sure we don't have this group open read/write by asking
878 ;; to examine a mailbox that doesn't exist. This seems to be
879 ;; the only way that allows us to reliably go back to unselected
880 ;; state on Courier.
881 (nnimap-command "EXAMINE DOES.NOT.EXIST"))
883 (deffoo nnimap-request-expunge-group (group &optional server)
884 (setq group (nnimap-decode-gnus-group group))
885 (when (nnimap-change-group group server)
886 (with-current-buffer (nnimap-buffer)
887 (car (nnimap-command "EXPUNGE")))))
889 (defun nnimap-get-flags (spec)
890 (let ((articles nil)
891 elems end)
892 (with-current-buffer (nnimap-buffer)
893 (erase-buffer)
894 (nnimap-wait-for-response (nnimap-send-command
895 "UID FETCH %s FLAGS" spec))
896 (setq end (point))
897 (subst-char-in-region (point-min) (point-max)
898 ?\\ ?% t)
899 (goto-char (point-min))
900 (while (search-forward " FETCH " end t)
901 (setq elems (read (current-buffer)))
902 (push (cons (cadr (memq 'UID elems))
903 (cadr (memq 'FLAGS elems)))
904 articles)))
905 (nreverse articles)))
907 (deffoo nnimap-close-group (group &optional server)
910 (deffoo nnimap-request-move-article (article group server accept-form
911 &optional last internal-move-group)
912 (setq group (nnimap-decode-gnus-group group))
913 (when internal-move-group
914 (setq internal-move-group (nnimap-decode-gnus-group internal-move-group)))
915 (with-temp-buffer
916 (mm-disable-multibyte)
917 (when (funcall (if internal-move-group
918 'nnimap-request-head
919 'nnimap-request-article)
920 article group server (current-buffer))
921 ;; If the move is internal (on the same server), just do it the easy
922 ;; way.
923 (let ((message-id (message-field-value "message-id")))
924 (if internal-move-group
925 (let ((result
926 (with-current-buffer (nnimap-buffer)
927 (nnimap-command "UID COPY %d %S"
928 article
929 (utf7-encode internal-move-group t)))))
930 (when (car result)
931 (nnimap-delete-article article)
932 (cons internal-move-group
933 (or (nnimap-find-uid-response "COPYUID" (cadr result))
934 (nnimap-find-article-by-message-id
935 internal-move-group server message-id
936 nnimap-request-articles-find-limit)))))
937 ;; Move the article to a different method.
938 (let ((result (eval accept-form)))
939 (when result
940 (nnimap-change-group group server)
941 (nnimap-delete-article article)
942 result)))))))
944 (deffoo nnimap-request-expire-articles (articles group &optional server force)
945 (setq group (nnimap-decode-gnus-group group))
946 (cond
947 ((null articles)
948 nil)
949 ((not (nnimap-change-group group server))
950 articles)
951 ((and force
952 (eq nnmail-expiry-target 'delete))
953 (unless (nnimap-delete-article (gnus-compress-sequence articles))
954 (nnheader-message 7 "Article marked for deletion, but not expunged."))
955 nil)
957 (let ((deletable-articles
958 (if (or force
959 (eq nnmail-expiry-wait 'immediate))
960 articles
961 (gnus-sorted-intersection
962 articles
963 (nnimap-find-expired-articles group)))))
964 (if (null deletable-articles)
965 articles
966 (if (eq nnmail-expiry-target 'delete)
967 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
968 (setq deletable-articles
969 (nnimap-process-expiry-targets
970 deletable-articles group server)))
971 ;; Return the articles we didn't delete.
972 (gnus-sorted-complement articles deletable-articles))))))
974 (defun nnimap-process-expiry-targets (articles group server)
975 (let ((deleted-articles nil))
976 (cond
977 ;; shortcut further processing if we're going to delete the articles
978 ((eq nnmail-expiry-target 'delete)
979 (setq deleted-articles articles)
981 ;; or just move them to another folder on the same IMAP server
982 ((and (not (functionp nnmail-expiry-target))
983 (gnus-server-equal (gnus-group-method nnmail-expiry-target)
984 (gnus-server-to-method
985 (format "nnimap:%s" server))))
986 (and (nnimap-change-group group server)
987 (with-current-buffer (nnimap-buffer)
988 (nnheader-message 7 "Expiring articles from %s: %s" group articles)
989 (nnimap-command
990 "UID COPY %s %S"
991 (nnimap-article-ranges (gnus-compress-sequence articles))
992 (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
993 (setq deleted-articles articles)))
996 (dolist (article articles)
997 (let ((target nnmail-expiry-target))
998 (with-temp-buffer
999 (mm-disable-multibyte)
1000 (when (nnimap-request-article article group server (current-buffer))
1001 (when (functionp target)
1002 (setq target (funcall target group)))
1003 (if (and target
1004 (not (eq target 'delete)))
1005 (if (or (gnus-request-group target t)
1006 (gnus-request-create-group target))
1007 (progn
1008 (nnmail-expiry-target-group target group)
1009 (nnheader-message 7 "Expiring article %s:%d to %s"
1010 group article target))
1011 (setq target nil))
1012 (nnheader-message 7 "Expiring article %s:%d" group article))
1013 (when target
1014 (push article deleted-articles))))))
1015 (setq deleted-articles (nreverse deleted-articles))))
1016 ;; Change back to the current group again.
1017 (nnimap-change-group group server)
1018 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
1019 deleted-articles))
1021 (defun nnimap-find-expired-articles (group)
1022 (let ((cutoff (nnmail-expired-article-p group nil nil)))
1023 (with-current-buffer (nnimap-buffer)
1024 (let ((result
1025 (nnimap-command
1026 "UID SEARCH SENTBEFORE %s"
1027 (format-time-string
1028 (format "%%d-%s-%%Y"
1029 (upcase
1030 (car (rassoc (nth 4 (decode-time cutoff))
1031 parse-time-months))))
1032 cutoff))))
1033 (and (car result)
1034 (delete 0 (mapcar #'string-to-number
1035 (cdr (assoc "SEARCH" (cdr result))))))))))
1038 (defun nnimap-find-article-by-message-id (group server message-id
1039 &optional limit)
1040 "Search for message with MESSAGE-ID in GROUP from SERVER.
1041 If LIMIT, first try to limit the search to the N last articles."
1042 (with-current-buffer (nnimap-buffer)
1043 (erase-buffer)
1044 (let* ((change-group-result (nnimap-change-group group server nil t))
1045 (number-of-article
1046 (and (listp change-group-result)
1047 (catch 'found
1048 (dolist (result (cdr change-group-result))
1049 (when (equal "EXISTS" (cadr result))
1050 (throw 'found (car result)))))))
1051 (sequence
1052 (nnimap-send-command
1053 "UID SEARCH%s HEADER Message-Id %S"
1054 (if (and limit number-of-article)
1055 ;; The -1 is because IMAP message
1056 ;; numbers are one-based rather than
1057 ;; zero-based.
1058 (format " %s:*" (- (string-to-number number-of-article)
1059 limit -1))
1061 message-id)))
1062 (when (nnimap-wait-for-response sequence)
1063 (let ((article (car (last (cdr (assoc "SEARCH"
1064 (nnimap-parse-response)))))))
1065 (if article
1066 (string-to-number article)
1067 (when (and limit number-of-article)
1068 (nnimap-find-article-by-message-id group server message-id))))))))
1070 (defun nnimap-delete-article (articles)
1071 (with-current-buffer (nnimap-buffer)
1072 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
1073 (nnimap-article-ranges articles))
1074 (cond
1075 ((nnimap-capability "UIDPLUS")
1076 (nnimap-command "UID EXPUNGE %s"
1077 (nnimap-article-ranges articles))
1079 (nnimap-expunge
1080 (nnimap-command "EXPUNGE")
1082 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1083 "server doesn't support UIDPLUS, so we won't "
1084 "delete this article now"))))))
1086 (deffoo nnimap-request-scan (&optional group server)
1087 (when group
1088 (setq group (nnimap-decode-gnus-group group)))
1089 (when (and (nnimap-change-group nil server)
1090 nnimap-inbox
1091 nnimap-split-methods)
1092 (nnheader-message 7 "nnimap %s splitting mail..." server)
1093 (if (listp nnimap-inbox)
1094 (dolist (nnimap-inbox nnimap-inbox)
1095 (nnimap-split-incoming-mail))
1096 (nnimap-split-incoming-mail))
1097 (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1099 (defun nnimap-marks-to-flags (marks)
1100 (let (flags flag)
1101 (dolist (mark marks)
1102 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1103 (push flag flags)))
1104 flags))
1106 (deffoo nnimap-request-update-group-status (group status &optional server)
1107 (setq group (nnimap-decode-gnus-group group))
1108 (when (nnimap-change-group nil server)
1109 (let ((command (assoc
1110 status
1111 '((subscribe "SUBSCRIBE")
1112 (unsubscribe "UNSUBSCRIBE")))))
1113 (when command
1114 (with-current-buffer (nnimap-buffer)
1115 (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1117 (deffoo nnimap-request-set-mark (group actions &optional server)
1118 (setq group (nnimap-decode-gnus-group group))
1119 (when (nnimap-change-group group server)
1120 (let (sequence)
1121 (with-current-buffer (nnimap-buffer)
1122 (erase-buffer)
1123 ;; Just send all the STORE commands without waiting for
1124 ;; response. If they're successful, they're successful.
1125 (dolist (action actions)
1126 (destructuring-bind (range action marks) action
1127 (let ((flags (nnimap-marks-to-flags marks)))
1128 (when flags
1129 (setq sequence (nnimap-send-command
1130 "UID STORE %s %sFLAGS.SILENT (%s)"
1131 (nnimap-article-ranges range)
1132 (cond
1133 ((eq action 'del) "-")
1134 ((eq action 'add) "+")
1135 ((eq action 'set) ""))
1136 (mapconcat #'identity flags " ")))))))
1137 ;; Wait for the last command to complete to avoid later
1138 ;; synchronization problems with the stream.
1139 (when sequence
1140 (nnimap-wait-for-response sequence))))))
1142 (deffoo nnimap-request-accept-article (group &optional server last)
1143 (unless group
1144 ;; We're respooling. Find out where mail splitting would place
1145 ;; this article.
1146 (setq group
1147 (caar
1148 (nnmail-article-group
1149 ;; We don't really care about the article number, because
1150 ;; that's determined by the IMAP server later. So just
1151 ;; return the group name.
1152 `(lambda (group)
1153 (list (list group)))))))
1154 (setq group (nnimap-decode-gnus-group group))
1155 (when (nnimap-change-group nil server)
1156 (nnmail-check-syntax)
1157 (let ((message-id (message-field-value "message-id"))
1158 sequence message)
1159 (nnimap-add-cr)
1160 (setq message (buffer-substring-no-properties (point-min) (point-max)))
1161 (with-current-buffer (nnimap-buffer)
1162 (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1163 message))
1164 ;; If we have this group open read-only, then unselect it
1165 ;; before appending to it.
1166 (when (equal (nnimap-examined nnimap-object) group)
1167 (nnimap-unselect-group))
1168 (erase-buffer)
1169 (setq sequence (nnimap-send-command
1170 "APPEND %S {%d}" (utf7-encode group t)
1171 (length message)))
1172 (unless nnimap-streaming
1173 (nnimap-wait-for-connection "^[+]"))
1174 (process-send-string (get-buffer-process (current-buffer)) message)
1175 (process-send-string (get-buffer-process (current-buffer))
1176 (if (nnimap-newlinep nnimap-object)
1177 "\n"
1178 "\r\n"))
1179 (let ((result (nnimap-get-response sequence)))
1180 (if (not (nnimap-ok-p result))
1181 (progn
1182 (nnheader-report 'nnimap "%s" result)
1183 nil)
1184 (cons group
1185 (or (nnimap-find-uid-response "APPENDUID" (car result))
1186 (nnimap-find-article-by-message-id
1187 group server message-id
1188 nnimap-request-articles-find-limit))))))))))
1190 (defun nnimap-process-quirk (greeting-match type data)
1191 (when (and (nnimap-greeting nnimap-object)
1192 (string-match greeting-match (nnimap-greeting nnimap-object))
1193 (eq type 'append)
1194 (string-match "\000" data))
1195 (let ((choice (gnus-multiple-choice
1196 "Message contains NUL characters. Delete, continue, abort? "
1197 '((?d "Delete NUL characters")
1198 (?c "Try to APPEND the message as is")
1199 (?a "Abort")))))
1200 (cond
1201 ((eq choice ?a)
1202 (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1203 ((eq choice ?c)
1204 data)
1206 (with-temp-buffer
1207 (insert data)
1208 (goto-char (point-min))
1209 (while (search-forward "\000" nil t)
1210 (replace-match "" t t))
1211 (buffer-string)))))))
1213 (defun nnimap-ok-p (value)
1214 (and (consp value)
1215 (consp (car value))
1216 (equal (caar value) "OK")))
1218 (defun nnimap-find-uid-response (name list)
1219 (let ((result (car (last (nnimap-find-response-element name list)))))
1220 (and result
1221 (string-to-number result))))
1223 (defun nnimap-find-response-element (name list)
1224 (let (result)
1225 (dolist (elem list)
1226 (when (and (consp elem)
1227 (equal name (car elem)))
1228 (setq result elem)))
1229 result))
1231 (deffoo nnimap-request-replace-article (article group buffer)
1232 (setq group (nnimap-decode-gnus-group group))
1233 (let (group-art)
1234 (when (and (nnimap-change-group group)
1235 ;; Put the article into the group.
1236 (with-current-buffer buffer
1237 (setq group-art
1238 (nnimap-request-accept-article group nil t))))
1239 (nnimap-delete-article (list article))
1240 ;; Return the new article number.
1241 (cdr group-art))))
1243 (defun nnimap-add-cr ()
1244 (goto-char (point-min))
1245 (while (re-search-forward "\r?\n" nil t)
1246 (replace-match "\r\n" t t)))
1248 (defun nnimap-get-groups ()
1249 (erase-buffer)
1250 (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1251 groups)
1252 (nnimap-wait-for-response sequence)
1253 (subst-char-in-region (point-min) (point-max)
1254 ?\\ ?% t)
1255 (goto-char (point-min))
1256 (nnimap-unfold-quoted-lines)
1257 (goto-char (point-min))
1258 (while (search-forward "* LIST " nil t)
1259 (let ((flags (read (current-buffer)))
1260 (separator (read (current-buffer)))
1261 (group (read (current-buffer))))
1262 (unless (member '%NoSelect flags)
1263 (push (utf7-decode (if (stringp group)
1264 group
1265 (format "%s" group)) t)
1266 groups))))
1267 (nreverse groups)))
1269 (defun nnimap-get-responses (sequences)
1270 (let (responses)
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))
1275 responses)))
1276 responses))
1278 (deffoo nnimap-request-list (&optional server)
1279 (when (nnimap-change-group nil server)
1280 (with-current-buffer nntp-server-buffer
1281 (erase-buffer)
1282 (let ((groups
1283 (with-current-buffer (nnimap-buffer)
1284 (nnimap-get-groups)))
1285 sequences responses)
1286 (when groups
1287 (with-current-buffer (nnimap-buffer)
1288 (setf (nnimap-group nnimap-object) nil)
1289 (dolist (group groups)
1290 (setf (nnimap-examined nnimap-object) group)
1291 (push (list (nnimap-send-command "EXAMINE %S"
1292 (utf7-encode group t))
1293 group)
1294 sequences))
1295 (nnimap-wait-for-response (caar sequences))
1296 (setq responses
1297 (nnimap-get-responses (mapcar #'car sequences))))
1298 (dolist (response responses)
1299 (let* ((sequence (car response))
1300 (response (cadr response))
1301 (group (cadr (assoc sequence sequences)))
1302 (egroup (encode-coding-string group 'utf-8)))
1303 (when (and group
1304 (equal (caar response) "OK"))
1305 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1306 highest exists)
1307 (dolist (elem response)
1308 (when (equal (cadr elem) "EXISTS")
1309 (setq exists (string-to-number (car elem)))))
1310 (when uidnext
1311 (setq highest (1- (string-to-number (car uidnext)))))
1312 (cond
1313 ((null highest)
1314 (insert (format "%S 0 1 y\n" egroup)))
1315 ((zerop exists)
1316 ;; Empty group.
1317 (insert (format "%S %d %d y\n" egroup
1318 highest (1+ highest))))
1320 ;; Return the widest possible range.
1321 (insert (format "%S %d 1 y\n" egroup
1322 (or highest exists)))))))))
1323 t)))))
1325 (deffoo nnimap-request-newgroups (date &optional server)
1326 (when (nnimap-change-group nil server)
1327 (with-current-buffer nntp-server-buffer
1328 (erase-buffer)
1329 (dolist (group (with-current-buffer (nnimap-buffer)
1330 (nnimap-get-groups)))
1331 (unless (assoc group nnimap-current-infos)
1332 ;; Insert dummy numbers here -- they don't matter.
1333 (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1334 t)))
1336 (deffoo nnimap-retrieve-group-data-early (server infos)
1337 (when (and (nnimap-change-group nil server)
1338 infos)
1339 (with-current-buffer (nnimap-buffer)
1340 (erase-buffer)
1341 (setf (nnimap-group nnimap-object) nil)
1342 (setf (nnimap-initial-resync nnimap-object) 0)
1343 (let ((qresyncp (nnimap-capability "QRESYNC"))
1344 params groups sequences active uidvalidity modseq group
1345 unexist)
1346 ;; Go through the infos and gather the data needed to know
1347 ;; what and how to request the data.
1348 (dolist (info infos)
1349 (setq params (gnus-info-params info)
1350 group (nnimap-decode-gnus-group
1351 (gnus-group-real-name (gnus-info-group info)))
1352 active (cdr (assq 'active params))
1353 unexist (assq 'unexist (gnus-info-marks info))
1354 uidvalidity (cdr (assq 'uidvalidity params))
1355 modseq (cdr (assq 'modseq params)))
1356 (setf (nnimap-examined nnimap-object) group)
1357 (if (and qresyncp
1358 uidvalidity
1359 active
1360 modseq
1361 unexist)
1362 (push
1363 (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1364 (utf7-encode group t)
1365 (nnimap-quirk "QRESYNC")
1366 uidvalidity modseq)
1367 'qresync
1368 nil group 'qresync)
1369 sequences)
1370 (let ((command
1371 (if uidvalidity
1372 "EXAMINE"
1373 ;; If we don't have a UIDVALIDITY, then this is
1374 ;; the first time we've seen the group, so we
1375 ;; have to do a SELECT (which is slower than an
1376 ;; examine), but will tell us whether the group
1377 ;; is read-only or not.
1378 "SELECT"))
1379 start)
1380 (if (and active uidvalidity unexist)
1381 ;; Fetch the last 100 flags.
1382 (setq start (max 1 (- (cdr active) 100)))
1383 (incf (nnimap-initial-resync nnimap-object))
1384 (setq start 1))
1385 (push (list (nnimap-send-command "%s %S" command
1386 (utf7-encode group t))
1387 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1388 start group command)
1389 sequences))))
1390 sequences))))
1392 (defun nnimap-quirk (command)
1393 (let ((quirk (assoc command nnimap-quirks)))
1394 ;; If this server is of a type that matches a quirk, then return
1395 ;; the "quirked" command instead of the proper one.
1396 (if (or (null quirk)
1397 (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1398 command
1399 (nth 2 quirk))))
1401 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences
1402 &optional dont-insert)
1403 (when (and sequences
1404 (nnimap-change-group nil server t)
1405 ;; Check that the process is still alive.
1406 (get-buffer-process (nnimap-buffer))
1407 (memq (process-status (get-buffer-process (nnimap-buffer)))
1408 '(open run)))
1409 (with-current-buffer (nnimap-buffer)
1410 ;; Wait for the final data to trickle in.
1411 (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1412 (caar sequences)
1413 (cadar sequences))
1415 ;; Now we should have most of the data we need, no matter
1416 ;; whether we're QRESYNCING, fetching all the flags from
1417 ;; scratch, or just fetching the last 100 flags per group.
1418 (nnimap-update-infos (nnimap-flags-to-marks
1419 (nnimap-parse-flags
1420 (nreverse sequences)))
1421 infos)
1422 (unless dont-insert
1423 ;; Finally, just return something resembling an active file in
1424 ;; the nntp buffer, so that the agent can save the info, too.
1425 (with-current-buffer nntp-server-buffer
1426 (erase-buffer)
1427 (dolist (info infos)
1428 (let* ((group (gnus-info-group info))
1429 (active (gnus-active group)))
1430 (when active
1431 (insert (format "%S %d %d y\n"
1432 (decode-coding-string
1433 (gnus-group-real-name group) 'utf-8)
1434 (cdr active)
1435 (car active))))))))))))
1437 (defun nnimap-update-infos (flags infos)
1438 (dolist (info infos)
1439 (let* ((group (nnimap-decode-gnus-group
1440 (gnus-group-real-name (gnus-info-group info))))
1441 (marks (cdr (assoc group flags))))
1442 (when marks
1443 (nnimap-update-info info marks)))))
1445 (defun nnimap-update-info (info marks)
1446 (destructuring-bind (existing flags high low uidnext start-article
1447 permanent-flags uidvalidity
1448 vanished highestmodseq) marks
1449 (cond
1450 ;; Ignore groups with no UIDNEXT/marks. This happens for
1451 ;; completely empty groups.
1452 ((and (not existing)
1453 (not uidnext))
1454 (let ((active (cdr (assq 'active (gnus-info-params info)))))
1455 (when active
1456 (gnus-set-active (gnus-info-group info) active))))
1457 ;; We have a mismatch between the old and new UIDVALIDITY
1458 ;; identifiers, so we have to re-request the group info (the next
1459 ;; time). This virtually never happens.
1460 ((let ((old-uidvalidity
1461 (cdr (assq 'uidvalidity (gnus-info-params info)))))
1462 (and old-uidvalidity
1463 (not (equal old-uidvalidity uidvalidity))
1464 (or (not start-article)
1465 (> start-article 1))))
1466 (gnus-group-remove-parameter info 'uidvalidity)
1467 (gnus-group-remove-parameter info 'modseq))
1468 ;; We have the data needed to update.
1470 (let* ((group (gnus-info-group info))
1471 (completep (and start-article
1472 (= start-article 1)))
1473 (active (or (gnus-active group)
1474 (cdr (assq 'active (gnus-info-params info))))))
1475 (when uidnext
1476 (setq high (1- uidnext)))
1477 ;; First set the active ranges based on high/low.
1478 (if (or completep
1479 (not (gnus-active group)))
1480 (gnus-set-active group
1481 (cond
1482 (active
1483 (cons (min (or low (car active))
1484 (car active))
1485 (max (or high (cdr active))
1486 (cdr active))))
1487 ((and low high)
1488 (cons low high))
1489 (uidnext
1490 ;; No articles in this group.
1491 (cons uidnext (1- uidnext)))
1492 (start-article
1493 (cons start-article (1- start-article)))
1495 ;; No articles and no uidnext.
1496 nil)))
1497 (gnus-set-active group
1498 (cons (car active)
1499 (or high (1- uidnext)))))
1500 ;; See whether this is a read-only group.
1501 (unless (eq permanent-flags 'not-scanned)
1502 (gnus-group-set-parameter
1503 info 'permanent-flags
1504 (and (or (memq '%* permanent-flags)
1505 (memq '%Seen permanent-flags))
1506 permanent-flags)))
1507 ;; Update marks and read articles if this isn't a
1508 ;; read-only IMAP group.
1509 (when (setq permanent-flags
1510 (cdr (assq 'permanent-flags (gnus-info-params info))))
1511 (if (and highestmodseq
1512 (not start-article))
1513 ;; We've gotten the data by QRESYNCing.
1514 (nnimap-update-qresync-info
1515 info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1516 ;; Do normal non-QRESYNC flag updates.
1517 ;; Update the list of read articles.
1518 (let* ((unread
1519 (gnus-compress-sequence
1520 (gnus-set-difference
1521 (gnus-set-difference
1522 existing
1523 (gnus-sorted-union
1524 (cdr (assoc '%Seen flags))
1525 (cdr (assoc '%Deleted flags))))
1526 (cdr (assoc '%Flagged flags)))))
1527 (read (gnus-range-difference
1528 (cons start-article high) unread)))
1529 (when (> start-article 1)
1530 (setq read
1531 (gnus-range-nconcat
1532 (if (> start-article 1)
1533 (gnus-sorted-range-intersection
1534 (cons 1 (1- start-article))
1535 (gnus-info-read info))
1536 (gnus-info-read info))
1537 read)))
1538 (when (or (not (listp permanent-flags))
1539 (memq '%Seen permanent-flags))
1540 (gnus-info-set-read info read))
1541 ;; Update the marks.
1542 (setq marks (gnus-info-marks info))
1543 (dolist (type (cdr nnimap-mark-alist))
1544 (when (or (not (listp permanent-flags))
1545 (memq (car (assoc (caddr type) flags))
1546 permanent-flags)
1547 (memq '%* permanent-flags))
1548 (let ((old-marks (assoc (car type) marks))
1549 (new-marks
1550 (gnus-compress-sequence
1551 (cdr (or (assoc (caddr type) flags) ; %Flagged
1552 (assoc (intern (cadr type) obarray) flags)
1553 (assoc (cadr type) flags)))))) ; "\Flagged"
1554 (setq marks (delq old-marks marks))
1555 (pop old-marks)
1556 (when (and old-marks
1557 (> start-article 1))
1558 (setq old-marks (gnus-range-difference
1559 old-marks
1560 (cons start-article high)))
1561 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1562 (when new-marks
1563 (push (cons (car type) new-marks) marks)))))
1564 ;; Keep track of non-existing articles.
1565 (let* ((old-unexists (assq 'unexist marks))
1566 (active (gnus-active group))
1567 (unexists
1568 (if completep
1569 (gnus-range-difference
1570 active
1571 (gnus-compress-sequence existing))
1572 (gnus-add-to-range
1573 (cdr old-unexists)
1574 (gnus-list-range-difference
1575 existing (gnus-active group))))))
1576 (when (> (car active) 1)
1577 (setq unexists (gnus-range-add
1578 (cons 1 (1- (car active)))
1579 unexists)))
1580 (if old-unexists
1581 (setcdr old-unexists unexists)
1582 (push (cons 'unexist unexists) marks)))
1583 (gnus-info-set-marks info marks t))))
1584 ;; Tell Gnus whether there are any \Recent messages in any of
1585 ;; the groups.
1586 (let ((recent (cdr (assoc '%Recent flags))))
1587 (when (and active
1588 recent
1589 (> (car (last recent)) (cdr active)))
1590 (push (list (cons (gnus-group-real-name group) 0))
1591 nnmail-split-history)))
1592 ;; Note the active level for the next run-through.
1593 (gnus-group-set-parameter info 'active (gnus-active group))
1594 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1595 (gnus-group-set-parameter info 'modseq highestmodseq)
1596 (nnimap-store-info info (gnus-active group)))))))
1598 (defun nnimap-update-qresync-info (info existing vanished flags)
1599 ;; Add all the vanished articles to the list of read articles.
1600 (gnus-info-set-read
1601 info
1602 (gnus-add-to-range
1603 (gnus-add-to-range
1604 (gnus-range-add (gnus-info-read info)
1605 vanished)
1606 (cdr (assq '%Flagged flags)))
1607 (cdr (assq '%Seen flags))))
1608 (let ((marks (gnus-info-marks info)))
1609 (dolist (type (cdr nnimap-mark-alist))
1610 (let ((ticks (assoc (car type) marks))
1611 (new-marks
1612 (cdr (or (assoc (caddr type) flags) ; %Flagged
1613 (assoc (intern (cadr type) obarray) flags)
1614 (assoc (cadr type) flags))))) ; "\Flagged"
1615 (setq marks (delq ticks marks))
1616 (pop ticks)
1617 ;; Add the new marks we got.
1618 (setq ticks (gnus-add-to-range ticks new-marks))
1619 ;; Remove the marks from messages that don't have them.
1620 (setq ticks (gnus-remove-from-range
1621 ticks
1622 (gnus-compress-sequence
1623 (gnus-sorted-complement existing new-marks))))
1624 (when ticks
1625 (push (cons (car type) ticks) marks)))
1626 (gnus-info-set-marks info marks t))
1627 ;; Add vanished to the list of unexisting articles.
1628 (when vanished
1629 (let* ((old-unexists (assq 'unexist marks))
1630 (unexists (gnus-range-add (cdr old-unexists) vanished)))
1631 (if old-unexists
1632 (setcdr old-unexists unexists)
1633 (push (cons 'unexist unexists) marks)))
1634 (gnus-info-set-marks info marks t))))
1636 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1637 (if (zerop (length irange))
1639 (let ((result nil))
1640 (dolist (elem (split-string irange ","))
1641 (push
1642 (if (string-match ":" elem)
1643 (let ((numbers (split-string elem ":")))
1644 (cons (string-to-number (car numbers))
1645 (string-to-number (cadr numbers))))
1646 (string-to-number elem))
1647 result))
1648 (nreverse result))))
1650 (defun nnimap-store-info (info active)
1651 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1652 (entry (assoc group nnimap-current-infos)))
1653 (if entry
1654 (setcdr entry (list info active))
1655 (push (list group info active) nnimap-current-infos))))
1657 (defun nnimap-flags-to-marks (groups)
1658 (let (data group totalp uidnext articles start-article mark permanent-flags
1659 uidvalidity vanished highestmodseq)
1660 (dolist (elem groups)
1661 (setq group (car elem)
1662 uidnext (nth 1 elem)
1663 start-article (nth 2 elem)
1664 permanent-flags (nth 3 elem)
1665 uidvalidity (nth 4 elem)
1666 vanished (nth 5 elem)
1667 highestmodseq (nth 6 elem)
1668 articles (nthcdr 7 elem))
1669 (let ((high (caar articles))
1670 marks low existing)
1671 (dolist (article articles)
1672 (setq low (car article))
1673 (push (car article) existing)
1674 (dolist (flag (cdr article))
1675 (setq mark (assoc flag marks))
1676 (if (not mark)
1677 (push (list flag (car article)) marks)
1678 (setcdr mark (cons (car article) (cdr mark))))))
1679 (push (list group existing marks high low uidnext start-article
1680 permanent-flags uidvalidity vanished highestmodseq)
1681 data)))
1682 data))
1684 (defun nnimap-parse-flags (sequences)
1685 (goto-char (point-min))
1686 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1687 ;; read it.
1688 (subst-char-in-region (point-min) (point-max)
1689 ?\\ ?% t)
1690 ;; Remove any MODSEQ entries in the buffer, because they may contain
1691 ;; numbers that are too large for 32-bit Emacsen.
1692 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1693 (replace-match "" t t))
1694 (goto-char (point-min))
1695 (let (start end articles groups uidnext elems permanent-flags
1696 uidvalidity vanished highestmodseq)
1697 (dolist (elem sequences)
1698 (destructuring-bind (group-sequence flag-sequence totalp group command)
1699 elem
1700 (setq start (point))
1701 (when (and
1702 ;; The EXAMINE was successful.
1703 (search-forward (format "\n%d OK " group-sequence) nil t)
1704 (progn
1705 (forward-line 1)
1706 (setq end (point))
1707 (goto-char start)
1708 (setq permanent-flags
1709 (if (equal command "SELECT")
1710 (and (search-forward "PERMANENTFLAGS "
1711 (or end (point-min)) t)
1712 (read (current-buffer)))
1713 'not-scanned))
1714 (goto-char start)
1715 (setq uidnext
1716 (and (search-forward "UIDNEXT "
1717 (or end (point-min)) t)
1718 (read (current-buffer))))
1719 (goto-char start)
1720 (setq uidvalidity
1721 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1722 (or end (point-min)) t)
1723 ;; Store UIDVALIDITY as a string, as it's
1724 ;; too big for 32-bit Emacsen, usually.
1725 (match-string 1)))
1726 (goto-char start)
1727 (setq vanished
1728 (and (eq flag-sequence 'qresync)
1729 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1730 (or end (point-min)) t)
1731 (match-string 1)))
1732 (goto-char start)
1733 (setq highestmodseq
1734 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1735 (or end (point-min)) t)
1736 (match-string 1)))
1737 (goto-char end)
1738 (forward-line -1))
1739 ;; The UID FETCH FLAGS was successful.
1740 (or (eq flag-sequence 'qresync)
1741 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1742 (if (eq flag-sequence 'qresync)
1743 (progn
1744 (goto-char start)
1745 (setq start end))
1746 (setq start (point))
1747 (goto-char end))
1748 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1749 (let ((p (point)))
1750 (setq elems (read (current-buffer)))
1751 (push (cons (cadr (memq 'UID elems))
1752 (cadr (memq 'FLAGS elems)))
1753 articles)))
1754 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1755 vanished highestmodseq)
1756 articles)
1757 groups)
1758 (if (eq flag-sequence 'qresync)
1759 (goto-char end)
1760 (setq end (point)))
1761 (setq articles nil))))
1762 groups))
1764 (defun nnimap-find-process-buffer (buffer)
1765 (cadr (assoc buffer nnimap-connection-alist)))
1767 (deffoo nnimap-request-post (&optional server)
1768 (setq nnimap-status-string "Read-only server")
1769 nil)
1771 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1772 (declare-function gnus-fetch-headers "gnus-sum"
1773 (articles &optional limit force-new dependencies))
1775 (autoload 'nnir-search-thread "nnir")
1777 (deffoo nnimap-request-thread (header &optional group server)
1778 (when group
1779 (setq group (nnimap-decode-gnus-group group)))
1780 (if gnus-refer-thread-use-nnir
1781 (nnir-search-thread header)
1782 (when (nnimap-change-group group server)
1783 (let* ((cmd (nnimap-make-thread-query header))
1784 (result (with-current-buffer (nnimap-buffer)
1785 (nnimap-command "UID SEARCH %s" cmd))))
1786 (when result
1787 (gnus-fetch-headers
1788 (and (car result)
1789 (delete 0 (mapcar #'string-to-number
1790 (cdr (assoc "SEARCH" (cdr result))))))
1791 nil t))))))
1793 (defun nnimap-change-group (group &optional server no-reconnect read-only)
1794 "Change group to GROUP if non-nil.
1795 If SERVER is set, check that server is connected, otherwise retry
1796 to reconnect, unless NO-RECONNECT is set to t. Return nil if
1797 unsuccessful in connecting.
1798 If GROUP is nil, return t.
1799 If READ-ONLY is set, send EXAMINE rather than SELECT to the server.
1800 Return the server's response to the SELECT or EXAMINE command."
1801 (let ((open-result t))
1802 (when (and server
1803 (not (nnimap-server-opened server)))
1804 (setq open-result (nnimap-open-server server nil no-reconnect)))
1805 (cond
1806 ((not open-result)
1807 nil)
1808 ((not group)
1811 (with-current-buffer (nnimap-buffer)
1812 (let ((result (nnimap-command "%s %S"
1813 (if read-only
1814 "EXAMINE"
1815 "SELECT")
1816 (utf7-encode group t))))
1817 (when (car result)
1818 (setf (nnimap-group nnimap-object) group
1819 (nnimap-select-result nnimap-object) result)
1820 result)))))))
1822 (defun nnimap-find-connection (buffer)
1823 "Find the connection delivering to BUFFER."
1824 (let ((entry (assoc buffer nnimap-connection-alist)))
1825 (when entry
1826 (if (and (buffer-name (cadr entry))
1827 (get-buffer-process (cadr entry))
1828 (memq (process-status (get-buffer-process (cadr entry)))
1829 '(open run)))
1830 (get-buffer-process (cadr entry))
1831 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1832 nil))))
1834 (defvar nnimap-sequence 0)
1836 (defun nnimap-send-command (&rest args)
1837 (setf (nnimap-last-command-time nnimap-object) (current-time))
1838 (process-send-string
1839 (get-buffer-process (current-buffer))
1840 (nnimap-log-command
1841 (format "%d %s%s\n"
1842 (incf nnimap-sequence)
1843 (apply #'format args)
1844 (if (nnimap-newlinep nnimap-object)
1846 "\r"))))
1847 ;; Some servers apparently can't have many outstanding
1848 ;; commands, so throttle them.
1849 (unless nnimap-streaming
1850 (nnimap-wait-for-response nnimap-sequence))
1851 nnimap-sequence)
1853 (defvar nnimap-record-commands nil
1854 "If non-nil, log commands to the \"*imap log*\" buffer.")
1856 (defun nnimap-log-buffer ()
1857 (let ((name "*imap log*"))
1858 (or (get-buffer name)
1859 (with-current-buffer (get-buffer-create name)
1860 (when (boundp 'window-point-insertion-type)
1861 (make-local-variable 'window-point-insertion-type)
1862 (setq window-point-insertion-type t))
1863 (current-buffer)))))
1865 (defun nnimap-log-command (command)
1866 (when nnimap-record-commands
1867 (with-current-buffer (nnimap-log-buffer)
1868 (goto-char (point-max))
1869 (insert (format-time-string "%H:%M:%S")
1870 " [" nnimap-address "] "
1871 (if nnimap-inhibit-logging
1872 "(inhibited)\n"
1873 command))))
1874 command)
1876 (defun nnimap-command (&rest args)
1877 (erase-buffer)
1878 (let* ((sequence (apply #'nnimap-send-command args))
1879 (response (nnimap-get-response sequence)))
1880 (if (equal (caar response) "OK")
1881 (cons t response)
1882 (nnheader-report 'nnimap "%s"
1883 (mapconcat (lambda (a)
1884 (format "%s" a))
1885 (car response) " "))
1886 nil)))
1888 (defun nnimap-get-response (sequence)
1889 (nnimap-wait-for-response sequence)
1890 (nnimap-parse-response))
1892 (defun nnimap-wait-for-connection (&optional regexp)
1893 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1895 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1896 (let ((process (get-buffer-process (current-buffer))))
1897 (goto-char (point-min))
1898 (while (and (memq (process-status process)
1899 '(open run))
1900 (not (re-search-forward regexp nil t)))
1901 (nnheader-accept-process-output process)
1902 (goto-char (point-min)))
1903 (forward-line -1)
1904 (and (looking-at (or response-regexp regexp))
1905 (match-string 1))))
1907 (defun nnimap-wait-for-response (sequence &optional messagep)
1908 (let ((process (get-buffer-process (current-buffer)))
1909 openp)
1910 (condition-case nil
1911 (progn
1912 (goto-char (point-max))
1913 (while (and (setq openp (memq (process-status process)
1914 '(open run)))
1915 (progn
1916 ;; Skip past any "*" lines that the server has
1917 ;; output.
1918 (while (and (not (bobp))
1919 (progn
1920 (forward-line -1)
1921 (looking-at "\\*\\|[0-9]+ OK NOOP"))))
1922 (not (looking-at (format "%d .*\n" sequence)))))
1923 (when messagep
1924 (nnheader-message-maybe
1925 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1926 nnimap-address
1927 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1928 (format " (initial sync of %d group%s; please wait)"
1929 (nnimap-initial-resync nnimap-object)
1930 (if (= (nnimap-initial-resync nnimap-object) 1)
1932 "s"))
1933 "")))
1934 (nnheader-accept-process-output process)
1935 (goto-char (point-max)))
1936 (setf (nnimap-initial-resync nnimap-object) 0)
1937 openp)
1938 (quit
1939 (when debug-on-quit
1940 (debug "Quit"))
1941 ;; The user hit C-g while we were waiting: kill the process, in case
1942 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1943 ;; NAT routers).
1944 (delete-process process)
1945 nil))))
1947 (defun nnimap-parse-response ()
1948 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1949 result)
1950 (dolist (line lines)
1951 (push (cdr (nnimap-parse-line line)) result))
1952 ;; Return the OK/error code first, and then all the "continuation
1953 ;; lines" afterwards.
1954 (cons (pop result)
1955 (nreverse result))))
1957 ;; Parse an IMAP response line lightly. They look like
1958 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1959 ;; the lines into a list of strings and lists of string.
1960 (defun nnimap-parse-line (line)
1961 (let (char result)
1962 (with-temp-buffer
1963 (mm-disable-multibyte)
1964 (insert line)
1965 (goto-char (point-min))
1966 (while (not (eobp))
1967 (if (eql (setq char (following-char)) ? )
1968 (forward-char 1)
1969 (push
1970 (cond
1971 ((eql char ?\[)
1972 (split-string
1973 (buffer-substring
1974 (1+ (point))
1975 (if (search-forward "]" (line-end-position) 'move)
1976 (1- (point))
1977 (point)))))
1978 ((eql char ?\()
1979 (split-string
1980 (buffer-substring
1981 (1+ (point))
1982 (if (search-forward ")" (line-end-position) 'move)
1983 (1- (point))
1984 (point)))))
1985 ((eql char ?\")
1986 (forward-char 1)
1987 (buffer-substring
1988 (point)
1989 (1- (or (search-forward "\"" (line-end-position) 'move)
1990 (point)))))
1992 (buffer-substring (point) (if (search-forward " " nil t)
1993 (1- (point))
1994 (goto-char (point-max))))))
1995 result)))
1996 (nreverse result))))
1998 (defun nnimap-last-response-string ()
1999 (save-excursion
2000 (forward-line 1)
2001 (let ((end (point)))
2002 (forward-line -1)
2003 (when (not (bobp))
2004 (forward-line -1)
2005 (while (and (not (bobp))
2006 (eql (following-char) ?*))
2007 (forward-line -1))
2008 (unless (eql (following-char) ?*)
2009 (forward-line 1)))
2010 (buffer-substring (point) end))))
2012 (defvar nnimap-incoming-split-list nil)
2014 (defun nnimap-fetch-inbox (articles)
2015 (erase-buffer)
2016 (nnimap-wait-for-response
2017 (nnimap-send-command
2018 "UID FETCH %s %s"
2019 (nnimap-article-ranges articles)
2020 (format "(UID %s%s)"
2021 (format
2022 (if (nnimap-ver4-p)
2023 "BODY.PEEK"
2024 "RFC822.PEEK"))
2025 (cond
2026 (nnimap-split-download-body-default
2027 "[]")
2028 ((nnimap-ver4-p)
2029 "[HEADER]")
2031 "[1]"))))
2034 (defun nnimap-split-incoming-mail ()
2035 (with-current-buffer (nnimap-buffer)
2036 (let ((nnimap-incoming-split-list nil)
2037 (nnmail-split-methods
2038 (cond
2039 ((eq nnimap-split-methods 'default)
2040 nnmail-split-methods)
2041 (nnimap-split-methods
2042 nnimap-split-methods)
2043 (nnimap-split-fancy
2044 'nnmail-split-fancy)))
2045 (nnmail-split-fancy (or nnimap-split-fancy
2046 nnmail-split-fancy))
2047 (nnmail-inhibit-default-split-group t)
2048 (groups (nnimap-get-groups))
2049 new-articles)
2050 (erase-buffer)
2051 (nnimap-command "SELECT %S" nnimap-inbox)
2052 (setf (nnimap-group nnimap-object) nnimap-inbox)
2053 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
2054 (when new-articles
2055 (nnimap-fetch-inbox new-articles)
2056 (nnimap-transform-split-mail)
2057 (nnheader-ms-strip-cr)
2058 (nnmail-cache-open)
2059 (nnmail-split-incoming (current-buffer)
2060 #'nnimap-save-mail-spec
2061 nil nil
2062 #'nnimap-dummy-active-number
2063 #'nnimap-save-mail-spec)
2064 (when nnimap-incoming-split-list
2065 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
2066 sequences junk-articles)
2067 ;; Create any groups that doesn't already exist on the
2068 ;; server first.
2069 (dolist (spec specs)
2070 (when (and (not (member (car spec) groups))
2071 (not (eq (car spec) 'junk)))
2072 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
2073 ;; Then copy over all the messages.
2074 (erase-buffer)
2075 (dolist (spec specs)
2076 (let ((group (car spec))
2077 (ranges (cdr spec)))
2078 (if (eq group 'junk)
2079 (setq junk-articles ranges)
2080 (push (list (nnimap-send-command
2081 "UID COPY %s %S"
2082 (nnimap-article-ranges ranges)
2083 (utf7-encode group t))
2084 ranges)
2085 sequences))))
2086 ;; Wait for the last COPY response...
2087 (when sequences
2088 (nnimap-wait-for-response (caar sequences))
2089 ;; And then mark the successful copy actions as deleted,
2090 ;; and possibly expunge them.
2091 (nnimap-mark-and-expunge-incoming
2092 (nnimap-parse-copied-articles sequences)))
2093 (nnimap-mark-and-expunge-incoming junk-articles)))))))
2095 (defun nnimap-mark-and-expunge-incoming (range)
2096 (when range
2097 (setq range (nnimap-article-ranges range))
2098 (erase-buffer)
2099 (let ((sequence
2100 (nnimap-send-command
2101 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
2102 (cond
2103 ;; If the server supports it, we now delete the message we have
2104 ;; just copied over.
2105 ((nnimap-capability "UIDPLUS")
2106 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
2107 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
2108 ;; user has configured it.
2109 (nnimap-expunge
2110 (setq sequence (nnimap-send-command "EXPUNGE"))))
2111 (nnimap-wait-for-response sequence))))
2113 (defun nnimap-parse-copied-articles (sequences)
2114 (let (sequence copied range)
2115 (goto-char (point-min))
2116 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2117 (setq sequence (string-to-number (match-string 1)))
2118 (when (setq range (cadr (assq sequence sequences)))
2119 (push (gnus-uncompress-range range) copied)))
2120 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2122 (defun nnimap-new-articles (flags)
2123 (let (new)
2124 (dolist (elem flags)
2125 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2126 (cdr elem))
2127 (push (car elem) new)))
2128 (gnus-compress-sequence (nreverse new))))
2130 (defun nnimap-make-split-specs (list)
2131 (let ((specs nil)
2132 entry)
2133 (dolist (elem list)
2134 (destructuring-bind (article spec) elem
2135 (dolist (group (delete nil (mapcar #'car spec)))
2136 (unless (setq entry (assoc group specs))
2137 (push (setq entry (list group)) specs))
2138 (setcdr entry (cons article (cdr entry))))))
2139 (dolist (entry specs)
2140 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2141 specs))
2143 (defun nnimap-transform-split-mail ()
2144 (goto-char (point-min))
2145 (let (article bytes)
2146 (block nil
2147 (while (not (eobp))
2148 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2149 (delete-region (point) (progn (forward-line 1) (point)))
2150 (when (eobp)
2151 (return)))
2152 (setq article (match-string 1)
2153 bytes (nnimap-get-length))
2154 (delete-region (line-beginning-position) (line-end-position))
2155 ;; Insert MMDF separator, and a way to remember what this
2156 ;; article UID is.
2157 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2158 (forward-char (1+ bytes))
2159 (setq bytes (nnimap-get-length))
2160 (delete-region (line-beginning-position) (line-end-position))
2161 ;; There's a body; skip past that.
2162 (when bytes
2163 (forward-char (1+ bytes))
2164 (delete-region (line-beginning-position) (line-end-position)))))))
2166 (defun nnimap-dummy-active-number (group &optional server)
2169 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2170 (let (article)
2171 (goto-char (point-min))
2172 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2173 (error "Invalid nnimap mail")
2174 (setq article (string-to-number (match-string 1))))
2175 (push (list article
2176 (if (eq group-art 'junk)
2177 (list (cons 'junk 1))
2178 group-art))
2179 nnimap-incoming-split-list)))
2181 (defun nnimap-make-thread-query (header)
2182 (let* ((id (mail-header-id header))
2183 (refs (split-string
2184 (or (mail-header-references header)
2185 "")))
2186 (value
2187 (format
2188 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2189 id id)))
2190 (dolist (refid refs value)
2191 (setq value (format
2192 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2193 refid refid value)))))
2196 (provide 'nnimap)
2198 ;;; nnimap.el ends here