Merge remote branch 'origin/no-gnus'
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- IMAP interface for Gnus
2
3 ;; Copyright (C) 2010-2012 Free Software Foundation, Inc.
4
5 ;; Author: Lars Magne Ingebrigtsen <larsi@gnus.org>
6 ;;         Simon Josefsson <simon@josefsson.org>
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
22
23 ;;; Commentary:
24
25 ;; nnimap interfaces Gnus with IMAP servers.
26
27 ;;; Code:
28
29 ;; For Emacs <22.2 and XEmacs.
30 (eval-and-compile
31   (unless (fboundp 'declare-function) (defmacro declare-function (&rest r))))
32
33 (eval-and-compile
34   (require 'nnheader)
35   ;; In Emacs 24, `open-protocol-stream' is an autoloaded alias for
36   ;; `make-network-stream'.
37   (unless (fboundp 'open-protocol-stream)
38     (require 'proto-stream)))
39
40 (eval-when-compile
41   (require 'cl))
42
43 (require 'nnheader)
44 (require 'gnus-util)
45 (require 'gnus)
46 (require 'nnoo)
47 (require 'netrc)
48 (require 'utf7)
49 (require 'tls)
50 (require 'parse-time)
51 (require 'nnmail)
52
53 (autoload 'auth-source-forget+ "auth-source")
54 (autoload 'auth-source-search "auth-source")
55
56 (nnoo-declare nnimap)
57
58 (defvoo nnimap-address nil
59   "The address of the IMAP server.")
60
61 (defvoo nnimap-user nil
62   "Username to use for authentication to the IMAP server.")
63
64 (defvoo nnimap-server-port nil
65   "The IMAP port used.
66 If nnimap-stream is `ssl', this will default to `imaps'.  If not,
67 it will default to `imap'.")
68
69 (defvoo nnimap-stream 'undecided
70   "How nnimap talks to the IMAP server.
71 The value should be either `undecided', `ssl' or `tls',
72 `network', `starttls', `plain', or `shell'.
73
74 If the value is `undecided', nnimap tries `ssl' first, then falls
75 back on `network'.")
76
77 (defvoo nnimap-shell-program (if (boundp 'imap-shell-program)
78                                  (if (listp imap-shell-program)
79                                      (car imap-shell-program)
80                                    imap-shell-program)
81                                "ssh %s imapd"))
82
83 (defvoo nnimap-inbox nil
84   "The mail box where incoming mail arrives and should be split out of.
85 This can be a string or a list of strings
86 For example, \"INBOX\" or (\"INBOX\" \"SENT\").")
87
88 (defvoo nnimap-split-methods nil
89   "How mail is split.
90 Uses the same syntax as `nnmail-split-methods'.")
91
92 (defvoo nnimap-split-fancy nil
93   "Uses the same syntax as `nnmail-split-fancy'.")
94
95 (defvoo nnimap-unsplittable-articles '(%Deleted %Seen)
96   "Articles with the flags in the list will not be considered when splitting.")
97
98 (make-obsolete-variable 'nnimap-split-rule "see `nnimap-split-methods'"
99                         "Emacs 24.1")
100
101 (defvoo nnimap-authenticator nil
102   "How nnimap authenticate itself to the server.
103 Possible choices are nil (use default methods) or `anonymous'.")
104
105 (defvoo nnimap-expunge t
106   "If non-nil, expunge articles after deleting them.
107 This is always done if the server supports UID EXPUNGE, but it's
108 not done by default on servers that doesn't support that command.")
109
110 (defvoo nnimap-streaming t
111   "If non-nil, try to use streaming commands with IMAP servers.
112 Switching this off will make nnimap slower, but it helps with
113 some servers.")
114
115 (defvoo nnimap-connection-alist nil)
116
117 (defvoo nnimap-current-infos nil)
118
119 (defvoo nnimap-fetch-partial-articles nil
120   "If non-nil, Gnus will fetch partial articles.
121 If t, Gnus will fetch only the first part.  If a string, it
122 will fetch all parts that have types that match that string.  A
123 likely value would be \"text/\" to automatically fetch all
124 textual parts.")
125
126 (defvar nnimap-process nil)
127
128 (defvar nnimap-status-string "")
129
130 (defvar nnimap-split-download-body-default nil
131   "Internal variable with default value for `nnimap-split-download-body'.")
132
133 (defvar nnimap-keepalive-timer nil)
134 (defvar nnimap-process-buffers nil)
135
136 (defstruct nnimap
137   group process commands capabilities select-result newlinep server
138   last-command-time greeting examined stream-type initial-resync)
139
140 (defvar nnimap-object nil)
141
142 (defvar nnimap-mark-alist
143   '((read "\\Seen" %Seen)
144     (tick "\\Flagged" %Flagged)
145     (reply "\\Answered" %Answered)
146     (expire "gnus-expire")
147     (dormant "gnus-dormant")
148     (score "gnus-score")
149     (save "gnus-save")
150     (download "gnus-download")
151     (forward "gnus-forward")))
152
153 (defvar nnimap-quirks
154   '(("QRESYNC" "Zimbra" "QRESYNC ")))
155
156 (defvar nnimap-inhibit-logging nil)
157
158 (defun nnimap-buffer ()
159   (nnimap-find-process-buffer nntp-server-buffer))
160
161 (defun nnimap-header-parameters ()
162   (format "(UID RFC822.SIZE BODYSTRUCTURE %s)"
163           (format
164            (if (nnimap-ver4-p)
165                "BODY.PEEK[HEADER.FIELDS %s]"
166              "RFC822.HEADER.LINES %s")
167            (append '(Subject From Date Message-Id
168                              References In-Reply-To Xref)
169                    nnmail-extra-headers))))
170
171 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
172   (when group
173     (setq group (nnimap-decode-gnus-group group)))
174   (with-current-buffer nntp-server-buffer
175     (erase-buffer)
176     (when (nnimap-possibly-change-group group server)
177       (with-current-buffer (nnimap-buffer)
178         (erase-buffer)
179         (nnimap-wait-for-response
180          (nnimap-send-command
181           "UID FETCH %s %s"
182           (nnimap-article-ranges (gnus-compress-sequence articles))
183           (nnimap-header-parameters))
184          t)
185         (nnimap-transform-headers)
186         (nnheader-remove-cr-followed-by-lf))
187       (insert-buffer-substring
188        (nnimap-find-process-buffer (current-buffer))))
189     'headers))
190
191 (defun nnimap-transform-headers ()
192   (goto-char (point-min))
193   (let (article lines size string)
194     (block nil
195       (while (not (eobp))
196         (while (not (looking-at "\\* [0-9]+ FETCH"))
197           (delete-region (point) (progn (forward-line 1) (point)))
198           (when (eobp)
199             (return)))
200         (goto-char (match-end 0))
201         ;; Unfold quoted {number} strings.
202         (while (re-search-forward
203                 "[^]][ (]{\\([0-9]+\\)}\r?\n"
204                 (save-excursion
205                   ;; Start of the header section.
206                   (or (re-search-forward "] {[0-9]+}\r?\n" nil t)
207                       ;; Start of the next FETCH.
208                       (re-search-forward "\\* [0-9]+ FETCH" nil t)
209                       (point-max)))
210                 t)
211           (setq size (string-to-number (match-string 1)))
212           (delete-region (+ (match-beginning 0) 2) (point))
213           (setq string (buffer-substring (point) (+ (point) size)))
214           (delete-region (point) (+ (point) size))
215           (insert (format "%S" (mm-subst-char-in-string ?\n ?\s string))))
216         (beginning-of-line)
217         (setq article
218               (and (re-search-forward "UID \\([0-9]+\\)" (line-end-position)
219                                       t)
220                    (match-string 1)))
221         (setq lines nil)
222         (setq size
223               (and (re-search-forward "RFC822.SIZE \\([0-9]+\\)"
224                                       (line-end-position)
225                                       t)
226                    (match-string 1)))
227         (beginning-of-line)
228         (when (search-forward "BODYSTRUCTURE" (line-end-position) t)
229           (let ((structure (ignore-errors
230                              (read (current-buffer)))))
231             (while (and (consp structure)
232                         (not (atom (car structure))))
233               (setq structure (car structure)))
234             (setq lines (if (and
235                              (stringp (car structure))
236                              (equal (upcase (nth 0 structure)) "MESSAGE")
237                              (equal (upcase (nth 1 structure)) "RFC822"))
238                             (nth 9 structure)
239                           (nth 7 structure)))))
240         (delete-region (line-beginning-position) (line-end-position))
241         (insert (format "211 %s Article retrieved." article))
242         (forward-line 1)
243         (when size
244           (insert (format "Chars: %s\n" size)))
245         (when lines
246           (insert (format "Lines: %s\n" lines)))
247         (unless (re-search-forward "^\r$" nil t)
248           (goto-char (point-max)))
249         (delete-region (line-beginning-position) (line-end-position))
250         (insert ".")
251         (forward-line 1)))))
252
253 (defun nnimap-unfold-quoted-lines ()
254   ;; Unfold quoted {number} strings.
255   (let (size string)
256     (while (re-search-forward " {\\([0-9]+\\)}\r?\n" nil t)
257       (setq size (string-to-number (match-string 1)))
258       (delete-region (1+ (match-beginning 0)) (point))
259       (setq string (buffer-substring (point) (+ (point) size)))
260       (delete-region (point) (+ (point) size))
261       (insert (format "%S" string)))))
262
263 (defun nnimap-get-length ()
264   (and (re-search-forward "{\\([0-9]+\\)}" (line-end-position) t)
265        (string-to-number (match-string 1))))
266
267 (defun nnimap-article-ranges (ranges)
268   (let (result)
269     (cond
270      ((numberp ranges)
271       (number-to-string ranges))
272      ((numberp (cdr ranges))
273       (format "%d:%d" (car ranges) (cdr ranges)))
274      (t
275       (dolist (elem ranges)
276         (push
277          (if (consp elem)
278              (format "%d:%d" (car elem) (cdr elem))
279            (number-to-string elem))
280          result))
281       (mapconcat #'identity (nreverse result) ",")))))
282
283 (deffoo nnimap-open-server (server &optional defs no-reconnect)
284   (if (nnimap-server-opened server)
285       t
286     (unless (assq 'nnimap-address defs)
287       (setq defs (append defs (list (list 'nnimap-address server)))))
288     (nnoo-change-server 'nnimap server defs)
289     (if no-reconnect
290         (nnimap-find-connection nntp-server-buffer)
291       (or (nnimap-find-connection nntp-server-buffer)
292           (nnimap-open-connection nntp-server-buffer)))))
293
294 (defun nnimap-make-process-buffer (buffer)
295   (with-current-buffer
296       (generate-new-buffer (format " *nnimap %s %s %s*"
297                                    nnimap-address nnimap-server-port
298                                    (gnus-buffer-exists-p buffer)))
299     (mm-disable-multibyte)
300     (buffer-disable-undo)
301     (gnus-add-buffer)
302     (set (make-local-variable 'after-change-functions) nil)
303     (set (make-local-variable 'nnimap-object)
304          (make-nnimap :server (nnoo-current-server 'nnimap)
305                       :initial-resync 0))
306     (push (list buffer (current-buffer)) nnimap-connection-alist)
307     (push (current-buffer) nnimap-process-buffers)
308     (current-buffer)))
309
310 (defun nnimap-credentials (address ports user)
311   (let* ((auth-source-creation-prompts
312           '((user  . "IMAP user at %h: ")
313             (secret . "IMAP password for %u@%h: ")))
314          (found (nth 0 (auth-source-search :max 1
315                                            :host address
316                                            :port ports
317                                            :user user
318                                            :require '(:user :secret)
319                                            :create t))))
320     (if found
321         (list (plist-get found :user)
322               (let ((secret (plist-get found :secret)))
323                 (if (functionp secret)
324                     (funcall secret)
325                   secret))
326               (plist-get found :save-function))
327       nil)))
328
329 (defun nnimap-keepalive ()
330   (let ((now (current-time)))
331     (dolist (buffer nnimap-process-buffers)
332       (when (buffer-name buffer)
333         (with-current-buffer buffer
334           (when (and nnimap-object
335                      (nnimap-last-command-time nnimap-object)
336                      (> (gnus-float-time
337                          (time-subtract
338                           now
339                           (nnimap-last-command-time nnimap-object)))
340                         ;; More than five minutes since the last command.
341                         (* 5 60)))
342             (nnimap-send-command "NOOP")))))))
343
344 (defun nnimap-open-connection (buffer)
345   ;; Be backwards-compatible -- the earlier value of nnimap-stream was
346   ;; `ssl' when nnimap-server-port was nil.  Sort of.
347   (when (and nnimap-server-port
348              (eq nnimap-stream 'undecided))
349     (setq nnimap-stream 'ssl))
350   (let ((stream
351          (if (eq nnimap-stream 'undecided)
352              (loop for type in '(ssl network)
353                    for stream = (let ((nnimap-stream type))
354                                   (nnimap-open-connection-1 buffer))
355                    while (eq stream 'no-connect)
356                    finally (return stream))
357            (nnimap-open-connection-1 buffer))))
358     (if (eq stream 'no-connect)
359         nil
360       stream)))
361
362 (defun nnimap-map-port (port)
363   (if (equal port "imaps")
364       "993"
365     port))
366
367 (defun nnimap-open-connection-1 (buffer)
368   (unless nnimap-keepalive-timer
369     (setq nnimap-keepalive-timer (run-at-time (* 60 15) (* 60 15)
370                                               'nnimap-keepalive)))
371   (with-current-buffer (nnimap-make-process-buffer buffer)
372     (let* ((coding-system-for-read 'binary)
373            (coding-system-for-write 'binary)
374            (ports
375             (cond
376              ((memq nnimap-stream '(network plain starttls))
377               (nnheader-message 7 "Opening connection to %s..."
378                                 nnimap-address)
379               '("imap" "143"))
380              ((eq nnimap-stream 'shell)
381               (nnheader-message 7 "Opening connection to %s via shell..."
382                                 nnimap-address)
383               '("imap"))
384              ((memq nnimap-stream '(ssl tls))
385               (nnheader-message 7 "Opening connection to %s via tls..."
386                                 nnimap-address)
387               '("imaps" "imap" "993" "143"))
388              (t
389               (error "Unknown stream type: %s" nnimap-stream))))
390            login-result credentials)
391       (when nnimap-server-port
392         (push nnimap-server-port ports))
393       (let* ((stream-list
394               (open-protocol-stream
395                "*nnimap*" (current-buffer) nnimap-address
396                (nnimap-map-port (car ports))
397                :type nnimap-stream
398                :return-list t
399                :shell-command nnimap-shell-program
400                :capability-command "1 CAPABILITY\r\n"
401                :end-of-command "\r\n"
402                :success " OK "
403                :starttls-function
404                (lambda (capabilities)
405                  (when (gnus-string-match-p "STARTTLS" capabilities)
406                    "1 STARTTLS\r\n"))))
407              (stream (car stream-list))
408              (props (cdr stream-list))
409              (greeting (plist-get props :greeting))
410              (capabilities (plist-get props :capabilities))
411              (stream-type (plist-get props :type)))
412         (when (and stream (not (memq (process-status stream) '(open run))))
413           (setq stream nil))
414
415         (when (and (fboundp 'set-network-process-option) ;; Not in XEmacs.
416                    (fboundp 'process-type) ;; Emacs 22 doesn't provide it.
417                    (eq (process-type stream) 'network))
418           ;; Use TCP-keepalive so that connections that pass through a NAT
419           ;; router don't hang when left idle.
420           (set-network-process-option stream :keepalive t))
421
422         (setf (nnimap-process nnimap-object) stream)
423         (setf (nnimap-stream-type nnimap-object) stream-type)
424         (if (not stream)
425             (progn
426               (nnheader-report 'nnimap "Unable to contact %s:%s via %s"
427                                nnimap-address (car ports) nnimap-stream)
428               'no-connect)
429           (gnus-set-process-query-on-exit-flag stream nil)
430           (if (not (gnus-string-match-p "[*.] \\(OK\\|PREAUTH\\)" greeting))
431               (nnheader-report 'nnimap "%s" greeting)
432             ;; Store the greeting (for debugging purposes).
433             (setf (nnimap-greeting nnimap-object) greeting)
434             (setf (nnimap-capabilities nnimap-object)
435                   (mapcar #'upcase
436                           (split-string capabilities)))
437             (unless (gnus-string-match-p "[*.] PREAUTH" greeting)
438               (if (not (setq credentials
439                              (if (eq nnimap-authenticator 'anonymous)
440                                  (list "anonymous"
441                                        (message-make-address))
442                                ;; Look for the credentials based on
443                                ;; the virtual server name and the address
444                                (nnimap-credentials
445                                 (gnus-delete-duplicates
446                                  (list
447                                   nnimap-address
448                                   (nnoo-current-server 'nnimap)))
449                                 ports
450                                 nnimap-user))))
451                   (setq nnimap-object nil)
452                 (let ((nnimap-inhibit-logging t))
453                   (setq login-result
454                         (nnimap-login (car credentials) (cadr credentials))))
455                 (if (car login-result)
456                     (progn
457                       ;; Save the credentials if a save function exists
458                       ;; (such a function will only be passed if a new
459                       ;; token was created).
460                       (when (functionp (nth 2 credentials))
461                         (funcall (nth 2 credentials)))
462                       ;; See if CAPABILITY is set as part of login
463                       ;; response.
464                       (dolist (response (cddr login-result))
465                         (when (string= "CAPABILITY" (upcase (car response)))
466                           (setf (nnimap-capabilities nnimap-object)
467                                 (mapcar #'upcase (cdr response))))))
468                   ;; If the login failed, then forget the credentials
469                   ;; that are now possibly cached.
470                   (dolist (host (list (nnoo-current-server 'nnimap)
471                                       nnimap-address))
472                     (dolist (port ports)
473                       (auth-source-forget+ :host host :port port)))
474                   (delete-process (nnimap-process nnimap-object))
475                   (setq nnimap-object nil))))
476             (when nnimap-object
477               (when (nnimap-capability "QRESYNC")
478                 (nnimap-command "ENABLE QRESYNC"))
479               (nnimap-process nnimap-object))))))))
480
481 (autoload 'rfc2104-hash "rfc2104")
482
483 (defun nnimap-login (user password)
484   (cond
485    ;; Prefer plain LOGIN if it's enabled (since it requires fewer
486    ;; round trips than CRAM-MD5, and it's less likely to be buggy),
487    ;; and we're using an encrypted connection.
488    ((and (not (nnimap-capability "LOGINDISABLED"))
489          (eq (nnimap-stream-type nnimap-object) 'tls))
490     (nnimap-command "LOGIN %S %S" user password))
491    ((nnimap-capability "AUTH=CRAM-MD5")
492     (erase-buffer)
493     (let ((sequence (nnimap-send-command "AUTHENTICATE CRAM-MD5"))
494           (challenge (nnimap-wait-for-line "^\\+\\(.*\\)\n")))
495       (process-send-string
496        (get-buffer-process (current-buffer))
497        (concat
498         (base64-encode-string
499          (concat user " "
500                  (rfc2104-hash 'md5 64 16 password
501                                (base64-decode-string challenge))))
502         "\r\n"))
503       (nnimap-wait-for-response sequence)))
504    ((not (nnimap-capability "LOGINDISABLED"))
505     (nnimap-command "LOGIN %S %S" user password))
506    ((nnimap-capability "AUTH=PLAIN")
507     (nnimap-command
508      "AUTHENTICATE PLAIN %s"
509      (base64-encode-string
510       (format "\000%s\000%s"
511               (nnimap-quote-specials user)
512               (nnimap-quote-specials password)))))))
513
514 (defun nnimap-quote-specials (string)
515   (with-temp-buffer
516     (insert string)
517     (goto-char (point-min))
518     (while (re-search-forward "[\\\"]" nil t)
519       (forward-char -1)
520       (insert "\\")
521       (forward-char 1))
522     (buffer-string)))
523
524 (defun nnimap-find-parameter (parameter elems)
525   (let (result)
526     (dolist (elem elems)
527       (cond
528        ((equal (car elem) parameter)
529         (setq result (cdr elem)))
530        ((and (equal (car elem) "OK")
531              (consp (cadr elem))
532              (equal (caadr elem) parameter))
533         (setq result (cdr (cadr elem))))))
534     result))
535
536 (deffoo nnimap-close-server (&optional server)
537   (when (nnoo-change-server 'nnimap server nil)
538     (ignore-errors
539       (delete-process (get-buffer-process (nnimap-buffer))))
540     (nnoo-close-server 'nnimap server)
541     t))
542
543 (deffoo nnimap-request-close ()
544   t)
545
546 (deffoo nnimap-server-opened (&optional server)
547   (and (nnoo-current-server-p 'nnimap server)
548        nntp-server-buffer
549        (gnus-buffer-live-p nntp-server-buffer)
550        (nnimap-find-connection nntp-server-buffer)))
551
552 (deffoo nnimap-status-message (&optional server)
553   nnimap-status-string)
554
555 (deffoo nnimap-request-article (article &optional group server to-buffer)
556   (when group
557     (setq group (nnimap-decode-gnus-group group)))
558   (with-current-buffer nntp-server-buffer
559     (let ((result (nnimap-possibly-change-group group server))
560           parts structure)
561       (when (stringp article)
562         (setq article (nnimap-find-article-by-message-id group article)))
563       (when (and result
564                  article)
565         (erase-buffer)
566         (with-current-buffer (nnimap-buffer)
567           (erase-buffer)
568           (when nnimap-fetch-partial-articles
569             (nnimap-command "UID FETCH %d (BODYSTRUCTURE)" article)
570             (goto-char (point-min))
571             (when (re-search-forward "FETCH.*BODYSTRUCTURE" nil t)
572               (setq structure (ignore-errors
573                                 (let ((start (point)))
574                                   (forward-sexp 1)
575                                   (downcase-region start (point))
576                                   (goto-char start)
577                                   (read (current-buffer))))
578                     parts (nnimap-find-wanted-parts structure))))
579           (when (if parts
580                     (nnimap-get-partial-article article parts structure)
581                   (nnimap-get-whole-article article))
582             (let ((buffer (current-buffer)))
583               (with-current-buffer (or to-buffer nntp-server-buffer)
584                 (nnheader-insert-buffer-substring buffer)
585                 (nnheader-ms-strip-cr)))
586             (cons group article)))))))
587
588 (deffoo nnimap-request-head (article &optional group server to-buffer)
589   (when group
590     (setq group (nnimap-decode-gnus-group group)))
591   (when (nnimap-possibly-change-group group server)
592     (with-current-buffer (nnimap-buffer)
593       (when (stringp article)
594         (setq article (nnimap-find-article-by-message-id group article)))
595       (if (null article)
596           nil
597         (nnimap-get-whole-article
598          article (format "UID FETCH %%d %s"
599                          (nnimap-header-parameters)))
600         (let ((buffer (current-buffer)))
601           (with-current-buffer (or to-buffer nntp-server-buffer)
602             (erase-buffer)
603             (insert-buffer-substring buffer)
604             (nnheader-ms-strip-cr)
605             (cons group article)))))))
606
607 (defun nnimap-get-whole-article (article &optional command)
608   (let ((result
609          (nnimap-command
610           (or command
611               (if (nnimap-ver4-p)
612                   "UID FETCH %d BODY.PEEK[]"
613                 "UID FETCH %d RFC822.PEEK"))
614           article)))
615     ;; Check that we really got an article.
616     (goto-char (point-min))
617     (unless (re-search-forward "\\* [0-9]+ FETCH" nil t)
618       (setq result nil))
619     (when result
620       ;; Remove any data that may have arrived before the FETCH data.
621       (beginning-of-line)
622       (unless (bobp)
623         (delete-region (point-min) (point)))
624       (let ((bytes (nnimap-get-length)))
625         (delete-region (line-beginning-position)
626                        (progn (forward-line 1) (point)))
627         (goto-char (+ (point) bytes))
628         (delete-region (point) (point-max)))
629       t)))
630
631 (defun nnimap-capability (capability)
632   (member capability (nnimap-capabilities nnimap-object)))
633
634 (defun nnimap-ver4-p ()
635   (nnimap-capability "IMAP4REV1"))
636
637 (defun nnimap-get-partial-article (article parts structure)
638   (let ((result
639          (nnimap-command
640           "UID FETCH %d (%s %s)"
641           article
642           (if (nnimap-ver4-p)
643               "BODY.PEEK[HEADER]"
644             "RFC822.HEADER")
645           (if (nnimap-ver4-p)
646               (mapconcat (lambda (part)
647                            (format "BODY.PEEK[%s]" part))
648                          parts " ")
649             (mapconcat (lambda (part)
650                          (format "RFC822.PEEK[%s]" part))
651                        parts " ")))))
652     (when result
653       (nnimap-convert-partial-article structure))))
654
655 (defun nnimap-convert-partial-article (structure)
656   ;; First just skip past the headers.
657   (goto-char (point-min))
658   (let ((bytes (nnimap-get-length))
659         id parts)
660     ;; Delete "FETCH" line.
661     (delete-region (line-beginning-position)
662                    (progn (forward-line 1) (point)))
663     (goto-char (+ (point) bytes))
664     ;; Collect all the body parts.
665     (while (looking-at ".*BODY\\[\\([.0-9]+\\)\\]")
666       (setq id (match-string 1)
667             bytes (or (nnimap-get-length) 0))
668       (beginning-of-line)
669       (delete-region (point) (progn (forward-line 1) (point)))
670       (push (list id (buffer-substring (point) (+ (point) bytes)))
671             parts)
672       (delete-region (point) (+ (point) bytes)))
673     ;; Delete trailing junk.
674     (delete-region (point) (point-max))
675     ;; Now insert all the parts again where they fit in the structure.
676     (nnimap-insert-partial-structure structure parts)
677     t))
678
679 (defun nnimap-insert-partial-structure (structure parts &optional subp)
680   (let (type boundary)
681     (let ((bstruc structure))
682       (while (consp (car bstruc))
683         (pop bstruc))
684       (setq type (car bstruc))
685       (setq bstruc (car (cdr bstruc)))
686       (let ((has-boundary (member "boundary" bstruc)))
687         (when has-boundary
688           (setq boundary (cadr has-boundary)))))
689     (when subp
690       (insert (format "Content-type: multipart/%s; boundary=%S\n\n"
691                       (downcase type) boundary)))
692     (while (not (stringp (car structure)))
693       (insert "\n--" boundary "\n")
694       (if (consp (caar structure))
695           (nnimap-insert-partial-structure (pop structure) parts t)
696         (let ((bit (pop structure)))
697           (insert (format "Content-type: %s/%s"
698                           (downcase (nth 0 bit))
699                           (downcase (nth 1 bit))))
700           (if (member-ignore-case "CHARSET" (nth 2 bit))
701               (insert (format
702                        "; charset=%S\n"
703                        (cadr (member-ignore-case "CHARSET" (nth 2 bit)))))
704             (insert "\n"))
705           (insert (format "Content-transfer-encoding: %s\n"
706                           (nth 5 bit)))
707           (insert "\n")
708           (when (assoc (nth 9 bit) parts)
709             (insert (cadr (assoc (nth 9 bit) parts)))))))
710     (insert "\n--" boundary "--\n")))
711
712 (defun nnimap-find-wanted-parts (structure)
713   (message-flatten-list (nnimap-find-wanted-parts-1 structure "")))
714
715 (defun nnimap-find-wanted-parts-1 (structure prefix)
716   (let ((num 1)
717         parts)
718     (while (consp (car structure))
719       (let ((sub (pop structure)))
720         (if (consp (car sub))
721             (push (nnimap-find-wanted-parts-1
722                    sub (if (string= prefix "")
723                            (number-to-string num)
724                          (format "%s.%s" prefix num)))
725                   parts)
726           (let ((type (format "%s/%s" (nth 0 sub) (nth 1 sub)))
727                 (id (if (string= prefix "")
728                         (number-to-string num)
729                       (format "%s.%s" prefix num))))
730             (setcar (nthcdr 9 sub) id)
731             (when (if (eq nnimap-fetch-partial-articles t)
732                       (equal id "1")
733                     (string-match nnimap-fetch-partial-articles type))
734               (push id parts))))
735         (incf num)))
736     (nreverse parts)))
737
738 (defun nnimap-decode-gnus-group (group)
739   (decode-coding-string group 'utf-8))
740
741 (deffoo nnimap-request-group (group &optional server dont-check info)
742   (setq group (nnimap-decode-gnus-group group))
743   (let ((result (nnimap-possibly-change-group
744                  ;; Don't SELECT the group if we're going to select it
745                  ;; later, anyway.
746                  (if (and (not dont-check)
747                           (assoc group nnimap-current-infos))
748                      nil
749                    group)
750                  server))
751         articles active marks high low)
752     (with-current-buffer nntp-server-buffer
753       (when result
754         (if (and dont-check
755                  (setq active (nth 2 (assoc group nnimap-current-infos))))
756             (insert (format "211 %d %d %d %S\n"
757                             (- (cdr active) (car active))
758                             (car active)
759                             (cdr active)
760                             group))
761           (with-current-buffer (nnimap-buffer)
762             (erase-buffer)
763             (let ((group-sequence
764                    (nnimap-send-command "SELECT %S" (utf7-encode group t)))
765                   (flag-sequence
766                    (nnimap-send-command "UID FETCH 1:* FLAGS")))
767               (setf (nnimap-group nnimap-object) group)
768               (nnimap-wait-for-response flag-sequence)
769               (setq marks
770                     (nnimap-flags-to-marks
771                      (nnimap-parse-flags
772                       (list (list group-sequence flag-sequence
773                                   1 group "SELECT")))))
774               (when (and info
775                          marks)
776                 (nnimap-update-infos marks (list info))
777                 (nnimap-store-info info (gnus-active (gnus-info-group info))))
778               (goto-char (point-max))
779               (let ((uidnext (nth 5 (car marks))))
780                 (setq high (or (if uidnext
781                                    (1- uidnext)
782                                  (nth 3 (car marks)))
783                                0)
784                       low (or (nth 4 (car marks)) uidnext 1)))))
785           (erase-buffer)
786           (insert
787            (format
788             "211 %d %d %d %S\n" (1+ (- high low)) low high group)))
789         t))))
790
791 (deffoo nnimap-request-create-group (group &optional server args)
792   (setq group (nnimap-decode-gnus-group group))
793   (when (nnimap-possibly-change-group nil server)
794     (with-current-buffer (nnimap-buffer)
795       (car (nnimap-command "CREATE %S" (utf7-encode group t))))))
796
797 (deffoo nnimap-request-delete-group (group &optional force server)
798   (setq group (nnimap-decode-gnus-group group))
799   (when (nnimap-possibly-change-group nil server)
800     (with-current-buffer (nnimap-buffer)
801       (car (nnimap-command "DELETE %S" (utf7-encode group t))))))
802
803 (deffoo nnimap-request-rename-group (group new-name &optional server)
804   (setq group (nnimap-decode-gnus-group group))
805   (when (nnimap-possibly-change-group nil server)
806     (with-current-buffer (nnimap-buffer)
807       (nnimap-unselect-group)
808       (car (nnimap-command "RENAME %S %S"
809                            (utf7-encode group t) (utf7-encode new-name t))))))
810
811 (defun nnimap-unselect-group ()
812   ;; Make sure we don't have this group open read/write by asking
813   ;; to examine a mailbox that doesn't exist.  This seems to be
814   ;; the only way that allows us to reliably go back to unselected
815   ;; state on Courier.
816   (nnimap-command "EXAMINE DOES.NOT.EXIST"))
817
818 (deffoo nnimap-request-expunge-group (group &optional server)
819   (setq group (nnimap-decode-gnus-group group))
820   (when (nnimap-possibly-change-group group server)
821     (with-current-buffer (nnimap-buffer)
822       (car (nnimap-command "EXPUNGE")))))
823
824 (defun nnimap-get-flags (spec)
825   (let ((articles nil)
826         elems end)
827     (with-current-buffer (nnimap-buffer)
828       (erase-buffer)
829       (nnimap-wait-for-response (nnimap-send-command
830                                  "UID FETCH %s FLAGS" spec))
831       (setq end (point))
832       (subst-char-in-region (point-min) (point-max)
833                             ?\\ ?% t)
834       (goto-char (point-min))
835       (while (search-forward " FETCH " end t)
836         (setq elems (read (current-buffer)))
837         (push (cons (cadr (memq 'UID elems))
838                     (cadr (memq 'FLAGS elems)))
839               articles)))
840     (nreverse articles)))
841
842 (deffoo nnimap-close-group (group &optional server)
843   t)
844
845 (deffoo nnimap-request-move-article (article group server accept-form
846                                              &optional last internal-move-group)
847   (setq group (nnimap-decode-gnus-group group))
848   (with-temp-buffer
849     (mm-disable-multibyte)
850     (when (funcall (if internal-move-group
851                        'nnimap-request-head
852                      'nnimap-request-article)
853                    article group server (current-buffer))
854       ;; If the move is internal (on the same server), just do it the easy
855       ;; way.
856       (let ((message-id (message-field-value "message-id")))
857         (if internal-move-group
858             (let ((result
859                    (with-current-buffer (nnimap-buffer)
860                      (nnimap-command "UID COPY %d %S"
861                                      article
862                                      (utf7-encode internal-move-group t)))))
863               (when (car result)
864                 (nnimap-delete-article article)
865                 (cons internal-move-group
866                       (or (nnimap-find-uid-response "COPYUID" (cadr result))
867                           (nnimap-find-article-by-message-id
868                            internal-move-group message-id)))))
869           ;; Move the article to a different method.
870           (let ((result (eval accept-form)))
871             (when result
872               (nnimap-possibly-change-group group server)
873               (nnimap-delete-article article)
874               result)))))))
875
876 (deffoo nnimap-request-expire-articles (articles group &optional server force)
877   (setq group (nnimap-decode-gnus-group group))
878   (cond
879    ((null articles)
880     nil)
881    ((not (nnimap-possibly-change-group group server))
882     articles)
883    ((and force
884          (eq nnmail-expiry-target 'delete))
885     (unless (nnimap-delete-article (gnus-compress-sequence articles))
886       (nnheader-message 7 "Article marked for deletion, but not expunged."))
887     nil)
888    (t
889     (let ((deletable-articles
890            (if (or force
891                    (eq nnmail-expiry-wait 'immediate))
892                articles
893              (gnus-sorted-intersection
894               articles
895               (nnimap-find-expired-articles group)))))
896       (if (null deletable-articles)
897           articles
898         (if (eq nnmail-expiry-target 'delete)
899             (nnimap-delete-article (gnus-compress-sequence deletable-articles))
900           (setq deletable-articles
901                 (nnimap-process-expiry-targets
902                  deletable-articles group server)))
903         ;; Return the articles we didn't delete.
904         (gnus-sorted-complement articles deletable-articles))))))
905
906 (defun nnimap-process-expiry-targets (articles group server)
907   (let ((deleted-articles nil))
908     (cond
909      ;; shortcut further processing if we're going to delete the articles
910      ((eq nnmail-expiry-target 'delete)
911       (setq deleted-articles articles)
912       t)
913      ;; or just move them to another folder on the same IMAP server
914      ((and (not (functionp nnmail-expiry-target))
915            (gnus-server-equal (gnus-group-method nnmail-expiry-target)
916                               (gnus-server-to-method
917                                (format "nnimap:%s" server))))
918       (and (nnimap-possibly-change-group group server)
919            (with-current-buffer (nnimap-buffer)
920              (nnheader-message 7 "Expiring articles from %s: %s" group articles)
921              (nnimap-command
922               "UID COPY %s %S"
923               (nnimap-article-ranges (gnus-compress-sequence articles))
924               (utf7-encode (gnus-group-real-name nnmail-expiry-target) t))
925              (setq deleted-articles articles)))
926       t)
927      (t
928       (dolist (article articles)
929         (let ((target nnmail-expiry-target))
930           (with-temp-buffer
931             (mm-disable-multibyte)
932             (when (nnimap-request-article article group server (current-buffer))
933               (when (functionp target)
934                 (setq target (funcall target group)))
935               (if (and target
936                        (not (eq target 'delete)))
937                   (if (or (gnus-request-group target t)
938                           (gnus-request-create-group target))
939                       (progn
940                         (nnmail-expiry-target-group target group)
941                         (nnheader-message 7 "Expiring article %s:%d to %s"
942                                           group article target))
943                     (setq target nil))
944                 (nnheader-message 7 "Expiring article %s:%d" group article))
945               (when target
946                 (push article deleted-articles))))))))
947     ;; Change back to the current group again.
948     (nnimap-possibly-change-group group server)
949     (setq deleted-articles (nreverse deleted-articles))
950     (nnimap-delete-article (gnus-compress-sequence deleted-articles))
951     deleted-articles))
952
953 (defun nnimap-find-expired-articles (group)
954   (let ((cutoff (nnmail-expired-article-p group nil nil)))
955     (with-current-buffer (nnimap-buffer)
956       (let ((result
957              (nnimap-command
958               "UID SEARCH SENTBEFORE %s"
959               (format-time-string
960                (format "%%d-%s-%%Y"
961                        (upcase
962                         (car (rassoc (nth 4 (decode-time cutoff))
963                                      parse-time-months))))
964                cutoff))))
965         (and (car result)
966              (delete 0 (mapcar #'string-to-number
967                                (cdr (assoc "SEARCH" (cdr result))))))))))
968
969
970 (defun nnimap-find-article-by-message-id (group message-id)
971   (with-current-buffer (nnimap-buffer)
972     (erase-buffer)
973     (unless (equal group (nnimap-group nnimap-object))
974       (setf (nnimap-group nnimap-object) nil)
975       (setf (nnimap-examined nnimap-object) group)
976       (nnimap-send-command "EXAMINE %S" (utf7-encode group t)))
977     (let ((sequence
978            (nnimap-send-command "UID SEARCH HEADER Message-Id %S" message-id))
979           article result)
980       (setq result (nnimap-wait-for-response sequence))
981       (when (and result
982                  (car (setq result (nnimap-parse-response))))
983         ;; Select the last instance of the message in the group.
984         (and (setq article
985                    (car (last (cdr (assoc "SEARCH" (cdr result))))))
986              (string-to-number article))))))
987
988 (defun nnimap-delete-article (articles)
989   (with-current-buffer (nnimap-buffer)
990     (nnimap-command "UID STORE %s +FLAGS.SILENT (\\Deleted)"
991                     (nnimap-article-ranges articles))
992     (cond
993      ((nnimap-capability "UIDPLUS")
994       (nnimap-command "UID EXPUNGE %s"
995                       (nnimap-article-ranges articles))
996       t)
997      (nnimap-expunge
998       (nnimap-command "EXPUNGE")
999       t)
1000      (t (gnus-message 7 (concat "nnimap: nnimap-expunge is not set and the "
1001                                 "server doesn't support UIDPLUS, so we won't "
1002                                 "delete this article now"))))))
1003
1004 (deffoo nnimap-request-scan (&optional group server)
1005   (when group
1006     (setq group (nnimap-decode-gnus-group group)))
1007   (when (and (nnimap-possibly-change-group nil server)
1008              nnimap-inbox
1009              nnimap-split-methods)
1010     (nnheader-message 7 "nnimap %s splitting mail..." server)
1011     (if (listp nnimap-inbox)
1012        (dolist (nnimap-inbox nnimap-inbox)
1013          (nnimap-split-incoming-mail))
1014       (nnimap-split-incoming-mail))
1015     (nnheader-message 7 "nnimap %s splitting mail...done" server)))
1016
1017 (defun nnimap-marks-to-flags (marks)
1018   (let (flags flag)
1019     (dolist (mark marks)
1020       (when (setq flag (cadr (assq mark nnimap-mark-alist)))
1021         (push flag flags)))
1022     flags))
1023
1024 (deffoo nnimap-request-update-group-status (group status &optional server)
1025   (setq group (nnimap-decode-gnus-group group))
1026   (when (nnimap-possibly-change-group nil server)
1027     (let ((command (assoc
1028                     status
1029                     '((subscribe "SUBSCRIBE")
1030                       (unsubscribe "UNSUBSCRIBE")))))
1031       (when command
1032         (with-current-buffer (nnimap-buffer)
1033           (nnimap-command "%s %S" (cadr command) (utf7-encode group t)))))))
1034
1035 (deffoo nnimap-request-set-mark (group actions &optional server)
1036   (setq group (nnimap-decode-gnus-group group))
1037   (when (nnimap-possibly-change-group group server)
1038     (let (sequence)
1039       (with-current-buffer (nnimap-buffer)
1040         (erase-buffer)
1041         ;; Just send all the STORE commands without waiting for
1042         ;; response.  If they're successful, they're successful.
1043         (dolist (action actions)
1044           (destructuring-bind (range action marks) action
1045             (let ((flags (nnimap-marks-to-flags marks)))
1046               (when flags
1047                 (setq sequence (nnimap-send-command
1048                                 "UID STORE %s %sFLAGS.SILENT (%s)"
1049                                 (nnimap-article-ranges range)
1050                                 (cond
1051                                  ((eq action 'del) "-")
1052                                  ((eq action 'add) "+")
1053                                  ((eq action 'set) ""))
1054                                 (mapconcat #'identity flags " ")))))))
1055         ;; Wait for the last command to complete to avoid later
1056         ;; synchronization problems with the stream.
1057         (when sequence
1058           (nnimap-wait-for-response sequence))))))
1059
1060 (deffoo nnimap-request-accept-article (group &optional server last)
1061   (setq group (nnimap-decode-gnus-group group))
1062   (when (nnimap-possibly-change-group nil server)
1063     (nnmail-check-syntax)
1064     (let ((message-id (message-field-value "message-id"))
1065           sequence message)
1066       (nnimap-add-cr)
1067       (setq message (buffer-substring-no-properties (point-min) (point-max)))
1068       (with-current-buffer (nnimap-buffer)
1069         (when (setq message (or (nnimap-process-quirk "OK Gimap " 'append message)
1070                                 message))
1071           ;; If we have this group open read-only, then unselect it
1072           ;; before appending to it.
1073           (when (equal (nnimap-examined nnimap-object) group)
1074             (nnimap-unselect-group))
1075           (erase-buffer)
1076           (setq sequence (nnimap-send-command
1077                           "APPEND %S {%d}" (utf7-encode group t)
1078                           (length message)))
1079           (unless nnimap-streaming
1080             (nnimap-wait-for-connection "^[+]"))
1081           (process-send-string (get-buffer-process (current-buffer)) message)
1082           (process-send-string (get-buffer-process (current-buffer))
1083                                (if (nnimap-newlinep nnimap-object)
1084                                    "\n"
1085                                  "\r\n"))
1086           (let ((result (nnimap-get-response sequence)))
1087             (if (not (nnimap-ok-p result))
1088                 (progn
1089                   (nnheader-report 'nnimap "%s" result)
1090                   nil)
1091               (cons group
1092                     (or (nnimap-find-uid-response "APPENDUID" (car result))
1093                         (nnimap-find-article-by-message-id
1094                          group message-id))))))))))
1095
1096 (defun nnimap-process-quirk (greeting-match type data)
1097   (when (and (nnimap-greeting nnimap-object)
1098              (string-match greeting-match (nnimap-greeting nnimap-object))
1099              (eq type 'append)
1100              (string-match "\000" data))
1101     (let ((choice (gnus-multiple-choice
1102                    "Message contains NUL characters.  Delete, continue, abort? "
1103                    '((?d "Delete NUL characters")
1104                      (?c "Try to APPEND the message as is")
1105                      (?a "Abort")))))
1106       (cond
1107        ((eq choice ?a)
1108         (nnheader-report 'nnimap "Aborted APPEND due to NUL characters"))
1109        ((eq choice ?c)
1110         data)
1111        (t
1112         (with-temp-buffer
1113           (insert data)
1114           (goto-char (point-min))
1115           (while (search-forward "\000" nil t)
1116             (replace-match "" t t))
1117           (buffer-string)))))))
1118
1119 (defun nnimap-ok-p (value)
1120   (and (consp value)
1121        (consp (car value))
1122        (equal (caar value) "OK")))
1123
1124 (defun nnimap-find-uid-response (name list)
1125   (let ((result (car (last (nnimap-find-response-element name list)))))
1126     (and result
1127          (string-to-number result))))
1128
1129 (defun nnimap-find-response-element (name list)
1130   (let (result)
1131     (dolist (elem list)
1132       (when (and (consp elem)
1133                  (equal name (car elem)))
1134         (setq result elem)))
1135     result))
1136
1137 (deffoo nnimap-request-replace-article (article group buffer)
1138   (setq group (nnimap-decode-gnus-group group))
1139   (let (group-art)
1140     (when (and (nnimap-possibly-change-group group nil)
1141                ;; Put the article into the group.
1142                (with-current-buffer buffer
1143                  (setq group-art
1144                        (nnimap-request-accept-article group nil t))))
1145       (nnimap-delete-article (list article))
1146       ;; Return the new article number.
1147       (cdr group-art))))
1148
1149 (defun nnimap-add-cr ()
1150   (goto-char (point-min))
1151   (while (re-search-forward "\r?\n" nil t)
1152     (replace-match "\r\n" t t)))
1153
1154 (defun nnimap-get-groups ()
1155   (erase-buffer)
1156   (let ((sequence (nnimap-send-command "LIST \"\" \"*\""))
1157         groups)
1158     (nnimap-wait-for-response sequence)
1159     (subst-char-in-region (point-min) (point-max)
1160                           ?\\ ?% t)
1161     (goto-char (point-min))
1162     (nnimap-unfold-quoted-lines)
1163     (goto-char (point-min))
1164     (while (search-forward "* LIST " nil t)
1165       (let ((flags (read (current-buffer)))
1166             (separator (read (current-buffer)))
1167             (group (read (current-buffer))))
1168         (unless (member '%NoSelect flags)
1169           (push (utf7-decode (if (stringp group)
1170                                  group
1171                                (format "%s" group)) t)
1172                 groups))))
1173     (nreverse groups)))
1174
1175 (deffoo nnimap-request-list (&optional server)
1176   (when (nnimap-possibly-change-group nil server)
1177     (with-current-buffer nntp-server-buffer
1178       (erase-buffer)
1179       (let ((groups
1180              (with-current-buffer (nnimap-buffer)
1181                (nnimap-get-groups)))
1182             sequences responses)
1183         (when groups
1184           (with-current-buffer (nnimap-buffer)
1185             (setf (nnimap-group nnimap-object) nil)
1186             (dolist (group groups)
1187               (setf (nnimap-examined nnimap-object) group)
1188               (push (list (nnimap-send-command "EXAMINE %S"
1189                                                (utf7-encode group t))
1190                           group)
1191                     sequences))
1192             (nnimap-wait-for-response (caar sequences))
1193             (setq responses
1194                   (nnimap-get-responses (mapcar #'car sequences))))
1195           (dolist (response responses)
1196             (let* ((sequence (car response))
1197                    (response (cadr response))
1198                    (group (cadr (assoc sequence sequences)))
1199                    (egroup (encode-coding-string group 'utf-8)))
1200               (when (and group
1201                          (equal (caar response) "OK"))
1202                 (let ((uidnext (nnimap-find-parameter "UIDNEXT" response))
1203                       highest exists)
1204                   (dolist (elem response)
1205                     (when (equal (cadr elem) "EXISTS")
1206                       (setq exists (string-to-number (car elem)))))
1207                   (when uidnext
1208                     (setq highest (1- (string-to-number (car uidnext)))))
1209                   (cond
1210                    ((null highest)
1211                     (insert (format "%S 0 1 y\n" egroup)))
1212                    ((zerop exists)
1213                     ;; Empty group.
1214                     (insert (format "%S %d %d y\n" egroup
1215                                     highest (1+ highest))))
1216                    (t
1217                     ;; Return the widest possible range.
1218                     (insert (format "%S %d 1 y\n" egroup
1219                                     (or highest exists)))))))))
1220           t)))))
1221
1222 (deffoo nnimap-request-newgroups (date &optional server)
1223   (when (nnimap-possibly-change-group nil server)
1224     (with-current-buffer nntp-server-buffer
1225       (erase-buffer)
1226       (dolist (group (with-current-buffer (nnimap-buffer)
1227                        (nnimap-get-groups)))
1228         (unless (assoc group nnimap-current-infos)
1229           ;; Insert dummy numbers here -- they don't matter.
1230           (insert (format "%S 0 1 y\n" (encode-coding-string group 'utf-8)))))
1231       t)))
1232
1233 (deffoo nnimap-retrieve-group-data-early (server infos)
1234   (when (and (nnimap-possibly-change-group nil server)
1235              infos)
1236     (with-current-buffer (nnimap-buffer)
1237       (erase-buffer)
1238       (setf (nnimap-group nnimap-object) nil)
1239       (setf (nnimap-initial-resync nnimap-object) 0)
1240       (let ((qresyncp (nnimap-capability "QRESYNC"))
1241             params groups sequences active uidvalidity modseq group
1242             unexist)
1243         ;; Go through the infos and gather the data needed to know
1244         ;; what and how to request the data.
1245         (dolist (info infos)
1246           (setq params (gnus-info-params info)
1247                 group (nnimap-decode-gnus-group
1248                        (gnus-group-real-name (gnus-info-group info)))
1249                 active (cdr (assq 'active params))
1250                 unexist (assq 'unexist (gnus-info-marks info))
1251                 uidvalidity (cdr (assq 'uidvalidity params))
1252                 modseq (cdr (assq 'modseq params)))
1253           (setf (nnimap-examined nnimap-object) group)
1254           (if (and qresyncp
1255                    uidvalidity
1256                    active
1257                    modseq
1258                    unexist)
1259               (push
1260                (list (nnimap-send-command "EXAMINE %S (%s (%s %s))"
1261                                           (utf7-encode group t)
1262                                           (nnimap-quirk "QRESYNC")
1263                                           uidvalidity modseq)
1264                      'qresync
1265                      nil group 'qresync)
1266                sequences)
1267             (let ((command
1268                    (if uidvalidity
1269                        "EXAMINE"
1270                      ;; If we don't have a UIDVALIDITY, then this is
1271                      ;; the first time we've seen the group, so we
1272                      ;; have to do a SELECT (which is slower than an
1273                      ;; examine), but will tell us whether the group
1274                      ;; is read-only or not.
1275                      "SELECT"))
1276                   start)
1277               (if (and active uidvalidity unexist)
1278                   ;; Fetch the last 100 flags.
1279                   (setq start (max 1 (- (cdr active) 100)))
1280                 (incf (nnimap-initial-resync nnimap-object))
1281                 (setq start 1))
1282               (push (list (nnimap-send-command "%s %S" command
1283                                                (utf7-encode group t))
1284                           (nnimap-send-command "UID FETCH %d:* FLAGS" start)
1285                           start group command)
1286                     sequences))))
1287         sequences))))
1288
1289 (defun nnimap-quirk (command)
1290   (let ((quirk (assoc command nnimap-quirks)))
1291     ;; If this server is of a type that matches a quirk, then return
1292     ;; the "quirked" command instead of the proper one.
1293     (if (or (null quirk)
1294             (not (string-match (nth 1 quirk) (nnimap-greeting nnimap-object))))
1295         command
1296       (nth 2 quirk))))
1297
1298 (deffoo nnimap-finish-retrieve-group-infos (server infos sequences)
1299   (when (and sequences
1300              (nnimap-possibly-change-group nil server t)
1301              ;; Check that the process is still alive.
1302              (get-buffer-process (nnimap-buffer))
1303              (memq (process-status (get-buffer-process (nnimap-buffer)))
1304                    '(open run)))
1305     (with-current-buffer (nnimap-buffer)
1306       ;; Wait for the final data to trickle in.
1307       (when (nnimap-wait-for-response (if (eq (cadar sequences) 'qresync)
1308                                           (caar sequences)
1309                                         (cadar sequences))
1310                                       t)
1311         ;; Now we should have most of the data we need, no matter
1312         ;; whether we're QRESYNCING, fetching all the flags from
1313         ;; scratch, or just fetching the last 100 flags per group.
1314         (nnimap-update-infos (nnimap-flags-to-marks
1315                               (nnimap-parse-flags
1316                                (nreverse sequences)))
1317                              infos)
1318         ;; Finally, just return something resembling an active file in
1319         ;; the nntp buffer, so that the agent can save the info, too.
1320         (with-current-buffer nntp-server-buffer
1321           (erase-buffer)
1322           (dolist (info infos)
1323             (let* ((group (gnus-info-group info))
1324                    (active (gnus-active group)))
1325               (when active
1326                 (insert (format "%S %d %d y\n"
1327                                 (decode-coding-string
1328                                  (gnus-group-real-name group) 'utf-8)
1329                                 (cdr active)
1330                                 (car active)))))))))))
1331
1332 (defun nnimap-update-infos (flags infos)
1333   (dolist (info infos)
1334     (let* ((group (nnimap-decode-gnus-group
1335                    (gnus-group-real-name (gnus-info-group info))))
1336            (marks (cdr (assoc group flags))))
1337       (when marks
1338         (nnimap-update-info info marks)))))
1339
1340 (defun nnimap-update-info (info marks)
1341   (destructuring-bind (existing flags high low uidnext start-article
1342                                 permanent-flags uidvalidity
1343                                 vanished highestmodseq) marks
1344     (cond
1345      ;; Ignore groups with no UIDNEXT/marks.  This happens for
1346      ;; completely empty groups.
1347      ((and (not existing)
1348            (not uidnext))
1349       (let ((active (cdr (assq 'active (gnus-info-params info)))))
1350         (when active
1351           (gnus-set-active (gnus-info-group info) active))))
1352      ;; We have a mismatch between the old and new UIDVALIDITY
1353      ;; identifiers, so we have to re-request the group info (the next
1354      ;; time).  This virtually never happens.
1355      ((let ((old-uidvalidity
1356              (cdr (assq 'uidvalidity (gnus-info-params info)))))
1357         (and old-uidvalidity
1358              (not (equal old-uidvalidity uidvalidity))
1359              (or (not start-article)
1360                  (> start-article 1))))
1361       (gnus-group-remove-parameter info 'uidvalidity)
1362       (gnus-group-remove-parameter info 'modseq))
1363      ;; We have the data needed to update.
1364      (t
1365       (let* ((group (gnus-info-group info))
1366              (completep (and start-article
1367                              (= start-article 1)))
1368              (active (or (gnus-active group)
1369                          (cdr (assq 'active (gnus-info-params info))))))
1370         (when uidnext
1371           (setq high (1- uidnext)))
1372         ;; First set the active ranges based on high/low.
1373         (if (or completep
1374                 (not (gnus-active group)))
1375             (gnus-set-active group
1376                              (cond
1377                               (active
1378                                (cons (min (or low (car active))
1379                                           (car active))
1380                                      (max (or high (cdr active))
1381                                           (cdr active))))
1382                               ((and low high)
1383                                (cons low high))
1384                               (uidnext
1385                                ;; No articles in this group.
1386                                (cons uidnext (1- uidnext)))
1387                               (start-article
1388                                (cons start-article (1- start-article)))
1389                               (t
1390                                ;; No articles and no uidnext.
1391                                nil)))
1392           (gnus-set-active group
1393                            (cons (car active)
1394                                  (or high (1- uidnext)))))
1395         ;; See whether this is a read-only group.
1396         (unless (eq permanent-flags 'not-scanned)
1397           (gnus-group-set-parameter
1398            info 'permanent-flags
1399            (and (or (memq '%* permanent-flags)
1400                     (memq '%Seen permanent-flags))
1401                 permanent-flags)))
1402         ;; Update marks and read articles if this isn't a
1403         ;; read-only IMAP group.
1404         (when (setq permanent-flags
1405                     (cdr (assq 'permanent-flags (gnus-info-params info))))
1406           (if (and highestmodseq
1407                    (not start-article))
1408               ;; We've gotten the data by QRESYNCing.
1409               (nnimap-update-qresync-info
1410                info existing (nnimap-imap-ranges-to-gnus-ranges vanished) flags)
1411             ;; Do normal non-QRESYNC flag updates.
1412             ;; Update the list of read articles.
1413             (let* ((unread
1414                     (gnus-compress-sequence
1415                      (gnus-set-difference
1416                       (gnus-set-difference
1417                        existing
1418                        (cdr (assoc '%Seen flags)))
1419                       (cdr (assoc '%Flagged flags)))))
1420                    (read (gnus-range-difference
1421                           (cons start-article high) unread)))
1422               (when (> start-article 1)
1423                 (setq read
1424                       (gnus-range-nconcat
1425                        (if (> start-article 1)
1426                            (gnus-sorted-range-intersection
1427                             (cons 1 (1- start-article))
1428                             (gnus-info-read info))
1429                          (gnus-info-read info))
1430                        read)))
1431               (when (or (not (listp permanent-flags))
1432                         (memq '%Seen permanent-flags))
1433                 (gnus-info-set-read info read))
1434               ;; Update the marks.
1435               (setq marks (gnus-info-marks info))
1436               (dolist (type (cdr nnimap-mark-alist))
1437                 (when (or (not (listp permanent-flags))
1438                           (memq (car (assoc (caddr type) flags))
1439                                 permanent-flags)
1440                           (memq '%* permanent-flags))
1441                   (let ((old-marks (assoc (car type) marks))
1442                         (new-marks
1443                          (gnus-compress-sequence
1444                           (cdr (or (assoc (caddr type) flags) ; %Flagged
1445                                    (assoc (intern (cadr type) obarray) flags)
1446                                    (assoc (cadr type) flags)))))) ; "\Flagged"
1447                     (setq marks (delq old-marks marks))
1448                     (pop old-marks)
1449                     (when (and old-marks
1450                                (> start-article 1))
1451                       (setq old-marks (gnus-range-difference
1452                                        old-marks
1453                                        (cons start-article high)))
1454                       (setq new-marks (gnus-range-nconcat old-marks new-marks)))
1455                     (when new-marks
1456                       (push (cons (car type) new-marks) marks)))))
1457               ;; Keep track of non-existing articles.
1458               (let* ((old-unexists (assq 'unexist marks))
1459                      (active (gnus-active group))
1460                      (unexists
1461                       (if completep
1462                           (gnus-range-difference
1463                            active
1464                            (gnus-compress-sequence existing))
1465                         (gnus-add-to-range
1466                          (cdr old-unexists)
1467                          (gnus-list-range-difference
1468                           existing (gnus-active group))))))
1469                 (when (> (car active) 1)
1470                   (setq unexists (gnus-range-add
1471                                   (cons 1 (1- (car active)))
1472                                   unexists)))
1473                 (if old-unexists
1474                     (setcdr old-unexists unexists)
1475                   (push (cons 'unexist unexists) marks)))
1476               (gnus-info-set-marks info marks t))))
1477         ;; Tell Gnus whether there are any \Recent messages in any of
1478         ;; the groups.
1479         (let ((recent (cdr (assoc '%Recent flags))))
1480           (when (and active
1481                      recent
1482                      (> (car (last recent)) (cdr active)))
1483             (push (list (cons (gnus-group-real-name group) 0))
1484                   nnmail-split-history)))
1485         ;; Note the active level for the next run-through.
1486         (gnus-group-set-parameter info 'active (gnus-active group))
1487         (gnus-group-set-parameter info 'uidvalidity uidvalidity)
1488         (gnus-group-set-parameter info 'modseq highestmodseq)
1489         (nnimap-store-info info (gnus-active group)))))))
1490
1491 (defun nnimap-update-qresync-info (info existing vanished flags)
1492   ;; Add all the vanished articles to the list of read articles.
1493   (gnus-info-set-read
1494    info
1495    (gnus-add-to-range
1496     (gnus-add-to-range
1497      (gnus-range-add (gnus-info-read info)
1498                      vanished)
1499      (cdr (assq '%Flagged flags)))
1500     (cdr (assq '%Seen flags))))
1501   (let ((marks (gnus-info-marks info)))
1502     (dolist (type (cdr nnimap-mark-alist))
1503       (let ((ticks (assoc (car type) marks))
1504             (new-marks
1505              (cdr (or (assoc (caddr type) flags) ; %Flagged
1506                       (assoc (intern (cadr type) obarray) flags)
1507                       (assoc (cadr type) flags))))) ; "\Flagged"
1508         (setq marks (delq ticks marks))
1509         (pop ticks)
1510         ;; Add the new marks we got.
1511         (setq ticks (gnus-add-to-range ticks new-marks))
1512         ;; Remove the marks from messages that don't have them.
1513         (setq ticks (gnus-remove-from-range
1514                      ticks
1515                      (gnus-compress-sequence
1516                       (gnus-sorted-complement existing new-marks))))
1517         (when ticks
1518           (push (cons (car type) ticks) marks)))
1519       (gnus-info-set-marks info marks t))
1520     ;; Add vanished to the list of unexisting articles.
1521     (when vanished
1522       (let* ((old-unexists (assq 'unexist marks))
1523              (unexists (gnus-range-add (cdr old-unexists) vanished)))
1524         (if old-unexists
1525             (setcdr old-unexists unexists)
1526           (push (cons 'unexist unexists) marks)))
1527       (gnus-info-set-marks info marks t))))
1528
1529 (defun nnimap-imap-ranges-to-gnus-ranges (irange)
1530   (if (zerop (length irange))
1531       nil
1532     (let ((result nil))
1533       (dolist (elem (split-string irange ","))
1534         (push
1535          (if (string-match ":" elem)
1536              (let ((numbers (split-string elem ":")))
1537                (cons (string-to-number (car numbers))
1538                      (string-to-number (cadr numbers))))
1539            (string-to-number elem))
1540          result))
1541       (nreverse result))))
1542
1543 (defun nnimap-store-info (info active)
1544   (let* ((group (gnus-group-real-name (gnus-info-group info)))
1545          (entry (assoc group nnimap-current-infos)))
1546     (if entry
1547         (setcdr entry (list info active))
1548       (push (list group info active) nnimap-current-infos))))
1549
1550 (defun nnimap-flags-to-marks (groups)
1551   (let (data group totalp uidnext articles start-article mark permanent-flags
1552              uidvalidity vanished highestmodseq)
1553     (dolist (elem groups)
1554       (setq group (car elem)
1555             uidnext (nth 1 elem)
1556             start-article (nth 2 elem)
1557             permanent-flags (nth 3 elem)
1558             uidvalidity (nth 4 elem)
1559             vanished (nth 5 elem)
1560             highestmodseq (nth 6 elem)
1561             articles (nthcdr 7 elem))
1562       (let ((high (caar articles))
1563             marks low existing)
1564         (dolist (article articles)
1565           (setq low (car article))
1566           (push (car article) existing)
1567           (dolist (flag (cdr article))
1568             (setq mark (assoc flag marks))
1569             (if (not mark)
1570                 (push (list flag (car article)) marks)
1571               (setcdr mark (cons (car article) (cdr mark))))))
1572         (push (list group existing marks high low uidnext start-article
1573                     permanent-flags uidvalidity vanished highestmodseq)
1574               data)))
1575     data))
1576
1577 (defun nnimap-parse-flags (sequences)
1578   (goto-char (point-min))
1579   ;; Change \Delete etc to %Delete, so that the Emacs Lisp reader can
1580   ;; read it.
1581   (subst-char-in-region (point-min) (point-max)
1582                         ?\\ ?% t)
1583   ;; Remove any MODSEQ entries in the buffer, because they may contain
1584   ;; numbers that are too large for 32-bit Emacsen.
1585   (while (re-search-forward " MODSEQ ([0-9]+)" nil t)
1586     (replace-match "" t t))
1587   (goto-char (point-min))
1588   (let (start end articles groups uidnext elems permanent-flags
1589               uidvalidity vanished highestmodseq)
1590     (dolist (elem sequences)
1591       (destructuring-bind (group-sequence flag-sequence totalp group command)
1592           elem
1593         (setq start (point))
1594         (when (and
1595                ;; The EXAMINE was successful.
1596                (search-forward (format "\n%d OK " group-sequence) nil t)
1597                (progn
1598                  (forward-line 1)
1599                  (setq end (point))
1600                  (goto-char start)
1601                  (setq permanent-flags
1602                        (if (equal command "SELECT")
1603                            (and (search-forward "PERMANENTFLAGS "
1604                                                 (or end (point-min)) t)
1605                                 (read (current-buffer)))
1606                          'not-scanned))
1607                  (goto-char start)
1608                  (setq uidnext
1609                        (and (search-forward "UIDNEXT "
1610                                             (or end (point-min)) t)
1611                             (read (current-buffer))))
1612                  (goto-char start)
1613                  (setq uidvalidity
1614                        (and (re-search-forward "UIDVALIDITY \\([0-9]+\\)"
1615                                                (or end (point-min)) t)
1616                             ;; Store UIDVALIDITY as a string, as it's
1617                             ;; too big for 32-bit Emacsen, usually.
1618                             (match-string 1)))
1619                  (goto-char start)
1620                  (setq vanished
1621                        (and (eq flag-sequence 'qresync)
1622                             (re-search-forward "^\\* VANISHED .*? \\([0-9:,]+\\)"
1623                                                (or end (point-min)) t)
1624                             (match-string 1)))
1625                  (goto-char start)
1626                  (setq highestmodseq
1627                        (and (re-search-forward "HIGHESTMODSEQ \\([0-9]+\\)"
1628                                             (or end (point-min)) t)
1629                             (match-string 1)))
1630                  (goto-char end)
1631                  (forward-line -1))
1632                ;; The UID FETCH FLAGS was successful.
1633                (or (eq flag-sequence 'qresync)
1634                    (search-forward (format "\n%d OK " flag-sequence) nil t)))
1635           (if (eq flag-sequence 'qresync)
1636               (progn
1637                 (goto-char start)
1638                 (setq start end))
1639             (setq start (point))
1640             (goto-char end))
1641           (while (re-search-forward "^\\* [0-9]+ FETCH " start t)
1642             (let ((p (point)))
1643               (setq elems (read (current-buffer)))
1644               (push (cons (cadr (memq 'UID elems))
1645                           (cadr (memq 'FLAGS elems)))
1646                     articles)))
1647           (push (nconc (list group uidnext totalp permanent-flags uidvalidity
1648                              vanished highestmodseq)
1649                        articles)
1650                 groups)
1651           (if (eq flag-sequence 'qresync)
1652               (goto-char end)
1653             (setq end (point)))
1654           (setq articles nil))))
1655     groups))
1656
1657 (defun nnimap-find-process-buffer (buffer)
1658   (cadr (assoc buffer nnimap-connection-alist)))
1659
1660 (deffoo nnimap-request-post (&optional server)
1661   (setq nnimap-status-string "Read-only server")
1662   nil)
1663
1664 (defvar gnus-refer-thread-use-nnir) ;; gnus-sum.el
1665 (declare-function gnus-fetch-headers "gnus-sum"
1666                   (articles &optional limit force-new dependencies))
1667
1668 (autoload 'nnir-search-thread "nnir")
1669
1670 (deffoo nnimap-request-thread (header &optional group server)
1671   (when group
1672     (setq group (nnimap-decode-gnus-group group)))
1673   (if gnus-refer-thread-use-nnir
1674       (nnir-search-thread header)
1675     (when (nnimap-possibly-change-group group server)
1676       (let* ((cmd (nnimap-make-thread-query header))
1677              (result (with-current-buffer (nnimap-buffer)
1678                        (nnimap-command  "UID SEARCH %s" cmd))))
1679         (when result
1680           (gnus-fetch-headers
1681            (and (car result)
1682                 (delete 0 (mapcar #'string-to-number
1683                                   (cdr (assoc "SEARCH" (cdr result))))))
1684            nil t))))))
1685
1686 (defun nnimap-possibly-change-group (group server &optional no-reconnect)
1687   (let ((open-result t))
1688     (when (and server
1689                (not (nnimap-server-opened server)))
1690       (setq open-result (nnimap-open-server server nil no-reconnect)))
1691     (cond
1692      ((not open-result)
1693       nil)
1694      ((not group)
1695       t)
1696      (t
1697       (with-current-buffer (nnimap-buffer)
1698         (if (equal group (nnimap-group nnimap-object))
1699             t
1700           (let ((result (nnimap-command "SELECT %S" (utf7-encode group t))))
1701             (when (car result)
1702               (setf (nnimap-group nnimap-object) group
1703                     (nnimap-select-result nnimap-object) result)
1704               result))))))))
1705
1706 (defun nnimap-find-connection (buffer)
1707   "Find the connection delivering to BUFFER."
1708   (let ((entry (assoc buffer nnimap-connection-alist)))
1709     (when entry
1710       (if (and (buffer-name (cadr entry))
1711                (get-buffer-process (cadr entry))
1712                (memq (process-status (get-buffer-process (cadr entry)))
1713                      '(open run)))
1714           (get-buffer-process (cadr entry))
1715         (setq nnimap-connection-alist (delq entry nnimap-connection-alist))
1716         nil))))
1717
1718 (defvar nnimap-sequence 0)
1719
1720 (defun nnimap-send-command (&rest args)
1721   (setf (nnimap-last-command-time nnimap-object) (current-time))
1722   (process-send-string
1723    (get-buffer-process (current-buffer))
1724    (nnimap-log-command
1725     (format "%d %s%s\n"
1726             (incf nnimap-sequence)
1727             (apply #'format args)
1728             (if (nnimap-newlinep nnimap-object)
1729                 ""
1730               "\r"))))
1731   ;; Some servers apparently can't have many outstanding
1732   ;; commands, so throttle them.
1733   (unless nnimap-streaming
1734     (nnimap-wait-for-response nnimap-sequence))
1735   nnimap-sequence)
1736
1737 (defvar nnimap-record-commands nil
1738   "If non-nil, log commands to the \"*imap log*\" buffer.")
1739
1740 (defun nnimap-log-command (command)
1741   (when nnimap-record-commands
1742     (with-current-buffer (get-buffer-create "*imap log*")
1743       (goto-char (point-max))
1744       (insert (format-time-string "%H:%M:%S")
1745               " [" nnimap-address "] "
1746               (if nnimap-inhibit-logging
1747                   "(inhibited)\n"
1748                 command))))
1749   command)
1750
1751 (defun nnimap-command (&rest args)
1752   (erase-buffer)
1753   (let* ((sequence (apply #'nnimap-send-command args))
1754          (response (nnimap-get-response sequence)))
1755     (if (equal (caar response) "OK")
1756         (cons t response)
1757       (nnheader-report 'nnimap "%s"
1758                        (mapconcat (lambda (a)
1759                                     (format "%s" a))
1760                                   (car response) " "))
1761       nil)))
1762
1763 (defun nnimap-get-response (sequence)
1764   (nnimap-wait-for-response sequence)
1765   (nnimap-parse-response))
1766
1767 (defun nnimap-wait-for-connection (&optional regexp)
1768   (nnimap-wait-for-line (or regexp "^[*.] .*\n") "[*.] \\([A-Z0-9]+\\)"))
1769
1770 (defun nnimap-wait-for-line (regexp &optional response-regexp)
1771   (let ((process (get-buffer-process (current-buffer))))
1772     (goto-char (point-min))
1773     (while (and (memq (process-status process)
1774                       '(open run))
1775                 (not (re-search-forward regexp nil t)))
1776       (nnheader-accept-process-output process)
1777       (goto-char (point-min)))
1778     (forward-line -1)
1779     (and (looking-at (or response-regexp regexp))
1780          (match-string 1))))
1781
1782 (defun nnimap-wait-for-response (sequence &optional messagep)
1783   (let ((process (get-buffer-process (current-buffer)))
1784         openp)
1785     (condition-case nil
1786         (progn
1787           (goto-char (point-max))
1788           (while (and (setq openp (memq (process-status process)
1789                                         '(open run)))
1790                       (progn
1791                         ;; Skip past any "*" lines that the server has
1792                         ;; output.
1793                         (while (and (not (bobp))
1794                                     (progn
1795                                       (forward-line -1)
1796                                       (looking-at "\\*"))))
1797                         (not (looking-at (format "%d .*\n" sequence)))))
1798             (when messagep
1799               (nnheader-message-maybe
1800                7 "nnimap read %dk from %s%s" (/ (buffer-size) 1000)
1801                nnimap-address
1802                (if (not (zerop (nnimap-initial-resync nnimap-object)))
1803                    (format " (initial sync of %d group%s; please wait)"
1804                            (nnimap-initial-resync nnimap-object)
1805                            (if (= (nnimap-initial-resync nnimap-object) 1)
1806                                ""
1807                              "s"))
1808                  "")))
1809             (nnheader-accept-process-output process)
1810             (goto-char (point-max)))
1811           (setf (nnimap-initial-resync nnimap-object) 0)
1812           openp)
1813       (quit
1814        (when debug-on-quit
1815          (debug "Quit"))
1816        ;; The user hit C-g while we were waiting: kill the process, in case
1817        ;; it's a gnutls-cli process that's stuck (tends to happen a lot behind
1818        ;; NAT routers).
1819        (delete-process process)
1820        nil))))
1821
1822 (defun nnimap-parse-response ()
1823   (let ((lines (split-string (nnimap-last-response-string) "\r\n" t))
1824         result)
1825     (dolist (line lines)
1826       (push (cdr (nnimap-parse-line line)) result))
1827     ;; Return the OK/error code first, and then all the "continuation
1828     ;; lines" afterwards.
1829     (cons (pop result)
1830           (nreverse result))))
1831
1832 ;; Parse an IMAP response line lightly.  They look like
1833 ;; "* OK [UIDVALIDITY 1164213559] UIDs valid", typically, so parse
1834 ;; the lines into a list of strings and lists of string.
1835 (defun nnimap-parse-line (line)
1836   (let (char result)
1837     (with-temp-buffer
1838       (mm-disable-multibyte)
1839       (insert line)
1840       (goto-char (point-min))
1841       (while (not (eobp))
1842         (if (eql (setq char (following-char)) ? )
1843             (forward-char 1)
1844           (push
1845            (cond
1846             ((eql char ?\[)
1847              (split-string
1848               (buffer-substring
1849                (1+ (point))
1850                (if (search-forward "]" (line-end-position) 'move)
1851                    (1- (point))
1852                  (point)))))
1853             ((eql char ?\()
1854              (split-string
1855               (buffer-substring
1856                (1+ (point))
1857                (if (search-forward ")" (line-end-position) 'move)
1858                    (1- (point))
1859                  (point)))))
1860             ((eql char ?\")
1861              (forward-char 1)
1862              (buffer-substring
1863               (point)
1864               (1- (or (search-forward "\"" (line-end-position) 'move)
1865                       (point)))))
1866             (t
1867              (buffer-substring (point) (if (search-forward " " nil t)
1868                                            (1- (point))
1869                                          (goto-char (point-max))))))
1870            result)))
1871       (nreverse result))))
1872
1873 (defun nnimap-last-response-string ()
1874   (save-excursion
1875     (forward-line 1)
1876     (let ((end (point)))
1877       (forward-line -1)
1878       (when (not (bobp))
1879         (forward-line -1)
1880         (while (and (not (bobp))
1881                     (eql (following-char) ?*))
1882           (forward-line -1))
1883         (unless (eql (following-char) ?*)
1884           (forward-line 1)))
1885       (buffer-substring (point) end))))
1886
1887 (defun nnimap-get-responses (sequences)
1888   (let (responses)
1889     (dolist (sequence sequences)
1890       (goto-char (point-min))
1891       (when (re-search-forward (format "^%d " sequence) nil t)
1892         (push (list sequence (nnimap-parse-response))
1893               responses)))
1894     responses))
1895
1896 (defvar nnimap-incoming-split-list nil)
1897
1898 (defun nnimap-fetch-inbox (articles)
1899   (erase-buffer)
1900   (nnimap-wait-for-response
1901    (nnimap-send-command
1902     "UID FETCH %s %s"
1903     (nnimap-article-ranges articles)
1904     (format "(UID %s%s)"
1905             (format
1906              (if (nnimap-ver4-p)
1907                  "BODY.PEEK"
1908                "RFC822.PEEK"))
1909             (cond
1910              (nnimap-split-download-body-default
1911               "[]")
1912              ((nnimap-ver4-p)
1913               "[HEADER]")
1914              (t
1915               "[1]"))))
1916    t))
1917
1918 (defun nnimap-split-incoming-mail ()
1919   (with-current-buffer (nnimap-buffer)
1920     (let ((nnimap-incoming-split-list nil)
1921           (nnmail-split-methods
1922            (cond
1923             ((eq nnimap-split-methods 'default)
1924              nnmail-split-methods)
1925             (nnimap-split-methods
1926              nnimap-split-methods)
1927             (nnimap-split-fancy
1928              'nnmail-split-fancy)))
1929           (nnmail-split-fancy (or nnimap-split-fancy
1930                                   nnmail-split-fancy))
1931           (nnmail-inhibit-default-split-group t)
1932           (groups (nnimap-get-groups))
1933           new-articles)
1934       (erase-buffer)
1935       (nnimap-command "SELECT %S" nnimap-inbox)
1936       (setf (nnimap-group nnimap-object) nnimap-inbox)
1937       (setq new-articles (nnimap-new-articles (nnimap-get-flags "1:*")))
1938       (when new-articles
1939         (nnimap-fetch-inbox new-articles)
1940         (nnimap-transform-split-mail)
1941         (nnheader-ms-strip-cr)
1942         (nnmail-cache-open)
1943         (nnmail-split-incoming (current-buffer)
1944                                #'nnimap-save-mail-spec
1945                                nil nil
1946                                #'nnimap-dummy-active-number
1947                                #'nnimap-save-mail-spec)
1948         (when nnimap-incoming-split-list
1949           (let ((specs (nnimap-make-split-specs nnimap-incoming-split-list))
1950                 sequences junk-articles)
1951             ;; Create any groups that doesn't already exist on the
1952             ;; server first.
1953             (dolist (spec specs)
1954               (when (and (not (member (car spec) groups))
1955                          (not (eq (car spec) 'junk)))
1956                 (nnimap-command "CREATE %S" (utf7-encode (car spec) t))))
1957             ;; Then copy over all the messages.
1958             (erase-buffer)
1959             (dolist (spec specs)
1960               (let ((group (car spec))
1961                     (ranges (cdr spec)))
1962                 (if (eq group 'junk)
1963                     (setq junk-articles ranges)
1964                   (push (list (nnimap-send-command
1965                                "UID COPY %s %S"
1966                                (nnimap-article-ranges ranges)
1967                                (utf7-encode group t))
1968                               ranges)
1969                         sequences))))
1970             ;; Wait for the last COPY response...
1971             (when sequences
1972               (nnimap-wait-for-response (caar sequences))
1973               ;; And then mark the successful copy actions as deleted,
1974               ;; and possibly expunge them.
1975               (nnimap-mark-and-expunge-incoming
1976                (nnimap-parse-copied-articles sequences)))
1977             (nnimap-mark-and-expunge-incoming junk-articles)))))))
1978
1979 (defun nnimap-mark-and-expunge-incoming (range)
1980   (when range
1981     (setq range (nnimap-article-ranges range))
1982     (erase-buffer)
1983     (let ((sequence
1984            (nnimap-send-command
1985             "UID STORE %s +FLAGS.SILENT (\\Deleted)" range)))
1986       (cond
1987        ;; If the server supports it, we now delete the message we have
1988        ;; just copied over.
1989        ((nnimap-capability "UIDPLUS")
1990         (setq sequence (nnimap-send-command "UID EXPUNGE %s" range)))
1991        ;; If it doesn't support UID EXPUNGE, then we only expunge if the
1992        ;; user has configured it.
1993        (nnimap-expunge
1994         (setq sequence (nnimap-send-command "EXPUNGE"))))
1995       (nnimap-wait-for-response sequence))))
1996
1997 (defun nnimap-parse-copied-articles (sequences)
1998   (let (sequence copied range)
1999     (goto-char (point-min))
2000     (while (re-search-forward "^\\([0-9]+\\) OK\\b" nil t)
2001       (setq sequence (string-to-number (match-string 1)))
2002       (when (setq range (cadr (assq sequence sequences)))
2003         (push (gnus-uncompress-range range) copied)))
2004     (gnus-compress-sequence (sort (apply #'nconc copied) #'<))))
2005
2006 (defun nnimap-new-articles (flags)
2007   (let (new)
2008     (dolist (elem flags)
2009       (unless (gnus-list-memq-of-list nnimap-unsplittable-articles
2010                                       (cdr elem))
2011         (push (car elem) new)))
2012     (gnus-compress-sequence (nreverse new))))
2013
2014 (defun nnimap-make-split-specs (list)
2015   (let ((specs nil)
2016         entry)
2017     (dolist (elem list)
2018       (destructuring-bind (article spec) elem
2019         (dolist (group (delete nil (mapcar #'car spec)))
2020           (unless (setq entry (assoc group specs))
2021             (push (setq entry (list group)) specs))
2022           (setcdr entry (cons article (cdr entry))))))
2023     (dolist (entry specs)
2024       (setcdr entry (gnus-compress-sequence (sort (cdr entry) #'<))))
2025     specs))
2026
2027 (defun nnimap-transform-split-mail ()
2028   (goto-char (point-min))
2029   (let (article bytes)
2030     (block nil
2031       (while (not (eobp))
2032         (while (not (looking-at "\\* [0-9]+ FETCH.+UID \\([0-9]+\\)"))
2033           (delete-region (point) (progn (forward-line 1) (point)))
2034           (when (eobp)
2035             (return)))
2036         (setq article (match-string 1)
2037               bytes (nnimap-get-length))
2038         (delete-region (line-beginning-position) (line-end-position))
2039         ;; Insert MMDF separator, and a way to remember what this
2040         ;; article UID is.
2041         (insert (format "\^A\^A\^A\^A\n\nX-nnimap-article: %s" article))
2042         (forward-char (1+ bytes))
2043         (setq bytes (nnimap-get-length))
2044         (delete-region (line-beginning-position) (line-end-position))
2045         ;; There's a body; skip past that.
2046         (when bytes
2047           (forward-char (1+ bytes))
2048           (delete-region (line-beginning-position) (line-end-position)))))))
2049
2050 (defun nnimap-dummy-active-number (group &optional server)
2051   1)
2052
2053 (defun nnimap-save-mail-spec (group-art &optional server full-nov)
2054   (let (article)
2055     (goto-char (point-min))
2056     (if (not (re-search-forward "X-nnimap-article: \\([0-9]+\\)" nil t))
2057         (error "Invalid nnimap mail")
2058       (setq article (string-to-number (match-string 1))))
2059     (push (list article
2060                 (if (eq group-art 'junk)
2061                     (list (cons 'junk 1))
2062                   group-art))
2063           nnimap-incoming-split-list)))
2064
2065 (defun nnimap-make-thread-query (header)
2066   (let* ((id  (mail-header-id header))
2067          (refs (split-string
2068                 (or (mail-header-references header)
2069                     "")))
2070          (value
2071           (format
2072            "(OR HEADER REFERENCES %S HEADER Message-Id %S)"
2073            id id)))
2074     (dolist (refid refs value)
2075       (setq value (format
2076                    "(OR (OR HEADER Message-Id %S HEADER REFERENCES %S) %s)"
2077                    refid refid value)))))
2078
2079
2080 (provide 'nnimap)
2081
2082 ;;; nnimap.el ends here