]> code.delx.au - gnu-emacs/blob - lisp/gnus/nnimap.el
Merge from emacs-24; up to 2012-12-06T01:39:03Z!monnier@iro.umontreal.ca
[gnu-emacs] / lisp / gnus / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2013 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 (or (not group) (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 (gnus-sorted-union
1424 (cdr (assoc '%Seen flags))
1425 (cdr (assoc '%Deleted flags))))
1426 (cdr (assoc '%Flagged flags)))))
1427 (read (gnus-range-difference
1428 (cons start-article high) unread)))
1429 (when (> start-article 1)
1430 (setq read
1431 (gnus-range-nconcat
1432 (if (> start-article 1)
1433 (gnus-sorted-range-intersection
1434 (cons 1 (1- start-article))
1435 (gnus-info-read info))
1436 (gnus-info-read info))
1437 read)))
1438 (when (or (not (listp permanent-flags))
1439 (memq '%Seen permanent-flags))
1440 (gnus-info-set-read info read))
1441 ;; Update the marks.
1442 (setq marks (gnus-info-marks info))
1443 (dolist (type (cdr nnimap-mark-alist))
1444 (when (or (not (listp permanent-flags))
1445 (memq (car (assoc (caddr type) flags))
1446 permanent-flags)
1447 (memq '%* permanent-flags))
1448 (let ((old-marks (assoc (car type) marks))
1449 (new-marks
1450 (gnus-compress-sequence
1451 (cdr (or (assoc (caddr type) flags) ; %Flagged
1452 (assoc (intern (cadr type) obarray) flags)
1453 (assoc (cadr type) flags)))))) ; "\Flagged"
1454 (setq marks (delq old-marks marks))
1455 (pop old-marks)
1456 (when (and old-marks
1457 (> start-article 1))
1458 (setq old-marks (gnus-range-difference
1459 old-marks
1460 (cons start-article high)))
1461 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1462 (when new-marks
1463 (push (cons (car type) new-marks) marks)))))
1464 (gnus-info-set-marks info marks t))))
1465 ;; Tell Gnus whether there are any \Recent messages in any of
1466 ;; the groups.
1467 (let ((recent (cdr (assoc '%Recent flags))))
1468 (when (and active
1469 recent
1470 (> (car (last recent)) (cdr active)))
1471 (push (list (cons (gnus-group-real-name group) 0))
1472 nnmail-split-history)))
1473 ;; Note the active level for the next run-through.
1474 (gnus-group-set-parameter info 'active (gnus-active group))
1475 (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1476 (gnus-group-set-parameter info 'modseq highestmodseq)
1477 (nnimap-store-info info (gnus-active group)))))))
1478
1479 (defun nnimap-update-qresync-info (info existing vanished flags)
1480 ;; Add all the vanished articles to the list of read articles.
1481 (gnus-info-set-read
1482 info
1483 (gnus-add-to-range
1484 (gnus-add-to-range
1485 (gnus-range-add (gnus-info-read info)
1486 vanished)
1487 (cdr (assq '%Flagged flags)))
1488 (cdr (assq '%Seen flags))))
1489 (let ((marks (gnus-info-marks info)))
1490 (dolist (type (cdr nnimap-mark-alist))
1491 (let ((ticks (assoc (car type) marks))
1492 (new-marks
1493 (cdr (or (assoc (caddr type) flags) ; %Flagged
1494 (assoc (intern (cadr type) obarray) flags)
1495 (assoc (cadr type) flags))))) ; "\Flagged"
1496 (setq marks (delq ticks marks))
1497 (pop ticks)
1498 ;; Add the new marks we got.
1499 (setq ticks (gnus-add-to-range ticks new-marks))
1500 ;; Remove the marks from messages that don't have them.
1501 (setq ticks (gnus-remove-from-range
1502 ticks
1503 (gnus-compress-sequence
1504 (gnus-sorted-complement existing new-marks))))
1505 (when ticks
1506 (push (cons (car type) ticks) marks)))
1507 (gnus-info-set-marks info marks t))))
1508
1509 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1510 (if (zerop (length irange))
1511 nil
1512 (let ((result nil))
1513 (dolist (elem (split-string irange ","))
1514 (push
1515 (if (string-match ":" elem)
1516 (let ((numbers (split-string elem ":")))
1517 (cons (string-to-number (car numbers))
1518 (string-to-number (cadr numbers))))
1519 (string-to-number elem))
1520 result))
1521 (nreverse result))))
1522
1523 (defun nnimap-store-info (info active)
1524 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1525 (entry (assoc group nnimap-current-infos)))
1526 (if entry
1527 (setcdr entry (list info active))
1528 (push (list group info active) nnimap-current-infos))))
1529
1530 (defun nnimap-flags-to-marks (groups)
1531 (let (data group totalp uidnext articles start-article mark permanent-flags
1532 uidvalidity vanished highestmodseq)
1533 (dolist (elem groups)
1534 (setq group (car elem)
1535 uidnext (nth 1 elem)
1536 start-article (nth 2 elem)
1537 permanent-flags (nth 3 elem)
1538 uidvalidity (nth 4 elem)
1539 vanished (nth 5 elem)
1540 highestmodseq (nth 6 elem)
1541 articles (nthcdr 7 elem))
1542 (let ((high (caar articles))
1543 marks low existing)
1544 (dolist (article articles)
1545 (setq low (car article))
1546 (push (car article) existing)
1547 (dolist (flag (cdr article))
1548 (setq mark (assoc flag marks))
1549 (if (not mark)
1550 (push (list flag (car article)) marks)
1551 (setcdr mark (cons (car article) (cdr mark))))))
1552 (push (list group existing marks high low uidnext start-article
1553 permanent-flags uidvalidity vanished highestmodseq)
1554 data)))
1555 data))
1556
1557 (defun nnimap-parse-flags (sequences)
1558 (goto-char (point-min))
1559 ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1560 ;; read it.
1561 (subst-char-in-region (point-min) (point-max)
1562 ?\\ ?% t)
1563 ;; Remove any MODSEQ entries in the buffer, because they may contain
1564 ;; numbers that are too large for 32-bit Emacsen.
1565 (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1566 (replace-match "" t t))
1567 (goto-char (point-min))
1568 (let (start end articles groups uidnext elems permanent-flags
1569 uidvalidity vanished highestmodseq)
1570 (dolist (elem sequences)
1571 (destructuring-bind (group-sequence flag-sequence totalp group command)
1572 elem
1573 (setq start (point))
1574 (when (and
1575 ;; The EXAMINE was successful.
1576 (search-forward (format "\n%d OK " group-sequence) nil t)
1577 (progn
1578 (forward-line 1)
1579 (setq end (point))
1580 (goto-char start)
1581 (setq permanent-flags
1582 (if (equal command "SELECT")
1583 (and (search-forward "PERMANENTFLAGS "
1584 (or end (point-min)) t)
1585 (read (current-buffer)))
1586 'not-scanned))
1587 (goto-char start)
1588 (setq uidnext
1589 (and (search-forward "UIDNEXT "
1590 (or end (point-min)) t)
1591 (read (current-buffer))))
1592 (goto-char start)
1593 (setq uidvalidity
1594 (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1595 (or end (point-min)) t)
1596 ;; Store UIDVALIDITY as a string, as it's
1597 ;; too big for 32-bit Emacsen, usually.
1598 (match-string 1)))
1599 (goto-char start)
1600 (setq vanished
1601 (and (eq flag-sequence 'qresync)
1602 (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1603 (or end (point-min)) t)
1604 (match-string 1)))
1605 (goto-char start)
1606 (setq highestmodseq
1607 (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1608 (or end (point-min)) t)
1609 (match-string 1)))
1610 (goto-char end)
1611 (forward-line -1))
1612 ;; The UID FETCH FLAGS was successful.
1613 (or (eq flag-sequence 'qresync)
1614 (search-forward (format "\n%d OK " flag-sequence) nil t)))
1615 (if (eq flag-sequence 'qresync)
1616 (progn
1617 (goto-char start)
1618 (setq start end))
1619 (setq start (point))
1620 (goto-char end))
1621 (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1622 (let ((p (point)))
1623 (setq elems (read (current-buffer)))
1624 (push (cons (cadr (memq 'UID elems))
1625 (cadr (memq 'FLAGS elems)))
1626 articles)))
1627 (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1628 vanished highestmodseq)
1629 articles)
1630 groups)
1631 (if (eq flag-sequence 'qresync)
1632 (goto-char end)
1633 (setq end (point)))
1634 (setq articles nil))))
1635 groups))
1636
1637 (defun nnimap-find-process-buffer (buffer)
1638 (cadr (assoc buffer nnimap-connection-alist)))
1639
1640 (deffoo nnimap-request-post (&optional server)
1641 (setq nnimap-status-string "Read-only server")
1642 nil)
1643
1644 (declare-function gnus-fetch-headers "gnus-sum"
1645 (articles &optional limit force-new dependencies))
1646
1647 (autoload 'nnir-search-thread "nnir")
1648
1649 (deffoo nnimap-request-thread (header &optional group server)
1650 (when group
1651 (setq group (nnimap-decode-gnus-group group)))
1652 (if gnus-refer-thread-use-nnir
1653 (nnir-search-thread header)
1654 (when (nnimap-possibly-change-group group server)
1655 (let* ((cmd (nnimap-make-thread-query header))
1656 (result (with-current-buffer (nnimap-buffer)
1657 (nnimap-command "UID SEARCH %s" cmd))))
1658 (when result
1659 (gnus-fetch-headers
1660 (and (car result)
1661 (delete 0 (mapcar #'string-to-number
1662 (cdr (assoc "SEARCH" (cdr result))))))
1663 nil t))))))
1664
1665 (defun nnimap-possibly-change-group (group server &optional no-reconnect)
1666 (let ((open-result t))
1667 (when (and server
1668 (not (nnimap-server-opened server)))
1669 (setq open-result (nnimap-open-server server nil no-reconnect)))
1670 (cond
1671 ((not open-result)
1672 nil)
1673 ((not group)
1674 t)
1675 (t
1676 (with-current-buffer (nnimap-buffer)
1677 (if (equal group (nnimap-group nnimap-object))
1678 t
1679 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1680 (when (car result)
1681 (setf (nnimap-group nnimap-object) group
1682 (nnimap-select-result nnimap-object) result)
1683 result))))))))
1684
1685 (defun nnimap-find-connection (buffer)
1686 "Find the connection delivering to BUFFER."
1687 (let ((entry (assoc buffer nnimap-connection-alist)))
1688 (when entry
1689 (if (and (buffer-name (cadr entry))
1690 (get-buffer-process (cadr entry))
1691 (memq (process-status (get-buffer-process (cadr entry)))
1692 '(open run)))
1693 (get-buffer-process (cadr entry))
1694 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1695 nil))))
1696
1697 (defvar nnimap-sequence 0)
1698
1699 (defun nnimap-send-command (&rest args)
1700 (setf (nnimap-last-command-time nnimap-object) (current-time))
1701 (process-send-string
1702 (get-buffer-process (current-buffer))
1703 (nnimap-log-command
1704 (format "%d %s%s\n"
1705 (incf nnimap-sequence)
1706 (apply #'format args)
1707 (if (nnimap-newlinep nnimap-object)
1708 ""
1709 "\r"))))
1710 ;; Some servers apparently can't have many outstanding
1711 ;; commands, so throttle them.
1712 (unless nnimap-streaming
1713 (nnimap-wait-for-response nnimap-sequence))
1714 nnimap-sequence)
1715
1716 (defvar nnimap-record-commands nil
1717 "If non-nil, log commands to the \"*imap log*\" buffer.")
1718
1719 (defun nnimap-log-command (command)
1720 (when nnimap-record-commands
1721 (with-current-buffer (get-buffer-create "*imap log*")
1722 (goto-char (point-max))
1723 (insert (format-time-string "%H:%M:%S")
1724 " [" nnimap-address "] "
1725 (if nnimap-inhibit-logging
1726 "(inhibited)\n"
1727 command))))
1728 command)
1729
1730 (defun nnimap-command (&rest args)
1731 (erase-buffer)
1732 (let* ((sequence (apply #'nnimap-send-command args))
1733 (response (nnimap-get-response sequence)))
1734 (if (equal (caar response) "OK")
1735 (cons t response)
1736 (nnheader-report 'nnimap "%s"
1737 (mapconcat (lambda (a)
1738 (format "%s" a))
1739 (car response) " "))
1740 nil)))
1741
1742 (defun nnimap-get-response (sequence)
1743 (nnimap-wait-for-response sequence)
1744 (nnimap-parse-response))
1745
1746 (defun nnimap-wait-for-connection (&optional regexp)
1747 (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1748
1749 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1750 (let ((process (get-buffer-process (current-buffer))))
1751 (goto-char (point-min))
1752 (while (and (memq (process-status process)
1753 '(open run))
1754 (not (re-search-forward regexp nil t)))
1755 (nnheader-accept-process-output process)
1756 (goto-char (point-min)))
1757 (forward-line -1)
1758 (and (looking-at (or response-regexp regexp))
1759 (match-string 1))))
1760
1761 (defun nnimap-wait-for-response (sequence &optional messagep)
1762 (let ((process (get-buffer-process (current-buffer)))
1763 openp)
1764 (condition-case nil
1765 (progn
1766 (goto-char (point-max))
1767 (while (and (setq openp (memq (process-status process)
1768 '(open run)))
1769 (progn
1770 ;; Skip past any "*" lines that the server has
1771 ;; output.
1772 (while (and (not (bobp))
1773 (progn
1774 (forward-line -1)
1775 (looking-at "\\*"))))
1776 (not (looking-at (format "%d .*\n" sequence)))))
1777 (when messagep
1778 (nnheader-message-maybe
1779 7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1780 nnimap-address
1781 (if (not (zerop (nnimap-initial-resync nnimap-object)))
1782 (format " (initial sync of %d group%s; please wait)"
1783 (nnimap-initial-resync nnimap-object)
1784 (if (= (nnimap-initial-resync nnimap-object) 1)
1785 ""
1786 "s"))
1787 "")))
1788 (nnheader-accept-process-output process)
1789 (goto-char (point-max)))
1790 (setf (nnimap-initial-resync nnimap-object) 0)
1791 openp)
1792 (quit
1793 (when debug-on-quit
1794 (debug "Quit"))
1795 ;; The user hit C-g while we were waiting: kill the process, in case
1796 ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1797 ;; NAT routers).
1798 (delete-process process)
1799 nil))))
1800
1801 (defun nnimap-parse-response ()
1802 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1803 result)
1804 (dolist (line lines)
1805 (push (cdr (nnimap-parse-line line)) result))
1806 ;; Return the OK/error code first, and then all the "continuation
1807 ;; lines" afterwards.
1808 (cons (pop result)
1809 (nreverse result))))
1810
1811 ;; Parse an IMAP response line lightly. They look like
1812 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1813 ;; the lines into a list of strings and lists of string.
1814 (defun nnimap-parse-line (line)
1815 (let (char result)
1816 (with-temp-buffer
1817 (mm-disable-multibyte)
1818 (insert line)
1819 (goto-char (point-min))
1820 (while (not (eobp))
1821 (if (eql (setq char (following-char)) ? )
1822 (forward-char 1)
1823 (push
1824 (cond
1825 ((eql char ?\[)
1826 (split-string
1827 (buffer-substring
1828 (1+ (point))
1829 (if (search-forward "]" (line-end-position) 'move)
1830 (1- (point))
1831 (point)))))
1832 ((eql char ?\()
1833 (split-string
1834 (buffer-substring
1835 (1+ (point))
1836 (if (search-forward ")" (line-end-position) 'move)
1837 (1- (point))
1838 (point)))))
1839 ((eql char ?\")
1840 (forward-char 1)
1841 (buffer-substring
1842 (point)
1843 (1- (or (search-forward "\"" (line-end-position) 'move)
1844 (point)))))
1845 (t
1846 (buffer-substring (point) (if (search-forward " " nil t)
1847 (1- (point))
1848 (goto-char (point-max))))))
1849 result)))
1850 (nreverse result))))
1851
1852 (defun nnimap-last-response-string ()
1853 (save-excursion
1854 (forward-line 1)
1855 (let ((end (point)))
1856 (forward-line -1)
1857 (when (not (bobp))
1858 (forward-line -1)
1859 (while (and (not (bobp))
1860 (eql (following-char) ?*))
1861 (forward-line -1))
1862 (unless (eql (following-char) ?*)
1863 (forward-line 1)))
1864 (buffer-substring (point) end))))
1865
1866 (defun nnimap-get-responses (sequences)
1867 (let (responses)
1868 (dolist (sequence sequences)
1869 (goto-char (point-min))
1870 (when (re-search-forward (format "^%d " sequence) nil t)
1871 (push (list sequence (nnimap-parse-response))
1872 responses)))
1873 responses))
1874
1875 (defvar nnimap-incoming-split-list nil)
1876
1877 (defun nnimap-fetch-inbox (articles)
1878 (erase-buffer)
1879 (nnimap-wait-for-response
1880 (nnimap-send-command
1881 "UID FETCH %s %s"
1882 (nnimap-article-ranges articles)
1883 (format "(UID %s%s)"
1884 (format
1885 (if (nnimap-ver4-p)
1886 "BODY.PEEK"
1887 "RFC822.PEEK"))
1888 (cond
1889 (nnimap-split-download-body-default
1890 "[]")
1891 ((nnimap-ver4-p)
1892 "[HEADER]")
1893 (t
1894 "[1]"))))
1895 t))
1896
1897 (defun nnimap-split-incoming-mail ()
1898 (with-current-buffer (nnimap-buffer)
1899 (let ((nnimap-incoming-split-list nil)
1900 (nnmail-split-methods
1901 (cond
1902 ((eq nnimap-split-methods 'default)
1903 nnmail-split-methods)
1904 (nnimap-split-methods
1905 nnimap-split-methods)
1906 (nnimap-split-fancy
1907 'nnmail-split-fancy)))
1908 (nnmail-split-fancy (or nnimap-split-fancy
1909 nnmail-split-fancy))
1910 (nnmail-inhibit-default-split-group t)
1911 (groups (nnimap-get-groups))
1912 new-articles)
1913 (erase-buffer)
1914 (nnimap-command "SELECT %S" nnimap-inbox)
1915 (setf (nnimap-group nnimap-object) nnimap-inbox)
1916 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1917 (when new-articles
1918 (nnimap-fetch-inbox new-articles)
1919 (nnimap-transform-split-mail)
1920 (nnheader-ms-strip-cr)
1921 (nnmail-cache-open)
1922 (nnmail-split-incoming (current-buffer)
1923 #'nnimap-save-mail-spec
1924 nil nil
1925 #'nnimap-dummy-active-number
1926 #'nnimap-save-mail-spec)
1927 (when nnimap-incoming-split-list
1928 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1929 sequences junk-articles)
1930 ;; Create any groups that doesn't already exist on the
1931 ;; server first.
1932 (dolist (spec specs)
1933 (when (and (not (member (car spec) groups))
1934 (not (eq (car spec) 'junk)))
1935 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1936 ;; Then copy over all the messages.
1937 (erase-buffer)
1938 (dolist (spec specs)
1939 (let ((group (car spec))
1940 (ranges (cdr spec)))
1941 (if (eq group 'junk)
1942 (setq junk-articles ranges)
1943 (push (list (nnimap-send-command
1944 "UID COPY %s %S"
1945 (nnimap-article-ranges ranges)
1946 (utf7-encode group t))
1947 ranges)
1948 sequences))))
1949 ;; Wait for the last COPY response...
1950 (when sequences
1951 (nnimap-wait-for-response (caar sequences))
1952 ;; And then mark the successful copy actions as deleted,
1953 ;; and possibly expunge them.
1954 (nnimap-mark-and-expunge-incoming
1955 (nnimap-parse-copied-articles sequences)))
1956 (nnimap-mark-and-expunge-incoming junk-articles)))))))
1957
1958 (defun nnimap-mark-and-expunge-incoming (range)
1959 (when range
1960 (setq range (nnimap-article-ranges range))
1961 (erase-buffer)
1962 (let ((sequence
1963 (nnimap-send-command
1964 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1965 (cond
1966 ;; If the server supports it, we now delete the message we have
1967 ;; just copied over.
1968 ((nnimap-capability "UIDPLUS")
1969 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1970 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1971 ;; user has configured it.
1972 (nnimap-expunge
1973 (setq sequence (nnimap-send-command "EXPUNGE"))))
1974 (nnimap-wait-for-response sequence))))
1975
1976 (defun nnimap-parse-copied-articles (sequences)
1977 (let (sequence copied range)
1978 (goto-char (point-min))
1979 (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
1980 (setq sequence (string-to-number (match-string 1)))
1981 (when (setq range (cadr (assq sequence sequences)))
1982 (push (gnus-uncompress-range range) copied)))
1983 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1984
1985 (defun nnimap-new-articles (flags)
1986 (let (new)
1987 (dolist (elem flags)
1988 (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1989 (cdr elem))
1990 (push (car elem) new)))
1991 (gnus-compress-sequence (nreverse new))))
1992
1993 (defun nnimap-make-split-specs (list)
1994 (let ((specs nil)
1995 entry)
1996 (dolist (elem list)
1997 (destructuring-bind (article spec) elem
1998 (dolist (group (delete nil (mapcar #'car spec)))
1999 (unless (setq entry (assoc group specs))
2000 (push (setq entry (list group)) specs))
2001 (setcdr entry (cons article (cdr entry))))))
2002 (dolist (entry specs)
2003 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2004 specs))
2005
2006 (defun nnimap-transform-split-mail ()
2007 (goto-char (point-min))
2008 (let (article bytes)
2009 (block nil
2010 (while (not (eobp))
2011 (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2012 (delete-region (point) (progn (forward-line 1) (point)))
2013 (when (eobp)
2014 (return)))
2015 (setq article (match-string 1)
2016 bytes (nnimap-get-length))
2017 (delete-region (line-beginning-position) (line-end-position))
2018 ;; Insert MMDF separator, and a way to remember what this
2019 ;; article UID is.
2020 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2021 (forward-char (1+ bytes))
2022 (setq bytes (nnimap-get-length))
2023 (delete-region (line-beginning-position) (line-end-position))
2024 ;; There's a body; skip past that.
2025 (when bytes
2026 (forward-char (1+ bytes))
2027 (delete-region (line-beginning-position) (line-end-position)))))))
2028
2029 (defun nnimap-dummy-active-number (group &optional server)
2030 1)
2031
2032 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2033 (let (article)
2034 (goto-char (point-min))
2035 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2036 (error "Invalid nnimap mail")
2037 (setq article (string-to-number (match-string 1))))
2038 (push (list article
2039 (if (eq group-art 'junk)
2040 (list (cons 'junk 1))
2041 group-art))
2042 nnimap-incoming-split-list)))
2043
2044 (defun nnimap-make-thread-query (header)
2045 (let* ((id (mail-header-id header))
2046 (refs (split-string
2047 (or (mail-header-references header)
2048 "")))
2049 (value
2050 (format
2051 "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2052 id id)))
2053 (dolist (refid refs value)
2054 (setq value (format
2055 "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2056 refid refid value)))))
2057
2058
2059 (provide 'nnimap)
2060
2061 ;;; nnimap.el ends here