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
|
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
namespace DreamShield.Deployment.Utils
{
/// <summary>
/// Classe qui permet de représenter les clefs du registre.
/// Partout où une variable name est utilisée, il s'agit d'un chemin
/// au sens du registre qui peut être HKEY_LOCAL_MACHINE\Microsoft\Windows
/// ou encore CurrentVersion\Uninstall.
/// </summary>
public class LocalRegistryKey
{
#region Constants
public const string HKLM = "HKEY_LOCAL_MACHINE";
public const string HKCU = "HKEY_CURRENT_USER";
public const string HKCR = "HKEY_CLASSES_ROOT";
public const string HKU = "HKEY_USERS";
#endregion
#region Creation
/// <summary>
/// Crée un nouvel objet de registre.
/// La clef renvoyée est un "parent virtuel" qui contient les clefs
/// HKLM, HKCU, HKCR et HKU
/// </summary>
/// <returns></returns>
public static LocalRegistryKey CreateRepository()
{
LocalRegistryKey res = new LocalRegistryKey(null, null);
res.Childs.AddRange(new LocalRegistryKey[]{
new LocalRegistryKey(null, HKLM),
new LocalRegistryKey(null, HKCU),
new LocalRegistryKey(null, HKCR),
new LocalRegistryKey(null, HKU)
});
res.GlobalRoot = true;
return res;
}
#endregion
#region Globals & Constructor
/// <summary>
/// Clef parente, null pour les clefs racines
/// </summary>
public virtual LocalRegistryKey Parent { get; protected set; }
protected List<LocalRegistryKey> Childs { get; private set; }
/// <summary>
/// Clefs enfantes
/// </summary>
public virtual LocalRegistryKey[] SubKeys
{
get { return Childs.ToArray(); }
}
private LocalRegistryKey(LocalRegistryKey parent, string name)
{
if (parent != null && String.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
GlobalRoot = false;
Parent = parent;
_name = name;
Childs = new List<LocalRegistryKey>();
if (!GlobalRoot)
{
InitRegValues();
}
}
#endregion
#region Access
/// <summary>
/// Indique si cette clef est le parent virtuel des clefs racines
/// </summary>
public virtual bool GlobalRoot { get; protected set; }
/// <summary>
/// Indique si la clef actuelle est une racine
/// </summary>
public virtual bool IsRoot
{
get { return Parent == null; }
}
string _name = null;
/// <summary>
/// Nom de la clef. Il ne peut être modifié que pour les clefs non racines
/// </summary>
public virtual string Name
{
get
{
return _name;
}
set
{
if (IsRoot)
throw new InvalidOperationException("Impossible de renommer une racine");
else
{
if (String.IsNullOrEmpty(value))
throw new ArgumentNullException("value");
else if (String.Equals(_name, value, StringComparison.OrdinalIgnoreCase))
_name = value;
else
{
if (Parent.KeyExists(value))
throw new DuplicateNameException(value);
else
_name = value;
}
}
}
}
/// <summary>
/// Indique si la clef spécifiée existe
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public virtual bool KeyExists(string name)
{
LocalRegistryKey key = null;
return TryGetKey(name, out key);
}
/// <summary>
/// Obtients une clef (exception si elle n'existe pas)
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public virtual LocalRegistryKey Key(string name)
{
return Key(name, false);
}
/// <summary>
/// Charge la clef en la créant si elle n'existe pas et que canCreate vaut true.
/// </summary>
/// <remarks>Aucune clef ne peut être crée au même niveau que les clefs racines</remarks>
/// <param name="name"></param>
/// <param name="canCreate">Indique si la clef doit être crée si elle n'existe pas</param>
/// <returns></returns>
public virtual LocalRegistryKey Key(string name, bool canCreate)
{
LocalRegistryKey key = null;
if (TryGetKey(name, out key, canCreate))
return key;
else
throw new KeyNotFoundException(name);
}
/// <summary>
/// Tente d'obtenir la clef spécifiée et la renvoi si elle existe, ou renvoi
/// nul sinon dans key
/// </summary>
/// <param name="name"></param>
/// <param name="key"></param>
/// <returns></returns>
public virtual bool TryGetKey(string name, out LocalRegistryKey key)
{
return TryGetKey(name, out key, false);
}
protected virtual bool TryGetKey(string name, out LocalRegistryKey key, bool canCreate)
{
if (String.IsNullOrEmpty(name))
throw new ArgumentNullException("value");
string[] secs = name.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
key = this;
for (int i = 0; i < secs.Length; i++)
{
key = FindKey(key, secs[i], canCreate);
if (key == null)
break;
}
return key != null;
}
protected virtual LocalRegistryKey FindKey(LocalRegistryKey key, string name, bool canCreate)
{
if (String.IsNullOrEmpty(name))
throw new ArgumentNullException("name");
if (name.Contains("]") || name.Contains("["))
throw new InvalidDataException("Nom invalide :" + name);
foreach (var item in key.Childs)
{
if (item.Name != null && item.Name.Equals(name, StringComparison.OrdinalIgnoreCase))
return item;
}
if (canCreate)
{
if (key.GlobalRoot)
{
/* Impossible de créer une clef racine */
return null;
}
else
{
LocalRegistryKey n_key = new LocalRegistryKey(key, name);
key.Childs.Add(n_key);
return n_key;
}
}
else
{
return null;
}
}
#endregion
#region Utils
/// <summary>
/// Efface tous le contenu des clefs
/// </summary>
/// <remarks>Ne peut pas être appelé sur la racine virtuelle</remarks>
public virtual void Clear()
{
if (GlobalRoot)
throw new InvalidOperationException("Impossible de supprimer les clefs racines");
else
{
Childs.Clear();
Values.Clear();
}
}
/// <summary>
/// Supprime la clef
/// </summary>
/// <remarks>Une clef racine ne peut pas être supprimée.</remarks>
public virtual void Delete()
{
if (IsRoot)
throw new InvalidOperationException("Impossible de supprimer une racine");
else
{
Parent.Childs.Remove(this);
Childs.Clear();
if (Values != null)
{
Values.Clear();
}
Values = null;
Childs = null;
Parent = null;
_name = null;
}
}
/// <summary>
/// Obtient le nom complet de la clef
/// </summary>
public virtual string FullName
{
get
{
return (Parent != null ? Parent.FullName + "\\" : "") + Name;
}
}
public override string ToString()
{
string s = FullName;
return String.IsNullOrEmpty(s) ? base.ToString() : s;
}
#endregion
#region Values
/// <summary>
/// Liste des valeurs.
/// Pour la valeur par défaut, utiliser comme clef "" (la chaine vide), null étant une valeur
/// de clef interdite
/// </summary>
public virtual Dictionary<string, LocalRegistryValue> Values { get; protected set; }
protected static RegValueKeysComparer RegValueKeysComparerInstance = new RegValueKeysComparer();
protected void InitRegValues()
{
Values = new Dictionary<string, LocalRegistryValue>(RegValueKeysComparerInstance);
}
/* Juste par sécurité */
protected class RegValueKeysComparer : IEqualityComparer<string>
{
#region IEqualityComparer<string> Membres
public virtual bool Equals(string x, string y)
{
if (String.IsNullOrEmpty(x))
return String.IsNullOrEmpty(y);
else
{
return String.Equals(x, y, StringComparison.OrdinalIgnoreCase);
}
}
public virtual int GetHashCode(string obj)
{
return obj == null ? 0 : obj.GetHashCode();
}
#endregion
}
#endregion
}
public class LocalRegistryValue
{
public LocalRegistryValue(ValueType vType, object vVal)
{
ValueType = vType;
Value = vVal;
}
protected ValueType valueType = ValueType.Binary;
/// <summary>
/// Type de valeur
/// </summary>
/// <remarks>Changer de type efface automatiquement la variable Value</remarks>
public virtual ValueType ValueType
{
get
{
return valueType;
}
set
{
if (valueType != value)
{
valueType = value;
_value = null;
}
}
}
protected object _value = null;
/// <summary>
/// Valeur, doit être convertible en ValueType
/// </summary>
public virtual object Value
{
get { return _value; }
set
{
if (!CheckValue(ValueType, value))
throw new InvalidDataException(String.Format("L'argument {0} n'est pas convertible en {1}", value, ValueType));
else
_value = value;
}
}
protected virtual bool CheckValue(ValueType ValueType, object value)
{
if (value == null)
return true;
else
{
switch (ValueType)
{
case ValueType.Binary: { return typeof(byte[]).IsAssignableFrom(value.GetType()); }
case ValueType.DWORD: { return typeof(uint).IsAssignableFrom(value.GetType()); }
case ValueType.QWORD: { return typeof(ulong).IsAssignableFrom(value.GetType()); }
case ValueType.MultiString: { return typeof(string[]).IsAssignableFrom(value.GetType()); }
case ValueType.ExpandableString:
case ValueType.String:
{
return typeof(string).IsAssignableFrom(value.GetType());
}
default: { return false; }
}
}
}
public override string ToString()
{
return String.Format("{0}", Value);
}
}
public enum ValueType
{
/// <summary>
/// Binary registry value type : convertit en byte[]
/// </summary>
Binary,
/// <summary>
/// DWORD registry value type : convertit en uint
/// </summary>
DWORD,
/// <summary>
/// QWORD registry value type : convertit en ulong
/// </summary>
QWORD,
/// <summary>
/// Expandable string registry value type : convertit en string
/// </summary>
ExpandableString,
/// <summary>
/// MultiString registry value type : convertit en string[]
/// </summary>
MultiString,
/// <summary>
/// String registry value type : convertit en string
/// </summary>
String
}
public static class RegFileImporter
{
public static LocalRegistryKey ProcessRegistryFile(StreamReader input)
{
return ProcessRegistryFile(input, null);
}
public static LocalRegistryKey ProcessRegistryFile(StreamReader input, LocalRegistryKey result)
{
if (result == null)
result = LocalRegistryKey.CreateRepository();
LocalRegistryKey last = null;
string current_line = "";
while (!input.EndOfStream)
{
current_line = input.ReadLine();
if (current_line.StartsWith("["))
{
/* section */
int end = current_line.IndexOf("]");
if (end < 1)
throw new InvalidDataException("Ligne invalide :" + current_line);
else
{
string key_name = current_line.Substring(1, end - 1);
last = result.Key(key_name, true);
}
}
else if (current_line.StartsWith("@"))
{
/* valeur par défaut */
ReadValue(current_line, input, last);
}
else if (current_line.StartsWith("\""))
{
/* valeur nommée */
ReadValue(current_line, input, last);
}
}
return result;
}
private static void ReadValue(string current_line, StreamReader input, LocalRegistryKey last)
{
if (String.IsNullOrEmpty(current_line))
return;
else
{
string[] secs = current_line.Split(new char[] { '=' }, 2);
if (secs.Length != 2)
throw new InvalidDataException("Ligne invalide :" + current_line);
else
{
string name = secs[0];
string data = secs[1];
if (name == "@")
name = "";
else
name = name.Substring(1, name.Length - 2); /* On retire les quotes */
if (String.IsNullOrEmpty(data) || data == "\"\"")
{
last.Values[name] = new LocalRegistryValue(ValueType.String, null);
}
else
{
if (data.StartsWith("hex:")) // binary
{
last.Values[name] = new LocalRegistryValue(ValueType.Binary,
(byte[])ParseBinaryArray(data.Substring("hex:".Length), input));
}
else if (data.StartsWith("dword:")) //dword
{
last.Values[name] = new LocalRegistryValue(ValueType.DWORD,
(uint)ParseDword(data.Substring("dword:".Length), input));
}
else if (data.StartsWith("hex(b):")) //qword
{
/* Pourquoi le QWORD est-il stoqué sous la form de byte[] ?? */
byte[] b_val = ParseBinaryArray(data.Substring("hex(b):".Length), input);
ulong val = BitConverter.ToUInt64(b_val, 0);
last.Values[name] = new LocalRegistryValue(ValueType.QWORD,val);
}
else if (data.StartsWith("hex(2):")) // expandable string
{
string str = ParseString(data.Substring("hex(2):".Length), input);
last.Values[name] = new LocalRegistryValue(ValueType.ExpandableString,
Encoding.Unicode.GetString(BytesFromString(str)));
}
else if (data.StartsWith("hex(7):")) // multi-string
{
string str = ParseString(data.Substring("hex(7):".Length), input);
last.Values[name] = new LocalRegistryValue(ValueType.MultiString,
(string[])ParseMultiString(str));
}
else // string
{
last.Values[name] = new LocalRegistryValue(ValueType.String,
(string)ArrangeString(ParseString(data.Substring(1, data.Length - 2), input)));
}
}
}
}
}
private static string ArrangeString(string p)
{
string res = "";
int actual = 0;
using (StringReader reader = new StringReader(p))
{
while (true)
{
actual = reader.Read();
if (actual < 0)
break;
else
{
char c = (char)actual;
if (c == '\\') /* échappement */
{
int escape = reader.Read();
if (escape < 0)
throw new InvalidDataException("Séquence d'échappement invalide : fin du flux rencontré pour la ligne : " + p);
else
{
char e = (char)escape;
switch (e)
{
case 'n': { res += "\n"; break; }
case 'r': { res += "\r"; break; }
case '\\': { res += "\\"; break; }
case '0': { res += "\0"; break; }
case '\"': { res += "\""; break; }
case '\'': { res += "\'"; break; }
default:
throw new InvalidDataException(String.Format("Séquence d'échappement non reconnue, {0}, à la ligne {1}", c.ToString() + e.ToString(), p));
}
}
}
else
{
res += c.ToString();
}
}
}
}
return res;
}
private static string[] ParseMultiString(string str)
{
if (String.IsNullOrEmpty(str))
return new string[0];
else
{
str = Encoding.Unicode.GetString(BytesFromString(str));
return str.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
}
private static byte[] BytesFromString(string p)
{
string[] parts = p.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
byte[] res = new byte[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
res[i] = byte.Parse(parts[i], System.Globalization.NumberStyles.HexNumber);
}
return res;
}
private static string ParseString(string p, StreamReader input)
{
return ReadFullString(p, input);
}
private static uint ParseDword(string p, StreamReader input)
{
return uint.Parse(p, System.Globalization.NumberStyles.HexNumber);
}
private static byte[] ParseBinaryArray(string p, StreamReader input)
{
return BytesFromString(ReadFullString(p, input));
}
private static string ReadFullString(string p, StreamReader input)
{
string s = "";
bool do_next = false;
do
{
if (p.EndsWith("\\"))
{
s += p.Substring(0, p.Length - 1); ;
do_next = true;
}
else
{
s += p;
do_next = false;
}
if (do_next)
{
p = input.ReadLine();
p = p.Substring(2); /* 2 espaces au début de la ligne */
}
}
while (do_next);
return s;
}
}
} |
Partager