* nnimap.el: Fix problem with `g' chopping of low-numbered articles.
[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       ;; Make sure we don't have this group open read/write by asking
731       ;; to examine a mailbox that doesn't exist.  This seems to be
732       ;; the only way that allows us to reliably go back to unselected
733       ;; state on Courier.
734       (car (nnimap-command "RENAME %S %S"
735                            (utf7-encode group t) (utf7-encode new-name t))))))
736
737 (deffoo nnimap-request-expunge-group (group &optional server)
738   (when (nnimap-possibly-change-group group server)
739     (with-current-buffer (nnimap-buffer)
740       (car (nnimap-command "EXPUNGE")))))
741
742 (defun nnimap-get-flags (spec)
743   (let ((articles nil)
744         elems end)
745     (with-current-buffer (nnimap-buffer)
746       (erase-buffer)
747       (nnimap-wait-for-response (nnimap-send-command
748                                  "UID FETCH %s FLAGS" spec))
749       (setq end (point))
750       (subst-char-in-region (point-min) (point-max)
751                             ?\\ ?% t)
752       (goto-char (point-min))
753       (while (search-forward " FETCH " end t)
754         (setq elems (read (current-buffer)))
755         (push (cons (cadr (memq 'UID elems))
756                     (cadr (memq 'FLAGS elems)))
757               articles)))
758     (nreverse articles)))
759
760 (deffoo nnimap-close-group (group &optional server)
761   t)
762
763 (deffoo nnimap-request-move-article (article group server accept-form
764                                              &optional last internal-move-group)
765   (with-temp-buffer
766     (mm-disable-multibyte)
767     (when (funcall (if internal-move-group
768                        'nnimap-request-head
769                      'nnimap-request-article)
770                    article group server (current-buffer))
771       ;; If the move is internal (on the same server), just do it the easy
772       ;; way.
773       (let ((message-id (message-field-value "message-id")))
774         (if internal-move-group
775             (let ((result
776                    (with-current-buffer (nnimap-buffer)
777                      (nnimap-command "UID COPY %d %S"
778                                      article
779                                      (utf7-encode internal-move-group t)))))
780               (when (car result)
781                 (nnimap-delete-article article)
782                 (cons internal-move-group
783                       (nnimap-find-article-by-message-id
784                        internal-move-group message-id))))
785           ;; Move the article to a different method.
786           (let ((result (eval accept-form)))
787             (when result
788               (nnimap-delete-article article)
789               result)))))))
790
791 (deffoo nnimap-request-expire-articles (articles group &optional server force)
792   (cond
793    ((null articles)
794     nil)
795    ((not (nnimap-possibly-change-group group server))
796     articles)
797    ((and force
798          (eq nnmail-expiry-target 'delete))
799     (unless (nnimap-delete-article (gnus-compress-sequence articles))
800       (nnheader-message 7 "Article marked for deletion, but not expunged."))
801     nil)
802    (t
803     (let ((deletable-articles
804            (if (or force
805                    (eq nnmail-expiry-wait 'immediate))
806                articles
807              (gnus-sorted-intersection
808               articles
809               (nnimap-find-expired-articles group)))))
810       (if (null deletable-articles)
811           articles
812         (if (eq nnmail-expiry-target 'delete)
813             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
814           (setq deletable-articles
815                 (nnimap-process-expiry-targets
816                  deletable-articles group server)))
817         ;; Return the articles we didn't delete.
818         (gnus-sorted-complement articles deletable-articles))))))
819
820 (defun nnimap-process-expiry-targets (articles group server)
821   (let ((deleted-articles nil))
822     (dolist (article articles)
823       (let ((target nnmail-expiry-target))
824         (with-temp-buffer
825           (mm-disable-multibyte)
826           (when (nnimap-request-article article group server (current-buffer))
827             (nnheader-message 7 "Expiring article %s:%d" group article)
828             (when (functionp target)
829               (setq target (funcall target group)))
830             (when (and target
831                        (not (eq target 'delete)))
832               (if (or (gnus-request-group target t)
833                       (gnus-request-create-group target))
834                   (nnmail-expiry-target-group target group)
835                 (setq target nil)))
836             (when target
837               (push article deleted-articles))))))
838     ;; Change back to the current group again.
839     (nnimap-possibly-change-group group server)
840     (setq deleted-articles (nreverse deleted-articles))
841     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
842     deleted-articles))
843
844 (defun nnimap-find-expired-articles (group)
845   (let ((cutoff (nnmail-expired-article-p group nil nil)))
846     (with-current-buffer (nnimap-buffer)
847       (let ((result
848              (nnimap-command
849               "UID SEARCH SENTBEFORE %s"
850               (format-time-string
851                (format "%%d-%s-%%Y"
852                        (upcase
853                         (car (rassoc (nth 4 (decode-time cutoff))
854                                      parse-time-months))))
855                cutoff))))
856         (and (car result)
857              (delete 0 (mapcar #'string-to-number
858                                (cdr (assoc "SEARCH" (cdr result))))))))))
859
860
861 (defun nnimap-find-article-by-message-id (group message-id)
862   (with-current-buffer (nnimap-buffer)
863     (erase-buffer)
864     (unless (equal group (nnimap-group nnimap-object))
865       (setf (nnimap-group nnimap-object) nil)
866       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
867     (let ((sequence
868            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
869           article result)
870       (setq result (nnimap-wait-for-response sequence))
871       (when (and result
872                  (car (setq result (nnimap-parse-response))))
873         ;; Select the last instance of the message in the group.
874         (and (setq article
875                    (car (last (assoc "SEARCH" (cdr result)))))
876              (string-to-number article))))))
877
878 (defun nnimap-delete-article (articles)
879   (with-current-buffer (nnimap-buffer)
880     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
881                     (nnimap-article-ranges articles))
882     (cond
883      ((nnimap-capability "UIDPLUS")
884       (nnimap-command "UID EXPUNGE %s"
885                       (nnimap-article-ranges articles))
886       t)
887      (nnimap-expunge
888       (nnimap-command "EXPUNGE")
889       t)
890      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
891                                 "server doesn't support UIDPLUS, so we won't "
892                                 "delete this article now"))))))
893
894 (deffoo nnimap-request-scan (&optional group server)
895   (when (and (nnimap-possibly-change-group nil server)
896              nnimap-inbox
897              nnimap-split-methods)
898     (nnheader-message 7 "nnimap %s splitting mail..." server)
899     (nnimap-split-incoming-mail)))
900
901 (defun nnimap-marks-to-flags (marks)
902   (let (flags flag)
903     (dolist (mark marks)
904       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
905         (push flag flags)))
906     flags))
907
908 (deffoo nnimap-request-set-mark (group actions &optional server)
909   (when (nnimap-possibly-change-group group server)
910     (let (sequence)
911       (with-current-buffer (nnimap-buffer)
912         (erase-buffer)
913         ;; Just send all the STORE commands without waiting for
914         ;; response.  If they're successful, they're successful.
915         (dolist (action actions)
916           (destructuring-bind (range action marks) action
917             (let ((flags (nnimap-marks-to-flags marks)))
918               (when flags
919                 (setq sequence (nnimap-send-command
920                                 "UID STORE %s %sFLAGS.SILENT (%s)"
921                                 (nnimap-article-ranges range)
922                                 (if (eq action 'del)
923                                     "-"
924                                   "+")
925                                 (mapconcat #'identity flags " ")))))))
926         ;; Wait for the last command to complete to avoid later
927         ;; syncronisation problems with the stream.
928         (when sequence
929           (nnimap-wait-for-response sequence))))))
930
931 (deffoo nnimap-request-accept-article (group &optional server last)
932   (when (nnimap-possibly-change-group nil server)
933     (nnmail-check-syntax)
934     (let ((message-id (message-field-value "message-id"))
935           sequence message)
936       (nnimap-add-cr)
937       (setq message (buffer-substring-no-properties (point-min) (point-max)))
938       (with-current-buffer (nnimap-buffer)
939         (erase-buffer)
940         (setq sequence (nnimap-send-command
941                         "APPEND %S {%d}" (utf7-encode group t)
942                         (length message)))
943         (unless nnimap-streaming
944           (nnimap-wait-for-connection "^[+]"))
945         (process-send-string (get-buffer-process (current-buffer)) message)
946         (process-send-string (get-buffer-process (current-buffer))
947                              (if (nnimap-newlinep nnimap-object)
948                                  "\n"
949                                "\r\n"))
950         (let ((result (nnimap-get-response sequence)))
951           (if (not (car result))
952               (progn
953                 (nnheader-message 7 "%s" (nnheader-get-report-string 'nnimap))
954                 nil)
955             (cons group
956                   (nnimap-find-article-by-message-id group message-id))))))))
957
958 (deffoo nnimap-request-replace-article (article group buffer)
959   (let (group-art)
960     (when (and (nnimap-possibly-change-group group nil)
961                ;; Put the article into the group.
962                (with-current-buffer buffer
963                  (setq group-art
964                        (nnimap-request-accept-article group nil t))))
965       (nnimap-delete-article (list article))
966       ;; Return the new article number.
967       (cdr group-art))))
968
969 (defun nnimap-add-cr ()
970   (goto-char (point-min))
971   (while (re-search-forward "\r?\n" nil t)
972     (replace-match "\r\n" t t)))
973
974 (defun nnimap-get-groups ()
975   (let ((result (nnimap-command "LIST \"\" \"*\""))
976         groups)
977     (when (car result)
978       (dolist (line (cdr result))
979         (when (and (equal (car line) "LIST")
980                    (not (and (caadr line)
981                              (string-match "noselect" (caadr line)))))
982           (push (car (last line)) groups)))
983       (nreverse groups))))
984
985 (deffoo nnimap-request-list (&optional server)
986   (nnimap-possibly-change-group nil server)
987   (with-current-buffer nntp-server-buffer
988     (erase-buffer)
989     (let ((groups
990            (with-current-buffer (nnimap-buffer)
991              (nnimap-get-groups)))
992           sequences responses)
993       (when groups
994         (with-current-buffer (nnimap-buffer)
995           (setf (nnimap-group nnimap-object) nil)
996           (dolist (group groups)
997             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
998                         group)
999                   sequences))
1000           (nnimap-wait-for-response (caar sequences))
1001           (setq responses
1002                 (nnimap-get-responses (mapcar #'car sequences))))
1003         (dolist (response responses)
1004           (let* ((sequence (car response))
1005                  (response (cadr response))
1006                  (group (cadr (assoc sequence sequences))))
1007             (when (and group
1008                        (equal (caar response) "OK"))
1009               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1010                     highest exists)
1011                 (dolist (elem response)
1012                   (when (equal (cadr elem) "EXISTS")
1013                     (setq exists (string-to-number (car elem)))))
1014                 (when uidnext
1015                   (setq highest (1- (string-to-number (car uidnext)))))
1016                 (cond
1017                  ((null highest)
1018                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
1019                  ((zerop exists)
1020                   ;; Empty group.
1021                   (insert (format "%S %d %d y\n"
1022                                   (utf7-decode group t) highest (1+ highest))))
1023                  (t
1024                   ;; Return the widest possible range.
1025                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
1026                                   (or highest exists)))))))))
1027         t))))
1028
1029 (deffoo nnimap-request-newgroups (date &optional server)
1030   (nnimap-possibly-change-group nil server)
1031   (with-current-buffer nntp-server-buffer
1032     (erase-buffer)
1033     (dolist (group (with-current-buffer (nnimap-buffer)
1034                      (nnimap-get-groups)))
1035       (unless (assoc group nnimap-current-infos)
1036         ;; Insert dummy numbers here -- they don't matter.
1037         (insert (format "%S 0 1 y\n" group))))
1038     t))
1039
1040 (deffoo nnimap-retrieve-group-data-early (server infos)
1041   (when (nnimap-possibly-change-group nil server)
1042     (with-current-buffer (nnimap-buffer)
1043       (erase-buffer)
1044       (setf (nnimap-group nnimap-object) nil)
1045       (let ((qresyncp (nnimap-capability "QRESYNC"))
1046             params groups sequences active uidvalidity modseq group)
1047         ;; Go through the infos and gather the data needed to know
1048         ;; what and how to request the data.
1049         (dolist (info infos)
1050           (setq params (gnus-info-params info)
1051                 group (gnus-group-real-name (gnus-info-group info))
1052                 active (cdr (assq 'active params))
1053                 uidvalidity (cdr (assq 'uidvalidity params))
1054                 modseq (cdr (assq 'modseq params)))
1055           (if (and qresyncp
1056                    uidvalidity
1057                    modseq)
1058               (push
1059                (list (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
1060                                           (utf7-encode group t)
1061                                           uidvalidity modseq)
1062                      'qresync
1063                      nil group 'qresync)
1064                sequences)
1065             (let ((start
1066                    (if (and active uidvalidity)
1067                        ;; Fetch the last 100 flags.
1068                        (max 1 (- (cdr active) 100))
1069                      1))
1070                   (command
1071                    (if uidvalidity
1072                        "EXAMINE"
1073                      ;; If we don't have a UIDVALIDITY, then this is
1074                      ;; the first time we've seen the group, so we
1075                      ;; have to do a SELECT (which is slower than an
1076                      ;; examine), but will tell us whether the group
1077                      ;; is read-only or not.
1078                      "SELECT")))
1079               (push (list (nnimap-send-command "%s %S" command
1080                                                (utf7-encode group t))
1081                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1082                           start group command)
1083                     sequences))))
1084         sequences))))
1085
1086 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1087   (when (and sequences
1088              (nnimap-possibly-change-group nil server))
1089     (with-current-buffer (nnimap-buffer)
1090       ;; Wait for the final data to trickle in.
1091       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1092                                           (caar sequences)
1093                                         (cadar sequences))
1094                                       t)
1095         ;; Now we should have most of the data we need, no matter
1096         ;; whether we're QRESYNCING, fetching all the flags from
1097         ;; scratch, or just fetching the last 100 flags per group.
1098         (nnimap-update-infos (nnimap-flags-to-marks
1099                               (nnimap-parse-flags
1100                                (nreverse sequences)))
1101                              infos)
1102         ;; Finally, just return something resembling an active file in
1103         ;; the nntp buffer, so that the agent can save the info, too.
1104         (with-current-buffer nntp-server-buffer
1105           (erase-buffer)
1106           (dolist (info infos)
1107             (let* ((group (gnus-info-group info))
1108                    (active (gnus-active group)))
1109               (when active
1110                 (insert (format "%S %d %d y\n"
1111                                 (gnus-group-real-name group)
1112                                 (cdr active)
1113                                 (car active)))))))))))
1114
1115 (defun nnimap-update-infos (flags infos)
1116   (dolist (info infos)
1117     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1118            (marks (cdr (assoc group flags))))
1119       (when marks
1120         (nnimap-update-info info marks)))))
1121
1122 (defun nnimap-update-info (info marks)
1123   (destructuring-bind (existing flags high low uidnext start-article
1124                                 permanent-flags uidvalidity
1125                                 vanished highestmodseq) marks
1126     (cond
1127      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1128      ;; completely empty groups.
1129      ((and (not existing)
1130            (not uidnext))
1131       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1132         (when active
1133           (gnus-set-active (gnus-info-group info) active))))
1134      ;; We have a mismatch between the old and new UIDVALIDITY
1135      ;; identifiers, so we have to re-request the group info (the next
1136      ;; time).  This virtually never happens.
1137      ((let ((old-uidvalidity
1138              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1139         (and old-uidvalidity
1140              (not (equal old-uidvalidity uidvalidity))
1141              (> start-article 1)))
1142       (gnus-group-remove-parameter info 'uidvalidity)
1143       (gnus-group-remove-parameter info 'modseq))
1144      ;; We have the data needed to update.
1145      (t
1146       (let* ((group (gnus-info-group info))
1147              (completep (and start-article
1148                              (= start-article 1)))
1149              (active (or (gnus-active group)
1150                          (cdr (assq 'active (gnus-info-params info))))))
1151         (when uidnext
1152           (setq high (1- uidnext)))
1153         ;; First set the active ranges based on high/low.
1154         (if (or completep
1155                 (not (gnus-active group)))
1156             (gnus-set-active group
1157                              (cond
1158                               (active
1159                                (cons (min (or low (car active))
1160                                           (car active))
1161                                      (max (or high (cdr active))
1162                                           (cdr active))))
1163                               ((and low high)
1164                                (cons low high))
1165                               (uidnext
1166                                ;; No articles in this group.
1167                                (cons uidnext (1- uidnext)))
1168                               (start-article
1169                                (cons start-article (1- start-article)))
1170                               (t
1171                                ;; No articles and no uidnext.
1172                                nil)))
1173           (gnus-set-active
1174            group
1175            (cons (car active)
1176                  (or high (1- uidnext)))))
1177         ;; See whether this is a read-only group.
1178         (unless (eq permanent-flags 'not-scanned)
1179           (gnus-group-set-parameter
1180            info 'permanent-flags
1181            (and (or (memq '%* permanent-flags)
1182                     (memq '%Seen permanent-flags))
1183                 permanent-flags)))
1184         ;; Update marks and read articles if this isn't a
1185         ;; read-only IMAP group.
1186         (when (setq permanent-flags
1187                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1188           (if (and highestmodseq
1189                    (not start-article))
1190               ;; We've gotten the data by QRESYNCing.
1191               (nnimap-update-qresync-info
1192                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1193             ;; Do normal non-QRESYNC flag updates.
1194             ;; Update the list of read articles.
1195             (let* ((unread
1196                     (gnus-compress-sequence
1197                      (gnus-set-difference
1198                       (gnus-set-difference
1199                        existing
1200                        (cdr (assoc '%Seen flags)))
1201                       (cdr (assoc '%Flagged flags)))))
1202                    (read (gnus-range-difference
1203                           (cons start-article high) unread)))
1204               (when (> start-article 1)
1205                 (setq read
1206                       (gnus-range-nconcat
1207                        (if (> start-article 1)
1208                            (gnus-sorted-range-intersection
1209                             (cons 1 (1- start-article))
1210                             (gnus-info-read info))
1211                          (gnus-info-read info))
1212                        read)))
1213               (when (or (not (listp permanent-flags))
1214                         (memq '%Seen permanent-flags))
1215                 (gnus-info-set-read info read))
1216               ;; Update the marks.
1217               (setq marks (gnus-info-marks info))
1218               (dolist (type (cdr nnimap-mark-alist))
1219                 (when (or (not (listp permanent-flags))
1220                           (memq (car (assoc (caddr type) flags))
1221                                 permanent-flags)
1222                           (memq '%* permanent-flags))
1223                   (let ((old-marks (assoc (car type) marks))
1224                         (new-marks
1225                          (gnus-compress-sequence
1226                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1227                                    (assoc (intern (cadr type) obarray) flags)
1228                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1229                     (setq marks (delq old-marks marks))
1230                     (pop old-marks)
1231                     (when (and old-marks
1232                                (> start-article 1))
1233                       (setq old-marks (gnus-range-difference
1234                                        old-marks
1235                                        (cons start-article high)))
1236                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1237                     (when new-marks
1238                       (push (cons (car type) new-marks) marks)))))
1239               (gnus-info-set-marks info marks t))))
1240         ;; Note the active level for the next run-through.
1241         (gnus-group-set-parameter info 'active (gnus-active group))
1242         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1243         (gnus-group-set-parameter info 'modseq highestmodseq)
1244         (nnimap-store-info info (gnus-active group)))))))
1245
1246 (defun nnimap-update-qresync-info (info existing vanished flags)
1247   ;; Add all the vanished articles to the list of read articles.
1248   (gnus-info-set-read
1249    info
1250    (gnus-add-to-range
1251     (gnus-add-to-range
1252      (gnus-range-add (gnus-info-read info)
1253                      vanished)
1254      (cdr (assq '%Flagged flags)))
1255     (cdr (assq '%Seen flags))))
1256   (let ((marks (gnus-info-marks info)))
1257     (dolist (type (cdr nnimap-mark-alist))
1258       (let ((ticks (assoc (car type) marks))
1259             (new-marks
1260              (cdr (or (assoc (caddr type) flags) ; %Flagged
1261                       (assoc (intern (cadr type) obarray) flags)
1262                       (assoc (cadr type) flags))))) ; "\Flagged"
1263         (setq marks (delq ticks marks))
1264         (pop ticks)
1265         ;; Add the new marks we got.
1266         (setq ticks (gnus-add-to-range ticks new-marks))
1267         ;; Remove the marks from messages that don't have them.
1268         (setq ticks (gnus-remove-from-range
1269                      ticks
1270                      (gnus-compress-sequence
1271                       (gnus-sorted-complement existing new-marks))))
1272         (when ticks
1273           (push (cons (car type) ticks) marks)))
1274       (gnus-info-set-marks info marks t))))
1275
1276 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1277   (if (zerop (length irange))
1278       nil
1279     (let ((result nil))
1280       (dolist (elem (split-string irange ","))
1281         (push
1282          (if (string-match ":" elem)
1283              (let ((numbers (split-string elem ":")))
1284                (cons (string-to-number (car numbers))
1285                      (string-to-number (cadr numbers))))
1286            (string-to-number elem))
1287          result))
1288       (nreverse result))))
1289
1290 (defun nnimap-store-info (info active)
1291   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1292          (entry (assoc group nnimap-current-infos)))
1293     (if entry
1294         (setcdr entry (list info active))
1295       (push (list group info active) nnimap-current-infos))))
1296
1297 (defun nnimap-flags-to-marks (groups)
1298   (let (data group totalp uidnext articles start-article mark permanent-flags
1299              uidvalidity vanished highestmodseq)
1300     (dolist (elem groups)
1301       (setq group (car elem)
1302             uidnext (nth 1 elem)
1303             start-article (nth 2 elem)
1304             permanent-flags (nth 3 elem)
1305             uidvalidity (nth 4 elem)
1306             vanished (nth 5 elem)
1307             highestmodseq (nth 6 elem)
1308             articles (nthcdr 7 elem))
1309       (let ((high (caar articles))
1310             marks low existing)
1311         (dolist (article articles)
1312           (setq low (car article))
1313           (push (car article) existing)
1314           (dolist (flag (cdr article))
1315             (setq mark (assoc flag marks))
1316             (if (not mark)
1317                 (push (list flag (car article)) marks)
1318               (setcdr mark (cons (car article) (cdr mark))))))
1319         (push (list group existing marks high low uidnext start-article
1320                     permanent-flags uidvalidity vanished highestmodseq)
1321               data)))
1322     data))
1323
1324 (defun nnimap-parse-flags (sequences)
1325   (goto-char (point-min))
1326   ;; Change \Delete etc to %Delete, so that the reader can read it.
1327   (subst-char-in-region (point-min) (point-max)
1328                         ?\\ ?% t)
1329   (let (start end articles groups uidnext elems permanent-flags
1330               uidvalidity vanished highestmodseq)
1331     (dolist (elem sequences)
1332       (destructuring-bind (group-sequence flag-sequence totalp group command)
1333           elem
1334         (setq start (point))
1335         (when (and
1336                ;; The EXAMINE was successful.
1337                (search-forward (format "\n%d OK " group-sequence) nil t)
1338                (progn
1339                  (forward-line 1)
1340                  (setq end (point))
1341                  (goto-char start)
1342                  (setq permanent-flags
1343                        (if (equal command "SELECT")
1344                            (and (search-forward "PERMANENTFLAGS "
1345                                                 (or end (point-min)) t)
1346                                 (read (current-buffer)))
1347                          'not-scanned))
1348                  (goto-char start)
1349                  (setq uidnext
1350                        (and (search-forward "UIDNEXT "
1351                                             (or end (point-min)) t)
1352                             (read (current-buffer))))
1353                  (goto-char start)
1354                  (setq uidvalidity
1355                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1356                                                (or end (point-min)) t)
1357                             ;; Store UIDVALIDITY as a string, as it's
1358                             ;; too big for 32-bit Emacsen, usually.
1359                             (match-string 1)))
1360                  (goto-char start)
1361                  (setq vanished
1362                        (and (eq flag-sequence 'qresync)
1363                             (re-search-forward "VANISHED.* \\([0-9:,]+\\)"
1364                                                (or end (point-min)) t)
1365                             (match-string 1)))
1366                  (goto-char start)
1367                  (setq highestmodseq
1368                        (and (search-forward "HIGHESTMODSEQ "
1369                                             (or end (point-min)) t)
1370                             (read (current-buffer))))
1371                  (goto-char end)
1372                  (forward-line -1))
1373                ;; The UID FETCH FLAGS was successful.
1374                (or (eq flag-sequence 'qresync)
1375                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1376           (if (eq flag-sequence 'qresync)
1377               (progn
1378                 (goto-char start)
1379                 (setq start end))
1380             (setq start (point))
1381             (goto-char end))
1382           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1383             (setq elems (read (current-buffer)))
1384             (push (cons (cadr (memq 'UID elems))
1385                         (cadr (memq 'FLAGS elems)))
1386                   articles))
1387           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1388                              vanished highestmodseq)
1389                        articles)
1390                 groups)
1391           (goto-char end)
1392           (setq articles nil))))
1393     groups))
1394
1395 (defun nnimap-find-process-buffer (buffer)
1396   (cadr (assoc buffer nnimap-connection-alist)))
1397
1398 (deffoo nnimap-request-post (&optional server)
1399   (setq nnimap-status-string "Read-only server")
1400   nil)
1401
1402 (deffoo nnimap-request-thread (id)
1403   (let* ((refs (split-string
1404                 (or (mail-header-references (gnus-summary-article-header))
1405                     "")))
1406          (cmd (let ((value
1407                      (format
1408                       "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1409                       id id)))
1410                 (dolist (refid refs value)
1411                   (setq value (format
1412                                "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1413                                refid refid value)))))
1414          (result (with-current-buffer (nnimap-buffer)
1415                    (nnimap-command  "UID SEARCH %s" cmd))))
1416     (gnus-fetch-headers
1417      (and (car result) (delete 0 (mapcar #'string-to-number
1418                                          (cdr (assoc "SEARCH" (cdr result))))))
1419      nil t)))
1420
1421 (defun nnimap-possibly-change-group (group server)
1422   (let ((open-result t))
1423     (when (and server
1424                (not (nnimap-server-opened server)))
1425       (setq open-result (nnimap-open-server server)))
1426     (cond
1427      ((not open-result)
1428       nil)
1429      ((not group)
1430       t)
1431      (t
1432       (with-current-buffer (nnimap-buffer)
1433         (if (equal group (nnimap-group nnimap-object))
1434             t
1435           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1436             (when (car result)
1437               (setf (nnimap-group nnimap-object) group
1438                     (nnimap-select-result nnimap-object) result)
1439               result))))))))
1440
1441 (defun nnimap-find-connection (buffer)
1442   "Find the connection delivering to BUFFER."
1443   (let ((entry (assoc buffer nnimap-connection-alist)))
1444     (when entry
1445       (if (and (buffer-name (cadr entry))
1446                (get-buffer-process (cadr entry))
1447                (memq (process-status (get-buffer-process (cadr entry)))
1448                      '(open run)))
1449           (get-buffer-process (cadr entry))
1450         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1451         nil))))
1452
1453 (defvar nnimap-sequence 0)
1454
1455 (defun nnimap-send-command (&rest args)
1456   (process-send-string
1457    (get-buffer-process (current-buffer))
1458    (nnimap-log-command
1459     (format "%d %s%s\n"
1460             (incf nnimap-sequence)
1461             (apply #'format args)
1462             (if (nnimap-newlinep nnimap-object)
1463                 ""
1464               "\r"))))
1465   ;; Some servers apparently can't have many outstanding
1466   ;; commands, so throttle them.
1467   (unless nnimap-streaming
1468     (nnimap-wait-for-response nnimap-sequence))
1469   nnimap-sequence)
1470
1471 (defun nnimap-log-command (command)
1472   (with-current-buffer (get-buffer-create "*imap log*")
1473     (goto-char (point-max))
1474     (insert (format-time-string "%H:%M:%S") " " command))
1475   command)
1476
1477 (defun nnimap-command (&rest args)
1478   (erase-buffer)
1479   (setf (nnimap-last-command-time nnimap-object) (current-time))
1480   (let* ((sequence (apply #'nnimap-send-command args))
1481          (response (nnimap-get-response sequence)))
1482     (if (equal (caar response) "OK")
1483         (cons t response)
1484       (nnheader-report 'nnimap "%s"
1485                        (mapconcat (lambda (a)
1486                                     (format "%s" a))
1487                                   (car response) " "))
1488       nil)))
1489
1490 (defun nnimap-get-response (sequence)
1491   (nnimap-wait-for-response sequence)
1492   (nnimap-parse-response))
1493
1494 (defun nnimap-wait-for-connection (&optional regexp)
1495   (unless regexp
1496     (setq regexp "^[*.] .*\n"))
1497   (let ((process (get-buffer-process (current-buffer))))
1498     (goto-char (point-min))
1499     (while (and (memq (process-status process)
1500                       '(open run))
1501                 (not (re-search-forward regexp nil t)))
1502       (nnheader-accept-process-output process)
1503       (goto-char (point-min)))
1504     (forward-line -1)
1505     (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1506          (match-string 1))))
1507
1508 (defun nnimap-wait-for-response (sequence &optional messagep)
1509   (let ((process (get-buffer-process (current-buffer)))
1510         openp)
1511     (condition-case nil
1512         (progn
1513           (goto-char (point-max))
1514           (while (and (setq openp (memq (process-status process)
1515                                         '(open run)))
1516                       (not (re-search-backward
1517                             (format "^%d .*\n" sequence)
1518                             (if nnimap-streaming
1519                                 (max (point-min) (- (point) 500))
1520                               (point-min))
1521                             t)))
1522             (when messagep
1523               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1524             (nnheader-accept-process-output process)
1525             (goto-char (point-max)))
1526           openp)
1527       (quit
1528        ;; The user hit C-g while we were waiting: kill the process, in case
1529        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1530        ;; NAT routers).
1531        (delete-process process)
1532        nil))))
1533
1534 (defun nnimap-parse-response ()
1535   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1536         result)
1537     (dolist (line lines)
1538       (push (cdr (nnimap-parse-line line)) result))
1539     ;; Return the OK/error code first, and then all the "continuation
1540     ;; lines" afterwards.
1541     (cons (pop result)
1542           (nreverse result))))
1543
1544 ;; Parse an IMAP response line lightly.  They look like
1545 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1546 ;; the lines into a list of strings and lists of string.
1547 (defun nnimap-parse-line (line)
1548   (let (char result)
1549     (with-temp-buffer
1550       (mm-disable-multibyte)
1551       (insert line)
1552       (goto-char (point-min))
1553       (while (not (eobp))
1554         (if (eql (setq char (following-char)) ? )
1555             (forward-char 1)
1556           (push
1557            (cond
1558             ((eql char ?\[)
1559              (split-string
1560               (buffer-substring
1561                (1+ (point))
1562                (if (search-forward "]" (line-end-position) 'move)
1563                    (1- (point))
1564                  (point)))))
1565             ((eql char ?\()
1566              (split-string
1567               (buffer-substring
1568                (1+ (point))
1569                (if (search-forward ")" (line-end-position) 'move)
1570                    (1- (point))
1571                  (point)))))
1572             ((eql char ?\")
1573              (forward-char 1)
1574              (buffer-substring
1575               (point)
1576               (1- (or (search-forward "\"" (line-end-position) 'move)
1577                       (point)))))
1578             (t
1579              (buffer-substring (point) (if (search-forward " " nil t)
1580                                            (1- (point))
1581                                          (goto-char (point-max))))))
1582            result)))
1583       (nreverse result))))
1584
1585 (defun nnimap-last-response-string ()
1586   (save-excursion
1587     (forward-line 1)
1588     (let ((end (point)))
1589       (forward-line -1)
1590       (when (not (bobp))
1591         (forward-line -1)
1592         (while (and (not (bobp))
1593                     (eql (following-char) ?*))
1594           (forward-line -1))
1595         (unless (eql (following-char) ?*)
1596           (forward-line 1)))
1597       (buffer-substring (point) end))))
1598
1599 (defun nnimap-get-responses (sequences)
1600   (let (responses)
1601     (dolist (sequence sequences)
1602       (goto-char (point-min))
1603       (when (re-search-forward (format "^%d " sequence) nil t)
1604         (push (list sequence (nnimap-parse-response))
1605               responses)))
1606     responses))
1607
1608 (defvar nnimap-incoming-split-list nil)
1609
1610 (defun nnimap-fetch-inbox (articles)
1611   (erase-buffer)
1612   (nnimap-wait-for-response
1613    (nnimap-send-command
1614     "UID FETCH %s %s"
1615     (nnimap-article-ranges articles)
1616     (format "(UID %s%s)"
1617             (format
1618              (if (nnimap-ver4-p)
1619                  "BODY.PEEK[HEADER] BODY.PEEK"
1620                "RFC822.PEEK"))
1621             (if nnimap-split-download-body-default
1622                 "[]"
1623               "[1]")))
1624    t))
1625
1626 (defun nnimap-split-incoming-mail ()
1627   (with-current-buffer (nnimap-buffer)
1628     (let ((nnimap-incoming-split-list nil)
1629           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1630                                     nnmail-split-methods
1631                                   nnimap-split-methods))
1632           (nnmail-split-fancy (or nnimap-split-fancy
1633                                   nnmail-split-fancy))
1634           (nnmail-inhibit-default-split-group t)
1635           (groups (nnimap-get-groups))
1636           new-articles)
1637       (erase-buffer)
1638       (nnimap-command "SELECT %S" nnimap-inbox)
1639       (setf (nnimap-group nnimap-object) nnimap-inbox)
1640       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1641       (when new-articles
1642         (nnimap-fetch-inbox new-articles)
1643         (nnimap-transform-split-mail)
1644         (nnheader-ms-strip-cr)
1645         (nnmail-cache-open)
1646         (nnmail-split-incoming (current-buffer)
1647                                #'nnimap-save-mail-spec
1648                                nil nil
1649                                #'nnimap-dummy-active-number
1650                                #'nnimap-save-mail-spec)
1651         (when nnimap-incoming-split-list
1652           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1653                 sequences junk-articles)
1654             ;; Create any groups that doesn't already exist on the
1655             ;; server first.
1656             (dolist (spec specs)
1657               (when (and (not (member (car spec) groups))
1658                          (not (eq (car spec) 'junk)))
1659                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1660             ;; Then copy over all the messages.
1661             (erase-buffer)
1662             (dolist (spec specs)
1663               (let ((group (car spec))
1664                     (ranges (cdr spec)))
1665                 (if (eq group 'junk)
1666                     (setq junk-articles ranges)
1667                   (push (list (nnimap-send-command
1668                                "UID COPY %s %S"
1669                                (nnimap-article-ranges ranges)
1670                                (utf7-encode group t))
1671                               ranges)
1672                         sequences))))
1673             ;; Wait for the last COPY response...
1674             (when sequences
1675               (nnimap-wait-for-response (caar sequences))
1676               ;; And then mark the successful copy actions as deleted,
1677               ;; and possibly expunge them.
1678               (nnimap-mark-and-expunge-incoming
1679                (nnimap-parse-copied-articles sequences)))
1680             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1681
1682 (defun nnimap-mark-and-expunge-incoming (range)
1683   (when range
1684     (setq range (nnimap-article-ranges range))
1685     (erase-buffer)
1686     (let ((sequence
1687            (nnimap-send-command
1688             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1689       (cond
1690        ;; If the server supports it, we now delete the message we have
1691        ;; just copied over.
1692        ((nnimap-capability "UIDPLUS")
1693         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1694        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1695        ;; user has configured it.
1696        (nnimap-expunge
1697         (setq sequence (nnimap-send-command "EXPUNGE"))))
1698       (nnimap-wait-for-response sequence))))
1699
1700 (defun nnimap-parse-copied-articles (sequences)
1701   (let (sequence copied range)
1702     (goto-char (point-min))
1703     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1704       (setq sequence (string-to-number (match-string 1)))
1705       (when (setq range (cadr (assq sequence sequences)))
1706         (push (gnus-uncompress-range range) copied)))
1707     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1708
1709 (defun nnimap-new-articles (flags)
1710   (let (new)
1711     (dolist (elem flags)
1712       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
1713                                       (cdr elem))
1714         (push (car elem) new)))
1715     (gnus-compress-sequence (nreverse new))))
1716
1717 (defun nnimap-make-split-specs (list)
1718   (let ((specs nil)
1719         entry)
1720     (dolist (elem list)
1721       (destructuring-bind (article spec) elem
1722         (dolist (group (delete nil (mapcar #'car spec)))
1723           (unless (setq entry (assoc group specs))
1724             (push (setq entry (list group)) specs))
1725           (setcdr entry (cons article (cdr entry))))))
1726     (dolist (entry specs)
1727       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1728     specs))
1729
1730 (defun nnimap-transform-split-mail ()
1731   (goto-char (point-min))
1732   (let (article bytes)
1733     (block nil
1734       (while (not (eobp))
1735         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1736           (delete-region (point) (progn (forward-line 1) (point)))
1737           (when (eobp)
1738             (return)))
1739         (setq article (match-string 1)
1740               bytes (nnimap-get-length))
1741         (delete-region (line-beginning-position) (line-end-position))
1742         ;; Insert MMDF separator, and a way to remember what this
1743         ;; article UID is.
1744         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1745         (forward-char (1+ bytes))
1746         (setq bytes (nnimap-get-length))
1747         (delete-region (line-beginning-position) (line-end-position))
1748         ;; There's a body; skip past that.
1749         (when bytes
1750           (forward-char (1+ bytes))
1751           (delete-region (line-beginning-position) (line-end-position)))))))
1752
1753 (defun nnimap-dummy-active-number (group &optional server)
1754   1)
1755
1756 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1757   (let (article)
1758     (goto-char (point-min))
1759     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1760         (error "Invalid nnimap mail")
1761       (setq article (string-to-number (match-string 1))))
1762     (push (list article
1763                 (if (eq group-art 'junk)
1764                     (list (cons 'junk 1))
1765                   group-art))
1766           nnimap-incoming-split-list)))
1767
1768 (provide 'nnimap)
1769
1770 ;;; nnimap.el ends here