Skip to content

Commit

Permalink
Prevent Access Violation inside PacketHandler (#344)
Browse files Browse the repository at this point in the history
  • Loading branch information
kayoub5 authored Nov 4, 2021
1 parent 068cd30 commit d7a5e50
Showing 1 changed file with 29 additions and 5 deletions.
34 changes: 29 additions & 5 deletions SharpPcap/LibPcap/PcapDevice.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ You should have received a copy of the GNU Lesser General Public License
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

namespace SharpPcap.LibPcap
Expand Down Expand Up @@ -279,12 +280,35 @@ public int GetNextPacketPointers(ref IntPtr header, ref IntPtr data)
/// </summary>
protected virtual void PacketHandler(IntPtr param, IntPtr /* pcap_pkthdr* */ header, IntPtr data)
{
unsafe
var handle = Handle;
var gotRef = false;
try
{
var pcapHeader = PcapHeader.FromPointer(header);
var dataSpan = new Span<byte>(data.ToPointer(), (int)pcapHeader.CaptureLength);

SendPacketArrivalEvent(pcapHeader, dataSpan);
// Make sure that handle does not get closed until this function is done
// See https://github.com/chmorgan/sharppcap/issues/343
handle.DangerousAddRef(ref gotRef);
if (!gotRef)
{
return;
}
unsafe
{
var pcapHeader = PcapHeader.FromPointer(header);
var dataSpan = new Span<byte>(data.ToPointer(), (int)pcapHeader.CaptureLength);
SendPacketArrivalEvent(pcapHeader, dataSpan);
}
}
catch (ObjectDisposedException)
{
// If Dispose was called in another thread, DangerousAddRef will throw this
// Ignore
}
finally
{
if (gotRef)
{
handle.DangerousRelease();
}
}
}

Expand Down

0 comments on commit d7a5e50

Please sign in to comment.