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