Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
99 changes: 0 additions & 99 deletions dotnet/LDWin.Core/Capture/CaptureService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -184,105 +184,6 @@ private static HashSet<string> GetUsableInterfaceGuids()
return null;
}

/// <inheritdoc />
public LinkData? Capture(AdapterInfo adapter, TimeSpan timeout, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(adapter);

var device = FindDevice(adapter.Name)
?? throw new InvalidOperationException(
$"Capture adapter '{adapter.Name}' was not found. It may have been removed " +
"or Npcap may not be installed.");

var deadline = Stopwatch.StartNew();
bool opened = false;

try
{
// SharpPcap 6.x configuration-based open. Promiscuous mode is needed
// to see CDP/LLDP frames destined for switch multicast addresses.
device.Open(new DeviceConfiguration
{
Mode = DeviceModes.Promiscuous,
ReadTimeout = ReadTimeoutMs,
});
opened = true;

device.Filter = CdpLldpFilter;

while (true)
{
cancellationToken.ThrowIfCancellationRequested();

if (deadline.Elapsed >= timeout)
{
return null;
}

// GetNextPacket returns after at most ReadTimeoutMs even when no
// packet arrives, so the loop stays responsive to the deadline
// and cancellation token.
var status = device.GetNextPacket(out PacketCapture e);

if (status != GetPacketStatus.PacketRead)
{
// Timeout / no packet this iteration - re-check deadline & token.
continue;
}

byte[] frame;
try
{
frame = e.GetPacket().Data;
}
catch
{
continue;
}

if (frame is not { Length: > 0 })
{
continue;
}

foreach (var decoder in _decoders)
{
LinkData? data;
try
{
if (!decoder.TryDecode(frame, out data) || data is null)
{
continue;
}
}
catch
{
// A decoder throwing on a malformed frame must not abort
// the capture; just try the next decoder / next frame.
continue;
}

PopulateLocalFields(data, adapter);
return data;
}
}
}
finally
{
if (opened)
{
try
{
device.Close();
}
catch
{
// Best-effort close; nothing actionable on failure.
}
}
}
}

/// <inheritdoc />
public IReadOnlyList<LinkData> CaptureAll(
AdapterInfo adapter,
Expand Down
8 changes: 0 additions & 8 deletions dotnet/LDWin.Core/Capture/ICaptureService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,6 @@ public interface ICaptureService
/// <summary>All adapters Npcap can capture on.</summary>
IReadOnlyList<AdapterInfo> GetAdapters();

/// <summary>
/// Listen on <paramref name="adapter"/> until a CDP/LLDP frame is received
/// and decoded, the <paramref name="timeout"/> elapses, or the operation is
/// cancelled. Returns the decoded <see cref="LinkData"/> (with local-adapter
/// fields populated) or <c>null</c> if nothing was received in time.
/// </summary>
LinkData? Capture(AdapterInfo adapter, TimeSpan timeout, CancellationToken cancellationToken = default);

/// <summary>
/// Listen on <paramref name="adapter"/> for the full <paramref name="timeout"/>,
/// collecting every distinct CDP/LLDP neighbour that announces itself.
Expand Down
6 changes: 4 additions & 2 deletions dotnet/LDWin.Core/Models/LinkData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ public string ToReport()
sb.AppendLine($"Platform / model : {Platform}");
sb.AppendLine($"Software version : {SoftwareVersion}");
sb.AppendLine($"Management address : {ManagementAddress}");
sb.AppendLine($"Native VLAN : {Vlan}");

// Optional fields - only shown when the announcement carried them.
// Optional fields - only shown when the announcement carried them. Vlan
// (CDP's Native VLAN TLV) and PortVlanId (LLDP's 802.1 PVID TLV) come from
// different protocols and are rarely both present on the same neighbour.
if (!string.IsNullOrEmpty(Vlan)) sb.AppendLine($"Native VLAN : {Vlan}");
if (!string.IsNullOrEmpty(PortVlanId)) sb.AppendLine($"Port VLAN ID (PVID) : {PortVlanId}");
if (!string.IsNullOrEmpty(VlanName)) sb.AppendLine($"VLAN name : {VlanName}");
if (!string.IsNullOrEmpty(VtpDomain)) sb.AppendLine($"VTP domain : {VtpDomain}");
Expand Down
43 changes: 43 additions & 0 deletions dotnet/LDWin.Core/Protocols/CdpDecoder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,13 @@ public bool TryDecode(byte[] frame, out LinkData? data)
offset += tlvLength;
}

