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