-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathProgram.cs
More file actions
707 lines (653 loc) · 20.2 KB
/
Copy pathProgram.cs
File metadata and controls
707 lines (653 loc) · 20.2 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Text;
using Microsoft.Win32;
using System.Reflection;
using System.Diagnostics;
using System.Security.Permissions;
using System.Security;
using System.Text.RegularExpressions;
namespace Hosts;
class NoWritePermissionException : ApplicationException
{
public override string Message => "No write permission to modify the hosts file.";
}
class HostNotSpecifiedException : ApplicationException
{
public override string Message => "Host is not specified.";
}
class HostNotFoundException : ApplicationException
{
public string Host { get; protected set; }
public NetAddressType IpType { get; protected set; }
public HostNotFoundException(string host, NetAddressType ip_type = NetAddressType.None)
{
Host = host;
IpType = ip_type;
}
public override string Message => IpType switch
{
NetAddressType.IPv4 => $"Host '{Host}' is not found for IPv4.",
NetAddressType.IPv6 => $"Host '{Host}' is not found for IPv6.",
_ => $"Host '{Host}' is not found.",
};
}
static class Program
{
static bool IsShell = false;
static readonly bool IsUnix = (Environment.OSVersion.Platform == PlatformID.Unix) || (Environment.OSVersion.Platform == PlatformID.MacOSX);
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").ToLower();
}
catch (Exception e)
{
throw new Exception("Cannot get path to hosts file from registry.", e);
}
}
static bool MakeWritable(string filename)
{
try
{
if (File.Exists(filename))
{
// Remove ReadOnly flag if it is there.
FileAttributes attributes = File.GetAttributes(filename);
if ((attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
File.SetAttributes(filename, attributes & ~FileAttributes.ReadOnly);
}
}
File.OpenWrite(filename).Close();
return true;
}
catch
{
return false;
}
}
static void ForceCopy(string src, string dst)
{
MakeWritable(dst);
File.Copy(src, dst, true);
}
static void Help()
{
if (!IsShell) Console.WriteLine($"""
{ProgramMeta.GetTitle()}
{ProgramMeta.GetCopyright()}
https://veg.by/projects/hostscmd/
{ProgramMeta.GetDescription()}
Usage:
hosts [shell] Run interactive shell.
hosts <command> Execute a command.
""");
Console.WriteLine("""
Commands:
add <host> [aliases] [ipv4] [ipv6] # [comment] Add new host.
set <host|mask> [ipv4] [ipv6] # [comment] Update host.
del <host|mask> Delete host.
on <host|mask> Enable host.
off <host|mask> Disable host.
list [--all] [mask] Display active or all hosts.
hide <host|mask> Hide host from 'list'.
unhide <host|mask> Unhide host.
print Display raw hosts file.
format Reformat hosts file.
clean Reformat and delete all comments.
rollback Rollback last operation.
backup Backup hosts file.
restore Restore hosts file from backup.
reset Reset hosts file (remove everything).
""");
if (!IsUnix) Console.WriteLine("""
open Open hosts file in notepad.
""");
if (IsShell) Console.WriteLine("""
exit Exit from the shell.
""");
}
static string LaxHostArg(string host)
{
// Let's be a bit less punishing and strip HTTP protocol.
return Regex.Replace(host, @"^https?://([^/]+)/?$", "$1", RegexOptions.IgnoreCase);
}
static HostsEditor Hosts;
static bool Execute(List<string> args)
{
try
{
var args_queue = new Queue<string>(args);
var mode = (args_queue.Count > 0) ? args_queue.Dequeue().ToLower() : "help";
var hosts_file = Hosts.FileName;
var rollback_file = hosts_file + ".rollback";
switch (mode)
{
case "open" when (IsUnix):
{
var exe = FileAssoc.GetExecutable(".txt") ?? "notepad";
Process.Start(exe, '"' + hosts_file + '"');
return true;
}
case "apply":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (args_queue.Count == 0) throw new Exception("Applied file is not specified.");
var apply_file = args_queue.Dequeue();
if (!File.Exists(apply_file)) throw new Exception("Applied file does not exist.");
ForceCopy(hosts_file, rollback_file);
ForceCopy(apply_file, hosts_file);
Console.WriteLine("[OK] New hosts file has been applied successfully.");
return true;
}
case "backup":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
var backup_name = (args_queue.Count > 0 ? args_queue.Dequeue().ToLower() : "backup");
// On Windows, hosts.ics serves other purposes, so we can't store a backup there.
if (!IsUnix && backup_name == "ics") { throw new Exception("The backup name \"ics\" is not allowed."); }
var backup_file = hosts_file + "." + backup_name;
ForceCopy(hosts_file, backup_file);
Console.WriteLine("[OK] Hosts file has been backed up successfully.");
return true;
}
case "restore":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
var backup_name = (args_queue.Count > 0 ? args_queue.Dequeue().ToLower() : "backup");
// On Windows, hosts.ics serves other purposes, so we can't store a backup there.
if (!IsUnix && backup_name == "ics") { throw new Exception("The backup name \"ics\" is not allowed."); }
var backup_file = hosts_file + "." + backup_name;
if (!File.Exists(backup_file)) throw new Exception("Backup file does not exist.");
ForceCopy(hosts_file, rollback_file);
ForceCopy(backup_file, hosts_file);
Console.WriteLine("[OK] Hosts file has been restored successfully.");
return true;
}
case "rollback":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (!File.Exists(rollback_file)) throw new Exception("Rollback file does not exist.");
if (File.Exists(hosts_file)) File.Delete(hosts_file);
File.Move(rollback_file, hosts_file);
Console.WriteLine("[OK] Hosts file has been rolled back successfully.");
return true;
}
case "reset":
case "empty":
case "recreate":
case "erase":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
ForceCopy(hosts_file, rollback_file);
File.WriteAllText(hosts_file, new HostsItem("127.0.0.1", "localhost").ToString());
Console.WriteLine("[OK] New hosts file has been created successfully.");
return true;
}
case "help":
case "--help":
case "-h":
case "/?":
{
Help();
return true;
}
}
Hosts.Load();
List<HostsItem> Lines;
switch (mode)
{
case "print":
case "raw":
case "file":
{
Console.WriteLine(File.ReadAllText(Hosts.FileName, Hosts.Encoding));
return true;
}
case "list":
case "view":
case "select":
case "ls":
case "show":
{
RunListMode(args_queue.ToList());
return true;
}
case "format":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
Hosts.ResetFormat();
Console.WriteLine("[OK] Hosts file has been formatted successfully.");
break;
}
case "clean":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
Hosts.RemoveInvalid();
Hosts.ResetFormat();
Console.WriteLine("[OK] Hosts file has been cleaned successfully.");
break;
}
case "add":
case "new":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
RunAddMode(args_queue.ToList());
break;
}
case "set":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
RunUpdateMode(args_queue.ToList(), true);
break;
}
case "change":
case "update":
case "upd":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
RunUpdateMode(args_queue.ToList(), false);
break;
}
case "rem":
case "rm":
case "remove":
case "del":
case "delete":
case "unset":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (args_queue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(LaxHostArg(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 (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (args_queue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(LaxHostArg(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 (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (args_queue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(LaxHostArg(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 (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (args_queue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(LaxHostArg(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 "unhide":
{
if (!MakeWritable(hosts_file)) throw new NoWritePermissionException();
if (args_queue.Count == 0) throw new HostNotSpecifiedException();
Lines = Hosts.GetMatched(LaxHostArg(args[1]));
if (Lines.Count == 0) throw new HostNotFoundException(args[1]);
foreach (HostsItem Line in Lines)
{
Line.Hidden = false;
Console.WriteLine("[UNHIDDEN] {0} {1}", Line.IP.ToString(), Line.Aliases.ToString());
}
break;
}
default:
{
Console.WriteLine($"[ERROR] Unknown command '{mode}'.\n");
Help();
return false;
}
}
MakeWritable(rollback_file);
ForceCopy(hosts_file, rollback_file);
Hosts.Save();
return true;
}
catch (Exception e)
{
#if DEBUG
Console.WriteLine("[ERROR] " + e.ToString());
#else
Console.WriteLine("[ERROR] " + e.Message);
#endif
return false;
}
}
static void RunListMode(List<string> args)
{
bool? visible_only = true;
bool? enabled_only = true;
string mask = null;
var args_queue = new Queue<string>(args);
while (args_queue.Count > 0)
{
string arg = args_queue.Dequeue().ToLower();
if (arg == "--all")
{
visible_only = null;
enabled_only = null;
}
else if (mask == null)
{
mask = LaxHostArg(arg);
if (!mask.StartsWith("*") && !mask.EndsWith("*"))
{
mask = '*' + mask + '*';
}
}
else
{
throw new Exception($"Unknown argument '{arg}'.");
}
}
View(mask ?? "*", visible_only, enabled_only);
}
static void View(string mask, bool? visible_only = null, bool? enabled_only = null)
{
int enabled = 0;
int disabled = 0;
int hidden = 0;
if (mask != "*") Console.WriteLine("Mask: {0}\n", mask);
Hosts.RemoveInvalid();
Hosts.ResetFormat();
List<HostsItem> found_lines = Hosts.GetMatched(mask);
foreach (HostsItem line in found_lines)
{
if (line.Enabled) enabled++; else disabled++;
if (line.Hidden) hidden++;
if (visible_only != null && visible_only.Value == line.Hidden) continue;
if (enabled_only != null && enabled_only.Value != line.Enabled) continue;
Console.WriteLine(line);
}
if (found_lines.Count > 0) Console.WriteLine();
Console.WriteLine("Enabled: {0,-4} Disabled: {1,-4} Hidden: {2,-4}", enabled, disabled, hidden);
}
static void AddHostsItem(NetAddress address, HostAliases aliases, string comment)
{
if (aliases.Count == 0) throw new HostNotSpecifiedException();
// Remove duplicates
var lines = Hosts.GetValid().FindAll(item => item.IP.Type == address.Type && item.Aliases.ContainsAny(aliases));
foreach (var line in lines)
{
if (!line.Aliases.Except(aliases).Any())
{
Hosts.Remove(line);
Console.WriteLine("[REMOVED] {0} {1}", line.IP.ToString(), line.Aliases.ToString());
}
else
{
line.Aliases.RemoveAll(aliases);
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(List<string> args)
{
if (args.Count == 0) throw new HostNotSpecifiedException();
HostAliases aliases = new HostAliases();
NetAddress address_ipv4 = null;
NetAddress address_ipv6 = null;
string comment = "";
bool in_comment = false;
var args_queue = new Queue<string>(args);
while (args_queue.Count > 0)
{
string arg = args_queue.Dequeue();
if (in_comment)
{
if (comment.Length > 0) { 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)
{
if (address_ipv4 != null) { throw new Exception("More than one IPv4 address is not allowed."); }
address_ipv4 = address_test;
}
else
{
if (address_ipv6 != null) { throw new Exception("More than one IPv6 address is not allowed."); }
address_ipv6 = address_test;
}
continue;
}
var hostname_test = HostName.TryCreate(LaxHostArg(arg));
if (hostname_test != null)
{
aliases.Add(hostname_test);
continue;
}
throw new Exception($"Unknown argument '{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(List<string> args, bool autoadd = false)
{
if (args.Count == 0) throw new HostNotSpecifiedException();
var args_queue = new Queue<string>(args);
string mask = LaxHostArg(args_queue.Dequeue());
NetAddress address_ipv4 = null;
NetAddress address_ipv6 = null;
string comment = null;
bool in_comment = false;
while (args_queue.Count > 0)
{
string arg = args_queue.Dequeue();
if (in_comment)
{
if (comment.Length > 0) { 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)
{
if (address_ipv4 != null) { throw new Exception("More than one IPv4 address is not allowed."); }
address_ipv4 = address_test;
}
else
{
if (address_ipv6 != null) { throw new Exception("More than one IPv6 address is not allowed."); }
address_ipv6 = address_test;
}
continue;
}
throw new Exception($"Unknown argument '{arg}'.");
}
if (address_ipv4 == null && address_ipv6 == null && comment == null)
{
throw new Exception("Not enough arguments.");
}
List<HostsItem> lines = Hosts.GetMatched(mask);
if (!autoadd || mask.IndexOf('*') != -1)
{
if (lines.Count == 0) { throw new HostNotFoundException(mask); }
if (address_ipv4 != null && !lines.Any(item => item.IP.Type == NetAddressType.IPv4))
{
throw new HostNotFoundException(mask, NetAddressType.IPv4);
}
if (address_ipv6 != null && !lines.Any(item => item.IP.Type == NetAddressType.IPv6))
{
throw new HostNotFoundException(mask, NetAddressType.IPv6);
}
}
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 (autoadd && address_ipv4 != null && !ipv4_added)
{
AddHostsItem(address_ipv4, new HostAliases(mask), comment);
}
if (autoadd && address_ipv6 != null && !ipv6_added)
{
AddHostsItem(address_ipv6, new HostAliases(mask), comment);
}
}
static void Init()
{
Hosts = new HostsEditor(GetHostsFileName());
try
{
// Create default hosts file if not exists
var hosts_file = Hosts.FileName;
if (!File.Exists(hosts_file))
{
File.WriteAllText(hosts_file, new HostsItem("127.0.0.1", "localhost").ToString());
}
// Try to create backup on first run
var backup_file = hosts_file + ".backup";
if (!File.Exists(backup_file))
{
ForceCopy(hosts_file, backup_file);
}
}
catch
{
throw new Exception("The hosts file does not exist.");
}
}
static int Main(string[] args)
{
try
{
Init();
if (args.Length > 0 && args[0].ToLower() != "shell")
{
return Execute(args.ToList()) ? 0 : 1;
}
else
{
IsShell = true;
Console.WriteLine($"""
{ProgramMeta.GetTitle()}
{ProgramMeta.GetCopyright()}
Hosts file: {Hosts.FileName.ToLower()}
""");
while (true)
{
Console.Write("hosts> ");
var command = Console.ReadLine();
if (command == null) { break; } // Ctrl+C or Ctrl+Break?
command = command.Replace("\0", "").Trim(); // A workaround for an ancient Mono bug.
if (command == "") { continue; }
if (command.StartsWith("hosts ", StringComparison.OrdinalIgnoreCase))
{
command = command.Substring(6).TrimStart();
}
if (command.ToLower() is "exit" or "quit") { break; }
Execute(command.Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries).ToList());
Console.WriteLine();
}
return 0;
}
}
catch (Exception e)
{
#if DEBUG
Console.WriteLine("[ERROR] " + e.ToString());
#else
Console.WriteLine("[ERROR] " + e.Message);
#endif
return 1;
}
}
}