net8, language features, bugfixes

This commit is contained in:
kkb 2023-12-18 16:31:00 +01:00
parent 1591618c2c
commit ce99053a10
353 changed files with 3245 additions and 3944 deletions

View file

@ -5,14 +5,10 @@ using Vaitr.Network;
namespace Insight.Agent.Network;
public class AgentSession : TcpSession<IMessage>
public class AgentSession(IEnumerable<IMessageHandler<AgentSession>> handlers, ISerializer<IMessage> serializer, ILogger<AgentSession> logger)
: TcpSession<IMessage>(serializer, logger)
{
private readonly IEnumerable<IMessageHandler<AgentSession>> _handlers;
public AgentSession(IEnumerable<IMessageHandler<AgentSession>> handlers, ISerializer<IMessage> serializer, ILogger<AgentSession> logger) : base(serializer, logger)
{
_handlers = handlers;
}
private readonly IEnumerable<IMessageHandler<AgentSession>> _handlers = handlers;
protected override ValueTask OnConnectedAsync(CancellationToken cancellationToken)
{

View file

@ -2,20 +2,12 @@
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Logging;
namespace Insight.Agent.Network.Handlers;
public class CustomHandler : IMessageHandler<AgentSession>
public class CustomHandler(ScriptService scriptService) : IMessageHandler<AgentSession>
{
private readonly ScriptService _scriptService;
private readonly ILogger<CustomHandler> _logger;
public CustomHandler(ScriptService scriptService, ILogger<CustomHandler> logger)
{
_scriptService = scriptService;
_logger = logger;
}
private readonly ScriptService _scriptService = scriptService;
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
@ -29,6 +21,7 @@ public class CustomHandler : IMessageHandler<AgentSession>
private async ValueTask OnRequestAsync(AgentSession sender, Request request, CancellationToken cancellationToken)
{
if (request.RequestData is null) return;
var result = await _scriptService.QueryAsync(request.RequestData);
await sender.SendAsync(new Response(request)

View file

@ -59,7 +59,7 @@ public class DriveHandler : IMessageHandler<AgentSession>
drive.InterfaceType = @object.GetValue<string>(properties, "interfacetype")?.Trim();
drive.FirmwareRevision = @object.GetValue<string>(properties, "firmwarerevision")?.Trim();
drive.PNPDeviceID = @object.GetValue<string>(properties, "pnpdeviceid")?.Trim();
drive.Volumes = new List<Volume>();
drive.Volumes = [];
var diskpartition = @object.GetRelated("win32_diskpartition");
using (diskpartition)
@ -155,7 +155,7 @@ public class DriveHandler : IMessageHandler<AgentSession>
{
using (collection2)
{
foreach (ManagementObject @object2 in collection2)
foreach (ManagementObject @object2 in collection2.Cast<ManagementObject>())
{
var properties2 = @object2.GetPropertyHashes();

View file

@ -19,7 +19,7 @@ public class InterfaceHandler : IMessageHandler<AgentSession>
case InventoryRequest:
{
var result = new Collection<Interface>();
result.AddRange(GetInterfaces());
if (GetInterfaces() is List<Interface> interfaces) result.AddRange(interfaces);
await sender.SendAsync(result, cancellationToken);
break;
@ -27,10 +27,10 @@ public class InterfaceHandler : IMessageHandler<AgentSession>
}
}
private static List<Interface> GetInterfaces()
private static List<Interface>? GetInterfaces()
{
if (NetworkInterface.GetIsNetworkAvailable() is false) return null;
if (NetworkInterface.GetAllNetworkInterfaces().Any() is false) return null;
if (NetworkInterface.GetAllNetworkInterfaces().Length == 0) return null;
var interfaces = new List<Interface>();
@ -99,7 +99,7 @@ public class InterfaceHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var properties = @object.GetPropertyHashes();
@ -185,7 +185,7 @@ public class InterfaceHandler : IMessageHandler<AgentSession>
{
var addresses = new List<Unicast>();
if (unicastCollection.Any() is false) return addresses;
if (unicastCollection.Count == 0) return addresses;
foreach (var unicast in unicastCollection)
{
@ -210,7 +210,7 @@ public class InterfaceHandler : IMessageHandler<AgentSession>
{
var addresses = new List<IPAddress2>();
if (addressCollection.Any() is false) return addresses;
if (addressCollection.Count == 0) return addresses;
foreach (var address in addressCollection)
{
@ -224,7 +224,7 @@ public class InterfaceHandler : IMessageHandler<AgentSession>
{
var addresses = new List<IPAddress2>();
if (addressCollection.Any() is false) return addresses;
if (addressCollection.Count == 0) return addresses;
foreach (var address in addressCollection)
{

View file

@ -14,12 +14,12 @@ public class MainboardHandler : IMessageHandler<AgentSession>
switch (message)
{
case InventoryRequest:
await sender.SendAsync(GetMainboard(), cancellationToken);
if (GetMainboard() is Mainboard mainboard) await sender.SendAsync(mainboard, cancellationToken);
break;
}
}
private static Mainboard GetMainboard()
private static Mainboard? GetMainboard()
{
using var searcher = new ManagementObjectSearcher
{

View file

@ -41,7 +41,7 @@ public class OperationSystemHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var properties = @object.GetPropertyHashes();
@ -51,7 +51,8 @@ public class OperationSystemHandler : IMessageHandler<AgentSession>
if (@object.TryGetValue<string>(properties, "osarchitecture", out var architecture))
{
if (architecture is not null && architecture.ToLower().Contains("64")) os.Architecture = Architecture.X64;
if (architecture is not null && architecture.Contains("64", StringComparison.CurrentCultureIgnoreCase))
os.Architecture = Architecture.X64;
}
else
{

View file

@ -2,20 +2,12 @@
using Insight.Domain.Interfaces;
using Insight.Domain.Network;
using Insight.Domain.Network.Agent.Messages;
using Microsoft.Extensions.Logging;
namespace Insight.Agent.Network.Handlers;
public class ProxyHandler : IMessageHandler<AgentSession>
public class ProxyHandler(ScriptService scriptService) : IMessageHandler<AgentSession>
{
private readonly ScriptService _scriptService;
private readonly ILogger<ProxyHandler> _logger;
public ProxyHandler(ScriptService scriptService, ILogger<ProxyHandler> logger)
{
_scriptService = scriptService;
_logger = logger;
}
private readonly ScriptService _scriptService = scriptService;
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
@ -29,6 +21,7 @@ public class ProxyHandler : IMessageHandler<AgentSession>
private async ValueTask OnProxyRequestAsync(AgentSession sender, Proxy<Request> proxyRequest, CancellationToken cancellationToken)
{
if (proxyRequest.Message?.RequestData is null) return;
var result = await _scriptService.QueryAsync(proxyRequest.Message.RequestData);
await sender.SendAsync(new Proxy<Response>()

View file

@ -30,7 +30,7 @@ public class ServiceHandler : IMessageHandler<AgentSession>
var services = new List<Service>();
var serviceControllers = ServiceController.GetServices()?.OrderBy(s => s.DisplayName)?.ToList();
if (serviceControllers is null || serviceControllers.Any() is false) throw new InvalidOperationException("SERVICE Collection NULL");
if (serviceControllers is null || serviceControllers.Count == 0) throw new InvalidOperationException("SERVICE Collection NULL");
foreach (var sc in serviceControllers)
{
@ -102,7 +102,7 @@ public class ServiceHandler : IMessageHandler<AgentSession>
}
}
if (services2.Any() is false) return services;
if (services2.Count == 0) return services;
foreach (var svc in services)
{
@ -117,6 +117,6 @@ public class ServiceHandler : IMessageHandler<AgentSession>
svc.Delay = map.Delay;
}
return services.OrderBy(x => x.Name).ToList();
return [.. services.OrderBy(x => x.Name)];
}
}

View file

@ -48,7 +48,7 @@ public class SessionHandler : IMessageHandler<AgentSession>
//public const int WTS_CURRENT_SESSION = -1;
[DllImport("wtsapi32.dll")]
static extern int WTSEnumerateSessions(
private static extern int WTSEnumerateSessions(
nint pServer,
[MarshalAs(UnmanagedType.U4)] int iReserved,
[MarshalAs(UnmanagedType.U4)] int iVersion,
@ -64,7 +64,7 @@ public class SessionHandler : IMessageHandler<AgentSession>
out uint iBytesReturned);
[DllImport("wtsapi32.dll")]
static extern void WTSFreeMemory(
private static extern void WTSFreeMemory(
nint pMemory);
[StructLayout(LayoutKind.Sequential)]

View file

@ -89,121 +89,6 @@ public class StoragePoolHandler : IMessageHandler<AgentSession>
return pools;
}
private static List<PhysicalDisk> GetPhysicalDisks()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname from msft_physicaldisk")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_physicaldisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var disks = new List<PhysicalDisk>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new PhysicalDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.Manufacturer = @object.GetValue<string>(properties, "manufacturer")?.Trim();
disk.Model = @object.GetValue<string>(properties, "model")?.Trim();
disk.MediaType = @object.GetValue<ushort>(properties, "mediatype");
disk.BusType = @object.GetValue<ushort>(properties, "bustype");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (PhysicalDisk.OperationalState)p).ToList();
}
disk.Health = (PhysicalDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
if (@object.TryGetValue<ushort[]>(properties, "supportedusages", out var supportedusages) && supportedusages is not null)
{
disk.SupportedUsages = supportedusages.Select(p => (SupportedUsagesEnum)p).ToList();
}
disk.Usage = @object.GetValue<ushort>(properties, "usage");
disk.PhysicalLocation = @object.GetValue<string>(properties, "physicallocation")?.Trim();
disk.SerialNumber = @object.GetValue<string>(properties, "serialnumber")?.Trim();
disk.FirmwareVersion = @object.GetValue<string>(properties, "firmwareversion")?.Trim();
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.LogicalSectorSize = @object.GetValue<ulong>(properties, "logicalsectorsize");
disk.PhysicalSectorSize = @object.GetValue<ulong>(properties, "physicalsectorsize");
disk.VirtualDiskFootprint = @object.GetValue<ulong>(properties, "virtualdiskfootprint");
disks.Add(disk);
}
}
return disks;
}
private static List<VirtualDisk> GetVirtualDisks()
{
using var searcher = new ManagementObjectSearcher
{
Scope = new ManagementScope(@"root\microsoft\windows\storage"),
Query = new ObjectQuery("select objectid, uniqueid, name, friendlyname, access, provisioningtype, physicaldiskredundancy, resiliencysettingname, isdeduplicationenabled, issnapshot, operationalstatus, healthstatus, size, allocatedsize, footprintonpool, readcachesize, writecachesize from msft_virtualdisk")
};
if (searcher.TryGet(out var collection) is false)
{
searcher.Query = new ObjectQuery("select * from msft_virtualdisk");
if (searcher.TryGet(out collection) is false) throw new InvalidOperationException("WMI Collection NULL");
}
var disks = new List<VirtualDisk>();
using (collection)
{
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new VirtualDisk();
var properties = @object.GetPropertyHashes();
disk.UniqueId = @object.GetValue<string>(properties, "uniqueid")?.Trim();
disk.Name = @object.GetValue<string>(properties, "name")?.Trim();
disk.FriendlyName = @object.GetValue<string>(properties, "friendlyname")?.Trim();
disk.AccessType = (AccessTypeEnum)@object.GetValue<ushort>(properties, "access");
disk.ProvisioningType = (ProvisioningTypeEnum)@object.GetValue<ushort>(properties, "provisioningtype");
disk.PhysicalDiskRedundancy = @object.GetValue<ushort>(properties, "physicaldiskredundancy");
disk.ResiliencySettingName = @object.GetValue<string>(properties, "resiliencysettingname")?.Trim();
disk.Deduplication = @object.GetValue<bool>(properties, "isdeduplicationenabled");
disk.IsSnapshot = @object.GetValue<bool>(properties, "issnapshot");
if (@object.TryGetValue<ushort[]>(properties, "operationalstatus", out var operationals) && operationals is not null)
{
disk.States = operationals.Select(p => (VirtualDisk.OperationalState)p).ToList();
}
disk.Health = (VirtualDisk.HealthState)@object.GetValue<ushort>(properties, "healthstatus");
disk.Size = @object.GetValue<ulong>(properties, "size");
disk.AllocatedSize = @object.GetValue<ulong>(properties, "allocatedsize");
disk.FootprintOnPool = @object.GetValue<ulong>(properties, "footprintonpool");
disk.ReadCacheSize = @object.GetValue<ulong>(properties, "readcachesize");
disk.WriteCacheSize = @object.GetValue<ulong>(properties, "writecachesize");
disks.Add(disk);
}
}
return disks;
}
private static List<PhysicalDisk> QueryPhysicalDisksByStoragePool(string storagePoolObjectId)
{
using var searcher = new ManagementObjectSearcher
@ -218,7 +103,7 @@ public class StoragePoolHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new PhysicalDisk();
@ -275,7 +160,7 @@ public class StoragePoolHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var disk = new VirtualDisk();

View file

@ -87,7 +87,6 @@ public class SystemInfoHandler : IMessageHandler<AgentSession>
private static string GetWindowsProductKeyFromDigitalProductId(byte[] digitalProductId, DigitalProductIdVersion digitalProductIdVersion)
{
var productKey = digitalProductIdVersion == DigitalProductIdVersion.Windows8AndUp
? DecodeProductKeyWin8AndUp(digitalProductId)
: DecodeProductKey(digitalProductId);
@ -124,7 +123,7 @@ public class SystemInfoHandler : IMessageHandler<AgentSession>
var digitMapIndex = 0;
for (var j = decodeStringLength - 1; j >= 0; j--)
{
var byteValue = digitMapIndex << 8 | (byte)hexPid[j];
var byteValue = digitMapIndex << 8 | (byte)hexPid[j]!;
hexPid[j] = (byte)(byteValue / 24);
digitMapIndex = byteValue % 24;
decodedChars[i] = digits[digitMapIndex];
@ -148,17 +147,17 @@ public class SystemInfoHandler : IMessageHandler<AgentSession>
var current = 0;
for (var j = 14; j >= 0; j--)
{
current = current * 256;
current *= 256;
current = digitalProductId[j + keyOffset] + current;
digitalProductId[j + keyOffset] = (byte)(current / 24);
current = current % 24;
current %= 24;
last = current;
}
key = digits[current] + key;
}
var keypart1 = key.Substring(1, last);
var keypart2 = key.Substring(last + 1, key.Length - (last + 1));
var keypart2 = key[(last + 1)..];
key = keypart1 + "N" + keypart2;
for (var i = 5; i < key.Length; i += 6)

View file

@ -10,7 +10,7 @@ using UpdateCollection = Insight.Domain.Network.Agent.Messages.UpdateCollection;
namespace Insight.Agent.Network.Handlers;
[SupportedOSPlatform("windows")]
public class UpdateHandler : IMessageHandler<AgentSession>
public partial class UpdateHandler : IMessageHandler<AgentSession>
{
public async ValueTask HandleAsync<TMessage>(AgentSession sender, TMessage message, CancellationToken cancellationToken) where TMessage : IMessage
{
@ -60,7 +60,7 @@ public class UpdateHandler : IMessageHandler<AgentSession>
try
{
var rx = new Regex(@"KB(\d+)");
var rx = KnowledgeBaseRegex();
update.Hotfix = rx.Match(wupdate.Title).Value;
}
catch (Exception)
@ -125,4 +125,7 @@ public class UpdateHandler : IMessageHandler<AgentSession>
return updates;
}
[GeneratedRegex(@"KB(\d+)")]
private static partial Regex KnowledgeBaseRegex();
}

View file

@ -32,7 +32,7 @@ public class UserHandler : IMessageHandler<AgentSession>
foreach (var u in users)
{
u.Groups = new List<Group>();
u.Groups = [];
foreach (var ug in usergrouping.Where(ug => ug.UserDomain == u.Domain && ug.UserName == u.Name))
{
@ -67,7 +67,7 @@ public class UserHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var group = new Group();
@ -83,7 +83,7 @@ public class UserHandler : IMessageHandler<AgentSession>
}
}
return groups.OrderBy(x => x.Name)?.ToList();
return [.. groups.OrderBy(x => x.Name)];
}
private static List<User> QueryUsers()
@ -105,7 +105,7 @@ public class UserHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var user = new User();
@ -150,7 +150,7 @@ public class UserHandler : IMessageHandler<AgentSession>
using (collection)
{
foreach (ManagementObject @object in collection)
foreach (ManagementObject @object in collection.Cast<ManagementObject>())
{
var usergroup = new UserGroupMap();

View file

@ -341,7 +341,7 @@ public class VirtualMaschineHandler : IMessageHandler<AgentSession>
{
conf.ParentId = parentGuid.ToString();
parentConfig.Childs ??= new List<VirtualMaschineConfiguration>();
parentConfig.Childs ??= [];
parentConfig.Childs.Add(conf);
}
else