-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
626 lines (562 loc) · 17.8 KB
/
Program.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using System.Security.Permissions;
using System.Security;
namespace Hosts
{
class HostNotSpecifiedException : ApplicationException { }
class HostNotFoundException : ApplicationException
{
public string Host { get; protected set; }
public HostNotFoundException(string host) { Host = host; }
}
class Program
{
static bool IsUnix;
static string GetHostsFileName()
{
if (IsUnix)
{
return "/etc/hosts";
}
try
{
RegistryKey HostsRegKey = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\");
string HostsPath = (string)HostsRegKey.GetValue("DataBasePath");
HostsRegKey.Close();
if (HostsPath.Trim() == "") throw new Exception("Empty path");
return Environment.ExpandEnvironmentVariables(HostsPath + @"\hosts");
}
catch (Exception e)
{
throw new Exception("Cannot get path to the hosts file from the registry", e);
}
}
static T GetAssemblyAttribute<T>()
{
object[] attributes = Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(T), false);
return (attributes.Length == 0) ? default(T) : (T)attributes[0];
}
static string GetTitle()
{
var attr = GetAssemblyAttribute<AssemblyTitleAttribute>();
if (attr == null) return String.Empty;
var title = attr.Title;
var version = GetVersion();
if (version != null)
{
title += " v" + version;
}
#if DEBUG
title += " DEBUG";
#endif
var date = GetBuildDate();
if (date != DateTime.MinValue)
{
title += date.ToString(" [dd.MM.yyyy]");
}
return title;
}
static string GetVersion()
{
var attr = GetAssemblyAttribute<AssemblyFileVersionAttribute>();
if (attr == null) return null;
var parts = new List<string>(attr.Version.TrimEnd('0', '.').Split('.'));
if (parts.Count == 0) return null;
while (parts.Count < 3)
{
parts.Add("0");
}
return String.Join(".", parts.ToArray());
}
static DateTime GetBuildDate()
{
try
{
// Read it from the PE header
var buffer = File.ReadAllBytes(Assembly.GetExecutingAssembly().Location);
var pe = BitConverter.ToInt32(buffer, 0x3C);
var time = BitConverter.ToInt32(buffer, pe + 8);
return (new DateTime(1970, 1, 1, 0, 0, 0, 0)).AddSeconds(time);
}
catch
{
return DateTime.MinValue;
}
}
static string GetCopyright()
{
var attr = GetAssemblyAttribute<AssemblyCopyrightAttribute>();
return (attr == null) ? String.Empty : attr.Copyright;
}
static string GetDescription()
{
var attr = GetAssemblyAttribute<AssemblyDescriptionAttribute>();
return (attr == null) ? String.Empty : attr.Description;
}
static void Help(bool interactive)
{
if (!interactive)
{
Console.WriteLine(GetTitle());
Console.WriteLine(GetCopyright());
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine(" hosts - run hosts command interpreter");
Console.WriteLine(" hosts <command> <params> - execute hosts command");
}
Console.WriteLine();
Console.WriteLine("Commands:");
Console.WriteLine(" add <host> <aliases> <addr> # <comment> - add new host");
Console.WriteLine(" set <host|mask> <addr> # <comment> - set ip and comment for host");
Console.WriteLine(" rem <host|mask> - remove host");
Console.WriteLine(" on <host|mask> - enable host");
Console.WriteLine(" off <host|mask> - disable host");
Console.WriteLine(" view [all] <mask> - display enabled and visible, or all hosts");
Console.WriteLine(" hide <host|mask> - hide host from 'hosts view'");
Console.WriteLine(" show <host|mask> - show host in 'hosts view'");
Console.WriteLine(" print - display raw hosts file");
Console.WriteLine(" format - format host rows");
Console.WriteLine(" clean - format and remove all comments");
Console.WriteLine(" rollback - rollback last operation");
Console.WriteLine(" backup - backup hosts file");
Console.WriteLine(" restore - restore hosts file from backup");
Console.WriteLine(" empty - empty hosts file");
if (!IsUnix)
{
Console.WriteLine(" open - open hosts file in notepad");
}
if (interactive)
{
Console.WriteLine(" exit - exit from command interpreter");
}
Console.WriteLine();
Console.WriteLine("Details:\n " + GetDescription());
}
static HostsEditor Hosts;
static Queue<string> ArgsQueue;
static void View(string mask, bool? visibleOnly = null, bool? enabledOnly = null)
{
int enabled = 0;
int disabled = 0;
int hidden = 0;
if (mask != "*") Console.WriteLine("Mask: {0}\n", mask);
Hosts.RemoveInvalid();
Hosts.ResetFormat();
List<HostsItem> FoundLines = Hosts.GetMatched(mask);
foreach (HostsItem Line in FoundLines)
{
if (Line.Enabled) enabled++; else disabled++;
if (Line.Hidden) hidden++;
if (visibleOnly != null && visibleOnly.Value == Line.Hidden) continue;
if (enabledOnly != null && enabledOnly.Value != Line.Enabled) continue;
Console.WriteLine(Line);
}
if(FoundLines.Count > 0) Console.WriteLine();
Console.WriteLine("Enabled: {0,-4} Disabled: {1,-4} Hidden: {2,-4}", enabled, disabled, hidden);
}
static void Run(string[] args, bool interactive)
{
try
{
ArgsQueue = new Queue<string>(args);
string Mode = (ArgsQueue.Count > 0) ? ArgsQueue.Dequeue().ToLower() : "help";
string HostsFile = GetHostsFileName();
string BackupHostsFile = HostsFile + ".backup";
string RollbackHostsFile = HostsFile + ".rollback";
// Check permissions
FileIOPermission HostsPermissions = new FileIOPermission(FileIOPermissionAccess.AllAccess, HostsFile);
if (!SecurityManager.IsGranted(HostsPermissions)) throw new Exception("No write permission to the hosts file");
// Create default hosts file if not exists
if (!File.Exists(HostsFile))
{
File.WriteAllText(HostsFile, new HostsItem("127.0.0.1", "localhost").ToString());
}
switch (Mode)
{
case "open":
if (IsUnix) break;
var exe = FileAssoc.GetExecutable(".txt") ?? "notepad";
Process.Start(exe, '"' + HostsFile + '"');
return;
case "backup":
if (ArgsQueue.Count > 0) BackupHostsFile = HostsFile + "." + ArgsQueue.Dequeue().ToLower();
File.Copy(HostsFile, BackupHostsFile, true);
Console.WriteLine("[OK] Hosts file backed up successfully");
return;
case "restore":
if (ArgsQueue.Count > 0) BackupHostsFile = HostsFile + "." + ArgsQueue.Dequeue().ToLower();
if (!File.Exists(BackupHostsFile)) throw new Exception("Backup file is not exists");
File.Copy(HostsFile, RollbackHostsFile, true);
File.Copy(BackupHostsFile, HostsFile, true);
Console.WriteLine("[OK] Hosts file restored successfully");
return;
case "rollback":
if (!File.Exists(RollbackHostsFile)) throw new Exception("Rollback file is not exists");
if (File.Exists(HostsFile)) File.Delete(HostsFile);
File.Move(RollbackHostsFile, HostsFile);
Console.WriteLine("[OK] Hosts file rolled back successfully");
return;
case "empty":
case "recreate":
File.Copy(HostsFile, RollbackHostsFile, true);
File.WriteAllText(HostsFile, new HostsItem("127.0.0.1", "localhost").ToString());
Console.WriteLine("[OK] New hosts file created successfully");
return;
case "help":
Help(interactive);
return;
}
// Try to create backup on first run
if (!File.Exists(BackupHostsFile))
{
try
{
File.Copy(HostsFile, BackupHostsFile);
}
catch {}
}
Hosts = new HostsEditor(HostsFile);
Hosts.Load();
List<HostsItem> Lines;
switch (Mode)
{
case "print":
case "raw":
case "file":
Console.WriteLine(File.ReadAllText(Hosts.FileName, Hosts.Encoding));
return;
case "list":
case "view":
case "select":
case "ls":
RunListMode(interactive);
return;
case "format":
Hosts.ResetFormat();
Console.WriteLine("[OK] Hosts file formatted successfully");
break;
case "clean":
Hosts.RemoveInvalid();
Hosts.ResetFormat();
Console.WriteLine("[OK] Hosts file cleaned successfully");
break;
case "add":
case "new":
RunAddMode();
break;
case "set":
RunUpdateMode(true);
break;
case "change":
case "update":
case "upd":
RunUpdateMode(false);
break;
case "rem":
case "rm":
case "remove":
case "del":
case "delete":
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(args[1]);
if (Lines.Count == 0) throw new HostNotFoundException(args[1]);
foreach (HostsItem Line in Lines)
{
Hosts.Remove(Line);
Console.WriteLine("[REMOVED] {0} {1}", Line.IP.ToString(), Line.Aliases.ToString());
}
break;
case "on":
case "enable":
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(args[1]);
if (Lines.Count == 0) throw new HostNotFoundException(args[1]);
foreach (HostsItem Line in Lines)
{
Line.Enabled = true;
Console.WriteLine("[ENABLED] {0} {1}", Line.IP.ToString(), Line.Aliases.ToString());
}
break;
case "off":
case "disable":
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(args[1]);
if (Lines.Count == 0) throw new HostNotFoundException(args[1]);
foreach (HostsItem Line in Lines)
{
Line.Enabled = false;
Console.WriteLine("[DISABLED] {0} {1}", Line.IP.ToString(), Line.Aliases.ToString());
}
break;
case "hide":
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(args[1]);
if (Lines.Count == 0) throw new HostNotFoundException(args[1]);
foreach (HostsItem Line in Lines)
{
Line.Hidden = true;
Console.WriteLine("[HIDDEN] {0} {1}", Line.IP.ToString(), Line.Aliases.ToString());
}
break;
case "show":
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(args[1]);
if (Lines.Count == 0) throw new HostNotFoundException(args[1]);
foreach (HostsItem Line in Lines)
{
Line.Hidden = false;
Console.WriteLine("[SHOWN] {0} {1}", Line.IP.ToString(), Line.Aliases.ToString());
}
break;
default:
Console.WriteLine("[ERROR] Unknown command");
Help(interactive);
return;
}
File.Copy(HostsFile, RollbackHostsFile, true);
Hosts.Save();
}
catch (HostNotSpecifiedException)
{
Console.WriteLine("[ERROR] Host not specified");
}
catch (HostNotFoundException e)
{
Console.WriteLine("[ERROR] Host '{0}' not found", e.Host);
}
catch (Exception e)
{
#if DEBUG
Console.WriteLine("[ERROR] " + e.ToString());
#else
Console.WriteLine("[ERROR] " + e.Message);
#endif
}
}
static void RunListMode(bool interactive)
{
if (!interactive)
{
Console.WriteLine(GetTitle());
Console.WriteLine("Hosts file: " + Hosts.FileName.ToLower());
Console.WriteLine();
}
bool? visibleOnly = true;
bool? enabledOnly = true;
string mask = "*";
if (ArgsQueue.Count > 0)
{
string arg = ArgsQueue.Dequeue().ToLower();
if (arg == "all")
{
visibleOnly = null;
enabledOnly = null;
arg = (ArgsQueue.Count > 0) ? ArgsQueue.Dequeue().ToLower() : "*";
}
mask = arg;
if (!mask.StartsWith("*")) mask = '*' + mask;
if (!mask.EndsWith("*")) mask += '*';
}
View(mask, visibleOnly, enabledOnly);
}
static void AddHostsItem(NetAddress address, HostAliases aliases, string comment)
{
if (aliases.Count == 0) throw new HostNotSpecifiedException();
// Remove duplicates
foreach (HostName host in aliases)
{
var lines = Hosts.FindAll(item => item.Valid && item.IP.Type == address.Type && item.Aliases.Contains(host));
foreach (var line in lines)
{
if (line.Aliases.Count == 1)
{
Hosts.Remove(line);
Console.WriteLine("[REMOVED] {0} {1}", line.IP.ToString(), line.Aliases.ToString());
}
else
{
line.Aliases.Remove(host);
Console.WriteLine("[UPDATED] {0} {1}", line.IP.ToString(), line.Aliases.ToString());
}
}
}
// New host
var new_item = new HostsItem(address, aliases, comment == null ? "" : comment.Trim());
Hosts.Add(new_item);
Console.WriteLine("[ADDED] {0} {1}", new_item.IP.ToString(), new_item.Aliases.ToString());
}
static void RunAddMode()
{
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
HostAliases aliases = new HostAliases();
NetAddress address_ipv4 = null;
NetAddress address_ipv6 = null;
string comment = "";
bool in_comment = false;
while (ArgsQueue.Count > 0)
{
string arg = ArgsQueue.Dequeue();
if (in_comment)
{
comment += arg + " ";
continue;
}
if (arg.Length > 0 && arg[0] == '#')
{
in_comment = true;
comment = (arg.Length > 1) ? (arg.Substring(1) + " ") : "";
continue;
}
arg = arg.ToLower();
var address_test = NetAddress.TryCreate(arg);
if (address_test != null)
{
if (address_test.Type == NetAddressType.IPv4)
address_ipv4 = address_test;
else
address_ipv6 = address_test;
continue;
}
var hostname_test = HostName.TryCreate(arg);
if (hostname_test != null)
{
aliases.Add(hostname_test);
continue;
}
throw new Exception(String.Format("Unknown argument '{0}'", arg));
}
if (address_ipv4 == null && address_ipv6 == null)
{
address_ipv4 = new NetAddress("127.0.0.1");
}
if (address_ipv4 != null)
{
AddHostsItem(address_ipv4, aliases, comment.Trim());
}
if (address_ipv6 != null)
{
AddHostsItem(address_ipv6, aliases, comment.Trim());
}
}
static void RunUpdateMode(bool autoadd = false)
{
if (ArgsQueue.Count == 0) throw new HostNotSpecifiedException();
string mask = ArgsQueue.Dequeue();
List<HostsItem> lines = Hosts.GetMatched(mask);
if (lines.Count == 0 && (!autoadd || mask.IndexOf('*') != -1))
{
throw new HostNotFoundException(mask);
}
NetAddress address_ipv4 = null;
NetAddress address_ipv6 = null;
string comment = null;
bool in_comment = false;
while (ArgsQueue.Count > 0)
{
string arg = ArgsQueue.Dequeue();
if (in_comment)
{
comment += arg + " ";
continue;
}
if (arg.Length > 0 && arg[0] == '#')
{
in_comment = true;
comment = (arg.Length > 1) ? (arg.Substring(1) + " ") : "";
continue;
}
arg = arg.ToLower();
NetAddress address_test = NetAddress.TryCreate(arg);
if (address_test != null)
{
if (address_test.Type == NetAddressType.IPv4)
address_ipv4 = address_test;
else
address_ipv6 = address_test;
continue;
}
}
var ipv4_added = false;
var ipv6_added = false;
foreach (HostsItem line in lines)
{
if (address_ipv4 == null && address_ipv6 == null && comment != null)
{
// Update comments only
line.Comment = comment;
Console.WriteLine("[UPDATED] {0} {1}", line.IP.ToString(), line.Aliases.ToString());
continue;
}
if (address_ipv4 != null && line.IP.Type == NetAddressType.IPv4)
{
ipv4_added = true;
line.IP = address_ipv4;
if (comment != null) line.Comment = comment;
Console.WriteLine("[UPDATED] {0} {1}", line.IP.ToString(), line.Aliases.ToString());
}
if (address_ipv6 != null && line.IP.Type == NetAddressType.IPv6)
{
ipv6_added = true;
line.IP = address_ipv6;
if (comment != null) line.Comment = comment;
Console.WriteLine("[UPDATED] {0} {1}", line.IP.ToString(), line.Aliases.ToString());
}
}
if (address_ipv4 != null && !ipv4_added && autoadd)
{
AddHostsItem(address_ipv4, new HostAliases(mask), comment);
}
if (address_ipv6 != null && !ipv6_added && autoadd)
{
AddHostsItem(address_ipv6, new HostAliases(mask), comment);
}
}
static void Main(string[] args)
{
try
{
IsUnix = (Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX);
if (args.Length > 0)
{
Run(args, false);
}
else
{
Console.WriteLine(GetTitle());
Console.WriteLine(GetCopyright());
Console.WriteLine("Hosts file: " + GetHostsFileName().ToLower());
Console.WriteLine();
while (true)
{
Console.Write("hosts> ");
var command = (Console.ReadLine() ?? "").Replace("\0", "").Trim();
if (command == "") continue;
if (command.StartsWith("hosts "))
{
command = command.Substring(6).TrimStart();
}
if (command == "exit" || command == "quit") break;
args = command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Run(args, true);
Console.WriteLine();
}
}
}
catch (Exception e)
{
#if DEBUG
Console.WriteLine("[ERROR] " + e.ToString());
#else
Console.WriteLine("[ERROR] " + e.Message);
#endif
Console.ReadKey();
}
}
}
}