aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Program.cs
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2025-12-13 17:33:46 -0600
committerGitHub <noreply@github.com>2025-12-13 17:33:46 -0600
commitfbad7874abc8717dec820980eacce8dd22e8a932 (patch)
treefd7023550e6e65cddccedfe4e3073d686329e02c /src/slskd/Program.cs
parent8c842ff28f507e886ebf7ca6217e11ae2650dff9 (diff)
parent0b939fe41b22e0151d2b0e106310520f19d0c670 (diff)
downloadslskd-fbad7874abc8717dec820980eacce8dd22e8a932.tar.gz
Merge pull request #1580 from slskd/copilot/gracefully-handle-mutex-creation
Handle Mutex creation failures in restricted environments
Diffstat (limited to 'src/slskd/Program.cs')
-rw-r--r--src/slskd/Program.cs35
1 files changed, 32 insertions, 3 deletions
diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs
index cb1961a2..770c6746 100644
--- a/src/slskd/Program.cs
+++ b/src/slskd/Program.cs
@@ -242,7 +242,7 @@ namespace slskd
private static IConfigurationRoot Configuration { get; set; }
private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup();
private static ILogger Log { get; set; } = new ConsoleWriteLineLogger();
- private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName));
+ private static Mutex Mutex { get; set; }
private static IDisposable DotNetRuntimeStats { get; set; }
[Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
@@ -340,9 +340,29 @@ namespace slskd
// the application isn't being run in command mode. check the mutex to ensure
// only one long-running instance.
- if (!Mutex.WaitOne(millisecondsTimeout: 0, exitContext: false))
+ try
+ {
+ Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out bool created);
+
+ if (!created)
+ {
+ Log.Fatal($"An instance of {AppName} is already running");
+ return;
+ }
+ }
+ catch (IOException ex)
+ {
+ Log.Fatal($"I/O exception attempting to acquire the application singleton mutex; this can happen when running in a restricted environment (such as a read-only filesystem or container). Exception: {ex.Message}");
+ return;
+ }
+ catch (UnauthorizedAccessException ex)
{
- Log.Fatal($"An instance of {AppName} is already running");
+ Log.Fatal($"Unauthorized access attempting to acquire the application singleton mutex; this can happen when running with insuffucent permissions. Exception: {ex.Message}");
+ return;
+ }
+ catch (Exception ex)
+ {
+ Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}");
return;
}
@@ -587,6 +607,15 @@ namespace slskd
}
finally
{
+ try
+ {
+ Mutex?.Dispose();
+ }
+ catch (Exception)
+ {
+ // Ignore disposal errors to prevent masking other exceptions
+ }
+
Serilog.Log.CloseAndFlush();
}
}