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