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