Don't wait for a response when we haven't requested anything.
[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 (eval-and-compile
30   (require 'nnheader))
31
32 (eval-when-compile
33   (require 'cl))
34
35 (require 'nnheader)
36 (require 'gnus-util)
37 (require 'gnus)
38 (require 'nnoo)
39 (require 'netrc)
40
41 (nnoo-declare nnimap)
42
43 (defvoo nnimap-address nil
44   "The address of the IMAP server.")
45
46 (defvoo nnimap-server-port nil
47   "The IMAP port used.
48 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
49 it will default to `imap'.")
50
51 (defvoo nnimap-stream 'ssl
52   "How nnimap will talk to the IMAP server.
53 Values are `ssl' and `network'.")
54
55 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
56                                  (if (listp imap-shell-program)
57                                      (car imap-shell-program)
58                                    imap-shell-program)
59                                "ssh %s imapd"))
60
61 (defvoo nnimap-inbox nil
62   "The mail box where incoming mail arrives and should be split out of.")
63
64 (defvoo nnimap-expunge-inbox nil
65   "If non-nil, expunge the inbox after fetching mail.
66 This is always done if the server supports UID EXPUNGE, but it's
67 not done by default on servers that doesn't support that command.")
68
69 (defvoo nnimap-authenticator nil
70   "How nnimap authenticate itself to the server.
71 Possible choices are nil (use default methods) or `anonymous'.")
72
73 (defvoo nnimap-fetch-partial-articles nil
74   "If non-nil, nnimap will fetch partial articles.
75 If t, nnimap will fetch only the first part.  If a string, it
76 will fetch all parts that have types that match that string.  A
77 likely value would be \"text/\" to automatically fetch all
78 textual parts.")
79
80 (defvoo nnimap-connection-alist nil)
81
82 (defvoo nnimap-current-infos nil)
83
84 (defvar nnimap-process nil)
85
86 (defvar nnimap-status-string "")
87
88 (defvar nnimap-split-download-body-default nil
89   "Internal variable with default value for `nnimap-split-download-body'.")
90
91 (defstruct nnimap
92   group process commands capabilities select-result newlinep)
93
94 (defvar nnimap-object nil)
95
96 (defvar nnimap-mark-alist
97   '((read "\\Seen")
98     (tick "\\Flagged")
99     (reply "\\Answered")
100     (expire "gnus-expire")
101     (dormant "gnus-dormant")
102     (score "gnus-score")
103     (save "gnus-save")
104     (download "gnus-download")
105     (forward "gnus-forward")))
106
107 (defvar nnimap-split-methods nil)
108
109 (defun nnimap-buffer ()
110   (nnimap-find-process-buffer nntp-server-buffer))
111
112 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
113   (with-current-buffer nntp-server-buffer
114     (erase-buffer)
115     (when (nnimap-possibly-change-group group server)
116       (with-current-buffer (nnimap-buffer)
117         (nnimap-send-command "SELECT %S" (utf7-encode group t))
118         (erase-buffer)
119         (nnimap-wait-for-response
120          (nnimap-send-command
121           "UID FETCH %s %s"
122           (nnimap-article-ranges (gnus-compress-sequence articles))
123           (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
124                   (format
125                    (if (member "IMAP4REV1"
126                                (nnimap-capabilities nnimap-object))
127                        "BODY.PEEK[HEADER.FIELDS %s]"
128                      "RFC822.HEADER.LINES %s")
129                    (append '(Subject From Date Message-Id
130                                      References In-Reply-To Xref)
131                            nnmail-extra-headers))))
132          t)
133         (nnimap-transform-headers))
134       (insert-buffer-substring
135        (nnimap-find-process-buffer (current-buffer))))
136     t))
137
138 (defun nnimap-transform-headers ()
139   (goto-char (point-min))
140   (let (article bytes lines)
141     (block nil
142       (while (not (eobp))
143         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
144           (delete-region (point) (progn (forward-line 1) (point)))
145           (when (eobp)
146             (return)))
147         (setq article (match-string 1)
148               bytes (nnimap-get-length)
149               lines nil)
150         (beginning-of-line)
151         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
152           (let ((structure (ignore-errors (read (current-buffer)))))
153             (while (and (consp structure)
154                         (not (stringp (car structure))))
155               (setq structure (car structure)))
156             (setq lines (nth 7 structure))))
157         (delete-region (line-beginning-position) (line-end-position))
158         (insert (format "211 %s Article retrieved." article))
159         (forward-line 1)
160         (insert (format "Chars: %d\n" bytes))
161         (when lines
162           (insert (format "Lines: %s\n" lines)))
163         (re-search-forward "^\r$")
164         (delete-region (line-beginning-position) (line-end-position))
165         (insert ".")
166         (forward-line 1)))))
167
168 (defun nnimap-get-length ()
169   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
170        (string-to-number (match-string 1))))
171
172 (defun nnimap-article-ranges (ranges)
173   (let (result)
174     (cond
175      ((numberp ranges)
176       (number-to-string ranges))
177      ((numberp (cdr ranges))
178       (format "%d:%d" (car ranges) (cdr ranges)))
179      (t
180       (dolist (elem ranges)
181         (push
182          (if (consp elem)
183              (format "%d:%d" (car elem) (cdr elem))
184            (number-to-string elem))
185          result))
186       (mapconcat #'identity (nreverse result) ",")))))
187
188 (deffoo nnimap-open-server (server &optional defs)
189   (if (nnimap-server-opened server)
190       t
191     (unless (assq 'nnimap-address defs)
192       (setq defs (append defs (list (list 'nnimap-address server)))))
193     (nnoo-change-server 'nnimap server defs)
194     (or (nnimap-find-connection nntp-server-buffer)
195         (nnimap-open-connection nntp-server-buffer))))
196
197 (defun nnimap-make-process-buffer (buffer)
198   (with-current-buffer
199       (generate-new-buffer (format "*nnimap %s %s %s*"
200                                    nnimap-address nnimap-server-port
201                                    (gnus-buffer-exists-p buffer)))
202     (mm-disable-multibyte)
203     (buffer-disable-undo)
204     (gnus-add-buffer)
205     (set (make-local-variable 'after-change-functions) nil)
206     (set (make-local-variable 'nnimap-object) (make-nnimap))
207     (push (list buffer (current-buffer)) nnimap-connection-alist)
208     (current-buffer)))
209
210 (defun nnimap-open-shell-stream (name buffer host port)
211   (let ((process-connection-type nil))
212     (start-process name buffer shell-file-name
213                    shell-command-switch
214                    (format-spec
215                     nnimap-shell-program
216                     (format-spec-make
217                      ?s host
218                      ?p port)))))
219
220 (defun nnimap-credentials (address ports)
221   (let (port credentials)
222     ;; Request the credentials from all ports, but only query on the
223     ;; last port if all the previous ones have failed.
224     (while (and (null credentials)
225                 (setq port (pop ports)))
226       (setq credentials
227             (auth-source-user-or-password
228              '("login" "password") address port nil (null ports))))
229     credentials))
230
231 (defun nnimap-open-connection (buffer)
232   (with-current-buffer (nnimap-make-process-buffer buffer)
233     (let* ((coding-system-for-read 'binary)
234            (coding-system-for-write 'binary)
235            (ports
236             (cond
237              ((eq nnimap-stream 'network)
238               (open-network-stream
239                "*nnimap*" (current-buffer) nnimap-address
240                (or nnimap-server-port
241                    (if (netrc-find-service-number "imap")
242                        "imap"
243                      "143")))
244               '("143" "imap"))
245              ((eq nnimap-stream 'shell)
246               (nnimap-open-shell-stream
247                "*nnimap*" (current-buffer) nnimap-address
248                (or nnimap-server-port "imap"))
249               '("imap"))
250              ((eq nnimap-stream 'ssl)
251               (open-tls-stream
252                "*nnimap*" (current-buffer) nnimap-address
253                (or nnimap-server-port
254                    (if (netrc-find-service-number "imaps")
255                        "imaps"
256                      "993")))
257               '("143" "993" "imap" "imaps"))))
258            connection-result login-result credentials)
259       (setf (nnimap-process nnimap-object)
260             (get-buffer-process (current-buffer)))
261       (when (and (nnimap-process nnimap-object)
262                  (memq (process-status (nnimap-process nnimap-object))
263                        '(open run)))
264         (gnus-set-process-query-on-exit-flag (nnimap-process nnimap-object) nil)
265         (when (setq connection-result (nnimap-wait-for-connection))
266           (unless (equal connection-result "PREAUTH")
267             (if (not (setq credentials
268                            (if (eq nnimap-authenticator 'anonymous)
269                                (list "anonymous"
270                                      (message-make-address))
271                              (nnimap-credentials
272                               nnimap-address
273                               (if nnimap-server-port
274                                   (cons (format "%s" nnimap-server-port) ports)
275                                 ports)))))
276                 (setq nnimap-object nil)
277               (setq login-result (nnimap-command "LOGIN %S %S"
278                                                  (car credentials)
279                                                  (cadr credentials)))
280               (unless (car login-result)
281                 (delete-process (nnimap-process nnimap-object))
282                 (setq nnimap-object nil))))
283           (when nnimap-object
284             (setf (nnimap-capabilities nnimap-object)
285                   (mapcar
286                    #'upcase
287                    (or (nnimap-find-parameter "CAPABILITY" (cdr login-result))
288                        (nnimap-find-parameter
289                         "CAPABILITY" (cdr (nnimap-command "CAPABILITY"))))))
290             (when (member "QRESYNC" (nnimap-capabilities nnimap-object))
291               (nnimap-command "ENABLE QRESYNC"))
292             t))))))
293
294 (defun nnimap-find-parameter (parameter elems)
295   (let (result)
296     (dolist (elem elems)
297       (cond
298        ((equal (car elem) parameter)
299         (setq result (cdr elem)))
300        ((and (equal (car elem) "OK")
301              (consp (cadr elem))
302              (equal (caadr elem) parameter))
303         (setq result (cdr (cadr elem))))))
304     result))
305
306 (deffoo nnimap-close-server (&optional server)
307   t)
308
309 (deffoo nnimap-request-close ()
310   t)
311
312 (deffoo nnimap-server-opened (&optional server)
313   (and (nnoo-current-server-p 'nnimap server)
314        nntp-server-buffer
315        (gnus-buffer-live-p nntp-server-buffer)
316        (nnimap-find-connection nntp-server-buffer)))
317
318 (deffoo nnimap-status-message (&optional server)
319   nnimap-status-string)
320
321 (deffoo nnimap-request-article (article &optional group server to-buffer)
322   (with-current-buffer nntp-server-buffer
323     (let ((result (nnimap-possibly-change-group group server))
324           parts)
325       (when (stringp article)
326         (setq article (nnimap-find-article-by-message-id group article)))
327       (when (and result
328                  article)
329         (erase-buffer)
330         (with-current-buffer (nnimap-buffer)
331           (erase-buffer)
332           (when nnimap-fetch-partial-articles
333             (if (eq nnimap-fetch-partial-articles t)
334                 (setq parts '(1))
335               (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
336               (goto-char (point-min))
337               (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
338                 (let ((structure (ignore-errors (read (current-buffer)))))
339                   (setq parts (nnimap-find-wanted-parts structure))))))
340           (setq result
341                 (nnimap-command
342                  (if (member "IMAP4REV1" (nnimap-capabilities nnimap-object))
343                      "UID FETCH %d BODY.PEEK[]"
344                    "UID FETCH %d RFC822.PEEK")
345                  article))
346           ;; Check that we really got an article.
347           (goto-char (point-min))
348           (unless (looking-at "\\* [0-9]+ FETCH")
349             (setq result nil)))
350         (let ((buffer (nnimap-find-process-buffer (current-buffer))))
351           (when (car result)
352             (with-current-buffer (or to-buffer nntp-server-buffer)
353               (insert-buffer-substring buffer)
354               (goto-char (point-min))
355               (let ((bytes (nnimap-get-length)))
356                 (delete-region (line-beginning-position)
357                                (progn (forward-line 1) (point)))
358                 (goto-char (+ (point) bytes))
359                 (delete-region (point) (point-max))
360                 (nnheader-ms-strip-cr))
361               (cons group article))))))))
362
363 (defun nnimap-find-wanted-parts (structure)
364   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
365
366 (defun nnimap-find-wanted-parts-1 (structure prefix)
367   (let ((num 1)
368         parts)
369     (while (consp (car structure))
370       (let ((sub (pop structure)))
371         (if (consp (car sub))
372             (push (nnimap-find-wanted-parts-1
373                    sub (if (string= prefix "")
374                            (number-to-string num)
375                          (format "%s.%s" prefix num)))
376                   parts)
377           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub))))
378             (when (string-match nnimap-fetch-partial-articles type)
379               (push (if (string= prefix "")
380                         (number-to-string num)
381                       (format "%s.%s" prefix num))
382                     parts)))
383           (incf num))))
384     (nreverse parts)))
385
386 (deffoo nnimap-request-group (group &optional server dont-check info)
387   (with-current-buffer nntp-server-buffer
388     (let ((result (nnimap-possibly-change-group group server))
389           articles active marks high low)
390       (when result
391         (if (and dont-check
392                  (setq active (nth 2 (assoc group nnimap-current-infos))))
393             (insert (format "211 %d %d %d %S\n"
394                             (- (cdr active) (car active))
395                             (car active)
396                             (cdr active)
397                             group))
398           (with-current-buffer (nnimap-buffer)
399             (erase-buffer)
400             (let ((group-sequence
401                    (nnimap-send-command "SELECT %S" (utf7-encode group)))
402                   (flag-sequence
403                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
404               (nnimap-wait-for-response flag-sequence)
405               (setq marks
406                     (nnimap-flags-to-marks
407                      (nnimap-parse-flags
408                       (list (list group-sequence flag-sequence 1 group)))))
409               (when info
410                 (nnimap-update-infos marks (list info)))
411               (goto-char (point-max))
412               (cond
413                (marks
414                 (setq high (nth 3 (car marks))
415                       low (nth 4 (car marks))))
416                ((re-search-backward "UIDNEXT \\([0-9]+\\)" nil t)
417                 (setq high (string-to-number (match-string 1))
418                       low 1)))))
419           (erase-buffer)
420           (insert
421            (format
422             "211 %d %d %d %S\n"
423             (1+ (- high low))
424             low high group))))
425       t)))
426
427 (defun nnimap-get-flags (spec)
428   (let ((articles nil)
429         elems)
430     (with-current-buffer (nnimap-buffer)
431       (erase-buffer)
432       (nnimap-wait-for-response (nnimap-send-command
433                                  "UID FETCH %s FLAGS" spec))
434       (goto-char (point-min))
435       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
436         (setq elems (nnimap-parse-line (match-string 1)))
437         (push (cons (string-to-number (cadr (member "UID" elems)))
438                     (cadr (member "FLAGS" elems)))
439               articles)))
440     (nreverse articles)))
441
442 (deffoo nnimap-close-group (group &optional server)
443   t)
444
445 (deffoo nnimap-request-move-article (article group server accept-form
446                                              &optional last internal-move-group)
447   (when (nnimap-possibly-change-group group server)
448     ;; If the move is internal (on the same server), just do it the easy
449     ;; way.
450     (let ((message-id (message-field-value "message-id")))
451       (if internal-move-group
452           (let ((result
453                  (with-current-buffer (nnimap-buffer)
454                    (nnimap-command "UID COPY %d %S"
455                                    article
456                                    (utf7-encode internal-move-group t)))))
457             (when (car result)
458               (nnimap-delete-article article)
459               (cons internal-move-group
460                     (nnimap-find-article-by-message-id
461                      internal-move-group message-id))))
462         (with-temp-buffer
463           (let ((result (eval accept-form)))
464             (when result
465               (nnimap-delete-article article)
466               result)))))))
467
468 (deffoo nnimap-request-expire-articles (articles group &optional server force)
469   (cond
470    ((not (nnimap-possibly-change-group group server))
471     articles)
472    (force
473     (unless (nnimap-delete-article articles)
474       (message "Article marked for deletion, but not expunged."))
475     nil)
476    (t
477     articles)))
478
479 (defun nnimap-find-article-by-message-id (group message-id)
480   (when (nnimap-possibly-change-group group nil)
481     (with-current-buffer (nnimap-buffer)
482       (let ((result
483              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
484             article)
485         (when (car result)
486           ;; Select the last instance of the message in the group.
487           (and (setq article
488                      (car (last (assoc "SEARCH" (cdr result)))))
489                (string-to-number article)))))))
490
491 (defun nnimap-delete-article (articles)
492   (with-current-buffer (nnimap-buffer)
493     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
494                     (nnimap-article-ranges articles))
495     (when (member "UIDPLUS" (nnimap-capabilities nnimap-object))
496       (nnimap-send-command "UID EXPUNGE %s"
497                            (nnimap-article-ranges articles))
498       t)))
499
500 (deffoo nnimap-request-scan (&optional group server)
501   (when (and (nnimap-possibly-change-group nil server)
502              (equal group nnimap-inbox)
503              nnimap-inbox
504              nnimap-split-methods)
505     (nnimap-split-incoming-mail)))
506
507 (defun nnimap-marks-to-flags (marks)
508   (let (flags flag)
509     (dolist (mark marks)
510       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
511         (push flag flags)))
512     flags))
513
514 (deffoo nnimap-request-set-mark (group actions &optional server)
515   (when (nnimap-possibly-change-group group server)
516     (let (sequence)
517       (with-current-buffer (nnimap-buffer)
518         ;; Just send all the STORE commands without waiting for
519         ;; response.  If they're successful, they're successful.
520         (dolist (action actions)
521           (destructuring-bind (range action marks) action
522             (let ((flags (nnimap-marks-to-flags marks)))
523               (when flags
524                 (setq sequence (nnimap-send-command
525                                 "UID STORE %s %sFLAGS.SILENT (%s)"
526                                 (nnimap-article-ranges range)
527                                 (if (eq action 'del)
528                                     "-"
529                                   "+")
530                                 (mapconcat #'identity flags " ")))))))
531         ;; Wait for the last command to complete to avoid later
532         ;; syncronisation problems with the stream.
533         (when sequence
534           (nnimap-wait-for-response sequence))))))
535
536 (deffoo nnimap-request-accept-article (group &optional server last)
537   (when (nnimap-possibly-change-group nil server)
538     (nnmail-check-syntax)
539     (let ((message (buffer-string))
540           (message-id (message-field-value "message-id"))
541           sequence)
542       (with-current-buffer (nnimap-buffer)
543         (setq sequence (nnimap-send-command
544                         "APPEND %S {%d}" (utf7-encode group t)
545                         (length message)))
546         (process-send-string (get-buffer-process (current-buffer)) message)
547         (process-send-string (get-buffer-process (current-buffer))
548                              (if (nnimap-newlinep nnimap-object)
549                                  "\n"
550                                "\r\n"))
551         (let ((result (nnimap-get-response sequence)))
552           (when result
553             (cons group
554                   (nnimap-find-article-by-message-id group message-id))))))))
555
556 (defun nnimap-add-cr ()
557   (goto-char (point-min))
558   (while (re-search-forward "\r?\n" nil t)
559     (replace-match "\r\n" t t)))
560
561 (defun nnimap-get-groups ()
562   (let ((result (nnimap-command "LIST \"\" \"*\""))
563         groups)
564     (when (car result)
565       (dolist (line (cdr result))
566         (when (and (equal (car line) "LIST")
567                    (not (and (caadr line)
568                              (string-match "noselect" (caadr line)))))
569           (push (car (last line)) groups)))
570       (nreverse groups))))
571
572 (deffoo nnimap-request-list (&optional server)
573   (nnimap-possibly-change-group nil server)
574   (with-current-buffer nntp-server-buffer
575     (erase-buffer)
576     (let ((groups
577            (with-current-buffer (nnimap-buffer)
578              (nnimap-get-groups)))
579           sequences responses)
580       (when groups
581         (with-current-buffer (nnimap-buffer)
582           (dolist (group groups)
583             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
584                         group)
585                   sequences))
586           (nnimap-wait-for-response (caar sequences))
587           (setq responses
588                 (nnimap-get-responses (mapcar #'car sequences))))
589         (dolist (response responses)
590           (let* ((sequence (car response))
591                  (response (cadr response))
592                  (group (cadr (assoc sequence sequences))))
593             (when (and group
594                        (equal (caar response) "OK"))
595               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
596                     highest exists)
597                 (dolist (elem response)
598                   (when (equal (cadr elem) "EXISTS")
599                     (setq exists (string-to-number (car elem)))))
600                 (when uidnext
601                   (setq highest (1- (string-to-number (car uidnext)))))
602                 (cond
603                  ((null highest)
604                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
605                  ((zerop exists)
606                   ;; Empty group.
607                   (insert (format "%S %d %d y\n"
608                                   (utf7-decode group t) highest (1+ highest))))
609                  (t
610                   ;; Return the widest possible range.
611                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
612                                   (or highest exists)))))))))
613         t))))
614
615 (deffoo nnimap-retrieve-group-data-early (server infos)
616   (when (nnimap-possibly-change-group nil server)
617     (with-current-buffer (nnimap-buffer)
618       ;; QRESYNC handling isn't implemented.
619       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
620             marks groups sequences)
621         ;; Go through the infos and gather the data needed to know
622         ;; what and how to request the data.
623         (dolist (info infos)
624           (setq marks (gnus-info-marks info))
625           (push (list (gnus-group-real-name (gnus-info-group info))
626                       (cdr (assq 'active marks))
627                       (cdr (assq 'uid marks)))
628                 groups))
629         ;; Then request the data.
630         (erase-buffer)
631         (dolist (elem groups)
632           (if (and qresyncp
633                    (nth 2 elem))
634               (push
635                (list 'qresync
636                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
637                                           (car elem)
638                                           (car (nth 2 elem))
639                                           (cdr (nth 2 elem)))
640                      nil
641                      (car elem))
642                sequences)
643             (let ((start
644                    (if (nth 1 elem)
645                        ;; Fetch the last 100 flags.
646                        (max 1 (- (cdr (nth 1 elem)) 100))
647                      1)))
648               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
649                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
650                           start
651                           (car elem))
652                     sequences))))
653         sequences))))
654
655 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
656   (when (and sequences
657              (nnimap-possibly-change-group nil server))
658     (with-current-buffer (nnimap-buffer)
659       ;; Wait for the final data to trickle in.
660       (nnimap-wait-for-response (cadar sequences))
661       ;; Now we should have all the data we need, no matter whether
662       ;; we're QRESYNCING, fetching all the flags from scratch, or
663       ;; just fetching the last 100 flags per group.
664       (nnimap-update-infos (nnimap-flags-to-marks
665                             (nnimap-parse-flags
666                              (nreverse sequences)))
667                            infos)
668       ;; Finally, just return something resembling an active file in
669       ;; the nntp buffer, so that the agent can save the info, too.
670       (with-current-buffer nntp-server-buffer
671         (erase-buffer)
672         (dolist (info infos)
673           (let* ((group (gnus-info-group info))
674                  (active (gnus-active group)))
675             (when active
676               (insert (format "%S %d %d y\n"
677                               (gnus-group-real-name group)
678                               (cdr active)
679                               (car active))))))))))
680
681 (defun nnimap-update-infos (flags infos)
682   (dolist (info infos)
683     (let ((group (gnus-group-real-name (gnus-info-group info))))
684       (nnimap-update-info info (cdr (assoc group flags))))))
685
686 (defun nnimap-update-info (info marks)
687   (when marks
688     (destructuring-bind (existing flags high low uidnext start-article) marks
689       (let ((group (gnus-info-group info))
690             (completep (and start-article
691                             (= start-article 1))))
692         ;; First set the active ranges based on high/low.
693         (if (or completep
694                 (not (gnus-active group)))
695             (gnus-set-active group
696                              (if high
697                                  (cons low high)
698                                ;; No articles in this group.
699                                (cons (1- uidnext) uidnext)))
700           (setcdr (gnus-active group) high))
701         ;; Then update the list of read articles.
702         (let* ((unread
703                 (gnus-compress-sequence
704                  (gnus-set-difference
705                   (gnus-set-difference
706                    existing
707                    (cdr (assoc "\\Seen" flags)))
708                   (cdr (assoc "\\Flagged" flags)))))
709                (read (gnus-range-difference
710                       (cons start-article high) unread)))
711           (when (> start-article 1)
712             (setq read
713                   (gnus-range-nconcat
714                    (if (> start-article 1)
715                        (gnus-sorted-range-intersection
716                         (cons 1 (1- start-article))
717                         (gnus-info-read info))
718                      (gnus-info-read info))
719                    read)))
720           (gnus-info-set-read info read)
721           ;; Update the marks.
722           (setq marks (gnus-info-marks info))
723           ;; Note the active level for the next run-through.
724           (let ((active (assq 'active marks)))
725             (if active
726                 (setcdr active (gnus-active group))
727               (push (cons 'active (gnus-active group)) marks)))
728           (dolist (type (cdr nnimap-mark-alist))
729             (let ((old-marks (assoc (car type) marks))
730                   (new-marks (gnus-compress-sequence
731                               (cdr (assoc (cadr type) flags)))))
732               (setq marks (delq old-marks marks))
733               (pop old-marks)
734               (when (and old-marks
735                          (> start-article 1))
736                 (setq old-marks (gnus-range-difference
737                                  old-marks
738                                  (cons start-article high)))
739                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
740               (when new-marks
741                 (push (cons (car type) new-marks) marks)))
742             (gnus-info-set-marks info marks t)
743             (nnimap-store-info info (gnus-active group))))))))
744
745 (defun nnimap-store-info (info active)
746   (let* ((group (gnus-group-real-name (gnus-info-group info)))
747          (entry (assoc group nnimap-current-infos)))
748     (if entry
749         (setcdr entry (list info active))
750       (push (list group info active) nnimap-current-infos))))
751
752 (defun nnimap-flags-to-marks (groups)
753   (let (data group totalp uidnext articles start-article mark)
754     (dolist (elem groups)
755       (setq group (car elem)
756             uidnext (cadr elem)
757             start-article (caddr elem)
758             articles (cdddr elem))
759       (let ((high (caar articles))
760             marks low existing)
761         (dolist (article articles)
762           (setq low (car article))
763           (push (car article) existing)
764           (dolist (flag (cdr article))
765             (setq mark (assoc flag marks))
766             (if (not mark)
767                 (push (list flag (car article)) marks)
768               (setcdr mark (cons (car article) (cdr mark)))))
769           (push (list group existing marks high low uidnext start-article)
770                 data))))
771     data))
772
773 (defun nnimap-parse-flags (sequences)
774   (goto-char (point-min))
775   (let (start end articles groups uidnext elems)
776     (dolist (elem sequences)
777       (destructuring-bind (group-sequence flag-sequence totalp group) elem
778         ;; The EXAMINE was successful.
779         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
780                    (progn
781                      (forward-line 1)
782                      (setq start (point))
783                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
784                                                (or end (point-min)) t)
785                          (setq uidnext (string-to-number (match-string 1)))
786                        (setq uidnext nil))
787                      (goto-char start))
788                    ;; The UID FETCH FLAGS was successful.
789                    (search-forward (format "\n%d OK " flag-sequence) nil t))
790           (setq end (point))
791           (goto-char start)
792           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
793             (setq elems (nnimap-parse-line (match-string 1)))
794             (push (cons (string-to-number (cadr (member "UID" elems)))
795                         (cadr (member "FLAGS" elems)))
796                   articles))
797           (push (nconc (list group uidnext totalp) articles) groups)
798           (setq articles nil))))
799     groups))
800
801 (defun nnimap-find-process-buffer (buffer)
802   (cadr (assoc buffer nnimap-connection-alist)))
803
804 (deffoo nnimap-request-post (&optional server)
805   (setq nnimap-status-string "Read-only server")
806   nil)
807
808 (defun nnimap-possibly-change-group (group server)
809   (let ((open-result t))
810     (when (and server
811                (not (nnimap-server-opened server)))
812       (setq open-result (nnimap-open-server server)))
813     (cond
814      ((not open-result)
815       nil)
816      ((not group)
817       t)
818      (t
819       (with-current-buffer (nnimap-buffer)
820         (if (equal group (nnimap-group nnimap-object))
821             t
822           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
823             (when (car result)
824               (setf (nnimap-group nnimap-object) group
825                     (nnimap-select-result nnimap-object) result)
826               result))))))))
827
828 (defun nnimap-find-connection (buffer)
829   "Find the connection delivering to BUFFER."
830   (let ((entry (assoc buffer nnimap-connection-alist)))
831     (when entry
832       (if (and (buffer-name (cadr entry))
833                (get-buffer-process (cadr entry))
834                (memq (process-status (get-buffer-process (cadr entry)))
835                      '(open run)))
836           (get-buffer-process (cadr entry))
837         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
838         nil))))
839
840 (defvar nnimap-sequence 0)
841
842 (defun nnimap-send-command (&rest args)
843   (process-send-string
844    (get-buffer-process (current-buffer))
845    (nnimap-log-command
846     (format "%d %s%s\n"
847             (incf nnimap-sequence)
848             (apply #'format args)
849             (if (nnimap-newlinep nnimap-object)
850                 ""
851               "\r"))))
852   nnimap-sequence)
853
854 (defun nnimap-log-command (command)
855   (with-current-buffer (get-buffer-create "*imap log*")
856     (goto-char (point-max))
857     (insert (format-time-string "%H:%M:%S") " " command))
858   command)
859
860 (defun nnimap-command (&rest args)
861   (erase-buffer)
862   (let* ((sequence (apply #'nnimap-send-command args))
863          (response (nnimap-get-response sequence)))
864     (if (equal (caar response) "OK")
865         (cons t response)
866       (nnheader-report 'nnimap "%s"
867                        (mapconcat #'identity (car response) " "))
868       nil)))
869
870 (defun nnimap-get-response (sequence)
871   (nnimap-wait-for-response sequence)
872   (nnimap-parse-response))
873
874 (defun nnimap-wait-for-connection ()
875   (let ((process (get-buffer-process (current-buffer))))
876     (goto-char (point-min))
877     (while (and (memq (process-status process)
878                       '(open run))
879                 (not (re-search-forward "^\\* .*\n" nil t)))
880       (nnheader-accept-process-output process)
881       (goto-char (point-min)))
882     (forward-line -1)
883     (and (looking-at "\\* \\([A-Z0-9]+\\)")
884          (match-string 1))))
885
886 (defun nnimap-wait-for-response (sequence &optional messagep)
887   (let ((process (get-buffer-process (current-buffer))))
888     (goto-char (point-max))
889     (while (and (memq (process-status process)
890                       '(open run))
891                 (not (re-search-backward (format "^%d .*\n" sequence)
892                                          (max (point-min) (- (point) 500))
893                                          t)))
894       (when messagep
895         (message "Read %dKB" (/ (buffer-size) 1000)))
896       (nnheader-accept-process-output process)
897       (goto-char (point-max)))))
898
899 (defun nnimap-parse-response ()
900   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
901         result)
902     (dolist (line lines)
903       (push (cdr (nnimap-parse-line line)) result))
904     ;; Return the OK/error code first, and then all the "continuation
905     ;; lines" afterwards.
906     (cons (pop result)
907           (nreverse result))))
908
909 ;; Parse an IMAP response line lightly.  They look like
910 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
911 ;; the lines into a list of strings and lists of string.
912 (defun nnimap-parse-line (line)
913   (let (char result)
914     (with-temp-buffer
915       (insert line)
916       (goto-char (point-min))
917       (while (not (eobp))
918         (if (eql (setq char (following-char)) ? )
919             (forward-char 1)
920           (push
921            (cond
922             ((eql char ?\[)
923              (split-string (buffer-substring
924                             (1+ (point)) (1- (search-forward "]")))))
925             ((eql char ?\()
926              (split-string (buffer-substring
927                             (1+ (point)) (1- (search-forward ")")))))
928             ((eql char ?\")
929              (forward-char 1)
930              (buffer-substring (point) (1- (search-forward "\""))))
931             (t
932              (buffer-substring (point) (if (search-forward " " nil t)
933                                            (1- (point))
934                                          (goto-char (point-max))))))
935            result)))
936       (nreverse result))))
937
938 (defun nnimap-last-response-string ()
939   (save-excursion
940     (forward-line 1)
941     (let ((end (point)))
942       (forward-line -1)
943       (when (not (bobp))
944         (forward-line -1)
945         (while (and (not (bobp))
946                     (eql (following-char) ?*))
947           (forward-line -1))
948         (unless (eql (following-char) ?*)
949           (forward-line 1)))
950       (buffer-substring (point) end))))
951
952 (defun nnimap-get-responses (sequences)
953   (let (responses)
954     (dolist (sequence sequences)
955       (goto-char (point-min))
956       (when (re-search-forward (format "^%d " sequence) nil t)
957         (push (list sequence (nnimap-parse-response))
958               responses)))
959     responses))
960
961 (defvar nnimap-incoming-split-list nil)
962
963 (defun nnimap-fetch-inbox (articles)
964   (erase-buffer)
965   (nnimap-wait-for-response
966    (nnimap-send-command
967     "UID FETCH %s %s"
968     (nnimap-article-ranges articles)
969     (format "(UID %s%s)"
970             (format
971              (if (member "IMAP4REV1"
972                          (nnimap-capabilities nnimap-object))
973                  "BODY.PEEK[HEADER] BODY.PEEK"
974                "RFC822.PEEK"))
975             (if nnimap-split-download-body-default
976                 "[]"
977               "[1]")))
978    t))
979
980 (defun nnimap-split-incoming-mail ()
981   (with-current-buffer (nnimap-buffer)
982     (let ((nnimap-incoming-split-list nil)
983           (nnmail-split-methods nnimap-split-methods)
984           (nnmail-inhibit-default-split-group t)
985           (groups (nnimap-get-groups))
986           new-articles)
987       (erase-buffer)
988       (nnimap-command "SELECT %S" nnimap-inbox)
989       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
990       (when new-articles
991         (nnimap-fetch-inbox new-articles)
992         (nnimap-transform-split-mail)
993         (nnheader-ms-strip-cr)
994         (nnmail-cache-open)
995         (nnmail-split-incoming (current-buffer)
996                                #'nnimap-save-mail-spec
997                                nil nil
998                                #'nnimap-dummy-active-number)
999         (when nnimap-incoming-split-list
1000           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1001                 sequences)
1002             ;; Create any groups that doesn't already exist on the
1003             ;; server first.
1004             (dolist (spec specs)
1005               (unless (member (car spec) groups)
1006                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1007             ;; Then copy over all the messages.
1008             (erase-buffer)
1009             (dolist (spec specs)
1010               (let ((group (car spec))
1011                     (ranges (cdr spec)))
1012                 (push (list (nnimap-send-command "UID COPY %s %S"
1013                                                  (nnimap-article-ranges ranges)
1014                                                  (utf7-encode group t))
1015                             ranges)
1016                       sequences)))
1017             ;; Wait for the last COPY response...
1018             (when sequences
1019               (nnimap-wait-for-response (caar sequences))
1020               ;; And then mark the successful copy actions as deleted,
1021               ;; and possibly expunge them.
1022               (nnimap-mark-and-expunge-incoming
1023                (nnimap-parse-copied-articles sequences)))))))))
1024
1025 (defun nnimap-mark-and-expunge-incoming (range)
1026   (when range
1027     (setq range (nnimap-article-ranges range))
1028     (nnimap-send-command
1029      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
1030     (cond
1031      ;; If the server supports it, we now delete the message we have
1032      ;; just copied over.
1033      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1034       (nnimap-send-command "UID EXPUNGE %s" range))
1035      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1036      ;; user has configured it.
1037      (nnimap-expunge-inbox
1038       (nnimap-send-command "EXPUNGE")))))
1039
1040 (defun nnimap-parse-copied-articles (sequences)
1041   (let (sequence copied range)
1042     (goto-char (point-min))
1043     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1044       (setq sequence (string-to-number (match-string 1)))
1045       (when (setq range (cadr (assq sequence sequences)))
1046         (push (gnus-uncompress-range range) copied)))
1047     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1048
1049 (defun nnimap-new-articles (flags)
1050   (let (new)
1051     (dolist (elem flags)
1052       (when (or (null (cdr elem))
1053                 (and (not (member "\\Deleted" (cdr elem)))
1054                      (not (member "\\Seen" (cdr elem)))))
1055         (push (car elem) new)))
1056     (gnus-compress-sequence (nreverse new))))
1057
1058 (defun nnimap-make-split-specs (list)
1059   (let ((specs nil)
1060         entry)
1061     (dolist (elem list)
1062       (destructuring-bind (article spec) elem
1063         (dolist (group (delete nil (mapcar #'car spec)))
1064           (unless (setq entry (assoc group specs))
1065             (push (setq entry (list group)) specs))
1066           (setcdr entry (cons article (cdr entry))))))
1067     (dolist (entry specs)
1068       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1069     specs))
1070
1071 (defun nnimap-transform-split-mail ()
1072   (goto-char (point-min))
1073   (let (article bytes)
1074     (block nil
1075       (while (not (eobp))
1076         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1077           (delete-region (point) (progn (forward-line 1) (point)))
1078           (when (eobp)
1079             (return)))
1080         (setq article (match-string 1)
1081               bytes (nnimap-get-length))
1082         (delete-region (line-beginning-position) (line-end-position))
1083         ;; Insert MMDF separator, and a way to remember what this
1084         ;; article UID is.
1085         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1086         (forward-char (1+ bytes))
1087         (setq bytes (nnimap-get-length))
1088         (delete-region (line-beginning-position) (line-end-position))
1089         (forward-char (1+ bytes))
1090         (delete-region (line-beginning-position) (line-end-position))))))
1091
1092 (defun nnimap-dummy-active-number (group &optional server)
1093   1)
1094
1095 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1096   (let (article)
1097     (goto-char (point-min))
1098     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1099         (error "Invalid nnimap mail")
1100       (setq article (string-to-number (match-string 1))))
1101     (push (list article group-art)
1102           nnimap-incoming-split-list)))
1103
1104 (provide 'nnimap)
1105
1106 ;;; nnimap.el ends here