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