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