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