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