-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1668 lines (1478 loc) · 76.1 KB
/
Copy pathProgram.cs
File metadata and controls
1668 lines (1478 loc) · 76.1 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
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// AskUI Connection Debugger
// Diagnoses DNS, TCP, proxy, and gRPC connectivity to an AskUI Controller.
// Usage: askui-debug [--port 26000] [--verbose] [--no-color] <host>
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
const string Version = "0.2.0";
Console.OutputEncoding = Encoding.UTF8;
// ─── Argument parsing / interactive mode ──────────────────────────────────────
string? host = null;
int port = 26000;
bool verbose = false;
bool noColor = false;
string? outputFilename = null;
StreamWriter? outputFile = null;
// Always keep a reference to the real screen before any redirection.
TextWriter screenOut = Console.Out;
if (args.Length == 0)
{
// Interactive mode: no arguments — user probably double-clicked the binary.
Console.WriteLine();
Console.WriteLine(" AskUI Connection Debugger v" + Version);
Console.WriteLine();
Console.Write(" Hostname or IP address: ");
host = Console.ReadLine()?.Trim() ?? "";
if (string.IsNullOrWhiteSpace(host))
{
Console.Error.WriteLine(" No host entered. Press Enter to exit.");
Console.ReadLine();
return 1;
}
var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var defaultPath = Path.Combine(desktop, "askui-debug-output.txt");
Console.Write($" Output file [{defaultPath}]: ");
var fn = Console.ReadLine()?.Trim();
outputFilename = string.IsNullOrEmpty(fn)
? defaultPath
: Path.IsPathRooted(fn) ? fn : Path.Combine(desktop, fn);
outputFile = new StreamWriter(outputFilename, append: false, Encoding.UTF8);
noColor = true; // file output must be plain text
}
else
{
// CLI mode: parse flags.
for (int i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--port" or "-p" when i + 1 < args.Length:
port = int.Parse(args[++i]);
break;
case "--verbose" or "-v":
verbose = true;
break;
case "--no-color":
noColor = true;
break;
case "--help" or "-h":
PrintUsage();
return 0;
default:
if (!args[i].StartsWith('-'))
host = args[i];
break;
}
}
if (host is null) { PrintUsage(); return 1; }
}
// Normalize: strip scheme / trailing slash
host = host.TrimStart()
.Replace("https://", "", StringComparison.OrdinalIgnoreCase)
.Replace("http://", "", StringComparison.OrdinalIgnoreCase)
.TrimEnd('/');
// Handle host:port shorthand (e.g. "192.168.1.100:26000")
if (!host.StartsWith('[') && host.Contains(':'))
{
var lastColon = host.LastIndexOf(':');
if (int.TryParse(host[(lastColon + 1)..], out var embeddedPort))
{
port = embeddedPort;
host = host[..lastColon];
}
}
// ─── Wire up logging and progress display ────────────────────────────────────
//
// Interactive mode:
// • Logger → outputFile only (full details, no screen noise)
// • Progress → screenOut only (spinner/step list, no file noise)
// • Summary → TeeWriter (results appear on screen AND in file)
//
// CLI mode:
// • Logger → Console.Out (full verbose output, current behaviour)
// • Progress → disabled (Logger already shows everything)
// • Summary → Console.Out
Logger log;
TerminalProgress progress;
TextWriter summaryOut;
if (outputFile is not null)
{
log = new Logger(verbose, false, outputFile);
progress = new TerminalProgress(screenOut, enabled: true);
summaryOut = new TeeWriter(screenOut, outputFile);
}
else
{
log = new Logger(verbose, !noColor, Console.Out);
progress = new TerminalProgress(Console.Out, enabled: false);
summaryOut = Console.Out;
}
// Header — written via summaryOut so it lands in both screen and file.
summaryOut.WriteLine();
summaryOut.WriteLine($" AskUI Connection Debugger v{Version}");
summaryOut.WriteLine($" Target: {host}:{port}");
summaryOut.WriteLine();
summaryOut.Flush();
var checker = new Checker(log, progress, summaryOut, host, port);
await checker.RunAllAsync();
if (outputFile is not null)
{
summaryOut.WriteLine();
summaryOut.WriteLine($" Results saved to: {Path.GetFullPath(outputFilename!)}");
summaryOut.WriteLine(" Send that file to the AskUI team.");
summaryOut.WriteLine();
summaryOut.WriteLine(" You can close this window now.");
summaryOut.Flush();
await outputFile.FlushAsync();
outputFile.Dispose();
}
return 0;
// ─── Usage ────────────────────────────────────────────────────────────────────
static void PrintUsage() => Console.Error.WriteLine("""
AskUI Connection Debugger
Diagnoses DNS, TCP, proxy, and gRPC connectivity to an AskUI Controller.
Usage:
askui-debug [flags] <host>
Flags:
--port, -p <port> Target port (default: 26000)
--verbose, -v Show debug-level output
--no-color Disable colored output
--help, -h Show this help
Examples:
askui-debug controller-host
askui-debug --port 26000 192.168.1.100
askui-debug --verbose --no-color 192.168.1.100
""");
// ═════════════════════════════════════════════════════════════════════════════
// Logger — writes detailed output to a TextWriter (file or console).
// ═════════════════════════════════════════════════════════════════════════════
class Logger
{
private readonly bool _verbose;
private readonly bool _color;
private readonly TextWriter _out;
// ANSI escape codes
private const string Reset = "\x1b[0m";
private const string Bold = "\x1b[1m";
private const string Dim = "\x1b[2m";
private const string Red = "\x1b[31m";
private const string Green = "\x1b[32m";
private const string Yellow = "\x1b[33m";
private const string Cyan = "\x1b[36m";
public Logger(bool verbose, bool color, TextWriter output)
{
_verbose = verbose;
_out = output;
if (color && RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
try { EnableWindowsAnsi(); } catch { color = false; }
}
_color = color;
}
public void Section(string name)
{
const int w = 56;
var bar = new string('─', w);
_out.WriteLine();
_out.WriteLine(" " + C(Cyan, bar));
_out.WriteLine(" " + C(Bold, " " + name));
_out.WriteLine(" " + C(Cyan, bar));
}
public void Pass (string fmt, params object?[] a) => Line(C(Green, "[PASS]"), fmt, a);
public void Fail (string fmt, params object?[] a) => Line(C(Red, "[FAIL]"), fmt, a);
public void Warn (string fmt, params object?[] a) => Line(C(Yellow, "[WARN]"), fmt, a);
public void Info (string fmt, params object?[] a) => Line(C(Cyan, "[INFO]"), fmt, a);
public void Sub (string fmt, params object?[] a) => _out.WriteLine(" " + string.Format(fmt, a));
public void Debug(string fmt, params object?[] a)
{
if (_verbose) Line(C(Dim, "[DBUG]"), fmt, a);
}
private void Line(string tag, string fmt, object?[] a) =>
_out.WriteLine($" {tag} {string.Format(fmt, a)}");
private string C(string code, string text) =>
_color ? $"{code}{text}{Reset}" : text;
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
private static void EnableWindowsAnsi()
{
var handle = GetStdHandle(-11); // STD_OUTPUT_HANDLE
GetConsoleMode(handle, out var mode);
SetConsoleMode(handle, mode | 0x0004); // ENABLE_VIRTUAL_TERMINAL_PROCESSING
}
[DllImport("kernel32.dll")] private static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")] private static extern bool GetConsoleMode(IntPtr h, out uint mode);
[DllImport("kernel32.dll")] private static extern bool SetConsoleMode(IntPtr h, uint mode);
}
// ═════════════════════════════════════════════════════════════════════════════
// TerminalProgress — spinner + step list displayed on the screen.
// Disabled in CLI mode (Logger already writes everything).
// ═════════════════════════════════════════════════════════════════════════════
class TerminalProgress
{
private static readonly string[] Frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
private const string PassIcon = "✓";
private const string FailIcon = "✗";
private readonly TextWriter _screen;
private readonly bool _enabled;
private CancellationTokenSource? _cts;
private Task? _spinnerTask;
private string _stepName = "";
public TerminalProgress(TextWriter screen, bool enabled)
{
_screen = screen;
_enabled = enabled;
}
public void Begin(string stepName)
{
if (!_enabled) return;
_stepName = stepName;
_cts = new CancellationTokenSource();
_spinnerTask = SpinAsync(_cts.Token);
}
public async Task EndAsync(bool passed)
{
if (!_enabled) return;
if (_cts is not null)
{
await _cts.CancelAsync();
try { await _spinnerTask!; } catch (OperationCanceledException) { }
_cts.Dispose();
_cts = null;
}
var icon = passed ? PassIcon : FailIcon;
var line = $" {icon} {_stepName}";
var width = 0;
try { width = Console.WindowWidth - 1; } catch { width = 79; }
// Overwrite the spinner line, pad to erase any leftover characters.
_screen.Write('\r');
_screen.WriteLine(line.PadRight(Math.Max(line.Length, width)));
}
private async Task SpinAsync(CancellationToken ct)
{
int frame = 0;
while (!ct.IsCancellationRequested)
{
var spinner = Frames[frame % Frames.Length];
_screen.Write($"\r {spinner} {_stepName}...");
frame++;
try { await Task.Delay(80, ct); }
catch (OperationCanceledException) { break; }
}
}
}
// ═════════════════════════════════════════════════════════════════════════════
// Check result tracking
// ═════════════════════════════════════════════════════════════════════════════
record CheckResult(string Name, bool Passed, string Note);
record FirewallRule(string Name, string Action, string Profiles);
// ═════════════════════════════════════════════════════════════════════════════
// Checker — orchestrates all checks
// ═════════════════════════════════════════════════════════════════════════════
class Checker(Logger log, TerminalProgress progress, TextWriter summaryOut, string host, int port)
{
private readonly List<CheckResult> _results = [];
private readonly List<string> _resolvedIPs = [];
private readonly List<string> _resolvedIPv6s = [];
private string TargetUrl => $"http://{host}:{port}";
public async Task RunAllAsync()
{
await RunAsync("System Information", () => { CheckSystemInfo(); return Task.CompletedTask; });
await RunAsync("Local AskUI Service", CheckLocalServiceAsync);
await RunAsync("Local Network Interfaces", () => { CheckLocalInterfaces(); return Task.CompletedTask; });
await RunAsync("DNS / Name Resolution", CheckDnsAsync);
await RunAsync("Route / Subnet Analysis", () => { CheckRouting(); return Task.CompletedTask; });
await RunAsync("OS Routing Table", CheckRoutingTableAsync);
await RunAsync("ARP Cache", CheckArpAsync);
await RunAsync("ICMP Ping", CheckIcmpAsync);
await RunAsync("Proxy Configuration", () => { CheckProxy(); return Task.CompletedTask; });
await RunAsync("Windows Firewall Rules", CheckFirewallAsync);
await RunAsync("TCP Connectivity", CheckTcpAsync);
await RunAsync("gRPC — no proxy", () => CheckGrpcAsync(useProxy: false));
await RunAsync("gRPC — system proxy", () => CheckGrpcAsync(useProxy: true));
await RunAsync("Controller Discovery", CheckAskUIControllerAsync);
PrintSummary();
}
// Wraps a check: starts the spinner, runs the check, stops the spinner.
// Pass/fail for the spinner is determined by whether any new failure results
// were added to _results during the check.
private async Task RunAsync(string name, Func<Task> check)
{
log.Section(name);
progress.Begin(name);
var failsBefore = _results.Count(r => !r.Passed);
await check();
var failsAfter = _results.Count(r => !r.Passed);
await progress.EndAsync(failsAfter == failsBefore);
}
// ── Record helpers ────────────────────────────────────────────────────────
private void Pass(string name, string note)
{
_results.Add(new(name, true, note));
log.Pass("{0}", note);
}
private void Fail(string name, string note)
{
_results.Add(new(name, false, note));
log.Fail("{0}", note);
}
// ── Check: System Information ─────────────────────────────────────────────
private void CheckSystemInfo()
{
log.Info("Version : {0}", "0.2.0");
log.Info("OS / Arch : {0} / {1}", RuntimeInformation.OSDescription, RuntimeInformation.ProcessArchitecture);
log.Info("Hostname : {0}", Dns.GetHostName());
log.Info("Time (UTC) : {0}", DateTime.UtcNow.ToString("o"));
log.Info("Target : {0}:{1}", host, port);
}
// ── Check: Local AskUI Service ────────────────────────────────────────────
//
// Checks whether the AskUI Core Service (or a standalone Controller) is
// listening on port 26000 on THIS machine — the one running the tool.
// Useful when the tool is run on the controller machine itself to verify
// the service started successfully.
private async Task CheckLocalServiceAsync()
{
log.Info("Checking whether port 26000 is listening locally on this machine...");
IPEndPoint[] listeners;
try
{
listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
}
catch
{
// Fallback: try a TCP connect if the listener table isn't available.
using var tcp = new TcpClient();
try
{
await tcp.ConnectAsync("127.0.0.1", 26000).WaitAsync(TimeSpan.FromSeconds(2));
Pass("Local Service", "port 26000 is open locally (listener table unavailable — verified via connect)");
}
catch
{
log.Info("Port 26000 is not listening on this machine.");
log.Sub("Expected on the CLIENT machine. If this IS the controller, start the AskUI Core Service.");
}
return;
}
var matches = listeners.Where(ep => ep.Port == 26000).ToList();
if (matches.Count == 0)
{
log.Info("Port 26000 is not listening on this machine.");
log.Sub("Expected on the CLIENT machine. If this IS the controller, start the AskUI Core Service.");
return;
}
foreach (var ep in matches)
{
bool isAny = ep.Address.Equals(IPAddress.Any) || ep.Address.Equals(IPAddress.IPv6Any);
bool isLoopback = IPAddress.IsLoopback(ep.Address);
if (isLoopback)
{
Fail("Local Service",
$"AskUI Core Service is bound to {ep.Address}:{ep.Port} — LOOPBACK ONLY");
log.Sub("The service is running but only accepts connections from THIS machine.");
log.Sub("Remote clients (including the Desktop App on another machine) cannot reach it.");
log.Sub("→ Check the AskUI Core Service configuration — the bind address must be 0.0.0.0.");
}
else if (isAny)
{
Pass("Local Service",
$"AskUI Core Service is listening on 0.0.0.0:{ep.Port} — accepts remote connections");
}
else
{
Pass("Local Service",
$"AskUI Core Service is listening on {ep.Address}:{ep.Port}");
log.Sub("Bound to a specific interface. Remote clients on other adapters may not reach it.");
}
}
}
// ── Check: Local Network Interfaces ───────────────────────────────────────
private void CheckLocalInterfaces()
{
foreach (var iface in NetworkInterface.GetAllNetworkInterfaces())
{
if (iface.NetworkInterfaceType is NetworkInterfaceType.Loopback) continue;
var up = iface.OperationalStatus == OperationalStatus.Up;
var state = up ? "UP " : "DOWN";
var ipProps = iface.GetIPProperties();
var ips = new List<string>();
var hasApipa = false;
foreach (var addr in ipProps.UnicastAddresses)
{
var ip = addr.Address;
if (ip.AddressFamily != AddressFamily.InterNetwork) continue;
var s = ip.ToString();
if (IsApipa(ip)) { s += " ⚠ APIPA — DHCP failed, not routable remotely"; hasApipa = true; }
ips.Add(s);
}
var ipStr = ips.Count > 0 ? string.Join(" | ", ips) : "(no IPv4 address)";
if (hasApipa) log.Warn("[{0}] {1,-22} {2}", state, iface.Name, ipStr);
else if (up) log.Pass("[{0}] {1,-22} {2}", state, iface.Name, ipStr);
else log.Info("[{0}] {1,-22} {2}", state, iface.Name, ipStr);
}
}
// ── Check: DNS / Name Resolution ──────────────────────────────────────────
private async Task CheckDnsAsync()
{
if (IPAddress.TryParse(host, out var rawIp))
{
if (rawIp.AddressFamily == AddressFamily.InterNetworkV6)
{
log.Info("Host is a raw IPv6 address — DNS resolution skipped");
_resolvedIPv6s.Add(host);
_results.Add(new("DNS", true, "raw IPv6 address, no resolution needed"));
}
else
{
log.Info("Host is a raw IPv4 address — DNS resolution skipped");
_resolvedIPs.Add(host);
_results.Add(new("DNS", true, "raw IPv4 address, no resolution needed"));
}
return;
}
log.Info("Resolving \"{0}\" via system resolver (hosts → DNS → LLMNR → NetBIOS)...", host);
log.Debug("System resolver = Dns.GetHostAddressesAsync (calls getaddrinfo on all platforms)");
try
{
var sw = Stopwatch.StartNew();
var addresses = await Dns.GetHostAddressesAsync(host).WaitAsync(TimeSpan.FromSeconds(5));
sw.Stop();
var v4Count = addresses.Count(a => a.AddressFamily == AddressFamily.InterNetwork);
var v6Count = addresses.Count(a => a.AddressFamily == AddressFamily.InterNetworkV6);
log.Pass("Resolved {0} address(es) for \"{1}\" in {2}ms ({3} IPv4/A, {4} IPv6/AAAA):",
addresses.Length, host, sw.ElapsedMilliseconds, v4Count, v6Count);
bool anyUsable = false;
foreach (var addr in addresses)
{
if (addr.AddressFamily == AddressFamily.InterNetworkV6)
{
log.Sub(" {0} (IPv6/AAAA)", addr);
_resolvedIPv6s.Add(addr.ToString());
anyUsable = true;
continue;
}
if (IsApipa(addr))
{
log.Warn(" {0} ← APIPA (169.254.x.x) — this adapter has no DHCP lease", addr);
log.Sub(" The machine has a working adapter on a different IP.");
log.Sub(" Run `ipconfig /all` on the target and look for 10.x / 192.168.x / 172.x");
}
else
{
log.Sub(" {0}", addr);
_resolvedIPs.Add(addr.ToString());
anyUsable = true;
}
}
if (!anyUsable)
{
Fail("DNS", "all resolved IPs are APIPA (169.254.x.x) — unreachable over the network");
return;
}
var dnsParts = new List<string>();
if (_resolvedIPs.Count > 0) dnsParts.Add(string.Join(", ", _resolvedIPs));
if (_resolvedIPv6s.Count > 0) dnsParts.Add($"{_resolvedIPv6s.Count} IPv6");
_results.Add(new("DNS", true, $"resolved: {string.Join(" | ", dnsParts)}"));
}
catch (Exception ex)
{
Fail("DNS", $"resolution failed: {ex.Message}");
log.Sub("→ Try the IP address directly instead of the hostname.");
log.Sub("→ On the target machine, run `ipconfig /all` to find its real IP.");
log.Debug("Full exception: {0}", ex);
}
}
// ── Check: Route / Subnet Analysis (Layer 3) ──────────────────────────────
//
// Determines whether the target IP is on the same subnet as a local interface
// (direct Layer-2 path) or must be routed through a gateway (cross-subnet /
// inter-VLAN). A cross-subnet path means a router or ACL firewall sits
// between the machines — a common cause of silent TCP timeouts.
private void CheckRouting()
{
var targets = _resolvedIPs.Count > 0 ? _resolvedIPs : [host];
foreach (var ipStr in targets)
{
if (!IPAddress.TryParse(ipStr, out var targetIp) ||
targetIp.AddressFamily != AddressFamily.InterNetwork)
{
log.Info("Route analysis skipped for {0} (not an IPv4 address).", ipStr);
continue;
}
string? matchIface = null;
IPAddress? matchLocalIp = null;
IPAddress? matchMask = null;
foreach (var iface in NetworkInterface.GetAllNetworkInterfaces())
{
if (iface.OperationalStatus != OperationalStatus.Up) continue;
if (iface.NetworkInterfaceType == NetworkInterfaceType.Loopback) continue;
foreach (var unicast in iface.GetIPProperties().UnicastAddresses)
{
if (unicast.Address.AddressFamily != AddressFamily.InterNetwork) continue;
if (IsApipa(unicast.Address)) continue;
var mask = unicast.IPv4Mask;
if (mask is null) continue;
if (IsInSameSubnet(targetIp, unicast.Address, mask))
{
matchIface = iface.Name;
matchLocalIp = unicast.Address;
matchMask = mask;
break;
}
}
if (matchIface is not null) break;
}
if (matchIface is not null)
{
Pass($"Route:{ipStr}", $"same subnet as {matchLocalIp}/{MaskToCidr(matchMask!)} via {matchIface}");
log.Sub("Traffic takes a direct Layer-2 path — no router between the two machines.");
}
else
{
log.Warn("{0} is on a different subnet — traffic will be routed through a gateway.", ipStr);
log.Sub("A router or inter-VLAN firewall sits between this machine and the target.");
log.Sub("If TCP times out, a network-level ACL between subnets may be dropping packets.");
var gateways = new List<string>();
foreach (var iface in NetworkInterface.GetAllNetworkInterfaces())
{
if (iface.OperationalStatus != OperationalStatus.Up) continue;
foreach (var gw in iface.GetIPProperties().GatewayAddresses)
if (gw.Address.AddressFamily == AddressFamily.InterNetwork)
gateways.Add($"{gw.Address} (via {iface.Name})");
}
if (gateways.Count > 0)
log.Sub("Default gateway(s): {0}", string.Join(", ", gateways));
_results.Add(new($"Route:{ipStr}", false,
"different subnet — routed through gateway (inter-VLAN firewall possible)"));
}
}
}
private static bool IsInSameSubnet(IPAddress a, IPAddress b, IPAddress mask)
{
var ab = a.GetAddressBytes();
var bb = b.GetAddressBytes();
var mb = mask.GetAddressBytes();
for (int i = 0; i < 4; i++)
if ((ab[i] & mb[i]) != (bb[i] & mb[i])) return false;
return true;
}
private static int MaskToCidr(IPAddress mask)
{
var bits = mask.GetAddressBytes();
return bits.Sum(b => System.Numerics.BitOperations.PopCount(b));
}
// ── Check: OS Routing Table (IPv4 + IPv6) ─────────────────────────────────
//
// Reads the OS routing table for both address families and shows the default
// gateway(s). Then performs a specific route lookup for every resolved target
// IP so the operator can see exactly what path packets will take.
private async Task CheckRoutingTableAsync()
{
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
bool isMac = RuntimeInformation.IsOSPlatform(OSPlatform.OSX);
log.Info("Reading OS routing table (IPv4 + IPv6)...");
if (isWindows)
{
var v4Table = await RunCommandAsync("route", "print -4");
log.Debug("route print -4:{0}{1}", Environment.NewLine, v4Table);
ShowWindowsDefaultRoutes(v4Table, "IPv4");
var v6Table = await RunCommandAsync("route", "print -6");
log.Debug("route print -6:{0}{1}", Environment.NewLine, v6Table);
ShowWindowsDefaultRoutes(v6Table, "IPv6");
}
else if (isMac)
{
var v4Table = await RunCommandAsync("netstat", "-rn -f inet");
log.Debug("netstat -rn -f inet:{0}{1}", Environment.NewLine, v4Table);
ShowUnixDefaultRoutes(v4Table, "IPv4");
var v6Table = await RunCommandAsync("netstat", "-rn -f inet6");
log.Debug("netstat -rn -f inet6:{0}{1}", Environment.NewLine, v6Table);
ShowUnixDefaultRoutes(v6Table, "IPv6");
}
else // Linux
{
var v4Table = await RunCommandAsync("ip", "route show");
log.Debug("ip route show:{0}{1}", Environment.NewLine, v4Table);
ShowLinuxDefaultRoutes(v4Table, "IPv4");
var v6Table = await RunCommandAsync("ip", "-6 route show");
log.Debug("ip -6 route show:{0}{1}", Environment.NewLine, v6Table);
ShowLinuxDefaultRoutes(v6Table, "IPv6");
}
// Specific route lookup for each resolved target IP
IEnumerable<string> ipv4Targets = _resolvedIPs.Count > 0
? _resolvedIPs
: (IPAddress.TryParse(host, out var ph) && ph.AddressFamily == AddressFamily.InterNetwork
? (IEnumerable<string>)[host]
: []);
foreach (var ip in ipv4Targets)
await ShowSpecificRouteAsync(ip, isIPv6: false, isWindows, isMac);
foreach (var ip in _resolvedIPv6s)
await ShowSpecificRouteAsync(ip, isIPv6: true, isWindows, isMac);
_results.Add(new("Routing Table", true, "OS routing table read (informational)"));
}
private void ShowWindowsDefaultRoutes(string routeOutput, string family)
{
bool inActive = false;
int shown = 0;
foreach (var raw in routeOutput.Split('\n'))
{
var line = raw.TrimEnd();
if (line.TrimStart().StartsWith("Active Routes:", StringComparison.OrdinalIgnoreCase))
{
inActive = true;
continue;
}
if (!inActive) continue;
if (line.Contains("=====") ||
line.TrimStart().StartsWith("Persistent Routes:", StringComparison.OrdinalIgnoreCase))
break;
var t = line.Trim();
if (string.IsNullOrEmpty(t)) continue;
if (t.StartsWith("Network Destination", StringComparison.OrdinalIgnoreCase)) continue;
bool isDefault = family == "IPv4"
? t.StartsWith("0.0.0.0")
: t.StartsWith("::/0") || t.StartsWith("::0/0");
if (isDefault) { log.Sub("{0} default route: {1}", family, t); shown++; }
}
if (shown == 0) log.Info("{0}: no default route found in routing table.", family);
}
private void ShowUnixDefaultRoutes(string netstatOutput, string family)
{
int shown = 0;
foreach (var raw in netstatOutput.Split('\n'))
{
var t = raw.Trim();
if (t.StartsWith("default", StringComparison.OrdinalIgnoreCase))
{
log.Sub("{0} default route: {1}", family, t);
shown++;
}
}
if (shown == 0) log.Info("{0}: no default route found.", family);
}
private void ShowLinuxDefaultRoutes(string ipRouteOutput, string family)
{
int shown = 0;
foreach (var raw in ipRouteOutput.Split('\n'))
{
var t = raw.Trim();
if (t.StartsWith("default ", StringComparison.OrdinalIgnoreCase))
{
log.Sub("{0} default route: {1}", family, t);
shown++;
}
}
if (shown == 0) log.Info("{0}: no default route found.", family);
}
private async Task ShowSpecificRouteAsync(string ip, bool isIPv6, bool isWindows, bool isMac)
{
log.Info("Route lookup for {0} ({1}):", ip, isIPv6 ? "IPv6" : "IPv4");
string output;
if (isWindows)
{
var script = $@"$ErrorActionPreference='SilentlyContinue'
try {{
$r=Find-NetRoute -RemoteIPAddress '{ip}' 2>$null | Select-Object -First 1
if($r){{""Prefix=$($r.DestinationPrefix) NextHop=$($r.NextHop) Interface=$($r.InterfaceAlias) Metric=$($r.RouteMetric)""}}
}} catch {{}}";
var encoded = Convert.ToBase64String(Encoding.Unicode.GetBytes(script));
output = await RunCommandAsync("powershell", $"-NoProfile -NonInteractive -EncodedCommand {encoded}");
}
else if (isMac)
{
output = isIPv6
? await RunCommandAsync("route", $"-n get -inet6 {ip}")
: await RunCommandAsync("route", $"-n get {ip}");
}
else
{
output = isIPv6
? await RunCommandAsync("ip", $"-6 route get {ip}")
: await RunCommandAsync("ip", $"route get {ip}");
}
log.Debug("Route lookup output:{0}{1}", Environment.NewLine, output);
if (string.IsNullOrWhiteSpace(output))
{
if (isIPv6)
log.Info("No IPv6 route for {0} — this machine may have no IPv6 connectivity.", ip);
else
log.Warn("No route found for {0} — host may be unreachable.", ip);
return;
}
foreach (var line in output.Split('\n', StringSplitOptions.RemoveEmptyEntries).Take(10))
{
var t = line.TrimEnd();
if (!string.IsNullOrEmpty(t.Trim()))
log.Sub(" {0}", t.TrimStart());
}
}
// ── Check: ARP Cache (Layer 2) ────────────────────────────────────────────
//
// Looks up the target IP in the local ARP table. A hit confirms the host has
// been seen at Layer 2 (same broadcast domain) recently. A miss is expected
// when the target is on a different subnet or on first contact — not a failure.
private async Task CheckArpAsync()
{
var targets = _resolvedIPs.Count > 0 ? _resolvedIPs : [host];
foreach (var ip in targets)
{
log.Info("Checking ARP cache for {0}...", ip);
var arpArgs = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? $"-a {ip}" : $"-n {ip}";
var output = await RunCommandAsync("arp", arpArgs);
log.Debug("arp output:{0}{1}", Environment.NewLine, output);
var mac = ParseArpMac(output, ip);
if (mac is not null)
{
Pass($"ARP:{ip}", $"{ip} → {mac} (host has Layer-2 visibility)");
}
else
{
log.Info("{0} not in ARP cache.", ip);
log.Sub("Expected if the target is on a different subnet (traffic goes via gateway).");
log.Sub("Expected on first connection attempt or after ARP cache expiry.");
}
}
}
private static string? ParseArpMac(string output, string ip)
{
foreach (var line in output.Split('\n'))
{
if (!line.Contains(ip)) continue;
if (line.Contains("no entry", StringComparison.OrdinalIgnoreCase)) return null;
if (line.Contains("No ARP Entries", StringComparison.OrdinalIgnoreCase)) return null;
var parts = line.Split([' ', '\t'], StringSplitOptions.RemoveEmptyEntries);
foreach (var p in parts)
{
if (p.Length < 17) continue;
var norm = p.Replace(':', '-').ToLowerInvariant();
var segments = norm.Split('-');
if (segments.Length == 6 &&
segments.All(s => s.Length == 2 && s.All(c => "0123456789abcdef".Contains(c))))
return p;
}
}
return null;
}
// ── Check: ICMP Ping (Layer 3) ────────────────────────────────────────────
//
// Sends 4 ICMP echo probes. A response proves IP-level reachability even if
// the TCP port is firewalled. No response does NOT prove the host is down —
// Windows Firewall blocks ICMP by default.
//
// Cross-correlate with TCP:
// ICMP pass + TCP fail → host alive, block is at Layer 4 (port / firewall)
// ICMP fail + TCP fail → host unreachable at network level, or ICMP blocked
// ICMP pass + TCP pass → all good
private async Task CheckIcmpAsync()
{
var targets = _resolvedIPs.Count > 0 ? _resolvedIPs : [host];
using var ping = new Ping();
foreach (var ip in targets)
{
log.Info("Sending 4 ICMP echo probes to {0}...", ip);
var latencies = new List<long>();
int receivedTtl = 0;
var failures = new List<string>();
for (int i = 0; i < 4; i++)
{
try
{
var reply = await ping.SendPingAsync(ip, 3000);
if (reply.Status == IPStatus.Success)
{
latencies.Add(reply.RoundtripTime);
receivedTtl = reply.Options?.Ttl ?? receivedTtl;
}
else
{
failures.Add(reply.Status.ToString());
log.Debug("ICMP probe {0}: {1}", i + 1, reply.Status);
}
}
catch (Exception ex)
{
failures.Add(ex.Message);
log.Debug("ICMP probe {0} exception: {1}", i + 1, ex.Message);
}
}
if (latencies.Count > 0)
{
var avg = (long)latencies.Average();
var min = latencies.Min();
var max = latencies.Max();
Pass($"ICMP:{ip}", $"responds to ping — avg {avg}ms (min {min} / max {max}), TTL={receivedTtl}");
if (receivedTtl > 0)
{
int initialTtl = receivedTtl <= 64 ? 64 : receivedTtl <= 128 ? 128 : 255;
int hops = initialTtl - receivedTtl;
if (hops > 0)
log.Sub("~{0} hop(s) to target (received TTL {1}, estimated initial TTL {2})", hops, receivedTtl, initialTtl);
}
}
else
{
var reason = failures.Count > 0 ? failures[0] : "all probes timed out";
log.Warn("No ICMP response from {0}: {1}", ip, reason);
log.Sub("Windows Firewall blocks ICMP by default — a non-response is NOT proof the host is down.");
log.Sub("Cross-reference with TCP: both timeout → likely a network-level block.");
_results.Add(new($"ICMP:{ip}", false,
$"no ICMP response ({reason}) — may be firewall-blocked, not necessarily unreachable"));
}
}
}
// ── Check: Proxy Configuration ────────────────────────────────────────────
private void CheckProxy()
{
var envVars = new[] { "HTTP_PROXY", "http_proxy", "HTTPS_PROXY", "https_proxy", "NO_PROXY", "no_proxy" };
bool anySet = false;
foreach (var key in envVars)
{
var val = Environment.GetEnvironmentVariable(key);
if (val is not null) { log.Warn("{0,-14} = {1}", key, val); anySet = true; }
else log.Debug("{0,-14} = (not set)", key);
}
if (!anySet) log.Pass("No proxy environment variables set");
var sysProxy = WebRequest.DefaultWebProxy;
if (sysProxy is not null)
{
var targetUri = new Uri(TargetUrl);
var proxyUri = sysProxy.GetProxy(targetUri);
var bypassed = sysProxy.IsBypassed(targetUri);
if (!bypassed && proxyUri?.Host != targetUri.Host)
{
log.Warn("System proxy detected for {0}: {1}", TargetUrl, proxyUri);
log.Sub("gRPC over HTTP/2 cleartext (h2c) cannot tunnel through most HTTP proxies.");
log.Sub("The proxy may silently drop or reject gRPC connections.");
}
else
{
log.Pass("No proxy would be used for {0} (direct connection)", TargetUrl);
}
}
else
{
log.Pass("WebRequest.DefaultWebProxy is null — no system proxy configured");
}
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
log.Info("Tip: Run `netsh winhttp show proxy` to inspect the WinHTTP proxy separately.");
}
}
// ── Check: Windows Firewall Rules ─────────────────────────────────────────
//
// Reads the global firewall policy (on/off, default inbound/outbound actions)
// and queries rules specific to the target port:
// • Inbound — relevant if THIS machine is the AskUI Controller.
// • Outbound — relevant if THIS machine is the CLIENT connecting remotely.
//
// Only meaningful on Windows; other platforms get manual-command hints.
private async Task CheckFirewallAsync()