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