-
Notifications
You must be signed in to change notification settings - Fork 735
/
Copy pathHostsFileEditor.cs
135 lines (111 loc) · 4.46 KB
/
HostsFileEditor.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
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using log4net;
using NETworkManager.Utilities;
namespace NETworkManager.Models.HostsFileEditor;
public static class HostsFileEditor
{
#region Events
public static event EventHandler HostsFileChanged;
private static void OnHostsFileChanged()
{
Log.Debug("OnHostsFileChanged - Hosts file changed.");
HostsFileChanged?.Invoke(null, EventArgs.Empty);
}
#endregion
#region Variables
private static readonly ILog Log = LogManager.GetLogger(typeof(HostsFileEditor));
private static readonly FileSystemWatcher HostsFileWatcher;
/// <summary>
/// Path to the hosts file.
/// </summary>
private static string HostsFilePath => Path.Combine(Environment.SystemDirectory, "drivers", "etc", "hosts");
/// <summary>
/// Example values in the hosts file that should be ignored.
/// </summary>
private static readonly HashSet<(string IPAddress, string Hostname)> ExampleValuesToIgnore =
[
("102.54.94.97", "rhino.acme.com"),
("38.25.63.10", "x.acme.com")
];
/// <summary>
/// Regex to match a hosts file entry with optional comments, supporting IPv4, IPv6, and hostnames
/// </summary>
private static readonly Regex HostsFileEntryRegex = new(RegexHelper.HostsEntryRegex);
#endregion
#region Constructor
static HostsFileEditor()
{
// Create a file system watcher to monitor changes to the hosts file
try
{
Log.Debug("HostsFileEditor - Creating file system watcher for hosts file...");
// Create the file system watcher
HostsFileWatcher = new FileSystemWatcher();
HostsFileWatcher.Path = Path.GetDirectoryName(HostsFilePath) ?? throw new InvalidOperationException("Hosts file path is invalid.");
HostsFileWatcher.Filter = Path.GetFileName(HostsFilePath) ?? throw new InvalidOperationException("Hosts file name is invalid.");
HostsFileWatcher.NotifyFilter = NotifyFilters.LastWrite;
// Maybe fired twice. This is a known bug/feature.
// See: https://stackoverflow.com/questions/1764809/filesystemwatcher-changed-event-is-raised-twice
HostsFileWatcher.Changed += (_, _) => OnHostsFileChanged();
// Enable the file system watcher
HostsFileWatcher.EnableRaisingEvents = true;
Log.Debug("HostsFileEditor - File system watcher for hosts file created.");
}
catch (Exception ex)
{
Log.Error("Failed to create file system watcher for hosts file.", ex);
}
}
#endregion
#region Methods
public static Task<IEnumerable<HostsFileEntry>> GetHostsFileEntriesAsync()
{
return Task.Run(GetHostsFileEntries);
}
/// <summary>
///
/// </summary>
/// <returns></returns>
private static IEnumerable<HostsFileEntry> GetHostsFileEntries()
{
var hostsFileLines = File.ReadAllLines(HostsFilePath);
// Parse the hosts file content
var entries = new List<HostsFileEntry>();
foreach (var line in hostsFileLines)
{
var result = HostsFileEntryRegex.Match(line.Trim());
if (result.Success)
{
Log.Debug("GetHostsFileEntries - Line matched: " + line);
var entry = new HostsFileEntry
{
IsEnabled = !result.Groups[1].Value.Equals("#"),
IPAddress = result.Groups[2].Value,
Hostname = result.Groups[3].Value.Replace(@"\s", "").Trim(),
Comment = result.Groups[4].Value.TrimStart('#'),
Line = line
};
// Skip example entries
if(!entry.IsEnabled)
{
if (ExampleValuesToIgnore.Contains((entry.IPAddress, entry.Hostname)))
{
Log.Debug("GetHostsFileEntries - Matched example entry. Skipping...");
continue;
}
}
entries.Add(entry);
}
else
{
Log.Debug("GetHostsFileEntries - Line not matched: " + line);
}
}
return entries;
}
#endregion
}