Skip to content

Commit d7a5e50

Browse files
authored
Prevent Access Violation inside PacketHandler (#344)
1 parent 068cd30 commit d7a5e50

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

SharpPcap/LibPcap/PcapDevice.cs

+29-5
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ You should have received a copy of the GNU Lesser General Public License
2121
using System;
2222
using System.Collections.Generic;
2323
using System.ComponentModel;
24+
using System.Runtime.CompilerServices;
2425
using System.Runtime.InteropServices;
2526

2627
namespace SharpPcap.LibPcap
@@ -279,12 +280,35 @@ public int GetNextPacketPointers(ref IntPtr header, ref IntPtr data)
279280
/// </summary>
280281
protected virtual void PacketHandler(IntPtr param, IntPtr /* pcap_pkthdr* */ header, IntPtr data)
281282
{
282-
unsafe
283+
var handle = Handle;
284+
var gotRef = false;
285+
try
283286
{
284-
var pcapHeader = PcapHeader.FromPointer(header);
285-
var dataSpan = new Span<byte>(data.ToPointer(), (int)pcapHeader.CaptureLength);
286-
287-
SendPacketArrivalEvent(pcapHeader, dataSpan);
287+
// Make sure that handle does not get closed until this function is done
288+
// See https://github.com/chmorgan/sharppcap/issues/343
289+
handle.DangerousAddRef(ref gotRef);
290+
if (!gotRef)
291+
{
292+
return;
293+
}
294+
unsafe
295+
{
296+
var pcapHeader = PcapHeader.FromPointer(header);
297+
var dataSpan = new Span<byte>(data.ToPointer(), (int)pcapHeader.CaptureLength);
298+
SendPacketArrivalEvent(pcapHeader, dataSpan);
299+
}
300+
}
301+
catch (ObjectDisposedException)
302+
{
303+
// If Dispose was called in another thread, DangerousAddRef will throw this
304+
// Ignore
305+
}
306+
finally
307+
{
308+
if (gotRef)
309+
{
310+
handle.DangerousRelease();
311+
}
288312
}
289313
}
290314

0 commit comments

Comments
 (0)