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