Skip to content

Fixing potential race-condition in WinpkFilterDevice.cs - #656

Merged
kayoub5 merged 1 commit into
dotpcap:masterfrom
meta-space:winpkfilter-race-patch
Oct 8, 2026
Merged

kayoub5 merged 1 commit into
dotpcap:masterfrom
meta-space:winpkfilter-race-patch

Conversation

@meta-space

Copy link
Copy Markdown
Contributor

Summary

I would like to offer a bugfix for a race condition in the WinpkFilterDevice

Motivation

In the Capture loop an incoming Packet might go undetected if is arrives once all packets from the buffer have been processed:

protected override void CaptureLoop(CancellationToken token)
{
	using (ManualResetEvent manualResetEvent = new ManualResetEvent(false))
	{
		WaitHandle[] waitHandles = new WaitHandle[] { token.WaitHandle, manualResetEvent };
		bool success = NativeMethods.SetPacketEvent(DriverHandle, AdapterHandle, manualResetEvent.SafeWaitHandle);
		if (!success)
		{
			throw new PcapException("Can not perform capture");
		}
		while (!token.IsCancellationRequested)
		{
			if (WaitHandle.WaitAny(waitHandles) == 0)
			{
				// We got a cancellation request
				return;
			}
			while (GetNextPacket(out PacketCapture capture) == GetPacketStatus.PacketRead)
			{
				RaiseOnPacketArrival(capture); // forward all queued packets to application
			}
			// race condition HERE: arriving packets won't trigger waitHandles, because manualResetEvent.Reset() immediately resets
			manualResetEvent.Reset();
		}
	}
}

Changes

Simply move the manualResetEvent.Reset(); in from of the while loop.

Testing

Tricky, I did add artifial Sleeps to increase to window of the race condition.
Depending how the HW Filter and Adapter are configured and how "noisy" your network is, the Capture will get unblocked on its own. Ideally you need a completely isolated network segment.

Notes

I'm aware that probably 99.99% of people won't be affected by this defect because most protocols today have retries and recovery mechanisms. We where implementing a proprietary legacy serial protocol over ethernet, which was strictly request/response and were experiencing strange hangs and aborts we did not receive a response.

We since patched and built sharppcap DLL for our application. But then I thought a PR might be welcome upstream

Fixing potential race-condition
@kayoub5
kayoub5 merged commit 667db17 into dotpcap:master Oct 8, 2026
1 of 8 checks passed
@kayoub5

kayoub5 commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

Thanks, merged

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants