From d08fdb8ddc7c88dec82da282f713e6a45e70f0d3 Mon Sep 17 00:00:00 2001 From: seladb Date: Tue, 5 Dec 2023 00:06:04 -0800 Subject: [PATCH] Check `pcap_dispatch` return value (#1252) --- Pcap++/src/PcapLiveDevice.cpp | 37 +++++++++++++++++++++++++++++++---- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/Pcap++/src/PcapLiveDevice.cpp b/Pcap++/src/PcapLiveDevice.cpp index 2ee315112a..c799dc9aea 100644 --- a/Pcap++/src/PcapLiveDevice.cpp +++ b/Pcap++/src/PcapLiveDevice.cpp @@ -176,12 +176,24 @@ void PcapLiveDevice::captureThreadMain() if (m_CaptureCallbackMode) { while (!m_StopThread) - pcap_dispatch(m_PcapDescriptor, -1, onPacketArrives, (uint8_t*)this); + { + if (pcap_dispatch(m_PcapDescriptor, -1, onPacketArrives, reinterpret_cast(this)) == -1) + { + PCPP_LOG_ERROR("pcap_dispatch returned an error: " << pcap_geterr(m_PcapDescriptor)); + m_StopThread = true; + } + } } else { while (!m_StopThread) - pcap_dispatch(m_PcapDescriptor, 100, onPacketArrivesNoCallback, (uint8_t*)this); + { + if (pcap_dispatch(m_PcapDescriptor, 100, onPacketArrivesNoCallback, reinterpret_cast(this)) == -1) + { + PCPP_LOG_ERROR("pcap_dispatch returned an error: " << pcap_geterr(m_PcapDescriptor)); + m_StopThread = true; + } + } } PCPP_LOG_DEBUG("Ended capture thread for device '" << m_Name << "'"); } @@ -496,11 +508,18 @@ int PcapLiveDevice::startCaptureBlockingMode(OnPacketArrivesStopBlocking onPacke m_CaptureThreadStarted = true; m_StopThread = false; + bool pcapDispatchError = false; + if (timeout <= 0) { while (!m_StopThread) { - pcap_dispatch(m_PcapDescriptor, -1, onPacketArrivesBlockingMode, (uint8_t*)this); + if (pcap_dispatch(m_PcapDescriptor, -1, onPacketArrivesBlockingMode, reinterpret_cast(this)) == -1) + { + PCPP_LOG_ERROR("pcap_dispatch returned an error: " << pcap_geterr(m_PcapDescriptor)); + pcapDispatchError = true; + m_StopThread = true; + } } curTimeSec = startTimeSec + timeout; } @@ -509,7 +528,12 @@ int PcapLiveDevice::startCaptureBlockingMode(OnPacketArrivesStopBlocking onPacke while (!m_StopThread && curTimeSec <= (startTimeSec + timeout)) { long curTimeNSec = 0; - pcap_dispatch(m_PcapDescriptor, -1, onPacketArrivesBlockingMode, (uint8_t*)this); + if (pcap_dispatch(m_PcapDescriptor, -1, onPacketArrivesBlockingMode, reinterpret_cast(this)) == -1) + { + PCPP_LOG_ERROR("pcap_dispatch returned an error: " << pcap_geterr(m_PcapDescriptor)); + pcapDispatchError = true; + m_StopThread = true; + } clockGetTime(curTimeSec, curTimeNSec); } } @@ -521,6 +545,11 @@ int PcapLiveDevice::startCaptureBlockingMode(OnPacketArrivesStopBlocking onPacke m_cbOnPacketArrivesBlockingMode = nullptr; m_cbOnPacketArrivesBlockingModeUserCookie = nullptr; + if (pcapDispatchError) + { + return 0; + } + if (curTimeSec > (startTimeSec + timeout)) return -1; return 1;