(mm-coding-system-priorities): Protect against nil value
[gnus] / lisp / nnimap.el
1 ;;; nnimap.el --- imap backend for Gnus
2
3 ;; Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006,
4 ;;   2007, 2008, 2009  Free Software Foundation, Inc.
5
6 ;; Author: Simon Josefsson <simon@josefsson.org>
7 ;;         Jim Radford <radford@robby.caltech.edu>
8 ;; Keywords: mail
9
10 ;; This file is part of GNU Emacs.
11
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs.  If not, see <http://www.gnu.org/licenses/>.
24
25 ;;; Commentary:
26
27 ;; Todo, major things:
28 ;;
29 ;;   o Fix Gnus to view correct number of unread/total articles in group buffer
30 ;;   o Fix Gnus to handle leading '.' in group names (fixed?)
31 ;;   o Finish disconnected mode (moving articles between mailboxes unplugged)
32 ;;   o Sieve
33 ;;   o MIME (partial article fetches)
34 ;;   o Split to other backends, different split rules for different
35 ;;     servers/inboxes
36 ;;
37 ;; Todo, minor things:
38 ;;
39 ;;   o Don't require half of Gnus -- backends should be standalone
40 ;;   o Verify that we don't use IMAP4rev1 specific things (RFC2060 App B)
41 ;;   o Dont uid fetch 1,* in nnimap-retrive-groups (slow)
42 ;;   o Split up big fetches (1,* header especially) in smaller chunks
43 ;;   o What do I do with gnus-newsgroup-*?
44 ;;   o Tell Gnus about new groups (how can we tell?)
45 ;;   o Respooling (fix Gnus?) (unnecessary?)
46 ;;   o Add support for the following: (if applicable)
47 ;;       request-list-newsgroups, request-regenerate
48 ;;       list-active-group,
49 ;;       request-associate-buffer, request-restore-buffer,
50 ;;   o Do The Right Thing when UIDVALIDITY changes (what's the right thing?)
51 ;;   o Support RFC2221 (Login referrals)
52 ;;   o IMAP2BIS compatibility? (RFC2061)
53 ;;   o ACAP stuff (perhaps a different project, would be nice to ACAPify
54 ;;     .newsrc.eld)
55 ;;   o What about Gnus's article editing, can we support it?  NO!
56 ;;   o Use \Draft to support the draft group??
57 ;;   o Duplicate suppression
58 ;;   o Rewrite UID SEARCH UID X as UID FETCH X (UID) for those with slow servers
59
60 ;;; Code:
61
62 (require 'imap)
63 (require 'nnoo)
64 (require 'nnmail)
65 (require 'nnheader)
66 (require 'mm-util)
67 (require 'gnus)
68 (require 'gnus-range)
69 (require 'gnus-start)
70 (require 'gnus-int)
71
72 (eval-when-compile (require 'cl))
73
74 (autoload 'auth-source-user-or-password "auth-source")
75
76 (nnoo-declare nnimap)
77
78 (defconst nnimap-version "nnimap 1.0")
79
80 (defgroup nnimap nil
81   "Reading IMAP mail with Gnus."
82   :group 'gnus)
83
84 (defvoo nnimap-address nil
85   "Address of physical IMAP server.  If nil, use the virtual server's name.")
86
87 (defvoo nnimap-server-port nil
88   "Port number on physical IMAP server.
89 If nil, defaults to 993 for TLS/SSL connections and 143 otherwise.")
90
91 ;; Splitting variables
92
93 (defcustom nnimap-split-crosspost t
94   "If non-nil, do crossposting if several split methods match the mail.
95 If nil, the first match found will be used."
96   :group 'nnimap
97   :type 'boolean)
98
99 (defcustom nnimap-split-inbox nil
100   "Name of mailbox to split mail from.
101
102 Mail is read from this mailbox and split according to rules in
103 `nnimap-split-rule'.
104
105 This can be a string or a list of strings."
106   :group 'nnimap
107   :type '(choice (string)
108                  (repeat string)))
109
110 (define-widget 'nnimap-strict-function 'function
111   "This widget only matches values that are functionp.
112
113 Warning: This means that a value that is the symbol of a not yet
114 loaded function will not match.  Use with care."
115   :match 'nnimap-strict-function-match)
116
117 (defun nnimap-strict-function-match (widget value)
118   "Ignoring WIDGET, match if VALUE is a function."
119   (functionp value))
120
121 (defcustom nnimap-split-rule nil
122   "Mail will be split according to these rules.
123
124 Mail is read from mailbox(es) specified in `nnimap-split-inbox'.
125
126 If you'd like, for instance, one mail group for mail from the
127 \"gnus-imap\" mailing list, one group for junk mail and leave
128 everything else in the incoming mailbox, you could do something like
129 this:
130
131 \(setq nnimap-split-rule '((\"INBOX.gnus-imap\"   \"From:.*gnus-imap\")
132                           (\"INBOX.junk\"        \"Subject:.*buy\")))
133
134 As you can see, `nnimap-split-rule' is a list of lists, where the
135 first element in each \"rule\" is the name of the IMAP mailbox (or the
136 symbol `junk' if you want to remove the mail), and the second is a
137 regexp that nnimap will try to match on the header to find a fit.
138
139 The second element can also be a function.  In that case, it will be
140 called narrowed to the headers with the first element of the rule as
141 the argument.  It should return a non-nil value if it thinks that the
142 mail belongs in that group.
143
144 This variable can also have a function as its value, the function will
145 be called with the headers narrowed and should return a group where it
146 thinks the article should be splitted to.  See `nnimap-split-fancy'.
147
148 To allow for different split rules on different virtual servers, and
149 even different split rules in different inboxes on the same server,
150 the syntax of this variable have been extended along the lines of:
151
152 \(setq nnimap-split-rule
153       '((\"my1server\"    (\".*\"    ((\"ding\"    \"ding@gnus.org\")
154                                   (\"junk\"    \"From:.*Simon\")))
155         (\"my2server\"    (\"INBOX\" nnimap-split-fancy))
156         (\"my[34]server\" (\".*\"    ((\"private\" \"To:.*Simon\")
157                                   (\"junk\"    my-junk-func)))))
158
159 The virtual server name is in fact a regexp, so that the same rules
160 may apply to several servers.  In the example, the servers
161 \"my3server\" and \"my4server\" both use the same rules.  Similarly,
162 the inbox string is also a regexp.  The actual splitting rules are as
163 before, either a function, or a list with group/regexp or
164 group/function elements."
165   :group 'nnimap
166   ;; FIXME: Doesn't allow `("my2server" ("INBOX" nnimap-split-fancy))'
167   ;; per example above.  -- fx
168   :type '(choice :tag "Rule type"
169                  (repeat :menu-tag "Single-server"
170                          :tag "Single-server list"
171                          (list (string :tag "Mailbox")
172                                (choice :tag "Predicate"
173                                        (regexp :tag "A regexp")
174                                        (nnimap-strict-function :tag "A function"))))
175                  (choice :menu-tag "A function"
176                          :tag "A function"
177                          (function-item nnimap-split-fancy)
178                          (function-item nnmail-split-fancy)
179                          (nnimap-strict-function :tag "User-defined function"))
180                  (repeat :menu-tag "Multi-server (extended)"
181                          :tag "Multi-server list"
182                          (list (regexp :tag "Server regexp")
183                                (list (regexp :tag "Incoming Mailbox regexp")
184                                      (repeat :tag "Rules for matching server(s) and mailbox(es)"
185                                              (list (string :tag "Destination mailbox")
186                                                    (choice :tag "Predicate"
187                                                            (regexp :tag "A Regexp")
188                                                            (nnimap-strict-function :tag "A Function")))))))))
189
190 (defcustom nnimap-split-predicate "UNSEEN UNDELETED"
191   "The predicate used to find articles to split.
192 If you use another IMAP client to peek on articles but always would
193 like nnimap to split them once it's started, you could change this to
194 \"UNDELETED\". Other available predicates are available in
195 RFC2060 section 6.4.4."
196   :group 'nnimap
197   :type 'string)
198
199 (defcustom nnimap-split-fancy nil
200   "Like the variable `nnmail-split-fancy'."
201   :group 'nnimap
202   :type 'sexp)
203
204 (defvar nnimap-split-download-body-default nil
205   "Internal variable with default value for `nnimap-split-download-body'.")
206
207 (defcustom nnimap-split-download-body 'default
208   "Whether to download entire articles during splitting.
209 This is generally not required, and will slow things down considerably.
210 You may need it if you want to use an advanced splitting function that
211 analyzes the body before splitting the article.
212 If this variable is nil, bodies will not be downloaded; if this
213 variable is the symbol `default' the default behavior is
214 used (which currently is nil, unless you use a statistical
215 spam.el test); if this variable is another non-nil value bodies
216 will be downloaded."
217   :version "22.1"
218   :group 'nnimap
219   :type '(choice (const :tag "Let system decide" deault)
220                  boolean))
221
222 ;; Performance / bug workaround variables
223
224 (defcustom nnimap-close-asynchronous t
225   "Close mailboxes asynchronously in `nnimap-close-group'.
226 This means that errors caught by nnimap when closing the mailbox will
227 not prevent Gnus from updating the group status, which may be harmful.
228 However, it increases speed."
229   :version "22.1"
230   :type 'boolean
231   :group 'nnimap)
232
233 (defcustom nnimap-dont-close t
234   "Never close mailboxes.
235 This increases the speed of closing mailboxes (quiting group) but may
236 decrease the speed of selecting another mailbox later.  Re-selecting
237 the same mailbox will be faster though."
238   :version "22.1"
239   :type 'boolean
240   :group 'nnimap)
241
242 (defcustom nnimap-retrieve-groups-asynchronous t
243   "Send asynchronous STATUS commands for each mailbox before checking mail.
244 If you have mailboxes that rarely receives mail, this speeds up new
245 mail checking.  It works by first sending STATUS commands for each
246 mailbox, and then only checking groups which has a modified UIDNEXT
247 more carefully for new mail.
248
249 In summary, the default is O((1-p)*k+p*n) and changing it to nil makes
250 it O(n).  If p is small, then the default is probably faster."
251   :version "22.1"
252   :type 'boolean
253   :group 'nnimap)
254
255 (defvoo nnimap-need-unselect-to-notice-new-mail t
256   "Unselect mailboxes before looking for new mail in them.
257 Some servers seem to need this under some circumstances.")
258
259 (defvoo nnimap-logout-timeout nil
260   "Close server immediately if it can't logout in this number of seconds.
261 If it is nil, never close server until logout completes.  This variable
262 overrides `imap-logout-timeout' on a per-server basis.")
263
264 ;; Authorization / Privacy variables
265
266 (defvoo nnimap-auth-method nil
267   "Obsolete.")
268
269 (defvoo nnimap-stream nil
270   "How nnimap will connect to the server.
271
272 The default, nil, will try to use the \"best\" method the server can
273 handle.
274
275 Change this if
276
277 1) you want to connect with TLS/SSL.  The TLS/SSL integration
278    with IMAP is suboptimal so you'll have to tell it
279    specifically.
280
281 2) your server is more capable than your environment -- i.e. your
282    server accept Kerberos login's but you haven't installed the
283    `imtest' program or your machine isn't configured for Kerberos.
284
285 Possible choices: gssapi, kerberos4, starttls, tls, ssl, network, shell.
286 See also `imap-streams' and `imap-stream-alist'.")
287
288 (defvoo nnimap-authenticator nil
289   "How nnimap authenticate itself to the server.
290
291 The default, nil, will try to use the \"best\" method the server can
292 handle.
293
294 There is only one reason for fiddling with this variable, and that is
295 if your server is more capable than your environment -- i.e. you
296 connect to a server that accept Kerberos login's but you haven't
297 installed the `imtest' program or your machine isn't configured for
298 Kerberos.
299
300 Possible choices: gssapi, kerberos4, digest-md5, cram-md5, login, anonymous.
301 See also `imap-authenticators' and `imap-authenticator-alist'")
302
303 (defvoo nnimap-directory (nnheader-concat gnus-directory "overview/")
304   "Directory to keep NOV cache files for nnimap groups.
305 See also `nnimap-nov-file-name'.")
306
307 (defvoo nnimap-nov-file-name "nnimap."
308   "NOV cache base filename.
309 The group name and `nnimap-nov-file-name-suffix' will be appended.  A
310 typical complete file name would be
311 ~/News/overview/nnimap.pdc.INBOX.ding.nov, or
312 ~/News/overview/nnimap/pdc/INBOX/ding/nov if
313 `nnmail-use-long-file-names' is nil")
314
315 (defvoo nnimap-nov-file-name-suffix ".novcache"
316   "Suffix for NOV cache base filename.")
317
318 (defvoo nnimap-nov-is-evil gnus-agent
319   "If non-nil, never generate or use a local nov database for this backend.
320 Using nov databases should speed up header fetching considerably.
321 However, it will invoke a UID SEARCH UID command on the server, and
322 some servers implement this command inefficiently by opening each and
323 every message in the group, thus making it quite slow.
324 Unlike other backends, you do not need to take special care if you
325 flip this variable.")
326
327 (defvoo nnimap-search-uids-not-since-is-evil nil
328   "If non-nil, avoid \"UID SEARCH UID ... NOT SINCE\" queries when expiring.
329 Instead, use \"UID SEARCH SINCE\" to prune the list of expirable
330 articles within Gnus.  This seems to be faster on Courier in some cases.")
331
332 (defvoo nnimap-expunge-on-close 'always ; 'ask, 'never
333   "Whether to expunge a group when it is closed.
334 When a IMAP group with articles marked for deletion is closed, this
335 variable determine if nnimap should actually remove the articles or
336 not.
337
338 If always, nnimap always perform a expunge when closing the group.
339 If never, nnimap never expunges articles marked for deletion.
340 If ask, nnimap will ask you if you wish to expunge marked articles.
341
342 When setting this variable to `never', you can only expunge articles
343 by using `G x' (gnus-group-nnimap-expunge) from the Group buffer.")
344
345 (defvoo nnimap-list-pattern "*"
346   "A string LIMIT or list of strings with mailbox wildcards used to limit available groups.
347 See below for available wildcards.
348
349 The LIMIT string can be a cons cell (REFERENCE . LIMIT), where
350 REFERENCE will be passed as the first parameter to LIST/LSUB.  The
351 semantics of this are server specific, on the University of Washington
352 server you can specify a directory.
353
354 Example:
355  '(\"INBOX\" \"mail/*\" (\"~friend/mail/\" . \"list/*\"))
356
357 There are two wildcards * and %. * matches everything, % matches
358 everything in the current hierarchy.")
359
360 (defvoo nnimap-news-groups nil
361   "IMAP support a news-like mode, also known as bulletin board mode,
362 where replies is sent via IMAP instead of SMTP.
363
364 This variable should contain a regexp matching groups where you wish
365 replies to be stored to the mailbox directly.
366
367 Example:
368   '(\"^[^I][^N][^B][^O][^X].*$\")
369
370 This will match all groups not beginning with \"INBOX\".
371
372 Note that there is nothing technically different between mail-like and
373 news-like mailboxes.  If you wish to have a group with todo items or
374 similar which you wouldn't want to set up a mailing list for, you can
375 use this to make replies go directly to the group.")
376
377 (defvoo nnimap-expunge-search-string "UID %s NOT SINCE %s"
378   "IMAP search command to use for articles that are to be expired.
379 The first %s is replaced by a UID set of articles to search on,
380 and the second %s is replaced by a date criterium.
381
382 One useful (and perhaps the only useful) value to change this to would
383 be `UID %s NOT SENTSINCE %s' to make nnimap use the Date: header
384 instead of the internal date of messages.  See section 6.4.4 of RFC
385 2060 for more information on valid strings.
386
387 However, if `nnimap-search-uids-not-since-is-evil' is true, this
388 variable has no effect since the search logic is reversed.")
389
390 (defvoo nnimap-importantize-dormant t
391   "If non-nil, mark \"dormant\" articles as \"ticked\" for other IMAP clients.
392 Note that within Gnus, dormant articles will still (only) be
393 marked as ticked.  This is to make \"dormant\" articles stand out,
394 just like \"ticked\" articles, in other IMAP clients.")
395
396 (defvoo nnimap-server-address nil
397   "Obsolete.  Use `nnimap-address'.")
398
399 (defcustom nnimap-authinfo-file "~/.authinfo"
400   "Authorization information for IMAP servers.  In .netrc format."
401   :type
402   '(choice file
403            (repeat :tag "Entries"
404                    :menu-tag "Inline"
405                    (list :format "%v"
406                          :value ("" ("login" . "") ("password" . ""))
407                          (string :tag "Host")
408                          (checklist :inline t
409                                     (cons :format "%v"
410                                           (const :format "" "login")
411                                           (string :format "Login: %v"))
412                                     (cons :format "%v"
413                                           (const :format "" "password")
414                                           (string :format "Password: %v"))))))
415   :group 'nnimap)
416
417 (defcustom nnimap-prune-cache t
418   "If non-nil, nnimap check whether articles still exist on server before using data stored in NOV cache."
419   :type 'boolean
420   :group 'nnimap)
421
422 (defvar nnimap-request-list-method 'imap-mailbox-list
423   "Method to use to request a list of all folders from the server.
424 If this is 'imap-mailbox-lsub, then use a server-side subscription list to
425 restrict visible folders.")
426
427 (defcustom nnimap-id nil
428   "Plist with client identity to send to server upon login.
429 A nil value means no information is sent, symbol `no' to disable ID query
430 altogether, or plist with identifier-value pairs to send to
431 server.  RFC 2971 describes the list as follows:
432
433    Any string may be sent as a field, but the following are defined to
434    describe certain values that might be sent.  Implementations are free
435    to send none, any, or all of these.  Strings are not case-sensitive.
436    Field strings MUST NOT be longer than 30 octets.  Value strings MUST
437    NOT be longer than 1024 octets.  Implementations MUST NOT send more
438    than 30 field-value pairs.
439
440      name            Name of the program
441      version         Version number of the program
442      os              Name of the operating system
443      os-version      Version of the operating system
444      vendor          Vendor of the client/server
445      support-url     URL to contact for support
446      address         Postal address of contact/vendor
447      date            Date program was released, specified as a date-time
448                        in IMAP4rev1
449      command         Command used to start the program
450      arguments       Arguments supplied on the command line, if any
451                        if any
452      environment     Description of environment, i.e., UNIX environment
453                        variables or Windows registry settings
454
455    Implementations MUST NOT send the same field name more than once.
456
457 An example plist would be '(\"name\" \"Gnus\" \"version\" gnus-version-number
458 \"os\" system-configuration \"vendor\" \"GNU\")."
459   :group 'nnimap
460   :type '(choice (const :tag "No information" nil)
461                  (const :tag "Disable ID query" no)
462                  (plist :key-type string :value-type string)))
463
464 (defcustom nnimap-debug nil
465   "If non-nil, trace nnimap- functions into `nnimap-debug-buffer'.
466 Uses `trace-function-background', so you can turn it off with,
467 say, `untrace-all'.
468
469 Note that username, passwords and other privacy sensitive
470 information (such as e-mail) may be stored in the buffer.
471 It is not written to disk, however.  Do not enable this
472 variable unless you are comfortable with that.
473
474 This variable only takes effect when loading the `nnimap' library.
475 See also `nnimap-log'."
476   :group 'nnimap
477   :type 'boolean)
478
479 ;; Internal variables:
480
481 (defvar nnimap-debug-buffer "*nnimap-debug*")
482 (defvar nnimap-mailbox-info (gnus-make-hashtable 997))
483 (defvar nnimap-current-move-server nil)
484 (defvar nnimap-current-move-group nil)
485 (defvar nnimap-current-move-article nil)
486 (defvar nnimap-length)
487 (defvar nnimap-progress-chars '(?| ?/ ?- ?\\))
488 (defvar nnimap-progress-how-often 20)
489 (defvar nnimap-counter)
490 (defvar nnimap-server-buffer-alist nil) ;; Map server name to buffers.
491 (defvar nnimap-current-server nil) ;; Current server
492 (defvar nnimap-server-buffer nil) ;; Current servers' buffer
493
494 \f
495
496 (nnoo-define-basics nnimap)
497
498 ;; Utility functions:
499
500 (defsubst nnimap-get-server-buffer (server)
501   "Return buffer for SERVER, if nil use current server."
502   (cadr (assoc (or server nnimap-current-server) nnimap-server-buffer-alist)))
503
504 (defun nnimap-remove-server-from-buffer-alist (server list)
505   "Remove SERVER from LIST."
506   (let (l)
507     (dolist (e list)
508       (unless (equal server (car-safe e))
509         (push e l)))
510     l))
511
512 (defun nnimap-possibly-change-server (server)
513   "Return buffer for SERVER, changing the current server as a side-effect.
514 If SERVER is nil, uses the current server."
515   (setq nnimap-current-server (or server nnimap-current-server)
516         nnimap-server-buffer (nnimap-get-server-buffer nnimap-current-server)))
517
518 (defun nnimap-verify-uidvalidity (group server)
519   "Verify stored uidvalidity match current one in GROUP on SERVER."
520   (let* ((gnusgroup (gnus-group-prefixed-name
521                      group (gnus-server-to-method
522                             (format "nnimap:%s" server))))
523          (new-uidvalidity (imap-mailbox-get 'uidvalidity))
524          (old-uidvalidity (gnus-group-get-parameter gnusgroup 'uidvalidity))
525          (dir (file-name-as-directory (expand-file-name nnimap-directory)))
526          (nameuid (nnheader-translate-file-chars
527                    (concat nnimap-nov-file-name
528                            (if (equal server "")
529                                "unnamed"
530                              server) "." group "." old-uidvalidity
531                            nnimap-nov-file-name-suffix) t))
532          (file (if (or nnmail-use-long-file-names
533                        (file-exists-p (expand-file-name nameuid dir)))
534                    (expand-file-name nameuid dir)
535                  (expand-file-name
536                   (mm-encode-coding-string
537                    (nnheader-replace-chars-in-string nameuid ?. ?/)
538                    nnmail-pathname-coding-system)
539                   dir))))
540     (if old-uidvalidity
541         (if (not (equal old-uidvalidity new-uidvalidity))
542             ;; uidvalidity clash
543             (gnus-delete-file file)
544           (gnus-group-set-parameter gnusgroup 'uidvalidity new-uidvalidity)
545           t)
546       (gnus-group-add-parameter gnusgroup (cons 'uidvalidity new-uidvalidity))
547       t)))
548
549 (defun nnimap-before-find-minmax-bugworkaround ()
550   "Function called before iterating through mailboxes with
551 `nnimap-find-minmax-uid'."
552   (when nnimap-need-unselect-to-notice-new-mail
553     ;; XXX this is for UoW imapd problem, it doesn't notice new mail in
554     ;; currently selected mailbox without a re-select/examine.
555     (or (null (imap-current-mailbox nnimap-server-buffer))
556         (imap-mailbox-unselect nnimap-server-buffer))))
557
558 (defun nnimap-find-minmax-uid (group &optional examine)
559   "Find lowest and highest active article number in GROUP.
560 If EXAMINE is non-nil the group is selected read-only."
561   (with-current-buffer nnimap-server-buffer
562     (when (or (string= group (imap-current-mailbox))
563               (imap-mailbox-select group examine))
564       (let (minuid maxuid)
565         (when (> (imap-mailbox-get 'exists) 0)
566           (imap-fetch-safe '("1,*" . "1,*:*") "UID" nil 'nouidfetch)
567           (imap-message-map (lambda (uid Uid)
568                               (setq minuid (if minuid (min minuid uid) uid)
569                                     maxuid (if maxuid (max maxuid uid) uid)))
570                             'UID))
571         (list (imap-mailbox-get 'exists) minuid maxuid)))))
572
573 (defun nnimap-possibly-change-group (group &optional server)
574   "Make GROUP the current group, and SERVER the current server."
575   (when (nnimap-possibly-change-server server)
576     (with-current-buffer nnimap-server-buffer
577       (if (or (null group) (imap-current-mailbox-p group))
578           imap-current-mailbox
579         (if (imap-mailbox-select group)
580             (if (or (nnimap-verify-uidvalidity
581                      group (or server nnimap-current-server))
582                     (zerop (imap-mailbox-get 'exists group))
583                     t ;; for OGnus to see if ignoring uidvalidity
584                     ;; changes has any bad effects.
585                     (yes-or-no-p
586                      (format
587                       "nnimap: Group %s is not uidvalid.  Continue? " group)))
588                 imap-current-mailbox
589               (imap-mailbox-unselect)
590               (error "nnimap: Group %s is not uid-valid" group))
591           (nnheader-report 'nnimap (imap-error-text)))))))
592
593 (defun nnimap-replace-whitespace (string)
594   "Return STRING with all whitespace replaced with space."
595   (when string
596     (while (string-match "[\r\n\t]+" string)
597       (setq string (replace-match " " t t string)))
598     string))
599
600 ;; Required backend functions
601
602 (defun nnimap-retrieve-headers-progress ()
603   "Hook to insert NOV line for current article into `nntp-server-buffer'."
604   (and (numberp nnmail-large-newsgroup)
605        (zerop (% (incf nnimap-counter) nnimap-progress-how-often))
606        (> nnimap-length nnmail-large-newsgroup)
607        (nnheader-message 6 "nnimap: Retrieving headers... %c"
608                          (nth (/ (% nnimap-counter
609                                     (* (length nnimap-progress-chars)
610                                        nnimap-progress-how-often))
611                                  nnimap-progress-how-often)
612                               nnimap-progress-chars)))
613   (with-current-buffer nntp-server-buffer
614     (let (headers lines chars uid mbx)
615       (with-current-buffer nnimap-server-buffer
616         (setq uid imap-current-message
617               mbx imap-current-mailbox
618               headers (if (imap-capability 'IMAP4rev1)
619                            ;; xxx don't just use car? alist doesn't contain
620                            ;; anything else now, but it might...
621                            (nth 2 (car (imap-message-get uid 'BODYDETAIL)))
622                         (imap-message-get uid 'RFC822.HEADER))
623               lines (imap-body-lines (imap-message-body imap-current-message))
624               chars (imap-message-get imap-current-message 'RFC822.SIZE)))
625       (nnheader-insert-nov
626        ;; At this stage, we only have bytes, so let's use unibyte buffers
627        ;; to make it more clear.
628        (mm-with-unibyte-buffer
629          (buffer-disable-undo)
630          (insert headers)
631          (let ((head (nnheader-parse-naked-head uid)))
632            (mail-header-set-number head uid)
633            (mail-header-set-chars head chars)
634            (mail-header-set-lines head lines)
635            (mail-header-set-xref
636             head (format "%s %s:%d" (system-name) mbx uid))
637            head))))))
638
639 (defun nnimap-retrieve-which-headers (articles fetch-old)
640   "Get a range of articles to fetch based on ARTICLES and FETCH-OLD."
641   (with-current-buffer nnimap-server-buffer
642     (if (numberp (car-safe articles))
643         (imap-search
644          (concat "UID "
645                  (imap-range-to-message-set
646                   (gnus-compress-sequence
647                    (append (gnus-uncompress-sequence
648                             (and fetch-old
649                                  (cons (if (numberp fetch-old)
650                                            (max 1 (- (car articles) fetch-old))
651                                          1)
652                                        (1- (car articles)))))
653                            articles)))))
654       (mapcar (lambda (msgid)
655                 (imap-search
656                  (format "HEADER Message-Id \"%s\"" msgid)))
657               articles))))
658
659 (defun nnimap-group-overview-filename (group server)
660   "Make file name for GROUP on SERVER."
661   (let* ((dir (file-name-as-directory (expand-file-name nnimap-directory)))
662          (uidvalidity (gnus-group-get-parameter
663                        (gnus-group-prefixed-name
664                         group (gnus-server-to-method
665                                (format "nnimap:%s" server)))
666                        'uidvalidity))
667          (name (nnheader-translate-file-chars
668                 (concat nnimap-nov-file-name
669                         (if (equal server "")
670                             "unnamed"
671                           server) "." group nnimap-nov-file-name-suffix) t))
672          (nameuid (nnheader-translate-file-chars
673                    (concat nnimap-nov-file-name
674                            (if (equal server "")
675                                "unnamed"
676                              server) "." group "." uidvalidity
677                            nnimap-nov-file-name-suffix) t))
678          (oldfile (if (or nnmail-use-long-file-names
679                           (file-exists-p (expand-file-name name dir)))
680                       (expand-file-name name dir)
681                     (expand-file-name
682                      (mm-encode-coding-string
683                       (nnheader-replace-chars-in-string name ?. ?/)
684                       nnmail-pathname-coding-system)
685                      dir)))
686          (newfile (if (or nnmail-use-long-file-names
687                           (file-exists-p (expand-file-name nameuid dir)))
688                       (expand-file-name nameuid dir)
689                     (expand-file-name
690                      (mm-encode-coding-string
691                       (nnheader-replace-chars-in-string nameuid ?. ?/)
692                       nnmail-pathname-coding-system)
693                      dir))))
694     (when (and (file-exists-p oldfile) (not (file-exists-p newfile)))
695       (message "nnimap: Upgrading novcache filename...")
696       (sit-for 1)
697       (gnus-make-directory (file-name-directory newfile))
698       (unless (ignore-errors (rename-file oldfile newfile) t)
699         (if (ignore-errors (copy-file oldfile newfile) t)
700             (delete-file oldfile)
701           (error "Can't rename `%s' to `%s'" oldfile newfile))))
702     newfile))
703
704 (defun nnimap-retrieve-headers-from-file (group server)
705   (with-current-buffer nntp-server-buffer
706     (let ((nov (nnimap-group-overview-filename group server)))
707       (when (file-exists-p nov)
708         (mm-insert-file-contents nov)
709         (set-buffer-modified-p nil)
710         (let ((min (ignore-errors (goto-char (point-min))
711                                   (read (current-buffer))))
712               (max (ignore-errors (goto-char (point-max))
713                                   (forward-line -1)
714                                   (read (current-buffer)))))
715           (if (and (numberp min) (numberp max))
716               (cons min max)
717             ;; junk, remove it, it's saved later
718             (erase-buffer)
719             nil))))))
720
721 (defun nnimap-retrieve-headers-from-server (articles group server)
722   (with-current-buffer nnimap-server-buffer
723     (let ((imap-fetch-data-hook '(nnimap-retrieve-headers-progress))
724           (nnimap-length (gnus-range-length articles))
725           (nnimap-counter 0))
726       (imap-fetch (imap-range-to-message-set articles)
727                   (concat "(UID RFC822.SIZE BODY "
728                           (let ((headers
729                                  (append '(Subject From Date Message-Id
730                                                    References In-Reply-To Xref)
731                                          (copy-sequence
732                                           nnmail-extra-headers))))
733                             (if (imap-capability 'IMAP4rev1)
734                                 (format "BODY.PEEK[HEADER.FIELDS %s])" headers)
735                               (format "RFC822.HEADER.LINES %s)" headers)))))
736       (with-current-buffer nntp-server-buffer
737         (sort-numeric-fields 1 (point-min) (point-max)))
738       (and (numberp nnmail-large-newsgroup)
739            (> nnimap-length nnmail-large-newsgroup)
740            (nnheader-message 6 "nnimap: Retrieving headers...done")))))
741
742 (defun nnimap-dont-use-nov-p (group server)
743   (or gnus-nov-is-evil nnimap-nov-is-evil
744       (unless (and (gnus-make-directory
745                     (file-name-directory
746                      (nnimap-group-overview-filename group server)))
747                    (file-writable-p
748                     (nnimap-group-overview-filename group server)))
749         (message "nnimap: Nov cache not writable, %s"
750                  (nnimap-group-overview-filename group server)))))
751
752 (deffoo nnimap-retrieve-headers (articles &optional group server fetch-old)
753   (when (nnimap-possibly-change-group group server)
754     (with-current-buffer nntp-server-buffer
755       (erase-buffer)
756       (if (nnimap-dont-use-nov-p group server)
757           (nnimap-retrieve-headers-from-server
758            (gnus-compress-sequence articles) group server)
759         (let (uids cached low high)
760           (when (setq uids (nnimap-retrieve-which-headers articles fetch-old)
761                       low (car uids)
762                       high (car (last uids)))
763             (if (setq cached (nnimap-retrieve-headers-from-file group server))
764                 (progn
765                   ;; fetch articles with uids before cache block
766                   (when (< low (car cached))
767                     (goto-char (point-min))
768                     (nnimap-retrieve-headers-from-server
769                      (cons low (1- (car cached))) group server))
770                   ;; fetch articles with uids after cache block
771                   (when (> high (cdr cached))
772                     (goto-char (point-max))
773                     (nnimap-retrieve-headers-from-server
774                      (cons (1+ (cdr cached)) high) group server))
775                   (when nnimap-prune-cache
776                     ;; remove nov's for articles which has expired on server
777                     (goto-char (point-min))
778                     (dolist (uid (gnus-set-difference articles uids))
779                       (when (re-search-forward (format "^%d\t" uid) nil t)
780                         (gnus-delete-line)))))
781               ;; nothing cached, fetch whole range from server
782               (nnimap-retrieve-headers-from-server
783                (cons low high) group server))
784             (when (buffer-modified-p)
785               (nnmail-write-region
786                (point-min) (point-max)
787                (nnimap-group-overview-filename group server) nil 'nomesg))
788             (nnheader-nov-delete-outside-range low high))))
789       'nov)))
790
791 (defun nnimap-open-connection (server)
792   ;; Note: `nnimap-open-server' that calls this function binds
793   ;; `imap-logout-timeout' to `nnimap-logout-timeout'.
794   (if (not (imap-open nnimap-address nnimap-server-port nnimap-stream
795                       nnimap-authenticator nnimap-server-buffer))
796       (nnheader-report 'nnimap "Can't open connection to server %s" server)
797     (unless (or (imap-capability 'IMAP4 nnimap-server-buffer)
798                 (imap-capability 'IMAP4rev1 nnimap-server-buffer))
799       (imap-close nnimap-server-buffer)
800       (nnheader-report 'nnimap "Server %s is not IMAP4 compliant" server))
801     (let* ((list (progn (gnus-message 7 "Parsing authinfo file `%s'."
802                                       nnimap-authinfo-file)
803                         (netrc-parse nnimap-authinfo-file)))
804            (port (if nnimap-server-port
805                      (int-to-string nnimap-server-port)
806                    "imap"))
807            (user (or
808                   (auth-source-user-or-password "login" server port) ; this is preferred to netrc-*
809                   (netrc-machine-user-or-password
810                    "login"
811                    list
812                    (list server
813                          (or nnimap-server-address
814                              nnimap-address))
815                    (list port)
816                    (list "imap" "imaps" "143" "993"))))
817            (passwd (or
818                     (auth-source-user-or-password "password" server port) ; this is preferred to netrc-*
819                     (netrc-machine-user-or-password
820                      "password"
821                      list
822                      (list server
823                            (or nnimap-server-address
824                                nnimap-address))
825                      (list port)
826                      (list "imap" "imaps" "143" "993")))))
827       (if (imap-authenticate user passwd nnimap-server-buffer)
828           (prog2
829               (setq nnimap-server-buffer-alist
830                     (nnimap-remove-server-from-buffer-alist
831                      server
832                      nnimap-server-buffer-alist))
833               (push (list server nnimap-server-buffer)
834                     nnimap-server-buffer-alist)
835             (imap-id nnimap-id nnimap-server-buffer)
836             (nnimap-possibly-change-server server))
837         (imap-close nnimap-server-buffer)
838         (kill-buffer nnimap-server-buffer)
839         (nnheader-report 'nnimap "Could not authenticate to %s" server)))))
840
841 (deffoo nnimap-open-server (server &optional defs)
842   (nnheader-init-server-buffer)
843   (if (nnimap-server-opened server)
844       t
845     (unless (assq 'nnimap-server-buffer defs)
846       (push (list 'nnimap-server-buffer (concat " *nnimap* " server)) defs))
847     ;; translate `nnimap-server-address' to `nnimap-address' in defs
848     ;; for people that configured nnimap with a very old version
849     (unless (assq 'nnimap-address defs)
850       (if (assq 'nnimap-server-address defs)
851           (push (list 'nnimap-address
852                       (cadr (assq 'nnimap-server-address defs))) defs)
853         (push (list 'nnimap-address server) defs)))
854     (nnoo-change-server 'nnimap server defs)
855     (or nnimap-server-buffer
856         (setq nnimap-server-buffer (cadr (assq 'nnimap-server-buffer defs))))
857     (with-current-buffer (get-buffer-create nnimap-server-buffer)
858       (nnoo-change-server 'nnimap server defs))
859     (let ((imap-logout-timeout nnimap-logout-timeout))
860       (or (and nnimap-server-buffer
861                (imap-opened nnimap-server-buffer)
862                (if (with-current-buffer nnimap-server-buffer
863                      (memq imap-state '(auth selected examine)))
864                    t
865                  (imap-close nnimap-server-buffer)
866                  (nnimap-open-connection server)))
867           (nnimap-open-connection server)))))
868
869 (deffoo nnimap-server-opened (&optional server)
870   "Whether SERVER is opened.
871 If SERVER is the current virtual server, and the connection to the
872 physical server is alive, this function return a non-nil value.  If
873 SERVER is nil, it is treated as the current server."
874   ;; clean up autologouts??
875   (and (or server nnimap-current-server)
876        (nnoo-server-opened 'nnimap (or server nnimap-current-server))
877        (imap-opened (nnimap-get-server-buffer server))))
878
879 (deffoo nnimap-close-server (&optional server)
880   "Close connection to server and free all resources connected to it.
881 Return nil if the server couldn't be closed for some reason."
882   (let ((server (or server nnimap-current-server))
883         (imap-logout-timeout nnimap-logout-timeout))
884     (when (or (nnimap-server-opened server)
885               (imap-opened (nnimap-get-server-buffer server)))
886       (imap-close (nnimap-get-server-buffer server))
887       (kill-buffer (nnimap-get-server-buffer server))
888       (setq nnimap-server-buffer nil
889             nnimap-current-server nil
890             nnimap-server-buffer-alist
891             (nnimap-remove-server-from-buffer-alist
892              server
893              nnimap-server-buffer-alist)))
894     (nnoo-close-server 'nnimap server)))
895
896 (deffoo nnimap-request-close ()
897   "Close connection to all servers and free all resources that the backend have reserved.
898 All buffers that have been created by that
899 backend should be killed.  (Not the nntp-server-buffer, though.) This
900 function is generally only called when Gnus is shutting down."
901   (mapc (lambda (server) (nnimap-close-server (car server)))
902         nnimap-server-buffer-alist)
903   (setq nnimap-server-buffer-alist nil))
904
905 (deffoo nnimap-status-message (&optional server)
906   "This function returns the last error message from server."
907   (when (nnimap-possibly-change-server server)
908     (nnoo-status-message 'nnimap server)))
909
910 ;; We used to use a string-as-multibyte here, but it is really incorrect.
911 ;; This function is used when we're about to insert a unibyte string
912 ;; into a potentially multibyte buffer.  The string is either an article
913 ;; header or body (or both?), undecoded.  When Emacs is asked to convert
914 ;; a unibyte string to multibyte, it may either use the equivalent of
915 ;; nothing (e.g. non-Mule XEmacs), string-make-unibyte (i.e. decode using
916 ;; locale), string-as-multibyte (decode using emacs-internal coding system)
917 ;; or string-to-multibyte (keep the data undecoded as a sequence of bytes).
918 ;; Only the last one preserves the data such that we can reliably later on
919 ;; decode the text using the mime info.
920 (defalias 'nnimap-demule 'mm-string-to-multibyte)
921
922 (defun nnimap-make-callback (article gnus-callback buffer)
923   "Return a callback function."
924   `(lambda ()
925      (nnimap-callback ,article ,gnus-callback ,buffer)))
926
927 (defun nnimap-callback (article gnus-callback buffer)
928   (when (eq article (imap-current-message))
929     (remove-hook 'imap-fetch-data-hook
930                  (nnimap-make-callback article gnus-callback buffer))
931     (with-current-buffer buffer
932       (insert
933        (with-current-buffer nnimap-server-buffer
934          (nnimap-demule
935           (if (imap-capability 'IMAP4rev1)
936               ;; xxx don't just use car? alist doesn't contain
937               ;; anything else now, but it might...
938               (nth 2 (car (imap-message-get article 'BODYDETAIL)))
939             (imap-message-get article 'RFC822)))))
940       (nnheader-ms-strip-cr)
941       (funcall gnus-callback t))))
942
943 (defun nnimap-request-article-part (article part prop &optional
944                                             group server to-buffer detail)
945   (when (nnimap-possibly-change-group group server)
946     (let ((article (if (stringp article)
947                        (car-safe (imap-search
948                                   (format "HEADER Message-Id \"%s\"" article)
949                                   nnimap-server-buffer))
950                      article)))
951       (when article
952         (gnus-message 10 "nnimap: Fetching (part of) article %d from %s..."
953                       article (or group imap-current-mailbox
954                                   gnus-newsgroup-name))
955         (if (not nnheader-callback-function)
956             (with-current-buffer (or to-buffer nntp-server-buffer)
957               (erase-buffer)
958               (let ((data (imap-fetch article part prop nil
959                                       nnimap-server-buffer)))
960                 (insert (nnimap-demule (if detail
961                                            (nth 2 (car data))
962                                          data))))
963               (nnheader-ms-strip-cr)
964               (gnus-message
965                10 "nnimap: Fetching (part of) article %d from %s...done"
966                article (or group imap-current-mailbox gnus-newsgroup-name))
967               (if (bobp)
968                   (nnheader-report 'nnimap "No such article %d in %s: %s"
969                                    article (or group imap-current-mailbox
970                                                gnus-newsgroup-name)
971                                    (imap-error-text nnimap-server-buffer))
972                 (cons group article)))
973           (add-hook 'imap-fetch-data-hook
974                     (nnimap-make-callback article
975                                           nnheader-callback-function
976                                           nntp-server-buffer))
977           (imap-fetch-asynch article part nil nnimap-server-buffer)
978           (cons group article))))))
979
980 (deffoo nnimap-asynchronous-p ()
981   t)
982
983 (deffoo nnimap-request-article (article &optional group server to-buffer)
984   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
985       (nnimap-request-article-part
986        article "BODY.PEEK[]" 'BODYDETAIL group server to-buffer 'detail)
987     (nnimap-request-article-part
988      article "RFC822.PEEK" 'RFC822 group server to-buffer)))
989
990 (deffoo nnimap-request-head (article &optional group server to-buffer)
991   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
992       (nnimap-request-article-part
993        article "BODY.PEEK[HEADER]" 'BODYDETAIL group server to-buffer 'detail)
994     (nnimap-request-article-part
995      article "RFC822.HEADER" 'RFC822.HEADER group server to-buffer)))
996
997 (deffoo nnimap-request-body (article &optional group server to-buffer)
998   (if (imap-capability 'IMAP4rev1 nnimap-server-buffer)
999       (nnimap-request-article-part
1000        article "BODY.PEEK[TEXT]" 'BODYDETAIL group server to-buffer 'detail)
1001     (nnimap-request-article-part
1002      article "RFC822.TEXT.PEEK" 'RFC822.TEXT group server to-buffer)))
1003
1004 (deffoo nnimap-request-group (group &optional server fast)
1005   (nnimap-request-update-info-internal
1006    group
1007    (gnus-get-info (gnus-group-prefixed-name
1008                    group (gnus-server-to-method (format "nnimap:%s" server))))
1009    server)
1010   (when (nnimap-possibly-change-group group server)
1011     (nnimap-before-find-minmax-bugworkaround)
1012     (let (info)
1013       (cond (fast group)
1014             ((null (setq info (nnimap-find-minmax-uid group t)))
1015              (nnheader-report 'nnimap "Could not get active info for %s"
1016                               group))
1017             (t
1018              (nnheader-insert "211 %d %d %d %s\n" (or (nth 0 info) 0)
1019                               (max 1 (or (nth 1 info) 1))
1020                               (or (nth 2 info) 0) group)
1021              (nnheader-report 'nnimap "Group %s selected" group)
1022              t)))))