Debian Codegraph @

protolib/src/unix/bpfCap.cpp

raw
1 /**
2 * @file bpfCap.cpp
3 * @brief ProtoCap class using Berkely Packet Filter (bpf) for packet capture.
4 */
5
6 /**
7 *
8 * @class BpfCap
9 *
10 * @brief This is an implementation of the Protolib class ProtoCap
11 * using the Berkeley Packet Filter (bpf) for packet capture
12 *
13 */
14
15 #include "protoCap.h" // for ProtoCap definition
16 #include "protoSocket.h"
17 #include "protoDebug.h"
18
19
20 #include <sys/types.h>
21 #include <sys/time.h>
22 #include <sys/ioctl.h>
23 #include <net/bpf.h>
24 #include <sys/socket.h>
25 #include <net/if.h>
26 #include <stdio.h> // for snprintf()
27 #include <fcntl.h> // for open()
28 #include <unistd.h> // for close()
29
30 // NOTE: On MacOSX (Darwin), we may want to use a PF_NDRV socket instead ???
31
32 class BpfCap : public ProtoCap
33 {
34 public:
35 BpfCap();
36 ~BpfCap();
37
38 bool Open(const char* interfaceName = NULL);
39 void Close();
40 bool Send(const char* buffer, unsigned int& numBytes);
41 bool Recv(char* buffer, unsigned int& numBytes, Direction* direction = NULL);
42
43 private:
44 char* bpf_buffer;
45 unsigned int bpf_buflen;
46 unsigned int bpf_captured;
47 unsigned int bpf_index;
48 }; // end class BpfCap
49
50
51 ProtoCap* ProtoCap::Create()
52 {
53 return (static_cast<ProtoCap*>(new BpfCap));
54 }
55 /**
56 * @brief Enables input notification by default.
57 *
58 */
59 BpfCap::BpfCap()
60 : bpf_buffer(NULL), bpf_buflen(0), bpf_captured(0), bpf_index(0)
61 {
62 StartInputNotification(); // enable input notification by default
63 }
64
65 BpfCap::~BpfCap()
66 {
67 Close();
68 }
69 /**
70 * @brief Associates a bpf filter with an interface.
71 *
72 * Associates a Berkely Packet Filter with the specified interface or it not provded, the
73 * default local interface will be used. Enables immediate packet by packet notification.
74 *
75 * @param interfaceName
76 * @return success or failure indicator
77 */
78
79 bool BpfCap::Open(const char* interfaceName)
80 {
81 char buffer[256];
82 if (NULL == interfaceName)
83 {
84 // Try to determine a "default" interface
85 ProtoAddress localAddress;
86 if (!localAddress.ResolveLocalAddress())
87 {
88 PLOG(PL_ERROR, "BpfCap::Open() error: couldn't auto determine local interface\n");
89 return false;
90 }
91 if (!ProtoSocket::GetInterfaceName(localAddress, buffer, 256))
92 {
93 PLOG(PL_ERROR, "BpfCap::Open() error: couldn't determine local interface name\n");
94 return false;
95 }
96 interfaceName = buffer;
97 }
98
99 ProtoAddress macAddr;
100 if (!ProtoSocket::GetInterfaceAddress(interfaceName, ProtoAddress::ETH, if_addr))
101 PLOG(PL_ERROR, "BpfCap::Open() warning: unable to get MAC address for interface \"%s\"\n", interfaceName);
102
103 int ifIndex = ProtoSocket::GetInterfaceIndex(interfaceName);
104
105 int i = 0;
106 int fd = -1;
107 do
108 {
109 char bpfName[256];
110 bpfName[255] = '\0';
111 snprintf(bpfName, 255, "/dev/bpf%d", i++);
112 fd = open(bpfName, O_RDWR);
113 } while ((fd < 0) && (EBUSY == errno));
114
115 if (fd < 0)
116 {
117 PLOG(PL_ERROR, "BpfCap::Open() all bpf devices busy\n");
118 return false;
119 }
120
121 // Check the BPF version
122 struct bpf_version bpfVersion;
123 if (ioctl(fd, BIOCVERSION, (caddr_t)&bpfVersion) < 0)
124 {
125 PLOG(PL_ERROR, "BpfCap::Open() ioctl(BIOCVERSION) error: %s\n",
126 GetErrorString());
127 close(fd);
128 return false;
129 }
130 if (bpfVersion.bv_major != BPF_MAJOR_VERSION ||
131 bpfVersion.bv_minor < BPF_MINOR_VERSION)
132 {
133 PLOG(PL_ERROR, "BpfCap::Open() kernel bpf version out of date\n");
134 close(fd);
135 return false;
136 }
137 // Set which interface we interested in, and buffer size
138 unsigned int buflen;
139 if ((ioctl(fd, BIOCGBLEN, (caddr_t)&buflen) < 0) || buflen < 32768)
140 buflen = 32768;
141
142 for ( ; buflen != 0; buflen >>= 1)
143 {
144 ioctl(fd, BIOCSBLEN, (caddr_t)&buflen);
145 struct ifreq ifr;
146 strncpy(ifr.ifr_name, interfaceName, sizeof(ifr.ifr_name));
147 if (ioctl(fd, BIOCSETIF, (caddr_t)&ifr) >= 0)
148 break;
149 if (errno != ENOBUFS)
150 {
151 PLOG(PL_ERROR, "BpfCap::Open() ioctl(BIOCSETIF) error: %s\n",
152 GetErrorString());
153 close(fd);
154 return false;
155 }
156 }
157
158 if (0 == buflen)
159 {
160 PLOG(PL_ERROR, "BpfCap::Open() unable to set bpf buffer\n");
161 close(fd);
162 return false;
163 }
164 // Set interface to promiscuous mode
165 // (TBD) Allow it to open in non-promiscuous mode???
166 if (ioctl(fd, BIOCPROMISC, NULL) < 0)
167 {
168 PLOG(PL_ERROR, "BpfCap::Open() ioctl(BIOCPROMISC) error: %s\n",
169 GetErrorString());
170 close(fd);
171 return false;
172 }
173
174 // For protolib purposes we generally want immediate
175 // packet-by-packet notification
176 unsigned int enable = 1;
177 if (ioctl(fd, BIOCIMMEDIATE, &enable) < 0)
178 {
179 PLOG(PL_ERROR, "BpfCap::Open() ioctl(BIOCIMMEDIATE) error: %s\n",
180 GetErrorString());
181 close(fd);
182 return false;
183 }
184
185 // Set it to non-blocking, too
186 int flags = fcntl(fd, F_GETFL, 0);
187 if (-1 == flags)
188 {
189 PLOG(PL_ERROR, "BpfCap::Open() fcnt(F_GETFL) error: %s\n",
190 GetErrorString());
191 close(fd);
192 return false;
193 }
194 flags |= O_NONBLOCK;
195 if (-1 == fcntl(fd, F_SETFL, flags))
196 {
197 PLOG(PL_ERROR, "BpfCap::Open() fcnt(F_SETFL O_NONBLOCK) error: %s\n",
198 GetErrorString());
199 close(fd);
200 return false;
201 }
202
203 if (ioctl(fd, BIOCGBLEN, (caddr_t)&buflen) < 0)
204 {
205 PLOG(PL_ERROR, "BpfCap::Open() ioctl(BIOCGBLEN) error: %s\n",
206 GetErrorString());
207 close(fd);
208 return false;
209 }
210
211 Close(); // just in case
212
213 // Allocate buffer for reading available packets
214 if (NULL == (bpf_buffer = new char[buflen]))
215 {
216 PLOG(PL_ERROR, "BpfCap::Open() new bp_buffer error: %s\n",
217 GetErrorString());
218 Close();
219 return false;
220 }
221 bpf_buflen = buflen;
222 descriptor = fd;
223
224 if (!ProtoCap::Open(interfaceName))
225 {
226 PLOG(PL_ERROR, "BpfCap::Open() ProtoCap::Open() error\n");
227 Close();
228 return false;
229 }
230 if_index = ifIndex;
231 return true;
232 } // end BpfCap::Open()
233
234 void BpfCap::Close()
235 {
236 if (NULL != bpf_buffer)
237 {
238 delete[] bpf_buffer;
239 bpf_buffer = NULL;
240 bpf_buflen = 0;
241 }
242 ProtoCap::Close();
243 if (INVALID_HANDLE != descriptor)
244 {
245 close(descriptor);
246 descriptor = INVALID_HANDLE;
247 }
248 } // end BpfCap::Close()
249
250
251 /**
252 * @brief Recv's the packet into buffer.
253 *
254 * @param buffer
255 * @param numBytes
256 * @param direction
257 *
258 * @return success or failure indicator
259 */
260
261 bool BpfCap::Recv(char* buffer, unsigned int& numBytes, Direction* direction)
262 {
263 if (NULL != direction) *direction = INBOUND;
264 if (bpf_index >= bpf_captured)
265 {
266 for (;;)
267 {
268 ssize_t result = read(descriptor, bpf_buffer, bpf_buflen);
269 if (result < 0)
270 {
271 switch (errno)
272 {
273 case EINTR:
274 continue; // try again
275 case EWOULDBLOCK:
276 numBytes = 0;
277 return true;
278 default:
279 PLOG(PL_ERROR, "BpfCap::Recv() read() error: %s\n",
280 GetErrorString());
281 numBytes = 0;
282 return false;
283 }
284 }
285 else
286 {
287 bpf_captured = result;
288 bpf_index = 0;
289 break;
290 }
291 }
292 }
293
294 // Determine next packet (if applicable)
295 if (bpf_captured > bpf_index)
296 {
297 // The (void*) cast here avoids alignment warnings from the compiler
298 struct bpf_hdr* bpfHdr = (struct bpf_hdr*)((void*)(bpf_buffer + bpf_index));
299 if (numBytes >= bpfHdr->bh_caplen)
300 {
301 memcpy(buffer, bpf_buffer+bpf_index+bpfHdr->bh_hdrlen, bpfHdr->bh_caplen);
302 numBytes = bpfHdr->bh_caplen;
303 bpf_index += BPF_WORDALIGN(bpfHdr->bh_caplen + bpfHdr->bh_hdrlen);
304 }
305 else
306 {
307 PLOG(PL_ERROR, "BpfCap::Recv() error packet too big for buffer\n");
308 return false;
309 }
310 }
311 else
312 {
313 numBytes = 0;
314 }
315 // TBD - make sure this doesn't screw up inbound multicast/broadcast traffic
316 if ((NULL != direction) && (0 == memcmp(if_addr.GetRawHostAddress(), buffer+6, 6)))
317 *direction = OUTBOUND;
318 return true;
319 } // end BpfCap::Recv()
320
321 /**
322 * @brief Write packet to the bpf descriptor.
323 *
324 * 802.3 frames are not supported
325 *
326 * @param buffer
327 * @param buflen
328 *
329 * @return success or failure indicator
330 */
331
332 bool BpfCap::Send(const char* buffer, unsigned int& numBytes)
333 {
334 // Make sure packet is a type that is OK for us to send
335 // (Some packets seem to cause a PF_PACKET socket trouble)
336 UINT16 type;
337 memcpy(&type, buffer+12, 2);
338 type = ntohs(type);
339 if (type <= 0x05dc) // assume it's 802.3 Length and ignore
340 {
341 PLOG(PL_ERROR, "BpfCap::Send() unsupported 802.3 frame (len = %04x)\n", type);
342 return false;
343 }
344 for (;;)
345 {
346 ssize_t result = write(descriptor, buffer, numBytes);
347 if (result < 0)
348 {
349 switch (errno)
350 {
351 case EINTR:
352 continue; // try again
353 case EWOULDBLOCK:
354 numBytes = 0;
355 case ENOBUFS:
356 // because this doesn't block write()
357 default:
358 PLOG(PL_ERROR, "BpfCap::Send() error: %s", GetErrorString());
359 break;
360 }
361 return false;
362 }
363 else
364 {
365 ASSERT(result == (ssize_t)numBytes);
366 break;
367 }
368 }
369 return true;
370 } // end BpfCap::Send()