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