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