Fix threading issues in PowerShell cmdlets (v2025.04.15.1543)

This commit is contained in:
GraceSolutions
2025-04-15 16:50:35 -04:00
parent 570860bdc2
commit 09de38898d
71 changed files with 2670 additions and 1863 deletions
@@ -46,55 +46,70 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var firewallService = new FirewallService(ApiClient, Logger);
var firewallService = new FirewallService(ApiClient, Logger);
if (NoRollback.IsPresent)
if (NoRollback.IsPresent)
{
WriteVerbose("Applying firewall changes without rollback protection");
var applyResult = ExecuteAsyncTask(() => firewallService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
WriteVerbose("Applying firewall changes without rollback protection");
var applyTask = Task.Run(async () => await firewallService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Firewall changes applied: {applyResult.Status}");
return;
}
WriteVerbose($"Firewall changes applied: {applyResult.Status}");
}
else
{
WriteVerbose("Creating savepoint for rollback protection");
var savepointResult = ExecuteAsyncTask(() => firewallService.CreateSavepointAsync());
// Only continue if no exception occurred
if (ProcessingException != null || savepointResult == null)
{
return;
}
var revision = savepointResult.Revision;
WriteVerbose($"Created savepoint with revision {revision}");
WriteVerbose("Applying firewall changes with rollback protection");
var applyResult = ExecuteAsyncTask(() => firewallService.ApplyChangesAsync(revision));
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"Firewall changes applied: {applyResult.Status}");
if (CancelRollback.IsPresent)
{
WriteVerbose($"Waiting {Timeout} seconds before cancelling rollback");
System.Threading.Thread.Sleep(Timeout * 1000);
WriteVerbose("Cancelling automatic rollback");
var cancelResult = ExecuteAsyncTask(() => firewallService.CancelRollbackAsync(revision));
// Only continue if no exception occurred
if (ProcessingException != null || cancelResult == null)
{
return;
}
WriteVerbose($"Rollback cancelled: {cancelResult.Status}");
}
else
{
WriteVerbose("Creating savepoint for rollback protection");
var savepointTask = Task.Run(async () => await firewallService.CreateSavepointAsync());
var savepointResult = savepointTask.GetAwaiter().GetResult();
var revision = savepointResult.Revision;
WriteVerbose($"Created savepoint with revision {revision}");
WriteVerbose("Applying firewall changes with rollback protection");
var applyTask = Task.Run(async () => await firewallService.ApplyChangesAsync(revision));
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Firewall changes applied: {applyResult.Status}");
if (CancelRollback.IsPresent)
{
WriteVerbose($"Waiting {Timeout} seconds before cancelling rollback");
System.Threading.Thread.Sleep(Timeout * 1000);
WriteVerbose("Cancelling automatic rollback");
var cancelTask = Task.Run(async () => await firewallService.CancelRollbackAsync(revision));
var cancelResult = cancelTask.GetAwaiter().GetResult();
WriteVerbose($"Rollback cancelled: {cancelResult.Status}");
}
else
{
WriteVerbose($"Automatic rollback will occur in 60 seconds if connectivity is lost");
}
WriteVerbose($"Automatic rollback will occur in 60 seconds if connectivity is lost");
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
}
@@ -57,6 +57,14 @@ namespace PSOPNSenseAPI.Cmdlets
[Parameter(Mandatory = false, ParameterSetName = "FromIPWithSubnetMask")]
public string IPWithSubnetMask { get; set; }
/// <summary>
/// Begins the processing of the cmdlet
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
}
/// <summary>
/// Processes the cmdlet
/// </summary>
@@ -88,22 +96,16 @@ namespace PSOPNSenseAPI.Cmdlets
string[] parts = IPWithCIDR.Split('/');
if (parts.Length != 2)
{
WriteError(new ErrorRecord(
new ArgumentException($"Invalid IP with CIDR: {IPWithCIDR}. Expected format: 192.168.1.0/24"),
"InvalidIPWithCIDR",
ErrorCategory.InvalidArgument,
null));
// Use WriteWarning instead of WriteError to avoid threading issues
WriteWarning($"Invalid IP with CIDR: {IPWithCIDR}. Expected format: 192.168.1.0/24");
return;
}
string ip = parts[0];
if (!int.TryParse(parts[1], out int cidr))
{
WriteError(new ErrorRecord(
new ArgumentException($"Invalid CIDR: {parts[1]}"),
"InvalidCIDR",
ErrorCategory.InvalidArgument,
null));
// Use WriteWarning instead of WriteError to avoid threading issues
WriteWarning($"Invalid CIDR: {parts[1]}");
return;
}
@@ -118,11 +120,8 @@ namespace PSOPNSenseAPI.Cmdlets
string[] parts = IPWithSubnetMask.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (parts.Length != 2)
{
WriteError(new ErrorRecord(
new ArgumentException($"Invalid IP with subnet mask: {IPWithSubnetMask}. Expected format: 192.168.1.0 255.255.255.0"),
"InvalidIPWithSubnetMask",
ErrorCategory.InvalidArgument,
null));
// Use WriteWarning instead of WriteError to avoid threading issues
WriteWarning($"Invalid IP with subnet mask: {IPWithSubnetMask}. Expected format: 192.168.1.0 255.255.255.0");
return;
}
@@ -136,12 +135,17 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"ConversionError",
ErrorCategory.InvalidOperation,
null));
// Use WriteWarning instead of WriteError to avoid threading issues
WriteWarning($"Conversion error: {ex.Message}");
}
}
/// <summary>
/// Ends the processing of the cmdlet
/// </summary>
protected override void EndProcessing()
{
base.EndProcessing();
}
}
}
@@ -28,21 +28,20 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var firewallService = new FirewallService(ApiClient, Logger);
var firewallService = new FirewallService(ApiClient, Logger);
var task = Task.Run(async () => await firewallService.ToggleRuleAsync(Uuid, false));
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => firewallService.ToggleRuleAsync(Uuid, false));
WriteVerbose($"Firewall rule {Uuid} disabled: {result.Result}");
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteVerbose($"Firewall rule {Uuid} disabled: {result.Result}");
}
}
}
@@ -28,22 +28,21 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var pluginService = new PluginService(ApiClient, Logger);
var pluginService = new PluginService(ApiClient, Logger);
var task = Task.Run(async () => await pluginService.DisablePluginAsync(Name));
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => pluginService.DisablePluginAsync(Name));
WriteVerbose($"Plugin {Name} disabled: {result.Status}");
WriteObject($"Plugin {Name} disabled: {result.Status}");
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteVerbose($"Plugin {Name} disabled: {result.Status}");
WriteObject($"Plugin {Name} disabled: {result.Status}");
}
}
}
@@ -38,79 +38,100 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var tailscaleService = new TailscaleService(ApiClient, Logger);
// Check if the plugin is installed
var isInstalled = ExecuteAsyncTask(() => tailscaleService.IsPluginInstalledAsync());
// Only continue if no exception occurred
if (ProcessingException != null)
{
var tailscaleService = new TailscaleService(ApiClient, Logger);
return;
}
// Check if the plugin is installed
var isInstalledTask = Task.Run(async () => await tailscaleService.IsPluginInstalledAsync());
var isInstalled = isInstalledTask.GetAwaiter().GetResult();
if (!isInstalled)
{
WriteWarning("Tailscale plugin is not installed on the OPNSense firewall.");
return;
}
if (!isInstalled)
{
WriteWarning("Tailscale plugin is not installed on the OPNSense firewall.");
return;
}
// Get current settings
var settingsResult = ExecuteAsyncTask(() => tailscaleService.GetSettingsAsync());
// Get current settings
var settingsTask = Task.Run(async () => await tailscaleService.GetSettingsAsync());
var currentSettings = settingsTask.GetAwaiter().GetResult().General;
// Only continue if no exception occurred
if (ProcessingException != null || settingsResult == null)
{
return;
}
// Create new settings with disabled flag
var settings = new TailscaleSettings
{
Enabled = "0",
AcceptDns = currentSettings.AcceptDns,
AcceptRoutes = currentSettings.AcceptRoutes,
AdvertiseExitNode = currentSettings.AdvertiseExitNode,
AdvertiseRoutes = currentSettings.AdvertiseRoutes,
RoutesToAdvertise = currentSettings.RoutesToAdvertise,
Hostname = currentSettings.Hostname,
LoginServer = currentSettings.LoginServer,
Ssh = currentSettings.Ssh,
Ephemeral = currentSettings.Ephemeral,
ResetOnStart = currentSettings.ResetOnStart
};
var currentSettings = settingsResult.General;
if (!Force.IsPresent && !ShouldProcess("OPNSense firewall", "Disable Tailscale"))
// Create new settings with disabled flag
var settings = new TailscaleSettings
{
Enabled = "0",
AcceptDns = currentSettings.AcceptDns,
AcceptRoutes = currentSettings.AcceptRoutes,
AdvertiseExitNode = currentSettings.AdvertiseExitNode,
AdvertiseRoutes = currentSettings.AdvertiseRoutes,
RoutesToAdvertise = currentSettings.RoutesToAdvertise,
Hostname = currentSettings.Hostname,
LoginServer = currentSettings.LoginServer,
Ssh = currentSettings.Ssh,
Ephemeral = currentSettings.Ephemeral,
ResetOnStart = currentSettings.ResetOnStart
};
if (!Force.IsPresent && !ShouldProcess("OPNSense firewall", "Disable Tailscale"))
{
return;
}
// Update settings
var updateResult = ExecuteAsyncTask(() => tailscaleService.UpdateSettingsAsync(settings));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Tailscale settings updated: {updateResult.Result}");
// Stop the service if requested
if (Stop.IsPresent)
{
WriteVerbose("Stopping Tailscale service...");
var stopResult = ExecuteAsyncTask(() => tailscaleService.StopServiceAsync());
// Only continue if no exception occurred
if (ProcessingException != null || stopResult == null)
{
return;
}
// Update settings
var updateTask = Task.Run(async () => await tailscaleService.UpdateSettingsAsync(settings));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Tailscale settings updated: {updateResult.Result}");
// Stop the service if requested
if (Stop.IsPresent)
{
WriteVerbose("Stopping Tailscale service...");
var stopTask = Task.Run(async () => await tailscaleService.StopServiceAsync());
var stopResult = stopTask.GetAwaiter().GetResult();
WriteVerbose($"Tailscale service stopped: {stopResult.Status}");
}
// Get updated status
var statusTask = Task.Run(async () => await tailscaleService.GetStatusAsync());
var status = statusTask.GetAwaiter().GetResult();
// Create result object
var result = new PSObject();
result.Properties.Add(new PSNoteProperty("PluginInstalled", true));
result.Properties.Add(new PSNoteProperty("Enabled", status.Enabled));
result.Properties.Add(new PSNoteProperty("Running", status.Running));
result.Properties.Add(new PSNoteProperty("Status", status.Status));
WriteObject(result);
WriteVerbose($"Tailscale service stopped: {stopResult.Status}");
}
catch (Exception ex)
// Get updated status
var status = ExecuteAsyncTask(() => tailscaleService.GetStatusAsync());
// Only continue if no exception occurred
if (ProcessingException != null || status == null)
{
HandleException(ex);
return;
}
// Create result object
var result = new PSObject();
result.Properties.Add(new PSNoteProperty("PluginInstalled", true));
result.Properties.Add(new PSNoteProperty("Enabled", status.Enabled));
result.Properties.Add(new PSNoteProperty("Running", status.Running));
result.Properties.Add(new PSNoteProperty("Status", status.Status));
WriteObject(result);
}
}
}
@@ -17,6 +17,14 @@ namespace PSOPNSenseAPI.Cmdlets
[OutputType(typeof(void))]
public class DisconnectOPNSenseCmdlet : PSCmdlet
{
/// <summary>
/// Begins the processing of the cmdlet
/// </summary>
protected override void BeginProcessing()
{
base.BeginProcessing();
}
/// <summary>
/// Processes the cmdlet
/// </summary>
@@ -38,12 +46,17 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"DisconnectionFailed",
ErrorCategory.ConnectionError,
null));
// Use WriteWarning instead of WriteError to avoid threading issues
WriteWarning($"Failed to disconnect: {ex.Message}");
}
}
/// <summary>
/// Ends the processing of the cmdlet
/// </summary>
protected override void EndProcessing()
{
base.EndProcessing();
}
}
}
@@ -28,21 +28,20 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var firewallService = new FirewallService(ApiClient, Logger);
var firewallService = new FirewallService(ApiClient, Logger);
var task = Task.Run(async () => await firewallService.ToggleRuleAsync(Uuid, true));
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => firewallService.ToggleRuleAsync(Uuid, true));
WriteVerbose($"Firewall rule {Uuid} enabled: {result.Result}");
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteVerbose($"Firewall rule {Uuid} enabled: {result.Result}");
}
}
}
@@ -28,22 +28,21 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var pluginService = new PluginService(ApiClient, Logger);
var pluginService = new PluginService(ApiClient, Logger);
var task = Task.Run(async () => await pluginService.EnablePluginAsync(Name));
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => pluginService.EnablePluginAsync(Name));
WriteVerbose($"Plugin {Name} enabled: {result.Status}");
WriteObject($"Plugin {Name} enabled: {result.Status}");
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteVerbose($"Plugin {Name} enabled: {result.Status}");
WriteObject($"Plugin {Name} enabled: {result.Status}");
}
}
}
@@ -35,28 +35,31 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
string fullPath = Path.FullName;
// Check if the file exists
if (File.Exists(fullPath) && !Force.IsPresent)
{
ProcessingException = new IOException($"The file '{fullPath}' already exists. Use -Force to overwrite.");
WriteWarning($"The file '{fullPath}' already exists. Use -Force to overwrite.");
return;
}
var configService = new ConfigService(ApiClient, Logger);
// Use our safe execution method
var configContent = ExecuteAsyncTask(() => configService.ExportConfigAsync());
// Only continue if no exception occurred
if (ProcessingException != null || configContent == null)
{
return;
}
try
{
string fullPath = Path.FullName;
// Check if the file exists
if (File.Exists(fullPath) && !Force.IsPresent)
{
WriteError(new ErrorRecord(
new IOException($"The file '{fullPath}' already exists. Use -Force to overwrite."),
"FileExists",
ErrorCategory.ResourceExists,
fullPath));
return;
}
var configService = new ConfigService(ApiClient, Logger);
// Execute the async method synchronously on the main thread
var configContent = configService.ExportConfigAsync().GetAwaiter().GetResult();
// Create the directory if it doesn't exist
var directory = System.IO.Path.GetDirectoryName(fullPath);
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory))
@@ -71,7 +74,8 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
HandleException(ex);
ProcessingException = ex;
WriteWarning($"Failed to write configuration to file: {ex.Message}");
}
}
}
@@ -52,54 +52,60 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var aliasService = new AliasService(ApiClient, Logger);
if (ParameterSetName == "ByUuid")
{
var aliasService = new AliasService(ApiClient, Logger);
// Use our safe execution method
var result = ExecuteAsyncTask(() => aliasService.GetAliasAsync(Uuid));
if (ParameterSetName == "ByUuid")
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
var task = Task.Run(async () => await aliasService.GetAliasAsync(Uuid));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Alias);
return;
}
else
{
var task = Task.Run(async () => await aliasService.GetAliasesAsync());
var result = task.GetAwaiter().GetResult();
// Filter by name if specified
if (ParameterSetName == "ByName")
WriteObject(result.Alias);
}
else
{
// Use our safe execution method
var result = ExecuteAsyncTask(() => aliasService.GetAliasesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
// Filter by name if specified
if (ParameterSetName == "ByName")
{
var filteredByName = result.Rows.FindAll(a => a.Name.Equals(Name, StringComparison.OrdinalIgnoreCase));
// Further filter by type if specified
if (!string.IsNullOrEmpty(Type))
{
var filteredByName = result.Rows.FindAll(a => a.Name.Equals(Name, StringComparison.OrdinalIgnoreCase));
// Further filter by type if specified
if (!string.IsNullOrEmpty(Type))
{
var filteredByType = filteredByName.FindAll(a => a.Type.Equals(Type, StringComparison.OrdinalIgnoreCase));
WriteObject(filteredByType, true);
}
else
{
WriteObject(filteredByName, true);
}
}
// Filter by type if specified
else if (!string.IsNullOrEmpty(Type))
{
var filteredByType = result.Rows.FindAll(a => a.Type.Equals(Type, StringComparison.OrdinalIgnoreCase));
var filteredByType = filteredByName.FindAll(a => a.Type.Equals(Type, StringComparison.OrdinalIgnoreCase));
WriteObject(filteredByType, true);
}
else
{
WriteObject(result.Rows, true);
WriteObject(filteredByName, true);
}
}
}
catch (Exception ex)
{
HandleException(ex);
// Filter by type if specified
else if (!string.IsNullOrEmpty(Type))
{
var filteredByType = result.Rows.FindAll(a => a.Type.Equals(Type, StringComparison.OrdinalIgnoreCase));
WriteObject(filteredByType, true);
}
else
{
WriteObject(result.Rows, true);
}
}
}
}
@@ -21,21 +21,20 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var configService = new ConfigService(ApiClient, Logger);
var configService = new ConfigService(ApiClient, Logger);
var task = Task.Run(async () => await configService.GetConfigBackupsAsync());
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => configService.GetConfigBackupsAsync());
WriteObject(result.Backups, true);
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteObject(result.Backups, true);
}
}
}
@@ -28,17 +28,23 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
var configService = new ConfigService(ApiClient, Logger);
// Use our safe execution method
var configContent = ExecuteAsyncTask(() => configService.ExportConfigAsync());
// Only continue if no exception occurred
if (ProcessingException != null || configContent == null)
{
return;
}
// Convert the byte array to an XML document
var xmlDoc = new XmlDocument();
try
{
var configService = new ConfigService(ApiClient, Logger);
// Execute the async method synchronously on the main thread
var configContent = configService.ExportConfigAsync().GetAwaiter().GetResult();
// Convert the byte array to an XML document
var xmlDoc = new XmlDocument();
using (var memoryStream = new MemoryStream(configContent))
{
xmlDoc.Load(memoryStream);
@@ -49,7 +55,8 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
HandleException(ex);
ProcessingException = ex;
WriteWarning($"Failed to parse XML configuration: {ex.Message}");
}
}
}
@@ -40,28 +40,35 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var dhcpService = new DHCPService(ApiClient, Logger);
var dhcpService = new DHCPService(ApiClient, Logger);
if (ParameterSetName == "ByUuid")
{
var task = Task.Run(async () => await dhcpService.GetOptionAsync(Interface, Uuid));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Option);
}
else
{
var task = Task.Run(async () => await dhcpService.GetOptionsAsync(Interface));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Rows, true);
}
}
catch (Exception ex)
if (ParameterSetName == "ByUuid")
{
HandleException(ex);
// Use our safe execution method
var result = ExecuteAsyncTask(() => dhcpService.GetOptionAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Option);
}
else
{
// Use our safe execution method
var result = ExecuteAsyncTask(() => dhcpService.GetOptionsAsync(Interface));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Rows, true);
}
}
}
@@ -33,43 +33,49 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
if (ParameterSetName == "ByInterface")
{
var dhcpService = new DHCPService(ApiClient, Logger);
// Use our safe execution method
var result = ExecuteAsyncTask(() => dhcpService.GetServerAsync(Interface));
if (ParameterSetName == "ByInterface")
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
var task = Task.Run(async () => await dhcpService.GetServerAsync(Interface));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Server);
return;
}
else
{
var task = Task.Run(async () => await dhcpService.GetServersAsync());
var result = task.GetAwaiter().GetResult();
foreach (var kvp in result.Servers.Interfaces)
{
var server = new PSObject();
server.Properties.Add(new PSNoteProperty("Interface", kvp.Key));
server.Properties.Add(new PSNoteProperty("Enabled", kvp.Value.Enabled == "1"));
server.Properties.Add(new PSNoteProperty("RangeFrom", kvp.Value.RangeFrom));
server.Properties.Add(new PSNoteProperty("RangeTo", kvp.Value.RangeTo));
server.Properties.Add(new PSNoteProperty("DefaultLeaseTime", kvp.Value.DefaultLeaseTime));
server.Properties.Add(new PSNoteProperty("MaxLeaseTime", kvp.Value.MaxLeaseTime));
server.Properties.Add(new PSNoteProperty("Domain", kvp.Value.Domain));
server.Properties.Add(new PSNoteProperty("DnsServers", kvp.Value.DnsServers));
server.Properties.Add(new PSNoteProperty("Gateway", kvp.Value.Gateway));
WriteObject(server);
}
}
WriteObject(result.Server);
}
catch (Exception ex)
else
{
HandleException(ex);
// Use our safe execution method
var result = ExecuteAsyncTask(() => dhcpService.GetServersAsync());
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
foreach (var kvp in result.Servers.Interfaces)
{
var server = new PSObject();
server.Properties.Add(new PSNoteProperty("Interface", kvp.Key));
server.Properties.Add(new PSNoteProperty("Enabled", kvp.Value.Enabled == "1"));
server.Properties.Add(new PSNoteProperty("RangeFrom", kvp.Value.RangeFrom));
server.Properties.Add(new PSNoteProperty("RangeTo", kvp.Value.RangeTo));
server.Properties.Add(new PSNoteProperty("DefaultLeaseTime", kvp.Value.DefaultLeaseTime));
server.Properties.Add(new PSNoteProperty("MaxLeaseTime", kvp.Value.MaxLeaseTime));
server.Properties.Add(new PSNoteProperty("Domain", kvp.Value.Domain));
server.Properties.Add(new PSNoteProperty("DnsServers", kvp.Value.DnsServers));
server.Properties.Add(new PSNoteProperty("Gateway", kvp.Value.Gateway));
WriteObject(server);
}
}
}
}
@@ -40,28 +40,35 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var dhcpService = new DHCPService(ApiClient, Logger);
var dhcpService = new DHCPService(ApiClient, Logger);
if (ParameterSetName == "ByUuid")
{
var task = Task.Run(async () => await dhcpService.GetStaticMappingAsync(Interface, Uuid));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Mapping);
}
else
{
var task = Task.Run(async () => await dhcpService.GetStaticMappingsAsync(Interface));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Rows, true);
}
}
catch (Exception ex)
if (ParameterSetName == "ByUuid")
{
HandleException(ex);
// Use our safe execution method
var result = ExecuteAsyncTask(() => dhcpService.GetStaticMappingAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Mapping);
}
else
{
// Use our safe execution method
var result = ExecuteAsyncTask(() => dhcpService.GetStaticMappingsAsync(Interface));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Rows, true);
}
}
}
@@ -21,21 +21,20 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var dnsService = new DNSService(ApiClient, Logger);
var dnsService = new DNSService(ApiClient, Logger);
var task = Task.Run(async () => await dnsService.GetDNSForwardingAsync());
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => dnsService.GetDNSForwardingAsync());
WriteObject(result.Forward);
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteObject(result.Forward);
}
}
}
@@ -21,32 +21,31 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dnsService = new DNSService(ApiClient, Logger);
// Use our safe execution method
var result = ExecuteAsyncTask(() => dnsService.GetDNSConfigAsync());
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
var dnsService = new DNSService(ApiClient, Logger);
var task = Task.Run(async () => await dnsService.GetDNSConfigAsync());
var result = task.GetAwaiter().GetResult();
var dnsConfig = new PSObject();
dnsConfig.Properties.Add(new PSNoteProperty("Enabled", result.Unbound.Enabled == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("Port", result.Unbound.Port));
dnsConfig.Properties.Add(new PSNoteProperty("Interfaces", result.Unbound.Interfaces));
dnsConfig.Properties.Add(new PSNoteProperty("Forwarding", result.Unbound.Forwarding == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("Forwarders", result.Unbound.Forwarders));
dnsConfig.Properties.Add(new PSNoteProperty("RegisterDhcp", result.Unbound.RegisterDhcp == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("RegisterDhcpDomain", result.Unbound.RegisterDhcpDomain));
dnsConfig.Properties.Add(new PSNoteProperty("RegisterDhcpStatic", result.Unbound.RegisterDhcpStatic == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("ActiveInterfaces", result.Unbound.ActiveInterfaces));
WriteObject(dnsConfig);
}
catch (Exception ex)
{
HandleException(ex);
return;
}
var dnsConfig = new PSObject();
dnsConfig.Properties.Add(new PSNoteProperty("Enabled", result.Unbound.Enabled == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("Port", result.Unbound.Port));
dnsConfig.Properties.Add(new PSNoteProperty("Interfaces", result.Unbound.Interfaces));
dnsConfig.Properties.Add(new PSNoteProperty("Forwarding", result.Unbound.Forwarding == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("Forwarders", result.Unbound.Forwarders));
dnsConfig.Properties.Add(new PSNoteProperty("RegisterDhcp", result.Unbound.RegisterDhcp == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("RegisterDhcpDomain", result.Unbound.RegisterDhcpDomain));
dnsConfig.Properties.Add(new PSNoteProperty("RegisterDhcpStatic", result.Unbound.RegisterDhcpStatic == "1"));
dnsConfig.Properties.Add(new PSNoteProperty("ActiveInterfaces", result.Unbound.ActiveInterfaces));
WriteObject(dnsConfig);
}
}
}
@@ -58,28 +58,35 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var firewallService = new FirewallService(ApiClient, Logger);
var firewallService = new FirewallService(ApiClient, Logger);
if (ParameterSetName == "ByUuid")
{
var task = Task.Run(async () => await firewallService.GetRuleAsync(Uuid));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Rule);
}
else
{
var task = Task.Run(async () => await firewallService.GetRulesAsync(SearchPhrase, Page, RowCount));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Rows, true);
}
}
catch (Exception ex)
if (ParameterSetName == "ByUuid")
{
HandleException(ex);
// Use our safe execution method
var result = ExecuteAsyncTask(() => firewallService.GetRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Rule);
}
else
{
// Use our safe execution method
var result = ExecuteAsyncTask(() => firewallService.GetRulesAsync(SearchPhrase, Page, RowCount));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Rows, true);
}
}
}
@@ -26,33 +26,32 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var interfaceService = new InterfaceService(ApiClient, Logger);
// Use our safe execution method
var result = ExecuteAsyncTask(() => interfaceService.GetInterfaceStatisticsAsync());
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
var interfaceService = new InterfaceService(ApiClient, Logger);
var task = Task.Run(async () => await interfaceService.GetInterfaceStatisticsAsync());
var result = task.GetAwaiter().GetResult();
foreach (var kvp in result.Statistics)
{
var stats = new PSObject();
stats.Properties.Add(new PSNoteProperty("Name", kvp.Key));
stats.Properties.Add(new PSNoteProperty("InPackets", kvp.Value.InPackets));
stats.Properties.Add(new PSNoteProperty("InBytes", kvp.Value.InBytes));
stats.Properties.Add(new PSNoteProperty("InErrors", 0));
stats.Properties.Add(new PSNoteProperty("OutPackets", kvp.Value.OutPackets));
stats.Properties.Add(new PSNoteProperty("OutBytes", kvp.Value.OutBytes));
stats.Properties.Add(new PSNoteProperty("OutErrors", 0));
stats.Properties.Add(new PSNoteProperty("Collisions", 0));
WriteObject(stats);
}
return;
}
catch (Exception ex)
foreach (var kvp in result.Statistics)
{
HandleException(ex);
var stats = new PSObject();
stats.Properties.Add(new PSNoteProperty("Name", kvp.Key));
stats.Properties.Add(new PSNoteProperty("InPackets", kvp.Value.InPackets));
stats.Properties.Add(new PSNoteProperty("InBytes", kvp.Value.InBytes));
stats.Properties.Add(new PSNoteProperty("InErrors", 0));
stats.Properties.Add(new PSNoteProperty("OutPackets", kvp.Value.OutPackets));
stats.Properties.Add(new PSNoteProperty("OutBytes", kvp.Value.OutBytes));
stats.Properties.Add(new PSNoteProperty("OutErrors", 0));
stats.Properties.Add(new PSNoteProperty("Collisions", 0));
WriteObject(stats);
}
}
}
@@ -43,60 +43,59 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var pluginService = new PluginService(ApiClient, Logger);
// Use our safe execution method
var result = ExecuteAsyncTask(() => pluginService.GetPluginsAsync());
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
var pluginService = new PluginService(ApiClient, Logger);
return;
}
var task = Task.Run(async () => await pluginService.GetPluginsAsync());
var result = task.GetAwaiter().GetResult();
if (ParameterSetName == "Installed" || ParameterSetName == "")
if (ParameterSetName == "Installed" || ParameterSetName == "")
{
foreach (var kvp in result.Installed)
{
foreach (var kvp in result.Installed)
{
var plugin = new PSObject();
plugin.Properties.Add(new PSNoteProperty("Name", kvp.Key));
plugin.Properties.Add(new PSNoteProperty("Version", kvp.Value.Version));
plugin.Properties.Add(new PSNoteProperty("Comment", kvp.Value.Comment));
plugin.Properties.Add(new PSNoteProperty("Repository", kvp.Value.Repository));
plugin.Properties.Add(new PSNoteProperty("Origin", kvp.Value.Origin));
plugin.Properties.Add(new PSNoteProperty("License", kvp.Value.License));
plugin.Properties.Add(new PSNoteProperty("FlatSize", kvp.Value.FlatSize));
plugin.Properties.Add(new PSNoteProperty("Locked", kvp.Value.Locked == "1"));
plugin.Properties.Add(new PSNoteProperty("Enabled", kvp.Value.Enabled == "1"));
plugin.Properties.Add(new PSNoteProperty("Status", "Installed"));
WriteObject(plugin);
}
}
var plugin = new PSObject();
plugin.Properties.Add(new PSNoteProperty("Name", kvp.Key));
plugin.Properties.Add(new PSNoteProperty("Version", kvp.Value.Version));
plugin.Properties.Add(new PSNoteProperty("Comment", kvp.Value.Comment));
plugin.Properties.Add(new PSNoteProperty("Repository", kvp.Value.Repository));
plugin.Properties.Add(new PSNoteProperty("Origin", kvp.Value.Origin));
plugin.Properties.Add(new PSNoteProperty("License", kvp.Value.License));
plugin.Properties.Add(new PSNoteProperty("FlatSize", kvp.Value.FlatSize));
plugin.Properties.Add(new PSNoteProperty("Locked", kvp.Value.Locked == "1"));
plugin.Properties.Add(new PSNoteProperty("Enabled", kvp.Value.Enabled == "1"));
plugin.Properties.Add(new PSNoteProperty("Status", "Installed"));
if (ParameterSetName == "Available" || ParameterSetName == "")
{
foreach (var kvp in result.Available)
{
// Skip if the plugin is already installed
if (result.Installed.ContainsKey(kvp.Key))
continue;
var plugin = new PSObject();
plugin.Properties.Add(new PSNoteProperty("Name", kvp.Key));
plugin.Properties.Add(new PSNoteProperty("Version", kvp.Value.Version));
plugin.Properties.Add(new PSNoteProperty("Comment", kvp.Value.Comment));
plugin.Properties.Add(new PSNoteProperty("Repository", kvp.Value.Repository));
plugin.Properties.Add(new PSNoteProperty("Origin", kvp.Value.Origin));
plugin.Properties.Add(new PSNoteProperty("License", kvp.Value.License));
plugin.Properties.Add(new PSNoteProperty("FlatSize", kvp.Value.FlatSize));
plugin.Properties.Add(new PSNoteProperty("Status", "Available"));
WriteObject(plugin);
}
WriteObject(plugin);
}
}
catch (Exception ex)
if (ParameterSetName == "Available" || ParameterSetName == "")
{
HandleException(ex);
foreach (var kvp in result.Available)
{
// Skip if the plugin is already installed
if (result.Installed.ContainsKey(kvp.Key))
continue;
var plugin = new PSObject();
plugin.Properties.Add(new PSNoteProperty("Name", kvp.Key));
plugin.Properties.Add(new PSNoteProperty("Version", kvp.Value.Version));
plugin.Properties.Add(new PSNoteProperty("Comment", kvp.Value.Comment));
plugin.Properties.Add(new PSNoteProperty("Repository", kvp.Value.Repository));
plugin.Properties.Add(new PSNoteProperty("Origin", kvp.Value.Origin));
plugin.Properties.Add(new PSNoteProperty("License", kvp.Value.License));
plugin.Properties.Add(new PSNoteProperty("FlatSize", kvp.Value.FlatSize));
plugin.Properties.Add(new PSNoteProperty("Status", "Available"));
WriteObject(plugin);
}
}
}
}
@@ -19,7 +19,7 @@ namespace PSOPNSenseAPI.Cmdlets
/// </summary>
[Cmdlet(VerbsCommon.Get, "OPNSensePortForwardingRule")]
[OutputType(typeof(PortForwardingRule))]
public class GetOPNSensePortForwardingRuleCmdlet : OPNSenseCmdlet
public class GetOPNSensePortForwardingRuleCmdlet : OPNSenseBaseCmdlet
{
/// <summary>
/// <para type="description">The UUID of the port forwarding rule to get. If not specified, all rules are returned.</para>
@@ -30,14 +30,21 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
var portForwardingService = new PortForwardingService(SessionState.ApiClient);
var portForwardingService = new PortForwardingService(ApiClient);
if (!string.IsNullOrEmpty(Uuid))
{
// Get a specific rule
var rule = Task.Run(async () => await portForwardingService.GetPortForwardingRuleAsync(Uuid)).GetAwaiter().GetResult();
// Use our safe execution method
var rule = ExecuteAsyncTask(() => portForwardingService.GetPortForwardingRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
if (rule != null)
{
WriteObject(rule);
@@ -49,8 +56,15 @@ namespace PSOPNSenseAPI.Cmdlets
}
else
{
// Get all rules
var rules = Task.Run(async () => await portForwardingService.GetPortForwardingRulesAsync()).GetAwaiter().GetResult();
// Use our safe execution method
var rules = ExecuteAsyncTask(() => portForwardingService.GetPortForwardingRulesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || rules == null)
{
return;
}
WriteObject(rules, true);
}
}
@@ -21,21 +21,20 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var systemDNSService = new SystemDNSService(ApiClient, Logger);
var systemDNSService = new SystemDNSService(ApiClient, Logger);
var task = Task.Run(async () => await systemDNSService.GetSystemDNSAsync());
var result = task.GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => systemDNSService.GetSystemDNSAsync());
WriteObject(result.System);
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteObject(result.System);
}
}
}
@@ -33,28 +33,35 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var interfaceService = new InterfaceService(ApiClient, Logger);
var interfaceService = new InterfaceService(ApiClient, Logger);
if (ParameterSetName == "ByUuid")
{
var task = Task.Run(async () => await interfaceService.GetVLANAsync(Uuid));
var result = task.GetAwaiter().GetResult();
WriteObject(result.Vlan);
}
else
{
var task = Task.Run(async () => await interfaceService.GetVLANsAsync());
var result = task.GetAwaiter().GetResult();
WriteObject(result.Rows, true);
}
}
catch (Exception ex)
if (ParameterSetName == "ByUuid")
{
HandleException(ex);
// Use our safe execution method
var result = ExecuteAsyncTask(() => interfaceService.GetVLANAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Vlan);
}
else
{
// Use our safe execution method
var result = ExecuteAsyncTask(() => interfaceService.GetVLANsAsync());
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteObject(result.Rows, true);
}
}
}
@@ -35,42 +35,46 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
string fullPath = Path.FullName;
// Check if the file exists
if (!File.Exists(fullPath))
{
ProcessingException = new FileNotFoundException($"The file '{fullPath}' does not exist.");
WriteWarning($"The file '{fullPath}' does not exist.");
return;
}
if (!Force.IsPresent && !ShouldProcess(fullPath, "Import configuration"))
{
return;
}
var configService = new ConfigService(ApiClient, Logger);
try
{
string fullPath = Path.FullName;
// Check if the file exists
if (!File.Exists(fullPath))
{
WriteError(new ErrorRecord(
new FileNotFoundException($"The file '{fullPath}' does not exist."),
"FileNotFound",
ErrorCategory.ObjectNotFound,
fullPath));
return;
}
if (!Force.IsPresent && !ShouldProcess(fullPath, "Import configuration"))
{
return;
}
var configService = new ConfigService(ApiClient, Logger);
// Read the configuration file
var configContent = File.ReadAllBytes(fullPath);
// Execute the async method synchronously on the main thread
var result = configService.ImportConfigAsync(configContent).GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => configService.ImportConfigAsync(configContent));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteVerbose($"Imported configuration from {fullPath}: {result.Status}");
WriteWarning("The firewall is restarting. You may need to reconnect after it comes back online.");
}
catch (Exception ex)
{
HandleException(ex);
ProcessingException = ex;
WriteWarning($"Failed to read or process configuration file: {ex.Message}");
}
}
}
@@ -185,11 +185,7 @@ namespace PSOPNSenseAPI.Cmdlets
{
if (prefixLength <= network.Cidr)
{
WriteError(new ErrorRecord(
new ArgumentException($"Prefix length ({prefixLength}) must be greater than the network CIDR ({network.Cidr})."),
"InvalidPrefixLength",
ErrorCategory.InvalidArgument,
null));
ProcessingException = new ArgumentException($"Prefix length ({prefixLength}) must be greater than the network CIDR ({network.Cidr}).");
return;
}
@@ -206,11 +202,7 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (ArgumentException ex)
{
WriteError(new ErrorRecord(
ex,
"InvalidSubnetCount",
ErrorCategory.InvalidArgument,
null));
ProcessingException = ex;
}
}
@@ -236,11 +228,7 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"InvalidIPAddress",
ErrorCategory.InvalidArgument,
null));
ProcessingException = ex;
}
}
@@ -267,11 +255,7 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"InvalidAdditionalNetwork",
ErrorCategory.InvalidArgument,
null));
ProcessingException = ex;
}
}
@@ -292,11 +276,7 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"SupernetError",
ErrorCategory.InvalidOperation,
null));
ProcessingException = ex;
}
}
@@ -317,11 +297,7 @@ namespace PSOPNSenseAPI.Cmdlets
}
catch (Exception ex)
{
WriteError(new ErrorRecord(
ex,
"SupernetSummarizeError",
ErrorCategory.InvalidOperation,
null));
ProcessingException = ex;
}
}
}
@@ -83,35 +83,34 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var firewallService = new FirewallService(ApiClient, Logger);
var rule = new FirewallRuleCreate
{
var firewallService = new FirewallService(ApiClient, Logger);
Description = Description,
Protocol = Protocol,
SourceNet = SourceNet,
SourcePort = SourcePort,
DestinationNet = DestinationNet,
DestinationPort = DestinationPort,
Action = Action,
Sequence = Sequence,
Enabled = Enabled.IsPresent ? "1" : "0"
};
var rule = new FirewallRuleCreate
{
Description = Description,
Protocol = Protocol,
SourceNet = SourceNet,
SourcePort = SourcePort,
DestinationNet = DestinationNet,
DestinationPort = DestinationPort,
Action = Action,
Sequence = Sequence,
Enabled = Enabled.IsPresent ? "1" : "0"
};
// Use our safe execution method
var result = ExecuteAsyncTask(() => firewallService.CreateRuleAsync(rule));
var task = Task.Run(async () => await firewallService.CreateRuleAsync(rule));
var result = task.GetAwaiter().GetResult();
WriteVerbose($"Created firewall rule with UUID {result.Uuid}");
WriteObject(result.Uuid);
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteVerbose($"Created firewall rule with UUID {result.Uuid}");
WriteObject(result.Uuid);
}
}
}
@@ -15,7 +15,7 @@ namespace PSOPNSenseAPI.Cmdlets
/// </summary>
[Cmdlet(VerbsCommon.New, "OPNSensePortForwardingRule", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType(typeof(PortForwardingRule))]
public class NewOPNSensePortForwardingRuleCmdlet : OPNSenseCmdlet
public class NewOPNSensePortForwardingRuleCmdlet : OPNSenseBaseCmdlet
{
/// <summary>
/// <para type="description">Whether the rule is enabled.</para>
@@ -106,7 +106,7 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
var rule = new PortForwardingRule
{
@@ -127,8 +127,16 @@ namespace PSOPNSenseAPI.Cmdlets
if (Force || ShouldProcess($"OPNSense firewall", $"Create port forwarding rule from {Destination}:{DestinationPort} to {TargetIP}:{TargetPort}"))
{
var portForwardingService = new PortForwardingService(SessionState.ApiClient);
var uuid = Task.Run(async () => await portForwardingService.CreatePortForwardingRuleAsync(rule)).GetAwaiter().GetResult();
var portForwardingService = new PortForwardingService(ApiClient);
// Use our safe execution method
var uuid = ExecuteAsyncTask(() => portForwardingService.CreatePortForwardingRuleAsync(rule));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
if (!string.IsNullOrEmpty(uuid))
{
@@ -138,11 +146,8 @@ namespace PSOPNSenseAPI.Cmdlets
}
else
{
WriteError(new ErrorRecord(
new PSInvalidOperationException("Failed to create port forwarding rule."),
"PortForwardingRuleCreationFailed",
ErrorCategory.InvalidOperation,
null));
ProcessingException = new PSInvalidOperationException("Failed to create port forwarding rule.");
WriteWarning("Failed to create port forwarding rule.");
}
}
}
@@ -99,199 +99,219 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
// Parse the network CIDR
var ipNetwork = IPNetwork2.Parse(Network);
// Validate subnet mask bits
if (SubnetMaskBits <= ipNetwork.Cidr)
{
// Parse the network CIDR
var ipNetwork = IPNetwork2.Parse(Network);
ProcessingException = new ArgumentException($"Subnet mask bits ({SubnetMaskBits}) must be greater than the network CIDR ({ipNetwork.Cidr}).");
WriteWarning($"Subnet mask bits ({SubnetMaskBits}) must be greater than the network CIDR ({ipNetwork.Cidr}).");
return;
}
// Validate subnet mask bits
if (SubnetMaskBits <= ipNetwork.Cidr)
// Calculate the number of subnets
int numSubnets = (int)Math.Pow(2, SubnetMaskBits - ipNetwork.Cidr);
// Calculate the maximum VLAN ID
int maxVlanId = StartingVlanId + (numSubnets - 1) * VlanIdIncrement;
// Validate the maximum VLAN ID
if (maxVlanId > 4094)
{
ProcessingException = new ArgumentException($"The maximum VLAN ID ({maxVlanId}) exceeds the maximum allowed value (4094).");
WriteWarning($"The maximum VLAN ID ({maxVlanId}) exceeds the maximum allowed value (4094).");
return;
}
// Get confirmation
if (!Force.IsPresent && !ShouldProcess($"Create {numSubnets} VLANs for subnets of {Network} with VLAN IDs {StartingVlanId}-{maxVlanId}", "New-OPNSenseSubnetVLANs"))
{
return;
}
// Get the interface service
var interfaceService = new InterfaceService(ApiClient, Logger);
// Verify the parent interface exists
var interfaceDetail = ExecuteAsyncTask(() => interfaceService.GetInterfaceDetailAsync(ParentInterface));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
// Get existing VLANs
var vlansResult = ExecuteAsyncTask(() => interfaceService.GetVLANsAsync());
// Only continue if no exception occurred
if (ProcessingException != null || vlansResult == null)
{
return;
}
var existingVlans = vlansResult.Rows;
// Create a list to store the created VLANs
var createdVlans = new List<PSObject>();
// Get DHCP service if needed
DHCPService dhcpService = null;
if (EnableDHCP.IsPresent)
{
dhcpService = new DHCPService(ApiClient, Logger);
}
// Divide the network into subnets
var subnets = ipNetwork.Subnet((byte)SubnetMaskBits);
int vlanId = StartingVlanId;
int subnetIndex = 0;
foreach (var subnet in subnets)
{
// Calculate the gateway IP (first host address)
var gatewayIp = GetFirstHostAddress(subnet);
// Calculate the DHCP range (second host address to last host address)
var dhcpStart = GetSecondHostAddress(subnet);
var dhcpEnd = GetLastHostAddress(subnet);
// Create a description for the VLAN
string description = $"{DescriptionPrefix} {vlanId} - {subnet}";
// Check if the VLAN already exists
var existingVlan = existingVlans.FirstOrDefault(v =>
v.Interface == ParentInterface &&
int.Parse(v.Tag) == vlanId);
if (existingVlan != null)
{
WriteError(new ErrorRecord(
new ArgumentException($"Subnet mask bits ({SubnetMaskBits}) must be greater than the network CIDR ({ipNetwork.Cidr})."),
"InvalidSubnetMaskBits",
ErrorCategory.InvalidArgument,
SubnetMaskBits));
return;
WriteVerbose($"VLAN {vlanId} already exists on interface {ParentInterface}");
// Add the existing VLAN to the list
var vlanInfo = new PSObject();
vlanInfo.Properties.Add(new PSNoteProperty("VlanId", vlanId));
vlanInfo.Properties.Add(new PSNoteProperty("Subnet", subnet.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Gateway", gatewayIp.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Uuid", existingVlan.Uuid));
vlanInfo.Properties.Add(new PSNoteProperty("Status", "Existing"));
createdVlans.Add(vlanInfo);
}
// Calculate the number of subnets
int numSubnets = (int)Math.Pow(2, SubnetMaskBits - ipNetwork.Cidr);
// Calculate the maximum VLAN ID
int maxVlanId = StartingVlanId + (numSubnets - 1) * VlanIdIncrement;
// Validate the maximum VLAN ID
if (maxVlanId > 4094)
else
{
WriteError(new ErrorRecord(
new ArgumentException($"The maximum VLAN ID ({maxVlanId}) exceeds the maximum allowed value (4094)."),
"InvalidVlanIdRange",
ErrorCategory.InvalidArgument,
maxVlanId));
return;
}
// Get confirmation
if (!Force.IsPresent && !ShouldProcess($"Create {numSubnets} VLANs for subnets of {Network} with VLAN IDs {StartingVlanId}-{maxVlanId}", "New-OPNSenseSubnetVLANs"))
{
return;
}
// Get the interface service
var interfaceService = new InterfaceService(ApiClient, Logger);
// Verify the parent interface exists
var getInterfaceTask = Task.Run(async () => await interfaceService.GetInterfaceDetailAsync(ParentInterface));
getInterfaceTask.GetAwaiter().GetResult();
// Get existing VLANs
var getVlansTask = Task.Run(async () => await interfaceService.GetVLANsAsync());
var existingVlans = getVlansTask.GetAwaiter().GetResult().Rows;
// Create a list to store the created VLANs
var createdVlans = new List<PSObject>();
// Get DHCP service if needed
DHCPService dhcpService = null;
if (EnableDHCP.IsPresent)
{
dhcpService = new DHCPService(ApiClient, Logger);
}
// Divide the network into subnets
var subnets = ipNetwork.Subnet((byte)SubnetMaskBits);
int vlanId = StartingVlanId;
int subnetIndex = 0;
foreach (var subnet in subnets)
{
// Calculate the gateway IP (first host address)
var gatewayIp = GetFirstHostAddress(subnet);
// Calculate the DHCP range (second host address to last host address)
var dhcpStart = GetSecondHostAddress(subnet);
var dhcpEnd = GetLastHostAddress(subnet);
// Create a description for the VLAN
string description = $"{DescriptionPrefix} {vlanId} - {subnet}";
// Check if the VLAN already exists
var existingVlan = existingVlans.FirstOrDefault(v =>
v.Interface == ParentInterface &&
int.Parse(v.Tag) == vlanId);
if (existingVlan != null)
// Create the VLAN
var vlanConfig = new VLANConfig
{
WriteVerbose($"VLAN {vlanId} already exists on interface {ParentInterface}");
Interface = ParentInterface,
Tag = vlanId.ToString(),
Priority = "0",
Description = description
};
// Add the existing VLAN to the list
var vlanInfo = new PSObject();
vlanInfo.Properties.Add(new PSNoteProperty("VlanId", vlanId));
vlanInfo.Properties.Add(new PSNoteProperty("Subnet", subnet.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Gateway", gatewayIp.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Uuid", existingVlan.Uuid));
vlanInfo.Properties.Add(new PSNoteProperty("Status", "Existing"));
var createVlanResult = ExecuteAsyncTask(() => interfaceService.CreateVLANAsync(vlanConfig));
createdVlans.Add(vlanInfo);
}
else
// Only continue if no exception occurred
if (ProcessingException != null || createVlanResult == null)
{
// Create the VLAN
var vlanConfig = new VLANConfig
{
Interface = ParentInterface,
Tag = vlanId.ToString(),
Priority = "0",
Description = description
};
var createVlanTask = Task.Run(async () => await interfaceService.CreateVLANAsync(vlanConfig));
var createVlanResult = createVlanTask.GetAwaiter().GetResult();
WriteVerbose($"Created VLAN {vlanId} on interface {ParentInterface} with UUID {createVlanResult.Uuid}");
// Configure the VLAN interface
string vlanInterfaceName = $"{ParentInterface}.{vlanId}";
var interfaceConfig = new InterfaceConfig
{
Description = description,
IpAddress = gatewayIp.ToString(),
SubnetMask = SubnetMaskBits.ToString(),
Enabled = "1"
};
var updateInterfaceTask = Task.Run(async () => await interfaceService.UpdateInterfaceAsync(vlanInterfaceName, interfaceConfig));
updateInterfaceTask.GetAwaiter().GetResult();
WriteVerbose($"Configured interface {vlanInterfaceName} with IP {gatewayIp}/{SubnetMaskBits}");
// If EnableDHCP is specified, configure DHCP for the interface
if (EnableDHCP.IsPresent && dhcpService != null)
{
// Configure DHCP server for the interface
var dhcpConfig = new DHCPServerConfig
{
Enabled = "1",
RangeFrom = dhcpStart.ToString(),
RangeTo = dhcpEnd.ToString(),
DefaultLeaseTime = "7200",
MaxLeaseTime = "86400",
Domain = Domain,
Gateway = gatewayIp.ToString(),
DnsServers = DnsServers != null ? new List<string>(DnsServers) : new List<string> { gatewayIp.ToString() }
};
var updateDhcpTask = Task.Run(async () => await dhcpService.UpdateServerAsync(vlanInterfaceName, dhcpConfig));
updateDhcpTask.GetAwaiter().GetResult();
WriteVerbose($"Configured DHCP server for interface {vlanInterfaceName} with range {dhcpStart} - {dhcpEnd}");
}
// Add the created VLAN to the list
var vlanInfo = new PSObject();
vlanInfo.Properties.Add(new PSNoteProperty("VlanId", vlanId));
vlanInfo.Properties.Add(new PSNoteProperty("Subnet", subnet.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Gateway", gatewayIp.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Uuid", createVlanResult.Uuid));
vlanInfo.Properties.Add(new PSNoteProperty("Status", "Created"));
if (EnableDHCP.IsPresent)
{
vlanInfo.Properties.Add(new PSNoteProperty("DHCPRange", $"{dhcpStart} - {dhcpEnd}"));
}
createdVlans.Add(vlanInfo);
return;
}
// Increment the VLAN ID
vlanId += VlanIdIncrement;
subnetIndex++;
WriteVerbose($"Created VLAN {vlanId} on interface {ParentInterface} with UUID {createVlanResult.Uuid}");
// Configure the VLAN interface
string vlanInterfaceName = $"{ParentInterface}.{vlanId}";
var interfaceConfig = new InterfaceConfig
{
Description = description,
IpAddress = gatewayIp.ToString(),
SubnetMask = SubnetMaskBits.ToString(),
Enabled = "1"
};
var updateInterfaceResult = ExecuteAsyncTask(() => interfaceService.UpdateInterfaceAsync(vlanInterfaceName, interfaceConfig));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
WriteVerbose($"Configured interface {vlanInterfaceName} with IP {gatewayIp}/{SubnetMaskBits}");
// If EnableDHCP is specified, configure DHCP for the interface
if (EnableDHCP.IsPresent && dhcpService != null)
{
// Configure DHCP server for the interface
var dhcpConfig = new DHCPServerConfig
{
Enabled = "1",
RangeFrom = dhcpStart.ToString(),
RangeTo = dhcpEnd.ToString(),
DefaultLeaseTime = "7200",
MaxLeaseTime = "86400",
Domain = Domain,
Gateway = gatewayIp.ToString(),
DnsServers = DnsServers != null ? new List<string>(DnsServers) : new List<string> { gatewayIp.ToString() }
};
var updateDhcpResult = ExecuteAsyncTask(() => dhcpService.UpdateServerAsync(vlanInterfaceName, dhcpConfig));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
WriteVerbose($"Configured DHCP server for interface {vlanInterfaceName} with range {dhcpStart} - {dhcpEnd}");
}
// Add the created VLAN to the list
var vlanInfo = new PSObject();
vlanInfo.Properties.Add(new PSNoteProperty("VlanId", vlanId));
vlanInfo.Properties.Add(new PSNoteProperty("Subnet", subnet.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Gateway", gatewayIp.ToString()));
vlanInfo.Properties.Add(new PSNoteProperty("Uuid", createVlanResult.Uuid));
vlanInfo.Properties.Add(new PSNoteProperty("Status", "Created"));
if (EnableDHCP.IsPresent)
{
vlanInfo.Properties.Add(new PSNoteProperty("DHCPRange", $"{dhcpStart} - {dhcpEnd}"));
}
createdVlans.Add(vlanInfo);
}
// Apply DHCP changes if needed
if (EnableDHCP.IsPresent && dhcpService != null)
{
var applyDhcpTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyDhcpResult = applyDhcpTask.GetAwaiter().GetResult();
WriteVerbose($"Applied DHCP changes: {applyDhcpResult.Status}");
}
// Create a result object
var result = new PSObject();
result.Properties.Add(new PSNoteProperty("ParentInterface", ParentInterface));
result.Properties.Add(new PSNoteProperty("Network", Network));
result.Properties.Add(new PSNoteProperty("SubnetMaskBits", SubnetMaskBits));
result.Properties.Add(new PSNoteProperty("VLANs", createdVlans));
WriteObject(result);
// Increment the VLAN ID
vlanId += VlanIdIncrement;
subnetIndex++;
}
catch (Exception ex)
// Apply DHCP changes if needed
if (EnableDHCP.IsPresent && dhcpService != null)
{
HandleException(ex);
var applyDhcpResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyDhcpResult == null)
{
return;
}
WriteVerbose($"Applied DHCP changes: {applyDhcpResult.Status}");
}
// Create a result object
var result = new PSObject();
result.Properties.Add(new PSNoteProperty("ParentInterface", ParentInterface));
result.Properties.Add(new PSNoteProperty("Network", Network));
result.Properties.Add(new PSNoteProperty("SubnetMaskBits", SubnetMaskBits));
result.Properties.Add(new PSNoteProperty("VLANs", createdVlans));
WriteObject(result);
}
/// <summary>
@@ -48,30 +48,29 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var interfaceService = new InterfaceService(ApiClient, Logger);
var vlan = new VLANConfig
{
var interfaceService = new InterfaceService(ApiClient, Logger);
Interface = Interface,
Tag = Tag.ToString(),
Priority = Priority.ToString(),
Description = Description
};
var vlan = new VLANConfig
{
Interface = Interface,
Tag = Tag.ToString(),
Priority = Priority.ToString(),
Description = Description
};
// Use our safe execution method
var result = ExecuteAsyncTask(() => interfaceService.CreateVLANAsync(vlan));
var task = Task.Run(async () => await interfaceService.CreateVLANAsync(vlan));
var result = task.GetAwaiter().GetResult();
WriteVerbose($"Created VLAN with UUID {result.Uuid}");
WriteObject(result.Uuid);
}
catch (Exception ex)
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
HandleException(ex);
return;
}
WriteVerbose($"Created VLAN with UUID {result.Uuid}");
WriteObject(result.Uuid);
}
}
}
@@ -50,44 +50,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var aliasService = new AliasService(ApiClient, Logger);
// Get the alias details for the confirmation message
var getResult = ExecuteAsyncTask(() => aliasService.GetAliasAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var aliasService = new AliasService(ApiClient, Logger);
return;
}
// Get the alias details for the confirmation message
var getTask = Task.Run(async () => await aliasService.GetAliasAsync(Uuid));
var alias = getTask.GetAwaiter().GetResult().Alias;
var alias = getResult.Alias;
string confirmMessage = $"Alias: {alias.Name} ({alias.Type})";
if (!string.IsNullOrEmpty(alias.Description))
{
confirmMessage += $" - {alias.Description}";
}
string confirmMessage = $"Alias: {alias.Name} ({alias.Type})";
if (!string.IsNullOrEmpty(alias.Description))
{
confirmMessage += $" - {alias.Description}";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => aliasService.DeleteAliasAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"Alias {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => aliasService.ReconfigureAliasesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await aliasService.DeleteAliasAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"Alias {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await aliasService.ReconfigureAliasesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Alias changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"Alias changes applied: {applyResult.Status}");
}
}
}
@@ -45,44 +45,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
// Get the lease details for the confirmation message
var getResult = ExecuteAsyncTask(() => dhcpService.GetLeaseByMacAsync(MacAddress));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dhcpService = new DHCPService(ApiClient, Logger);
return;
}
// Get the lease details for the confirmation message
var getTask = Task.Run(async () => await dhcpService.GetLeaseByMacAsync(MacAddress));
var lease = getTask.GetAwaiter().GetResult().Lease;
var lease = getResult.Lease;
string confirmMessage = $"DHCP lease: {lease.MacAddress} -> {lease.IpAddress}";
if (!string.IsNullOrEmpty(lease.Hostname))
{
confirmMessage += $" ({lease.Hostname})";
}
string confirmMessage = $"DHCP lease: {lease.MacAddress} -> {lease.IpAddress}";
if (!string.IsNullOrEmpty(lease.Hostname))
{
confirmMessage += $" ({lease.Hostname})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => dhcpService.DeleteLeaseAsync(MacAddress));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"DHCP lease {MacAddress} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await dhcpService.DeleteLeaseAsync(MacAddress));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP lease {MacAddress} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
}
@@ -52,44 +52,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
// Get the option details for the confirmation message
var getResult = ExecuteAsyncTask(() => dhcpService.GetOptionAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dhcpService = new DHCPService(ApiClient, Logger);
return;
}
// Get the option details for the confirmation message
var getTask = Task.Run(async () => await dhcpService.GetOptionAsync(Interface, Uuid));
var option = getTask.GetAwaiter().GetResult().Option;
var option = getResult.Option;
string confirmMessage = $"DHCP option: {option.Number} = {option.Value}";
if (!string.IsNullOrEmpty(option.Description))
{
confirmMessage += $" ({option.Description})";
}
string confirmMessage = $"DHCP option: {option.Number} = {option.Value}";
if (!string.IsNullOrEmpty(option.Description))
{
confirmMessage += $" ({option.Description})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => dhcpService.DeleteOptionAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"DHCP option {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await dhcpService.DeleteOptionAsync(Interface, Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP option {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
}
@@ -52,44 +52,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
// Get the mapping details for the confirmation message
var getResult = ExecuteAsyncTask(() => dhcpService.GetStaticMappingAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dhcpService = new DHCPService(ApiClient, Logger);
return;
}
// Get the mapping details for the confirmation message
var getTask = Task.Run(async () => await dhcpService.GetStaticMappingAsync(Interface, Uuid));
var mapping = getTask.GetAwaiter().GetResult().Mapping;
var mapping = getResult.Mapping;
string confirmMessage = $"Static mapping: {mapping.MacAddress} -> {mapping.IpAddress}";
if (!string.IsNullOrEmpty(mapping.Hostname))
{
confirmMessage += $" ({mapping.Hostname})";
}
string confirmMessage = $"Static mapping: {mapping.MacAddress} -> {mapping.IpAddress}";
if (!string.IsNullOrEmpty(mapping.Hostname))
{
confirmMessage += $" ({mapping.Hostname})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => dhcpService.DeleteStaticMappingAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"Static mapping {Uuid} removed: {deleteResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await dhcpService.DeleteStaticMappingAsync(Interface, Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"Static mapping {Uuid} removed: {deleteResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
}
@@ -45,44 +45,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dnsService = new DNSService(ApiClient, Logger);
// Get the host details for the confirmation message
var getResult = ExecuteAsyncTask(() => dnsService.GetDNSForwardingHostAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dnsService = new DNSService(ApiClient, Logger);
return;
}
// Get the host details for the confirmation message
var getTask = Task.Run(async () => await dnsService.GetDNSForwardingHostAsync(Uuid));
var host = getTask.GetAwaiter().GetResult().Host;
var host = getResult.Host;
string confirmMessage = $"DNS forwarding host: {host.Domain} -> {host.Server}";
if (!string.IsNullOrEmpty(host.Description))
{
confirmMessage += $" ({host.Description})";
}
string confirmMessage = $"DNS forwarding host: {host.Domain} -> {host.Server}";
if (!string.IsNullOrEmpty(host.Description))
{
confirmMessage += $" ({host.Description})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => dnsService.DeleteDNSForwardingHostAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"DNS forwarding host {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dnsService.ApplyDNSChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await dnsService.DeleteDNSForwardingHostAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"DNS forwarding host {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dnsService.ApplyDNSChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
}
@@ -45,44 +45,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dnsService = new DNSService(ApiClient, Logger);
// Get the DNS override details for the confirmation message
var getResult = ExecuteAsyncTask(() => dnsService.GetDNSOverrideAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dnsService = new DNSService(ApiClient, Logger);
return;
}
// Get the DNS override details for the confirmation message
var getTask = Task.Run(async () => await dnsService.GetDNSOverrideAsync(Uuid));
var dnsOverride = getTask.GetAwaiter().GetResult().Host;
var dnsOverride = getResult.Host;
string confirmMessage = $"DNS override {dnsOverride.Hostname}.{dnsOverride.Domain} -> {dnsOverride.IpAddress}";
if (!string.IsNullOrEmpty(dnsOverride.Description))
{
confirmMessage += $" ({dnsOverride.Description})";
}
string confirmMessage = $"DNS override {dnsOverride.Hostname}.{dnsOverride.Domain} -> {dnsOverride.IpAddress}";
if (!string.IsNullOrEmpty(dnsOverride.Description))
{
confirmMessage += $" ({dnsOverride.Description})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => dnsService.DeleteDNSOverrideAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"DNS override {Uuid} removed: {deleteResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dnsService.ApplyDNSChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await dnsService.DeleteDNSOverrideAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"DNS override {Uuid} removed: {deleteResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dnsService.ApplyDNSChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
}
@@ -39,36 +39,41 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var firewallService = new FirewallService(ApiClient, Logger);
// Get the rule details for the confirmation message
var getResult = ExecuteAsyncTask(() => firewallService.GetRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var firewallService = new FirewallService(ApiClient, Logger);
// Get the rule details for the confirmation message
var getTask = Task.Run(async () => await firewallService.GetRuleAsync(Uuid));
var rule = getTask.GetAwaiter().GetResult().Rule;
string confirmMessage = $"Firewall rule: {rule.Description}";
if (!string.IsNullOrEmpty(rule.Protocol) && rule.Protocol != "any")
{
confirmMessage += $" ({rule.Protocol})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteTask = Task.Run(async () => await firewallService.DeleteRuleAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"Firewall rule {Uuid} removed: {deleteResult.Result}");
return;
}
catch (Exception ex)
var rule = getResult.Rule;
string confirmMessage = $"Firewall rule: {rule.Description}";
if (!string.IsNullOrEmpty(rule.Protocol) && rule.Protocol != "any")
{
HandleException(ex);
confirmMessage += $" ({rule.Protocol})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => firewallService.DeleteRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"Firewall rule {Uuid} removed: {deleteResult.Result}");
}
}
}
@@ -45,44 +45,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var gatewayService = new GatewayService(ApiClient, Logger);
// Get the gateway details for the confirmation message
var getResult = ExecuteAsyncTask(() => gatewayService.GetGatewayAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var gatewayService = new GatewayService(ApiClient, Logger);
return;
}
// Get the gateway details for the confirmation message
var getTask = Task.Run(async () => await gatewayService.GetGatewayAsync(Uuid));
var gateway = getTask.GetAwaiter().GetResult().Gateway;
var gateway = getResult.Gateway;
string confirmMessage = $"Gateway: {gateway.Name} ({gateway.IpAddress})";
if (!string.IsNullOrEmpty(gateway.Description))
{
confirmMessage += $" - {gateway.Description}";
}
string confirmMessage = $"Gateway: {gateway.Name} ({gateway.IpAddress})";
if (!string.IsNullOrEmpty(gateway.Description))
{
confirmMessage += $" - {gateway.Description}";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => gatewayService.DeleteGatewayAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"Gateway {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => gatewayService.ApplyGatewayChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await gatewayService.DeleteGatewayAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"Gateway {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await gatewayService.ApplyGatewayChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Gateway changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"Gateway changes applied: {applyResult.Status}");
}
}
}
@@ -13,7 +13,7 @@ namespace PSOPNSenseAPI.Cmdlets
/// </example>
/// </summary>
[Cmdlet(VerbsCommon.Remove, "OPNSensePortForwardingRule", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)]
public class RemoveOPNSensePortForwardingRuleCmdlet : OPNSenseCmdlet
public class RemoveOPNSensePortForwardingRuleCmdlet : OPNSenseBaseCmdlet
{
/// <summary>
/// <para type="description">The UUID of the port forwarding rule to remove.</para>
@@ -30,12 +30,18 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
var portForwardingService = new PortForwardingService(SessionState.ApiClient);
var portForwardingService = new PortForwardingService(ApiClient);
// Get the rule to display information in the confirmation message
var rule = Task.Run(async () => await portForwardingService.GetPortForwardingRuleAsync(Uuid)).GetAwaiter().GetResult();
var rule = ExecuteAsyncTask(() => portForwardingService.GetPortForwardingRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
if (rule == null)
{
@@ -52,7 +58,13 @@ namespace PSOPNSenseAPI.Cmdlets
if (Force || ShouldProcess($"OPNSense firewall", confirmationMessage))
{
var success = Task.Run(async () => await portForwardingService.DeletePortForwardingRuleAsync(Uuid)).GetAwaiter().GetResult();
var success = ExecuteAsyncTask(() => portForwardingService.DeletePortForwardingRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
if (success)
{
@@ -60,11 +72,8 @@ namespace PSOPNSenseAPI.Cmdlets
}
else
{
WriteError(new ErrorRecord(
new PSInvalidOperationException($"Failed to remove port forwarding rule with UUID '{Uuid}'."),
"PortForwardingRuleRemovalFailed",
ErrorCategory.InvalidOperation,
Uuid));
ProcessingException = new PSInvalidOperationException($"Failed to remove port forwarding rule with UUID '{Uuid}'.");
WriteWarning($"Failed to remove port forwarding rule with UUID '{Uuid}'.");
}
}
}
@@ -45,44 +45,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var routeService = new RouteService(ApiClient, Logger);
// Get the route details for the confirmation message
var getResult = ExecuteAsyncTask(() => routeService.GetRouteAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var routeService = new RouteService(ApiClient, Logger);
return;
}
// Get the route details for the confirmation message
var getTask = Task.Run(async () => await routeService.GetRouteAsync(Uuid));
var route = getTask.GetAwaiter().GetResult().Route;
var route = getResult.Route;
string confirmMessage = $"Route: {route.Network} via {route.Gateway}";
if (!string.IsNullOrEmpty(route.Description))
{
confirmMessage += $" ({route.Description})";
}
string confirmMessage = $"Route: {route.Network} via {route.Gateway}";
if (!string.IsNullOrEmpty(route.Description))
{
confirmMessage += $" ({route.Description})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => routeService.DeleteRouteAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"Route {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => routeService.ApplyRouteChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
var deleteTask = Task.Run(async () => await routeService.DeleteRouteAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"Route {Uuid} removed: {deleteResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await routeService.ApplyRouteChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Route changes applied: {applyResult.Status}");
}
}
catch (Exception ex)
{
HandleException(ex);
WriteVerbose($"Route changes applied: {applyResult.Status}");
}
}
}
@@ -39,36 +39,41 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var userService = new UserService(ApiClient, Logger);
// Get the user details for the confirmation message
var getResult = ExecuteAsyncTask(() => userService.GetUserAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var userService = new UserService(ApiClient, Logger);
// Get the user details for the confirmation message
var getTask = Task.Run(async () => await userService.GetUserAsync(Uuid));
var user = getTask.GetAwaiter().GetResult().User;
string confirmMessage = $"User: {user.Username}";
if (!string.IsNullOrEmpty(user.FullName))
{
confirmMessage += $" ({user.FullName})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteTask = Task.Run(async () => await userService.DeleteUserAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"User {Uuid} removed: {deleteResult.Result}");
return;
}
catch (Exception ex)
var user = getResult.User;
string confirmMessage = $"User: {user.Username}";
if (!string.IsNullOrEmpty(user.FullName))
{
HandleException(ex);
confirmMessage += $" ({user.FullName})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => userService.DeleteUserAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"User {Uuid} removed: {deleteResult.Result}");
}
}
}
@@ -39,36 +39,41 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var interfaceService = new InterfaceService(ApiClient, Logger);
// Get the VLAN details for the confirmation message
var getResult = ExecuteAsyncTask(() => interfaceService.GetVLANAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var interfaceService = new InterfaceService(ApiClient, Logger);
// Get the VLAN details for the confirmation message
var getTask = Task.Run(async () => await interfaceService.GetVLANAsync(Uuid));
var vlan = getTask.GetAwaiter().GetResult().Vlan;
string confirmMessage = $"VLAN {vlan.Tag} on interface {vlan.Interface}";
if (!string.IsNullOrEmpty(vlan.Description))
{
confirmMessage += $" ({vlan.Description})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteTask = Task.Run(async () => await interfaceService.DeleteVLANAsync(Uuid));
var deleteResult = deleteTask.GetAwaiter().GetResult();
WriteVerbose($"VLAN {Uuid} removed: {deleteResult.Result}");
return;
}
catch (Exception ex)
var vlan = getResult.Vlan;
string confirmMessage = $"VLAN {vlan.Tag} on interface {vlan.Interface}";
if (!string.IsNullOrEmpty(vlan.Description))
{
HandleException(ex);
confirmMessage += $" ({vlan.Description})";
}
if (!Force.IsPresent && !ShouldProcess(confirmMessage, "Remove"))
{
return;
}
var deleteResult = ExecuteAsyncTask(() => interfaceService.DeleteVLANAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || deleteResult == null)
{
return;
}
WriteVerbose($"VLAN {Uuid} removed: {deleteResult.Result}");
}
}
}
@@ -130,14 +130,23 @@ namespace PSOPNSenseAPI.Cmdlets
// Try to get the system status
var statusService = new SystemService(newClient, logger);
// We need to use Task.Run here because we're creating a new client
// We need to handle this specially because we're using a new client
// and can't use ExecuteAsyncTask which uses the existing client
var statusTask = Task.Run(async () => await statusService.GetStatusAsync());
var statusResult = statusTask.GetAwaiter().GetResult();
try
{
// Use ConfigureAwait(false) to avoid deadlocks
var statusResult = statusService.GetStatusAsync().ConfigureAwait(false).GetAwaiter().GetResult();
// If we get here, the firewall is back online
WriteVerbose("Successfully reconnected to the firewall");
WriteObject($"Firewall is back online. Uptime: {statusResult.Uptime}");
// If we get here, the firewall is back online
WriteVerbose("Successfully reconnected to the firewall");
WriteObject($"Firewall is back online. Uptime: {statusResult.Uptime}");
}
catch (Exception innerEx)
{
// Just log and continue the retry loop
WriteVerbose($"Status check failed: {innerEx.Message}");
throw; // Re-throw to be caught by the outer catch
}
// Set the new session
OPNSenseSession.Current = newClient;
@@ -53,26 +53,33 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
{
var configService = new ConfigService(ApiClient, Logger);
string actionDescription = "Restore configuration";
string targetName = ParameterSetName == "Filename" ? Filename : "from XML document";
var configService = new ConfigService(ApiClient, Logger);
string actionDescription = "Restore configuration";
string targetName = ParameterSetName == "Filename" ? Filename : "from XML document";
if (!Force.IsPresent && !ShouldProcess(targetName, actionDescription))
if (!Force.IsPresent && !ShouldProcess(targetName, actionDescription))
{
return;
}
if (ParameterSetName == "Filename")
{
// Use our safe execution method
var result = ExecuteAsyncTask(() => configService.RestoreConfigBackupAsync(Filename));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
if (ParameterSetName == "Filename")
{
// Restore from backup file - execute synchronously on the main thread
var result = configService.RestoreConfigBackupAsync(Filename).GetAwaiter().GetResult();
WriteVerbose($"Restored configuration from backup: {result.Status}");
}
else
WriteVerbose($"Restored configuration from backup: {result.Status}");
}
else
{
try
{
// Restore from XML document
byte[] configContent;
@@ -82,17 +89,26 @@ namespace PSOPNSenseAPI.Cmdlets
configContent = memoryStream.ToArray();
}
// Execute synchronously on the main thread
var result = configService.ImportConfigAsync(configContent).GetAwaiter().GetResult();
// Use our safe execution method
var result = ExecuteAsyncTask(() => configService.ImportConfigAsync(configContent));
// Only continue if no exception occurred
if (ProcessingException != null || result == null)
{
return;
}
WriteVerbose($"Restored configuration from XML document: {result.Status}");
}
catch (Exception ex)
{
ProcessingException = ex;
WriteWarning($"Failed to process XML document: {ex.Message}");
return;
}
}
WriteWarning("The firewall is restarting. You may need to reconnect after it comes back online.");
}
catch (Exception ex)
{
HandleException(ex);
}
WriteWarning("The firewall is restarting. You may need to reconnect after it comes back online.");
}
}
}
@@ -94,83 +94,93 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var aliasService = new AliasService(ApiClient, Logger);
// Get current alias
var getResult = ExecuteAsyncTask(() => aliasService.GetAliasAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var aliasService = new AliasService(ApiClient, Logger);
// Get current alias
var getTask = Task.Run(async () => await aliasService.GetAliasAsync(Uuid));
var currentAlias = getTask.GetAwaiter().GetResult().Alias;
// Create updated alias
var alias = new AliasConfig
{
Name = currentAlias.Name,
Type = currentAlias.Type,
Content = Content ?? currentAlias.Content,
Description = Description ?? currentAlias.Description,
Protocol = Protocol?.ToUpper() ?? currentAlias.Protocol,
UpdateFrequency = UpdateFrequency?.ToString() ?? currentAlias.UpdateFrequency,
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
alias.Enabled = "1";
}
else if (Enabled.IsPresent)
{
alias.Enabled = "1";
}
else if (Disabled.IsPresent)
{
alias.Enabled = "0";
}
else
{
alias.Enabled = currentAlias.Enabled;
}
// Handle counters
if (EnableCounters.IsPresent && DisableCounters.IsPresent)
{
WriteWarning("Both -EnableCounters and -DisableCounters parameters were specified. Using -EnableCounters.");
alias.Counters = "1";
}
else if (EnableCounters.IsPresent)
{
alias.Counters = "1";
}
else if (DisableCounters.IsPresent)
{
alias.Counters = "0";
}
else
{
alias.Counters = currentAlias.Counters;
}
// Update alias
var updateTask = Task.Run(async () => await aliasService.UpdateAliasAsync(Uuid, alias));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Alias {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await aliasService.ReconfigureAliasesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Alias changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentAlias = getResult.Alias;
// Create updated alias
var alias = new AliasConfig
{
HandleException(ex);
Name = currentAlias.Name,
Type = currentAlias.Type,
Content = Content ?? currentAlias.Content,
Description = Description ?? currentAlias.Description,
Protocol = Protocol?.ToUpper() ?? currentAlias.Protocol,
UpdateFrequency = UpdateFrequency?.ToString() ?? currentAlias.UpdateFrequency,
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
alias.Enabled = "1";
}
else if (Enabled.IsPresent)
{
alias.Enabled = "1";
}
else if (Disabled.IsPresent)
{
alias.Enabled = "0";
}
else
{
alias.Enabled = currentAlias.Enabled;
}
// Handle counters
if (EnableCounters.IsPresent && DisableCounters.IsPresent)
{
WriteWarning("Both -EnableCounters and -DisableCounters parameters were specified. Using -EnableCounters.");
alias.Counters = "1";
}
else if (EnableCounters.IsPresent)
{
alias.Counters = "1";
}
else if (DisableCounters.IsPresent)
{
alias.Counters = "0";
}
else
{
alias.Counters = currentAlias.Counters;
}
// Update alias
var updateResult = ExecuteAsyncTask(() => aliasService.UpdateAliasAsync(Uuid, alias));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Alias {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => aliasService.ReconfigureAliasesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"Alias changes applied: {applyResult.Status}");
}
}
}
@@ -66,43 +66,53 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
// Get current option
var getResult = ExecuteAsyncTask(() => dhcpService.GetOptionAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dhcpService = new DHCPService(ApiClient, Logger);
// Get current option
var getTask = Task.Run(async () => await dhcpService.GetOptionAsync(Interface, Uuid));
var currentOption = getTask.GetAwaiter().GetResult().Option;
// Create updated option
var option = new DHCPOptionConfig
{
Number = Number ?? currentOption.Number,
Value = Value ?? currentOption.Value,
Type = Type ?? currentOption.Type,
Description = Description ?? currentOption.Description
};
// Update option
var updateTask = Task.Run(async () => await dhcpService.UpdateOptionAsync(Interface, Uuid, option));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP option {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentOption = getResult.Option;
// Create updated option
var option = new DHCPOptionConfig
{
HandleException(ex);
Number = Number ?? currentOption.Number,
Value = Value ?? currentOption.Value,
Type = Type ?? currentOption.Type,
Description = Description ?? currentOption.Description
};
// Update option
var updateResult = ExecuteAsyncTask(() => dhcpService.UpdateOptionAsync(Interface, Uuid, option));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"DHCP option {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
}
@@ -94,65 +94,75 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
// First, get the current server configuration
var getResult = ExecuteAsyncTask(() => dhcpService.GetServerAsync(Interface));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dhcpService = new DHCPService(ApiClient, Logger);
// First, get the current server configuration
var getTask = Task.Run(async () => await dhcpService.GetServerAsync(Interface));
var currentServer = getTask.GetAwaiter().GetResult().Server;
// Create the updated configuration
var server = new DHCPServerConfig
{
RangeFrom = RangeFrom ?? currentServer.RangeFrom,
RangeTo = RangeTo ?? currentServer.RangeTo,
DefaultLeaseTime = DefaultLeaseTime?.ToString() ?? currentServer.DefaultLeaseTime,
MaxLeaseTime = MaxLeaseTime?.ToString() ?? currentServer.MaxLeaseTime,
Domain = Domain ?? currentServer.Domain,
DnsServers = DnsServers != null ? new List<string>(DnsServers) : currentServer.DnsServers,
Gateway = Gateway ?? currentServer.Gateway
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
server.Enabled = "1";
}
else if (Enabled.IsPresent)
{
server.Enabled = "1";
}
else if (Disabled.IsPresent)
{
server.Enabled = "0";
}
else
{
server.Enabled = currentServer.Enabled;
}
// Update the server
var updateTask = Task.Run(async () => await dhcpService.UpdateServerAsync(Interface, server));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP server for interface {Interface} updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentServer = getResult.Server;
// Create the updated configuration
var server = new DHCPServerConfig
{
HandleException(ex);
RangeFrom = RangeFrom ?? currentServer.RangeFrom,
RangeTo = RangeTo ?? currentServer.RangeTo,
DefaultLeaseTime = DefaultLeaseTime?.ToString() ?? currentServer.DefaultLeaseTime,
MaxLeaseTime = MaxLeaseTime?.ToString() ?? currentServer.MaxLeaseTime,
Domain = Domain ?? currentServer.Domain,
DnsServers = DnsServers != null ? new List<string>(DnsServers) : currentServer.DnsServers,
Gateway = Gateway ?? currentServer.Gateway
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
server.Enabled = "1";
}
else if (Enabled.IsPresent)
{
server.Enabled = "1";
}
else if (Disabled.IsPresent)
{
server.Enabled = "0";
}
else
{
server.Enabled = currentServer.Enabled;
}
// Update the server
var updateResult = ExecuteAsyncTask(() => dhcpService.UpdateServerAsync(Interface, server));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"DHCP server for interface {Interface} updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
}
@@ -82,62 +82,72 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dhcpService = new DHCPService(ApiClient, Logger);
// First, get the current mapping
var getResult = ExecuteAsyncTask(() => dhcpService.GetStaticMappingAsync(Interface, Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dhcpService = new DHCPService(ApiClient, Logger);
// First, get the current mapping
var getTask = Task.Run(async () => await dhcpService.GetStaticMappingAsync(Interface, Uuid));
var currentMapping = getTask.GetAwaiter().GetResult().Mapping;
// Create the updated mapping
var mapping = new DHCPStaticMappingConfig
{
MacAddress = MacAddress ?? currentMapping.MacAddress,
IpAddress = IpAddress ?? currentMapping.IpAddress,
Hostname = Hostname ?? currentMapping.Hostname,
Description = Description ?? currentMapping.Description
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
mapping.Enabled = "1";
}
else if (Enabled.IsPresent)
{
mapping.Enabled = "1";
}
else if (Disabled.IsPresent)
{
mapping.Enabled = "0";
}
else
{
mapping.Enabled = currentMapping.Enabled;
}
// Update the mapping
var updateTask = Task.Run(async () => await dhcpService.UpdateStaticMappingAsync(Interface, Uuid, mapping));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Static mapping {Uuid} updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dhcpService.ApplyChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentMapping = getResult.Mapping;
// Create the updated mapping
var mapping = new DHCPStaticMappingConfig
{
HandleException(ex);
MacAddress = MacAddress ?? currentMapping.MacAddress,
IpAddress = IpAddress ?? currentMapping.IpAddress,
Hostname = Hostname ?? currentMapping.Hostname,
Description = Description ?? currentMapping.Description
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
mapping.Enabled = "1";
}
else if (Enabled.IsPresent)
{
mapping.Enabled = "1";
}
else if (Disabled.IsPresent)
{
mapping.Enabled = "0";
}
else
{
mapping.Enabled = currentMapping.Enabled;
}
// Update the mapping
var updateResult = ExecuteAsyncTask(() => dhcpService.UpdateStaticMappingAsync(Interface, Uuid, mapping));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Static mapping {Uuid} updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dhcpService.ApplyChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"DHCP changes applied: {applyResult.Status}");
}
}
}
@@ -58,69 +58,79 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dnsService = new DNSService(ApiClient, Logger);
// Get current configuration
var getResult = ExecuteAsyncTask(() => dnsService.GetDNSForwardingAsync());
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dnsService = new DNSService(ApiClient, Logger);
// Get current configuration
var getTask = Task.Run(async () => await dnsService.GetDNSForwardingAsync());
var currentConfig = getTask.GetAwaiter().GetResult().Forward;
// Create updated configuration
var config = new DNSForwardingConfig
{
Type = Type ?? currentConfig.Type
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
config.Enabled = "1";
}
else if (Enabled.IsPresent)
{
config.Enabled = "1";
}
else if (Disabled.IsPresent)
{
config.Enabled = "0";
}
else
{
config.Enabled = currentConfig.Enabled;
}
// Handle DNS servers
if (DnsServers != null && DnsServers.Length > 0)
{
config.DnsServers = new List<string>(DnsServers);
}
else
{
config.DnsServers = currentConfig.DnsServers;
}
// Update configuration
var updateTask = Task.Run(async () => await dnsService.UpdateDNSForwardingAsync(config));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"DNS forwarding configuration updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dnsService.ApplyDNSChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentConfig = getResult.Forward;
// Create updated configuration
var config = new DNSForwardingConfig
{
HandleException(ex);
Type = Type ?? currentConfig.Type
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
config.Enabled = "1";
}
else if (Enabled.IsPresent)
{
config.Enabled = "1";
}
else if (Disabled.IsPresent)
{
config.Enabled = "0";
}
else
{
config.Enabled = currentConfig.Enabled;
}
// Handle DNS servers
if (DnsServers != null && DnsServers.Length > 0)
{
config.DnsServers = new List<string>(DnsServers);
}
else
{
config.DnsServers = currentConfig.DnsServers;
}
// Update configuration
var updateResult = ExecuteAsyncTask(() => dnsService.UpdateDNSForwardingAsync(config));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"DNS forwarding configuration updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dnsService.ApplyDNSChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
}
@@ -69,61 +69,71 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dnsService = new DNSService(ApiClient, Logger);
// Get current host
var getResult = ExecuteAsyncTask(() => dnsService.GetDNSForwardingHostAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dnsService = new DNSService(ApiClient, Logger);
// Get current host
var getTask = Task.Run(async () => await dnsService.GetDNSForwardingHostAsync(Uuid));
var currentHost = getTask.GetAwaiter().GetResult().Host;
// Create updated host
var host = new DNSForwardingHostConfig
{
Domain = Domain ?? currentHost.Domain,
Server = Server ?? currentHost.Server,
Description = Description ?? currentHost.Description
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
host.Enabled = "1";
}
else if (Enabled.IsPresent)
{
host.Enabled = "1";
}
else if (Disabled.IsPresent)
{
host.Enabled = "0";
}
else
{
host.Enabled = currentHost.Enabled;
}
// Update host
var updateTask = Task.Run(async () => await dnsService.UpdateDNSForwardingHostAsync(Uuid, host));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"DNS forwarding host {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dnsService.ApplyDNSChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentHost = getResult.Host;
// Create updated host
var host = new DNSForwardingHostConfig
{
HandleException(ex);
Domain = Domain ?? currentHost.Domain,
Server = Server ?? currentHost.Server,
Description = Description ?? currentHost.Description
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
host.Enabled = "1";
}
else if (Enabled.IsPresent)
{
host.Enabled = "1";
}
else if (Disabled.IsPresent)
{
host.Enabled = "0";
}
else
{
host.Enabled = currentHost.Enabled;
}
// Update host
var updateResult = ExecuteAsyncTask(() => dnsService.UpdateDNSForwardingHostAsync(Uuid, host));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"DNS forwarding host {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dnsService.ApplyDNSChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
}
@@ -82,48 +82,58 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var dnsService = new DNSService(ApiClient, Logger);
// First, get the current DNS configuration
var getResult = ExecuteAsyncTask(() => dnsService.GetDNSConfigAsync());
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var dnsService = new DNSService(ApiClient, Logger);
// First, get the current DNS configuration
var getTask = Task.Run(async () => await dnsService.GetDNSConfigAsync());
var currentConfig = getTask.GetAwaiter().GetResult().Unbound;
// Create the updated configuration
var dnsConfig = new DNSConfig
{
Enabled = MyInvocation.BoundParameters.ContainsKey(nameof(Enabled)) ? (Enabled.IsPresent ? "1" : "0") : currentConfig.Enabled,
Port = Port?.ToString() ?? currentConfig.Port,
Interfaces = Interfaces != null ? new List<string>(Interfaces) : currentConfig.Interfaces,
Forwarding = MyInvocation.BoundParameters.ContainsKey(nameof(Forwarding)) ? (Forwarding.IsPresent ? "1" : "0") : currentConfig.Forwarding,
Forwarders = Forwarders != null ? new List<string>(Forwarders) : currentConfig.Forwarders,
RegisterDhcp = MyInvocation.BoundParameters.ContainsKey(nameof(RegisterDhcp)) ? (RegisterDhcp.IsPresent ? "1" : "0") : currentConfig.RegisterDhcp,
RegisterDhcpDomain = RegisterDhcpDomain ?? currentConfig.RegisterDhcpDomain,
RegisterDhcpStatic = MyInvocation.BoundParameters.ContainsKey(nameof(RegisterDhcpStatic)) ? (RegisterDhcpStatic.IsPresent ? "1" : "0") : currentConfig.RegisterDhcpStatic,
ActiveInterfaces = currentConfig.ActiveInterfaces
};
// Update the DNS configuration
var updateTask = Task.Run(async () => await dnsService.UpdateDNSConfigAsync(dnsConfig));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"DNS server configuration updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await dnsService.ApplyDNSChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentConfig = getResult.Unbound;
// Create the updated configuration
var dnsConfig = new DNSConfig
{
HandleException(ex);
Enabled = MyInvocation.BoundParameters.ContainsKey(nameof(Enabled)) ? (Enabled.IsPresent ? "1" : "0") : currentConfig.Enabled,
Port = Port?.ToString() ?? currentConfig.Port,
Interfaces = Interfaces != null ? new List<string>(Interfaces) : currentConfig.Interfaces,
Forwarding = MyInvocation.BoundParameters.ContainsKey(nameof(Forwarding)) ? (Forwarding.IsPresent ? "1" : "0") : currentConfig.Forwarding,
Forwarders = Forwarders != null ? new List<string>(Forwarders) : currentConfig.Forwarders,
RegisterDhcp = MyInvocation.BoundParameters.ContainsKey(nameof(RegisterDhcp)) ? (RegisterDhcp.IsPresent ? "1" : "0") : currentConfig.RegisterDhcp,
RegisterDhcpDomain = RegisterDhcpDomain ?? currentConfig.RegisterDhcpDomain,
RegisterDhcpStatic = MyInvocation.BoundParameters.ContainsKey(nameof(RegisterDhcpStatic)) ? (RegisterDhcpStatic.IsPresent ? "1" : "0") : currentConfig.RegisterDhcpStatic,
ActiveInterfaces = currentConfig.ActiveInterfaces
};
// Update the DNS configuration
var updateResult = ExecuteAsyncTask(() => dnsService.UpdateDNSConfigAsync(dnsConfig));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"DNS server configuration updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => dnsService.ApplyDNSChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"DNS changes applied: {applyResult.Status}");
}
}
}
@@ -95,58 +95,63 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var firewallService = new FirewallService(ApiClient, Logger);
// First, get the current rule
var getResult = ExecuteAsyncTask(() => firewallService.GetRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var firewallService = new FirewallService(ApiClient, Logger);
// First, get the current rule
var getTask = Task.Run(async () => await firewallService.GetRuleAsync(Uuid));
var currentRule = getTask.GetAwaiter().GetResult().Rule;
// Create the updated rule
var rule = new FirewallRuleCreate
{
Description = Description ?? currentRule.Description,
Protocol = Protocol ?? currentRule.Protocol,
SourceNet = SourceNet ?? currentRule.SourceNet,
SourcePort = SourcePort ?? currentRule.SourcePort,
DestinationNet = DestinationNet ?? currentRule.DestinationNet,
DestinationPort = DestinationPort ?? currentRule.DestinationPort,
Action = Action ?? currentRule.Action,
Sequence = Sequence ?? currentRule.Sequence
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
rule.Enabled = "1";
}
else if (Enabled.IsPresent)
{
rule.Enabled = "1";
}
else if (Disabled.IsPresent)
{
rule.Enabled = "0";
}
else
{
rule.Enabled = currentRule.Enabled;
}
// Update the rule
var updateTask = Task.Run(async () => await firewallService.UpdateRuleAsync(Uuid, rule));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Firewall rule {Uuid} updated: {updateResult.Result}");
return;
}
catch (Exception ex)
var currentRule = getResult.Rule;
// Create the updated rule
var rule = new FirewallRuleCreate
{
HandleException(ex);
Description = Description ?? currentRule.Description,
Protocol = Protocol ?? currentRule.Protocol,
SourceNet = SourceNet ?? currentRule.SourceNet,
SourcePort = SourcePort ?? currentRule.SourcePort,
DestinationNet = DestinationNet ?? currentRule.DestinationNet,
DestinationPort = DestinationPort ?? currentRule.DestinationPort,
Action = Action ?? currentRule.Action,
Sequence = Sequence ?? currentRule.Sequence
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
rule.Enabled = "1";
}
else if (Enabled.IsPresent)
{
rule.Enabled = "1";
}
else if (Disabled.IsPresent)
{
rule.Enabled = "0";
}
else
{
rule.Enabled = currentRule.Enabled;
}
// Update the rule
var updateResult = ExecuteAsyncTask(() => firewallService.UpdateRuleAsync(Uuid, rule));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Firewall rule {Uuid} updated: {updateResult.Result}");
}
}
}
@@ -131,122 +131,132 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var gatewayService = new GatewayService(ApiClient, Logger);
// Get current gateway
var getResult = ExecuteAsyncTask(() => gatewayService.GetGatewayAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var gatewayService = new GatewayService(ApiClient, Logger);
// Get current gateway
var getTask = Task.Run(async () => await gatewayService.GetGatewayAsync(Uuid));
var currentGateway = getTask.GetAwaiter().GetResult().Gateway;
// Create updated gateway
var gateway = new GatewayConfig
{
Name = Name ?? currentGateway.Name,
Interface = Interface ?? currentGateway.Interface,
IpAddress = IpAddress ?? currentGateway.IpAddress,
MonitorIp = MonitorIp ?? currentGateway.MonitorIp,
Description = Description ?? currentGateway.Description,
Weight = Weight?.ToString() ?? currentGateway.Weight,
IpProtocol = IpProtocol ?? currentGateway.IpProtocol
};
// Handle default/not default
if (Default.IsPresent && NotDefault.IsPresent)
{
WriteWarning("Both -Default and -NotDefault parameters were specified. Using -Default.");
gateway.IsDefault = "1";
}
else if (Default.IsPresent)
{
gateway.IsDefault = "1";
}
else if (NotDefault.IsPresent)
{
gateway.IsDefault = "0";
}
else
{
gateway.IsDefault = currentGateway.IsDefault;
}
// Handle enabled/disabled
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
gateway.Disabled = "0";
}
else if (Enabled.IsPresent)
{
gateway.Disabled = "0";
}
else if (Disabled.IsPresent)
{
gateway.Disabled = "1";
}
else
{
gateway.Disabled = currentGateway.Disabled;
}
// Handle monitoring
if (EnableMonitoring.IsPresent && DisableMonitoring.IsPresent)
{
WriteWarning("Both -EnableMonitoring and -DisableMonitoring parameters were specified. Using -EnableMonitoring.");
gateway.MonitorDisable = "0";
}
else if (EnableMonitoring.IsPresent)
{
gateway.MonitorDisable = "0";
}
else if (DisableMonitoring.IsPresent)
{
gateway.MonitorDisable = "1";
}
else
{
gateway.MonitorDisable = currentGateway.MonitorDisable;
}
// Handle force down
if (ForceDown.IsPresent && NoForceDown.IsPresent)
{
WriteWarning("Both -ForceDown and -NoForceDown parameters were specified. Using -ForceDown.");
gateway.ForceDown = "1";
}
else if (ForceDown.IsPresent)
{
gateway.ForceDown = "1";
}
else if (NoForceDown.IsPresent)
{
gateway.ForceDown = "0";
}
else
{
gateway.ForceDown = currentGateway.ForceDown;
}
// Update gateway
var updateTask = Task.Run(async () => await gatewayService.UpdateGatewayAsync(Uuid, gateway));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Gateway {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await gatewayService.ApplyGatewayChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Gateway changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentGateway = getResult.Gateway;
// Create updated gateway
var gateway = new GatewayConfig
{
HandleException(ex);
Name = Name ?? currentGateway.Name,
Interface = Interface ?? currentGateway.Interface,
IpAddress = IpAddress ?? currentGateway.IpAddress,
MonitorIp = MonitorIp ?? currentGateway.MonitorIp,
Description = Description ?? currentGateway.Description,
Weight = Weight?.ToString() ?? currentGateway.Weight,
IpProtocol = IpProtocol ?? currentGateway.IpProtocol
};
// Handle default/not default
if (Default.IsPresent && NotDefault.IsPresent)
{
WriteWarning("Both -Default and -NotDefault parameters were specified. Using -Default.");
gateway.IsDefault = "1";
}
else if (Default.IsPresent)
{
gateway.IsDefault = "1";
}
else if (NotDefault.IsPresent)
{
gateway.IsDefault = "0";
}
else
{
gateway.IsDefault = currentGateway.IsDefault;
}
// Handle enabled/disabled
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
gateway.Disabled = "0";
}
else if (Enabled.IsPresent)
{
gateway.Disabled = "0";
}
else if (Disabled.IsPresent)
{
gateway.Disabled = "1";
}
else
{
gateway.Disabled = currentGateway.Disabled;
}
// Handle monitoring
if (EnableMonitoring.IsPresent && DisableMonitoring.IsPresent)
{
WriteWarning("Both -EnableMonitoring and -DisableMonitoring parameters were specified. Using -EnableMonitoring.");
gateway.MonitorDisable = "0";
}
else if (EnableMonitoring.IsPresent)
{
gateway.MonitorDisable = "0";
}
else if (DisableMonitoring.IsPresent)
{
gateway.MonitorDisable = "1";
}
else
{
gateway.MonitorDisable = currentGateway.MonitorDisable;
}
// Handle force down
if (ForceDown.IsPresent && NoForceDown.IsPresent)
{
WriteWarning("Both -ForceDown and -NoForceDown parameters were specified. Using -ForceDown.");
gateway.ForceDown = "1";
}
else if (ForceDown.IsPresent)
{
gateway.ForceDown = "1";
}
else if (NoForceDown.IsPresent)
{
gateway.ForceDown = "0";
}
else
{
gateway.ForceDown = currentGateway.ForceDown;
}
// Update gateway
var updateResult = ExecuteAsyncTask(() => gatewayService.UpdateGatewayAsync(Uuid, gateway));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Gateway {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => gatewayService.ApplyGatewayChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"Gateway changes applied: {applyResult.Status}");
}
}
}
@@ -87,44 +87,54 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var interfaceService = new InterfaceService(ApiClient, Logger);
// First, get the current interface configuration
var getResult = ExecuteAsyncTask(() => interfaceService.GetInterfaceDetailAsync(Name));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var interfaceService = new InterfaceService(ApiClient, Logger);
// First, get the current interface configuration
var getTask = Task.Run(async () => await interfaceService.GetInterfaceDetailAsync(Name));
var currentInterface = getTask.GetAwaiter().GetResult().Interface;
// Create the updated configuration
var interfaceConfig = new InterfaceConfig
{
Description = Description ?? currentInterface.Description,
IpAddress = IpAddress ?? currentInterface.IpAddress,
SubnetMask = SubnetMask ?? currentInterface.SubnetMask,
Gateway = Gateway ?? currentInterface.Gateway,
Enabled = Enabled.IsPresent ? "1" : "0"
};
// Update the interface
var updateTask = Task.Run(async () => await interfaceService.UpdateInterfaceAsync(Name, interfaceConfig));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Interface {Name} updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var restartTask = Task.Run(async () => await interfaceService.RestartInterfaceAsync(Name));
var restartResult = restartTask.GetAwaiter().GetResult();
WriteVerbose($"Interface {Name} restarted: {restartResult.Status}");
}
return;
}
catch (Exception ex)
var currentInterface = getResult.Interface;
// Create the updated configuration
var interfaceConfig = new InterfaceConfig
{
HandleException(ex);
Description = Description ?? currentInterface.Description,
IpAddress = IpAddress ?? currentInterface.IpAddress,
SubnetMask = SubnetMask ?? currentInterface.SubnetMask,
Gateway = Gateway ?? currentInterface.Gateway,
Enabled = Enabled.IsPresent ? "1" : "0"
};
// Update the interface
var updateResult = ExecuteAsyncTask(() => interfaceService.UpdateInterfaceAsync(Name, interfaceConfig));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Interface {Name} updated: {updateResult.Result}");
// Apply the changes if requested
if (Apply.IsPresent)
{
var restartResult = ExecuteAsyncTask(() => interfaceService.RestartInterfaceAsync(Name));
// Only continue if no exception occurred
if (ProcessingException != null || restartResult == null)
{
return;
}
WriteVerbose($"Interface {Name} restarted: {restartResult.Status}");
}
}
}
@@ -15,7 +15,7 @@ namespace PSOPNSenseAPI.Cmdlets
/// </summary>
[Cmdlet(VerbsCommon.Set, "OPNSensePortForwardingRule", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType(typeof(PortForwardingRule))]
public class SetOPNSensePortForwardingRuleCmdlet : OPNSenseCmdlet
public class SetOPNSensePortForwardingRuleCmdlet : OPNSenseBaseCmdlet
{
/// <summary>
/// <para type="description">The UUID of the port forwarding rule to update.</para>
@@ -118,20 +118,23 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
var portForwardingService = new PortForwardingService(SessionState.ApiClient);
var portForwardingService = new PortForwardingService(ApiClient);
// Get the existing rule
var existingRule = Task.Run(async () => await portForwardingService.GetPortForwardingRuleAsync(Uuid)).GetAwaiter().GetResult();
var existingRule = ExecuteAsyncTask(() => portForwardingService.GetPortForwardingRuleAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
if (existingRule == null)
{
WriteError(new ErrorRecord(
new PSArgumentException($"Port forwarding rule with UUID '{Uuid}' not found."),
"PortForwardingRuleNotFound",
ErrorCategory.ObjectNotFound,
Uuid));
ProcessingException = new PSArgumentException($"Port forwarding rule with UUID '{Uuid}' not found.");
WriteWarning($"Port forwarding rule with UUID '{Uuid}' not found.");
return;
}
@@ -177,7 +180,13 @@ namespace PSOPNSenseAPI.Cmdlets
if (Force || ShouldProcess($"OPNSense firewall", $"Update port forwarding rule with UUID '{Uuid}'"))
{
var success = Task.Run(async () => await portForwardingService.UpdatePortForwardingRuleAsync(existingRule)).GetAwaiter().GetResult();
var success = ExecuteAsyncTask(() => portForwardingService.UpdatePortForwardingRuleAsync(existingRule));
// Only continue if no exception occurred
if (ProcessingException != null)
{
return;
}
if (success)
{
@@ -190,11 +199,8 @@ namespace PSOPNSenseAPI.Cmdlets
}
else
{
WriteError(new ErrorRecord(
new PSInvalidOperationException($"Failed to update port forwarding rule with UUID '{Uuid}'."),
"PortForwardingRuleUpdateFailed",
ErrorCategory.InvalidOperation,
existingRule));
ProcessingException = new PSInvalidOperationException($"Failed to update port forwarding rule with UUID '{Uuid}'.");
WriteWarning($"Failed to update port forwarding rule with UUID '{Uuid}'.");
}
}
}
@@ -69,61 +69,71 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var routeService = new RouteService(ApiClient, Logger);
// Get current route
var getResult = ExecuteAsyncTask(() => routeService.GetRouteAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var routeService = new RouteService(ApiClient, Logger);
// Get current route
var getTask = Task.Run(async () => await routeService.GetRouteAsync(Uuid));
var currentRoute = getTask.GetAwaiter().GetResult().Route;
// Create updated route
var route = new RouteConfig
{
Network = Network ?? currentRoute.Network,
Gateway = Gateway ?? currentRoute.Gateway,
Description = Description ?? currentRoute.Description
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
route.Disabled = "0";
}
else if (Enabled.IsPresent)
{
route.Disabled = "0";
}
else if (Disabled.IsPresent)
{
route.Disabled = "1";
}
else
{
route.Disabled = currentRoute.Disabled;
}
// Update route
var updateTask = Task.Run(async () => await routeService.UpdateRouteAsync(Uuid, route));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"Route {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await routeService.ApplyRouteChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"Route changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentRoute = getResult.Route;
// Create updated route
var route = new RouteConfig
{
HandleException(ex);
Network = Network ?? currentRoute.Network,
Gateway = Gateway ?? currentRoute.Gateway,
Description = Description ?? currentRoute.Description
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
route.Disabled = "0";
}
else if (Enabled.IsPresent)
{
route.Disabled = "0";
}
else if (Disabled.IsPresent)
{
route.Disabled = "1";
}
else
{
route.Disabled = currentRoute.Disabled;
}
// Update route
var updateResult = ExecuteAsyncTask(() => routeService.UpdateRouteAsync(Uuid, route));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"Route {Uuid} updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => routeService.ApplyRouteChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"Route changes applied: {applyResult.Status}");
}
}
}
@@ -93,92 +93,102 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var systemDNSService = new SystemDNSService(ApiClient, Logger);
// Get current configuration
var getResult = ExecuteAsyncTask(() => systemDNSService.GetSystemDNSAsync());
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var systemDNSService = new SystemDNSService(ApiClient, Logger);
// Get current configuration
var getTask = Task.Run(async () => await systemDNSService.GetSystemDNSAsync());
var currentConfig = getTask.GetAwaiter().GetResult().System;
// Create updated configuration
var config = new SystemDNSConfig
{
Hostname = Hostname ?? currentConfig.Hostname,
Domain = Domain ?? currentConfig.Domain,
Timezone = Timezone ?? currentConfig.Timezone,
TimeServers = TimeServers ?? currentConfig.TimeServers,
Language = Language ?? currentConfig.Language
};
// Handle DNS servers
if (DnsServers != null && DnsServers.Length > 0)
{
config.DnsServers = new List<string>(DnsServers);
}
else
{
config.DnsServers = currentConfig.DnsServers;
}
// Handle DNS override
if (AllowDnsOverride.IsPresent && DisallowDnsOverride.IsPresent)
{
WriteWarning("Both -AllowDnsOverride and -DisallowDnsOverride parameters were specified. Using -AllowDnsOverride.");
config.DnsAllowOverride = "1";
}
else if (AllowDnsOverride.IsPresent)
{
config.DnsAllowOverride = "1";
}
else if (DisallowDnsOverride.IsPresent)
{
config.DnsAllowOverride = "0";
}
else
{
config.DnsAllowOverride = currentConfig.DnsAllowOverride;
}
// Handle DNS rebind protection
if (DisableDnsRebindProtection.IsPresent && EnableDnsRebindProtection.IsPresent)
{
WriteWarning("Both -DisableDnsRebindProtection and -EnableDnsRebindProtection parameters were specified. Using -DisableDnsRebindProtection.");
config.DnssecStripped = "1";
}
else if (DisableDnsRebindProtection.IsPresent)
{
config.DnssecStripped = "1";
}
else if (EnableDnsRebindProtection.IsPresent)
{
config.DnssecStripped = "0";
}
else
{
config.DnssecStripped = currentConfig.DnssecStripped;
}
// Update configuration
var updateTask = Task.Run(async () => await systemDNSService.UpdateSystemDNSAsync(config));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"System DNS configuration updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyTask = Task.Run(async () => await systemDNSService.ApplySystemDNSChangesAsync());
var applyResult = applyTask.GetAwaiter().GetResult();
WriteVerbose($"System DNS changes applied: {applyResult.Status}");
}
return;
}
catch (Exception ex)
var currentConfig = getResult.System;
// Create updated configuration
var config = new SystemDNSConfig
{
HandleException(ex);
Hostname = Hostname ?? currentConfig.Hostname,
Domain = Domain ?? currentConfig.Domain,
Timezone = Timezone ?? currentConfig.Timezone,
TimeServers = TimeServers ?? currentConfig.TimeServers,
Language = Language ?? currentConfig.Language
};
// Handle DNS servers
if (DnsServers != null && DnsServers.Length > 0)
{
config.DnsServers = new List<string>(DnsServers);
}
else
{
config.DnsServers = currentConfig.DnsServers;
}
// Handle DNS override
if (AllowDnsOverride.IsPresent && DisallowDnsOverride.IsPresent)
{
WriteWarning("Both -AllowDnsOverride and -DisallowDnsOverride parameters were specified. Using -AllowDnsOverride.");
config.DnsAllowOverride = "1";
}
else if (AllowDnsOverride.IsPresent)
{
config.DnsAllowOverride = "1";
}
else if (DisallowDnsOverride.IsPresent)
{
config.DnsAllowOverride = "0";
}
else
{
config.DnsAllowOverride = currentConfig.DnsAllowOverride;
}
// Handle DNS rebind protection
if (DisableDnsRebindProtection.IsPresent && EnableDnsRebindProtection.IsPresent)
{
WriteWarning("Both -DisableDnsRebindProtection and -EnableDnsRebindProtection parameters were specified. Using -DisableDnsRebindProtection.");
config.DnssecStripped = "1";
}
else if (DisableDnsRebindProtection.IsPresent)
{
config.DnssecStripped = "1";
}
else if (EnableDnsRebindProtection.IsPresent)
{
config.DnssecStripped = "0";
}
else
{
config.DnssecStripped = currentConfig.DnssecStripped;
}
// Update configuration
var updateResult = ExecuteAsyncTask(() => systemDNSService.UpdateSystemDNSAsync(config));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"System DNS configuration updated: {updateResult.Result}");
// Apply changes if requested
if (Apply.IsPresent)
{
var applyResult = ExecuteAsyncTask(() => systemDNSService.ApplySystemDNSChangesAsync());
// Only continue if no exception occurred
if (ProcessingException != null || applyResult == null)
{
return;
}
WriteVerbose($"System DNS changes applied: {applyResult.Status}");
}
}
}
@@ -76,56 +76,61 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var userService = new UserService(ApiClient, Logger);
// First, get the current user
var getResult = ExecuteAsyncTask(() => userService.GetUserAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var userService = new UserService(ApiClient, Logger);
// First, get the current user
var getTask = Task.Run(async () => await userService.GetUserAsync(Uuid));
var currentUser = getTask.GetAwaiter().GetResult().User;
// Create the updated user
var user = new UserConfig
{
Username = currentUser.Username,
Password = Password ?? "",
FullName = FullName ?? currentUser.FullName,
Email = Email ?? currentUser.Email,
Groups = Groups != null ? new List<string>(Groups) : currentUser.Groups,
Authorizations = Authorizations != null ? new List<string>(Authorizations) : currentUser.Authorizations
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
user.Disabled = "0";
}
else if (Enabled.IsPresent)
{
user.Disabled = "0";
}
else if (Disabled.IsPresent)
{
user.Disabled = "1";
}
else
{
user.Disabled = currentUser.Disabled;
}
// Update the user
var updateTask = Task.Run(async () => await userService.UpdateUserAsync(Uuid, user));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"User {Uuid} updated: {updateResult.Result}");
return;
}
catch (Exception ex)
var currentUser = getResult.User;
// Create the updated user
var user = new UserConfig
{
HandleException(ex);
Username = currentUser.Username,
Password = Password ?? "",
FullName = FullName ?? currentUser.FullName,
Email = Email ?? currentUser.Email,
Groups = Groups != null ? new List<string>(Groups) : currentUser.Groups,
Authorizations = Authorizations != null ? new List<string>(Authorizations) : currentUser.Authorizations
};
// Handle enabled/disabled state
if (Enabled.IsPresent && Disabled.IsPresent)
{
WriteWarning("Both -Enabled and -Disabled parameters were specified. Using -Enabled.");
user.Disabled = "0";
}
else if (Enabled.IsPresent)
{
user.Disabled = "0";
}
else if (Disabled.IsPresent)
{
user.Disabled = "1";
}
else
{
user.Disabled = currentUser.Disabled;
}
// Update the user
var updateResult = ExecuteAsyncTask(() => userService.UpdateUserAsync(Uuid, user));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"User {Uuid} updated: {updateResult.Result}");
}
}
}
@@ -59,35 +59,40 @@ namespace PSOPNSenseAPI.Cmdlets
/// <summary>
/// Processes the cmdlet
/// </summary>
protected override void ProcessRecord()
protected override void ProcessRecordInternal()
{
try
var interfaceService = new InterfaceService(ApiClient, Logger);
// First, get the current VLAN configuration
var getResult = ExecuteAsyncTask(() => interfaceService.GetVLANAsync(Uuid));
// Only continue if no exception occurred
if (ProcessingException != null || getResult == null)
{
var interfaceService = new InterfaceService(ApiClient, Logger);
// First, get the current VLAN configuration
var getTask = Task.Run(async () => await interfaceService.GetVLANAsync(Uuid));
var currentVlan = getTask.GetAwaiter().GetResult().Vlan;
// Create the updated configuration
var vlan = new VLANConfig
{
Interface = Interface ?? currentVlan.Interface,
Tag = Tag?.ToString() ?? currentVlan.Tag,
Priority = Priority?.ToString() ?? currentVlan.Priority,
Description = Description ?? currentVlan.Description
};
// Update the VLAN
var updateTask = Task.Run(async () => await interfaceService.UpdateVLANAsync(Uuid, vlan));
var updateResult = updateTask.GetAwaiter().GetResult();
WriteVerbose($"VLAN {Uuid} updated: {updateResult.Result}");
return;
}
catch (Exception ex)
var currentVlan = getResult.Vlan;
// Create the updated configuration
var vlan = new VLANConfig
{
HandleException(ex);
Interface = Interface ?? currentVlan.Interface,
Tag = Tag?.ToString() ?? currentVlan.Tag,
Priority = Priority?.ToString() ?? currentVlan.Priority,
Description = Description ?? currentVlan.Description
};
// Update the VLAN
var updateResult = ExecuteAsyncTask(() => interfaceService.UpdateVLANAsync(Uuid, vlan));
// Only continue if no exception occurred
if (ProcessingException != null || updateResult == null)
{
return;
}
WriteVerbose($"VLAN {Uuid} updated: {updateResult.Result}");
}
}
}
+1 -1
View File
@@ -3,7 +3,7 @@
RootModule = 'lib\PSOPNSenseAPI.dll'
# Version number of this module.
ModuleVersion = '2025.04.15.1257'
ModuleVersion = '2025.04.15.1543'
# Supported PSEditions
CompatiblePSEditions = @('Desktop', 'Core')