4d3ba516a717d3e0567def2fb0fe69d8194a5aa7
[darkstat] / cap.c
1 /* darkstat 3
2 * copyright (c) 2001-2009 Emil Mikulic.
3 *
4 * cap.c: interface to libpcap.
5 *
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
8 */
9
10 #include "darkstat.h"
11 #include "cap.h"
12 #include "conv.h"
13 #include "decode.h"
14 #include "hosts_db.h"
15 #include "localip.h"
16
17 #include <sys/ioctl.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/wait.h>
21 #ifdef HAVE_SYS_FILIO_H
22 # include <sys/filio.h> /* Solaris' FIONBIO hides here */
23 #endif
24 #include <assert.h>
25 #include "err.h"
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <unistd.h>
30
31 extern int want_pppoe, want_macs, want_hexdump, want_snaplen;
32
33 /* The cap process life-cycle:
34 *
35 * Init - cap_init()
36 * Fill fd_set - cap_fd_set()
37 * Poll - cap_poll()
38 * Stop - cap_stop()
39 */
40
41 /* Globals - only useful within this module. */
42 static pcap_t *pcap = NULL;
43 static int pcap_fd = -1;
44 static const linkhdr_t *linkhdr = NULL;
45
46 #define CAP_TIMEOUT 500 /* granularity of capture buffer, in milliseconds */
47
48 /* ---------------------------------------------------------------------------
49 * Init pcap. Exits on failure.
50 */
51 void
52 cap_init(const char *device, const char *filter, int promisc)
53 {
54 char errbuf[PCAP_ERRBUF_SIZE], *tmp_device;
55 int linktype, snaplen;
56
57 /* pcap doesn't like device being const */
58 tmp_device = xstrdup(device);
59
60 /* Open packet capture descriptor. */
61 errbuf[0] = '\0'; /* zero length string */
62 pcap = pcap_open_live(
63 tmp_device,
64 1, /* snaplen, irrelevant at this point */
65 0, /* promisc, also irrelevant */
66 CAP_TIMEOUT,
67 errbuf);
68
69 if (pcap == NULL)
70 errx(1, "pcap_open_live(): %s", errbuf);
71
72 /* Work out the linktype and what snaplen we need. */
73 linktype = pcap_datalink(pcap);
74 verbosef("linktype is %d", linktype);
75 if ((linktype == DLT_EN10MB) && want_macs)
76 show_mac_addrs = 1;
77 linkhdr = getlinkhdr(linktype);
78 if (linkhdr == NULL)
79 errx(1, "unknown linktype %d", linktype);
80 if (linkhdr->handler == NULL)
81 errx(1, "no handler for linktype %d", linktype);
82 snaplen = getsnaplen(linkhdr);
83 if (want_pppoe) {
84 snaplen += PPPOE_HDR_LEN;
85 if (linktype != DLT_EN10MB)
86 errx(1, "can't do PPPoE decoding on a non-Ethernet linktype");
87 }
88 verbosef("calculated snaplen minimum %d", snaplen);
89 if (want_snaplen > -1)
90 snaplen = want_snaplen;
91 verbosef("using snaplen %d", snaplen);
92
93 /* Close and re-open pcap to use the new snaplen. */
94 pcap_close(pcap);
95 errbuf[0] = '\0'; /* zero length string */
96 pcap = pcap_open_live(
97 tmp_device,
98 snaplen,
99 promisc,
100 CAP_TIMEOUT,
101 errbuf);
102
103 if (pcap == NULL)
104 errx(1, "pcap_open_live(): %s", errbuf);
105
106 if (errbuf[0] != '\0') /* not zero length anymore -> warning */
107 warnx("pcap_open_live() warning: %s", errbuf);
108
109 free(tmp_device);
110
111 if (promisc)
112 verbosef("capturing in promiscuous mode");
113 else
114 verbosef("capturing in non-promiscuous mode");
115
116 /* Set filter expression, if any. */
117 if (filter != NULL)
118 {
119 struct bpf_program prog;
120 char *tmp_filter = xstrdup(filter);
121 if (pcap_compile(
122 pcap,
123 &prog,
124 tmp_filter,
125 1, /* optimize */
126 0) /* netmask */
127 == -1)
128 errx(1, "pcap_compile(): %s", pcap_geterr(pcap));
129
130 if (pcap_setfilter(pcap, &prog) == -1)
131 errx(1, "pcap_setfilter(): %s", pcap_geterr(pcap));
132
133 pcap_freecode(&prog);
134 free(tmp_filter);
135 }
136
137 pcap_fd = pcap_fileno(pcap);
138
139 /* set non-blocking */
140 #ifdef linux
141 if (pcap_setnonblock(pcap, 1, errbuf) == -1)
142 errx(1, "pcap_setnonblock(): %s", errbuf);
143 #else
144 { int one = 1;
145 if (ioctl(pcap_fd, FIONBIO, &one) == -1)
146 err(1, "ioctl(pcap_fd, FIONBIO)"); }
147 #endif
148
149 #ifdef BIOCSETWF
150 {
151 /* Deny all writes to the socket */
152 struct bpf_insn bpf_wfilter[] = { BPF_STMT(BPF_RET+BPF_K, 0) };
153 int wf_len = sizeof(bpf_wfilter) / sizeof(struct bpf_insn);
154 struct bpf_program pr;
155
156 pr.bf_len = wf_len;
157 pr.bf_insns = bpf_wfilter;
158
159 if (ioctl(pcap_fd, BIOCSETWF, &pr) == -1)
160 err(1, "ioctl(pcap_fd, BIOCSETFW)");
161 verbosef("filtered out BPF writes");
162 }
163 #endif
164
165 #ifdef BIOCLOCK
166 /* set "locked" flag (no reset) */
167 if (ioctl(pcap_fd, BIOCLOCK) == -1)
168 err(1, "ioctl(pcap_fd, BIOCLOCK)");
169 verbosef("locked down BPF for security");
170 #endif
171 }
172
173 /*
174 * Set pcap_fd in the given fd_set.
175 */
176 void
177 cap_fd_set(
178 #ifdef linux
179 fd_set *read_set _unused_,
180 int *max_fd _unused_,
181 struct timeval *timeout,
182 #else
183 fd_set *read_set,
184 int *max_fd,
185 struct timeval *timeout _unused_,
186 #endif
187 int *need_timeout)
188 {
189 assert(*need_timeout == 0); /* we're first to get a shot at this */
190 #ifdef linux
191 /*
192 * Linux's BPF is immediate, so don't select() as it will lead to horrible
193 * performance. Instead, use a timeout for buffering.
194 */
195 *need_timeout = 1;
196 timeout->tv_sec = 0;
197 timeout->tv_usec = CAP_TIMEOUT * 1000; /* msec->usec */
198 #else
199 /* We have a BSD-like BPF, we can select() on it. */
200 FD_SET(pcap_fd, read_set);
201 *max_fd = max(*max_fd, pcap_fd);
202 #endif
203 }
204
205 unsigned int pkts_recv = 0, pkts_drop = 0;
206
207 static void
208 cap_stats_update(void)
209 {
210 struct pcap_stat ps;
211
212 if (pcap_stats(pcap, &ps) != 0) {
213 warnx("pcap_stats(): %s", pcap_geterr(pcap));
214 return;
215 }
216
217 pkts_recv = ps.ps_recv;
218 pkts_drop = ps.ps_drop;
219 }
220
221 /*
222 * Print hexdump of received packet.
223 */
224 static void
225 hexdump(const u_char *buf, const uint32_t len)
226 {
227 uint32_t i, col;
228
229 printf("packet of %u bytes:\n", len);
230 col = 0;
231 for (i=0, col=0; i<len; i++) {
232 if (col == 0) printf(" ");
233 printf("%02x", buf[i]);
234 if (i+1 == linkhdr->hdrlen)
235 printf("[");
236 else if (i+1 == linkhdr->hdrlen + IP_HDR_LEN)
237 printf("]");
238 else printf(" ");
239 col += 3;
240 if (col >= 72) {
241 printf("\n");
242 col = 0;
243 }
244 }
245 if (col != 0) printf("\n");
246 printf("\n");
247 }
248
249 /*
250 * Callback function for pcap_dispatch() which chains to the decoder specified
251 * in linkhdr struct.
252 */
253 static void
254 callback(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
255 {
256 if (want_hexdump) hexdump(bytes, h->caplen);
257 linkhdr->handler(user, h, bytes);
258 }
259
260 /*
261 * Process any packets currently in the capture buffer.
262 */
263 void
264 cap_poll(fd_set *read_set
265 #ifdef linux
266 _unused_
267 #endif
268 )
269 {
270 int total, ret;
271
272 #ifndef linux /* We don't use select() on Linux. */
273 if (!FD_ISSET(pcap_fd, read_set)) {
274 verbosef("cap_poll premature");
275 return;
276 }
277 #endif
278
279 /*
280 * Once per capture poll, check our IP address. It's used in accounting
281 * for traffic graphs.
282 */
283 localip_update(); /* FIXME: this might even be too often */
284
285 total = 0;
286 for (;;) {
287 ret = pcap_dispatch(
288 pcap,
289 -1, /* count, -1 = entire buffer */
290 callback,
291 NULL); /* user */
292
293 if (ret < 0) {
294 warnx("pcap_dispatch(): %s", pcap_geterr(pcap));
295 return;
296 }
297
298 /* Despite count = -1, Linux will only dispatch one packet at a time. */
299 total += ret;
300
301 #ifdef linux
302 /* keep looping until we've dispatched all the outstanding packets */
303 if (ret == 0) break;
304 #else
305 /* we get them all on the first shot */
306 break;
307 #endif
308 }
309 /*FIXME*/if (want_verbose) fprintf(stderr, "%-20d\r", total);
310 cap_stats_update();
311 }
312
313 void
314 cap_stop(void)
315 {
316 pcap_close(pcap);
317 }
318
319 /* Run through entire capfile. */
320 void
321 cap_from_file(const char *capfile, const char *filter)
322 {
323 char errbuf[PCAP_ERRBUF_SIZE];
324 int linktype, ret;
325
326 /* Open packet capture descriptor. */
327 errbuf[0] = '\0'; /* zero length string */
328 pcap = pcap_open_offline(capfile, errbuf);
329
330 if (pcap == NULL)
331 errx(1, "pcap_open_offline(): %s", errbuf);
332
333 if (errbuf[0] != '\0') /* not zero length anymore -> warning */
334 warnx("pcap_open_offline() warning: %s", errbuf);
335
336 /* Work out the linktype. */
337 linktype = pcap_datalink(pcap);
338 linkhdr = getlinkhdr(linktype);
339 if (linkhdr == NULL)
340 errx(1, "unknown linktype %d", linktype);
341 if (linkhdr->handler == NULL)
342 errx(1, "no handler for linktype %d", linktype);
343 if (linktype == DLT_EN10MB) /* FIXME: impossible with capfile? */
344 show_mac_addrs = 1;
345
346 /* Set filter expression, if any. */ /* FIXME: factor! */
347 if (filter != NULL)
348 {
349 struct bpf_program prog;
350 char *tmp_filter = xstrdup(filter);
351 if (pcap_compile(
352 pcap,
353 &prog,
354 tmp_filter,
355 1, /* optimize */
356 0) /* netmask */
357 == -1)
358 errx(1, "pcap_compile(): %s", pcap_geterr(pcap));
359
360 if (pcap_setfilter(pcap, &prog) == -1)
361 errx(1, "pcap_setfilter(): %s", pcap_geterr(pcap));
362
363 pcap_freecode(&prog);
364 free(tmp_filter);
365 }
366
367 /* Process file. */
368 ret = pcap_dispatch(
369 pcap,
370 -1, /* count, -1 = entire buffer */
371 callback,
372 NULL); /* user */
373
374 if (ret < 0)
375 errx(1, "pcap_dispatch(): %s", pcap_geterr(pcap));
376 }
377
378 /* vim:set ts=3 sw=3 tw=78 expandtab: */