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