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