diff --git a/.editorconfig b/.editorconfig index 26962341..d58e06be 100644 --- a/.editorconfig +++ b/.editorconfig @@ -160,6 +160,11 @@ dotnet_style_qualification_for_method = false:suggestion dotnet_style_qualification_for_property = false:suggestion dotnet_style_readonly_field = true:suggestion dotnet_style_require_accessibility_modifiers = omit_if_default:suggestion +spelling_checkable_types = strings,identifiers,comments +spelling_error_severity = information +spelling_exclusion_path = .github/linters/vs-spell-exclusion.txt +spelling_languages = en-us +spelling_use_default_exclusion_dictionary = true [*.{cs,razor}] charset = utf-8-bom diff --git a/.github/linters/vs-spell-exclusion.txt b/.github/linters/vs-spell-exclusion.txt new file mode 100644 index 00000000..3a0523e1 --- /dev/null +++ b/.github/linters/vs-spell-exclusion.txt @@ -0,0 +1,28 @@ +Balisson +busid +Codecov +csharp +devid +Dushan +errno +ioctl +ioctls +linux +netstandard +nosemgrep +pcap +replug +replugged +seqnum +serializer +setupapi +stdout +usbfilter +usbids +usbioctl +usbip +usbipd +usblib +Vbox +vhci +wsl diff --git a/.github/linters/vs-spell-exclusion.txt.license b/.github/linters/vs-spell-exclusion.txt.license new file mode 100644 index 00000000..eb059a19 --- /dev/null +++ b/.github/linters/vs-spell-exclusion.txt.license @@ -0,0 +1,3 @@ +SPDX-FileCopyrightText: 2024 Frans van Dorsselaer + +SPDX-License-Identifier: GPL-3.0-only diff --git a/UnitTests/Automation_Tests.cs b/UnitTests/Automation_Tests.cs index c1a412bf..d0a1867f 100644 --- a/UnitTests/Automation_Tests.cs +++ b/UnitTests/Automation_Tests.cs @@ -174,7 +174,7 @@ public void Device_BusId_Null() } [TestMethod] - public void Device_PeristedGuid() + public void Device_PersistedGuid() { var device = new Device() { diff --git a/UnitTests/ConsoleTools_Tests.cs b/UnitTests/ConsoleTools_Tests.cs index e4141a37..18309b90 100644 --- a/UnitTests/ConsoleTools_Tests.cs +++ b/UnitTests/ConsoleTools_Tests.cs @@ -67,19 +67,19 @@ public void ReportRebootRequired() [DataRow("VID_80EE&PID_CAFE", false)] [DataRow("VID_12AB&PID_34CD", true)] - public void CheckNoStub(string hardwareId, bool nostub) + public void CheckNoStub(string hardwareId, bool noStub) { - var vidpid = VidPid.FromHardwareOrInstanceId(hardwareId); + var vidPid = VidPid.FromHardwareOrInstanceId(hardwareId); var console = new TestConsole(); - if (nostub) + if (noStub) { - Assert.IsTrue(ConsoleTools.CheckNoStub(vidpid, console)); + Assert.IsTrue(ConsoleTools.CheckNoStub(vidPid, console)); Assert.IsTrue(string.IsNullOrEmpty(console.Out.ToString())); Assert.IsTrue(string.IsNullOrEmpty(console.Error.ToString())); } else { - Assert.IsFalse(ConsoleTools.CheckNoStub(vidpid, console)); + Assert.IsFalse(ConsoleTools.CheckNoStub(vidPid, console)); Assert.IsTrue(string.IsNullOrEmpty(console.Out.ToString())); Assert.IsFalse(string.IsNullOrEmpty(console.Error.ToString())); } diff --git a/UnitTests/ExportedDevice_Tests.cs b/UnitTests/ExportedDevice_Tests.cs index 7e2cf372..e7454cea 100644 --- a/UnitTests/ExportedDevice_Tests.cs +++ b/UnitTests/ExportedDevice_Tests.cs @@ -42,12 +42,12 @@ sealed class ExportedDevice_Tests 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - // busid (32 bytes, text) + // busId (32 bytes, text) (byte)'3', (byte)'-', (byte)'4', (byte)'2', 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - // busnum (4 bytes, big endian) + // busNum (4 bytes, big endian) 0, 0, 0, 3, - // devnum (4 bytes, big endian) + // devNum (4 bytes, big endian) 0, 0, 0, 42, // speed (4 bytes, enum, big endian) 0, 0, 0, (byte)UsbDeviceSpeed.USB_SPEED_SUPER_PLUS, diff --git a/Usbipd.Automation/BusId.cs b/Usbipd.Automation/BusId.cs index 230038f8..ffbab54e 100644 --- a/Usbipd.Automation/BusId.cs +++ b/Usbipd.Automation/BusId.cs @@ -21,7 +21,7 @@ public readonly record struct BusId public BusId(ushort bus, ushort port) { // Do not allow the explicit creation of the special IncompatibleHub value. - // Instead, use the static IncompatibleHub field (preferrable) or "default". + // Instead, use the static IncompatibleHub field (preferable) or "default". // USB supports up to 127 devices, but that would require multiple hubs; the "per hub" port will never be >99. // And if you have more than 99 hubs on one system, then you win a prize! (but we're not going to support it...) if (bus is 0 or > 99) diff --git a/Usbipd.PowerShell/GetUsbipdDevice.cs b/Usbipd.PowerShell/GetUsbipdDevice.cs index 2c314200..c767f246 100644 --- a/Usbipd.PowerShell/GetUsbipdDevice.cs +++ b/Usbipd.PowerShell/GetUsbipdDevice.cs @@ -39,8 +39,8 @@ protected override void BeginProcessing() var captureTasks = new[] { - Task.Run(async () => { stdout = await process.StandardOutput.ReadToEndAsync(); }), - Task.Run(async () => { stderr = await process.StandardError.ReadToEndAsync(); }), + Task.Run(async () => stdout = await process.StandardOutput.ReadToEndAsync()), + Task.Run(async () => stderr = await process.StandardError.ReadToEndAsync()), }; process.WaitForExit(); diff --git a/Usbipd.PowerShell/Installation.cs b/Usbipd.PowerShell/Installation.cs index 32becb02..101ffa83 100644 --- a/Usbipd.PowerShell/Installation.cs +++ b/Usbipd.PowerShell/Installation.cs @@ -50,8 +50,8 @@ public static string ExePath var captureTasks = new[] { - Task.Run(async () => { stdout = await process.StandardOutput.ReadToEndAsync(); }), - Task.Run(async () => { stderr = await process.StandardError.ReadToEndAsync(); }), + Task.Run(async () => stdout = await process.StandardOutput.ReadToEndAsync()), + Task.Run(async () => stderr = await process.StandardError.ReadToEndAsync()), }; process.WaitForExit(); diff --git a/Usbipd/AttachedEndpoint.cs b/Usbipd/AttachedEndpoint.cs index e18cac7e..78b0f5e0 100644 --- a/Usbipd/AttachedEndpoint.cs +++ b/Usbipd/AttachedEndpoint.cs @@ -201,10 +201,8 @@ async Task HandleSubmitIsochronousAsync(UsbIpHeaderBasic basic, UsbIpHeaderCmdSu } finally { - _ = Task.WhenAll(ioctls).ContinueWith(task => - { - gcHandle.Free(); - }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + _ = Task.WhenAll(ioctls).ContinueWith(task => gcHandle.Free(), + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } @@ -257,7 +255,7 @@ public async Task HandleSubmitAsync(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit } // We now have received the entire SUBMIT request: - // - If the request is "special" (reconfig, clear), then we will handle it immediately and await the result. + // - If the request is "special" (reconfigure, clear), then we will handle it immediately and await the result. // This means no further requests will be read until the special request has completed. // - Otherwise, we will start a new task so that the receiver can continue. // This means multiple URBs can be outstanding awaiting completion. @@ -329,10 +327,8 @@ public async Task HandleSubmitAsync(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit gcHandle.Free(); throw; } - _ = ioctl.ContinueWith(task => - { - gcHandle.Free(); - }, CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); + _ = ioctl.ContinueWith(task => gcHandle.Free(), + CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } else { diff --git a/Usbipd/CommandHandlersCli.cs b/Usbipd/CommandHandlersCli.cs index b95ec8c6..cc0a50a6 100644 --- a/Usbipd/CommandHandlersCli.cs +++ b/Usbipd/CommandHandlersCli.cs @@ -97,9 +97,9 @@ You should have received a copy of the GNU General Public License \ return Task.FromResult(ExitCode.Success); } - static string GetDescription(UsbDevice device, bool usbids) + static string GetDescription(UsbDevice device, bool usbIds) { - if (usbids) + if (usbIds) { var vendor = device.HardwareId.Vendor; return vendor is not null @@ -112,7 +112,7 @@ static string GetDescription(UsbDevice device, bool usbids) } } - Task ICommandHandlers.List(bool usbids, IConsole console, CancellationToken cancellationToken) + Task ICommandHandlers.List(bool usbIds, IConsole console, CancellationToken cancellationToken) { var allDevices = UsbDevice.GetAll().ToList(); console.WriteLine("Connected:"); @@ -126,7 +126,7 @@ Task ICommandHandlers.List(bool usbids, IConsole console, Cancellation : Policy.IsAutoBindAllowed(device) ? "Allowed" : "Not shared"; console.Write($"{(device.BusId.Value.IsIncompatibleHub ? string.Empty : device.BusId.Value),-5} "); console.Write($"{device.HardwareId,-9} "); - console.WriteTruncated(GetDescription(device, usbids), 60, true); + console.WriteTruncated(GetDescription(device, usbIds), 60, true); console.WriteLine($" {state}"); } console.WriteLine(string.Empty); @@ -137,7 +137,7 @@ Task ICommandHandlers.List(bool usbids, IConsole console, Cancellation { Debug.Assert(device.Guid.HasValue); console.Write($"{device.Guid.Value,-36:D} "); - console.WriteTruncated(GetDescription(device, usbids), 60, false); + console.WriteTruncated(GetDescription(device, usbIds), 60, false); console.WriteLine(string.Empty); } console.WriteLine(string.Empty); @@ -171,7 +171,7 @@ static ExitCode Bind(BusId busId, bool force, IConsole console) } if (!device.Guid.HasValue) { - RegistryUtils.Persist(device.InstanceId, device.Description); + RegistryUtilities.Persist(device.InstanceId, device.Description); } if (!force) { @@ -221,7 +221,7 @@ Task ICommandHandlers.Unbind(BusId busId, IConsole console, Cancellati { return Task.FromResult(ExitCode.AccessDenied); } - RegistryUtils.StopSharingDevice(device.Guid.Value); + RegistryUtilities.StopSharingDevice(device.Guid.Value); if (NewDev.UnforceVBoxDriver(device.InstanceId)) { console.ReportRebootRequired(); @@ -251,7 +251,7 @@ static ExitCode Unbind(IEnumerable devices, IConsole console) { if (device.Guid is not null) { - RegistryUtils.StopSharingDevice(device.Guid.Value); + RegistryUtilities.StopSharingDevice(device.Guid.Value); } try { @@ -278,7 +278,7 @@ static ExitCode Unbind(IEnumerable devices, IConsole console) Task ICommandHandlers.Unbind(Guid guid, IConsole console, CancellationToken cancellationToken) { - var device = RegistryUtils.GetBoundDevices().SingleOrDefault(d => d.Guid.HasValue && d.Guid.Value == guid); + var device = RegistryUtilities.GetBoundDevices().SingleOrDefault(d => d.Guid.HasValue && d.Guid.Value == guid); if (device is null) { console.ReportError($"There is no device with guid '{guid:D}'."); @@ -302,7 +302,7 @@ Task ICommandHandlers.UnbindAll(IConsole console, CancellationToken ca { return Task.FromResult(ExitCode.AccessDenied); } - RegistryUtils.StopSharingAllDevices(); + RegistryUtilities.StopSharingAllDevices(); var reboot = false; var driverError = false; foreach (var originalDeviceId in ConfigurationManager.GetOriginalDeviceIdsWithVBoxDriver()) @@ -373,7 +373,7 @@ static ExitCode Detach(IEnumerable devices, IConsole console) console.ReportInfo($"Device with busid '{device.BusId}' was already not attached."); continue; } - if (!RegistryUtils.SetDeviceAsDetached(device.Guid.Value)) + if (!RegistryUtilities.SetDeviceAsDetached(device.Guid.Value)) { console.ReportError($"Failed to detach device with busid '{device.BusId}'."); error = true; @@ -406,7 +406,7 @@ Task ICommandHandlers.Detach(VidPid vidPid, IConsole console, Cancella Task ICommandHandlers.DetachAll(IConsole console, CancellationToken cancellationToken) { - if (!RegistryUtils.SetAllDevicesAsDetached()) + if (!RegistryUtilities.SetAllDevicesAsDetached()) { console.ReportError($"Failed to detach one or more devices."); return Task.FromResult(ExitCode.Failure); @@ -451,7 +451,7 @@ Task ICommandHandlers.State(IConsole console, CancellationToken cancel Task ICommandHandlers.PolicyAdd(PolicyRule rule, IConsole console, CancellationToken cancellationToken) { - if (RegistryUtils.GetPolicyRules().FirstOrDefault(r => r.Value == rule) is var existingRule && existingRule.Key != default) + if (RegistryUtilities.GetPolicyRules().FirstOrDefault(r => r.Value == rule) is var existingRule && existingRule.Key != default) { console.ReportError($"Policy rule already exists with guid '{existingRule.Key:D}'."); return Task.FromResult(ExitCode.Failure); @@ -462,14 +462,14 @@ Task ICommandHandlers.PolicyAdd(PolicyRule rule, IConsole console, Can return Task.FromResult(ExitCode.AccessDenied); } - var guid = RegistryUtils.AddPolicyRule(rule); + var guid = RegistryUtilities.AddPolicyRule(rule); console.ReportInfo($"Policy rule created with guid '{guid:D}'."); return Task.FromResult(ExitCode.Success); } Task ICommandHandlers.PolicyList(IConsole console, CancellationToken cancellationToken) { - var policyRules = RegistryUtils.GetPolicyRules(); + var policyRules = RegistryUtilities.GetPolicyRules(); console.WriteLine("Policy rules:"); console.WriteLine($"{"GUID",-36} {"EFFECT",-6} {"OPERATION",-9} {"BUSID",-5} {"VID:PID",-9}"); foreach (var rule in policyRules) @@ -495,7 +495,7 @@ Task ICommandHandlers.PolicyList(IConsole console, CancellationToken c Task ICommandHandlers.PolicyRemove(Guid guid, IConsole console, CancellationToken cancellationToken) { - if (!RegistryUtils.GetPolicyRules().ContainsKey(guid)) + if (!RegistryUtilities.GetPolicyRules().ContainsKey(guid)) { console.ReportError($"There is no policy rule with guid '{guid:D}'."); return Task.FromResult(ExitCode.Failure); @@ -506,7 +506,7 @@ Task ICommandHandlers.PolicyRemove(Guid guid, IConsole console, Cancel return Task.FromResult(ExitCode.AccessDenied); } - RegistryUtils.RemovePolicyRule(guid); + RegistryUtilities.RemovePolicyRule(guid); return Task.FromResult(ExitCode.Success); } @@ -517,7 +517,7 @@ Task ICommandHandlers.PolicyRemoveAll(IConsole console, CancellationTo return Task.FromResult(ExitCode.AccessDenied); } - RegistryUtils.RemovePolicyRuleAll(); + RegistryUtilities.RemovePolicyRuleAll(); return Task.FromResult(ExitCode.Success); } } diff --git a/Usbipd/CommandHandlersServer.cs b/Usbipd/CommandHandlersServer.cs index fac7be45..1b67bb59 100644 --- a/Usbipd/CommandHandlersServer.cs +++ b/Usbipd/CommandHandlersServer.cs @@ -58,10 +58,7 @@ async Task ICommandHandlers.Server(string[] args, IConsole console, Ca { EventLog.CreateEventSource(Program.Product, "Application"); } - _ = logging.AddEventLog(settings => - { - settings.SourceName = Program.Product; - }); + _ = logging.AddEventLog(settings => settings.SourceName = Program.Product); }) .ConfigureServices((hostContext, services) => { diff --git a/Usbipd/ConfigurationManager.cs b/Usbipd/ConfigurationManager.cs index cb23af1d..dc83539b 100644 --- a/Usbipd/ConfigurationManager.cs +++ b/Usbipd/ConfigurationManager.cs @@ -316,8 +316,8 @@ public static bool HasVBoxDriver(string instanceId) try { var deviceNode = Locate_DevNode(instanceId, false); - var driverDesc = (string)Get_DevNode_Property(deviceNode, PInvoke.DEVPKEY_Device_DriverDesc); - return driverDesc == "VirtualBox USB"; + var driverDescription = (string)Get_DevNode_Property(deviceNode, PInvoke.DEVPKEY_Device_DriverDesc); + return driverDescription == "VirtualBox USB"; } catch (ConfigurationManagerException) { diff --git a/Usbipd/ConnectedClient.cs b/Usbipd/ConnectedClient.cs index 5067a799..5f791513 100644 --- a/Usbipd/ConnectedClient.cs +++ b/Usbipd/ConnectedClient.cs @@ -30,7 +30,7 @@ public async Task RunAsync(CancellationToken cancellationToken) { try { - var opCode = await RecvOpCodeAsync(cancellationToken); + var opCode = await ReceiveOpCodeAsync(cancellationToken); Logger.Debug($"Received opcode: {opCode}"); switch (opCode) { @@ -138,11 +138,11 @@ async Task HandleRequestImportAsync(CancellationToken cancellationToken) { // The device is not currently bound, but it is allowed by the policy. Auto-bind it now... Logger.AutoBind(ClientContext.ClientAddress, busId, bindDevice.InstanceId); - RegistryUtils.Persist(bindDevice.InstanceId, bindDevice.Description); + RegistryUtilities.Persist(bindDevice.InstanceId, bindDevice.Description); } } - var device = RegistryUtils.GetBoundDevices().SingleOrDefault(d => d.BusId.HasValue && d.BusId.Value == busId); + var device = RegistryUtilities.GetBoundDevices().SingleOrDefault(d => d.BusId.HasValue && d.BusId.Value == busId); if (device is null) { await SendOpCodeAsync(OpCode.OP_REP_IMPORT, Status.ST_NODEV); @@ -239,13 +239,13 @@ async Task HandleRequestImportAsync(CancellationToken cancellationToken) } // Detect unbind. - using var attachedKey = RegistryUtils.SetDeviceAsAttached(device.Guid.Value, device.BusId.Value, ClientContext.ClientAddress, + using var attachedKey = RegistryUtilities.SetDeviceAsAttached(device.Guid.Value, device.BusId.Value, ClientContext.ClientAddress, vboxDevice.InstanceId); - var lresult = PInvoke.RegNotifyChangeKeyValue(attachedKey.Handle, false, + var result = PInvoke.RegNotifyChangeKeyValue(attachedKey.Handle, false, Windows.Win32.System.Registry.REG_NOTIFY_FILTER.REG_NOTIFY_THREAD_AGNOSTIC, cancelEvent.SafeWaitHandle, true); - if (lresult != WIN32_ERROR.ERROR_SUCCESS) + if (result != WIN32_ERROR.ERROR_SUCCESS) { - throw new Win32Exception((int)lresult, nameof(PInvoke.RegNotifyChangeKeyValue)); + throw new Win32Exception((int)result, nameof(PInvoke.RegNotifyChangeKeyValue)); } await ServiceProvider.GetRequiredService().RunAsync(attachedClientTokenSource.Token); @@ -254,7 +254,7 @@ async Task HandleRequestImportAsync(CancellationToken cancellationToken) { notification?.Dispose(); - _ = RegistryUtils.SetDeviceAsDetached(device.Guid.Value); + _ = RegistryUtilities.SetDeviceAsDetached(device.Guid.Value); ClientContext.AttachedDevice.Dispose(); @@ -294,7 +294,7 @@ async Task HandleRequestImportAsync(CancellationToken cancellationToken) } } - async Task RecvOpCodeAsync(CancellationToken cancellationToken) + async Task ReceiveOpCodeAsync(CancellationToken cancellationToken) { var buf = new byte[8]; await Stream.ReadMessageAsync(buf, cancellationToken); diff --git a/Usbipd/ConsoleTools.cs b/Usbipd/ConsoleTools.cs index e450adde..56d95d9e 100644 --- a/Usbipd/ConsoleTools.cs +++ b/Usbipd/ConsoleTools.cs @@ -182,7 +182,7 @@ public static void ReportInfo(this IConsole console, string text) /// /// For example, 'list or 'bind' will work fine. But actually attaching is not going to work. /// Therefore, such commands will give a warning telling the user that the current action - /// is fine, but it will fail later on unless they resolve the situaton. + /// is fine, but it will fail later on unless they resolve the situation. /// /// /// @@ -269,7 +269,7 @@ public static void ReportRebootRequired(this IConsole console) public static bool CheckWriteAccess(IConsole console) { - if (!RegistryUtils.HasWriteAccess()) + if (!RegistryUtilities.HasWriteAccess()) { console.ReportError("Access denied; this operation requires administrator privileges."); return false; diff --git a/Usbipd/ExportedDevice.cs b/Usbipd/ExportedDevice.cs index 55ae3b02..a1d84d91 100644 --- a/Usbipd/ExportedDevice.cs +++ b/Usbipd/ExportedDevice.cs @@ -110,10 +110,10 @@ public void Serialize(Stream stream, bool includeInterfaces) } if (common.bDescriptorType == PInvoke.USB_INTERFACE_DESCRIPTOR_TYPE) { - BytesToStruct(buf.AsSpan(offset), out USB_INTERFACE_DESCRIPTOR iface); - if (iface.bAlternateSetting == 0) + BytesToStruct(buf.AsSpan(offset), out USB_INTERFACE_DESCRIPTOR descriptor); + if (descriptor.bAlternateSetting == 0) { - result.Add(new(iface.bInterfaceClass, iface.bInterfaceSubClass, iface.bInterfaceProtocol)); + result.Add(new(descriptor.bInterfaceClass, descriptor.bInterfaceSubClass, descriptor.bInterfaceProtocol)); } } offset += common.bLength; diff --git a/Usbipd/ICommandHandlers.cs b/Usbipd/ICommandHandlers.cs index b484160e..a754caba 100644 --- a/Usbipd/ICommandHandlers.cs +++ b/Usbipd/ICommandHandlers.cs @@ -17,7 +17,7 @@ interface ICommandHandlers public Task Detach(VidPid vidPid, IConsole console, CancellationToken cancellationToken); public Task DetachAll(IConsole console, CancellationToken cancellationToken); public Task License(IConsole console, CancellationToken cancellationToken); - public Task List(bool usbids, IConsole console, CancellationToken cancellationToken); + public Task List(bool usbIds, IConsole console, CancellationToken cancellationToken); public Task Server(string[] args, IConsole console, CancellationToken cancellationToken); public Task Unbind(BusId busId, IConsole console, CancellationToken cancellationToken); public Task Unbind(Guid guid, IConsole console, CancellationToken cancellationToken); diff --git a/Usbipd/NewDev.cs b/Usbipd/NewDev.cs index aad8e080..c98f1d98 100644 --- a/Usbipd/NewDev.cs +++ b/Usbipd/NewDev.cs @@ -68,7 +68,7 @@ public static bool ForceVBoxDriver(string originalInstanceId) cbSize = (uint)Marshal.SizeOf(), Flags = SETUP_DI_DEVICE_INSTALL_FLAGS.DI_ENUMSINGLEINF, FlagsEx = SETUP_DI_DEVICE_INSTALL_FLAGS_EX.DI_FLAGSEX_ALLOWEXCLUDEDDRVS, - DriverPath = @$"{RegistryUtils.InstallationFolder ?? throw new UnexpectedResultException("not installed")}\Drivers\VBoxUSB.inf", + DriverPath = @$"{RegistryUtilities.InstallationFolder ?? throw new UnexpectedResultException("not installed")}\Drivers\VBoxUSB.inf", }; PInvoke.SetupDiSetDeviceInstallParams(deviceInfoSet, deviceInfoData, deviceInstallParams) .ThrowOnError(nameof(PInvoke.SetupDiSetDeviceInstallParams)); diff --git a/Usbipd/PcapNg.cs b/Usbipd/PcapNg.cs index 757bbbde..07120218 100644 --- a/Usbipd/PcapNg.cs +++ b/Usbipd/PcapNg.cs @@ -78,39 +78,39 @@ public void DumpPacketNonIsoRequest(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit var timestamp = GetTimestamp() / 10; // in micro seconds - using var usbmon = new BinaryWriter(new MemoryStream()); - usbmon.Write((ulong)basic.seqnum); - usbmon.Write((byte)'S'); - usbmon.Write(ConvertType(basic.EndpointType(cmdSubmit))); - usbmon.Write(basic.RawEndpoint()); - usbmon.Write((byte)basic.devid); - usbmon.Write((ushort)(basic.devid >> 16)); - usbmon.Write((byte)(basic.ep == 0 ? '\0' : '-')); - usbmon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); - usbmon.Write(timestamp / 1000000); // seconds - usbmon.Write((uint)(timestamp % 1000000)); // micro seconds - usbmon.Write(-115); // -EINPROGRESS - usbmon.Write(cmdSubmit.transfer_buffer_length); // length - usbmon.Write(0); // actual + using var usbMon = new BinaryWriter(new MemoryStream()); + usbMon.Write((ulong)basic.seqnum); + usbMon.Write((byte)'S'); + usbMon.Write(ConvertType(basic.EndpointType(cmdSubmit))); + usbMon.Write(basic.RawEndpoint()); + usbMon.Write((byte)basic.devid); + usbMon.Write((ushort)(basic.devid >> 16)); + usbMon.Write((byte)(basic.ep == 0 ? '\0' : '-')); + usbMon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); + usbMon.Write(timestamp / 1000000); // seconds + usbMon.Write((uint)(timestamp % 1000000)); // micro seconds + usbMon.Write(-115); // -EINPROGRESS + usbMon.Write(cmdSubmit.transfer_buffer_length); // length + usbMon.Write(0); // actual if (basic.ep == 0) { - usbmon.Write(cmdSubmit.setup.bmRequestType.B); - usbmon.Write(cmdSubmit.setup.bRequest); - usbmon.Write(cmdSubmit.setup.wValue.W); - usbmon.Write(cmdSubmit.setup.wIndex.W); - usbmon.Write(cmdSubmit.setup.wLength); + usbMon.Write(cmdSubmit.setup.bmRequestType.B); + usbMon.Write(cmdSubmit.setup.bRequest); + usbMon.Write(cmdSubmit.setup.wValue.W); + usbMon.Write(cmdSubmit.setup.wIndex.W); + usbMon.Write(cmdSubmit.setup.wLength); } else { - usbmon.Write(0ul); // setup == 0 for ep != 0 + usbMon.Write(0ul); // setup == 0 for ep != 0 } - usbmon.Write(cmdSubmit.interval); - usbmon.Write(0u); // start_frame == 0 for non-ISO - usbmon.Write(cmdSubmit.transfer_flags); - usbmon.Write(0u); // number_of_packets == 0 for non-ISO - usbmon.Write(data); + usbMon.Write(cmdSubmit.interval); + usbMon.Write(0u); // start_frame == 0 for non-ISO + usbMon.Write(cmdSubmit.transfer_flags); + usbMon.Write(0u); // number_of_packets == 0 for non-ISO + usbMon.Write(data); - BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbmon)).AsTask().Wait(); + BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbMon)).AsTask().Wait(); } public void DumpPacketNonIsoReply(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit cmdSubmit, UsbIpHeaderRetSubmit retSubmit, ReadOnlySpan data) @@ -122,28 +122,28 @@ public void DumpPacketNonIsoReply(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit c var timestamp = GetTimestamp() / 10; // in micro seconds - using var usbmon = new BinaryWriter(new MemoryStream()); - usbmon.Write((ulong)basic.seqnum); - usbmon.Write((byte)'C'); - usbmon.Write(ConvertType(basic.EndpointType(cmdSubmit))); - usbmon.Write(basic.RawEndpoint()); - usbmon.Write((byte)basic.devid); - usbmon.Write((ushort)(basic.devid >> 16)); - usbmon.Write((byte)'-'); - usbmon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); - usbmon.Write(timestamp / 1000000); // seconds - usbmon.Write((uint)(timestamp % 1000000)); // micro seconds - usbmon.Write(retSubmit.status); - usbmon.Write(retSubmit.actual_length); // length - usbmon.Write(retSubmit.actual_length); // actual - usbmon.Write(0ul); // setup == 0 for reply - usbmon.Write(cmdSubmit.interval); - usbmon.Write(0u); // start_frame == 0 for non-ISO - usbmon.Write(cmdSubmit.transfer_flags); - usbmon.Write(0u); // number_of_packets == 0 for non-ISO - usbmon.Write(data); - - BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbmon)).AsTask().Wait(); + using var usbMon = new BinaryWriter(new MemoryStream()); + usbMon.Write((ulong)basic.seqnum); + usbMon.Write((byte)'C'); + usbMon.Write(ConvertType(basic.EndpointType(cmdSubmit))); + usbMon.Write(basic.RawEndpoint()); + usbMon.Write((byte)basic.devid); + usbMon.Write((ushort)(basic.devid >> 16)); + usbMon.Write((byte)'-'); + usbMon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); + usbMon.Write(timestamp / 1000000); // seconds + usbMon.Write((uint)(timestamp % 1000000)); // micro seconds + usbMon.Write(retSubmit.status); + usbMon.Write(retSubmit.actual_length); // length + usbMon.Write(retSubmit.actual_length); // actual + usbMon.Write(0ul); // setup == 0 for reply + usbMon.Write(cmdSubmit.interval); + usbMon.Write(0u); // start_frame == 0 for non-ISO + usbMon.Write(cmdSubmit.transfer_flags); + usbMon.Write(0u); // number_of_packets == 0 for non-ISO + usbMon.Write(data); + + BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbMon)).AsTask().Wait(); } public void DumpPacketIsoRequest(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit cmdSubmit, UsbIpIsoPacketDescriptor[] packetDescriptors, @@ -156,36 +156,36 @@ public void DumpPacketIsoRequest(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit cm var timestamp = GetTimestamp() / 10; // in micro seconds - using var usbmon = new BinaryWriter(new MemoryStream()); - usbmon.Write((ulong)basic.seqnum); - usbmon.Write((byte)'S'); - usbmon.Write((byte)0); // ISO - usbmon.Write(basic.RawEndpoint()); - usbmon.Write((byte)basic.devid); - usbmon.Write((ushort)(basic.devid >> 16)); - usbmon.Write((byte)'-'); - usbmon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); - usbmon.Write(timestamp / 1000000); // seconds - usbmon.Write((uint)(timestamp % 1000000)); // micro seconds - usbmon.Write(-115); // -EINPROGRESS - usbmon.Write(cmdSubmit.transfer_buffer_length); // length - usbmon.Write(data.Length + (packetDescriptors.Length * 16)); // actual - usbmon.Write((uint)0); // ISO error count - usbmon.Write((uint)packetDescriptors.Length); - usbmon.Write(cmdSubmit.interval); - usbmon.Write(cmdSubmit.start_frame); - usbmon.Write(cmdSubmit.transfer_flags); - usbmon.Write(cmdSubmit.number_of_packets); - usbmon.Write(data); + using var usbMon = new BinaryWriter(new MemoryStream()); + usbMon.Write((ulong)basic.seqnum); + usbMon.Write((byte)'S'); + usbMon.Write((byte)0); // ISO + usbMon.Write(basic.RawEndpoint()); + usbMon.Write((byte)basic.devid); + usbMon.Write((ushort)(basic.devid >> 16)); + usbMon.Write((byte)'-'); + usbMon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); + usbMon.Write(timestamp / 1000000); // seconds + usbMon.Write((uint)(timestamp % 1000000)); // micro seconds + usbMon.Write(-115); // -EINPROGRESS + usbMon.Write(cmdSubmit.transfer_buffer_length); // length + usbMon.Write(data.Length + (packetDescriptors.Length * 16)); // actual + usbMon.Write((uint)0); // ISO error count + usbMon.Write((uint)packetDescriptors.Length); + usbMon.Write(cmdSubmit.interval); + usbMon.Write(cmdSubmit.start_frame); + usbMon.Write(cmdSubmit.transfer_flags); + usbMon.Write(cmdSubmit.number_of_packets); + usbMon.Write(data); foreach (var packetDescriptor in packetDescriptors) { - usbmon.Write(packetDescriptor.status); - usbmon.Write(packetDescriptor.offset); - usbmon.Write(packetDescriptor.length); - usbmon.Write((uint)0); // padding + usbMon.Write(packetDescriptor.status); + usbMon.Write(packetDescriptor.offset); + usbMon.Write(packetDescriptor.length); + usbMon.Write((uint)0); // padding } - BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbmon)).AsTask().Wait(); + BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbMon)).AsTask().Wait(); } public void DumpPacketIsoReply(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit cmdSubmit, UsbIpHeaderRetSubmit retSubmit, @@ -198,39 +198,39 @@ public void DumpPacketIsoReply(UsbIpHeaderBasic basic, UsbIpHeaderCmdSubmit cmdS var timestamp = GetTimestamp() / 10; // in micro seconds - using var usbmon = new BinaryWriter(new MemoryStream()); - usbmon.Write((ulong)basic.seqnum); - usbmon.Write((byte)'C'); - usbmon.Write((byte)0); // ISO - usbmon.Write(basic.RawEndpoint()); - usbmon.Write((byte)basic.devid); - usbmon.Write((ushort)(basic.devid >> 16)); - usbmon.Write((byte)'-'); - usbmon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); - usbmon.Write(timestamp / 1000000); // seconds - usbmon.Write((uint)(timestamp % 1000000)); // micro seconds - usbmon.Write(retSubmit.status); - usbmon.Write(retSubmit.actual_length); // length - usbmon.Write(data.Length + (packetDescriptors.Length * 16)); // actual - usbmon.Write((uint)retSubmit.error_count); // ISO error count - usbmon.Write((uint)packetDescriptors.Length); - usbmon.Write(cmdSubmit.interval); - usbmon.Write(cmdSubmit.start_frame); - usbmon.Write(cmdSubmit.transfer_flags); - usbmon.Write(cmdSubmit.number_of_packets); + using var usbMon = new BinaryWriter(new MemoryStream()); + usbMon.Write((ulong)basic.seqnum); + usbMon.Write((byte)'C'); + usbMon.Write((byte)0); // ISO + usbMon.Write(basic.RawEndpoint()); + usbMon.Write((byte)basic.devid); + usbMon.Write((ushort)(basic.devid >> 16)); + usbMon.Write((byte)'-'); + usbMon.Write((byte)(data.IsEmpty ? basic.direction == UsbIpDir.USBIP_DIR_IN ? '<' : '>' : '\0')); + usbMon.Write(timestamp / 1000000); // seconds + usbMon.Write((uint)(timestamp % 1000000)); // micro seconds + usbMon.Write(retSubmit.status); + usbMon.Write(retSubmit.actual_length); // length + usbMon.Write(data.Length + (packetDescriptors.Length * 16)); // actual + usbMon.Write((uint)retSubmit.error_count); // ISO error count + usbMon.Write((uint)packetDescriptors.Length); + usbMon.Write(cmdSubmit.interval); + usbMon.Write(cmdSubmit.start_frame); + usbMon.Write(cmdSubmit.transfer_flags); + usbMon.Write(cmdSubmit.number_of_packets); var actualOffset = 0u; foreach (var packetDescriptor in packetDescriptors) { - // NOTE: Usbmon on Linux gets this wrong. On input, the actual_offset needs to be calculated. - usbmon.Write(packetDescriptor.status); - usbmon.Write(basic.direction == UsbIpDir.USBIP_DIR_IN ? actualOffset : packetDescriptor.offset); - usbmon.Write(packetDescriptor.actual_length); - usbmon.Write((uint)0); // padding + // NOTE: UsbMon on Linux gets this wrong. On input, the actual_offset needs to be calculated. + usbMon.Write(packetDescriptor.status); + usbMon.Write(basic.direction == UsbIpDir.USBIP_DIR_IN ? actualOffset : packetDescriptor.offset); + usbMon.Write(packetDescriptor.actual_length); + usbMon.Write((uint)0); // padding actualOffset += packetDescriptor.actual_length; } - usbmon.Write(data); + usbMon.Write(data); - BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbmon)).AsTask().Wait(); + BlockChannel.Writer.WriteAsync(CreateEnhancedPacketBlock(0, usbMon)).AsTask().Wait(); } static void UpdateChecksum(ref ushort checksum, byte[] data, int offset) @@ -263,7 +263,7 @@ public void DumpPacketUnlink(BusId busId, bool reply, UsbIpHeader header) } var source = reply ? hostFakeIpv4 : deviceFakeIpv4; - var dest = reply ? deviceFakeIpv4 : hostFakeIpv4; + var destination = reply ? deviceFakeIpv4 : hostFakeIpv4; using var ipv4 = new BinaryWriter(new MemoryStream()); // IPv4 header @@ -276,11 +276,11 @@ public void DumpPacketUnlink(BusId busId, bool reply, UsbIpHeader header) ipv4.Write((byte)6); // protocol = TCP ipv4.Write((ushort)0); // checksum (filled in later) ipv4.Write(source.Address.GetAddressBytes()); // source IP address - ipv4.Write(dest.Address.GetAddressBytes()); // destination IP address + ipv4.Write(destination.Address.GetAddressBytes()); // destination IP address // TCP header ipv4.Write(IPAddress.HostToNetworkOrder((short)source.Port)); // source port - ipv4.Write(IPAddress.HostToNetworkOrder((short)dest.Port)); // destination port + ipv4.Write(IPAddress.HostToNetworkOrder((short)destination.Port)); // destination port ipv4.Write(0); // sequence number (unused) ipv4.Write(0); // ACK number (unused) ipv4.Write((byte)0x50); // data offset (in uint_32), 0 (reserved) @@ -424,8 +424,8 @@ static byte[] CreateSectionHeaderBlock() { using var block = CreateBlock(0x0a0d0d0a); block.Write(0x1a2b3c4d); // endianness magic - block.Write((ushort)1); // major pcapng version - block.Write((ushort)0); // minor pcapng version + block.Write((ushort)1); // major PcapNg version + block.Write((ushort)0); // minor PcapNg version block.Write(0xffffffffffffffff); // unspecified section size AddOption(block, 3, $"{Environment.OSVersion.VersionString}"); // shb_os AddOption(block, 4, $"{Program.Product} {GitVersionInformation.InformationalVersion}"); // shb_userappl @@ -454,10 +454,10 @@ byte[] CreateInterfaceDescriptionBlockUnlink() return FinishBlock(block); } - byte[] CreateEnhancedPacketBlock(uint interfaceId, BinaryWriter usbmon) + byte[] CreateEnhancedPacketBlock(uint interfaceId, BinaryWriter usbMon) { - usbmon.Flush(); - var data = ((MemoryStream)usbmon.BaseStream).ToArray(); + usbMon.Flush(); + var data = ((MemoryStream)usbMon.BaseStream).ToArray(); return CreateEnhancedPacketBlock(interfaceId, data); } diff --git a/Usbipd/Policy.cs b/Usbipd/Policy.cs index 54b2f7c2..b543e893 100644 --- a/Usbipd/Policy.cs +++ b/Usbipd/Policy.cs @@ -16,7 +16,7 @@ public static bool IsAutoBindAllowed(UsbDevice device, IPAddress? client = null) // Firewalling is not supported yet. _ = client; - var rules = RegistryUtils.GetPolicyRules(); + var rules = RegistryUtilities.GetPolicyRules(); var allowed = rules.Values.Where(r => r.Effect == PolicyRuleEffect.Allow); var denied = rules.Values.Where(r => r.Effect == PolicyRuleEffect.Deny); diff --git a/Usbipd/PolicyRuleAutoBind.cs b/Usbipd/PolicyRuleAutoBind.cs index e5a3292c..e83bc50f 100644 --- a/Usbipd/PolicyRuleAutoBind.cs +++ b/Usbipd/PolicyRuleAutoBind.cs @@ -7,8 +7,8 @@ namespace Usbipd; -sealed record PolicyRuleAutoBind(PolicyRuleEffect effect, BusId? BusId, VidPid? HardwareId) - : PolicyRule(effect, PolicyRuleOperation.AutoBind) +sealed record PolicyRuleAutoBind(PolicyRuleEffect Effect, BusId? BusId, VidPid? HardwareId) + : PolicyRule(Effect, PolicyRuleOperation.AutoBind) { const string BusIdName = "BusId"; const string HardwareIdName = "HardwareId"; diff --git a/Usbipd/Program.cs b/Usbipd/Program.cs index 237e249f..a4056909 100644 --- a/Usbipd/Program.cs +++ b/Usbipd/Program.cs @@ -507,7 +507,7 @@ await commandHandlers.List(invocationContext.ParseResult.HasOption(usbidsOption) ArgumentHelpName = "GUID", Description = "Remove the policy rule having ", }.AddCompletions(completionContext => CompletionGuard(completionContext, () => - RegistryUtils.GetPolicyRules().Select(r => r.Key.ToString("D")))); + RegistryUtilities.GetPolicyRules().Select(r => r.Key.ToString("D")))); // // policy remove // @@ -610,7 +610,7 @@ await commandHandlers.Server(invocationContext.ParseResult.GetValueForArgument(k ArgumentHelpName = "GUID", Description = "Stop sharing persisted device having ", }.AddCompletions(completionContext => CompletionGuard(completionContext, () => - RegistryUtils.GetBoundDevices().Where(d => !d.BusId.HasValue).Select(d => d.Guid.GetValueOrDefault().ToString("D")))); + RegistryUtilities.GetBoundDevices().Where(d => !d.BusId.HasValue).Select(d => d.Guid.GetValueOrDefault().ToString("D")))); // // unbind [--hardware-id :] // diff --git a/Usbipd/RegistryUtils.cs b/Usbipd/RegistryUtilities.cs similarity index 99% rename from Usbipd/RegistryUtils.cs rename to Usbipd/RegistryUtilities.cs index 1aafc447..015d1c9c 100644 --- a/Usbipd/RegistryUtils.cs +++ b/Usbipd/RegistryUtilities.cs @@ -12,7 +12,7 @@ namespace Usbipd; -static class RegistryUtils +static class RegistryUtilities { const string DevicesRegistryPath = @"SOFTWARE\usbipd-win"; diff --git a/Usbipd/Server.cs b/Usbipd/Server.cs index 95abeefb..2e104005 100644 --- a/Usbipd/Server.cs +++ b/Usbipd/Server.cs @@ -82,7 +82,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken) Logger.Debug(GitVersionInformation.InformationalVersion); // Cleanup any left-overs in case the previous instance crashed. - _ = RegistryUtils.SetAllDevicesAsDetached(); + _ = RegistryUtilities.SetAllDevicesAsDetached(); // Non-interactive services have this disabled by default. // We require it so the ConfigurationManager can change the driver. diff --git a/Usbipd/Tools.cs b/Usbipd/Tools.cs index f630b134..8eafbc8e 100644 --- a/Usbipd/Tools.cs +++ b/Usbipd/Tools.cs @@ -31,12 +31,12 @@ public static async Task ReadMessageAsync(this Stream stream, Memory buf, { return; } - var rlen = await stream.ReadAtLeastAsync(buf, 1, true, cancellationToken); - if (rlen < buf.Length) + var readLength = await stream.ReadAtLeastAsync(buf, 1, true, cancellationToken); + if (readLength < buf.Length) { try { - await stream.ReadExactlyAsync(buf[rlen..], cancellationToken); + await stream.ReadExactlyAsync(buf[readLength..], cancellationToken); } catch (EndOfStreamException) { diff --git a/Usbipd/UsbDevice.cs b/Usbipd/UsbDevice.cs index 34e7afb1..240876dc 100644 --- a/Usbipd/UsbDevice.cs +++ b/Usbipd/UsbDevice.cs @@ -37,7 +37,7 @@ public VidPid HardwareId /// public static IEnumerable GetAll() { - var usbDevices = new Dictionary(RegistryUtils.GetBoundDevices().Select(d => KeyValuePair.Create(d.InstanceId, d))); + var usbDevices = new Dictionary(RegistryUtilities.GetBoundDevices().Select(d => KeyValuePair.Create(d.InstanceId, d))); foreach (var device in ConfigurationManager.GetConnectedUsbDevices()) { if (usbDevices.ContainsKey(device.InstanceId))