2022-10-13 13:05:43 +02:00
|
|
|
// Copyright (c) Microsoft Corporation
|
|
|
|
|
// The Microsoft Corporation licenses this file to you under the MIT license.
|
|
|
|
|
// See the LICENSE file in the project root for more information.
|
|
|
|
|
|
|
|
|
|
using System;
|
|
|
|
|
using System.Collections.Generic;
|
2022-10-24 20:09:00 +02:00
|
|
|
using System.Diagnostics;
|
2022-10-13 13:05:43 +02:00
|
|
|
using System.IO;
|
|
|
|
|
using System.IO.Abstractions;
|
|
|
|
|
using System.Linq;
|
|
|
|
|
using System.Net.NetworkInformation;
|
|
|
|
|
using System.Text;
|
|
|
|
|
using System.Threading;
|
|
|
|
|
using System.Threading.Tasks;
|
2024-09-16 16:09:43 -04:00
|
|
|
|
2024-04-26 19:41:44 +02:00
|
|
|
using HostsUILib.Exceptions;
|
|
|
|
|
using HostsUILib.Models;
|
|
|
|
|
using HostsUILib.Settings;
|
2022-10-24 20:09:00 +02:00
|
|
|
using Microsoft.Win32;
|
2022-10-13 13:05:43 +02:00
|
|
|
|
2024-04-26 19:41:44 +02:00
|
|
|
namespace HostsUILib.Helpers
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
2024-12-19 09:22:41 +08:00
|
|
|
public partial class HostsService : IHostsService, IDisposable
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
2025-11-05 09:42:31 +01:00
|
|
|
private const int DefaultBufferSize = 4096; // From System.IO.File source code
|
2022-10-13 13:05:43 +02:00
|
|
|
|
|
|
|
|
private readonly SemaphoreSlim _asyncLock = new SemaphoreSlim(1, 1);
|
|
|
|
|
private readonly IFileSystem _fileSystem;
|
|
|
|
|
private readonly IUserSettings _userSettings;
|
|
|
|
|
private readonly IElevationHelper _elevationHelper;
|
|
|
|
|
private readonly IFileSystemWatcher _fileSystemWatcher;
|
2025-11-05 09:42:31 +01:00
|
|
|
private readonly IBackupManager _backupManager;
|
2022-10-13 13:05:43 +02:00
|
|
|
private readonly string _hostsFilePath;
|
|
|
|
|
private bool _disposed;
|
|
|
|
|
|
|
|
|
|
public string HostsFilePath => _hostsFilePath;
|
|
|
|
|
|
|
|
|
|
public event EventHandler FileChanged;
|
|
|
|
|
|
2023-06-06 17:11:37 +02:00
|
|
|
public Encoding Encoding => _userSettings.Encoding == HostsEncoding.Utf8 ? new UTF8Encoding(false) : new UTF8Encoding(true);
|
|
|
|
|
|
2022-10-13 13:05:43 +02:00
|
|
|
public HostsService(
|
|
|
|
|
IFileSystem fileSystem,
|
|
|
|
|
IUserSettings userSettings,
|
2025-11-05 09:42:31 +01:00
|
|
|
IElevationHelper elevationHelper,
|
|
|
|
|
IBackupManager backupManager)
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
|
|
|
|
_fileSystem = fileSystem;
|
|
|
|
|
_userSettings = userSettings;
|
|
|
|
|
_elevationHelper = elevationHelper;
|
2025-11-05 09:42:31 +01:00
|
|
|
_backupManager = backupManager;
|
2022-10-13 13:05:43 +02:00
|
|
|
|
|
|
|
|
_hostsFilePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), @"System32\drivers\etc\hosts");
|
|
|
|
|
|
2024-11-11 10:42:40 +01:00
|
|
|
_fileSystemWatcher = _fileSystem.FileSystemWatcher.New();
|
2022-10-13 13:05:43 +02:00
|
|
|
_fileSystemWatcher.Path = _fileSystem.Path.GetDirectoryName(HostsFilePath);
|
|
|
|
|
_fileSystemWatcher.Filter = _fileSystem.Path.GetFileName(HostsFilePath);
|
|
|
|
|
_fileSystemWatcher.NotifyFilter = NotifyFilters.LastWrite;
|
|
|
|
|
_fileSystemWatcher.Changed += FileSystemWatcher_Changed;
|
|
|
|
|
_fileSystemWatcher.EnableRaisingEvents = true;
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-23 21:54:45 +02:00
|
|
|
public async Task<HostsData> ReadAsync()
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
|
|
|
|
var entries = new List<Entry>();
|
|
|
|
|
var unparsedBuilder = new StringBuilder();
|
2023-06-23 21:54:45 +02:00
|
|
|
var splittedEntries = false;
|
2022-10-13 13:05:43 +02:00
|
|
|
|
2025-11-05 09:42:31 +01:00
|
|
|
if (!_fileSystem.File.Exists(HostsFilePath))
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
2023-06-23 21:54:45 +02:00
|
|
|
return new HostsData(entries, unparsedBuilder.ToString(), false);
|
2022-10-13 13:05:43 +02:00
|
|
|
}
|
|
|
|
|
|
2023-06-06 17:11:37 +02:00
|
|
|
var lines = await _fileSystem.File.ReadAllLinesAsync(HostsFilePath, Encoding);
|
2022-10-13 13:05:43 +02:00
|
|
|
|
2023-06-23 21:54:45 +02:00
|
|
|
var id = 0;
|
|
|
|
|
|
2022-10-13 13:05:43 +02:00
|
|
|
for (var i = 0; i < lines.Length; i++)
|
|
|
|
|
{
|
|
|
|
|
var line = lines[i];
|
|
|
|
|
|
|
|
|
|
if (string.IsNullOrWhiteSpace(line))
|
|
|
|
|
{
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-23 21:54:45 +02:00
|
|
|
var entry = new Entry(id, line);
|
2022-10-13 13:05:43 +02:00
|
|
|
|
|
|
|
|
if (entry.Valid)
|
|
|
|
|
{
|
|
|
|
|
entries.Add(entry);
|
2023-06-23 21:54:45 +02:00
|
|
|
id++;
|
|
|
|
|
}
|
|
|
|
|
else if (entry.Validate(false))
|
|
|
|
|
{
|
|
|
|
|
foreach (var hostsChunk in entry.SplittedHosts.Chunk(Consts.MaxHostsCount))
|
|
|
|
|
{
|
|
|
|
|
var clonedEntry = entry.Clone();
|
|
|
|
|
clonedEntry.Id = id;
|
|
|
|
|
clonedEntry.Hosts = string.Join(' ', hostsChunk);
|
|
|
|
|
entries.Add(clonedEntry);
|
|
|
|
|
id++;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
splittedEntries = true;
|
2022-10-13 13:05:43 +02:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
if (unparsedBuilder.Length > 0)
|
|
|
|
|
{
|
|
|
|
|
unparsedBuilder.Append(Environment.NewLine);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
unparsedBuilder.Append(line);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-06-23 21:54:45 +02:00
|
|
|
return new HostsData(entries, unparsedBuilder.ToString(), splittedEntries);
|
2022-10-13 13:05:43 +02:00
|
|
|
}
|
|
|
|
|
|
2023-09-08 17:25:36 +02:00
|
|
|
public async Task WriteAsync(string additionalLines, IEnumerable<Entry> entries)
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
|
|
|
|
if (!_elevationHelper.IsElevated)
|
|
|
|
|
{
|
2023-09-08 17:25:36 +02:00
|
|
|
throw new NotRunningElevatedException();
|
2022-10-13 13:05:43 +02:00
|
|
|
}
|
|
|
|
|
|
2024-11-11 10:42:40 +01:00
|
|
|
if (_fileSystem.FileInfo.New(HostsFilePath).IsReadOnly)
|
2023-11-03 17:10:26 +01:00
|
|
|
{
|
|
|
|
|
throw new ReadOnlyHostsException();
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-13 13:05:43 +02:00
|
|
|
var lines = new List<string>();
|
|
|
|
|
|
|
|
|
|
if (entries.Any())
|
|
|
|
|
{
|
|
|
|
|
var addressPadding = entries.Max(e => e.Address.Length) + 1;
|
|
|
|
|
var hostsPadding = entries.Max(e => e.Hosts.Length) + 1;
|
|
|
|
|
var anyDisabled = entries.Any(e => !e.Active);
|
|
|
|
|
|
|
|
|
|
foreach (var e in entries)
|
|
|
|
|
{
|
|
|
|
|
var lineBuilder = new StringBuilder();
|
|
|
|
|
|
|
|
|
|
if (!e.Valid)
|
|
|
|
|
{
|
2023-06-05 12:02:32 +02:00
|
|
|
lineBuilder.Append(e.Line);
|
2022-10-13 13:05:43 +02:00
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
if (!e.Active)
|
|
|
|
|
{
|
|
|
|
|
lineBuilder.Append('#').Append(' ');
|
|
|
|
|
}
|
2025-08-19 00:58:10 -05:00
|
|
|
else if (anyDisabled && !_userSettings.NoLeadingSpaces)
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
|
|
|
|
lineBuilder.Append(' ').Append(' ');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
lineBuilder.Append(e.Address.PadRight(addressPadding));
|
|
|
|
|
lineBuilder.Append(string.Join(' ', e.Hosts).PadRight(hostsPadding));
|
|
|
|
|
|
|
|
|
|
if (e.Comment != string.Empty)
|
|
|
|
|
{
|
|
|
|
|
lineBuilder.Append('#').Append(' ');
|
|
|
|
|
lineBuilder.Append(e.Comment);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
lines.Add(lineBuilder.ToString().TrimEnd());
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (!string.IsNullOrWhiteSpace(additionalLines))
|
|
|
|
|
{
|
2023-06-06 17:11:37 +02:00
|
|
|
if (_userSettings.AdditionalLinesPosition == HostsAdditionalLinesPosition.Top)
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
|
|
|
|
lines.Insert(0, additionalLines);
|
|
|
|
|
}
|
2023-06-06 17:11:37 +02:00
|
|
|
else if (_userSettings.AdditionalLinesPosition == HostsAdditionalLinesPosition.Bottom)
|
2022-10-13 13:05:43 +02:00
|
|
|
{
|
|
|
|
|
lines.Add(additionalLines);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
await _asyncLock.WaitAsync();
|
|
|
|
|
_fileSystemWatcher.EnableRaisingEvents = false;
|
2025-11-05 09:42:31 +01:00
|
|
|
_backupManager.Create(HostsFilePath);
|
2022-10-13 13:05:43 +02:00
|
|
|
|
2024-08-16 20:36:26 +02:00
|
|
|
// FileMode.OpenOrCreate is necessary to prevent UnauthorizedAccessException when the hosts file is hidden
|
2025-11-05 09:42:31 +01:00
|
|
|
using var stream = _fileSystem.FileStream.New(HostsFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read, DefaultBufferSize, FileOptions.Asynchronous);
|
2024-08-16 20:36:26 +02:00
|
|
|
using var writer = new StreamWriter(stream, Encoding);
|
|
|
|
|
foreach (var line in lines)
|
|
|
|
|
{
|
|
|
|
|
await writer.WriteLineAsync(line.AsMemory());
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
stream.SetLength(stream.Position);
|
|
|
|
|
await writer.FlushAsync();
|
2022-10-13 13:05:43 +02:00
|
|
|
}
|
|
|
|
|
finally
|
|
|
|
|
{
|
|
|
|
|
_fileSystemWatcher.EnableRaisingEvents = true;
|
|
|
|
|
_asyncLock.Release();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<bool> PingAsync(string address)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
using var ping = new Ping();
|
|
|
|
|
var reply = await ping.SendPingAsync(address, 4000); // 4000 is the default ping timeout for ping.exe
|
|
|
|
|
return reply.Status == IPStatus.Success;
|
|
|
|
|
}
|
|
|
|
|
catch
|
|
|
|
|
{
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-24 20:09:00 +02:00
|
|
|
public void OpenHostsFile()
|
|
|
|
|
{
|
|
|
|
|
var notepadFallback = false;
|
|
|
|
|
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
// Try to open in default editor
|
|
|
|
|
var key = Registry.ClassesRoot.OpenSubKey("SystemFileAssociations\\text\\shell\\edit\\command");
|
|
|
|
|
if (key != null)
|
|
|
|
|
{
|
|
|
|
|
var commandPattern = key.GetValue(string.Empty).ToString(); // Default value
|
|
|
|
|
var file = null as string;
|
|
|
|
|
var args = null as string;
|
|
|
|
|
|
|
|
|
|
if (commandPattern.StartsWith('\"'))
|
|
|
|
|
{
|
|
|
|
|
var endQuoteIndex = commandPattern.IndexOf('\"', 1);
|
|
|
|
|
if (endQuoteIndex != -1)
|
|
|
|
|
{
|
|
|
|
|
file = commandPattern[1..endQuoteIndex];
|
|
|
|
|
args = commandPattern[(endQuoteIndex + 1)..].Trim();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
var spaceIndex = commandPattern.IndexOf(' ');
|
|
|
|
|
if (spaceIndex != -1)
|
|
|
|
|
{
|
|
|
|
|
file = commandPattern[..spaceIndex];
|
|
|
|
|
args = commandPattern[(spaceIndex + 1)..].Trim();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (file != null && args != null)
|
|
|
|
|
{
|
|
|
|
|
args = args.Replace("%1", HostsFilePath);
|
|
|
|
|
Process.Start(new ProcessStartInfo(file, args));
|
|
|
|
|
}
|
|
|
|
|
else
|
|
|
|
|
{
|
|
|
|
|
notepadFallback = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2024-04-26 19:41:44 +02:00
|
|
|
LoggerInstance.Logger.LogError("Failed to open default editor", ex);
|
2022-10-24 20:09:00 +02:00
|
|
|
notepadFallback = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (notepadFallback)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
Process.Start(new ProcessStartInfo("notepad.exe", HostsFilePath));
|
|
|
|
|
}
|
|
|
|
|
catch (Exception ex)
|
|
|
|
|
{
|
2024-04-26 19:41:44 +02:00
|
|
|
LoggerInstance.Logger.LogError("Failed to open notepad", ex);
|
2022-10-24 20:09:00 +02:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-08-16 20:36:26 +02:00
|
|
|
public void RemoveReadOnlyAttribute()
|
2023-11-03 17:10:26 +01:00
|
|
|
{
|
2024-11-11 10:42:40 +01:00
|
|
|
var fileInfo = _fileSystem.FileInfo.New(HostsFilePath);
|
2023-11-03 17:10:26 +01:00
|
|
|
if (fileInfo.IsReadOnly)
|
|
|
|
|
{
|
|
|
|
|
fileInfo.IsReadOnly = false;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2022-10-13 13:05:43 +02:00
|
|
|
public void Dispose()
|
|
|
|
|
{
|
|
|
|
|
Dispose(disposing: true);
|
|
|
|
|
GC.SuppressFinalize(this);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private void FileSystemWatcher_Changed(object sender, FileSystemEventArgs e)
|
|
|
|
|
{
|
|
|
|
|
_fileSystemWatcher.EnableRaisingEvents = false;
|
|
|
|
|
FileChanged?.Invoke(this, EventArgs.Empty);
|
|
|
|
|
_fileSystemWatcher.EnableRaisingEvents = true;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
protected virtual void Dispose(bool disposing)
|
|
|
|
|
{
|
|
|
|
|
if (!_disposed)
|
|
|
|
|
{
|
|
|
|
|
if (disposing)
|
|
|
|
|
{
|
|
|
|
|
_asyncLock.Dispose();
|
|
|
|
|
_disposed = true;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|