d7dc1fbd070aaab2bcaec16aa09ecc8d7a85bf14
[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         (re-search-forward "^\r$")
207         (delete-region (line-beginning-position) (line-end-position))
208         (insert ".")
209         (forward-line 1)))))
210
211 (defun nnimap-get-length ()
212   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
213        (string-to-number (match-string 1))))
214
215 (defun nnimap-article-ranges (ranges)
216   (let (result)
217     (cond
218      ((numberp ranges)
219       (number-to-string ranges))
220      ((numberp (cdr ranges))
221       (format "%d:%d" (car ranges) (cdr ranges)))
222      (t
223       (dolist (elem ranges)
224         (push
225          (if (consp elem)
226              (format "%d:%d" (car elem) (cdr elem))
227            (number-to-string elem))
228          result))
229       (mapconcat #'identity (nreverse result) ",")))))
230
231 (deffoo nnimap-open-server (server &optional defs)
232   (if (nnimap-server-opened server)
233       t
234     (unless (assq 'nnimap-address defs)
235       (setq defs (append defs (list (list 'nnimap-address server)))))
236     (nnoo-change-server 'nnimap server defs)
237     (or (nnimap-find-connection nntp-server-buffer)
238         (nnimap-open-connection nntp-server-buffer))))
239
240 (defun nnimap-make-process-buffer (buffer)
241   (with-current-buffer
242       (generate-new-buffer (format "*nnimap %s %s %s*"
243                                    nnimap-address nnimap-server-port
244                                    (gnus-buffer-exists-p buffer)))
245     (mm-disable-multibyte)
246     (buffer-disable-undo)
247     (gnus-add-buffer)
248     (set (make-local-variable 'after-change-functions) nil)
249     (set (make-local-variable 'nnimap-object)
250          (make-nnimap :server (nnoo-current-server 'nnimap)))
251     (push (list buffer (current-buffer)) nnimap-connection-alist)
252     (push (current-buffer) nnimap-process-buffers)
253     (current-buffer)))
254
255 (defun nnimap-open-shell-stream (name buffer host port)
256   (let ((process-connection-type nil))
257     (start-process name buffer shell-file-name
258                    shell-command-switch
259                    (format-spec
260                     nnimap-shell-program
261                     (format-spec-make
262                      ?s host
263                      ?p port)))))
264
265 (defun nnimap-credentials (address ports &optional inhibit-create)
266   (let (port credentials)
267     ;; Request the credentials from all ports, but only query on the
268     ;; last port if all the previous ones have failed.
269     (while (and (null credentials)
270                 (setq port (pop ports)))
271       (setq credentials
272             (auth-source-user-or-password
273              '("login" "password") address port nil
274              (if inhibit-create
275                  nil
276                (null ports)))))
277     credentials))
278
279 (defun nnimap-keepalive ()
280   (let ((now (current-time)))
281     (dolist (buffer nnimap-process-buffers)
282       (when (buffer-name buffer)
283         (with-current-buffer buffer
284           (when (and nnimap-object
285                      (nnimap-last-command-time nnimap-object)
286                      (> (time-to-seconds
287                          (time-subtract
288                           now
289                           (nnimap-last-command-time nnimap-object)))
290                         ;; More than five minutes since the last command.
291                         (* 5 60)))
292             (nnimap-send-command "NOOP")))))))
293
294 (declare-function gnutls-negotiate "subr" (fn file &optional arglist fileonly))
295
296 (defun nnimap-open-connection (buffer)
297   (unless nnimap-keepalive-timer
298     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
299                                               'nnimap-keepalive)))
300   (block nil
301     (with-current-buffer (nnimap-make-process-buffer buffer)
302       (let* ((coding-system-for-read 'binary)
303              (coding-system-for-write 'binary)
304              (port nil)
305              (ports
306               (cond
307                ((or (eq nnimap-stream 'network)
308                     (and (eq nnimap-stream 'starttls)
309                          (fboundp 'open-gnutls-stream)))
310                 (nnheader-message 7 "Opening connection to %s..."
311                                   nnimap-address)
312                 (open-network-stream
313                  "*nnimap*" (current-buffer) nnimap-address
314                  (setq port
315                        (or nnimap-server-port
316                            (if (netrc-find-service-number "imap")
317                                "imap"
318                              "143"))))
319                 '("143" "imap"))
320                ((eq nnimap-stream 'shell)
321                 (nnheader-message 7 "Opening connection to %s via shell..."
322                                   nnimap-address)
323                 (nnimap-open-shell-stream
324                  "*nnimap*" (current-buffer) nnimap-address
325                  (setq port (or nnimap-server-port "imap")))
326                 '("imap"))
327                ((eq nnimap-stream 'starttls)
328                 (nnheader-message 7 "Opening connection to %s via starttls..."
329                          nnimap-address)
330                 (let ((tls-program
331                        '("openssl s_client -connect %h:%p -no_ssl2 -ign_eof -starttls imap")))
332                   (open-tls-stream
333                    "*nnimap*" (current-buffer) nnimap-address
334                    (setq port (or nnimap-server-port "imap"))))
335                 '("imap"))
336                ((memq nnimap-stream '(ssl tls))
337                 (nnheader-message 7 "Opening connection to %s via tls..."
338                                   nnimap-address)
339                 (funcall (if (fboundp 'open-gnutls-stream)
340                              'open-gnutls-stream
341                            'open-tls-stream)
342                          "*nnimap*" (current-buffer) nnimap-address
343                          (setq port
344                                (or nnimap-server-port
345                                    (if (netrc-find-service-number "imaps")
346                                        "imaps"
347                                      "993"))))
348                 '("143" "993" "imap" "imaps"))
349                (t
350                 (error "Unknown stream type: %s" nnimap-stream))))
351              connection-result login-result credentials)
352         (setf (nnimap-process nnimap-object)
353               (get-buffer-process (current-buffer)))
354         (if (not (and (nnimap-process nnimap-object)
355                       (memq (process-status (nnimap-process nnimap-object))
356                             '(open run))))
357             (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
358                              nnimap-address port nnimap-stream)
359           (gnus-set-process-query-on-exit-flag
360            (nnimap-process nnimap-object) nil)
361           (if (not (setq connection-result (nnimap-wait-for-connection)))
362               (nnheader-report 'nnimap
363                                "%s" (buffer-substring
364                                      (point) (line-end-position)))
365             ;; Store the greeting (for debugging purposes).
366             (setf (nnimap-greeting nnimap-object)
367                   (buffer-substring (line-beginning-position)
368                                     (line-end-position)))
369             ;; Store the capabilities.
370             (setf (nnimap-capabilities nnimap-object)
371                   (mapcar
372                    #'upcase
373                    (nnimap-find-parameter
374                     "CAPABILITY" (cdr (nnimap-command "CAPABILITY")))))
375             (when nnimap-server-port
376               (push (format "%s" nnimap-server-port) ports))
377             ;; If this is a STARTTLS-capable server, then sever the
378             ;; connection and start a STARTTLS connection instead.
379             (cond
380              ((and (or (and (eq nnimap-stream 'network)
381                             (member "STARTTLS"
382                                     (nnimap-capabilities nnimap-object)))
383                        (eq nnimap-stream 'starttls))
384                    (fboundp 'open-gnutls-stream))
385               (nnimap-command "STARTTLS")
386               (gnutls-negotiate (nnimap-process nnimap-object) nil))
387              ((and (eq nnimap-stream 'network)
388                    (member "STARTTLS" (nnimap-capabilities nnimap-object)))
389               (let ((nnimap-stream 'starttls))
390                 (let ((tls-process
391                        (nnimap-open-connection buffer)))
392                   ;; If the STARTTLS connection was successful, we
393                   ;; kill our first non-encrypted connection.  If it
394                   ;; wasn't successful, we just use our unencrypted
395                   ;; connection.
396                   (when (memq (process-status tls-process) '(open run))
397                     (delete-process (nnimap-process nnimap-object))
398                     (kill-buffer (current-buffer))
399                     (return tls-process))))))
400             (unless (equal connection-result "PREAUTH")
401               (if (not (setq credentials
402                              (if (eq nnimap-authenticator 'anonymous)
403                                  (list "anonymous"
404                                        (message-make-address))
405                                (or
406                                 ;; First look for the credentials based
407                                 ;; on the virtual server name.
408                                 (nnimap-credentials
409                                  (nnoo-current-server 'nnimap) ports t)
410                                 ;; Then look them up based on the
411                                 ;; physical address.
412                                 (nnimap-credentials nnimap-address ports)))))
413                   (setq nnimap-object nil)
414                 (setq login-result (nnimap-command "LOGIN %S %S"
415                                                    (car credentials)
416                                                    (cadr credentials)))
417                 (unless (car login-result)
418                   ;; If the login failed, then forget the credentials
419                   ;; that are now possibly cached.
420                   (dolist (host (list (nnoo-current-server 'nnimap)
421                                       nnimap-address))
422                     (dolist (port ports)
423                       (dolist (element '("login" "password"))
424                         (auth-source-forget-user-or-password
425                          element host port))))
426                   (delete-process (nnimap-process nnimap-object))
427                   (setq nnimap-object nil))))
428             (when nnimap-object
429               (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
430                 (nnimap-command "ENABLE QRESYNC"))
431               (nnimap-process nnimap-object))))))))
432
433 (defun nnimap-find-parameter (parameter elems)
434   (let (result)
435     (dolist (elem elems)
436       (cond
437        ((equal (car elem) parameter)
438         (setq result (cdr elem)))
439        ((and (equal (car elem) "OK")
440              (consp (cadr elem))
441              (equal (caadr elem) parameter))
442         (setq result (cdr (cadr elem))))))
443     result))
444
445 (deffoo nnimap-close-server (&optional server)
446   (when (nnoo-change-server 'nnimap server nil)
447     (ignore-errors
448       (delete-process (get-buffer-process (nnimap-buffer))))
449     (nnoo-close-server 'nnimap server)
450     t))
451
452 (deffoo nnimap-request-close ()
453   t)
454
455 (deffoo nnimap-server-opened (&optional server)
456   (and (nnoo-current-server-p 'nnimap server)
457        nntp-server-buffer
458        (gnus-buffer-live-p nntp-server-buffer)
459        (nnimap-find-connection nntp-server-buffer)))
460
461 (deffoo nnimap-status-message (&optional server)
462   nnimap-status-string)
463
464 (deffoo nnimap-request-article (article &optional group server to-buffer)
465   (with-current-buffer nntp-server-buffer
466     (let ((result (nnimap-possibly-change-group group server))
467           parts structure)
468       (when (stringp article)
469         (setq article (nnimap-find-article-by-message-id group article)))
470       (when (and result
471                  article)
472         (erase-buffer)
473         (with-current-buffer (nnimap-buffer)
474           (erase-buffer)
475           (when nnimap-fetch-partial-articles
476             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
477             (goto-char (point-min))
478             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
479               (setq structure (ignore-errors
480                                 (let ((start (point)))
481                                   (forward-sexp 1)
482                                   (downcase-region start (point))
483                                   (goto-char start)
484                                   (read (current-buffer))))
485                     parts (nnimap-find-wanted-parts structure))))
486           (when (if parts
487                     (nnimap-get-partial-article article parts structure)
488                   (nnimap-get-whole-article article))
489             (let ((buffer (current-buffer)))
490               (with-current-buffer (or to-buffer nntp-server-buffer)
491                 (erase-buffer)
492                 (insert-buffer-substring buffer)
493                 (nnheader-ms-strip-cr)
494                 (cons group article)))))))))
495
496 (deffoo nnimap-request-head (article &optional group server to-buffer)
497   (when (nnimap-possibly-change-group group server)
498     (with-current-buffer (nnimap-buffer)
499       (when (stringp article)
500         (setq article (nnimap-find-article-by-message-id group article)))
501       (nnimap-get-whole-article
502        article (format "UID FETCH %%d %s"
503                        (nnimap-header-parameters)))
504       (let ((buffer (current-buffer)))
505         (with-current-buffer (or to-buffer nntp-server-buffer)
506           (erase-buffer)
507           (insert-buffer-substring buffer)
508           (nnheader-ms-strip-cr)
509           (cons group article))))))
510
511 (defun nnimap-get-whole-article (article &optional command)
512   (let ((result
513          (nnimap-command
514           (or command
515               (if (nnimap-ver4-p)
516                   "UID FETCH %d BODY.PEEK[]"
517                 "UID FETCH %d RFC822.PEEK"))
518           article)))
519     ;; Check that we really got an article.
520     (goto-char (point-min))
521     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
522       (setq result nil))
523     (when result
524       ;; Remove any data that may have arrived before the FETCH data.
525       (beginning-of-line)
526       (unless (bobp)
527         (delete-region (point-min) (point)))
528       (let ((bytes (nnimap-get-length)))
529         (delete-region (line-beginning-position)
530                        (progn (forward-line 1) (point)))
531         (goto-char (+ (point) bytes))
532         (delete-region (point) (point-max)))
533       t)))
534
535 (defun nnimap-ver4-p ()
536   (member "IMAP4REV1" (nnimap-capabilities nnimap-object)))
537
538 (defun nnimap-get-partial-article (article parts structure)
539   (let ((result
540          (nnimap-command
541           "UID FETCH %d (%s %s)"
542           article
543           (if (nnimap-ver4-p)
544               "BODY.PEEK[HEADER]"
545             "RFC822.HEADER")
546           (if (nnimap-ver4-p)
547               (mapconcat (lambda (part)
548                            (format "BODY.PEEK[%s]" part))
549                          parts " ")
550             (mapconcat (lambda (part)
551                          (format "RFC822.PEEK[%s]" part))
552                        parts " ")))))
553     (when result
554       (nnimap-convert-partial-article structure))))
555
556 (defun nnimap-convert-partial-article (structure)
557   ;; First just skip past the headers.
558   (goto-char (point-min))
559   (let ((bytes (nnimap-get-length))
560         id parts)
561     ;; Delete "FETCH" line.
562     (delete-region (line-beginning-position)
563                    (progn (forward-line 1) (point)))
564     (goto-char (+ (point) bytes))
565     ;; Collect all the body parts.
566     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
567       (setq id (match-string 1)
568             bytes (nnimap-get-length))
569       (beginning-of-line)
570       (delete-region (point) (progn (forward-line 1) (point)))
571       (push (list id (buffer-substring (point) (+ (point) bytes)))
572             parts)
573       (delete-region (point) (+ (point) bytes)))
574     ;; Delete trailing junk.
575     (delete-region (point) (point-max))
576     ;; Now insert all the parts again where they fit in the structure.
577     (nnimap-insert-partial-structure structure parts)
578     t))
579
580 (defun nnimap-insert-partial-structure (structure parts &optional subp)
581   (let (type boundary)
582     (let ((bstruc structure))
583       (while (consp (car bstruc))
584         (pop bstruc))
585       (setq type (car bstruc))
586       (setq bstruc (car (cdr bstruc)))
587       (let ((has-boundary (member "boundary" bstruc)))
588         (when has-boundary
589           (setq boundary (cadr has-boundary)))))
590     (when subp
591       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
592                       (downcase type) boundary)))
593     (while (not (stringp (car structure)))
594       (insert "\n--" boundary "\n")
595       (if (consp (caar structure))
596           (nnimap-insert-partial-structure (pop structure) parts t)
597         (let ((bit (pop structure)))
598           (insert (format  "Content-type: %s/%s"
599                            (downcase (nth 0 bit))
600                            (downcase (nth 1 bit))))
601           (if (member "CHARSET" (nth 2 bit))
602               (insert (format
603                        "; charset=%S\n" (cadr (member "CHARSET" (nth 2 bit)))))
604             (insert "\n"))
605           (insert (format "Content-transfer-encoding: %s\n"
606                           (nth 5 bit)))
607           (insert "\n")
608           (when (assoc (nth 9 bit) parts)
609             (insert (cadr (assoc (nth 9 bit) parts)))))))
610     (insert "\n--" boundary "--\n")))
611
612 (defun nnimap-find-wanted-parts (structure)
613   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
614
615 (defun nnimap-find-wanted-parts-1 (structure prefix)
616   (let ((num 1)
617         parts)
618     (while (consp (car structure))
619       (let ((sub (pop structure)))
620         (if (consp (car sub))
621             (push (nnimap-find-wanted-parts-1
622                    sub (if (string= prefix "")
623                            (number-to-string num)
624                          (format "%s.%s" prefix num)))
625                   parts)
626           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
627                 (id (if (string= prefix "")
628                         (number-to-string num)
629                       (format "%s.%s" prefix num))))
630             (setcar (nthcdr 9 sub) id)
631             (when (if (eq nnimap-fetch-partial-articles t)
632                       (equal id "1")
633                     (string-match nnimap-fetch-partial-articles type))
634               (push id parts))))
635         (incf num)))
636     (nreverse parts)))
637
638 (deffoo nnimap-request-group (group &optional server dont-check info)
639   (let ((result (nnimap-possibly-change-group
640                  ;; Don't SELECT the group if we're going to select it
641                  ;; later, anyway.
642                  (if dont-check
643                      nil
644                    group)
645                  server))
646         articles active marks high low)
647     (with-current-buffer nntp-server-buffer
648       (when result
649         (if (and dont-check
650                  (setq active (nth 2 (assoc group nnimap-current-infos))))
651             (insert (format "211 %d %d %d %S\n"
652                             (- (cdr active) (car active))
653                             (car active)
654                             (cdr active)
655                             group))
656           (with-current-buffer (nnimap-buffer)
657             (erase-buffer)
658             (let ((group-sequence
659                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
660                   (flag-sequence
661                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
662               (setf (nnimap-group nnimap-object) group)
663               (nnimap-wait-for-response flag-sequence)
664               (setq marks
665                     (nnimap-flags-to-marks
666                      (nnimap-parse-flags
667                       (list (list group-sequence flag-sequence
668                                   1 group "SELECT")))))
669               (when (and info
670                          marks)
671                 (nnimap-update-infos marks (list info)))
672               (goto-char (point-max))
673               (let ((uidnext (nth 5 (car marks))))
674                 (setq high (or (if uidnext
675                                    (1- uidnext)
676                                  (nth 3 (car marks)))
677                                0)
678                       low (or (nth 4 (car marks)) uidnext 1)))))
679           (erase-buffer)
680           (insert
681            (format
682             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
683         t))))
684
685 (deffoo nnimap-request-create-group (group &optional server args)
686   (when (nnimap-possibly-change-group nil server)
687     (with-current-buffer (nnimap-buffer)
688       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
689
690 (deffoo nnimap-request-delete-group (group &optional force server)
691   (when (nnimap-possibly-change-group nil server)
692     (with-current-buffer (nnimap-buffer)
693       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
694
695 (deffoo nnimap-request-rename-group (group new-name &optional server)
696   (when (nnimap-possibly-change-group nil server)
697     (with-current-buffer (nnimap-buffer)
698       ;; Make sure we don't have this group open read/write by asking
699       ;; to examine a mailbox that doesn't exist.  This seems to be
700       ;; the only way that allows us to reliably go back to unselected
701       ;; state on Courier.
702       (nnimap-command "EXAMINE DOES.NOT.EXIST")
703       (setf (nnimap-group nnimap-object) nil)
704       (car (nnimap-command "RENAME %S %S"
705                            (utf7-encode group t) (utf7-encode new-name t))))))
706
707 (deffoo nnimap-request-expunge-group (group &optional server)
708   (when (nnimap-possibly-change-group group server)
709     (with-current-buffer (nnimap-buffer)
710       (car (nnimap-command "EXPUNGE")))))
711
712 (defun nnimap-get-flags (spec)
713   (let ((articles nil)
714         elems end)
715     (with-current-buffer (nnimap-buffer)
716       (erase-buffer)
717       (nnimap-wait-for-response (nnimap-send-command
718                                  "UID FETCH %s FLAGS" spec))
719       (setq end (point))
720       (subst-char-in-region (point-min) (point-max)
721                             ?\\ ?% t)
722       (goto-char (point-min))
723       (while (search-forward " FETCH " end t)
724         (setq elems (read (current-buffer)))
725         (push (cons (cadr (memq 'UID elems))
726                     (cadr (memq 'FLAGS elems)))
727               articles)))
728     (nreverse articles)))
729
730 (deffoo nnimap-close-group (group &optional server)
731   t)
732
733 (deffoo nnimap-request-move-article (article group server accept-form
734                                              &optional last internal-move-group)
735   (with-temp-buffer
736     (mm-disable-multibyte)
737     (when (funcall (if internal-move-group
738                        'nnimap-request-head
739                      'nnimap-request-article)
740                    article group server (current-buffer))
741       ;; If the move is internal (on the same server), just do it the easy
742       ;; way.
743       (let ((message-id (message-field-value "message-id")))
744         (if internal-move-group
745             (let ((result
746                    (with-current-buffer (nnimap-buffer)
747                      (nnimap-command "UID COPY %d %S"
748                                      article
749                                      (utf7-encode internal-move-group t)))))
750               (when (car result)
751                 (nnimap-delete-article article)
752                 (cons internal-move-group
753                       (nnimap-find-article-by-message-id
754                        internal-move-group message-id))))
755           ;; Move the article to a different method.
756           (let ((result (eval accept-form)))
757             (when result
758               (nnimap-delete-article article)
759               result)))))))
760
761 (deffoo nnimap-request-expire-articles (articles group &optional server force)
762   (cond
763    ((null articles)
764     nil)
765    ((not (nnimap-possibly-change-group group server))
766     articles)
767    ((and force
768          (eq nnmail-expiry-target 'delete))
769     (unless (nnimap-delete-article (gnus-compress-sequence articles))
770       (nnheader-message 7 "Article marked for deletion, but not expunged."))
771     nil)
772    (t
773     (let ((deletable-articles
774            (if (or force
775                    (eq nnmail-expiry-wait 'immediate))
776                articles
777              (gnus-sorted-intersection
778               articles
779               (nnimap-find-expired-articles group)))))
780       (if (null deletable-articles)
781           articles
782         (if (eq nnmail-expiry-target 'delete)
783             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
784           (setq deletable-articles
785                 (nnimap-process-expiry-targets
786                  deletable-articles group server)))
787         ;; Return the articles we didn't delete.
788         (gnus-sorted-complement articles deletable-articles))))))
789
790 (defun nnimap-process-expiry-targets (articles group server)
791   (let ((deleted-articles nil))
792     (dolist (article articles)
793       (let ((target nnmail-expiry-target))
794         (with-temp-buffer
795           (mm-disable-multibyte)
796           (when (nnimap-request-article article group server (current-buffer))
797             (nnheader-message 7 "Expiring article %s:%d" group article)
798             (when (functionp target)
799               (setq target (funcall target group)))
800             (when (and target
801                        (not (eq target 'delete)))
802               (if (or (gnus-request-group target t)
803                       (gnus-request-create-group target))
804                   (nnmail-expiry-target-group target group)
805                 (setq target nil)))
806             (when target
807               (push article deleted-articles))))))
808     ;; Change back to the current group again.
809     (nnimap-possibly-change-group group server)
810     (setq deleted-articles (nreverse deleted-articles))
811     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
812     deleted-articles))
813
814 (defun nnimap-find-expired-articles (group)
815   (let ((cutoff (nnmail-expired-article-p group nil nil)))
816     (with-current-buffer (nnimap-buffer)
817       (let ((result
818              (nnimap-command
819               "UID SEARCH SENTBEFORE %s"
820               (format-time-string
821                (format "%%d-%s-%%Y"
822                        (upcase
823                         (car (rassoc (nth 4 (decode-time cutoff))
824                                      parse-time-months))))
825                cutoff))))
826         (and (car result)
827              (delete 0 (mapcar #'string-to-number
828                                (cdr (assoc "SEARCH" (cdr result))))))))))
829
830
831 (defun nnimap-find-article-by-message-id (group message-id)
832   (with-current-buffer (nnimap-buffer)
833     (erase-buffer)
834     (setf (nnimap-group nnimap-object) nil)
835     (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
836     (let ((sequence
837            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
838           article result)
839       (setq result (nnimap-wait-for-response sequence))
840       (when (and result
841                  (car (setq result (nnimap-parse-response))))
842         ;; Select the last instance of the message in the group.
843         (and (setq article
844                    (car (last (assoc "SEARCH" (cdr result)))))
845              (string-to-number article))))))
846
847 (defun nnimap-delete-article (articles)
848   (with-current-buffer (nnimap-buffer)
849     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
850                     (nnimap-article-ranges articles))
851     (cond
852      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
853       (nnimap-command "UID EXPUNGE %s"
854                       (nnimap-article-ranges articles))
855       t)
856      (nnimap-expunge
857       (nnimap-command "EXPUNGE")
858       t)
859      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
860                                 "server doesn't support UIDPLUS, so we won't "
861                                 "delete this article now"))))))
862
863 (deffoo nnimap-request-scan (&optional group server)
864   (when (and (nnimap-possibly-change-group nil server)
865              nnimap-inbox
866              nnimap-split-methods)
867     (nnheader-message 7 "nnimap %s splitting mail..." server)
868     (nnimap-split-incoming-mail)))
869
870 (defun nnimap-marks-to-flags (marks)
871   (let (flags flag)
872     (dolist (mark marks)
873       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
874         (push flag flags)))
875     flags))
876
877 (deffoo nnimap-request-set-mark (group actions &optional server)
878   (when (nnimap-possibly-change-group group server)
879     (let (sequence)
880       (with-current-buffer (nnimap-buffer)
881         (erase-buffer)
882         ;; Just send all the STORE commands without waiting for
883         ;; response.  If they're successful, they're successful.
884         (dolist (action actions)
885           (destructuring-bind (range action marks) action
886             (let ((flags (nnimap-marks-to-flags marks)))
887               (when flags
888                 (setq sequence (nnimap-send-command
889                                 "UID STORE %s %sFLAGS.SILENT (%s)"
890                                 (nnimap-article-ranges range)
891                                 (if (eq action 'del)
892                                     "-"
893                                   "+")
894                                 (mapconcat #'identity flags " ")))))))
895         ;; Wait for the last command to complete to avoid later
896         ;; syncronisation problems with the stream.
897         (when sequence
898           (nnimap-wait-for-response sequence))))))
899
900 (deffoo nnimap-request-accept-article (group &optional server last)
901   (when (nnimap-possibly-change-group nil server)
902     (nnmail-check-syntax)
903     (let ((message-id (message-field-value "message-id"))
904           sequence message)
905       (nnimap-add-cr)
906       (setq message (buffer-substring-no-properties (point-min) (point-max)))
907       (with-current-buffer (nnimap-buffer)
908         (setq sequence (nnimap-send-command
909                         "APPEND %S {%d}" (utf7-encode group t)
910                         (length message)))
911         (process-send-string (get-buffer-process (current-buffer)) message)
912         (process-send-string (get-buffer-process (current-buffer))
913                              (if (nnimap-newlinep nnimap-object)
914                                  "\n"
915                                "\r\n"))
916         (let ((result (nnimap-get-response sequence)))
917           (if (not (car result))
918               (progn
919                 (nnheader-message 7 "%s" (nnheader-get-report-string 'nnimap))
920                 nil)
921             (cons group
922                   (nnimap-find-article-by-message-id group message-id))))))))
923
924 (deffoo nnimap-request-replace-article (article group buffer)
925   (let (group-art)
926     (when (and (nnimap-possibly-change-group group nil)
927                ;; Put the article into the group.
928                (with-current-buffer buffer
929                  (setq group-art
930                        (nnimap-request-accept-article group nil t))))
931       (nnimap-delete-article (list article))
932       ;; Return the new article number.
933       (cdr group-art))))
934
935 (defun nnimap-add-cr ()
936   (goto-char (point-min))
937   (while (re-search-forward "\r?\n" nil t)
938     (replace-match "\r\n" t t)))
939
940 (defun nnimap-get-groups ()
941   (let ((result (nnimap-command "LIST \"\" \"*\""))
942         groups)
943     (when (car result)
944       (dolist (line (cdr result))
945         (when (and (equal (car line) "LIST")
946                    (not (and (caadr line)
947                              (string-match "noselect" (caadr line)))))
948           (push (car (last line)) groups)))
949       (nreverse groups))))
950
951 (deffoo nnimap-request-list (&optional server)
952   (nnimap-possibly-change-group nil server)
953   (with-current-buffer nntp-server-buffer
954     (erase-buffer)
955     (let ((groups
956            (with-current-buffer (nnimap-buffer)
957              (nnimap-get-groups)))
958           sequences responses)
959       (when groups
960         (with-current-buffer (nnimap-buffer)
961           (setf (nnimap-group nnimap-object) nil)
962           (dolist (group groups)
963             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
964                         group)
965                   sequences))
966           (nnimap-wait-for-response (caar sequences))
967           (setq responses
968                 (nnimap-get-responses (mapcar #'car sequences))))
969         (dolist (response responses)
970           (let* ((sequence (car response))
971                  (response (cadr response))
972                  (group (cadr (assoc sequence sequences))))
973             (when (and group
974                        (equal (caar response) "OK"))
975               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
976                     highest exists)
977                 (dolist (elem response)
978                   (when (equal (cadr elem) "EXISTS")
979                     (setq exists (string-to-number (car elem)))))
980                 (when uidnext
981                   (setq highest (1- (string-to-number (car uidnext)))))
982                 (cond
983                  ((null highest)
984                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
985                  ((zerop exists)
986                   ;; Empty group.
987                   (insert (format "%S %d %d y\n"
988                                   (utf7-decode group t) highest (1+ highest))))
989                  (t
990                   ;; Return the widest possible range.
991                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
992                                   (or highest exists)))))))))
993         t))))
994
995 (deffoo nnimap-request-newgroups (date &optional server)
996   (nnimap-possibly-change-group nil server)
997   (with-current-buffer nntp-server-buffer
998     (erase-buffer)
999     (dolist (group (with-current-buffer (nnimap-buffer)
1000                      (nnimap-get-groups)))
1001       (unless (assoc group nnimap-current-infos)
1002         ;; Insert dummy numbers here -- they don't matter.
1003         (insert (format "%S 0 1 y\n" group))))
1004     t))
1005
1006 (deffoo nnimap-retrieve-group-data-early (server infos)
1007   (when (nnimap-possibly-change-group nil server)
1008     (with-current-buffer (nnimap-buffer)
1009       (erase-buffer)
1010       (setf (nnimap-group nnimap-object) nil)
1011       ;; QRESYNC handling isn't implemented.
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           ;; Some servers apparently can't have many outstanding
1052           ;; commands, so throttle them.
1053           (when (and (not nnimap-streaming)
1054                      (car sequences))
1055             (nnimap-wait-for-response (caar sequences))))
1056         sequences))))
1057
1058 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1059   (when (and sequences
1060              (nnimap-possibly-change-group nil server))
1061     (with-current-buffer (nnimap-buffer)
1062       ;; Wait for the final data to trickle in.
1063       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1064                                           (caar sequences)
1065                                         (cadar sequences))
1066                                       t)
1067         ;; Now we should have most of the data we need, no matter
1068         ;; whether we're QRESYNCING, fetching all the flags from
1069         ;; scratch, or just fetching the last 100 flags per group.
1070         (nnimap-update-infos (nnimap-flags-to-marks
1071                               (nnimap-parse-flags
1072                                (nreverse sequences)))
1073                              infos)
1074         ;; Finally, just return something resembling an active file in
1075         ;; the nntp buffer, so that the agent can save the info, too.
1076         (with-current-buffer nntp-server-buffer
1077           (erase-buffer)
1078           (dolist (info infos)
1079             (let* ((group (gnus-info-group info))
1080                    (active (gnus-active group)))
1081               (when active
1082                 (insert (format "%S %d %d y\n"
1083                                 (gnus-group-real-name group)
1084                                 (cdr active)
1085                                 (car active)))))))))))
1086
1087 (defun nnimap-update-infos (flags infos)
1088   (dolist (info infos)
1089     (let* ((group (gnus-group-real-name (gnus-info-group info)))
1090            (marks (cdr (assoc group flags))))
1091       (when marks
1092         (nnimap-update-info info marks)))))
1093
1094 (defun nnimap-update-info (info marks)
1095   (destructuring-bind (existing flags high low uidnext start-article
1096                                 permanent-flags uidvalidity
1097                                 vanished highestmodseq) marks
1098     (cond
1099      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1100      ;; completely empty groups.
1101      ((and (not existing)
1102            (not uidnext))
1103       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1104         (when active
1105           (gnus-set-active (gnus-info-group info) active))))
1106      ;; We have a mismatch between the old and new UIDVALIDITY
1107      ;; identifiers, so we have to re-request the group info (the next
1108      ;; time).  This virtually never happens.
1109      ((let ((old-uidvalidity
1110              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1111         (and old-uidvalidity
1112              (not (equal old-uidvalidity uidvalidity))
1113              (> start-article 1)))
1114       (gnus-group-remove-parameter info 'uidvalidity)
1115       (gnus-group-remove-parameter info 'modseq))
1116      ;; We have the data needed to update.
1117      (t
1118       (let* ((group (gnus-info-group info))
1119              (completep (and start-article
1120                              (= start-article 1)))
1121              (active (or (gnus-active group)
1122                          (cdr (assq 'active (gnus-info-params info))))))
1123         (when uidnext
1124           (setq high (1- uidnext)))
1125         ;; First set the active ranges based on high/low.
1126         (if (or completep
1127                 (not (gnus-active group)))
1128             (gnus-set-active group
1129                              (cond
1130                               ((and low high)
1131                                (cons low high))
1132                               (uidnext
1133                                ;; No articles in this group.
1134                                (cons uidnext (1- uidnext)))
1135                               (active
1136                                active)
1137                               (start-article
1138                                (cons start-article (1- start-article)))
1139                               (t
1140                                ;; No articles and no uidnext.
1141                                nil)))
1142           (gnus-set-active
1143            group
1144            (cons (car active)
1145                  (or high (1- uidnext)))))
1146         ;; See whether this is a read-only group.
1147         (unless (eq permanent-flags 'not-scanned)
1148           (gnus-group-set-parameter
1149            info 'permanent-flags
1150            (and (or (memq '%* permanent-flags)
1151                     (memq '%Seen permanent-flags))
1152                 permanent-flags)))
1153         ;; Update marks and read articles if this isn't a
1154         ;; read-only IMAP group.
1155         (when (setq permanent-flags
1156                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1157           (if (and highestmodseq
1158                    (not start-article))
1159               ;; We've gotten the data by QRESYNCing.
1160               (nnimap-update-qresync-info
1161                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1162             ;; Do normal non-QRESYNC flag updates.
1163             ;; Update the list of read articles.
1164             (let* ((unread
1165                     (gnus-compress-sequence
1166                      (gnus-set-difference
1167                       (gnus-set-difference
1168                        existing
1169                        (cdr (assoc '%Seen flags)))
1170                       (cdr (assoc '%Flagged flags)))))
1171                    (read (gnus-range-difference
1172                           (cons start-article high) unread)))
1173               (when (> start-article 1)
1174                 (setq read
1175                       (gnus-range-nconcat
1176                        (if (> start-article 1)
1177                            (gnus-sorted-range-intersection
1178                             (cons 1 (1- start-article))
1179                             (gnus-info-read info))
1180                          (gnus-info-read info))
1181                        read)))
1182               (when (or (not (listp permanent-flags))
1183                         (memq '%Seen permanent-flags))
1184                 (gnus-info-set-read info read))
1185               ;; Update the marks.
1186               (setq marks (gnus-info-marks info))
1187               (dolist (type (cdr nnimap-mark-alist))
1188                 (when (or (not (listp permanent-flags))
1189                           (memq (assoc (caddr type) flags) permanent-flags)
1190                           (memq '%* permanent-flags))
1191                   (let ((old-marks (assoc (car type) marks))
1192                         (new-marks
1193                          (gnus-compress-sequence
1194                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1195                                    (assoc (intern (cadr type) obarray) flags)
1196                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1197                     (setq marks (delq old-marks marks))
1198                     (pop old-marks)
1199                     (when (and old-marks
1200                                (> start-article 1))
1201                       (setq old-marks (gnus-range-difference
1202                                        old-marks
1203                                        (cons start-article high)))
1204                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1205                     (when new-marks
1206                       (push (cons (car type) new-marks) marks)))))
1207               (gnus-info-set-marks info marks t))))
1208         ;; Note the active level for the next run-through.
1209         (gnus-group-set-parameter info 'active (gnus-active group))
1210         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1211         (gnus-group-set-parameter info 'modseq highestmodseq)
1212         (nnimap-store-info info (gnus-active group)))))))
1213
1214 (defun nnimap-update-qresync-info (info existing vanished flags)
1215   ;; Add all the vanished articles to the list of read articles.
1216   (gnus-info-set-read
1217    info
1218    (gnus-add-to-range
1219     (gnus-add-to-range
1220      (gnus-range-add (gnus-info-read info)
1221                      vanished)
1222      (cdr (assq '%Flagged flags)))
1223     (cdr (assq '%Seen flags))))
1224   (let ((marks (gnus-info-marks info)))
1225     (dolist (type (cdr nnimap-mark-alist))
1226       (let ((ticks (assoc (car type) marks))
1227             (new-marks
1228              (cdr (or (assoc (caddr type) flags) ; %Flagged
1229                       (assoc (intern (cadr type) obarray) flags)
1230                       (assoc (cadr type) flags))))) ; "\Flagged"
1231         (setq marks (delq ticks marks))
1232         (pop ticks)
1233         ;; Add the new marks we got.
1234         (setq ticks (gnus-add-to-range ticks new-marks))
1235         ;; Remove the marks from messages that don't have them.
1236         (setq ticks (gnus-remove-from-range
1237                      ticks
1238                      (gnus-compress-sequence
1239                       (gnus-sorted-complement existing new-marks))))
1240         (when ticks
1241           (push (cons (car type) ticks) marks)))
1242       (gnus-info-set-marks info marks t))))
1243
1244 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1245   (if (zerop (length irange))
1246       nil
1247     (let ((result nil))
1248       (dolist (elem (split-string irange ","))
1249         (push
1250          (if (string-match ":" elem)
1251              (let ((numbers (split-string elem ":")))
1252                (cons (string-to-number (car numbers))
1253                      (string-to-number (cadr numbers))))
1254            (string-to-number elem))
1255          result))
1256       (nreverse result))))
1257
1258 (defun nnimap-store-info (info active)
1259   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1260          (entry (assoc group nnimap-current-infos)))
1261     (if entry
1262         (setcdr entry (list info active))
1263       (push (list group info active) nnimap-current-infos))))
1264
1265 (defun nnimap-flags-to-marks (groups)
1266   (let (data group totalp uidnext articles start-article mark permanent-flags
1267              uidvalidity vanished highestmodseq)
1268     (dolist (elem groups)
1269       (setq group (car elem)
1270             uidnext (nth 1 elem)
1271             start-article (nth 2 elem)
1272             permanent-flags (nth 3 elem)
1273             uidvalidity (nth 4 elem)
1274             vanished (nth 5 elem)
1275             highestmodseq (nth 6 elem)
1276             articles (nthcdr 7 elem))
1277       (let ((high (caar articles))
1278             marks low existing)
1279         (dolist (article articles)
1280           (setq low (car article))
1281           (push (car article) existing)
1282           (dolist (flag (cdr article))
1283             (setq mark (assoc flag marks))
1284             (if (not mark)
1285                 (push (list flag (car article)) marks)
1286               (setcdr mark (cons (car article) (cdr mark))))))
1287         (push (list group existing marks high low uidnext start-article
1288                     permanent-flags uidvalidity vanished highestmodseq)
1289               data)))
1290     data))
1291
1292 (defun nnimap-parse-flags (sequences)
1293   (goto-char (point-min))
1294   ;; Change \Delete etc to %Delete, so that the reader can read it.
1295   (subst-char-in-region (point-min) (point-max)
1296                         ?\\ ?% t)
1297   (let (start end articles groups uidnext elems permanent-flags
1298               uidvalidity vanished highestmodseq)
1299     (dolist (elem sequences)
1300       (destructuring-bind (group-sequence flag-sequence totalp group command)
1301           elem
1302         (setq start (point))
1303         (when (and
1304                ;; The EXAMINE was successful.
1305                (search-forward (format "\n%d OK " group-sequence) nil t)
1306                (progn
1307                  (forward-line 1)
1308                  (setq end (point))
1309                  (goto-char start)
1310                  (setq permanent-flags
1311                        (if (equal command "SELECT")
1312                            (and (search-forward "PERMANENTFLAGS "
1313                                                 (or end (point-min)) t)
1314                                 (read (current-buffer)))
1315                          'not-scanned))
1316                  (goto-char start)
1317                  (setq uidnext
1318                        (and (search-forward "UIDNEXT "
1319                                             (or end (point-min)) t)
1320                             (read (current-buffer))))
1321                  (goto-char start)
1322                  (setq uidvalidity
1323                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1324                                                (or end (point-min)) t)
1325                             ;; Store UIDVALIDITY as a string, as it's
1326                             ;; too big for 32-bit Emacsen, usually.
1327                             (match-string 1)))
1328                  (goto-char start)
1329                  (setq vanished
1330                        (and (eq flag-sequence 'qresync)
1331                             (re-search-forward "VANISHED.* \\([0-9:,]+\\)"
1332                                                (or end (point-min)) t)
1333                             (match-string 1)))
1334                  (goto-char start)
1335                  (setq highestmodseq
1336                        (and (search-forward "HIGHESTMODSEQ "
1337                                             (or end (point-min)) t)
1338                             (read (current-buffer))))
1339                  (goto-char end)
1340                  (forward-line -1))
1341                ;; The UID FETCH FLAGS was successful.
1342                (or (eq flag-sequence 'qresync)
1343                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1344           (if (eq flag-sequence 'qresync)
1345               (progn
1346                 (goto-char start)
1347                 (setq start end))
1348             (setq start (point))
1349             (goto-char end))
1350           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1351             (setq elems (read (current-buffer)))
1352             (push (cons (cadr (memq 'UID elems))
1353                         (cadr (memq 'FLAGS elems)))
1354                   articles))
1355           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1356                              vanished highestmodseq)
1357                        articles)
1358                 groups)
1359           (goto-char end)
1360           (setq articles nil))))
1361     groups))
1362
1363 (defun nnimap-find-process-buffer (buffer)
1364   (cadr (assoc buffer nnimap-connection-alist)))
1365
1366 (deffoo nnimap-request-post (&optional server)
1367   (setq nnimap-status-string "Read-only server")
1368   nil)
1369
1370 (deffoo nnimap-request-thread (id)
1371     (let* ((refs (split-string
1372                (or (mail-header-references (gnus-summary-article-header))
1373                    "")))
1374            (cmd (let ((value
1375                        (format
1376                         "(OR HEADER REFERENCES %s HEADER Message-Id %s)"
1377                         id id)))
1378                   (dolist (refid refs value)
1379                     (setq value (format
1380                                  "(OR (OR HEADER Message-Id %s HEADER REFERENCES %s) %s)"
1381                                  refid refid value)))))
1382            (result
1383             (with-current-buffer (nnimap-buffer)
1384               (nnimap-command  "UID SEARCH %s" cmd))))
1385       (gnus-fetch-headers (and (car result)
1386            (delete 0 (mapcar #'string-to-number
1387                              (cdr (assoc "SEARCH" (cdr result)))))))))
1388
1389 (defun nnimap-possibly-change-group (group server)
1390   (let ((open-result t))
1391     (when (and server
1392                (not (nnimap-server-opened server)))
1393       (setq open-result (nnimap-open-server server)))
1394     (cond
1395      ((not open-result)
1396       nil)
1397      ((not group)
1398       t)
1399      (t
1400       (with-current-buffer (nnimap-buffer)
1401         (if (equal group (nnimap-group nnimap-object))
1402             t
1403           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1404             (when (car result)
1405               (setf (nnimap-group nnimap-object) group
1406                     (nnimap-select-result nnimap-object) result)
1407               result))))))))
1408
1409 (defun nnimap-find-connection (buffer)
1410   "Find the connection delivering to BUFFER."
1411   (let ((entry (assoc buffer nnimap-connection-alist)))
1412     (when entry
1413       (if (and (buffer-name (cadr entry))
1414                (get-buffer-process (cadr entry))
1415                (memq (process-status (get-buffer-process (cadr entry)))
1416                      '(open run)))
1417           (get-buffer-process (cadr entry))
1418         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1419         nil))))
1420
1421 (defvar nnimap-sequence 0)
1422
1423 (defun nnimap-send-command (&rest args)
1424   (process-send-string
1425    (get-buffer-process (current-buffer))
1426    (nnimap-log-command
1427     (format "%d %s%s\n"
1428             (incf nnimap-sequence)
1429             (apply #'format args)
1430             (if (nnimap-newlinep nnimap-object)
1431                 ""
1432               "\r"))))
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