Repository navigation
Expand file tree
/
Copy pathProxyTestController.cs
More file actions
697 lines (605 loc) · 31.4 KB
/
Copy pathProxyTestController.cs
File metadata and controls
697 lines (605 loc) · 31.4 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
using System;
using System.IO;
using System.Net;
using System.Net.Quic;
using System.Net.Security;
using System.Net.Sockets;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Titanium.Web.Proxy.EventArguments;
using Titanium.Web.Proxy.Examples.Shared;
using Titanium.Web.Proxy.Exceptions;
using Titanium.Web.Proxy.Http;
using Titanium.Web.Proxy.Models;
using Titanium.Web.Proxy.Options;
using Titanium.Web.Proxy.StreamExtended.Network;
namespace Titanium.Web.Proxy.Examples.Basic
{
public class ProxyTestController : IDisposable
{
private const int MaxUrlLength = 100;
private const int MaxWebSocketTextLength = 120;
private readonly ProxyServer proxyServer;
private ExplicitProxyEndPoint explicitEndPoint;
private readonly bool trustRootCertificate;
private readonly bool trustRootCertificateMachine;
#pragma warning disable TWP001 // HTTP/3 is experimental — example intentionally exercises this API
#nullable enable
private TransparentQuicProxyEndPoint? quicEndPoint;
#nullable restore
#pragma warning restore TWP001
public ProxyTestController()
{
// false,false: do not auto-trust on Start/SetAsSystemProxy — trust is opt-in via TWP_TRUST_ROOT.
proxyServer = new ProxyServer(false, false, false);
var certificateDirectory = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"Titanium.Web.Proxy");
Directory.CreateDirectory(certificateDirectory);
proxyServer.CertificateManager.PfxFilePath = Path.Combine(certificateDirectory, "rootCert.pfx");
// Opt-in MITM root trust for browser-driven runs:
// TWP_TRUST_ROOT=1 → Current User Personal + Trusted Root (recommended default)
// TWP_TRUST_ROOT_MACHINE=1 → also Local Machine stores (needs elevation)
trustRootCertificate = Environment.GetEnvironmentVariable("TWP_TRUST_ROOT") is "1" or "true" or "TRUE";
trustRootCertificateMachine =
Environment.GetEnvironmentVariable("TWP_TRUST_ROOT_MACHINE") is "1" or "true" or "TRUE";
if (trustRootCertificate || trustRootCertificateMachine)
{
proxyServer.CertificateManager.EnsureRootCertificate();
proxyServer.CertificateManager.TrustRootCertificate(machineTrusted: trustRootCertificateMachine);
}
// Traffic tape uses LogDebug so Release (Warning+) stays limited to failures;
// the built-in console sink (bounded channel, dedicated writer) never blocks a
// session thread on Console.WriteLine. DEBUG also keeps Trace + a rolling file.
#if DEBUG
proxyServer.Logging.MinimumLevel = LogLevel.Trace;
proxyServer.Logging.EnableFile = true;
proxyServer.Logging.FilePath = Path.Combine(
AppContext.BaseDirectory, "logs", "basic-proxy.log");
#else
proxyServer.Logging.MinimumLevel = LogLevel.Warning;
#endif
proxyServer.ApplyLoggingConfiguration();
// Match ProxyProfile.Balanced / library defaults so this example advertises the same
// out-of-the-box posture as NuGet consumers get from new ProxyServer(). Probe harnesses
// override via env (names below) when they need speed-oriented opt-ins.
//
// Env overrides: TWP_ENABLE_CONNECTION_POOL, TWP_FORWARD_UPSTREAM, TWP_PREFETCH,
// TWP_ENABLE_HTTP2, TWP_SAVE_FAKE_CERTS, TWP_LEAF_KEY (ec|rsa), TWP_CAPTURE_TIMING,
// TWP_SET_SYSTEM_PROXY, TWP_ENABLE_HTTP3, TWP_ENABLE_SVCB_DNS, TWP_SESSION_HOOKS
// (last three in StartProxy; TWP_SESSION_HOOKS=0 skips traffic-tape interception).
proxyServer.Profile = ProxyProfile.Balanced;
proxyServer.EnableConnectionPool = ReadEnvBool("TWP_ENABLE_CONNECTION_POOL", defaultValue: true);
// Per-request timing marks are measurement scaffolding; opt in for latency runs.
proxyServer.EnableRequestTimingCapture =
Environment.GetEnvironmentVariable("TWP_CAPTURE_TIMING") is "1" or "true" or "TRUE";
// Resolves the Windows system/PAC upstream gateway per destination. Left on so the example
// still works behind a corporate proxy. On a machine with no PAC or WPAD configured the
// lookup is a no-op, so it is not a cold-start cost there; disable upstream forwarding to
// measure its cost where a PAC script is actually deployed.
proxyServer.ForwardToUpstreamGateway = ReadEnvBool("TWP_FORWARD_UPSTREAM", defaultValue: true);
// Prefetch overlaps origin connect with client TLS on cache hits / HTTP/1.1 clients.
proxyServer.EnableTcpServerConnectionPrefetch = ReadEnvBool("TWP_PREFETCH", defaultValue: true);
proxyServer.EnableHttp2 = ReadEnvBool("TWP_ENABLE_HTTP2", defaultValue: true);
// Library Balanced defaults stay RSA for NuGet consumers; this example (and Inspector/CLI)
// uses fast cold-start leaves for modern browsers. Probe overrides:
// TWP_LEAF_KEY=rsa | TWP_SAVE_FAKE_CERTS=0
proxyServer.CertificateManager.ApplyFastColdStartLeafSettings();
if (Environment.GetEnvironmentVariable("TWP_LEAF_KEY") is "rsa" or "RSA" or "Rsa2048")
proxyServer.CertificateManager.LeafCertificateKeyAlgorithm =
Network.CertificateKeyAlgorithm.Rsa2048;
proxyServer.CertificateManager.SaveFakeCertificates =
ReadEnvBool("TWP_SAVE_FAKE_CERTS", defaultValue: true);
}
public void Dispose()
{
proxyServer.Dispose();
}
public void StartProxy()
{
// Session hooks force full H2 header decode/re-encode (disables compressed HEADERS relay).
// Set TWP_SESSION_HOOKS=0 to A/B YouTube/media without traffic-tape interception.
var sessionHooks = ReadEnvBool("TWP_SESSION_HOOKS", defaultValue: true);
if (sessionHooks)
{
proxyServer.BeforeRequest += OnRequest;
proxyServer.BeforeResponse += OnResponse;
proxyServer.AfterResponse += OnAfterResponse;
}
else
{
Logger.LogWarning(
"TWP_SESSION_HOOKS=0: BeforeRequest/BeforeResponse/AfterResponse not subscribed (H2 compressed relay on)");
}
// Inspect/modify the response body chunk-by-chunk as it streams, without buffering it in memory.
// Do not combine with SessionEventArgs.GetResponseBody (which buffers the whole body).
proxyServer.ServerCertificateValidationCallback += OnCertificateValidation;
proxyServer.ClientCertificateSelectionCallback += OnCertificateSelection;
explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 8000);
// Fired when a CONNECT request is received
explicitEndPoint.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
explicitEndPoint.BeforeTunnelConnectResponse += OnBeforeTunnelConnectResponse;
// An explicit endpoint is where the client knows about the existence of a proxy
// So client sends request in a proxy friendly manner
proxyServer.AddEndPoint(explicitEndPoint);
// HTTP/3 transparent QUIC endpoint (experimental — suppress TWP001 to opt in).
// Requires MsQuic native library and a supported OS:
// Windows: Windows 11 / Server 2022+
// Linux: apt install libmsquic
// macOS: bundle libmsquic + libssl + libcrypto with @loader_path RPATH
// Traffic must be redirected here (e.g. via iptables/nftables UDP REDIRECT on Linux,
// WFP on Windows, or pf rdr on macOS). See wiki/HTTP-3.md for setup details.
#pragma warning disable TWP001
// Example default is on (library Balanced default remains off). Set TWP_ENABLE_HTTP3=0 to disable.
// TWP_ENABLE_SVCB_DNS=1 enables background HTTPS/SVCB discovery when HTTP/3 is on.
var enableHttp3 = ReadEnvBool("TWP_ENABLE_HTTP3", defaultValue: true);
var enableSvcbEnv = Environment.GetEnvironmentVariable("TWP_ENABLE_SVCB_DNS");
if (enableHttp3 && QuicListener.IsSupported)
{
proxyServer.EnableHttp3 = true;
// Interactive system-proxy browsing: learn H3 from Alt-Svc on the first response.
// Proactive SVCB discovery is opt-in via TWP_ENABLE_SVCB_DNS so measurement runs can
// re-enable the matrix without editing this file.
proxyServer.EnableHttpsSvcbDnsDiscovery = enableSvcbEnv is "1" or "true" or "TRUE";
quicEndPoint = new TransparentQuicProxyEndPoint(IPAddress.Any, 443)
{
// Replace with IOriginalDestinationResolver for real NAT-transparent interception.
// ForwardHost and ForwardPort are used as a fallback when no resolver is set.
ForwardHost = "localhost",
ForwardPort = 443
};
quicEndPoint.BeforeQuicAuthenticate += OnBeforeQuicAuthenticate;
proxyServer.AddEndPoint(quicEndPoint);
Logger.LogWarning(
"HTTP/3 QUIC endpoint started on UDP 443 (SVCB discovery={Discovery}).",
proxyServer.EnableHttpsSvcbDnsDiscovery ? "on" : "off");
}
else
{
Logger.LogWarning(
"[HTTP/3] Skipped: QuicListener.IsSupported is false on this platform, or TWP_ENABLE_HTTP3 disabled it.");
Logger.LogWarning(" Windows: requires Windows 11 / Server 2022+.");
Logger.LogWarning(" Linux: apt install libmsquic");
Logger.LogWarning(" macOS: bundle libmsquic + libssl + libcrypto with @loader_path RPATH.");
}
#pragma warning restore TWP001
try
{
proxyServer.Start();
}
catch (Exception ex) when (IsAddressAlreadyInUse(ex))
{
Logger.LogWarning(ex, "Port 8000 in use; falling back to ephemeral port 0");
proxyServer.RemoveEndPoint(explicitEndPoint);
explicitEndPoint = new ExplicitProxyEndPoint(IPAddress.Any, 0);
explicitEndPoint.BeforeTunnelConnectRequest += OnBeforeTunnelConnectRequest;
explicitEndPoint.BeforeTunnelConnectResponse += OnBeforeTunnelConnectResponse;
proxyServer.AddEndPoint(explicitEndPoint);
proxyServer.Start();
}
foreach (var endPoint in proxyServer.ProxyEndPoints)
Logger.LogWarning("Listening on '{EndPointType}' endpoint at Ip {IpAddress} and port: {Port}",
endPoint.GetType().Name, endPoint.IpAddress, endPoint.Port);
// tools/ColdStartProbe connects to the endpoint directly and sets TWP_SET_SYSTEM_PROXY=0,
// so a measurement run never rewrites the machine's WinINet proxy configuration.
if (OperatingSystem.IsWindows() && ReadEnvBool("TWP_SET_SYSTEM_PROXY", defaultValue: true))
{
// Identity hosts are WinINET-bypassed; pinning demos use DecryptSsl=false below.
proxyServer.SetAsSystemProxy(explicitEndPoint, ProxyProtocolType.AllHttp,
KnownMitmExclusions.CreateSystemProxySettings());
}
Logger.LogWarning(
"Knobs: profile={Profile} pool={Pool} prefetch={Prefetch} h2={Http2} h3={Http3} " +
"forwardUpstream={ForwardUpstream} saveCerts={SaveCerts} leafKey={LeafKey} timing={Timing}",
proxyServer.Profile,
proxyServer.EnableConnectionPool,
proxyServer.EnableTcpServerConnectionPrefetch,
proxyServer.EnableHttp2,
enableHttp3,
proxyServer.ForwardToUpstreamGateway,
proxyServer.CertificateManager.SaveFakeCertificates,
proxyServer.CertificateManager.LeafCertificateKeyAlgorithm,
proxyServer.EnableRequestTimingCapture);
}
private static bool ReadEnvBool(string name, bool defaultValue)
{
return Environment.GetEnvironmentVariable(name) switch
{
"1" or "true" or "TRUE" => true,
"0" or "false" or "FALSE" => false,
_ => defaultValue
};
}
private static bool IsAddressAlreadyInUse(Exception ex)
{
for (var cur = ex; cur != null; cur = cur.InnerException)
{
if (cur is SocketException se &&
(se.SocketErrorCode == SocketError.AddressAlreadyInUse
|| se.NativeErrorCode is 10048 or 98))
return true;
}
return false;
}
public void Stop()
{
Logger.LogWarning("Stopping proxy...");
explicitEndPoint.BeforeTunnelConnectRequest -= OnBeforeTunnelConnectRequest;
explicitEndPoint.BeforeTunnelConnectResponse -= OnBeforeTunnelConnectResponse;
#pragma warning disable TWP001
if (quicEndPoint != null)
quicEndPoint.BeforeQuicAuthenticate -= OnBeforeQuicAuthenticate;
#pragma warning restore TWP001
proxyServer.BeforeRequest -= OnRequest;
proxyServer.BeforeResponse -= OnResponse;
proxyServer.AfterResponse -= OnAfterResponse;
proxyServer.ServerCertificateValidationCallback -= OnCertificateValidation;
proxyServer.ClientCertificateSelectionCallback -= OnCertificateSelection;
proxyServer.Stop();
// Only undo what this run installed (see TWP_TRUST_ROOT / TWP_TRUST_ROOT_MACHINE above).
if (trustRootCertificate || trustRootCertificateMachine)
proxyServer.CertificateManager.RemoveTrustedRootCertificate(
machineTrusted: trustRootCertificateMachine);
}
private async Task<IExternalProxy> OnGetCustomUpStreamProxyFunc(SessionEventArgsBase arg)
{
arg.GetState().AppendPipeline(nameof(OnGetCustomUpStreamProxyFunc));
// this is just to show the functionality, provided values are junk
return new ExternalProxy
{
BypassLocalhost = false,
HostName = "127.0.0.9",
Port = 9090,
Password = "fake", // NOSONAR S2068 - demo ExternalProxy sample credentials
UserName = "fake",
UseDefaultCredentials = false
};
}
private async Task<IExternalProxy> OnCustomUpStreamProxyFailureFunc(SessionEventArgsBase arg)
{
arg.GetState().AppendPipeline(nameof(OnCustomUpStreamProxyFailureFunc));
// this is just to show the functionality, provided values are junk
return new ExternalProxy
{
BypassLocalhost = false,
HostName = "127.0.0.10",
Port = 9191,
Password = "fake2", // NOSONAR S2068 - demo ExternalProxy sample credentials
UserName = "fake2",
UseDefaultCredentials = false
};
}
private async Task OnBeforeTunnelConnectRequest(object sender, TunnelConnectSessionEventArgs e)
{
var hostname = e.HttpClient.Request.RequestUri.Host;
e.GetState().AppendPipeline(nameof(OnBeforeTunnelConnectRequest) + ":" + hostname);
var clientLocalIp = e.ClientLocalEndPoint.Address;
if (!clientLocalIp.Equals(IPAddress.Loopback) && !clientLocalIp.Equals(IPAddress.IPv6Loopback))
e.HttpClient.UpStreamEndPoint = new IPEndPoint(clientLocalIp, 0);
if (KnownMitmExclusions.ShouldDisableSslDecrypt(hostname))
// Opaque tunnel for pinned apps (Dropbox/Webex) and identity hosts that still CONNECT.
e.DecryptSsl = false;
// Opaque tunnels (no decrypt) get a single Debug line; decrypted hosts show up as request lines later.
if (!e.DecryptSsl)
Logger.LogDebug("TUNNEL {Hostname} (ssl passthrough)", hostname);
#if DEBUG
else
Logger.LogDebug("Tunnel to: {Hostname}", hostname);
#endif
}
private void WebSocket_DataSent(object sender, DataEventArgs e)
{
var args = (SessionEventArgs)sender;
WebSocketDataSentReceived(args, e, true);
}
private void WebSocket_DataReceived(object sender, DataEventArgs e)
{
var args = (SessionEventArgs)sender;
WebSocketDataSentReceived(args, e, false);
}
private void WebSocketDataSentReceived(SessionEventArgs args, DataEventArgs e, bool sent)
{
var arrow = sent ? "→" : "←";
var decoder = sent ? args.WebSocketDecoderSend : args.WebSocketDecoderReceive;
foreach (var frame in decoder.Decode(e.Buffer, e.Offset, e.Count))
{
if (frame.OpCode == WebsocketOpCode.Binary)
{
Logger.LogDebug("WS {Arrow} binary {Length}B", arrow, frame.Data.Length);
continue;
}
if (frame.OpCode == WebsocketOpCode.Text)
Logger.LogDebug("WS {Arrow} {Text}", arrow,
Truncate(frame.GetText(), MaxWebSocketTextLength));
}
}
private static Task OnBeforeTunnelConnectResponse(object sender, TunnelConnectSessionEventArgs e)
{
e.GetState().AppendPipeline(
nameof(OnBeforeTunnelConnectResponse) + ":" + e.HttpClient.Request.RequestUri);
return Task.CompletedTask;
}
#pragma warning disable TWP001
private Task OnBeforeQuicAuthenticate(object sender, BeforeQuicAuthenticateEventArgs e)
{
Logger.LogDebug("[QUIC] Connection from {RemoteEndPoint} (SNI: {SniHostName})",
e.RemoteEndPoint, e.SniHostName);
return Task.CompletedTask;
}
#pragma warning restore TWP001
// intercept & cancel redirect or update requests
private async Task OnRequest(object sender, SessionEventArgs e)
{
var state = e.GetState();
state.RequestStartedUtc = DateTime.UtcNow;
state.AppendPipeline(nameof(OnRequest) + ":" + e.HttpClient.Request.RequestUri);
var clientLocalIp = e.ClientLocalEndPoint.Address;
if (!clientLocalIp.Equals(IPAddress.Loopback) && !clientLocalIp.Equals(IPAddress.IPv6Loopback))
e.HttpClient.UpStreamEndPoint = new IPEndPoint(clientLocalIp, 0);
// Subscribed here (rather than in OnResponse, once TunnelType.Websocket is known) so the
// proxy sees a raw-byte tap is wanted before it forwards the upgrade request - only then can
// it strip Sec-WebSocket-Extensions and keep frames uncompressed for WebSocketDecoder below
// (see WebSocketHandler.HasWebSocketDataTapHandler remarks).
if (e.HttpClient.Request.UpgradeToWebSocket)
{
e.DataSent += WebSocket_DataSent;
e.DataReceived += WebSocket_DataReceived;
}
if (e.HttpClient.Request.Url.Contains("yahoo.com"))
e.CustomUpStreamProxy = new ExternalProxy("localhost", 8888);
}
// Modify response
private async Task MultipartRequestPartSent(object sender, MultipartRequestPartSentEventArgs e)
{
e.GetState().AppendPipeline(nameof(MultipartRequestPartSent));
Logger.LogDebug("Multipart form data headers:");
foreach (var header in e.Headers)
Logger.LogDebug("{Header}", header.ToString());
}
private static Task OnResponse(object sender, SessionEventArgs e)
{
e.GetState().AppendPipeline(nameof(OnResponse));
return Task.CompletedTask;
}
// Called for each response body chunk as it streams to the client (no full-body buffering).
// Replace e.BodyBytes to modify the body on the fly.
private Task OnResponseBodyWrite(object sender, BeforeBodyWriteEventArgs e)
{
_ = sender; // Required by the event-handler signature.
Logger.LogDebug("Response body chunk: {Length} bytes (last: {IsLastChunk})",
e.BodyBytes.Length, e.IsLastChunk);
return Task.CompletedTask;
}
private async Task OnAfterResponse(object sender, SessionEventArgs e)
{
var state = e.GetState();
var request = e.HttpClient.Request;
var response = e.HttpClient.Response;
var statusCode = response?.StatusCode ?? 0;
var elapsedMs = state.RequestStartedUtc == default
? 0
: (long)(DateTime.UtcNow - state.RequestStartedUtc).TotalMilliseconds;
// A status-0 response with no HttpVersion means the origin round trip never produced a
// response at all. Classify expected teardown / origin reachability separately from
// genuine proxy defects so the traffic tape does not paint ad-beacon DNS misses red.
var tapeKind = ClassifyIncompleteSession(statusCode, e.Exception);
// Compact traffic tape: METHOD host/path → status H2↔H2 187ms
string line;
LogLevel level;
switch (tapeKind)
{
case IncompleteSessionKind.ClientCancelled:
line =
$"{request.Method,-7} {FormatUrlForConsole(request.Url)} ⇢ cancelled by client {elapsedMs}ms";
level = LogLevel.Debug;
break;
case IncompleteSessionKind.OriginReset:
// Origin RST_STREAM (REFUSED_STREAM / early reset) before any response headers —
// common under CDN load-shedding (e.g. GitHub/Fastly). Not a client abort.
line =
$"{request.Method,-7} {FormatUrlForConsole(request.Url)} ⇢ reset by origin {elapsedMs}ms";
level = LogLevel.Debug;
break;
case IncompleteSessionKind.ConnectFailed:
line =
$"{request.Method,-7} {FormatUrlForConsole(request.Url)} ⇢ connect failed {FormatHttpProtocolShort(request.HttpVersion)}↔? {elapsedMs}ms";
level = LogLevel.Warning;
break;
case IncompleteSessionKind.NoResponse:
// Status 0 with no classified exception (aborted beacon, force-killed proxy,
// idle teardown). Keep Warning — never paint these red as proxy defects.
line =
$"{request.Method,-7} {FormatUrlForConsole(request.Url)} ⇢ no response {FormatHttpProtocolShort(request.HttpVersion)}↔? {elapsedMs}ms";
level = LogLevel.Warning;
break;
default:
line =
$"{request.Method,-7} {FormatUrlForConsole(request.Url)} → {statusCode,3} {FormatHttpProtocolShort(request.HttpVersion)}↔{FormatHttpProtocolShort(response?.HttpVersion)} {elapsedMs}ms";
level = LevelForStatusCode(statusCode);
break;
}
Logger.Log(level, "{Line}", line);
#if DEBUG
try
{
LogLines(LogLevel.Debug, "Pipelineinfo: " + state.GetPipelineInfo());
}
catch
{
// PipelineInfo is diagnostic-only; ignore races/teardown.
}
#endif
}
private enum IncompleteSessionKind
{
None,
ClientCancelled,
OriginReset,
ConnectFailed,
NoResponse
}
/// <summary>
/// Maps status-0 sessions to traffic-tape presentation. Client aborts and origin
/// connect/DNS/TLS failures are expected under heavy browsing; only real 5xx
/// responses stay red. Status-0 with no attached exception (telemetry aborts,
/// force-killed proxy mid-request) is Warning via <see cref="IncompleteSessionKind.NoResponse" />,
/// not Error.
/// </summary>
private static IncompleteSessionKind ClassifyIncompleteSession(int statusCode, Exception exception)
{
if (statusCode != 0)
return IncompleteSessionKind.None;
if (exception == null)
return IncompleteSessionKind.NoResponse;
if (exception is ProxyTimeoutException ||
GetInnermostException(exception) is ProxyTimeoutException)
return IncompleteSessionKind.NoResponse;
var oce = exception as OperationCanceledException
?? GetInnermostException(exception) as OperationCanceledException;
if (oce != null)
{
// Http2Helper stamps distinct messages for client vs origin RST_STREAM before headers.
if (oce.Message.Contains("reset by the origin", StringComparison.OrdinalIgnoreCase) ||
oce.Message.Contains("connection was closed before this stream", StringComparison.OrdinalIgnoreCase))
return IncompleteSessionKind.OriginReset;
return IncompleteSessionKind.ClientCancelled;
}
if (IsOriginConnectFailure(exception))
return IncompleteSessionKind.ConnectFailed;
// Unknown exception with no response — still not a confirmed proxy defect.
return IncompleteSessionKind.NoResponse;
}
private static bool IsOriginConnectFailure(Exception exception)
{
for (var ex = exception; ex != null; ex = ex.InnerException)
{
switch (ex)
{
case SocketException socketEx:
switch (socketEx.SocketErrorCode)
{
case SocketError.HostNotFound:
case SocketError.NoData:
case SocketError.TryAgain:
case SocketError.NetworkUnreachable:
case SocketError.HostUnreachable:
case SocketError.ConnectionRefused:
case SocketError.TimedOut:
case SocketError.NetworkDown:
case SocketError.ConnectionReset:
case SocketError.ConnectionAborted:
return true;
}
break;
case IOException ioEx:
// TLS/TCP peer closed before headers (common for flaky ad sync endpoints).
if (ioEx.InnerException is SocketException)
return true;
if (ioEx.Message.IndexOf("unexpected EOF", StringComparison.OrdinalIgnoreCase) >= 0 ||
ioEx.Message.IndexOf("0 bytes from the transport stream", StringComparison.OrdinalIgnoreCase) >=
0)
return true;
break;
}
}
return false;
}
private static Exception GetInnermostException(Exception exception)
{
var current = exception;
while (current.InnerException != null)
current = current.InnerException;
return current;
}
private static LogLevel LevelForStatusCode(int statusCode)
{
// Status 0 must not reach here for incomplete sessions (ClassifyIncompleteSession
// handles those). Keep Error only for genuine 5xx wire responses.
if (statusCode >= 500)
return LogLevel.Error;
if (statusCode >= 400 || statusCode == 0)
return LogLevel.Warning;
return LogLevel.Information;
}
/// <summary>
/// Host + path for the console; drops long query strings and truncates.
/// </summary>
private static string FormatUrlForConsole(string url)
{
if (string.IsNullOrEmpty(url))
return url;
string compact;
if (Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
compact = uri.IsDefaultPort
? uri.Host + uri.AbsolutePath
: uri.Host + ":" + uri.Port + uri.AbsolutePath;
if (uri.Query.Length > 1)
compact += "?…";
}
else
{
compact = url;
}
return Truncate(compact, MaxUrlLength);
}
private static string Truncate(string value, int maxLength)
{
if (string.IsNullOrEmpty(value) || value.Length <= maxLength)
return value;
return value.Substring(0, maxLength - 1) + "…";
}
/// <summary>
/// Allows overriding default certificate validation logic
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static Task OnCertificateValidation(object sender, CertificateValidationEventArgs e)
{
e.GetState().AppendPipeline(nameof(OnCertificateValidation));
// set IsValid to true/false based on Certificate Errors
if (e.SslPolicyErrors == SslPolicyErrors.None) e.IsValid = true;
return Task.CompletedTask;
}
/// <summary>
/// Allows overriding default client certificate selection logic during mutual authentication
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static Task OnCertificateSelection(object sender, CertificateSelectionEventArgs e)
{
e.GetState().AppendPipeline(nameof(OnCertificateSelection));
// set e.clientCertificate to override
return Task.CompletedTask;
}
/// <summary>
/// Formats an HTTP version for brief console logs (e.g. H1.1, H2, H3).
/// </summary>
private static string FormatHttpProtocolShort(Version version)
{
if (version == null || version.Major == 0)
return "?";
if (version.Major >= 2)
return "H" + version.Major;
return "H" + version.Major + "." + version.Minor;
}
internal ILogger Logger => proxyServer.Logger;
/// <summary>
/// Logs each line separately so the async sink stamps every line. Never calls Console I/O
/// on the calling thread — <see cref="ILogger.Log" /> is a non-blocking channel write.
/// </summary>
private void LogLines(LogLevel level, string message)
{
var logger = Logger;
if (!logger.IsEnabled(level) || string.IsNullOrEmpty(message))
return;
foreach (var line in message.Split('\n'))
{
var trimmed = line.TrimEnd('\r');
if (trimmed.Length == 0)
continue;
logger.Log(level, "{Line}", trimmed);
}
}
}
}