1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760
|
//
// Conf.cs
//
// Copyright (C) 2005 Novell, Inc.
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
using System;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Xml.Serialization;
using System.Text.RegularExpressions;
using Beagle.Util;
namespace Beagle.Util {
public class Conf {
// No instantiation
private Conf () { }
public static Hashtable Sections;
public static IndexingConfig Indexing = null;
public static DaemonConfig Daemon = null;
public static SearchingConfig Searching = null;
private static string configs_dir;
private static Hashtable mtimes;
private static Hashtable subscriptions;
private static bool watching_for_updates;
private static bool update_watch_present;
private static BindingFlags method_search_flags = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod;
public delegate void ConfigUpdateHandler (Section section);
static Conf ()
{
Sections = new Hashtable (3);
mtimes = new Hashtable (3);
subscriptions = new Hashtable (3);
configs_dir = Path.Combine (PathFinder.StorageDir, "config");
if (!Directory.Exists (configs_dir))
Directory.CreateDirectory (configs_dir);
Conf.Load ();
}
public static void WatchForUpdates ()
{
// Make sure we don't try and watch for updates more than once
if (update_watch_present)
return;
if (Inotify.Enabled) {
Inotify.Subscribe (configs_dir, OnInotifyEvent, Inotify.EventType.Create | Inotify.EventType.CloseWrite);
} else {
// Poll for updates every 60 secs
GLib.Timeout.Add (60000, new GLib.TimeoutHandler (CheckForUpdates));
}
update_watch_present = true;
}
private static void OnInotifyEvent (Inotify.Watch watch, string path, string subitem, string srcpath, Inotify.EventType type)
{
if (subitem == "" || watching_for_updates == false)
return;
Load ();
}
private static bool CheckForUpdates ()
{
if (watching_for_updates)
Load ();
return true;
}
public static void Subscribe (Type type, ConfigUpdateHandler callback)
{
if (!subscriptions.ContainsKey (type))
subscriptions.Add (type, new ArrayList (1));
ArrayList callbacks = (ArrayList) subscriptions [type];
callbacks.Add (callback);
}
private static void NotifySubscribers (Section section)
{
Type type = section.GetType ();
ArrayList callbacks = (ArrayList) subscriptions [type];
if (callbacks == null)
return;
foreach (ConfigUpdateHandler callback in callbacks)
callback (section);
}
public static void Load ()
{
Load (false);
}
public static void Load (bool force)
{
Section temp;
// FIXME: Yeah
LoadFile (typeof (IndexingConfig), Indexing, out temp, force);
Indexing = (IndexingConfig) temp;
NotifySubscribers (Indexing);
LoadFile (typeof (DaemonConfig), Daemon, out temp, force);
Daemon = (DaemonConfig) temp;
NotifySubscribers (Daemon);
LoadFile (typeof (SearchingConfig), Searching, out temp, force);
Searching = (SearchingConfig) temp;
NotifySubscribers (Searching);
watching_for_updates = true;
}
public static void Save ()
{
Save (false);
}
public static void Save (bool force)
{
foreach (Section section in Sections.Values)
if (force || section.SaveNeeded)
SaveFile (section);
}
private static bool LoadFile (Type type, Section current, out Section section, bool force)
{
section = current;
object [] attrs = Attribute.GetCustomAttributes (type, typeof (ConfigSection));
if (attrs.Length == 0)
throw new ConfigException ("Could not find ConfigSection attribute on " + type);
string sectionname = ((ConfigSection) attrs [0]).Name;
string filename = sectionname + ".xml";
string filepath = Path.Combine (configs_dir, filename);
if (!File.Exists (filepath)) {
if (current == null)
ConstructDefaultSection (type, sectionname, out section);
return false;
}
if (!force && current != null && mtimes.ContainsKey (sectionname) &&
File.GetLastWriteTimeUtc (filepath).CompareTo ((DateTime) mtimes [sectionname]) <= 0)
return false;
Logger.Log.Debug ("Loading {0} from {1}", type, filename);
FileStream fs = null;
try {
fs = File.Open (filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
XmlSerializer serializer = new XmlSerializer (type);
section = (Section) serializer.Deserialize (fs);
} catch (Exception e) {
Logger.Log.Error (e, "Could not load configuration from {0}:", filename);
if (fs != null)
fs.Close ();
if (current == null)
ConstructDefaultSection (type, sectionname, out section);
return false;
}
fs.Close ();
Sections.Remove (sectionname);
Sections.Add (sectionname, section);
mtimes.Remove (sectionname);
mtimes.Add (sectionname, File.GetLastWriteTimeUtc (filepath));
return true;
}
private static bool SaveFile (Section section)
{
Type type = section.GetType ();
object [] attrs = Attribute.GetCustomAttributes (type, typeof (ConfigSection));
if (attrs.Length == 0)
throw new ConfigException ("Could not find ConfigSection attribute on " + type);
string sectionname = ((ConfigSection) attrs [0]).Name;
string filename = sectionname + ".xml";
string filepath = Path.Combine (configs_dir, filename);
Logger.Log.Debug ("Saving {0} to {1}", type, filename);
FileStream fs = null;
try {
watching_for_updates = false;
fs = new FileStream (filepath, FileMode.Create);
XmlSerializer serializer = new XmlSerializer (type);
XmlFu.SerializeUtf8 (serializer, fs, section);
} catch (Exception e) {
if (fs != null)
fs.Close ();
Logger.Log.Error ("Could not save configuration to {0}: {1}", filename, e);
watching_for_updates = true;
return false;
}
fs.Close ();
mtimes.Remove (sectionname);
mtimes.Add (sectionname, File.GetLastWriteTimeUtc (filepath));
watching_for_updates = true;
return true;
}
private static void ConstructDefaultSection (Type type, string sectionname, out Section section)
{
ConstructorInfo ctor = type.GetConstructor (Type.EmptyTypes);
section = (Section) ctor.Invoke (null);
Sections.Remove (sectionname);
Sections.Add (sectionname, section);
}
// Lists all config file options in a hash table where key is option name,
// and value is description.
public static Hashtable GetOptions (Section section)
{
Hashtable options = new Hashtable ();
MemberInfo [] members = section.GetType ().GetMembers (method_search_flags);
// Find all of the methods ("options") inside the specified section
// object which have the ConfigOption attribute.
foreach (MemberInfo member in members) {
object [] attrs = member.GetCustomAttributes (typeof (ConfigOption), false);
if (attrs.Length > 0)
options.Add (member.Name, ((ConfigOption) attrs [0]).Description);
}
return options;
}
public static bool InvokeOption (Section section, string option, string [] args, out string output)
{
MethodInfo method = section.GetType ().GetMethod (option, method_search_flags);
if (method == null) {
string msg = String.Format ("No such method '{0}' for section '{1}'", option, section);
throw new ConfigException(msg);
}
object [] attrs = method.GetCustomAttributes (typeof (ConfigOption), false);
if (attrs.Length == 0) {
string msg = String.Format ("Method '{0}' is not a configurable option", option);
throw new ConfigException (msg);
}
// Check the required number of parameters have been provided
ConfigOption attr = (ConfigOption) attrs [0];
if (attr.Params > 0 && args.Length < attr.Params) {
string msg = String.Format ("Option '{0}' requires {1} parameter(s): {2}", option, attr.Params, attr.ParamsDescription);
throw new ConfigException (msg);
}
object [] methodparams = { null, args };
bool result = (bool) method.Invoke (section, methodparams);
output = (string) methodparams [0];
// Mark the section as save-needed if we just changed something
if (result && attr.IsMutator)
section.SaveNeeded = true;
return result;
}
[ConfigSection (Name="searching")]
public class SearchingConfig : Section {
private bool autostart = true;
public bool Autostart {
get { return autostart; }
set { autostart = value; }
}
private KeyBinding show_search_window_binding = new KeyBinding ("F12");
public KeyBinding ShowSearchWindowBinding {
get { return show_search_window_binding; }
set { show_search_window_binding = value; }
}
private int max_displayed = 5;
public int MaxDisplayed {
get { return max_displayed; }
set {
if (value <= 0)
max_displayed = 1;
else
max_displayed = value;
}
}
// BeagleSearch window position and dimension
// stored as percentage of screen co-ordinates
// to deal with change of resolution problem - hints from tberman
private float beagle_search_pos_x = 0;
public float BeaglePosX {
get { return beagle_search_pos_x; }
set { beagle_search_pos_x = value; }
}
private float beagle_search_pos_y = 0;
public float BeaglePosY {
get { return beagle_search_pos_y; }
set { beagle_search_pos_y = value; }
}
private float beagle_search_width = 0;
public float BeagleSearchWidth {
get { return beagle_search_width; }
set { beagle_search_width = value; }
}
private float beagle_search_height = 0;
public float BeagleSearchHeight {
get { return beagle_search_height; }
set { beagle_search_height = value; }
}
// ah!We want a Queue but Queue doesnt serialize *easily*
private ArrayList search_history = new ArrayList ();
public ArrayList SearchHistory {
get { return search_history; }
set { search_history = value; }
}
}
[ConfigSection (Name="daemon")]
public class DaemonConfig : Section {
private ArrayList static_queryables = new ArrayList ();
public ArrayList StaticQueryables {
get { return static_queryables; }
set { static_queryables = value; }
}
// By default, every backend is allowed.
// Only maintain a list of denied backends.
private ArrayList denied_backends = new ArrayList ();
public ArrayList DeniedBackends {
get { return denied_backends; }
set { denied_backends = value; }
}
private bool allow_static_backend = false; // by default, false
public bool AllowStaticBackend {
get { return allow_static_backend; }
// Don't really want to expose this, but serialization requires it
set { allow_static_backend = value; }
}
private bool index_synchronization = true;
public bool IndexSynchronization {
get { return index_synchronization; }
// Don't really want to expose this, but serialization requires it
set { index_synchronization = value; }
}
[ConfigOption (Description="Enable a backend", Params=1, ParamsDescription="Name of the backend to enable")]
internal bool AllowBackend (out string output, string [] args)
{
denied_backends.Remove (args [0]);
output = "Backend allowed (need to restart beagled for changes to take effect).";
return true;
}
[ConfigOption (Description="Disable a backend", Params=1, ParamsDescription="Name of the backend to disable")]
internal bool DenyBackend (out string output, string [] args)
{
denied_backends.Add (args [0]);
output = "Backend disabled (need to restart beagled for changes to take effect).";
return true;
}
private bool allow_root = false;
public bool AllowRoot {
get { return allow_root; }
set { allow_root = value; }
}
[ConfigOption (Description="Add a static queryable", Params=1, ParamsDescription="Index path")]
internal bool AddStaticQueryable (out string output, string [] args)
{
static_queryables.Add (args [0]);
output = "Static queryable added.";
return true;
}
[ConfigOption (Description="Remove a static queryable", Params=1, ParamsDescription="Index path")]
internal bool DelStaticQueryable (out string output, string [] args)
{
static_queryables.Remove (args [0]);
output = "Static queryable removed.";
return true;
}
[ConfigOption (Description="List user-specified static queryables", IsMutator=false)]
internal bool ListStaticQueryables (out string output, string [] args)
{
output = "User-specified static queryables:\n";
foreach (string index_path in static_queryables)
output += String.Format (" - {0}\n", index_path);
return true;
}
[ConfigOption (Description="Toggles whether static indexes will be enabled")]
internal bool ToggleAllowStaticBackend (out string output, string [] args)
{
allow_static_backend = !allow_static_backend;
output = "Static indexes are " + ((allow_static_backend) ? "enabled" : "disabled") + " (need to restart beagled for changes to take effect).";
return true;
}
[ConfigOption (Description="Toggles whether your indexes will be synchronized locally if your home directory is on a network device (eg. NFS/Samba)")]
internal bool ToggleIndexSynchronization (out string output, string [] args)
{
index_synchronization = !index_synchronization;
output = "Index Synchronization is " + ((index_synchronization) ? "enabled" : "disabled") + ".";
return true;
}
[ConfigOption (Description="Toggles whether Beagle can be run as root")]
internal bool ToggleAllowRoot (out string output, string [] args)
{
allow_root = ! allow_root;
if (allow_root)
output = "Beagle is now permitted to run as root";
else
output = "Beagle is no longer permitted to run as root";
return true;
}
}
[ConfigSection (Name="indexing")]
public class IndexingConfig : Section
{
private ArrayList roots = new ArrayList ();
[XmlArray]
[XmlArrayItem(ElementName="Root", Type=typeof(string))]
public ArrayList Roots {
get { return roots; }
set { roots = value; }
}
private bool index_home_dir = true;
public bool IndexHomeDir {
get { return index_home_dir; }
set { index_home_dir = value; }
}
private bool index_on_battery = true;
public bool IndexOnBattery {
get { return index_on_battery; }
set { index_on_battery = value; }
}
private ArrayList excludes = new ArrayList ();
[XmlArray]
[XmlArrayItem (ElementName="ExcludeItem", Type=typeof(ExcludeItem))]
public ArrayList Excludes {
get { return excludes; }
set { excludes = value; }
}
[ConfigOption (Description="List the indexing roots", IsMutator=false)]
internal bool ListRoots (out string output, string [] args)
{
output = "Current roots:\n";
if (this.index_home_dir == true)
output += " - Your home directory\n";
foreach (string root in roots)
output += " - " + root + "\n";
return true;
}
[ConfigOption (Description="Toggles whether your home directory is to be indexed as a root")]
internal bool IndexHome (out string output, string [] args)
{
if (index_home_dir)
output = "Your home directory will not be indexed.";
else
output = "Your home directory will be indexed.";
index_home_dir = !index_home_dir;
return true;
}
[ConfigOption (Description="Toggles whether any data should be indexed if the system is on battery")]
internal bool IndexWhileOnBattery (out string output, string [] args)
{
if (index_on_battery)
output = "Data will not be indexed while on battery.";
else
output = "Data will be indexed while on battery.";
index_on_battery = !index_on_battery;
return true;
}
[ConfigOption (Description="Add a root path to be indexed", Params=1, ParamsDescription="A path")]
internal bool AddRoot (out string output, string [] args)
{
roots.Add (args [0]);
output = "Root added.";
return true;
}
[ConfigOption (Description="Remove an indexing root", Params=1, ParamsDescription="A path")]
internal bool DelRoot (out string output, string [] args)
{
roots.Remove (args [0]);
output = "Root removed.";
return true;
}
[ConfigOption (Description="List user-specified resources to be excluded from indexing", IsMutator=false)]
internal bool ListExcludes (out string output, string [] args)
{
output = "User-specified resources to be excluded from indexing:\n";
foreach (ExcludeItem exclude_item in excludes)
output += String.Format (" - [{0}] {1}\n", exclude_item.Type.ToString (), exclude_item.Value);
return true;
}
[ConfigOption (Description="Add a resource to exclude from indexing", Params=2, ParamsDescription="A type [path/pattern/mailfolder], a path/pattern/name")]
internal bool AddExclude (out string output, string [] args)
{
ExcludeType type;
try {
type = (ExcludeType) Enum.Parse (typeof (ExcludeType), args [0], true);
} catch (Exception e) {
output = String.Format("Invalid type '{0}'. Valid types: Path, Pattern, MailFolder", args [0]);
return false;
}
excludes.Add (new ExcludeItem (type, args [1]));
output = "Exclude added.";
return true;
}
[ConfigOption (Description="Remove an excluded resource", Params=2, ParamsDescription="A type [path/pattern/mailfolder], a path/pattern/name")]
internal bool DelExclude (out string output, string [] args)
{
ExcludeType type;
try {
type = (ExcludeType) Enum.Parse (typeof (ExcludeType), args [0], true);
} catch (Exception e) {
output = String.Format("Invalid type '{0}'. Valid types: Path, Pattern, MailFolder", args [0]);
return false;
}
foreach (ExcludeItem item in excludes) {
if (item.Type != type || item.Value != args [1])
continue;
excludes.Remove (item);
output = "Exclude removed.";
return true;
}
output = "Could not find requested exclude to remove.";
return false;
}
}
public class Section {
[XmlIgnore]
public bool SaveNeeded = false;
}
private class ConfigOption : Attribute {
public string Description;
public int Params;
public string ParamsDescription;
public bool IsMutator = true;
}
private class ConfigSection : Attribute {
public string Name;
}
public class ConfigException : Exception {
public ConfigException (string msg) : base (msg) { }
}
}
//////////////////////////////////////////////////////////////////////
public enum ExcludeType {
Path,
Pattern,
MailFolder
}
public class ExcludeItem {
private ExcludeType type;
private string val;
[XmlAttribute]
public ExcludeType Type {
get { return type; }
set { type = value; }
}
private string exactMatch;
private string prefix;
private string suffix;
private Regex regex;
[XmlAttribute]
public string Value {
get { return val; }
set {
switch (type) {
case ExcludeType.Path:
case ExcludeType.MailFolder:
prefix = value;
break;
case ExcludeType.Pattern:
if (value.StartsWith ("/") && value.EndsWith ("/")) {
regex = new Regex (value.Substring (1, value.Length - 2));
break;
}
int i = value.IndexOf ('*');
if (i == -1) {
exactMatch = value;
} else {
if (i > 0)
prefix = value.Substring (0, i);
if (i < value.Length-1)
suffix = value.Substring (i+1);
}
break;
}
val = value;
}
}
public ExcludeItem () {}
public ExcludeItem (ExcludeType type, string value) {
this.Type = type;
this.Value = value;
}
public bool IsMatch (string param)
{
switch (Type) {
case ExcludeType.Path:
case ExcludeType.MailFolder:
if (prefix != null && ! param.StartsWith (prefix))
return false;
return true;
case ExcludeType.Pattern:
if (exactMatch != null)
return param == exactMatch;
if (prefix != null && ! param.StartsWith (prefix))
return false;
if (suffix != null && ! param.EndsWith (suffix))
return false;
if (regex != null && ! regex.IsMatch (param))
return false;
return true;
}
return false;
}
public override bool Equals (object obj)
{
ExcludeItem exclude = obj as ExcludeItem;
return (exclude != null && exclude.Type == type && exclude.Value == val);
}
public override int GetHashCode ()
{
return (this.Value.GetHashCode () ^ (int) this.Type);
}
}
//////////////////////////////////////////////////////////////////////
public class KeyBinding {
public string Key;
[XmlAttribute]
public bool Ctrl = false;
[XmlAttribute]
public bool Alt = false;
public KeyBinding () {}
public KeyBinding (string key) : this (key, false, false) {}
public KeyBinding (string key, bool ctrl, bool alt)
{
Key = key;
Ctrl = ctrl;
Alt = alt;
}
public override string ToString ()
{
string result = "";
if (Ctrl)
result += "<Ctrl>";
if (Alt)
result += "<Alt>";
result += Key;
return result;
}
public string ToReadableString ()
{
return ToString ().Replace (">", "-").Replace ("<", "");
}
}
}
|