Merge changes made in Gnus trunk.
[bpt/emacs.git] / lisp / gnus / nnimap.el
CommitLineData
20a673b2 1;;; nnimap.el --- IMAP interface for Gnus
e84b4b86 2
20a673b2 3;; Copyright (C) 2010 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
aa8f8277 29(eval-and-compile
20a673b2 30 (require 'nnheader))
aa8f8277 31
20a673b2
KY
32(eval-when-compile
33 (require 'cl))
c113de23 34
f58208b1
LMI
35(require 'nnheader)
36(require 'gnus-util)
37(require 'gnus)
38(require 'nnoo)
20a673b2 39(require 'netrc)
14db1c41 40(require 'utf7)
6b958814 41(require 'tls)
0617bb00 42(require 'parse-time)
e952b711 43
635be05a
KY
44(autoload 'auth-source-forget-user-or-password "auth-source")
45(autoload 'auth-source-user-or-password "auth-source")
46
c113de23
GM
47(nnoo-declare nnimap)
48
c113de23 49(defvoo nnimap-address nil
20a673b2 50 "The address of the IMAP server.")
c113de23
GM
51
52(defvoo nnimap-server-port nil
20a673b2
KY
53 "The IMAP port used.
54If nnimap-stream is `ssl', this will default to `imaps'. If not,
55it will default to `imap'.")
56
57(defvoo nnimap-stream 'ssl
58 "How nnimap will talk to the IMAP server.
b1ae92ba 59Values are `ssl', `network', `starttls' or `shell'.")
20a673b2
KY
60
61(defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
62 (if (listp imap-shell-program)
63 (car imap-shell-program)
64 imap-shell-program)
65 "ssh %s imapd"))
66
67(defvoo nnimap-inbox nil
68 "The mail box where incoming mail arrives and should be split out of.")
69
8ccbef23
G
70(defvoo nnimap-split-methods nil
71 "How mail is split.
72Uses the same syntax as nnmail-split-methods")
73
6b958814
G
74(defvoo nnimap-split-fancy nil
75 "Uses the same syntax as nnmail-split-fancy.")
76
229b59da 77(make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
6b958814 78 "Emacs 24.1")
229b59da 79
bdaa75c7
LMI
80(defvoo nnimap-authenticator nil
81 "How nnimap authenticate itself to the server.
82Possible choices are nil (use default methods) or `anonymous'.")
83
b069e5a6
G
84(defvoo nnimap-expunge t
85 "If non-nil, expunge articles after deleting them.
86This is always done if the server supports UID EXPUNGE, but it's
87not done by default on servers that doesn't support that command.")
88
8ccbef23
G
89(defvoo nnimap-streaming t
90 "If non-nil, try to use streaming commands with IMAP servers.
91Switching this off will make nnimap slower, but it helps with
92some servers.")
0617bb00 93
20a673b2 94(defvoo nnimap-connection-alist nil)
286c4fc2
LMI
95
96(defvoo nnimap-current-infos nil)
97
9f2d52e7
G
98(defvoo nnimap-fetch-partial-articles nil
99 "If non-nil, Gnus will fetch partial articles.
100If t, nnimap will fetch only the first part. If a string, it
101will fetch all parts that have types that match that string. A
102likely value would be \"text/\" to automatically fetch all
103textual parts.")
104
20a673b2
KY
105(defvar nnimap-process nil)
106
107(defvar nnimap-status-string "")
23f87bed
MB
108
109(defvar nnimap-split-download-body-default nil
110 "Internal variable with default value for `nnimap-split-download-body'.")
111
61b1af82
G
112(defvar nnimap-keepalive-timer nil)
113(defvar nnimap-process-buffers nil)
114
20a673b2 115(defstruct nnimap
61b1af82 116 group process commands capabilities select-result newlinep server
4478e074 117 last-command-time greeting)
c113de23 118
20a673b2
KY
119(defvar nnimap-object nil)
120
121(defvar nnimap-mark-alist
b069e5a6
G
122 '((read "\\Seen" %Seen)
123 (tick "\\Flagged" %Flagged)
124 (reply "\\Answered" %Answered)
20a673b2
KY
125 (expire "gnus-expire")
126 (dormant "gnus-dormant")
127 (score "gnus-score")
128 (save "gnus-save")
129 (download "gnus-download")
130 (forward "gnus-forward")))
131
20a673b2
KY
132(defun nnimap-buffer ()
133 (nnimap-find-process-buffer nntp-server-buffer))
134
286c4fc2 135(deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
c113de23 136 (with-current-buffer nntp-server-buffer
20a673b2
KY
137 (erase-buffer)
138 (when (nnimap-possibly-change-group group server)
139 (with-current-buffer (nnimap-buffer)
20a673b2
KY
140 (erase-buffer)
141 (nnimap-wait-for-response
142 (nnimap-send-command
143 "UID FETCH %s %s"
144 (nnimap-article-ranges (gnus-compress-sequence articles))
145 (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
146 (format
8ccbef23 147 (if (nnimap-ver4-p)
20a673b2
KY
148 "BODY.PEEK[HEADER.FIELDS %s]"
149 "RFC822.HEADER.LINES %s")
150 (append '(Subject From Date Message-Id
151 References In-Reply-To Xref)
152 nnmail-extra-headers))))
153 t)
154 (nnimap-transform-headers))
155 (insert-buffer-substring
156 (nnimap-find-process-buffer (current-buffer))))
b1ae92ba 157 'headers))
20a673b2
KY
158
159(defun nnimap-transform-headers ()
160 (goto-char (point-min))
b1ae92ba 161 (let (article bytes lines size string)
20a673b2
KY
162 (block nil
163 (while (not (eobp))
164 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
165 (delete-region (point) (progn (forward-line 1) (point)))
166 (when (eobp)
167 (return)))
b1ae92ba
G
168 (setq article (match-string 1))
169 ;; Unfold quoted {number} strings.
170 (while (re-search-forward "[^]] {\\([0-9]+\\)}\r\n"
171 (1+ (line-end-position)) t)
172 (setq size (string-to-number (match-string 1)))
173 (delete-region (+ (match-beginning 0) 2) (point))
174 (setq string (delete-region (point) (+ (point) size)))
175 (insert (format "%S" string)))
176 (setq bytes (nnimap-get-length)
20a673b2
KY
177 lines nil)
178 (beginning-of-line)
a46359d4
LMI
179 (setq size
180 (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
181 (line-end-position)
182 t)
183 (match-string 1)))
184 (beginning-of-line)
20a673b2 185 (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
b1ae92ba
G
186 (let ((structure (ignore-errors
187 (read (current-buffer)))))
20a673b2
KY
188 (while (and (consp structure)
189 (not (stringp (car structure))))
190 (setq structure (car structure)))
191 (setq lines (nth 7 structure))))
192 (delete-region (line-beginning-position) (line-end-position))
193 (insert (format "211 %s Article retrieved." article))
194 (forward-line 1)
a46359d4
LMI
195 (when size
196 (insert (format "Chars: %s\n" size)))
20a673b2
KY
197 (when lines
198 (insert (format "Lines: %s\n" lines)))
199 (re-search-forward "^\r$")
200 (delete-region (line-beginning-position) (line-end-position))
201 (insert ".")
202 (forward-line 1)))))
203
204(defun nnimap-get-length ()
205 (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
206 (string-to-number (match-string 1))))
207
208(defun nnimap-article-ranges (ranges)
209 (let (result)
210 (cond
211 ((numberp ranges)
212 (number-to-string ranges))
213 ((numberp (cdr ranges))
214 (format "%d:%d" (car ranges) (cdr ranges)))
215 (t
216 (dolist (elem ranges)
217 (push
218 (if (consp elem)
219 (format "%d:%d" (car elem) (cdr elem))
220 (number-to-string elem))
221 result))
222 (mapconcat #'identity (nreverse result) ",")))))
223
286c4fc2 224(deffoo nnimap-open-server (server &optional defs)
c113de23
GM
225 (if (nnimap-server-opened server)
226 t
c113de23 227 (unless (assq 'nnimap-address defs)
20a673b2 228 (setq defs (append defs (list (list 'nnimap-address server)))))
c113de23 229 (nnoo-change-server 'nnimap server defs)
20a673b2
KY
230 (or (nnimap-find-connection nntp-server-buffer)
231 (nnimap-open-connection nntp-server-buffer))))
232
233(defun nnimap-make-process-buffer (buffer)
234 (with-current-buffer
235 (generate-new-buffer (format "*nnimap %s %s %s*"
236 nnimap-address nnimap-server-port
237 (gnus-buffer-exists-p buffer)))
238 (mm-disable-multibyte)
239 (buffer-disable-undo)
240 (gnus-add-buffer)
241 (set (make-local-variable 'after-change-functions) nil)
b069e5a6
G
242 (set (make-local-variable 'nnimap-object)
243 (make-nnimap :server (nnoo-current-server 'nnimap)))
20a673b2 244 (push (list buffer (current-buffer)) nnimap-connection-alist)
61b1af82 245 (push (current-buffer) nnimap-process-buffers)
20a673b2
KY
246 (current-buffer)))
247
248(defun nnimap-open-shell-stream (name buffer host port)
e8861cd2
LMI
249 (let ((process-connection-type nil))
250 (start-process name buffer shell-file-name
251 shell-command-switch
252 (format-spec
253 nnimap-shell-program
254 (format-spec-make
255 ?s host
256 ?p port)))))
20a673b2 257
2696d88f 258(defun nnimap-credentials (address ports &optional inhibit-create)
286c4fc2
LMI
259 (let (port credentials)
260 ;; Request the credentials from all ports, but only query on the
261 ;; last port if all the previous ones have failed.
262 (while (and (null credentials)
263 (setq port (pop ports)))
264 (setq credentials
265 (auth-source-user-or-password
2696d88f
G
266 '("login" "password") address port nil
267 (if inhibit-create
268 nil
269 (null ports)))))
286c4fc2
LMI
270 credentials))
271
61b1af82
G
272(defun nnimap-keepalive ()
273 (let ((now (current-time)))
274 (dolist (buffer nnimap-process-buffers)
275 (when (buffer-name buffer)
276 (with-current-buffer buffer
277 (when (and nnimap-object
278 (nnimap-last-command-time nnimap-object)
279 (> (time-to-seconds
280 (time-subtract
281 now
282 (nnimap-last-command-time nnimap-object)))
283 ;; More than five minutes since the last command.
284 (* 5 60)))
285 (nnimap-send-command "NOOP")))))))
286
20a673b2 287(defun nnimap-open-connection (buffer)
61b1af82
G
288 (unless nnimap-keepalive-timer
289 (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
290 'nnimap-keepalive)))
9f2d52e7
G
291 (block nil
292 (with-current-buffer (nnimap-make-process-buffer buffer)
293 (let* ((coding-system-for-read 'binary)
294 (coding-system-for-write 'binary)
295 (port nil)
296 (ports
297 (cond
298 ((eq nnimap-stream 'network)
299 (open-network-stream
300 "*nnimap*" (current-buffer) nnimap-address
301 (setq port
302 (or nnimap-server-port
303 (if (netrc-find-service-number "imap")
304 "imap"
305 "143"))))
306 '("143" "imap"))
307 ((eq nnimap-stream 'shell)
308 (nnimap-open-shell-stream
309 "*nnimap*" (current-buffer) nnimap-address
310 (setq port (or nnimap-server-port "imap")))
311 '("imap"))
312 ((eq nnimap-stream 'starttls)
6b958814
G
313 (let ((tls-program (nnimap-extend-tls-programs)))
314 (open-tls-stream
315 "*nnimap*" (current-buffer) nnimap-address
316 (setq port (or nnimap-server-port "imap"))
317 'starttls))
9f2d52e7 318 '("imap"))
71e691a5 319 ((memq nnimap-stream '(ssl tls))
9f2d52e7
G
320 (open-tls-stream
321 "*nnimap*" (current-buffer) nnimap-address
322 (setq port
323 (or nnimap-server-port
324 (if (netrc-find-service-number "imaps")
325 "imaps"
326 "993"))))
71e691a5
G
327 '("143" "993" "imap" "imaps"))
328 (t
329 (error "Unknown stream type: %s" nnimap-stream))))
9f2d52e7
G
330 connection-result login-result credentials)
331 (setf (nnimap-process nnimap-object)
332 (get-buffer-process (current-buffer)))
333 (if (not (and (nnimap-process nnimap-object)
334 (memq (process-status (nnimap-process nnimap-object))
335 '(open run))))
336 (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
337 nnimap-address port nnimap-stream)
338 (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
339 (if (not (setq connection-result (nnimap-wait-for-connection)))
340 (nnheader-report 'nnimap
341 "%s" (buffer-substring
342 (point) (line-end-position)))
343 ;; Store the greeting (for debugging purposes).
344 (setf (nnimap-greeting nnimap-object)
345 (buffer-substring (line-beginning-position)
346 (line-end-position)))
347 ;; Store the capabilities.
20a673b2
KY
348 (setf (nnimap-capabilities nnimap-object)
349 (mapcar
350 #'upcase
9f2d52e7
G
351 (nnimap-find-parameter
352 "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
9f2d52e7
G
353 (when nnimap-server-port
354 (push (format "%s" nnimap-server-port) ports))
6b958814
G
355 ;; If this is a STARTTLS-capable server, then sever the
356 ;; connection and start a STARTTLS connection instead.
357 (when (and (eq nnimap-stream 'network)
358 (member "STARTTLS" (nnimap-capabilities nnimap-object)))
359 (let ((nnimap-stream 'starttls))
360 (let ((tls-process
361 (nnimap-open-connection buffer)))
362 ;; If the STARTTLS connection was successful, we
363 ;; kill our first non-encrypted connection. If it
364 ;; wasn't successful, we just use our unencrypted
365 ;; connection.
366 (when (memq (process-status tls-process) '(open run))
367 (delete-process (nnimap-process nnimap-object))
368 (kill-buffer (current-buffer))
369 (return tls-process)))))
9f2d52e7
G
370 (unless (equal connection-result "PREAUTH")
371 (if (not (setq credentials
372 (if (eq nnimap-authenticator 'anonymous)
373 (list "anonymous"
374 (message-make-address))
375 (or
376 ;; First look for the credentials based
377 ;; on the virtual server name.
378 (nnimap-credentials
379 (nnoo-current-server 'nnimap) ports t)
380 ;; Then look them up based on the
381 ;; physical address.
382 (nnimap-credentials nnimap-address ports)))))
383 (setq nnimap-object nil)
384 (setq login-result (nnimap-command "LOGIN %S %S"
385 (car credentials)
386 (cadr credentials)))
387 (unless (car login-result)
388 ;; If the login failed, then forget the credentials
389 ;; that are now possibly cached.
390 (dolist (host (list (nnoo-current-server 'nnimap)
391 nnimap-address))
392 (dolist (port ports)
393 (dolist (element '("login" "password"))
394 (auth-source-forget-user-or-password
395 element host port))))
396 (delete-process (nnimap-process nnimap-object))
397 (setq nnimap-object nil))))
398 (when nnimap-object
399 (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
400 (nnimap-command "ENABLE QRESYNC"))
6b958814
G
401 (nnimap-process nnimap-object))))))))
402
403(defun nnimap-extend-tls-programs ()
404 (let ((programs tls-program)
405 result)
406 (unless (consp programs)
407 (setq programs (list programs)))
408 (dolist (program programs)
aecb42aa
LMI
409 (when (assoc (car (split-string program)) tls-starttls-switches)
410 (push (if (not (string-match "%s" program))
411 (concat program " " "%s")
412 program)
413 result)))
6b958814 414 (nreverse result)))
20a673b2
KY
415
416(defun nnimap-find-parameter (parameter elems)
417 (let (result)
418 (dolist (elem elems)
419 (cond
420 ((equal (car elem) parameter)
421 (setq result (cdr elem)))
422 ((and (equal (car elem) "OK")
423 (consp (cadr elem))
424 (equal (caadr elem) parameter))
425 (setq result (cdr (cadr elem))))))
426 result))
427
286c4fc2 428(deffoo nnimap-close-server (&optional server)
71e691a5
G
429 (when (nnoo-change-server 'nnimap server nil)
430 (ignore-errors
431 (delete-process (get-buffer-process (nnimap-buffer))))
432 t))
c113de23 433
286c4fc2 434(deffoo nnimap-request-close ()
20a673b2 435 t)
23f87bed 436
286c4fc2 437(deffoo nnimap-server-opened (&optional server)
20a673b2
KY
438 (and (nnoo-current-server-p 'nnimap server)
439 nntp-server-buffer
440 (gnus-buffer-live-p nntp-server-buffer)
441 (nnimap-find-connection nntp-server-buffer)))
c113de23 442
286c4fc2 443(deffoo nnimap-status-message (&optional server)
20a673b2 444 nnimap-status-string)
c113de23 445
286c4fc2 446(deffoo nnimap-request-article (article &optional group server to-buffer)
c113de23 447 (with-current-buffer nntp-server-buffer
bdaa75c7 448 (let ((result (nnimap-possibly-change-group group server))
8ccbef23 449 parts structure)
20a673b2
KY
450 (when (stringp article)
451 (setq article (nnimap-find-article-by-message-id group article)))
452 (when (and result
453 article)
454 (erase-buffer)
455 (with-current-buffer (nnimap-buffer)
456 (erase-buffer)
9f2d52e7
G
457 (when nnimap-fetch-partial-articles
458 (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
459 (goto-char (point-min))
460 (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
229b59da
G
461 (setq structure (ignore-errors
462 (let ((start (point)))
463 (forward-sexp 1)
464 (downcase-region start (point))
465 (goto-char (point))
466 (read (current-buffer))))
9f2d52e7 467 parts (nnimap-find-wanted-parts structure))))
8ccbef23
G
468 (when (if parts
469 (nnimap-get-partial-article article parts structure)
470 (nnimap-get-whole-article article))
471 (let ((buffer (current-buffer)))
472 (with-current-buffer (or to-buffer nntp-server-buffer)
473 (erase-buffer)
474 (insert-buffer-substring buffer)
475 (nnheader-ms-strip-cr)
476 (cons group article)))))))))
477
478(defun nnimap-get-whole-article (article)
479 (let ((result
480 (nnimap-command
481 (if (nnimap-ver4-p)
482 "UID FETCH %d BODY.PEEK[]"
483 "UID FETCH %d RFC822.PEEK")
484 article)))
485 ;; Check that we really got an article.
486 (goto-char (point-min))
4478e074 487 (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
8ccbef23
G
488 (setq result nil))
489 (when result
4478e074
G
490 ;; Remove any data that may have arrived before the FETCH data.
491 (beginning-of-line)
492 (unless (bobp)
493 (delete-region (point-min) (point)))
8ccbef23
G
494 (let ((bytes (nnimap-get-length)))
495 (delete-region (line-beginning-position)
496 (progn (forward-line 1) (point)))
497 (goto-char (+ (point) bytes))
498 (delete-region (point) (point-max)))
499 t)))
500
501(defun nnimap-ver4-p ()
502 (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
503
504(defun nnimap-get-partial-article (article parts structure)
505 (let ((result
506 (nnimap-command
507 "UID FETCH %d (%s %s)"
508 article
509 (if (nnimap-ver4-p)
510 "BODY.PEEK[HEADER]"
511 "RFC822.HEADER")
512 (if (nnimap-ver4-p)
513 (mapconcat (lambda (part)
514 (format "BODY.PEEK[%s]" part))
515 parts " ")
516 (mapconcat (lambda (part)
517 (format "RFC822.PEEK[%s]" part))
518 parts " ")))))
519 (when result
520 (nnimap-convert-partial-article structure))))
521
522(defun nnimap-convert-partial-article (structure)
523 ;; First just skip past the headers.
524 (goto-char (point-min))
525 (let ((bytes (nnimap-get-length))
526 id parts)
527 ;; Delete "FETCH" line.
528 (delete-region (line-beginning-position)
529 (progn (forward-line 1) (point)))
530 (goto-char (+ (point) bytes))
531 ;; Collect all the body parts.
532 (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
533 (setq id (match-string 1)
534 bytes (nnimap-get-length))
535 (beginning-of-line)
536 (delete-region (point) (progn (forward-line 1) (point)))
537 (push (list id (buffer-substring (point) (+ (point) bytes)))
538 parts)
539 (delete-region (point) (+ (point) bytes)))
540 ;; Delete trailing junk.
541 (delete-region (point) (point-max))
542 ;; Now insert all the parts again where they fit in the structure.
543 (nnimap-insert-partial-structure structure parts)
544 t))
545
546(defun nnimap-insert-partial-structure (structure parts &optional subp)
229b59da
G
547 (let (type boundary)
548 (let ((bstruc structure))
549 (while (consp (car bstruc))
550 (pop bstruc))
551 (setq type (car bstruc))
552 (setq bstruc (car (cdr bstruc)))
553 (when (and (stringp (car bstruc))
554 (string= (downcase (car bstruc)) "boundary"))
555 (setq boundary (cadr bstruc))))
8ccbef23
G
556 (when subp
557 (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
558 (downcase type) boundary)))
559 (while (not (stringp (car structure)))
560 (insert "\n--" boundary "\n")
561 (if (consp (caar structure))
562 (nnimap-insert-partial-structure (pop structure) parts t)
563 (let ((bit (pop structure)))
564 (insert (format "Content-type: %s/%s"
565 (downcase (nth 0 bit))
566 (downcase (nth 1 bit))))
567 (if (member "CHARSET" (nth 2 bit))
568 (insert (format
569 "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
570 (insert "\n"))
571 (insert (format "Content-transfer-encoding: %s\n"
572 (nth 5 bit)))
573 (insert "\n")
574 (when (assoc (nth 9 bit) parts)
575 (insert (cadr (assoc (nth 9 bit) parts)))))))
576 (insert "\n--" boundary "--\n")))
bdaa75c7
LMI
577
578(defun nnimap-find-wanted-parts (structure)
579 (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
580
581(defun nnimap-find-wanted-parts-1 (structure prefix)
582 (let ((num 1)
583 parts)
584 (while (consp (car structure))
585 (let ((sub (pop structure)))
586 (if (consp (car sub))
587 (push (nnimap-find-wanted-parts-1
588 sub (if (string= prefix "")
589 (number-to-string num)
590 (format "%s.%s" prefix num)))
591 parts)
8ccbef23
G
592 (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
593 (id (if (string= prefix "")
bdaa75c7 594 (number-to-string num)
8ccbef23
G
595 (format "%s.%s" prefix num))))
596 (setcar (nthcdr 9 sub) id)
9f2d52e7
G
597 (when (if (eq nnimap-fetch-partial-articles t)
598 (equal id "1")
599 (string-match nnimap-fetch-partial-articles type))
8ccbef23
G
600 (push id parts))))
601 (incf num)))
bdaa75c7 602 (nreverse parts)))
20a673b2 603
286c4fc2 604(deffoo nnimap-request-group (group &optional server dont-check info)
a46359d4
LMI
605 (let ((result (nnimap-possibly-change-group group server))
606 articles active marks high low)
607 (with-current-buffer nntp-server-buffer
20a673b2 608 (when result
286c4fc2
LMI
609 (if (and dont-check
610 (setq active (nth 2 (assoc group nnimap-current-infos))))
611 (insert (format "211 %d %d %d %S\n"
612 (- (cdr active) (car active))
613 (car active)
614 (cdr active)
615 group))
616 (with-current-buffer (nnimap-buffer)
617 (erase-buffer)
618 (let ((group-sequence
0617bb00 619 (nnimap-send-command "SELECT %S" (utf7-encode group t)))
286c4fc2
LMI
620 (flag-sequence
621 (nnimap-send-command "UID FETCH 1:* FLAGS")))
622 (nnimap-wait-for-response flag-sequence)
623 (setq marks
624 (nnimap-flags-to-marks
625 (nnimap-parse-flags
626 (list (list group-sequence flag-sequence 1 group)))))
627 (when info
628 (nnimap-update-infos marks (list info)))
629 (goto-char (point-max))
b1ae92ba 630 (let ((uidnext (nth 5 (car marks))))
a3f57c41
G
631 (setq high (or (if uidnext
632 (1- uidnext)
633 (nth 3 (car marks)))
634 0)
635 low (or (nth 4 (car marks)) uidnext 1)))))
286c4fc2
LMI
636 (erase-buffer)
637 (insert
638 (format
0617bb00
LMI
639 "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
640 t))))
641
642(deffoo nnimap-request-create-group (group &optional server args)
643 (when (nnimap-possibly-change-group nil server)
644 (with-current-buffer (nnimap-buffer)
645 (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
c113de23 646
a46359d4
LMI
647(deffoo nnimap-request-delete-group (group &optional force server)
648 (when (nnimap-possibly-change-group nil server)
649 (with-current-buffer (nnimap-buffer)
0617bb00
LMI
650 (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
651
652(deffoo nnimap-request-expunge-group (group &optional server)
653 (when (nnimap-possibly-change-group group server)
654 (with-current-buffer (nnimap-buffer)
655 (car (nnimap-command "EXPUNGE")))))
a46359d4 656
20a673b2
KY
657(defun nnimap-get-flags (spec)
658 (let ((articles nil)
659 elems)
660 (with-current-buffer (nnimap-buffer)
c113de23 661 (erase-buffer)
20a673b2
KY
662 (nnimap-wait-for-response (nnimap-send-command
663 "UID FETCH %s FLAGS" spec))
664 (goto-char (point-min))
665 (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
666 (setq elems (nnimap-parse-line (match-string 1)))
667 (push (cons (string-to-number (cadr (member "UID" elems)))
668 (cadr (member "FLAGS" elems)))
669 articles)))
670 (nreverse articles)))
a1506d29 671
286c4fc2 672(deffoo nnimap-close-group (group &optional server)
20a673b2 673 t)
c113de23 674
01c52d31 675(deffoo nnimap-request-move-article (article group server accept-form
20a673b2 676 &optional last internal-move-group)
0617bb00
LMI
677 (with-temp-buffer
678 (when (nnimap-request-article article group server (current-buffer))
679 ;; If the move is internal (on the same server), just do it the easy
680 ;; way.
681 (let ((message-id (message-field-value "message-id")))
682 (if internal-move-group
683 (let ((result
684 (with-current-buffer (nnimap-buffer)
685 (nnimap-command "UID COPY %d %S"
686 article
687 (utf7-encode internal-move-group t)))))
688 (when (car result)
a46359d4 689 (nnimap-delete-article article)
0617bb00
LMI
690 (cons internal-move-group
691 (nnimap-find-article-by-message-id
692 internal-move-group message-id))))
693 ;; Move the article to a different method.
694 (let ((result (eval accept-form)))
695 (when result
696 (nnimap-delete-article article)
697 result)))))))
20a673b2
KY
698
699(deffoo nnimap-request-expire-articles (articles group &optional server force)
700 (cond
0617bb00
LMI
701 ((null articles)
702 nil)
20a673b2
KY
703 ((not (nnimap-possibly-change-group group server))
704 articles)
0617bb00
LMI
705 ((and force
706 (eq nnmail-expiry-target 'delete))
4478e074 707 (unless (nnimap-delete-article (gnus-compress-sequence articles))
20a673b2
KY
708 (message "Article marked for deletion, but not expunged."))
709 nil)
710 (t
0617bb00 711 (let ((deletable-articles
b069e5a6
G
712 (if (or force
713 (eq nnmail-expiry-wait 'immediate))
0617bb00
LMI
714 articles
715 (gnus-sorted-intersection
716 articles
717 (nnimap-find-expired-articles group)))))
718 (if (null deletable-articles)
719 articles
720 (if (eq nnmail-expiry-target 'delete)
4478e074 721 (nnimap-delete-article (gnus-compress-sequence deletable-articles))
0617bb00
LMI
722 (setq deletable-articles
723 (nnimap-process-expiry-targets
724 deletable-articles group server)))
725 ;; Return the articles we didn't delete.
726 (gnus-sorted-complement articles deletable-articles))))))
727
728(defun nnimap-process-expiry-targets (articles group server)
729 (let ((deleted-articles nil))
730 (dolist (article articles)
731 (let ((target nnmail-expiry-target))
732 (with-temp-buffer
733 (when (nnimap-request-article article group server (current-buffer))
734 (message "Expiring article %s:%d" group article)
735 (when (functionp target)
736 (setq target (funcall target group)))
737 (when (and target
738 (not (eq target 'delete)))
739 (if (or (gnus-request-group target t)
740 (gnus-request-create-group target))
741 (nnmail-expiry-target-group target group)
742 (setq target nil)))
743 (when target
744 (push article deleted-articles))))))
745 ;; Change back to the current group again.
746 (nnimap-possibly-change-group group server)
747 (setq deleted-articles (nreverse deleted-articles))
4478e074 748 (nnimap-delete-article (gnus-compress-sequence deleted-articles))
0617bb00
LMI
749 deleted-articles))
750
751(defun nnimap-find-expired-articles (group)
752 (let ((cutoff (nnmail-expired-article-p group nil nil)))
753 (with-current-buffer (nnimap-buffer)
754 (let ((result
755 (nnimap-command
756 "UID SEARCH SENTBEFORE %s"
757 (format-time-string
758 (format "%%d-%s-%%Y"
759 (upcase
760 (car (rassoc (nth 4 (decode-time cutoff))
761 parse-time-months))))
762 cutoff))))
763 (and (car result)
764 (delete 0 (mapcar #'string-to-number
765 (cdr (assoc "SEARCH" (cdr result))))))))))
766
20a673b2
KY
767
768(defun nnimap-find-article-by-message-id (group message-id)
6b958814
G
769 (with-current-buffer (nnimap-buffer)
770 (erase-buffer)
771 (setf (nnimap-group nnimap-object) nil)
772 (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
773 (let ((sequence
774 (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
775 article result)
776 (setq result (nnimap-wait-for-response sequence))
777 (when (and result
778 (car (setq result (nnimap-parse-response))))
779 ;; Select the last instance of the message in the group.
780 (and (setq article
781 (car (last (assoc "SEARCH" (cdr result)))))
782 (string-to-number article))))))
20a673b2
KY
783
784(defun nnimap-delete-article (articles)
785 (with-current-buffer (nnimap-buffer)
786 (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
787 (nnimap-article-ranges articles))
0617bb00
LMI
788 (cond
789 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
790 (nnimap-command "UID EXPUNGE %s"
791 (nnimap-article-ranges articles))
792 t)
793 (nnimap-expunge
794 (nnimap-command "EXPUNGE")
7390c1cd
TZ
795 t)
796 (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
797 "server doesn't support UIDPLUS, so we won't "
798 "delete this article now"))))))
20a673b2
KY
799
800(deffoo nnimap-request-scan (&optional group server)
801 (when (and (nnimap-possibly-change-group nil server)
20a673b2
KY
802 nnimap-inbox
803 nnimap-split-methods)
b069e5a6 804 (message "nnimap %s splitting mail..." server)
20a673b2
KY
805 (nnimap-split-incoming-mail)))
806
807(defun nnimap-marks-to-flags (marks)
808 (let (flags flag)
809 (dolist (mark marks)
810 (when (setq flag (cadr (assq mark nnimap-mark-alist)))
811 (push flag flags)))
812 flags))
813
286c4fc2 814(deffoo nnimap-request-set-mark (group actions &optional server)
20a673b2
KY
815 (when (nnimap-possibly-change-group group server)
816 (let (sequence)
817 (with-current-buffer (nnimap-buffer)
229b59da 818 (erase-buffer)
20a673b2
KY
819 ;; Just send all the STORE commands without waiting for
820 ;; response. If they're successful, they're successful.
821 (dolist (action actions)
822 (destructuring-bind (range action marks) action
823 (let ((flags (nnimap-marks-to-flags marks)))
824 (when flags
825 (setq sequence (nnimap-send-command
826 "UID STORE %s %sFLAGS.SILENT (%s)"
827 (nnimap-article-ranges range)
828 (if (eq action 'del)
829 "-"
830 "+")
831 (mapconcat #'identity flags " ")))))))
832 ;; Wait for the last command to complete to avoid later
833 ;; syncronisation problems with the stream.
a46359d4
LMI
834 (when sequence
835 (nnimap-wait-for-response sequence))))))
a1506d29 836
c113de23 837(deffoo nnimap-request-accept-article (group &optional server last)
20a673b2
KY
838 (when (nnimap-possibly-change-group nil server)
839 (nnmail-check-syntax)
6b958814
G
840 (let ((message-id (message-field-value "message-id"))
841 sequence message)
842 (nnimap-add-cr)
843 (setq message (buffer-string))
20a673b2
KY
844 (with-current-buffer (nnimap-buffer)
845 (setq sequence (nnimap-send-command
846 "APPEND %S {%d}" (utf7-encode group t)
847 (length message)))
848 (process-send-string (get-buffer-process (current-buffer)) message)
286c4fc2
LMI
849 (process-send-string (get-buffer-process (current-buffer))
850 (if (nnimap-newlinep nnimap-object)
851 "\n"
852 "\r\n"))
20a673b2 853 (let ((result (nnimap-get-response sequence)))
062eae99
G
854 (if (not (car result))
855 (progn
856 (message "%s" (nnheader-get-report-string 'nnimap))
857 nil)
20a673b2
KY
858 (cons group
859 (nnimap-find-article-by-message-id group message-id))))))))
860
861(defun nnimap-add-cr ()
862 (goto-char (point-min))
863 (while (re-search-forward "\r?\n" nil t)
864 (replace-match "\r\n" t t)))
865
866(defun nnimap-get-groups ()
867 (let ((result (nnimap-command "LIST \"\" \"*\""))
868 groups)
869 (when (car result)
870 (dolist (line (cdr result))
871 (when (and (equal (car line) "LIST")
872 (not (and (caadr line)
873 (string-match "noselect" (caadr line)))))
874 (push (car (last line)) groups)))
875 (nreverse groups))))
876
286c4fc2 877(deffoo nnimap-request-list (&optional server)
20a673b2
KY
878 (nnimap-possibly-change-group nil server)
879 (with-current-buffer nntp-server-buffer
880 (erase-buffer)
881 (let ((groups
882 (with-current-buffer (nnimap-buffer)
883 (nnimap-get-groups)))
884 sequences responses)
885 (when groups
886 (with-current-buffer (nnimap-buffer)
b069e5a6 887 (setf (nnimap-group nnimap-object) nil)
20a673b2
KY
888 (dolist (group groups)
889 (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
890 group)
891 sequences))
892 (nnimap-wait-for-response (caar sequences))
893 (setq responses
894 (nnimap-get-responses (mapcar #'car sequences))))
895 (dolist (response responses)
896 (let* ((sequence (car response))
897 (response (cadr response))
898 (group (cadr (assoc sequence sequences))))
899 (when (and group
900 (equal (caar response) "OK"))
901 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
902 highest exists)
903 (dolist (elem response)
904 (when (equal (cadr elem) "EXISTS")
905 (setq exists (string-to-number (car elem)))))
906 (when uidnext
907 (setq highest (1- (string-to-number (car uidnext)))))
908 (cond
909 ((null highest)
910 (insert (format "%S 0 1 y\n" (utf7-decode group t))))
911 ((zerop exists)
912 ;; Empty group.
913 (insert (format "%S %d %d y\n"
914 (utf7-decode group t) highest (1+ highest))))
915 (t
916 ;; Return the widest possible range.
917 (insert (format "%S %d 1 y\n" (utf7-decode group t)
918 (or highest exists)))))))))
c113de23
GM
919 t))))
920
a3f57c41
G
921(deffoo nnimap-request-newgroups (date &optional server)
922 (nnimap-possibly-change-group nil server)
923 (with-current-buffer nntp-server-buffer
924 (erase-buffer)
925 (dolist (group (with-current-buffer (nnimap-buffer)
926 (nnimap-get-groups)))
927 (unless (assoc group nnimap-current-infos)
928 ;; Insert dummy numbers here -- they don't matter.
929 (insert (format "%S 0 1 y\n" group))))))
930
286c4fc2 931(deffoo nnimap-retrieve-group-data-early (server infos)
20a673b2
KY
932 (when (nnimap-possibly-change-group nil server)
933 (with-current-buffer (nnimap-buffer)
934 ;; QRESYNC handling isn't implemented.
935 (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
936 marks groups sequences)
937 ;; Go through the infos and gather the data needed to know
938 ;; what and how to request the data.
939 (dolist (info infos)
940 (setq marks (gnus-info-marks info))
941 (push (list (gnus-group-real-name (gnus-info-group info))
942 (cdr (assq 'active marks))
943 (cdr (assq 'uid marks)))
944 groups))
945 ;; Then request the data.
946 (erase-buffer)
b069e5a6 947 (setf (nnimap-group nnimap-object) nil)
20a673b2
KY
948 (dolist (elem groups)
949 (if (and qresyncp
950 (nth 2 elem))
951 (push
952 (list 'qresync
953 (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
954 (car elem)
955 (car (nth 2 elem))
956 (cdr (nth 2 elem)))
957 nil
958 (car elem))
959 sequences)
960 (let ((start
961 (if (nth 1 elem)
962 ;; Fetch the last 100 flags.
963 (max 1 (- (cdr (nth 1 elem)) 100))
964 1)))
965 (push (list (nnimap-send-command "EXAMINE %S" (car elem))
966 (nnimap-send-command "UID FETCH %d:* FLAGS" start)
967 start
968 (car elem))
8ccbef23
G
969 sequences)))
970 ;; Some servers apparently can't have many outstanding
971 ;; commands, so throttle them.
972 (when (and (not nnimap-streaming)
973 (car sequences))
974 (nnimap-wait-for-response (caar sequences))))
20a673b2
KY
975 sequences))))
976
286c4fc2 977(deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
20a673b2
KY
978 (when (and sequences
979 (nnimap-possibly-change-group nil server))
980 (with-current-buffer (nnimap-buffer)
981 ;; Wait for the final data to trickle in.
71e691a5 982 (when (nnimap-wait-for-response (cadar sequences) t)
8ccbef23
G
983 ;; Now we should have all the data we need, no matter whether
984 ;; we're QRESYNCING, fetching all the flags from scratch, or
985 ;; just fetching the last 100 flags per group.
986 (nnimap-update-infos (nnimap-flags-to-marks
987 (nnimap-parse-flags
988 (nreverse sequences)))
989 infos)
990 ;; Finally, just return something resembling an active file in
991 ;; the nntp buffer, so that the agent can save the info, too.
992 (with-current-buffer nntp-server-buffer
993 (erase-buffer)
994 (dolist (info infos)
995 (let* ((group (gnus-info-group info))
996 (active (gnus-active group)))
997 (when active
998 (insert (format "%S %d %d y\n"
999 (gnus-group-real-name group)
1000 (cdr active)
1001 (car active)))))))))))
20a673b2
KY
1002
1003(defun nnimap-update-infos (flags infos)
1004 (dolist (info infos)
1005 (let ((group (gnus-group-real-name (gnus-info-group info))))
1006 (nnimap-update-info info (cdr (assoc group flags))))))
1007
1008(defun nnimap-update-info (info marks)
a3f57c41
G
1009 (when (and marks
1010 ;; Ignore groups with no UIDNEXT values.
1011 (nth 4 marks))
b069e5a6
G
1012 (destructuring-bind (existing flags high low uidnext start-article
1013 permanent-flags) marks
20a673b2
KY
1014 (let ((group (gnus-info-group info))
1015 (completep (and start-article
1016 (= start-article 1))))
b1ae92ba
G
1017 (when uidnext
1018 (setq high (1- uidnext)))
20a673b2
KY
1019 ;; First set the active ranges based on high/low.
1020 (if (or completep
1021 (not (gnus-active group)))
1022 (gnus-set-active group
61b1af82
G
1023 (cond
1024 ((and low high)
1025 (cons low high))
1026 (uidnext
20a673b2 1027 ;; No articles in this group.
61b1af82
G
1028 (cons uidnext (1- uidnext)))
1029 (start-article
1030 (cons start-article (1- start-article)))
1031 (t
1032 ;; No articles and no uidnext.
1033 nil)))
9f2d52e7
G
1034 (gnus-set-active
1035 group
1036 (cons (car (gnus-active group))
1037 (or high (1- uidnext)))))
61b1af82
G
1038 (when (and (not high)
1039 uidnext)
b069e5a6 1040 (setq high (1- uidnext)))
20a673b2
KY
1041 ;; Then update the list of read articles.
1042 (let* ((unread
1043 (gnus-compress-sequence
1044 (gnus-set-difference
1045 (gnus-set-difference
1046 existing
b069e5a6
G
1047 (cdr (assoc '%Seen flags)))
1048 (cdr (assoc '%Flagged flags)))))
20a673b2
KY
1049 (read (gnus-range-difference
1050 (cons start-article high) unread)))
1051 (when (> start-article 1)
1052 (setq read
1053 (gnus-range-nconcat
286c4fc2
LMI
1054 (if (> start-article 1)
1055 (gnus-sorted-range-intersection
1056 (cons 1 (1- start-article))
1057 (gnus-info-read info))
1058 (gnus-info-read info))
20a673b2
KY
1059 read)))
1060 (gnus-info-set-read info read)
1061 ;; Update the marks.
1062 (setq marks (gnus-info-marks info))
1063 ;; Note the active level for the next run-through.
1064 (let ((active (assq 'active marks)))
1065 (if active
1066 (setcdr active (gnus-active group))
1067 (push (cons 'active (gnus-active group)) marks)))
1068 (dolist (type (cdr nnimap-mark-alist))
1069 (let ((old-marks (assoc (car type) marks))
b069e5a6
G
1070 (new-marks
1071 (gnus-compress-sequence
1072 (cdr (or (assoc (caddr type) flags) ; %Flagged
d8ec441e 1073 (assoc (intern (cadr type) obarray) flags)
b069e5a6 1074 (assoc (cadr type) flags)))))) ; "\Flagged"
20a673b2
KY
1075 (setq marks (delq old-marks marks))
1076 (pop old-marks)
1077 (when (and old-marks
1078 (> start-article 1))
1079 (setq old-marks (gnus-range-difference
286c4fc2
LMI
1080 old-marks
1081 (cons start-article high)))
20a673b2
KY
1082 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1083 (when new-marks
1084 (push (cons (car type) new-marks) marks)))
286c4fc2
LMI
1085 (gnus-info-set-marks info marks t)
1086 (nnimap-store-info info (gnus-active group))))))))
1087
1088(defun nnimap-store-info (info active)
1089 (let* ((group (gnus-group-real-name (gnus-info-group info)))
1090 (entry (assoc group nnimap-current-infos)))
1091 (if entry
1092 (setcdr entry (list info active))
1093 (push (list group info active) nnimap-current-infos))))
20a673b2
KY
1094
1095(defun nnimap-flags-to-marks (groups)
b069e5a6 1096 (let (data group totalp uidnext articles start-article mark permanent-flags)
20a673b2
KY
1097 (dolist (elem groups)
1098 (setq group (car elem)
b069e5a6
G
1099 uidnext (nth 1 elem)
1100 start-article (nth 2 elem)
1101 permanent-flags (nth 3 elem)
1102 articles (nthcdr 4 elem))
20a673b2
KY
1103 (let ((high (caar articles))
1104 marks low existing)
1105 (dolist (article articles)
1106 (setq low (car article))
1107 (push (car article) existing)
1108 (dolist (flag (cdr article))
1109 (setq mark (assoc flag marks))
1110 (if (not mark)
1111 (push (list flag (car article)) marks)
b069e5a6
G
1112 (setcdr mark (cons (car article) (cdr mark))))))
1113 (push (list group existing marks high low uidnext start-article
1114 permanent-flags)
1115 data)))
20a673b2
KY
1116 data))
1117
1118(defun nnimap-parse-flags (sequences)
1119 (goto-char (point-min))
b069e5a6
G
1120 ;; Change \Delete etc to %Delete, so that the reader can read it.
1121 (subst-char-in-region (point-min) (point-max)
1122 ?\\ ?% t)
1123 (let (start end articles groups uidnext elems permanent-flags)
20a673b2
KY
1124 (dolist (elem sequences)
1125 (destructuring-bind (group-sequence flag-sequence totalp group) elem
b069e5a6 1126 (setq start (point))
20a673b2
KY
1127 ;; The EXAMINE was successful.
1128 (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
1129 (progn
1130 (forward-line 1)
b069e5a6
G
1131 (setq end (point))
1132 (goto-char start)
1133 (setq permanent-flags
1134 (and (search-forward "PERMANENTFLAGS "
1135 (or end (point-min)) t)
1136 (read (current-buffer))))
1137 (goto-char start)
1138 (setq uidnext
1139 (and (search-forward "UIDNEXT "
1140 (or end (point-min)) t)
1141 (read (current-buffer))))
1142 (goto-char end)
1143 (forward-line -1))
20a673b2
KY
1144 ;; The UID FETCH FLAGS was successful.
1145 (search-forward (format "\n%d OK " flag-sequence) nil t))
b069e5a6
G
1146 (setq start (point))
1147 (goto-char end)
1148 (while (search-forward " FETCH " start t)
1149 (setq elems (read (current-buffer)))
1150 (push (cons (cadr (memq 'UID elems))
1151 (cadr (memq 'FLAGS elems)))
20a673b2 1152 articles))
b069e5a6
G
1153 (push (nconc (list group uidnext totalp permanent-flags) articles)
1154 groups)
20a673b2
KY
1155 (setq articles nil))))
1156 groups))
1157
1158(defun nnimap-find-process-buffer (buffer)
1159 (cadr (assoc buffer nnimap-connection-alist)))
1160
286c4fc2 1161(deffoo nnimap-request-post (&optional server)
20a673b2
KY
1162 (setq nnimap-status-string "Read-only server")
1163 nil)
c113de23 1164
20a673b2
KY
1165(defun nnimap-possibly-change-group (group server)
1166 (let ((open-result t))
1167 (when (and server
1168 (not (nnimap-server-opened server)))
1169 (setq open-result (nnimap-open-server server)))
1170 (cond
1171 ((not open-result)
1172 nil)
1173 ((not group)
1174 t)
1175 (t
1176 (with-current-buffer (nnimap-buffer)
1177 (if (equal group (nnimap-group nnimap-object))
1178 t
1179 (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1180 (when (car result)
286c4fc2
LMI
1181 (setf (nnimap-group nnimap-object) group
1182 (nnimap-select-result nnimap-object) result)
20a673b2
KY
1183 result))))))))
1184
1185(defun nnimap-find-connection (buffer)
1186 "Find the connection delivering to BUFFER."
1187 (let ((entry (assoc buffer nnimap-connection-alist)))
1188 (when entry
1189 (if (and (buffer-name (cadr entry))
1190 (get-buffer-process (cadr entry))
1191 (memq (process-status (get-buffer-process (cadr entry)))
1192 '(open run)))
1193 (get-buffer-process (cadr entry))
1194 (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1195 nil))))
1196
1197(defvar nnimap-sequence 0)
1198
1199(defun nnimap-send-command (&rest args)
1200 (process-send-string
1201 (get-buffer-process (current-buffer))
1202 (nnimap-log-command
286c4fc2 1203 (format "%d %s%s\n"
20a673b2 1204 (incf nnimap-sequence)
286c4fc2
LMI
1205 (apply #'format args)
1206 (if (nnimap-newlinep nnimap-object)
1207 ""
1208 "\r"))))
20a673b2
KY
1209 nnimap-sequence)
1210
1211(defun nnimap-log-command (command)
1212 (with-current-buffer (get-buffer-create "*imap log*")
1213 (goto-char (point-max))
1214 (insert (format-time-string "%H:%M:%S") " " command))
1215 command)
1216
1217(defun nnimap-command (&rest args)
1218 (erase-buffer)
61b1af82 1219 (setf (nnimap-last-command-time nnimap-object) (current-time))
20a673b2
KY
1220 (let* ((sequence (apply #'nnimap-send-command args))
1221 (response (nnimap-get-response sequence)))
1222 (if (equal (caar response) "OK")
1223 (cons t response)
1224 (nnheader-report 'nnimap "%s"
a46359d4
LMI
1225 (mapconcat (lambda (a)
1226 (format "%s" a))
1227 (car response) " "))
20a673b2
KY
1228 nil)))
1229
1230(defun nnimap-get-response (sequence)
1231 (nnimap-wait-for-response sequence)
1232 (nnimap-parse-response))
1233
286c4fc2
LMI
1234(defun nnimap-wait-for-connection ()
1235 (let ((process (get-buffer-process (current-buffer))))
1236 (goto-char (point-min))
1237 (while (and (memq (process-status process)
1238 '(open run))
6b958814 1239 (not (re-search-forward "^[*.] .*\n" nil t)))
286c4fc2
LMI
1240 (nnheader-accept-process-output process)
1241 (goto-char (point-min)))
bdaa75c7 1242 (forward-line -1)
6b958814 1243 (and (looking-at "[*.] \\([A-Z0-9]+\\)")
bdaa75c7 1244 (match-string 1))))
286c4fc2 1245
20a673b2 1246(defun nnimap-wait-for-response (sequence &optional messagep)
8ccbef23
G
1247 (let ((process (get-buffer-process (current-buffer)))
1248 openp)
bdaa75c7 1249 (goto-char (point-max))
8ccbef23
G
1250 (while (and (setq openp (memq (process-status process)
1251 '(open run)))
1252 (not (re-search-backward
1253 (format "^%d .*\n" sequence)
1254 (if nnimap-streaming
1255 (max (point-min) (- (point) 500))
1256 (point-min))
1257 t)))
bdaa75c7 1258 (when messagep
71e691a5 1259 (message "nnimap read %dk" (/ (buffer-size) 1000)))
bdaa75c7 1260 (nnheader-accept-process-output process)
8ccbef23
G
1261 (goto-char (point-max)))
1262 openp))
20a673b2
KY
1263
1264(defun nnimap-parse-response ()
1265 (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1266 result)
1267 (dolist (line lines)
1268 (push (cdr (nnimap-parse-line line)) result))
1269 ;; Return the OK/error code first, and then all the "continuation
1270 ;; lines" afterwards.
1271 (cons (pop result)
1272 (nreverse result))))
1273
1274;; Parse an IMAP response line lightly. They look like
1275;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1276;; the lines into a list of strings and lists of string.
1277(defun nnimap-parse-line (line)
1278 (let (char result)
1279 (with-temp-buffer
1280 (insert line)
1281 (goto-char (point-min))
1282 (while (not (eobp))
1283 (if (eql (setq char (following-char)) ? )
1284 (forward-char 1)
1285 (push
1286 (cond
1287 ((eql char ?\[)
1288 (split-string (buffer-substring
9f2d52e7
G
1289 (1+ (point))
1290 (1- (search-forward "]" (line-end-position) 'move)))))
20a673b2
KY
1291 ((eql char ?\()
1292 (split-string (buffer-substring
9f2d52e7
G
1293 (1+ (point))
1294 (1- (search-forward ")" (line-end-position) 'move)))))
20a673b2
KY
1295 ((eql char ?\")
1296 (forward-char 1)
9f2d52e7
G
1297 (buffer-substring
1298 (point)
1299 (1- (or (search-forward "\"" (line-end-position) 'move)
1300 (point)))))
20a673b2
KY
1301 (t
1302 (buffer-substring (point) (if (search-forward " " nil t)
1303 (1- (point))
1304 (goto-char (point-max))))))
1305 result)))
1306 (nreverse result))))
1307
1308(defun nnimap-last-response-string ()
1309 (save-excursion
1310 (forward-line 1)
1311 (let ((end (point)))
1312 (forward-line -1)
1313 (when (not (bobp))
1314 (forward-line -1)
1315 (while (and (not (bobp))
1316 (eql (following-char) ?*))
1317 (forward-line -1))
1318 (unless (eql (following-char) ?*)
1319 (forward-line 1)))
1320 (buffer-substring (point) end))))
1321
1322(defun nnimap-get-responses (sequences)
1323 (let (responses)
1324 (dolist (sequence sequences)
1325 (goto-char (point-min))
1326 (when (re-search-forward (format "^%d " sequence) nil t)
1327 (push (list sequence (nnimap-parse-response))
1328 responses)))
1329 responses))
1330
1331(defvar nnimap-incoming-split-list nil)
1332
1333(defun nnimap-fetch-inbox (articles)
1334 (erase-buffer)
1335 (nnimap-wait-for-response
1336 (nnimap-send-command
1337 "UID FETCH %s %s"
1338 (nnimap-article-ranges articles)
1339 (format "(UID %s%s)"
1340 (format
8ccbef23 1341 (if (nnimap-ver4-p)
20a673b2
KY
1342 "BODY.PEEK[HEADER] BODY.PEEK"
1343 "RFC822.PEEK"))
1344 (if nnimap-split-download-body-default
a46359d4 1345 "[]"
20a673b2
KY
1346 "[1]")))
1347 t))
1348
1349(defun nnimap-split-incoming-mail ()
1350 (with-current-buffer (nnimap-buffer)
1351 (let ((nnimap-incoming-split-list nil)
229b59da
G
1352 (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1353 nnmail-split-methods
1354 nnimap-split-methods))
6b958814
G
1355 (nnmail-split-fancy (or nnimap-split-fancy
1356 nnmail-split-fancy))
20a673b2
KY
1357 (nnmail-inhibit-default-split-group t)
1358 (groups (nnimap-get-groups))
1359 new-articles)
1360 (erase-buffer)
1361 (nnimap-command "SELECT %S" nnimap-inbox)
1362 (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1363 (when new-articles
1364 (nnimap-fetch-inbox new-articles)
1365 (nnimap-transform-split-mail)
1366 (nnheader-ms-strip-cr)
1367 (nnmail-cache-open)
1368 (nnmail-split-incoming (current-buffer)
1369 #'nnimap-save-mail-spec
1370 nil nil
b069e5a6
G
1371 #'nnimap-dummy-active-number
1372 #'nnimap-save-mail-spec)
20a673b2
KY
1373 (when nnimap-incoming-split-list
1374 (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
b069e5a6 1375 sequences junk-articles)
20a673b2
KY
1376 ;; Create any groups that doesn't already exist on the
1377 ;; server first.
1378 (dolist (spec specs)
b069e5a6
G
1379 (when (and (not (member (car spec) groups))
1380 (not (eq (car spec) 'junk)))
20a673b2
KY
1381 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1382 ;; Then copy over all the messages.
1383 (erase-buffer)
1384 (dolist (spec specs)
1385 (let ((group (car spec))
1386 (ranges (cdr spec)))
b069e5a6
G
1387 (if (eq group 'junk)
1388 (setq junk-articles ranges)
1389 (push (list (nnimap-send-command
1390 "UID COPY %s %S"
1391 (nnimap-article-ranges ranges)
1392 (utf7-encode group t))
1393 ranges)
1394 sequences))))
20a673b2
KY
1395 ;; Wait for the last COPY response...
1396 (when sequences
1397 (nnimap-wait-for-response (caar sequences))
1398 ;; And then mark the successful copy actions as deleted,
1399 ;; and possibly expunge them.
1400 (nnimap-mark-and-expunge-incoming
61b1af82
G
1401 (nnimap-parse-copied-articles sequences)))
1402 (nnimap-mark-and-expunge-incoming junk-articles)))))))
20a673b2
KY
1403
1404(defun nnimap-mark-and-expunge-incoming (range)
1405 (when range
1406 (setq range (nnimap-article-ranges range))
229b59da 1407 (erase-buffer)
0617bb00
LMI
1408 (let ((sequence
1409 (nnimap-send-command
1410 "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1411 (cond
1412 ;; If the server supports it, we now delete the message we have
1413 ;; just copied over.
1414 ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1415 (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1416 ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1417 ;; user has configured it.
b069e5a6 1418 (nnimap-expunge
0617bb00
LMI
1419 (setq sequence (nnimap-send-command "EXPUNGE"))))
1420 (nnimap-wait-for-response sequence))))
20a673b2
KY
1421
1422(defun nnimap-parse-copied-articles (sequences)
1423 (let (sequence copied range)
1424 (goto-char (point-min))
1425 (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1426 (setq sequence (string-to-number (match-string 1)))
1427 (when (setq range (cadr (assq sequence sequences)))
1428 (push (gnus-uncompress-range range) copied)))
1429 (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1430
1431(defun nnimap-new-articles (flags)
1432 (let (new)
1433 (dolist (elem flags)
1434 (when (or (null (cdr elem))
b069e5a6
G
1435 (and (not (memq '%Deleted (cdr elem)))
1436 (not (memq '%Seen (cdr elem)))))
20a673b2
KY
1437 (push (car elem) new)))
1438 (gnus-compress-sequence (nreverse new))))
1439
1440(defun nnimap-make-split-specs (list)
1441 (let ((specs nil)
1442 entry)
1443 (dolist (elem list)
1444 (destructuring-bind (article spec) elem
1445 (dolist (group (delete nil (mapcar #'car spec)))
1446 (unless (setq entry (assoc group specs))
1447 (push (setq entry (list group)) specs))
1448 (setcdr entry (cons article (cdr entry))))))
1449 (dolist (entry specs)
1450 (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1451 specs))
1452
1453(defun nnimap-transform-split-mail ()
1454 (goto-char (point-min))
1455 (let (article bytes)
1456 (block nil
1457 (while (not (eobp))
1458 (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1459 (delete-region (point) (progn (forward-line 1) (point)))
1460 (when (eobp)
1461 (return)))
1462 (setq article (match-string 1)
1463 bytes (nnimap-get-length))
1464 (delete-region (line-beginning-position) (line-end-position))
1465 ;; Insert MMDF separator, and a way to remember what this
1466 ;; article UID is.
1467 (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1468 (forward-char (1+ bytes))
1469 (setq bytes (nnimap-get-length))
1470 (delete-region (line-beginning-position) (line-end-position))
1471 (forward-char (1+ bytes))
1472 (delete-region (line-beginning-position) (line-end-position))))))
1473
1474(defun nnimap-dummy-active-number (group &optional server)
1475 1)
1476
1477(defun nnimap-save-mail-spec (group-art &optional server full-nov)
1478 (let (article)
1479 (goto-char (point-min))
1480 (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1481 (error "Invalid nnimap mail")
1482 (setq article (string-to-number (match-string 1))))
b069e5a6
G
1483 (push (list article
1484 (if (eq group-art 'junk)
1485 (list (cons 'junk 1))
1486 group-art))
20a673b2 1487 nnimap-incoming-split-list)))
c113de23 1488
c113de23
GM
1489(provide 'nnimap)
1490
1491;;; nnimap.el ends here