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