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