dbc16a2f307d3126b67a411fbf2894952a572245
[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               t)))))))
362
363 (defun nnimap-find-wanted-parts (structure)
364   (let ((nnimap-level 1))
365     (message-flatten-list (nnimap-find-wanted-parts-1 structure))))
366
367 (defun nnimap-find-wanted-parts-1 (structure)
368   (let (levels)
369     (while (consp (car structure))
370       (let ((sub (pop structure)))
371         (if (consp (car sub))
372             (push (nnimap-find-wanted-parts-1 sub) levels)
373           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub))))
374             (when (string-match nnimap-fetch-partial-articles type)
375               (push nnimap-level levels)))
376           (incf nnimap-level))))
377     (nreverse levels)))
378
379 (deffoo nnimap-request-group (group &optional server dont-check info)
380   (with-current-buffer nntp-server-buffer
381     (let ((result (nnimap-possibly-change-group group server))
382           articles active marks high low)
383       (when result
384         (if (and dont-check
385                  (setq active (nth 2 (assoc group nnimap-current-infos))))
386             (insert (format "211 %d %d %d %S\n"
387                             (- (cdr active) (car active))
388                             (car active)
389                             (cdr active)
390                             group))
391           (with-current-buffer (nnimap-buffer)
392             (erase-buffer)
393             (let ((group-sequence
394                    (nnimap-send-command "SELECT %S" (utf7-encode group)))
395                   (flag-sequence
396                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
397               (nnimap-wait-for-response flag-sequence)
398               (setq marks
399                     (nnimap-flags-to-marks
400                      (nnimap-parse-flags
401                       (list (list group-sequence flag-sequence 1 group)))))
402               (when info
403                 (nnimap-update-infos marks (list info)))
404               (goto-char (point-max))
405               (cond
406                (marks
407                 (setq high (nth 3 (car marks))
408                       low (nth 4 (car marks))))
409                ((re-search-backward "UIDNEXT \\([0-9]+\\)" nil t)
410                 (setq high (string-to-number (match-string 1))
411                       low 1)))))
412           (erase-buffer)
413           (insert
414            (format
415             "211 %d %d %d %S\n"
416             (1+ (- high low))
417             low high group))))
418       t)))
419
420 (defun nnimap-get-flags (spec)
421   (let ((articles nil)
422         elems)
423     (with-current-buffer (nnimap-buffer)
424       (erase-buffer)
425       (nnimap-wait-for-response (nnimap-send-command
426                                  "UID FETCH %s FLAGS" spec))
427       (goto-char (point-min))
428       (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" nil t)
429         (setq elems (nnimap-parse-line (match-string 1)))
430         (push (cons (string-to-number (cadr (member "UID" elems)))
431                     (cadr (member "FLAGS" elems)))
432               articles)))
433     (nreverse articles)))
434
435 (deffoo nnimap-close-group (group &optional server)
436   t)
437
438 (deffoo nnimap-request-move-article (article group server accept-form
439                                              &optional last internal-move-group)
440   (when (nnimap-possibly-change-group group server)
441     ;; If the move is internal (on the same server), just do it the easy
442     ;; way.
443     (let ((message-id (message-field-value "message-id")))
444       (if internal-move-group
445           (let ((result
446                  (with-current-buffer (nnimap-buffer)
447                    (nnimap-command "UID COPY %d %S"
448                                    article
449                                    (utf7-encode internal-move-group t)))))
450             (when (car result)
451               (nnimap-delete-article article)
452               (cons internal-move-group
453                     (nnimap-find-article-by-message-id
454                      internal-move-group message-id))))
455         (with-temp-buffer
456           (let ((result (eval accept-form)))
457             (when result
458               (nnimap-delete-article article)
459               result)))))))
460
461 (deffoo nnimap-request-expire-articles (articles group &optional server force)
462   (cond
463    ((not (nnimap-possibly-change-group group server))
464     articles)
465    (force
466     (unless (nnimap-delete-article articles)
467       (message "Article marked for deletion, but not expunged."))
468     nil)
469    (t
470     articles)))
471
472 (defun nnimap-find-article-by-message-id (group message-id)
473   (when (nnimap-possibly-change-group group nil)
474     (with-current-buffer (nnimap-buffer)
475       (let ((result
476              (nnimap-command "UID SEARCH HEADER Message-Id %S" message-id))
477             article)
478         (when (car result)
479           ;; Select the last instance of the message in the group.
480           (and (setq article
481                      (car (last (assoc "SEARCH" (cdr result)))))
482                (string-to-number article)))))))
483
484 (defun nnimap-delete-article (articles)
485   (with-current-buffer (nnimap-buffer)
486     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
487                     (nnimap-article-ranges articles))
488     (when (member "UIDPLUS" (nnimap-capabilities nnimap-object))
489       (nnimap-send-command "UID EXPUNGE %s"
490                            (nnimap-article-ranges articles))
491       t)))
492
493 (deffoo nnimap-request-scan (&optional group server)
494   (when (and (nnimap-possibly-change-group nil server)
495              (equal group nnimap-inbox)
496              nnimap-inbox
497              nnimap-split-methods)
498     (nnimap-split-incoming-mail)))
499
500 (defun nnimap-marks-to-flags (marks)
501   (let (flags flag)
502     (dolist (mark marks)
503       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
504         (push flag flags)))
505     flags))
506
507 (deffoo nnimap-request-set-mark (group actions &optional server)
508   (when (nnimap-possibly-change-group group server)
509     (let (sequence)
510       (with-current-buffer (nnimap-buffer)
511         ;; Just send all the STORE commands without waiting for
512         ;; response.  If they're successful, they're successful.
513         (dolist (action actions)
514           (destructuring-bind (range action marks) action
515             (let ((flags (nnimap-marks-to-flags marks)))
516               (when flags
517                 (setq sequence (nnimap-send-command
518                                 "UID STORE %s %sFLAGS.SILENT (%s)"
519                                 (nnimap-article-ranges range)
520                                 (if (eq action 'del)
521                                     "-"
522                                   "+")
523                                 (mapconcat #'identity flags " ")))))))
524         ;; Wait for the last command to complete to avoid later
525         ;; syncronisation problems with the stream.
526         (nnimap-wait-for-response sequence)))))
527
528 (deffoo nnimap-request-accept-article (group &optional server last)
529   (when (nnimap-possibly-change-group nil server)
530     (nnmail-check-syntax)
531     (let ((message (buffer-string))
532           (message-id (message-field-value "message-id"))
533           sequence)
534       (with-current-buffer (nnimap-buffer)
535         (setq sequence (nnimap-send-command
536                         "APPEND %S {%d}" (utf7-encode group t)
537                         (length message)))
538         (process-send-string (get-buffer-process (current-buffer)) message)
539         (process-send-string (get-buffer-process (current-buffer))
540                              (if (nnimap-newlinep nnimap-object)
541                                  "\n"
542                                "\r\n"))
543         (let ((result (nnimap-get-response sequence)))
544           (when result
545             (cons group
546                   (nnimap-find-article-by-message-id group message-id))))))))
547
548 (defun nnimap-add-cr ()
549   (goto-char (point-min))
550   (while (re-search-forward "\r?\n" nil t)
551     (replace-match "\r\n" t t)))
552
553 (defun nnimap-get-groups ()
554   (let ((result (nnimap-command "LIST \"\" \"*\""))
555         groups)
556     (when (car result)
557       (dolist (line (cdr result))
558         (when (and (equal (car line) "LIST")
559                    (not (and (caadr line)
560                              (string-match "noselect" (caadr line)))))
561           (push (car (last line)) groups)))
562       (nreverse groups))))
563
564 (deffoo nnimap-request-list (&optional server)
565   (nnimap-possibly-change-group nil server)
566   (with-current-buffer nntp-server-buffer
567     (erase-buffer)
568     (let ((groups
569            (with-current-buffer (nnimap-buffer)
570              (nnimap-get-groups)))
571           sequences responses)
572       (when groups
573         (with-current-buffer (nnimap-buffer)
574           (dolist (group groups)
575             (push (list (nnimap-send-command "EXAMINE %S" (utf7-encode group t))
576                         group)
577                   sequences))
578           (nnimap-wait-for-response (caar sequences))
579           (setq responses
580                 (nnimap-get-responses (mapcar #'car sequences))))
581         (dolist (response responses)
582           (let* ((sequence (car response))
583                  (response (cadr response))
584                  (group (cadr (assoc sequence sequences))))
585             (when (and group
586                        (equal (caar response) "OK"))
587               (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
588                     highest exists)
589                 (dolist (elem response)
590                   (when (equal (cadr elem) "EXISTS")
591                     (setq exists (string-to-number (car elem)))))
592                 (when uidnext
593                   (setq highest (1- (string-to-number (car uidnext)))))
594                 (cond
595                  ((null highest)
596                   (insert (format "%S 0 1 y\n" (utf7-decode group t))))
597                  ((zerop exists)
598                   ;; Empty group.
599                   (insert (format "%S %d %d y\n"
600                                   (utf7-decode group t) highest (1+ highest))))
601                  (t
602                   ;; Return the widest possible range.
603                   (insert (format "%S %d 1 y\n" (utf7-decode group t)
604                                   (or highest exists)))))))))
605         t))))
606
607 (deffoo nnimap-retrieve-group-data-early (server infos)
608   (when (nnimap-possibly-change-group nil server)
609     (with-current-buffer (nnimap-buffer)
610       ;; QRESYNC handling isn't implemented.
611       (let ((qresyncp (member "notQRESYNC" (nnimap-capabilities nnimap-object)))
612             marks groups sequences)
613         ;; Go through the infos and gather the data needed to know
614         ;; what and how to request the data.
615         (dolist (info infos)
616           (setq marks (gnus-info-marks info))
617           (push (list (gnus-group-real-name (gnus-info-group info))
618                       (cdr (assq 'active marks))
619                       (cdr (assq 'uid marks)))
620                 groups))
621         ;; Then request the data.
622         (erase-buffer)
623         (dolist (elem groups)
624           (if (and qresyncp
625                    (nth 2 elem))
626               (push
627                (list 'qresync
628                      (nnimap-send-command "EXAMINE %S (QRESYNC (%s %s))"
629                                           (car elem)
630                                           (car (nth 2 elem))
631                                           (cdr (nth 2 elem)))
632                      nil
633                      (car elem))
634                sequences)
635             (let ((start
636                    (if (nth 1 elem)
637                        ;; Fetch the last 100 flags.
638                        (max 1 (- (cdr (nth 1 elem)) 100))
639                      1)))
640               (push (list (nnimap-send-command "EXAMINE %S" (car elem))
641                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
642                           start
643                           (car elem))
644                     sequences))))
645         sequences))))
646
647 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
648   (when (and sequences
649              (nnimap-possibly-change-group nil server))
650     (with-current-buffer (nnimap-buffer)
651       ;; Wait for the final data to trickle in.
652       (nnimap-wait-for-response (cadar sequences))
653       ;; Now we should have all the data we need, no matter whether
654       ;; we're QRESYNCING, fetching all the flags from scratch, or
655       ;; just fetching the last 100 flags per group.
656       (nnimap-update-infos (nnimap-flags-to-marks
657                             (nnimap-parse-flags
658                              (nreverse sequences)))
659                            infos)
660       ;; Finally, just return something resembling an active file in
661       ;; the nntp buffer, so that the agent can save the info, too.
662       (with-current-buffer nntp-server-buffer
663         (erase-buffer)
664         (dolist (info infos)
665           (let* ((group (gnus-info-group info))
666                  (active (gnus-active group)))
667             (when active
668               (insert (format "%S %d %d y\n"
669                               (gnus-group-real-name group)
670                               (cdr active)
671                               (car active))))))))))
672
673 (defun nnimap-update-infos (flags infos)
674   (dolist (info infos)
675     (let ((group (gnus-group-real-name (gnus-info-group info))))
676       (nnimap-update-info info (cdr (assoc group flags))))))
677
678 (defun nnimap-update-info (info marks)
679   (when marks
680     (destructuring-bind (existing flags high low uidnext start-article) marks
681       (let ((group (gnus-info-group info))
682             (completep (and start-article
683                             (= start-article 1))))
684         ;; First set the active ranges based on high/low.
685         (if (or completep
686                 (not (gnus-active group)))
687             (gnus-set-active group
688                              (if high
689                                  (cons low high)
690                                ;; No articles in this group.
691                                (cons (1- uidnext) uidnext)))
692           (setcdr (gnus-active group) high))
693         ;; Then update the list of read articles.
694         (let* ((unread
695                 (gnus-compress-sequence
696                  (gnus-set-difference
697                   (gnus-set-difference
698                    existing
699                    (cdr (assoc "\\Seen" flags)))
700                   (cdr (assoc "\\Flagged" flags)))))
701                (read (gnus-range-difference
702                       (cons start-article high) unread)))
703           (when (> start-article 1)
704             (setq read
705                   (gnus-range-nconcat
706                    (if (> start-article 1)
707                        (gnus-sorted-range-intersection
708                         (cons 1 (1- start-article))
709                         (gnus-info-read info))
710                      (gnus-info-read info))
711                    read)))
712           (gnus-info-set-read info read)
713           ;; Update the marks.
714           (setq marks (gnus-info-marks info))
715           ;; Note the active level for the next run-through.
716           (let ((active (assq 'active marks)))
717             (if active
718                 (setcdr active (gnus-active group))
719               (push (cons 'active (gnus-active group)) marks)))
720           (dolist (type (cdr nnimap-mark-alist))
721             (let ((old-marks (assoc (car type) marks))
722                   (new-marks (gnus-compress-sequence
723                               (cdr (assoc (cadr type) flags)))))
724               (setq marks (delq old-marks marks))
725               (pop old-marks)
726               (when (and old-marks
727                          (> start-article 1))
728                 (setq old-marks (gnus-range-difference
729                                  old-marks
730                                  (cons start-article high)))
731                 (setq new-marks (gnus-range-nconcat old-marks new-marks)))
732               (when new-marks
733                 (push (cons (car type) new-marks) marks)))
734             (gnus-info-set-marks info marks t)
735             (nnimap-store-info info (gnus-active group))))))))
736
737 (defun nnimap-store-info (info active)
738   (let* ((group (gnus-group-real-name (gnus-info-group info)))
739          (entry (assoc group nnimap-current-infos)))
740     (if entry
741         (setcdr entry (list info active))
742       (push (list group info active) nnimap-current-infos))))
743
744 (defun nnimap-flags-to-marks (groups)
745   (let (data group totalp uidnext articles start-article mark)
746     (dolist (elem groups)
747       (setq group (car elem)
748             uidnext (cadr elem)
749             start-article (caddr elem)
750             articles (cdddr elem))
751       (let ((high (caar articles))
752             marks low existing)
753         (dolist (article articles)
754           (setq low (car article))
755           (push (car article) existing)
756           (dolist (flag (cdr article))
757             (setq mark (assoc flag marks))
758             (if (not mark)
759                 (push (list flag (car article)) marks)
760               (setcdr mark (cons (car article) (cdr mark)))))
761           (push (list group existing marks high low uidnext start-article)
762                 data))))
763     data))
764
765 (defun nnimap-parse-flags (sequences)
766   (goto-char (point-min))
767   (let (start end articles groups uidnext elems)
768     (dolist (elem sequences)
769       (destructuring-bind (group-sequence flag-sequence totalp group) elem
770         ;; The EXAMINE was successful.
771         (when (and (search-forward (format "\n%d OK " group-sequence) nil t)
772                    (progn
773                      (forward-line 1)
774                      (setq start (point))
775                      (if (re-search-backward "UIDNEXT \\([0-9]+\\)"
776                                                (or end (point-min)) t)
777                          (setq uidnext (string-to-number (match-string 1)))
778                        (setq uidnext nil))
779                      (goto-char start))
780                    ;; The UID FETCH FLAGS was successful.
781                    (search-forward (format "\n%d OK " flag-sequence) nil t))
782           (setq end (point))
783           (goto-char start)
784           (while (re-search-forward "^\\* [0-9]+ FETCH (\\(.*\\))" end t)
785             (setq elems (nnimap-parse-line (match-string 1)))
786             (push (cons (string-to-number (cadr (member "UID" elems)))
787                         (cadr (member "FLAGS" elems)))
788                   articles))
789           (push (nconc (list group uidnext totalp) articles) groups)
790           (setq articles nil))))
791     groups))
792
793 (defun nnimap-find-process-buffer (buffer)
794   (cadr (assoc buffer nnimap-connection-alist)))
795
796 (deffoo nnimap-request-post (&optional server)
797   (setq nnimap-status-string "Read-only server")
798   nil)
799
800 (defun nnimap-possibly-change-group (group server)
801   (let ((open-result t))
802     (when (and server
803                (not (nnimap-server-opened server)))
804       (setq open-result (nnimap-open-server server)))
805     (cond
806      ((not open-result)
807       nil)
808      ((not group)
809       t)
810      (t
811       (with-current-buffer (nnimap-buffer)
812         (if (equal group (nnimap-group nnimap-object))
813             t
814           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
815             (when (car result)
816               (setf (nnimap-group nnimap-object) group
817                     (nnimap-select-result nnimap-object) result)
818               result))))))))
819
820 (defun nnimap-find-connection (buffer)
821   "Find the connection delivering to BUFFER."
822   (let ((entry (assoc buffer nnimap-connection-alist)))
823     (when entry
824       (if (and (buffer-name (cadr entry))
825                (get-buffer-process (cadr entry))
826                (memq (process-status (get-buffer-process (cadr entry)))
827                      '(open run)))
828           (get-buffer-process (cadr entry))
829         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
830         nil))))
831
832 (defvar nnimap-sequence 0)
833
834 (defun nnimap-send-command (&rest args)
835   (process-send-string
836    (get-buffer-process (current-buffer))
837    (nnimap-log-command
838     (format "%d %s%s\n"
839             (incf nnimap-sequence)
840             (apply #'format args)
841             (if (nnimap-newlinep nnimap-object)
842                 ""
843               "\r"))))
844   nnimap-sequence)
845
846 (defun nnimap-log-command (command)
847   (with-current-buffer (get-buffer-create "*imap log*")
848     (goto-char (point-max))
849     (insert (format-time-string "%H:%M:%S") " " command))
850   command)
851
852 (defun nnimap-command (&rest args)
853   (erase-buffer)
854   (let* ((sequence (apply #'nnimap-send-command args))
855          (response (nnimap-get-response sequence)))
856     (if (equal (caar response) "OK")
857         (cons t response)
858       (nnheader-report 'nnimap "%s"
859                        (mapconcat #'identity (car response) " "))
860       nil)))
861
862 (defun nnimap-get-response (sequence)
863   (nnimap-wait-for-response sequence)
864   (nnimap-parse-response))
865
866 (defun nnimap-wait-for-connection ()
867   (let ((process (get-buffer-process (current-buffer))))
868     (goto-char (point-min))
869     (while (and (memq (process-status process)
870                       '(open run))
871                 (not (re-search-forward "^\\* " nil t)))
872       (nnheader-accept-process-output process)
873       (goto-char (point-min)))
874     (and (looking-at "[A-Z0-9]+")
875          (match-string 0))))
876
877 (defun nnimap-wait-for-response (sequence &optional messagep)
878   (let ((process (get-buffer-process (current-buffer))))
879     (goto-char (point-max))
880     (while (and (memq (process-status process)
881                       '(open run))
882                 (not (re-search-backward (format "^%d .*\n" sequence)
883                                          (max (point-min) (- (point) 500))
884                                          t)))
885       (when messagep
886         (message "Read %dKB" (/ (buffer-size) 1000)))
887       (nnheader-accept-process-output process)
888       (goto-char (point-max)))))
889
890 (defun nnimap-parse-response ()
891   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
892         result)
893     (dolist (line lines)
894       (push (cdr (nnimap-parse-line line)) result))
895     ;; Return the OK/error code first, and then all the "continuation
896     ;; lines" afterwards.
897     (cons (pop result)
898           (nreverse result))))
899
900 ;; Parse an IMAP response line lightly.  They look like
901 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
902 ;; the lines into a list of strings and lists of string.
903 (defun nnimap-parse-line (line)
904   (let (char result)
905     (with-temp-buffer
906       (insert line)
907       (goto-char (point-min))
908       (while (not (eobp))
909         (if (eql (setq char (following-char)) ? )
910             (forward-char 1)
911           (push
912            (cond
913             ((eql char ?\[)
914              (split-string (buffer-substring
915                             (1+ (point)) (1- (search-forward "]")))))
916             ((eql char ?\()
917              (split-string (buffer-substring
918                             (1+ (point)) (1- (search-forward ")")))))
919             ((eql char ?\")
920              (forward-char 1)
921              (buffer-substring (point) (1- (search-forward "\""))))
922             (t
923              (buffer-substring (point) (if (search-forward " " nil t)
924                                            (1- (point))
925                                          (goto-char (point-max))))))
926            result)))
927       (nreverse result))))
928
929 (defun nnimap-last-response-string ()
930   (save-excursion
931     (forward-line 1)
932     (let ((end (point)))
933       (forward-line -1)
934       (when (not (bobp))
935         (forward-line -1)
936         (while (and (not (bobp))
937                     (eql (following-char) ?*))
938           (forward-line -1))
939         (unless (eql (following-char) ?*)
940           (forward-line 1)))
941       (buffer-substring (point) end))))
942
943 (defun nnimap-get-responses (sequences)
944   (let (responses)
945     (dolist (sequence sequences)
946       (goto-char (point-min))
947       (when (re-search-forward (format "^%d " sequence) nil t)
948         (push (list sequence (nnimap-parse-response))
949               responses)))
950     responses))
951
952 (defvar nnimap-incoming-split-list nil)
953
954 (defun nnimap-fetch-inbox (articles)
955   (erase-buffer)
956   (nnimap-wait-for-response
957    (nnimap-send-command
958     "UID FETCH %s %s"
959     (nnimap-article-ranges articles)
960     (format "(UID %s%s)"
961             (format
962              (if (member "IMAP4REV1"
963                          (nnimap-capabilities nnimap-object))
964                  "BODY.PEEK[HEADER] BODY.PEEK"
965                "RFC822.PEEK"))
966             (if nnimap-split-download-body-default
967                 ""
968               "[1]")))
969    t))
970
971 (defun nnimap-split-incoming-mail ()
972   (with-current-buffer (nnimap-buffer)
973     (let ((nnimap-incoming-split-list nil)
974           (nnmail-split-methods nnimap-split-methods)
975           (nnmail-inhibit-default-split-group t)
976           (groups (nnimap-get-groups))
977           new-articles)
978       (erase-buffer)
979       (nnimap-command "SELECT %S" nnimap-inbox)
980       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
981       (when new-articles
982         (nnimap-fetch-inbox new-articles)
983         (nnimap-transform-split-mail)
984         (nnheader-ms-strip-cr)
985         (nnmail-cache-open)
986         (nnmail-split-incoming (current-buffer)
987                                #'nnimap-save-mail-spec
988                                nil nil
989                                #'nnimap-dummy-active-number)
990         (when nnimap-incoming-split-list
991           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
992                 sequences)
993             ;; Create any groups that doesn't already exist on the
994             ;; server first.
995             (dolist (spec specs)
996               (unless (member (car spec) groups)
997                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
998             ;; Then copy over all the messages.
999             (erase-buffer)
1000             (dolist (spec specs)
1001               (let ((group (car spec))
1002                     (ranges (cdr spec)))
1003                 (push (list (nnimap-send-command "UID COPY %s %S"
1004                                                  (nnimap-article-ranges ranges)
1005                                                  (utf7-encode group t))
1006                             ranges)
1007                       sequences)))
1008             ;; Wait for the last COPY response...
1009             (when sequences
1010               (nnimap-wait-for-response (caar sequences))
1011               ;; And then mark the successful copy actions as deleted,
1012               ;; and possibly expunge them.
1013               (nnimap-mark-and-expunge-incoming
1014                (nnimap-parse-copied-articles sequences)))))))))
1015
1016 (defun nnimap-mark-and-expunge-incoming (range)
1017   (when range
1018     (setq range (nnimap-article-ranges range))
1019     (nnimap-send-command
1020      "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)
1021     (cond
1022      ;; If the server supports it, we now delete the message we have
1023      ;; just copied over.
1024      ((member "UIDPLUS" (nnimap-capabilities nnimap-object))
1025       (nnimap-send-command "UID EXPUNGE %s" range))
1026      ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1027      ;; user has configured it.
1028      (nnimap-expunge-inbox
1029       (nnimap-send-command "EXPUNGE")))))
1030
1031 (defun nnimap-parse-copied-articles (sequences)
1032   (let (sequence copied range)
1033     (goto-char (point-min))
1034     (while (re-search-forward "^\\([0-9]+\\) OK " nil t)
1035       (setq sequence (string-to-number (match-string 1)))
1036       (when (setq range (cadr (assq sequence sequences)))
1037         (push (gnus-uncompress-range range) copied)))
1038     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
1039
1040 (defun nnimap-new-articles (flags)
1041   (let (new)
1042     (dolist (elem flags)
1043       (when (or (null (cdr elem))
1044                 (and (not (member "\\Deleted" (cdr elem)))
1045                      (not (member "\\Seen" (cdr elem)))))
1046         (push (car elem) new)))
1047     (gnus-compress-sequence (nreverse new))))
1048
1049 (defun nnimap-make-split-specs (list)
1050   (let ((specs nil)
1051         entry)
1052     (dolist (elem list)
1053       (destructuring-bind (article spec) elem
1054         (dolist (group (delete nil (mapcar #'car spec)))
1055           (unless (setq entry (assoc group specs))
1056             (push (setq entry (list group)) specs))
1057           (setcdr entry (cons article (cdr entry))))))
1058     (dolist (entry specs)
1059       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
1060     specs))
1061
1062 (defun nnimap-transform-split-mail ()
1063   (goto-char (point-min))
1064   (let (article bytes)
1065     (block nil
1066       (while (not (eobp))
1067         (while (not (looking-at "^\\* [0-9]+ FETCH.*UID \\([0-9]+\\)"))
1068           (delete-region (point) (progn (forward-line 1) (point)))
1069           (when (eobp)
1070             (return)))
1071         (setq article (match-string 1)
1072               bytes (nnimap-get-length))
1073         (delete-region (line-beginning-position) (line-end-position))
1074         ;; Insert MMDF separator, and a way to remember what this
1075         ;; article UID is.
1076         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
1077         (forward-char (1+ bytes))
1078         (setq bytes (nnimap-get-length))
1079         (delete-region (line-beginning-position) (line-end-position))
1080         (forward-char (1+ bytes))
1081         (delete-region (line-beginning-position) (line-end-position))))))
1082
1083 (defun nnimap-dummy-active-number (group &optional server)
1084   1)
1085
1086 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
1087   (let (article)
1088     (goto-char (point-min))
1089     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
1090         (error "Invalid nnimap mail")
1091       (setq article (string-to-number (match-string 1))))
1092     (push (list article group-art)
1093           nnimap-incoming-split-list)))
1094
1095 (provide 'nnimap)
1096
1097 ;;; nnimap.el ends here