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