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