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