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