Repository navigation
Expand file tree
/
Copy pathHaproxyHost.cs
More file actions
762 lines (672 loc) · 26.8 KB
/
Copy pathHaproxyHost.cs
File metadata and controls
762 lines (672 loc) · 26.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Text.RegularExpressions;
using Titanium.Web.Proxy.RpsLoadProbe.Support;
namespace Titanium.Web.Proxy.RpsLoadProbe;
/// <summary>
/// Starts open-source HAProxy (GPL) as a native reverse peer against the shared managed origin.
/// Uses a temp prefix so the user's install tree is never modified.
/// Not available on Windows (no official port) — <see cref="ResolveHaproxyExecutable"/> returns null.
/// </summary>
internal sealed class HaproxyHost : IDisposable
{
private readonly Process process;
private readonly string prefixDir;
public int Port { get; }
public string ListenUrl { get; }
public string Version { get; }
private HaproxyHost(Process process, string prefixDir, int port, string listenUrl, string version)
{
this.process = process;
this.prefixDir = prefixDir;
Port = port;
ListenUrl = listenUrl;
Version = version;
}
public static Task<HaproxyHost?> TryStartHttp1Async(int originHttpPort, string? haproxyPath) =>
TryStartAsync(BuildHttp1Conf(originHttpPort), listenScheme: "http", haproxyPath);
public static async Task<HaproxyHost?> TryStartHttp1TlsAsync(int originHttpPort, string? haproxyPath)
{
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildHttp1TlsConf(originHttpPort, pem), listenScheme: "https", haproxyPath);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
public static async Task<HaproxyHost?> TryStartHttp2Async(int originHttpPort, string? haproxyPath)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
if (exe == null)
return null;
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildHttp2Conf(originHttpPort, pem), listenScheme: "https", haproxyPath);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
/// <summary>
/// Client QUIC/h3 → cleartext HTTP/1. Returns null when HAProxy lacks <c>USE_QUIC</c>.
/// </summary>
public static async Task<HaproxyHost?> TryStartHttp3CleartextAsync(int originHttpPort, string? haproxyPath)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
if (exe == null || !SupportsQuic(exe))
return null;
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildHttp3CleartextConf(originHttpPort, pem), listenScheme: "https",
haproxyPath, listenHost: "localhost", requireUdp: true);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
public static Task<HaproxyHost?> TryStartHttp1ToHttpsAsync(int originHttpsPort, string? haproxyPath) =>
TryStartAsync(BuildHttp1ToHttpsConf(originHttpsPort), listenScheme: "http", haproxyPath);
public static async Task<HaproxyHost?> TryStartHttp1TlsToHttpsAsync(int originHttpsPort, string? haproxyPath)
{
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildHttp1TlsToHttpsConf(originHttpsPort, pem), listenScheme: "https",
haproxyPath);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
public static async Task<HaproxyHost?> TryStartHttp2ToHttpsHttp1Async(int originHttpsPort, string? haproxyPath)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
if (exe == null)
return null;
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildHttp2ToHttpsHttp1Conf(originHttpsPort, pem), listenScheme: "https",
haproxyPath);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
/// <summary>
/// Parameterized native reverse for product-possible wires that are not the original
/// eight terminate-to-H1 arms (h2c inbound, H2/H3 origin).
/// </summary>
public static async Task<HaproxyHost?> TryStartWireAsync(PeerInboundProto inbound, PeerOriginProto origin,
int originPort, string? haproxyPath)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
if (exe == null)
return null;
if ((inbound == PeerInboundProto.H3 || origin == PeerOriginProto.H3) && !SupportsQuic(exe))
return null;
// HAProxy 3.2: QUIC is frontend-only — backend quic4@ is rejected at config check.
if (origin == PeerOriginProto.H3)
return null;
var needsCerts = inbound is PeerInboundProto.H1Tls or PeerInboundProto.H2Tls or PeerInboundProto.H3;
var listenScheme = inbound is PeerInboundProto.H1c or PeerInboundProto.H2c ? "http" : "https";
// H3: match nginx — localhost SNI + dual-stack QUIC (Linux MsQuic prefers ::1).
var listenHost = inbound == PeerInboundProto.H3 ? "localhost" : "127.0.0.1";
var requireUdp = inbound == PeerInboundProto.H3;
if (!needsCerts)
return await TryStartAsync(BuildWireConf(inbound, origin, originPort, pemPath: null), listenScheme,
haproxyPath, listenHost, requireUdp);
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildWireConf(inbound, origin, originPort, pem), listenScheme,
haproxyPath, listenHost, requireUdp);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
public static async Task<HaproxyHost?> TryStartHttp3ToHttpsHttp1Async(int originHttpsPort, string? haproxyPath)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
if (exe == null || !SupportsQuic(exe))
return null;
var prefixProbe = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-certs-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixProbe);
try
{
var pem = await ExportLoopbackCombinedPemAsync(prefixProbe);
return await TryStartAsync(BuildHttp3ToHttpsHttp1Conf(originHttpsPort, pem), listenScheme: "https",
haproxyPath, listenHost: "localhost", requireUdp: true);
}
finally
{
TryDeleteDir(prefixProbe);
}
}
public static bool IsQuicCapable(string? haproxyPath)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
return exe != null && SupportsQuic(exe);
}
private static async Task<HaproxyHost?> TryStartAsync(Func<string, int, string> confBuilder, string listenScheme,
string? haproxyPath, string listenHost = "127.0.0.1", bool requireUdp = false)
{
var exe = ResolveHaproxyExecutable(haproxyPath);
if (exe == null)
return null;
var version = ReadVersion(exe);
var port = requireUdp ? GetFreeDualStackPort() : GetFreeTcpPort();
var prefixDir = Path.Combine(Path.GetTempPath(), "twp-rps-haproxy-" + Guid.NewGuid().ToString("N"));
Directory.CreateDirectory(prefixDir);
Directory.CreateDirectory(Path.Combine(prefixDir, "certs"));
var confPath = Path.GetFullPath(Path.Combine(prefixDir, "haproxy.cfg"));
var conf = confBuilder(prefixDir, port);
if (!conf.EndsWith('\n'))
conf += "\n";
await File.WriteAllTextAsync(confPath, conf, Encoding.ASCII);
await ValidateConfigAsync(exe, confPath);
var startInfo = new ProcessStartInfo
{
FileName = exe,
// -db: foreground, disable background mode (daemon).
Arguments = $"-f \"{confPath}\" -db",
WorkingDirectory = prefixDir,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
var process = Process.Start(startInfo)
?? throw new InvalidOperationException("Failed to start haproxy.");
var deadline = DateTime.UtcNow.AddSeconds(10);
while (DateTime.UtcNow < deadline)
{
if (IsPortOpen(port))
return new HaproxyHost(process, prefixDir, port, $"{listenScheme}://{listenHost}:{port}/", version);
if (process.HasExited)
{
await Task.Delay(100);
var err = await process.StandardError.ReadToEndAsync();
var stdout = await process.StandardOutput.ReadToEndAsync();
TryDeleteDir(prefixDir);
throw new InvalidOperationException(
$"haproxy exited early (code {process.ExitCode}, config: {confPath}). stderr: {err} stdout: {stdout}");
}
Thread.Sleep(50);
}
TryStop(process);
TryDeleteDir(prefixDir);
throw new TimeoutException($"haproxy did not open port {port} in time.");
}
private static string GlobalDefaults() => $"""
global
nbthread {Environment.ProcessorCount}
maxconn 4096
# Match Titanium's 64 KiB HTTP/2 window and 16 KiB frames. Default tune.bufsize is 16 KiB
# and flow-controls a large body down to that buffer.
tune.bufsize 65536
tune.h2.initial-window-size 65536
defaults
mode http
option http-keep-alive
timeout connect 5s
timeout client 65s
timeout server 65s
timeout http-keep-alive 65s
maxconn 4096
""";
private static Func<string, int, string> BuildHttp1Conf(int originHttpPort) => (_, port) => $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port}
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpPort} maxconn 256
""";
private static Func<string, int, string> BuildHttp1TlsConf(int originHttpPort, string pemPath) =>
(prefixDir, port) =>
{
var pemDest = CopyPem(prefixDir, pemPath);
return $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn http/1.1
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpPort} maxconn 256
""";
};
private static Func<string, int, string> BuildHttp2Conf(int originHttpPort, string pemPath) =>
(prefixDir, port) =>
{
var pemDest = CopyPem(prefixDir, pemPath);
return $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn h2,http/1.1
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpPort} maxconn 256
""";
};
private static Func<string, int, string> BuildHttp3CleartextConf(int originHttpPort, string pemPath) =>
(prefixDir, port) =>
{
var pemDest = CopyPem(prefixDir, pemPath);
// Dual-stack QUIC like nginx: Linux MsQuic resolves localhost → ::1 first.
return $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn h2,http/1.1
bind quic4@127.0.0.1:{port} ssl crt "{pemDest}" alpn h3
bind quic6@[::1]:{port} ssl crt "{pemDest}" alpn h3
http-response set-header alt-svc 'h3=":{port}"; ma=86400'
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpPort} maxconn 256
""";
};
private static Func<string, int, string> BuildHttp1ToHttpsConf(int originHttpsPort) =>
(_, port) => $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port}
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpsPort} ssl verify none sni str(localhost) maxconn 256
""";
private static Func<string, int, string> BuildHttp1TlsToHttpsConf(int originHttpsPort, string pemPath) =>
(prefixDir, port) =>
{
var pemDest = CopyPem(prefixDir, pemPath);
return $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn http/1.1
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpsPort} ssl verify none sni str(localhost) maxconn 256
""";
};
private static Func<string, int, string> BuildHttp2ToHttpsHttp1Conf(int originHttpsPort, string pemPath) =>
(prefixDir, port) =>
{
var pemDest = CopyPem(prefixDir, pemPath);
return $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn h2,http/1.1
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpsPort} ssl verify none sni str(localhost) maxconn 256
""";
};
private static Func<string, int, string> BuildHttp3ToHttpsHttp1Conf(int originHttpsPort, string pemPath) =>
(prefixDir, port) =>
{
var pemDest = CopyPem(prefixDir, pemPath);
return $"""
{GlobalDefaults()}
frontend fe
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn h2,http/1.1
bind quic4@127.0.0.1:{port} ssl crt "{pemDest}" alpn h3
bind quic6@[::1]:{port} ssl crt "{pemDest}" alpn h3
http-response set-header alt-svc 'h3=":{port}"; ma=86400'
default_backend be
backend be
http-reuse aggressive
server origin 127.0.0.1:{originHttpsPort} ssl verify none sni str(localhost) maxconn 256
""";
};
private static Func<string, int, string> BuildWireConf(PeerInboundProto inbound, PeerOriginProto origin,
int originPort, string? pemPath) =>
(prefixDir, port) =>
{
string? pemDest = null;
if (pemPath != null)
pemDest = CopyPem(prefixDir, pemPath);
// TLS (or H1) frontends talking cleartext HTTP/2 to the origin break under
// http-reuse aggressive (PROTOCOL_ERROR on reused connections). H2c→H2c is fine
// with aggressive because both sides stay prior-knowledge h2.
var reuse = origin == PeerOriginProto.H2c && inbound != PeerInboundProto.H2c
? "never"
: "aggressive";
// Kestrel HTTP/2 requires :scheme to match the transport. HAProxy defaults H2
// upstream :scheme to https (and forwards client https after TLS terminate).
// https://github.com/haproxy/haproxy/issues/77
var schemeRewrite = OriginSchemeRewrite(inbound, origin);
return $"""
{GlobalDefaults()}
frontend fe
{FrontendBinds(inbound, port, pemDest)}
default_backend be
backend be
http-reuse {reuse}
{schemeRewrite}{OriginServerLine(origin, originPort)}
""";
};
/// <summary>
/// Force absolute URI scheme so HAProxy's H2 upstream :scheme matches cleartext vs TLS origin.
/// </summary>
private static string OriginSchemeRewrite(PeerInboundProto inbound, PeerOriginProto origin)
{
var cleartextInbound = inbound is PeerInboundProto.H1c or PeerInboundProto.H2c;
return origin switch
{
PeerOriginProto.H2c => " http-request set-uri http://%[baseq]\n",
PeerOriginProto.H2Tls or PeerOriginProto.H3 when cleartextInbound =>
" http-request set-uri https://%[baseq]\n",
_ => string.Empty
};
}
private static string FrontendBinds(PeerInboundProto inbound, int port, string? pemDest) => inbound switch
{
PeerInboundProto.H1c => $" bind 127.0.0.1:{port}",
PeerInboundProto.H1Tls => $" bind 127.0.0.1:{port} ssl crt \"{pemDest}\" alpn http/1.1",
PeerInboundProto.H2c => $" bind 127.0.0.1:{port} proto h2",
PeerInboundProto.H2Tls => $" bind 127.0.0.1:{port} ssl crt \"{pemDest}\" alpn h2,http/1.1",
PeerInboundProto.H3 => $"""
bind 127.0.0.1:{port} ssl crt "{pemDest}" alpn h2,http/1.1
bind quic4@127.0.0.1:{port} ssl crt "{pemDest}" alpn h3
bind quic6@[::1]:{port} ssl crt "{pemDest}" alpn h3
http-response set-header alt-svc 'h3=":{port}"; ma=86400'
""",
_ => throw new ArgumentOutOfRangeException(nameof(inbound))
};
private static string OriginServerLine(PeerOriginProto origin, int originPort) => origin switch
{
PeerOriginProto.H1c => $" server origin 127.0.0.1:{originPort} maxconn 256",
PeerOriginProto.H1Tls =>
$" server origin 127.0.0.1:{originPort} ssl verify none sni str(localhost) maxconn 256",
PeerOriginProto.H2c => $" server origin 127.0.0.1:{originPort} proto h2 maxconn 256",
PeerOriginProto.H2Tls =>
$" server origin 127.0.0.1:{originPort} ssl verify none sni str(localhost) alpn h2 proto h2 maxconn 256",
PeerOriginProto.H3 =>
$" server origin quic4@127.0.0.1:{originPort} ssl verify none sni str(localhost) alpn h3 maxconn 256",
_ => throw new ArgumentOutOfRangeException(nameof(origin))
};
private static async Task ValidateConfigAsync(string exe, string confPath)
{
var startInfo = new ProcessStartInfo
{
FileName = exe,
Arguments = $"-c -f \"{confPath}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
};
using var process = Process.Start(startInfo)
?? throw new InvalidOperationException("Failed to start haproxy config check.");
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
var stdout = await stdoutTask;
var stderr = await stderrTask;
if (process.ExitCode != 0)
{
throw new InvalidOperationException(
$"haproxy config check failed (exit {process.ExitCode}) for '{confPath}': stderr: {stderr} stdout: {stdout}");
}
}
private static string CopyPem(string prefixDir, string pemPath)
{
var dest = Path.Combine(prefixDir, "certs", "server.pem");
File.Copy(pemPath, dest, overwrite: true);
return dest.Replace('\\', '/');
}
private static readonly Regex QuicConfigureFlag =
new(@"\bUSE_QUIC\b", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private static readonly Regex QuicOpensslCompatFlag =
new(@"\bUSE_QUIC_OPENSSL_COMPAT\b", RegexOptions.Compiled | RegexOptions.CultureInvariant);
/// <summary>
/// True when <c>haproxy -vv</c> lists a real QUIC stack (<c>USE_QUIC</c> without
/// <c>USE_QUIC_OPENSSL_COMPAT</c>). Compat builds reject <c>bind quic4@</c> unless
/// limited-quic is enabled; GHA installs QuicTLS instead.
/// </summary>
internal static bool SupportsQuic(string exe)
{
var text = ReadHaproxyOutput(exe, "-vv");
if (!QuicConfigureFlag.IsMatch(text))
return false;
return !QuicOpensslCompatFlag.IsMatch(text);
}
private static async Task<string> ExportLoopbackCombinedPemAsync(string dir)
{
Directory.CreateDirectory(dir);
using var cert = LoopbackCertificateAuthority.ServerCertificate;
var pemPath = Path.Combine(dir, "server.pem");
var certPem = PemEncoding.Write("CERTIFICATE", cert.RawData);
using var rsa = cert.GetRSAPrivateKey();
using var ecdsa = cert.GetECDsaPrivateKey();
string keyPem;
if (rsa != null)
keyPem = new string(PemEncoding.Write("PRIVATE KEY", rsa.ExportPkcs8PrivateKey()));
else if (ecdsa != null)
keyPem = new string(PemEncoding.Write("PRIVATE KEY", ecdsa.ExportPkcs8PrivateKey()));
else
throw new InvalidOperationException("Loopback server certificate has no exportable private key.");
await File.WriteAllTextAsync(pemPath, new string(certPem) + "\n" + keyPem);
return pemPath;
}
public void Dispose()
{
TryStop(process);
TryDeleteDir(prefixDir);
}
/// <summary>
/// Resolves HAProxy on PATH. Always returns null on Windows (no official port).
/// When PATH has both a distro binary and a QUIC build (GHA Linux), prefers USE_QUIC.
/// </summary>
public static string? ResolveHaproxyExecutable(string? haproxyPath)
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
return null;
if (!string.IsNullOrWhiteSpace(haproxyPath))
{
if (File.Exists(haproxyPath))
return Path.GetFullPath(haproxyPath);
return null;
}
return FindPreferredOnPath("haproxy");
}
/// <summary>
/// Walk PATH; prefer a binary whose <c>-vv</c> lists <c>USE_QUIC</c> so apt HAProxy
/// does not shadow the GHA QUIC prefix when both are present.
/// </summary>
private static string? FindPreferredOnPath(string fileName)
{
string? first = null;
var pathEnv = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
foreach (var dir in pathEnv.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
try
{
var candidate = Path.Combine(dir.Trim('"'), fileName);
if (!File.Exists(candidate))
continue;
first ??= candidate;
if (SupportsQuic(candidate))
return candidate;
}
catch
{
// ignore bad PATH entries
}
}
return first;
}
public static string HaproxyMissingMessage() =>
"""
haproxy was not found on PATH (and no --haproxy-path was given), or this OS is Windows.
TWP arms will still run. To enable the same-machine HAProxy control arm:
Linux: GHA builds HAProxy 3.2 with USE_QUIC (Ubuntu distro 2.8 has no QUIC).
Locally: build from source with USE_QUIC=1 USE_QUIC_OPENSSL_COMPAT=1, or a QUIC bottle.
macOS: brew install haproxy (GHA fails the job if USE_QUIC is missing after a 3.2 osx source fallback)
Windows: not supported (no official HAProxy Windows port) — cells are Not possible.
Then re-run with haproxy on PATH, or pass --haproxy-path <path-to-haproxy>.
HTTP/3 terminate needs USE_QUIC (GHA Linux/macOS require it; distro apt does not).
""";
private static string ReadVersion(string exe)
{
var text = ReadHaproxyOutput(exe, "-v");
// First line is usually "HAProxy version 2.x.y-... ..."
var line = text.Split('\n', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
.FirstOrDefault() ?? text;
return line.Trim();
}
private static string ReadHaproxyOutput(string exe, string arguments)
{
try
{
using var p = Process.Start(new ProcessStartInfo
{
FileName = exe,
Arguments = arguments,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
CreateNoWindow = true
});
if (p == null) return "unknown";
var err = p.StandardError.ReadToEnd();
var stdout = p.StandardOutput.ReadToEnd();
p.WaitForExit(5000);
var text = string.IsNullOrWhiteSpace(stdout) ? err : stdout;
if (!string.IsNullOrWhiteSpace(stdout) && !string.IsNullOrWhiteSpace(err))
text = stdout + " " + err;
return text.Trim();
}
catch
{
return "unknown";
}
}
private static void TryStop(Process process)
{
try
{
if (!process.HasExited)
{
process.Kill(entireProcessTree: true);
process.WaitForExit(5000);
}
}
catch
{
// best effort
}
process.Dispose();
}
private static string? FindOnPath(string fileName)
{
var pathEnv = Environment.GetEnvironmentVariable("PATH") ?? string.Empty;
foreach (var dir in pathEnv.Split(Path.PathSeparator, StringSplitOptions.RemoveEmptyEntries))
{
try
{
var candidate = Path.Combine(dir.Trim('"'), fileName);
if (File.Exists(candidate))
return candidate;
}
catch
{
// ignore bad PATH entries
}
}
return null;
}
private static bool IsPortOpen(int port)
{
try
{
using var client = new TcpClient();
var result = client.BeginConnect(IPAddress.Loopback, port, null, null);
var ok = result.AsyncWaitHandle.WaitOne(TimeSpan.FromMilliseconds(100));
if (!ok) return false;
client.EndConnect(result);
return true;
}
catch
{
return false;
}
}
private static int GetFreeTcpPort()
{
var listener = new TcpListener(IPAddress.Loopback, 0);
listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
private static int GetFreeDualStackPort()
{
for (var i = 0; i < 20; i++)
{
var port = GetFreeTcpPort();
if (IsUdpPortFree(port))
return port;
}
return GetFreeTcpPort();
}
private static bool IsUdpPortFree(int port)
{
try
{
using var udp = new UdpClient(new IPEndPoint(IPAddress.Loopback, port));
return true;
}
catch
{
return false;
}
}
private static void TryDeleteDir(string dir)
{
try
{
if (Directory.Exists(dir))
Directory.Delete(dir, recursive: true);
}
catch
{
// temp leftovers are fine
}
}
}