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