// Checksum is informational only: some captures include Ethernet
// padding past the CDP payload, which would make a strict
// byte-range guess unreliable, so a mismatch is surfaced rather
// than treated as a reason to discard an otherwise well-formed frame.
bool checksumValid = VerifyChecksum(frame, cdpHeaderOffset, offset - cdpHeaderOffset);
link.RawTlvs.Add(checksumValid ? "Checksum: OK" : "Checksum: mismatch (frame may be corrupt)");

if (!link.HasNeighbourInfo)
{
return false;
Expand Down Expand Up @@ -283,6 +290,42 @@ private static string ParseAddresses(byte[] frame, int valueOffset, int valueLen
return firstAny ?? string.Empty;
}

/// <summary>
/// Verifies the standard 16-bit ones'-complement Internet checksum (the same
/// algorithm IP/ICMP/TCP use) that CDP carries in its header. The checksum is
/// computed over the CDP header + TLVs as received (checksum field included,
/// unmodified); a valid frame sums to 0xFFFF.
/// </summary>
private static bool VerifyChecksum(byte[] frame, int offset, int length)
{
if (length <= 0)
{
return false;
}

long sum = 0;
int end = offset + length;
int i = offset;
while (i + 1 < end)
{
sum += (frame[i] << 8) | frame[i + 1];
i += 2;
}

if (i < end)
{
// Odd trailing byte: padded with a zero low byte.
sum += frame[i] << 8;
}

while ((sum >> 16) != 0)
{
sum = (sum & 0xFFFF) + (sum >> 16);
}

return sum == 0xFFFF;
}

private static string DecodeCapabilities(int bitmap)
{
var names = new (int Bit, string Name)[]
Expand Down
34 changes: 34 additions & 0 deletions dotnet/LDWin.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.0.31903.59
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDWin", "LDWin\LDWin.csproj", "{F9DCF8CF-1101-4EFE-9CC9-6DDD04FC6D7F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDWin.Core", "LDWin.Core\LDWin.Core.csproj", "{D2183BDA-0ED7-42B6-A450-107767470E89}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LDWin.Tests", "LDWin.Tests\LDWin.Tests.csproj", "{3571B592-AC95-47DA-AD89-C3F250FA02E6}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F9DCF8CF-1101-4EFE-9CC9-6DDD04FC6D7F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F9DCF8CF-1101-4EFE-9CC9-6DDD04FC6D7F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F9DCF8CF-1101-4EFE-9CC9-6DDD04FC6D7F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F9DCF8CF-1101-4EFE-9CC9-6DDD04FC6D7F}.Release|Any CPU.Build.0 = Release|Any CPU
{D2183BDA-0ED7-42B6-A450-107767470E89}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{D2183BDA-0ED7-42B6-A450-107767470E89}.Debug|Any CPU.Build.0 = Debug|Any CPU
{D2183BDA-0ED7-42B6-A450-107767470E89}.Release|Any CPU.ActiveCfg = Release|Any CPU
{D2183BDA-0ED7-42B6-A450-107767470E89}.Release|Any CPU.Build.0 = Release|Any CPU
{3571B592-AC95-47DA-AD89-C3F250FA02E6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{3571B592-AC95-47DA-AD89-C3F250FA02E6}.Debug|Any CPU.Build.0 = Debug|Any CPU
{3571B592-AC95-47DA-AD89-C3F250FA02E6}.Release|Any CPU.ActiveCfg = Release|Any CPU
{3571B592-AC95-47DA-AD89-C3F250FA02E6}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
43 changes: 22 additions & 21 deletions dotnet/LDWin/Gui/MainForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,10 @@ public sealed class MainForm : Form
private CancellationTokenSource? _captureCts;
private string? _lastReport;

// How long a single listen attempt runs before giving up (or retrying, if
// "keep listening" is checked).
private const int ListenSeconds = 60;

// Path to the settings file for persisting the last selected adapter.
private static readonly string SettingsDir =
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "LDWin");
Expand Down Expand Up @@ -178,7 +182,6 @@ private void OnFormLoad(object? sender, EventArgs e)
}
else
{
// Feature 5: show Npcap version in title bar when available.
var version = _npcap.GetInstalledVersion();
if (!string.IsNullOrWhiteSpace(version))
{
Expand All @@ -205,15 +208,16 @@ private void LoadAdapters()
_adapterCombo.Items.Add(adapter);
}

// Feature 3: restore previously selected adapter.
var saved = LoadSavedAdapterDescription();
// Restore the previously selected adapter, keyed by its stable Npcap
// device name rather than the (possibly duplicated) description.
var saved = LoadSavedAdapterName();
bool restored = false;
if (!string.IsNullOrEmpty(saved))
{
for (int i = 0; i < _adapterCombo.Items.Count; i++)
{
if (_adapterCombo.Items[i] is AdapterInfo ai &&
string.Equals(ai.Description, saved, StringComparison.OrdinalIgnoreCase))
string.Equals(ai.Name, saved, StringComparison.OrdinalIgnoreCase))
{
_adapterCombo.SelectedIndex = i;
restored = true;
Expand Down Expand Up @@ -243,18 +247,17 @@ private void LoadAdapters()

private void OnAdapterSelectionChanged(object? sender, EventArgs e)
{
// Feature 3: persist whenever the selection changes.
if (_adapterCombo.SelectedItem is AdapterInfo ai)
{
SaveAdapterDescription(ai.Description);
SaveAdapterName(ai.Name);
}
}

// -------------------------------------------------------------------------
// Settings persistence (Feature 3)
// Settings persistence
// -------------------------------------------------------------------------

private static string? LoadSavedAdapterDescription()
private static string? LoadSavedAdapterName()
{
try
{
Expand All @@ -271,12 +274,12 @@ private void OnAdapterSelectionChanged(object? sender, EventArgs e)
return null;
}

private static void SaveAdapterDescription(string description)
private static void SaveAdapterName(string name)
{
try
{
Directory.CreateDirectory(SettingsDir);
File.WriteAllText(SettingsFile, description);
File.WriteAllText(SettingsFile, name);
}
catch
{
Expand All @@ -285,14 +288,13 @@ private static void SaveAdapterDescription(string description)
}

// -------------------------------------------------------------------------
// Get / Stop button (Features 1, 2, 4)
// Get / Stop button
// -------------------------------------------------------------------------

private void OnGetOrStopClick(object? sender, EventArgs e)
{
if (_getButton.Text == "Stop")
{
// Feature 4: cancel the running capture/retry loop.
try
{
_captureCts?.Cancel();
Expand Down Expand Up @@ -320,8 +322,7 @@ private async void StartCapture()
return;
}

// Feature 3: persist the adapter at capture start.
SaveAdapterDescription(adapter.Description);
SaveAdapterName(adapter.Name);

// Switch button to "Stop" and disable Save/Copy while running.
_getButton.Text = "Stop";
Expand Down Expand Up @@ -352,8 +353,8 @@ private async void StartCapture()
_saveButton.Enabled = true;
_copyButton.Enabled = true;
_statusLabel.Text = liveNeighbours.Count == 1
? "Found 1 neighbour - still listening for more (up to 60s total)..."
: $"Found {liveNeighbours.Count} neighbours - still listening for more (up to 60s total)...";
? $"Found 1 neighbour - still listening for more (up to {ListenSeconds}s total)..."
: $"Found {liveNeighbours.Count} neighbours - still listening for more (up to {ListenSeconds}s total)...";
});

try
Expand All @@ -365,11 +366,11 @@ private async void StartCapture()
attempt++;
liveNeighbours.Clear();
_statusLabel.Text = keepListening && attempt > 1
? $"Listening for all CDP/LLDP neighbours (attempt {attempt}, up to 60s)..."
: "Listening for all CDP/LLDP neighbours (up to 60s)...";
? $"Listening for all CDP/LLDP neighbours (attempt {attempt}, up to {ListenSeconds}s)..."
: $"Listening for all CDP/LLDP neighbours (up to {ListenSeconds}s)...";

neighbours = await Task.Run(
() => _capture.CaptureAll(adapter, TimeSpan.FromSeconds(60), token, progress.Report),
() => _capture.CaptureAll(adapter, TimeSpan.FromSeconds(ListenSeconds), token, progress.Report),
token);

if (neighbours.Count == 0 && keepListening && !token.IsCancellationRequested)
Expand Down Expand Up @@ -422,7 +423,7 @@ private async void StartCapture()
}

// -------------------------------------------------------------------------
// Feature 2: raw TLV section + multi-neighbour display
// Multi-neighbour report (with raw TLV section per neighbour)
// -------------------------------------------------------------------------

private static string BuildMultiNeighbourReport(IReadOnlyList<LinkData> neighbours)
Expand Down Expand Up @@ -501,7 +502,7 @@ private void OnSaveLinkDataClick(object? sender, EventArgs e)
}

// -------------------------------------------------------------------------
// Feature 1: Copy button
// Copy button
// -------------------------------------------------------------------------

private void OnCopyClick(object? sender, EventArgs e)
Expand Down
Loading