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