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