PcapPlusPlus  Next
PcapLiveDevice.h
Go to the documentation of this file.
1 #pragma once
2 
3 #include <atomic>
4 #include <vector>
5 #include <thread>
6 #include <functional>
7 
8 #include "IpAddress.h"
9 #include "Device.h"
10 #include "PcapDevice.h"
11 
12 // forward declarations for structs and typedefs that are defined in pcap.h
13 struct pcap_if;
14 typedef pcap_if pcap_if_t;
15 struct pcap;
16 typedef pcap pcap_t;
17 struct pcap_pkthdr;
18 
20 
23 namespace pcpp
24 {
25  namespace internal
26  {
30  class PcapHandle
31  {
32  public:
34  constexpr PcapHandle() noexcept = default;
37  explicit PcapHandle(pcap_t* pcapDescriptor) noexcept;
38 
39  PcapHandle(const PcapHandle&) = delete;
40  PcapHandle(PcapHandle&& other) noexcept;
41 
42  PcapHandle& operator=(const PcapHandle&) = delete;
43  PcapHandle& operator=(PcapHandle&& other) noexcept;
44  PcapHandle& operator=(std::nullptr_t) noexcept;
45 
46  ~PcapHandle();
47 
49  bool isValid() const noexcept
50  {
51  return m_PcapDescriptor != nullptr;
52  }
53 
55  pcap_t* get() const noexcept
56  {
57  return m_PcapDescriptor;
58  }
59 
62  pcap_t* release() noexcept;
63 
67  void reset(pcap_t* pcapDescriptor = nullptr) noexcept;
68 
72  char const* getLastError() const noexcept;
73 
80  bool setFilter(std::string const& filter);
81 
84  bool clearFilter();
85 
92  bool getStatistics(PcapStats& stats) const;
93 
95  explicit operator bool() const noexcept
96  {
97  return isValid();
98  }
99 
100  bool operator==(std::nullptr_t) const noexcept
101  {
102  return !isValid();
103  }
104  bool operator!=(std::nullptr_t) const noexcept
105  {
106  return isValid();
107  }
108 
109  private:
110  pcap_t* m_PcapDescriptor = nullptr;
111  };
112  } // namespace internal
113 
114  class PcapLiveDevice;
115 
120  using OnPacketArrivesCallback = std::function<void(RawPacket*, PcapLiveDevice*, void*)>;
121 
127  using OnPacketArrivesStopBlocking = std::function<bool(RawPacket*, PcapLiveDevice*, void*)>;
128 
133  using OnStatsUpdateCallback = std::function<void(PcapStats&, void*)>;
134 
157  {
158  friend class PcapLiveDeviceList;
159 
160  protected:
164  {
165  explicit DeviceInterfaceDetails(pcap_if_t* pInterface);
167  std::string name;
169  std::string description;
171  std::vector<IPAddress> addresses;
174  };
175 
176  bool m_DeviceOpened = false;
177  internal::PcapHandle m_PcapDescriptor;
178 
179  // This is a second descriptor for the same device. It is needed because of a bug
180  // that occurs in libpcap on Linux (on Windows using WinPcap/Npcap it works well):
181  // It's impossible to capture packets sent by the same descriptor
182  pcap_t* m_PcapSendDescriptor;
183  int m_PcapSelectableFd;
184  DeviceInterfaceDetails m_InterfaceDetails;
185  // NOTE@Dimi: Possibly pull mtu, mac address and default gateway in the interface details.
186  // They only appear to be set in the constructor and not modified afterwards.
187  uint32_t m_DeviceMtu;
188  MacAddress m_MacAddress;
189  IPv4Address m_DefaultGateway;
190  std::thread m_CaptureThread;
191  std::thread m_StatsThread;
192 
193  // Should be set to true by the Caller for the Callee
194  std::atomic<bool> m_StopThread;
195  // Should be set to true by the Callee for the Caller
196  std::atomic<bool> m_CaptureThreadStarted;
197 
198  LinkLayerType m_LinkType;
199  bool m_UsePoll;
200 
201  // c'tor is not public, there should be only one for every interface (created by PcapLiveDeviceList)
202  PcapLiveDevice(pcap_if_t* pInterface, bool calculateMTU, bool calculateMacAddress, bool calculateDefaultGateway)
203  : PcapLiveDevice(DeviceInterfaceDetails(pInterface), calculateMTU, calculateMacAddress,
204  calculateDefaultGateway)
205  {}
206  PcapLiveDevice(DeviceInterfaceDetails interfaceDetails, bool calculateMTU, bool calculateMacAddress,
207  bool calculateDefaultGateway);
208 
209  void setDeviceMtu();
210  void setDeviceMacAddress();
211  void setDefaultGateway();
212 
213  public:
216  {
223  };
224 
227  {
229  Normal = 0,
231  Promiscuous = 1
232  };
233 
237  {
243  PCPP_OUT
244  };
245 
248  enum class TimestampProvider
249  {
251  Host = 0,
257  Adapter,
262  };
263 
267  {
269  Microseconds = 0,
271  Nanoseconds,
272  };
273 
278  {
281 
286 
294 
298 
305 
308  unsigned int nflogGroup;
309 
311  bool usePoll;
312 
316 
320 
343  int snapshotLength = 0, unsigned int nflogGroup = 0, bool usePoll = false,
346  {
347  this->mode = mode;
348  this->packetBufferTimeoutMs = packetBufferTimeoutMs;
349  this->packetBufferSize = packetBufferSize;
350  this->direction = direction;
351  this->snapshotLength = snapshotLength;
352  this->nflogGroup = nflogGroup;
353  this->usePoll = usePoll;
354  this->timestampProvider = timestampProvider;
355  this->timestampPrecision = timestampPrecision;
356  }
357  };
358 
359  PcapLiveDevice(const PcapLiveDevice& other) = delete;
360  PcapLiveDevice& operator=(const PcapLiveDevice& other) = delete;
362  ~PcapLiveDevice() override;
363 
366  {
367  return LibPcapDevice;
368  }
369 
371  std::string getName() const
372  {
373  return m_InterfaceDetails.name;
374  }
375 
378  std::string getDesc() const
379  {
380  return m_InterfaceDetails.description;
381  }
382 
384  bool getLoopback() const
385  {
386  return m_InterfaceDetails.isLoopback;
387  }
388 
390  virtual uint32_t getMtu() const
391  {
392  return m_DeviceMtu;
393  }
394 
396  virtual LinkLayerType getLinkType() const
397  {
398  return m_LinkType;
399  }
400 
402  std::vector<IPAddress> getIPAddresses() const
403  {
404  return m_InterfaceDetails.addresses;
405  }
406 
408  virtual MacAddress getMacAddress() const
409  {
410  return m_MacAddress;
411  }
412 
417 
422 
427 
432  const std::vector<IPv4Address>& getDnsServers() const;
433 
437  static std::string getPcapLibVersionInfo();
438 
454  virtual bool startCapture(OnPacketArrivesCallback onPacketArrives, void* onPacketArrivesUserCookie);
455 
479  virtual bool startCapture(OnPacketArrivesCallback onPacketArrives, void* onPacketArrivesUserCookie,
480  int intervalInSecondsToUpdateStats, OnStatsUpdateCallback onStatsUpdate,
481  void* onStatsUpdateUserCookie);
482 
500  virtual bool startCapture(int intervalInSecondsToUpdateStats, OnStatsUpdateCallback onStatsUpdate,
501  void* onStatsUpdateUserCookie);
502 
517  virtual bool startCapture(RawPacketVector& capturedPacketsVector);
518 
543  virtual int startCaptureBlockingMode(OnPacketArrivesStopBlocking onPacketArrives, void* userCookie,
544  const double timeout);
545 
549  void stopCapture();
550 
554 
558  bool doMtuCheck(int packetPayloadLength) const;
559 
573  PCPP_DEPRECATED("This method is deprecated. Use sendPacket(Packet const& packet, bool checkMtu) instead")
574  bool sendPacket(Packet* packet, bool checkMtu = true)
575  {
576  return sendPacket(*packet, checkMtu);
577  }
578 
591  bool sendPacket(Packet const& packet, bool checkMtu = true);
592 
605  bool sendPacket(RawPacket const& rawPacket, bool checkMtu = false);
606 
622  bool sendPacket(const uint8_t* packetData, int packetDataLength, int packetPayloadLength);
623 
639  bool sendPacket(const uint8_t* packetData, int packetDataLength, bool checkMtu = false,
641 
654  virtual int sendPackets(RawPacket* rawPacketsArr, int arrLength, bool checkMtu = false);
655 
668  virtual int sendPackets(Packet** packetsArr, int arrLength, bool checkMtu = true);
669 
681  virtual int sendPackets(const RawPacketVector& rawPackets, bool checkMtu = false);
682 
683  // implement abstract methods
684 
691  bool open() override;
692 
698  bool open(const DeviceConfiguration& config);
699 
700  void close() override;
701 
702  bool isOpened() const override
703  {
704  return m_DeviceOpened;
705  }
706 
709  virtual PcapLiveDevice* clone() const;
710 
711  void getStatistics(PcapStats& stats) const override;
712 
719  PCPP_DEPRECATED("Prefer GeneralFilter::matches(...) method directly.")
720  static bool matchPacketWithFilter(GeneralFilter& filter, RawPacket* rawPacket);
721 
722  protected:
730  virtual void prepareCapture(bool asyncCapture, bool captureStats)
731  {}
732 
733  internal::PcapHandle doOpen(const DeviceConfiguration& config);
734 
738  bool isPayloadWithinMtu(size_t payloadLength) const;
739 
752  bool isPayloadWithinMtu(Packet const& packet, bool allowUnknownLength = false,
753  size_t* outPayloadLength = nullptr) const;
754 
767  bool isPayloadWithinMtu(RawPacket const& rawPacket, bool allowUnknownLength = false,
768  size_t* outPayloadLength = nullptr) const;
769 
784  bool isPayloadWithinMtu(uint8_t const* packetData, size_t packetLen,
785  LinkLayerType linkType = pcpp::LINKTYPE_ETHERNET, bool allowUnknownLength = false,
786  size_t* outPayloadLength = nullptr) const;
787 
788  // Sends a packet directly to the network.
789  bool sendPacketUnchecked(uint8_t const* packetData, int packetDataLength);
790  bool sendPacketUnchecked(RawPacket const& rawPacket)
791  {
792  return sendPacketUnchecked(rawPacket.getRawData(), rawPacket.getRawDataLen());
793  }
794 
795  private:
796  bool isNflogDevice() const;
797 
798  bool doUpdateFilter(std::string const* filterAsString) override;
799  };
800 } // namespace pcpp
Definition: PcapFilter.h:158
Definition: Device.h:44
An interface for providing Pcap-based device statistics.
Definition: PcapDevice.h:25
Definition: IpAddress.h:30
Definition: IpAddress.h:165
Definition: MacAddress.h:24
Definition: Packet.h:48
Definition: PcapLiveDevice.h:157
PcapDirection
Definition: PcapLiveDevice.h:237
@ PCPP_IN
Only capture incoming traffics.
Definition: PcapLiveDevice.h:241
@ PCPP_OUT
Only capture outgoing traffics.
Definition: PcapLiveDevice.h:243
@ PCPP_INOUT
Capture traffics both incoming and outgoing.
Definition: PcapLiveDevice.h:239
void close() override
Close the device.
LiveDeviceType
The type of the live device.
Definition: PcapLiveDevice.h:216
@ WinPcapDevice
WinPcap/Npcap live device.
Definition: PcapLiveDevice.h:220
@ RemoteDevice
WinPcap/Npcap Remote Capture device.
Definition: PcapLiveDevice.h:222
@ LibPcapDevice
libPcap live device
Definition: PcapLiveDevice.h:218
virtual int startCaptureBlockingMode(OnPacketArrivesStopBlocking onPacketArrives, void *userCookie, const double timeout)
DeviceMode
Device capturing mode.
Definition: PcapLiveDevice.h:227
@ Normal
Only packets that their destination is this NIC are captured.
Definition: PcapLiveDevice.h:229
@ Promiscuous
All packets that arrive to the NIC are captured, even packets that their destination isn't this NIC.
Definition: PcapLiveDevice.h:231
virtual bool startCapture(int intervalInSecondsToUpdateStats, OnStatsUpdateCallback onStatsUpdate, void *onStatsUpdateUserCookie)
bool sendPacket(RawPacket const &rawPacket, bool checkMtu=false)
virtual uint32_t getMtu() const
Definition: PcapLiveDevice.h:390
virtual bool startCapture(OnPacketArrivesCallback onPacketArrives, void *onPacketArrivesUserCookie)
bool open(const DeviceConfiguration &config)
bool doMtuCheck(int packetPayloadLength) const
virtual MacAddress getMacAddress() const
Definition: PcapLiveDevice.h:408
bool sendPacket(const uint8_t *packetData, int packetDataLength, int packetPayloadLength)
IPv4Address getDefaultGateway() const
std::string getDesc() const
Definition: PcapLiveDevice.h:378
bool sendPacket(const uint8_t *packetData, int packetDataLength, bool checkMtu=false, pcpp::LinkLayerType linkType=pcpp::LINKTYPE_ETHERNET)
const std::vector< IPv4Address > & getDnsServers() const
void getStatistics(PcapStats &stats) const override
virtual int sendPackets(Packet **packetsArr, int arrLength, bool checkMtu=true)
bool isPayloadWithinMtu(size_t payloadLength) const
Checks whether the packetPayloadLength is smaller or equal than the device MTU.
static bool matchPacketWithFilter(GeneralFilter &filter, RawPacket *rawPacket)
virtual LiveDeviceType getDeviceType() const
Definition: PcapLiveDevice.h:365
virtual bool startCapture(OnPacketArrivesCallback onPacketArrives, void *onPacketArrivesUserCookie, int intervalInSecondsToUpdateStats, OnStatsUpdateCallback onStatsUpdate, void *onStatsUpdateUserCookie)
TimestampPrecision
Definition: PcapLiveDevice.h:267
@ Microseconds
use timestamps with microsecond precision, default
@ Nanoseconds
use timestamps with nanosecond precision
IPv6Address getIPv6Address() const
virtual bool startCapture(RawPacketVector &capturedPacketsVector)
~PcapLiveDevice() override
A destructor for this class.
bool sendPacket(Packet const &packet, bool checkMtu=true)
std::string getName() const
Definition: PcapLiveDevice.h:371
bool isPayloadWithinMtu(uint8_t const *packetData, size_t packetLen, LinkLayerType linkType=pcpp::LINKTYPE_ETHERNET, bool allowUnknownLength=false, size_t *outPayloadLength=nullptr) const
Checks whether the payload length of a packet's raw data is smaller or equal than the device MTU.
IPv4Address getIPv4Address() const
bool sendPacket(Packet *packet, bool checkMtu=true)
Definition: PcapLiveDevice.h:574
virtual int sendPackets(const RawPacketVector &rawPackets, bool checkMtu=false)
virtual int sendPackets(RawPacket *rawPacketsArr, int arrLength, bool checkMtu=false)
static std::string getPcapLibVersionInfo()
bool isPayloadWithinMtu(Packet const &packet, bool allowUnknownLength=false, size_t *outPayloadLength=nullptr) const
Checks whether the packet's payload length is smaller or equal than the device MTU.
virtual LinkLayerType getLinkType() const
Definition: PcapLiveDevice.h:396
bool isOpened() const override
Definition: PcapLiveDevice.h:702
TimestampProvider
Definition: PcapLiveDevice.h:249
@ AdapterUnsynced
device-provided, not synced with the system clock
@ HostLowPrecision
host-provided, low precision, synced with the system clock
@ Adapter
device-provided, synced with the system clock
@ HostHighPrecision
host-provided, high precision, synced with the system clock
@ Host
host-provided, unknown characteristics, default
@ HostHighPrecisionUnsynced
host-provided, high precision, not synced with the system clock
bool getLoopback() const
Definition: PcapLiveDevice.h:384
virtual PcapLiveDevice * clone() const
bool isPayloadWithinMtu(RawPacket const &rawPacket, bool allowUnknownLength=false, size_t *outPayloadLength=nullptr) const
Checks whether the payload length of a RawPacket is smaller or equal than the device MTU.
bool open() override
std::vector< IPAddress > getIPAddresses() const
Definition: PcapLiveDevice.h:402
virtual void prepareCapture(bool asyncCapture, bool captureStats)
Called before starting a capture to prepare the device for capturing packets.
Definition: PcapLiveDevice.h:730
Definition: PcapLiveDeviceList.h:22
Definition: PointerVector.h:50
Definition: RawPacket.h:261
const uint8_t * getRawData() const
Definition: RawPacket.h:426
int getRawDataLen() const
Definition: RawPacket.h:445
A wrapper class for pcap_t* which is the libpcap packet capture descriptor. This class is used to man...
Definition: PcapLiveDevice.h:31
pcap_t * release() noexcept
Releases ownership of the handle and returns the pcap descriptor.
char const * getLastError() const noexcept
Helper function to retrieve a view of the last error string for this handle.
bool setFilter(std::string const &filter)
Sets a filter on the handle. Only packets that match the filter will be captured by the handle.
void reset(pcap_t *pcapDescriptor=nullptr) noexcept
Replaces the managed handle with the provided one.
bool clearFilter()
Clears the filter currently set on the handle.
constexpr PcapHandle() noexcept=default
Creates an empty handle.
bool getStatistics(PcapStats &stats) const
Retrieves statistics from the pcap handle.
pcap_t * get() const noexcept
Definition: PcapLiveDevice.h:55
bool isValid() const noexcept
Definition: PcapLiveDevice.h:49
The main namespace for the PcapPlusPlus lib.
Definition: AssertionUtils.h:19
std::function< void(PcapStats &, void *)> OnStatsUpdateCallback
Definition: PcapLiveDevice.h:133
std::function< bool(RawPacket *, PcapLiveDevice *, void *)> OnPacketArrivesStopBlocking
Definition: PcapLiveDevice.h:127
std::function< void(RawPacket *, PcapLiveDevice *, void *)> OnPacketArrivesCallback
Definition: PcapLiveDevice.h:120
LinkLayerType
An enum describing all known link layer type. Taken from: http://www.tcpdump.org/linktypes....
Definition: RawPacket.h:22
@ LINKTYPE_ETHERNET
IEEE 802.3 Ethernet.
Definition: RawPacket.h:26
Definition: PcapLiveDevice.h:278
int packetBufferTimeoutMs
Definition: PcapLiveDevice.h:285
int snapshotLength
Definition: PcapLiveDevice.h:304
TimestampProvider timestampProvider
Definition: PcapLiveDevice.h:315
DeviceConfiguration(DeviceMode mode=Promiscuous, int packetBufferTimeoutMs=0, int packetBufferSize=0, PcapDirection direction=PCPP_INOUT, int snapshotLength=0, unsigned int nflogGroup=0, bool usePoll=false, TimestampProvider timestampProvider=TimestampProvider::Host, TimestampPrecision timestampPrecision=TimestampPrecision::Microseconds)
Definition: PcapLiveDevice.h:341
bool usePoll
In Unix-like system, use poll() for blocking mode.
Definition: PcapLiveDevice.h:311
int packetBufferSize
Definition: PcapLiveDevice.h:293
unsigned int nflogGroup
Definition: PcapLiveDevice.h:308
PcapDirection direction
Definition: PcapLiveDevice.h:297
TimestampPrecision timestampPrecision
Definition: PcapLiveDevice.h:319
DeviceMode mode
Indicates whether to open the device in promiscuous or normal mode.
Definition: PcapLiveDevice.h:280
A struct that contains all details of a network interface.
Definition: PcapLiveDevice.h:164
std::string description
Description of the device.
Definition: PcapLiveDevice.h:169
std::string name
Name of the device.
Definition: PcapLiveDevice.h:167
std::vector< IPAddress > addresses
IP addresses associated with the device.
Definition: PcapLiveDevice.h:171
bool isLoopback
Flag to indicate if the device is a loopback device.
Definition: PcapLiveDevice.h:173
Definition: PcapDevice.h:14