Implement --hexdump
[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;
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, caplen;
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 caplen it needs. */
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 caplen = getcaplen(linkhdr);
83 if (want_pppoe) {
84 caplen += PPPOE_HDR_LEN;
85 if (linktype != DLT_EN10MB)
86 errx(1, "can't do PPPoE decoding on a non-Ethernet linktype");
87 }
88 verbosef("caplen is %d", caplen);
89
90 /* Close and re-open pcap to use the new caplen. */
91 pcap_close(pcap);
92 errbuf[0] = '\0'; /* zero length string */
93 pcap = pcap_open_live(
94 tmp_device,
95 caplen,
96 promisc,
97 CAP_TIMEOUT,
98 errbuf);
99
100 if (pcap == NULL)
101 errx(1, "pcap_open_live(): %s", errbuf);
102
103 if (errbuf[0] != '\0') /* not zero length anymore -> warning */
104 warnx("pcap_open_live() warning: %s", errbuf);
105
106 free(tmp_device);
107
108 if (promisc)
109 verbosef("capturing in promiscuous mode");
110 else
111 verbosef("capturing in non-promiscuous mode");
112
113 /* Set filter expression, if any. */
114 if (filter != NULL)
115 {
116 struct bpf_program prog;
117 char *tmp_filter = xstrdup(filter);
118 if (pcap_compile(
119 pcap,
120 &prog,
121 tmp_filter,
122 1, /* optimize */
123 0) /* netmask */
124 == -1)
125 errx(1, "pcap_compile(): %s", pcap_geterr(pcap));
126
127 if (pcap_setfilter(pcap, &prog) == -1)
128 errx(1, "pcap_setfilter(): %s", pcap_geterr(pcap));
129
130 pcap_freecode(&prog);
131 free(tmp_filter);
132 }
133
134 pcap_fd = pcap_fileno(pcap);
135
136 /* set non-blocking */
137 { int one = 1;
138 if (ioctl(pcap_fd, FIONBIO, &one) == -1)
139 err(1, "ioctl(pcap_fd, FIONBIO)"); }
140
141 #ifdef BIOCSETWF
142 {
143 /* Deny all writes to the socket */
144 struct bpf_insn bpf_wfilter[] = { BPF_STMT(BPF_RET+BPF_K, 0) };
145 int wf_len = sizeof(bpf_wfilter) / sizeof(struct bpf_insn);
146 struct bpf_program pr;
147
148 pr.bf_len = wf_len;
149 pr.bf_insns = bpf_wfilter;
150
151 if (ioctl(pcap_fd, BIOCSETWF, &pr) == -1)
152 err(1, "ioctl(pcap_fd, BIOCSETFW)");
153 verbosef("filtered out BPF writes");
154 }
155 #endif
156
157 #ifdef BIOCLOCK
158 /* set "locked" flag (no reset) */
159 if (ioctl(pcap_fd, BIOCLOCK) == -1)
160 err(1, "ioctl(pcap_fd, BIOCLOCK)");
161 verbosef("locked down BPF for security");
162 #endif
163 }
164
165 /*
166 * Set pcap_fd in the given fd_set.
167 */
168 void
169 cap_fd_set(
170 #ifdef linux
171 fd_set *read_set _unused_,
172 int *max_fd _unused_,
173 struct timeval *timeout,
174 #else
175 fd_set *read_set,
176 int *max_fd,
177 struct timeval *timeout _unused_,
178 #endif
179 int *need_timeout)
180 {
181 assert(*need_timeout == 0); /* we're first to get a shot at this */
182 #ifdef linux
183 /*
184 * Linux's BPF is immediate, so don't select() as it will lead to horrible
185 * performance. Instead, use a timeout for buffering.
186 */
187 *need_timeout = 1;
188 timeout->tv_sec = 0;
189 timeout->tv_usec = CAP_TIMEOUT * 1000; /* msec->usec */
190 #else
191 /* We have a BSD-like BPF, we can select() on it. */
192 FD_SET(pcap_fd, read_set);
193 *max_fd = max(*max_fd, pcap_fd);
194 #endif
195 }
196
197 unsigned int pkts_recv = 0, pkts_drop = 0;
198
199 static void
200 cap_stats_update(void)
201 {
202 struct pcap_stat ps;
203
204 if (pcap_stats(pcap, &ps) != 0) {
205 warnx("pcap_stats(): %s", pcap_geterr(pcap));
206 return;
207 }
208
209 pkts_recv = ps.ps_recv;
210 pkts_drop = ps.ps_drop;
211 }
212
213 /*
214 * Print hexdump of received packet.
215 */
216 static void
217 hexdump(const u_char *buf, const uint32_t len)
218 {
219 uint32_t i, col;
220
221 printf("packet of %u bytes:\n", len);
222 col = 0;
223 for (i=0, col=0; i<len; i++) {
224 if (col == 0) printf(" ");
225 printf("%02x", buf[i]);
226 if (i+1 == linkhdr->hdrlen)
227 printf("[");
228 else if (i+1 == linkhdr->hdrlen + IP_HDR_LEN)
229 printf("]");
230 else printf(" ");
231 col += 3;
232 if (col >= 72) {
233 printf("\n");
234 col = 0;
235 }
236 }
237 if (col != 0) printf("\n");
238 printf("\n");
239 }
240
241 /*
242 * Callback function for pcap_dispatch() which chains to the decoder specified
243 * in linkhdr struct.
244 */
245 static void
246 callback(u_char *user, const struct pcap_pkthdr *h, const u_char *bytes)
247 {
248 if (want_hexdump) hexdump(bytes, h->caplen);
249 linkhdr->handler(user, h, bytes);
250 }
251
252 /*
253 * Process any packets currently in the capture buffer.
254 */
255 void
256 cap_poll(fd_set *read_set
257 #ifdef linux
258 _unused_
259 #endif
260 )
261 {
262 int total, ret;
263
264 #ifndef linux /* We don't use select() on Linux. */
265 if (!FD_ISSET(pcap_fd, read_set)) {
266 verbosef("cap_poll premature");
267 return;
268 }
269 #endif
270
271 /*
272 * Once per capture poll, check our IP address. It's used in accounting
273 * for traffic graphs.
274 */
275 localip_update(); /* FIXME: this might even be too often */
276
277 total = 0;
278 for (;;) {
279 ret = pcap_dispatch(
280 pcap,
281 -1, /* count, -1 = entire buffer */
282 callback,
283 NULL); /* user */
284
285 if (ret < 0) {
286 warnx("pcap_dispatch(): %s", pcap_geterr(pcap));
287 return;
288 }
289
290 /* Despite count = -1, Linux will only dispatch one packet at a time. */
291 total += ret;
292
293 #ifdef linux
294 /* keep looping until we've dispatched all the outstanding packets */
295 if (ret == 0) break;
296 #else
297 /* we get them all on the first shot */
298 break;
299 #endif
300 }
301 /*FIXME*/if (want_verbose) fprintf(stderr, "%-20d\r", total);
302 cap_stats_update();
303 }
304
305 void
306 cap_stop(void)
307 {
308 pcap_close(pcap);
309 }
310
311 /* Run through entire capfile. */
312 void
313 cap_from_file(const char *capfile, const char *filter)
314 {
315 char errbuf[PCAP_ERRBUF_SIZE];
316 int linktype, ret;
317
318 /* Open packet capture descriptor. */
319 errbuf[0] = '\0'; /* zero length string */
320 pcap = pcap_open_offline(capfile, errbuf);
321
322 if (pcap == NULL)
323 errx(1, "pcap_open_offline(): %s", errbuf);
324
325 if (errbuf[0] != '\0') /* not zero length anymore -> warning */
326 warnx("pcap_open_offline() warning: %s", errbuf);
327
328 /* Work out the linktype. */
329 linktype = pcap_datalink(pcap);
330 linkhdr = getlinkhdr(linktype);
331 if (linkhdr == NULL)
332 errx(1, "unknown linktype %d", linktype);
333 if (linkhdr->handler == NULL)
334 errx(1, "no handler for linktype %d", linktype);
335 if (linktype == DLT_EN10MB) /* FIXME: impossible with capfile? */
336 show_mac_addrs = 1;
337
338 /* Set filter expression, if any. */ /* FIXME: factor! */
339 if (filter != NULL)
340 {
341 struct bpf_program prog;
342 char *tmp_filter = xstrdup(filter);
343 if (pcap_compile(
344 pcap,
345 &prog,
346 tmp_filter,
347 1, /* optimize */
348 0) /* netmask */
349 == -1)
350 errx(1, "pcap_compile(): %s", pcap_geterr(pcap));
351
352 if (pcap_setfilter(pcap, &prog) == -1)
353 errx(1, "pcap_setfilter(): %s", pcap_geterr(pcap));
354
355 pcap_freecode(&prog);
356 free(tmp_filter);
357 }
358
359 /* Process file. */
360 ret = pcap_dispatch(
361 pcap,
362 -1, /* count, -1 = entire buffer */
363 callback,
364 NULL); /* user */
365
366 if (ret < 0)
367 errx(1, "pcap_dispatch(): %s", pcap_geterr(pcap));
368 }
369
370 /* vim:set ts=3 sw=3 tw=78 expandtab: */