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