(nnimap-transform-headers): Fold {quoted} strings more sloppily.
[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       ;; QRESYNC handling isn't implemented.
1013       (let ((qresyncp (member "QRESYNC" (nnimap-capabilities nnimap-object)))
1014             params groups sequences active uidvalidity modseq group)
1015         ;; Go through the infos and gather the data needed to know
1016         ;; what and how to request the data.
1017         (dolist (info infos)
1018           (setq params (gnus-info-params info)
1019                 group (gnus-group-real-name (gnus-info-group info))
1020                 active (cdr (assq 'active params))
1021                 uidvalidity (cdr (assq 'uidvalidity params))
1022                 modseq (cdr (assq 'modseq params)))
1023           (if (and qresyncp
1024                    uidvalidity
1025                    modseq)
1026               (push
1027                (list (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
1028                                           (utf7-encode group t)
1029                                           uidvalidity modseq)
1030                      'qresync
1031                      nil group 'qresync)
1032                sequences)
1033             (let ((start
1034                    (if (and active uidvalidity)
1035                        ;; Fetch the last 100 flags.
1036                        (max 1 (- (cdr active) 100))
1037                      1))
1038                   (command
1039                    (if uidvalidity
1040                        "EXAMINE"
1041                      ;; If we don't have a UIDVALIDITY, then this is
1042                      ;; the first time we've seen the group, so we
1043                      ;; have to do a SELECT (which is slower than an
1044                      ;; examine), but will tell us whether the group
1045                      ;; is read-only or not.
1046                      "SELECT")))
1047               (push (list (nnimap-send-command "%s %S" command
1048                                                (utf7-encode group t))
1049                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1050                           start group command)
1051                     sequences))))
1052         sequences))))
1053
1054 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1055   (when (and sequences
1056              (nnimap-possibly-change-group nil server))
1057     (with-current-buffer (nnimap-buffer)
1058       ;; Wait for the final data to trickle in.
1059       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1060                                           (caar sequences)
1061                                         (cadar sequences))
1062                                       t)
1063         ;; Now we should have most of the data we need, no matter
1064         ;; whether we're QRESYNCING, fetching all the flags from
1065         ;; scratch, or just fetching the last 100 flags per group.
1066         (nnimap-update-infos (nnimap-flags-to-marks
1067                               (nnimap-parse-flags
1068                                (nreverse sequences)))
1069                              infos)
1070         ;; Finally, just return something resembling an active file in
1071         ;; the nntp buffer, so that the agent can save the info, too.
1072         (with-current-buffer nntp-server-buffer
1073           (erase-buffer)
1074           (dolist (info infos)
1075             (let* ((group (gnus-info-group info))
1076                    (active (gnus-active group)))
1077               (when active
1078                 (insert (format "%S %d %d y\n"
1079                                 (gnus-group-real-name group)
1080                                 (cdr active)
1081                                 (car active)))))))))))
1082
1083 (defun nnimap-update-infos (flags infos)
1084   (dolist (info infos)
1085     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1086            (marks (cdr (assoc group flags))))
1087       (when marks
1088         (nnimap-update-info info marks)))))
1089
1090 (defun nnimap-update-info (info marks)
1091   (destructuring-bind (existing flags high low uidnext start-article
1092                                 permanent-flags uidvalidity
1093                                 vanished highestmodseq) marks
1094     (cond
1095      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1096      ;; completely empty groups.
1097      ((and (not existing)
1098            (not uidnext))
1099       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1100         (when active
1101           (gnus-set-active (gnus-info-group info) active))))
1102      ;; We have a mismatch between the old and new UIDVALIDITY
1103      ;; identifiers, so we have to re-request the group info (the next
1104      ;; time).  This virtually never happens.
1105      ((let ((old-uidvalidity
1106              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1107         (and old-uidvalidity
1108              (not (equal old-uidvalidity uidvalidity))
1109              (> start-article 1)))
1110       (gnus-group-remove-parameter info 'uidvalidity)
1111       (gnus-group-remove-parameter info 'modseq))
1112      ;; We have the data needed to update.
1113      (t
1114       (let* ((group (gnus-info-group info))
1115              (completep (and start-article
1116                              (= start-article 1)))
1117              (active (or (gnus-active group)
1118                          (cdr (assq 'active (gnus-info-params info))))))
1119         (when uidnext
1120           (setq high (1- uidnext)))
1121         ;; First set the active ranges based on high/low.
1122         (if (or completep
1123                 (not (gnus-active group)))
1124             (gnus-set-active group
1125                              (cond
1126                               ((and low high)
1127                                (cons low high))
1128                               (uidnext
1129                                ;; No articles in this group.
1130                                (cons uidnext (1- uidnext)))
1131                               (active
1132                                active)
1133                               (start-article
1134                                (cons start-article (1- start-article)))
1135                               (t
1136                                ;; No articles and no uidnext.
1137                                nil)))
1138           (gnus-set-active
1139            group
1140            (cons (car active)
1141                  (or high (1- uidnext)))))
1142         ;; See whether this is a read-only group.
1143         (unless (eq permanent-flags 'not-scanned)
1144           (gnus-group-set-parameter
1145            info 'permanent-flags
1146            (and (or (memq '%* permanent-flags)
1147                     (memq '%Seen permanent-flags))
1148                 permanent-flags)))
1149         ;; Update marks and read articles if this isn't a
1150         ;; read-only IMAP group.
1151         (when (setq permanent-flags
1152                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1153           (if (and highestmodseq
1154                    (not start-article))
1155               ;; We've gotten the data by QRESYNCing.
1156               (nnimap-update-qresync-info
1157                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1158             ;; Do normal non-QRESYNC flag updates.
1159             ;; Update the list of read articles.
1160             (let* ((unread
1161                     (gnus-compress-sequence
1162                      (gnus-set-difference
1163                       (gnus-set-difference
1164                        existing
1165                        (cdr (assoc '%Seen flags)))
1166                       (cdr (assoc '%Flagged flags)))))
1167                    (read (gnus-range-difference
1168                           (cons start-article high) unread)))
1169               (when (> start-article 1)
1170                 (setq read
1171                       (gnus-range-nconcat
1172                        (if (> start-article 1)
1173                            (gnus-sorted-range-intersection
1174                             (cons 1 (1- start-article))
1175                             (gnus-info-read info))
1176                          (gnus-info-read info))
1177                        read)))
1178               (when (or (not (listp permanent-flags))
1179                         (memq '%Seen permanent-flags))
1180                 (gnus-info-set-read info read))
1181               ;; Update the marks.
1182               (setq marks (gnus-info-marks info))
1183               (dolist (type (cdr nnimap-mark-alist))
1184                 (when (or (not (listp permanent-flags))
1185                           (memq (assoc (caddr type) flags) permanent-flags)
1186                           (memq '%* permanent-flags))
1187                   (let ((old-marks (assoc (car type) marks))
1188                         (new-marks
1189                          (gnus-compress-sequence
1190                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1191                                    (assoc (intern (cadr type) obarray) flags)
1192                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1193                     (setq marks (delq old-marks marks))
1194                     (pop old-marks)
1195                     (when (and old-marks
1196                                (> start-article 1))
1197                       (setq old-marks (gnus-range-difference
1198                                        old-marks
1199                                        (cons start-article high)))
1200                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1201                     (when new-marks
1202                       (push (cons (car type) new-marks) marks)))))
1203               (gnus-info-set-marks info marks t))))
1204         ;; Note the active level for the next run-through.
1205         (gnus-group-set-parameter info 'active (gnus-active group))
1206         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1207         (gnus-group-set-parameter info 'modseq highestmodseq)
1208         (nnimap-store-info info (gnus-active group)))))))
1209
1210 (defun nnimap-update-qresync-info (info existing vanished flags)
1211   ;; Add all the vanished articles to the list of read articles.
1212   (gnus-info-set-read
1213    info
1214    (gnus-add-to-range
1215     (gnus-add-to-range
1216      (gnus-range-add (gnus-info-read info)
1217                      vanished)
1218      (cdr (assq '%Flagged flags)))
1219     (cdr (assq '%Seen flags))))
1220   (let ((marks (gnus-info-marks info)))
1221     (dolist (type (cdr nnimap-mark-alist))
1222       (let ((ticks (assoc (car type) marks))
1223             (new-marks
1224              (cdr (or (assoc (caddr type) flags) ; %Flagged
1225                       (assoc (intern (cadr type) obarray) flags)
1226                       (assoc (cadr type) flags))))) ; "\Flagged"
1227         (setq marks (delq ticks marks))
1228         (pop ticks)
1229         ;; Add the new marks we got.
1230         (setq ticks (gnus-add-to-range ticks new-marks))
1231         ;; Remove the marks from messages that don't have them.
1232         (setq ticks (gnus-remove-from-range
1233                      ticks
1234                      (gnus-compress-sequence
1235                       (gnus-sorted-complement existing new-marks))))
1236         (when ticks
1237           (push (cons (car type) ticks) marks)))
1238       (gnus-info-set-marks info marks t))))
1239
1240 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1241   (if (zerop (length irange))
1242       nil
1243     (let ((result nil))
1244       (dolist (elem (split-string irange ","))
1245         (push
1246          (if (string-match ":" elem)
1247              (let ((numbers (split-string elem ":")))
1248                (cons (string-to-number (car numbers))
1249                      (string-to-number (cadr numbers))))
1250            (string-to-number elem))
1251          result))
1252       (nreverse result))))
1253
1254 (defun nnimap-store-info (info active)
1255   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1256          (entry (assoc group nnimap-current-infos)))
1257     (if entry
1258         (setcdr entry (list info active))
1259       (push (list group info active) nnimap-current-infos))))
1260
1261 (defun nnimap-flags-to-marks (groups)
1262   (let (data group totalp uidnext articles start-article mark permanent-flags
1263              uidvalidity vanished highestmodseq)
1264     (dolist (elem groups)
1265       (setq group (car elem)
1266             uidnext (nth 1 elem)
1267             start-article (nth 2 elem)
1268             permanent-flags (nth 3 elem)
1269             uidvalidity (nth 4 elem)
1270             vanished (nth 5 elem)
1271             highestmodseq (nth 6 elem)
1272             articles (nthcdr 7 elem))
1273       (let ((high (caar articles))
1274             marks low existing)
1275         (dolist (article articles)
1276           (setq low (car article))
1277           (push (car article) existing)
1278           (dolist (flag (cdr article))
1279             (setq mark (assoc flag marks))
1280             (if (not mark)
1281                 (push (list flag (car article)) marks)
1282               (setcdr mark (cons (car article) (cdr mark))))))
1283         (push (list group existing marks high low uidnext start-article
1284                     permanent-flags uidvalidity vanished highestmodseq)
1285               data)))
1286     data))
1287
1288 (defun nnimap-parse-flags (sequences)
1289   (goto-char (point-min))
1290   ;; Change \Delete etc to %Delete, so that the reader can read it.
1291   (subst-char-in-region (point-min) (point-max)
1292                         ?\\ ?% t)
1293   (let (start end articles groups uidnext elems permanent-flags
1294               uidvalidity vanished highestmodseq)
1295     (dolist (elem sequences)
1296       (destructuring-bind (group-sequence flag-sequence totalp group command)
1297           elem
1298         (setq start (point))
1299         (when (and
1300                ;; The EXAMINE was successful.
1301                (search-forward (format "\n%d OK " group-sequence) nil t)
1302                (progn
1303                  (forward-line 1)
1304                  (setq end (point))
1305                  (goto-char start)
1306                  (setq permanent-flags
1307                        (if (equal command "SELECT")
1308                            (and (search-forward "PERMANENTFLAGS "
1309                                                 (or end (point-min)) t)
1310                                 (read (current-buffer)))
1311                          'not-scanned))
1312                  (goto-char start)
1313                  (setq uidnext
1314                        (and (search-forward "UIDNEXT "
1315                                             (or end (point-min)) t)
1316                             (read (current-buffer))))
1317                  (goto-char start)
1318                  (setq uidvalidity
1319                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1320                                                (or end (point-min)) t)
1321                             ;; Store UIDVALIDITY as a string, as it's
1322                             ;; too big for 32-bit Emacsen, usually.
1323                             (match-string 1)))
1324                  (goto-char start)
1325                  (setq vanished
1326                        (and (eq flag-sequence 'qresync)
1327                             (re-search-forward "VANISHED.* \\([0-9:,]+\\)"
1328                                                (or end (point-min)) t)
1329                             (match-string 1)))
1330                  (goto-char start)
1331                  (setq highestmodseq
1332                        (and (search-forward "HIGHESTMODSEQ "
1333                                             (or end (point-min)) t)
1334                             (read (current-buffer))))
1335                  (goto-char end)
1336                  (forward-line -1))
1337                ;; The UID FETCH FLAGS was successful.
1338                (or (eq flag-sequence 'qresync)
1339                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1340           (if (eq flag-sequence 'qresync)
1341               (progn
1342                 (goto-char start)
1343                 (setq start end))
1344             (setq start (point))
1345             (goto-char end))
1346           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1347             (setq elems (read (current-buffer)))
1348             (push (cons (cadr (memq 'UID elems))
1349                         (cadr (memq 'FLAGS elems)))
1350                   articles))
1351           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1352                              vanished highestmodseq)
1353                        articles)
1354                 groups)
1355           (goto-char end)
1356           (setq articles nil))))
1357     groups))
1358
1359 (defun nnimap-find-process-buffer (buffer)
1360   (cadr (assoc buffer nnimap-connection-alist)))
1361
1362 (deffoo nnimap-request-post (&optional server)
1363   (setq nnimap-status-string "Read-only server")
1364   nil)
1365
1366 (deffoo nnimap-request-thread (id)
1367     (let* ((refs (split-string
1368                (or (mail-header-references (gnus-summary-article-header))
1369                    "")))
1370            (cmd (let ((value
1371                        (format
1372                         "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1373                         id id)))
1374                   (dolist (refid refs value)
1375                     (setq value (format
1376                                  "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1377                                  refid refid value)))))
1378            (result
1379             (with-current-buffer (nnimap-buffer)
1380               (nnimap-command  "UID SEARCH %s" cmd))))
1381       (gnus-fetch-headers (and (car result)
1382            (delete 0 (mapcar #'string-to-number
1383                              (cdr (assoc "SEARCH" (cdr result)))))))))
1384
1385 (defun nnimap-possibly-change-group (group server)
1386   (let ((open-result t))
1387     (when (and server
1388                (not (nnimap-server-opened server)))
1389       (setq open-result (nnimap-open-server server)))
1390     (cond
1391      ((not open-result)
1392       nil)
1393      ((not group)
1394       t)
1395      (t
1396       (with-current-buffer (nnimap-buffer)
1397         (if (equal group (nnimap-group nnimap-object))
1398             t
1399           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1400             (when (car result)
1401               (setf (nnimap-group nnimap-object) group
1402                     (nnimap-select-result nnimap-object) result)
1403               result))))))))
1404
1405 (defun nnimap-find-connection (buffer)
1406   "Find the connection delivering to BUFFER."
1407   (let ((entry (assoc buffer nnimap-connection-alist)))
1408     (when entry
1409       (if (and (buffer-name (cadr entry))
1410                (get-buffer-process (cadr entry))
1411                (memq (process-status (get-buffer-process (cadr entry)))
1412                      '(open run)))
1413           (get-buffer-process (cadr entry))
1414         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1415         nil))))
1416
1417 (defvar nnimap-sequence 0)
1418
1419 (defun nnimap-send-command (&rest args)
1420   (process-send-string
1421    (get-buffer-process (current-buffer))
1422    (nnimap-log-command
1423     (format "%d %s%s\n"
1424             (incf nnimap-sequence)
1425             (apply #'format args)
1426             (if (nnimap-newlinep nnimap-object)
1427                 ""
1428               "\r"))))
1429   ;; Some servers apparently can't have many outstanding
1430   ;; commands, so throttle them.
1431   (unless nnimap-streaming
1432     (nnimap-wait-for-response nnimap-sequence))
1433   nnimap-sequence)
1434
1435 (defun nnimap-log-command (command)
1436   (with-current-buffer (get-buffer-create "*imap log*")
1437     (goto-char (point-max))
1438     (insert (format-time-string "%H:%M:%S") " " command))
1439   command)
1440
1441 (defun nnimap-command (&rest args)
1442   (erase-buffer)
1443   (setf (nnimap-last-command-time nnimap-object) (current-time))
1444   (let* ((sequence (apply #'nnimap-send-command args))
1445          (response (nnimap-get-response sequence)))
1446     (if (equal (caar response) "OK")
1447         (cons t response)
1448       (nnheader-report 'nnimap "%s"
1449                        (mapconcat (lambda (a)
1450                                     (format "%s" a))
1451                                   (car response) " "))
1452       nil)))
1453
1454 (defun nnimap-get-response (sequence)
1455   (nnimap-wait-for-response sequence)
1456   (nnimap-parse-response))
1457
1458 (defun nnimap-wait-for-connection ()
1459   (let ((process (get-buffer-process (current-buffer))))
1460     (goto-char (point-min))
1461     (while (and (memq (process-status process)
1462                       '(open run))
1463                 (not (re-search-forward "^[*.] .*\n" nil t)))
1464       (nnheader-accept-process-output process)
1465       (goto-char (point-min)))
1466     (forward-line -1)
1467     (and (looking-at "[*.] \\([A-Z0-9]+\\)")
1468          (match-string 1))))
1469
1470 (defun nnimap-wait-for-response (sequence &optional messagep)
1471   (let ((process (get-buffer-process (current-buffer)))
1472         openp)
1473     (condition-case nil
1474         (progn
1475           (goto-char (point-max))
1476           (while (and (setq openp (memq (process-status process)
1477                                         '(open run)))
1478                       (not (re-search-backward
1479                             (format "^%d .*\n" sequence)
1480                             (if nnimap-streaming
1481                                 (max (point-min) (- (point) 500))
1482                               (point-min))
1483                             t)))
1484             (when messagep
1485               (nnheader-message 7 "nnimap read %dk" (/ (buffer-size) 1000)))
1486             (nnheader-accept-process-output process)
1487             (goto-char (point-max)))
1488           openp)
1489       (quit
1490        ;; The user hit C-g while we were waiting: kill the process, in case
1491        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1492        ;; NAT routers).
1493        (delete-process process)
1494        nil))))
1495
1496 (defun nnimap-parse-response ()
1497   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1498         result)
1499     (dolist (line lines)
1500       (push (cdr (nnimap-parse-line line)) result))
1501     ;; Return the OK/error code first, and then all the "continuation
1502     ;; lines" afterwards.
1503     (cons (pop result)
1504           (nreverse result))))
1505
1506 ;; Parse an IMAP response line lightly.  They look like
1507 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1508 ;; the lines into a list of strings and lists of string.
1509 (defun nnimap-parse-line (line)
1510   (let (char result)
1511     (with-temp-buffer
1512       (mm-disable-multibyte)
1513       (insert line)
1514       (goto-char (point-min))
1515       (while (not (eobp))
1516         (if (eql (setq char (following-char)) ? )
1517             (forward-char 1)
1518           (push
1519            (cond
1520             ((eql char ?\[)
1521              (split-string
1522               (buffer-substring
1523                (1+ (point))
1524                (1- (search-forward "]" (line-end-position) 'move)))))
1525             ((eql char ?\()
1526              (split-string
1527               (buffer-substring
1528                (1+ (point))
1529                (1- (search-forward ")" (line-end-position) 'move)))))
1530             ((eql char ?\")
1531              (forward-char 1)
1532              (buffer-substring
1533               (point)
1534               (1- (or (search-forward "\"" (line-end-position) 'move)
1535                       (point)))))
1536             (t
1537              (buffer-substring (point) (if (search-forward " " nil t)
1538                                            (1- (point))
1539                                          (goto-char (point-max))))))
1540            result)))
1541       (nreverse result))))
1542
1543 (defun nnimap-last-response-string ()
1544   (save-excursion
1545     (forward-line 1)
1546     (let ((end (point)))
1547       (forward-line -1)
1548       (when (not (bobp))
1549         (forward-line -1)
1550         (while (and (not (bobp))
1551                     (eql (following-char) ?*))
1552           (forward-line -1))
1553         (unless (eql (following-char) ?*)
1554           (forward-line 1)))
1555       (buffer-substring (point) end))))
1556
1557 (defun nnimap-get-responses (sequences)
1558   (let (responses)
1559     (dolist (sequence sequences)
1560       (goto-char (point-min))
1561       (when (re-search-forward (format "^%d " sequence) nil t)
1562         (push (list sequence (nnimap-parse-response))
1563               responses)))
1564     responses))
1565
1566 (defvar nnimap-incoming-split-list nil)
1567
1568 (defun nnimap-fetch-inbox (articles)
1569   (erase-buffer)
1570   (nnimap-wait-for-response
1571    (nnimap-send-command
1572     "UID FETCH %s %s"
1573     (nnimap-article-ranges articles)
1574     (format "(UID %s%s)"
1575             (format
1576              (if (nnimap-ver4-p)
1577                  "BODY.PEEK[HEADER] BODY.PEEK"
1578                "RFC822.PEEK"))
1579             (if nnimap-split-download-body-default
1580                 "[]"
1581               "[1]")))
1582    t))
1583
1584 (defun nnimap-split-incoming-mail ()
1585   (with-current-buffer (nnimap-buffer)
1586     (let ((nnimap-incoming-split-list nil)
1587           (nnmail-split-methods (if (eq nnimap-split-methods 'default)
1588                                     nnmail-split-methods
1589                                   nnimap-split-methods))
1590           (nnmail-split-fancy (or nnimap-split-fancy
1591                                   nnmail-split-fancy))
1592           (nnmail-inhibit-default-split-group t)
1593           (groups (nnimap-get-groups))
1594           new-articles)
1595       (erase-buffer)
1596       (nnimap-command "SELECT %S" nnimap-inbox)
1597       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1598       (when new-articles
1599         (nnimap-fetch-inbox new-articles)
1600         (nnimap-transform-split-mail)
1601         (nnheader-ms-strip-cr)
1602         (nnmail-cache-open)
1603         (nnmail-split-incoming (current-buffer)
1604                                #'nnimap-save-mail-spec
1605                                nil nil
1606                                #'nnimap-dummy-active-number
1607                                #'nnimap-save-mail-spec)
1608         (when nnimap-incoming-split-list
1609           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1610                 sequences junk-articles)
1611             ;; Create any groups that doesn't already exist on the
1612             ;; server first.
1613             (dolist (spec specs)
1614               (when (and (not (member (car spec) groups))
1615                          (not (eq (car spec) 'junk)))
1616                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1617             ;; Then copy over all the messages.
1618             (erase-buffer)
1619             (dolist (spec specs)
1620               (let ((group (car spec))
1621                     (ranges (cdr spec)))
1622                 (if (eq group 'junk)
1623                     (setq junk-articles ranges)
1624                   (push (list (nnimap-send-command
1625                                "UID COPY %s %S"
1626                                (nnimap-article-ranges ranges)
1627                                (utf7-encode group t))
1628                               ranges)
1629                         sequences))))
1630             ;; Wait for the last COPY response...
1631             (when sequences
1632               (nnimap-wait-for-response (caar sequences))
1633               ;; And then mark the successful copy actions as deleted,
1634               ;; and possibly expunge them.
1635               (nnimap-mark-and-expunge-incoming
1636                (nnimap-parse-copied-articles sequences)))
1637             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1638
1639 (defun nnimap-mark-and-expunge-incoming (range)
1640   (when range
1641     (setq range (nnimap-article-ranges range))
1642     (erase-buffer)
1643     (let ((sequence
1644            (nnimap-send-command
1645             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1646       (cond
1647        ;; If the server supports it, we now delete the message we have
1648        ;; just copied over.
1649        ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1650         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1651        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1652        ;; user has configured it.
1653        (nnimap-expunge
1654         (setq sequence (nnimap-send-command "EXPUNGE"))))
1655       (nnimap-wait-for-response sequence))))
1656
1657 (defun nnimap-parse-copied-articles (sequences)
1658   (let (sequence copied range)
1659     (goto-char (point-min))
1660     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1661       (setq sequence (string-to-number (match-string 1)))
1662       (when (setq range (cadr (assq sequence sequences)))
1663         (push (gnus-uncompress-range range) copied)))
1664     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1665
1666 (defun nnimap-new-articles (flags)
1667   (let (new)
1668     (dolist (elem flags)
1669       (when (or (null (cdr elem))
1670                 (and (not (memq '%Deleted (cdr elem)))
1671                      (not (memq '%Seen (cdr elem)))))
1672         (push (car elem) new)))
1673     (gnus-compress-sequence (nreverse new))))
1674
1675 (defun nnimap-make-split-specs (list)
1676   (let ((specs nil)
1677         entry)
1678     (dolist (elem list)
1679       (destructuring-bind (article spec) elem
1680         (dolist (group (delete nil (mapcar #'car spec)))
1681           (unless (setq entry (assoc group specs))
1682             (push (setq entry (list group)) specs))
1683           (setcdr entry (cons article (cdr entry))))))
1684     (dolist (entry specs)
1685       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1686     specs))
1687
1688 (defun nnimap-transform-split-mail ()
1689   (goto-char (point-min))
1690   (let (article bytes)
1691     (block nil
1692       (while (not (eobp))
1693         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1694           (delete-region (point) (progn (forward-line 1) (point)))
1695           (when (eobp)
1696             (return)))
1697         (setq article (match-string 1)
1698               bytes (nnimap-get-length))
1699         (delete-region (line-beginning-position) (line-end-position))
1700         ;; Insert MMDF separator, and a way to remember what this
1701         ;; article UID is.
1702         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1703         (forward-char (1+ bytes))
1704         (setq bytes (nnimap-get-length))
1705         (delete-region (line-beginning-position) (line-end-position))
1706         ;; There's a body; skip past that.
1707         (when bytes
1708           (forward-char (1+ bytes))
1709           (delete-region (line-beginning-position) (line-end-position)))))))
1710
1711 (defun nnimap-dummy-active-number (group &optional server)
1712   1)
1713
1714 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1715   (let (article)
1716     (goto-char (point-min))
1717     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1718         (error "Invalid nnimap mail")
1719       (setq article (string-to-number (match-string 1))))
1720     (push (list article
1721                 (if (eq group-art 'junk)
1722                     (list (cons 'junk 1))
1723                   group-art))
1724           nnimap-incoming-split-list)))
1725
1726 (provide 'nnimap)
1727
1728 ;;; nnimap.el ends here