File-Tunnel/ft/Threads.cs
fiddyschmitt 2d9294e16f Stop a bad connection from crashing the whole process
Two gaps let a single malformed frame or DNS/bind failure terminate ft:

  - Threads.StartNew ran the action with no try/catch, so any unhandled
    exception on a fire-and-forget worker took down the process.
  - The RemoteToLocalTunnel ConnectionAccepted handler (which runs on
    such a worker) parsed the peer-supplied endpoint - Split("://")[1]
    and AsEndpoint() - before its try, and the UDP branch (Bind on the
    --udp-send-from port) had no try at all. One malformed Connect frame,
    an unresolvable host, or an occupied UDP port crashed ft.

Wrap the StartNew action in a logging safety net, and wrap the entire
ConnectionAccepted handler (endpoint parse + both protocol branches) so a
failure logs and instructs the counterpart to tear the connection down
instead of escaping the thread. Also validate the proto://host:port split
rather than indexing [1] blindly.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SjajJ7d3BhSZGfsMrGRS5S
2026-07-06 22:56:38 +10:00

47 lines
1.4 KiB
C#

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ft
{
public static class Threads
{
public readonly static ConcurrentBag<Thread> CreatedThreads = [];
public static Thread StartNew(Action action, string threadName)
{
var thread = new Thread(() =>
{
try
{
action();
}
catch (Exception ex)
{
// A fire-and-forget worker throwing must not take down the whole process. The pumps do
// their own restart-on-error; this is the safety net for event handlers (e.g. the
// ConnectionAccepted handler) that run on these threads - one malformed frame or a DNS
// hiccup should drop that connection, not crash ft.
Program.Log($"Thread '{threadName}' terminated with an unhandled exception: {ex.Message}");
}
})
{
Name = $"[FT] {threadName}",
IsBackground = true
};
thread.Start();
if (Debugger.IsAttached)
{
CreatedThreads.Add(thread);
}
return thread;
}
}
}