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