-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathpcapcapturethread.cpp
More file actions
243 lines (209 loc) · 6.63 KB
/
pcapcapturethread.cpp
File metadata and controls
243 lines (209 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
/*
* WhatPulse External PCap Service - PCap Capture Thread Implementation
*
* Copyright (c) 2025 WhatPulse. All rights reserved.
*
* Licensed under CC BY-NC 4.0 with additional terms.
* See LICENSE file for complete terms and conditions.
*
* NOTICE: This software integrates with WhatPulse services. Reverse engineering
* the communication protocol or tampering with data transmission is prohibited.
*
* For licensing questions: support@whatpulse.org
*/
#include "pcapcapturethread.h"
#include "packethandler.h"
#include "logger.h"
#include <iostream>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <chrono>
#include <net/ethernet.h>
#include <netinet/ip.h>
#include <netinet/ip6.h>
#include <unistd.h>
// Protocol constants
#define ETHERTYPE_IP 0x0800
#define ETHERTYPE_IPV6 0x86dd
// Performance optimization constants (matching built-in PCap monitor)
#define DEFAULT_SNAPLEN 9000
PcapCaptureThread::PcapCaptureThread(const std::string &interface, bool verbose, IPacketHandler *handler) :
m_interface(interface), m_verbose(verbose), m_capturing(false), m_shouldStop(false),
m_pcapHandle(nullptr), m_handler(handler)
{
}
PcapCaptureThread::~PcapCaptureThread()
{
stop();
join();
}
void PcapCaptureThread::start()
{
m_thread = std::make_unique<std::thread>(&PcapCaptureThread::run, this);
}
void PcapCaptureThread::stop()
{
m_shouldStop.store(true);
std::lock_guard<std::mutex> lock(m_mutex);
if (m_pcapHandle)
{
pcap_breakloop(m_pcapHandle);
}
}
void PcapCaptureThread::join()
{
if (m_thread && m_thread->joinable())
{
m_thread->join();
}
}
void PcapCaptureThread::run()
{
char errbuf[PCAP_ERRBUF_SIZE];
LOG_INFO("Starting capture on interface: " + m_interface);
// Open pcap handle
m_pcapHandle = pcap_open_live(m_interface.c_str(),
DEFAULT_SNAPLEN, // optimized snap length
1, // promiscuous mode
1, // timeout (ms) - reduced for better performance
errbuf);
if (!m_pcapHandle)
{
LOG_ERROR("Unable to open interface " + m_interface + ": " + std::string(errbuf));
return;
}
// Set filter to capture only TCP and UDP traffic
struct bpf_program filter;
if (pcap_compile(m_pcapHandle, &filter, "tcp or udp", 1, PCAP_NETMASK_UNKNOWN) == -1)
{
LOG_ERROR("Unable to compile filter for interface " + m_interface + ": " + std::string(pcap_geterr(m_pcapHandle)));
pcap_close(m_pcapHandle);
m_pcapHandle = nullptr;
return;
}
if (pcap_setfilter(m_pcapHandle, &filter) == -1)
{
LOG_ERROR("Unable to set filter for interface " + m_interface + ": " + std::string(pcap_geterr(m_pcapHandle)));
pcap_freecode(&filter);
pcap_close(m_pcapHandle);
m_pcapHandle = nullptr;
return;
}
pcap_freecode(&filter);
m_capturing.store(true);
LOG_INFO("Capture started successfully on interface: " + m_interface);
// Start packet capture loop
while (!m_shouldStop.load())
{
int result = pcap_dispatch(m_pcapHandle, 1000, packetHandler, reinterpret_cast<u_char *>(this));
if (result == -1)
{
// Error occurred
if (!m_shouldStop.load())
{
LOG_ERROR("Error in pcap_dispatch for interface " + m_interface + ": " + std::string(pcap_geterr(m_pcapHandle)));
}
break;
}
else if (result == -2)
{
// Loop was broken
break;
}
// No sleep needed with larger batch size - let it run at full speed
}
m_capturing.store(false);
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_pcapHandle)
{
pcap_close(m_pcapHandle);
m_pcapHandle = nullptr;
}
}
LOG_INFO("Capture stopped on interface: " + m_interface);
}
void PcapCaptureThread::packetHandler(u_char *userData, const struct pcap_pkthdr *header, const u_char *packet)
{
PcapCaptureThread *thread = reinterpret_cast<PcapCaptureThread *>(userData);
thread->handlePacket(header, packet);
}
void PcapCaptureThread::handlePacket(const struct pcap_pkthdr *header, const u_char *packet)
{
if (m_shouldStop.load())
{
return;
}
// Basic validation
if (!header || !packet || header->caplen < sizeof(struct ether_header) || header->caplen > 65535)
{
return;
}
// Parse Ethernet header
const struct ether_header *ethHeader = reinterpret_cast<const struct ether_header *>(packet);
uint16_t etherType = ntohs(ethHeader->ether_type);
uint8_t ipVersion = 0;
if (etherType == ETHERTYPE_IP)
{
ipVersion = 4;
}
else if (etherType == ETHERTYPE_IPV6)
{
ipVersion = 6;
}
else
{
// Not IP traffic, ignore
return;
}
// Copy packet data starting from IP header (skip Ethernet header)
const u_char *ipPacket = packet + sizeof(struct ether_header);
uint32_t ipPacketLength = header->caplen - sizeof(struct ether_header);
// Use the original wire length (header->len) minus the Ethernet header for
// accurate byte counting. header->caplen may be less than header->len if
// snaplen truncated the capture, and it incorrectly included the Ethernet
// header size in the old code.
uint16_t ipWireLength = static_cast<uint16_t>(header->len - sizeof(struct ether_header));
// Create packet data structure
PacketData packetData;
packetData.ipVersion = ipVersion;
packetData.dataLength = ipWireLength;
packetData.timestamp = static_cast<uint32_t>(std::chrono::duration_cast<std::chrono::seconds>(
std::chrono::system_clock::now().time_since_epoch())
.count());
packetData.interfaceName = m_interface;
// Bounds checking for vector assignment
if (ipPacketLength > 0 && ipPacketLength <= 65535)
{
try {
packetData.packetData.reserve(ipPacketLength);
packetData.packetData.assign(ipPacket, ipPacket + ipPacketLength);
} catch (const std::exception& e) {
return; // Drop packet on exception
}
}
else
{
return; // Invalid packet length
}
// Debug logging for PCap packets
if (m_verbose && ipPacketLength >= 4)
{
std::stringstream debug;
debug << "PCAP [" << m_interface << "] Captured IPv" << static_cast<int>(ipVersion)
<< " packet - TotalLen: " << header->caplen
<< ", IPLen: " << ipPacketLength
<< ", IPHeader: 0x";
for (size_t i = 0; i < std::min(static_cast<size_t>(4), static_cast<size_t>(ipPacketLength)); i++)
{
debug << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(ipPacket[i]);
}
LOG_DEBUG(debug.str());
}
// Send to handler
if (m_handler)
{
m_handler->onPacketCaptured(packetData);
}
}