Skip to content

Commit fbad787

Browse files
authored
Merge pull request #1580 from slskd/copilot/gracefully-handle-mutex-creation
Handle Mutex creation failures in restricted environments
2 parents 8c842ff + 0b939fe commit fbad787

File tree

1 file changed

+32
-3
lines changed

1 file changed

+32
-3
lines changed

src/slskd/Program.cs

Lines changed: 32 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -242,7 +242,7 @@ public static class Program
242242
private static IConfigurationRoot Configuration { get; set; }
243243
private static OptionsAtStartup OptionsAtStartup { get; } = new OptionsAtStartup();
244244
private static ILogger Log { get; set; } = new ConsoleWriteLineLogger();
245-
private static Mutex Mutex { get; } = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName));
245+
private static Mutex Mutex { get; set; }
246246
private static IDisposable DotNetRuntimeStats { get; set; }
247247

248248
[Argument('g', "generate-cert", "generate X509 certificate and password for HTTPs")]
@@ -340,9 +340,29 @@ public static void Main(string[] args)
340340

341341
// the application isn't being run in command mode. check the mutex to ensure
342342
// only one long-running instance.
343-
if (!Mutex.WaitOne(millisecondsTimeout: 0, exitContext: false))
343+
try
344+
{
345+
Mutex = new Mutex(initiallyOwned: true, Compute.Sha256Hash(AppName), out bool created);
346+
347+
if (!created)
348+
{
349+
Log.Fatal($"An instance of {AppName} is already running");
350+
return;
351+
}
352+
}
353+
catch (IOException ex)
354+
{
355+
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}");
356+
return;
357+
}
358+
catch (UnauthorizedAccessException ex)
344359
{
345-
Log.Fatal($"An instance of {AppName} is already running");
360+
Log.Fatal($"Unauthorized access attempting to acquire the application singleton mutex; this can happen when running with insuffucent permissions. Exception: {ex.Message}");
361+
return;
362+
}
363+
catch (Exception ex)
364+
{
365+
Log.Fatal($"Failed to acquire the application singleton mutex: {ex.Message}");
346366
return;
347367
}
348368

@@ -587,6 +607,15 @@ static void ListenHttps(KestrelServerOptions o, IPAddress ip)
587607
}
588608
finally
589609
{
610+
try
611+
{
612+
Mutex?.Dispose();
613+
}
614+
catch (Exception)
615+
{
616+
// Ignore disposal errors to prevent masking other exceptions
617+
}
618+
590619
Serilog.Log.CloseAndFlush();
591620
}
592621
}

0 commit comments

Comments
 (0)