2 * copyright (c) 2001-2011 Emil Mikulic.
4 * cap.c: capture packets, and hand them off to decode and acct.
6 * You may use, modify and redistribute this file under the terms of the
7 * GNU General Public License version 2. (see COPYING.GPL)
24 #include <sys/ioctl.h>
25 #include <sys/types.h>
26 #include <sys/socket.h>
28 #ifdef HAVE_SYS_FILIO_H
29 # include <sys/filio.h> /* Solaris' FIONBIO hides here */
38 char *title_interfaces
= NULL
; /* for html.c */
40 /* The cap process life-cycle:
41 * - cap_add_ifname() one or more times
42 * - cap_add_filter() zero or more times
43 * - cap_start() once to start listening
45 * - cap_fd_set() to update the select() set
46 * - cap_poll() to read from ready pcap fds
52 STAILQ_ENTRY(strnode
) entries
;
57 STAILQ_ENTRY(cap_iface
) entries
;
63 const struct linkhdr
*linkhdr
;
64 struct local_ips local_ips
;
67 static STAILQ_HEAD(cli_ifnames_head
, strnode
) cli_ifnames
=
68 STAILQ_HEAD_INITIALIZER(cli_ifnames
);
70 static STAILQ_HEAD(cli_filters_head
, strnode
) cli_filters
=
71 STAILQ_HEAD_INITIALIZER(cli_filters
);
73 static STAILQ_HEAD(cap_ifs_head
, cap_iface
) cap_ifs
=
74 STAILQ_HEAD_INITIALIZER(cap_ifs
);
76 /* The read timeout passed to pcap_open_live() */
77 #define CAP_TIMEOUT_MSEC 500
79 void cap_add_ifname(const char *ifname
) {
80 struct strnode
*n
= xmalloc(sizeof(*n
));
82 STAILQ_INSERT_TAIL(&cli_ifnames
, n
, entries
);
85 void cap_add_filter(const char *filter
) {
86 struct strnode
*n
= xmalloc(sizeof(*n
));
88 STAILQ_INSERT_TAIL(&cli_filters
, n
, entries
);
91 static void cap_set_filter(pcap_t
*pcap
, const char *filter
) {
92 struct bpf_program prog
;
98 tmp_filter
= xstrdup(filter
);
106 errx(1, "pcap_compile(): %s", pcap_geterr(pcap
));
108 if (pcap_setfilter(pcap
, &prog
) == -1)
109 errx(1, "pcap_setfilter(): %s", pcap_geterr(pcap
));
111 pcap_freecode(&prog
);
115 static void cap_start_one(struct cap_iface
*iface
, const int promisc
) {
116 char errbuf
[PCAP_ERRBUF_SIZE
], *tmp_device
;
117 int linktype
, snaplen
, waited
;
119 /* pcap wants a non-const interface name string */
120 tmp_device
= xstrdup(iface
->name
);
122 verbosef("capturing on interface '%s' with filter '%s'",
123 tmp_device
, iface
->filter
);
125 verbosef("capturing on interface '%s' with no filter", tmp_device
);
127 /* Open packet capture descriptor. */
130 errbuf
[0] = '\0'; /* zero length string */
131 iface
->pcap
= pcap_open_live(
133 1, /* snaplen, irrelevant at this point */
134 0, /* promisc, also irrelevant */
137 if (iface
->pcap
!= NULL
)
138 break; /* success! */
140 if ((opt_wait_secs
!= -1) && strstr(errbuf
, "device is not up")) {
141 if ((opt_wait_secs
> 0) && (waited
>= opt_wait_secs
))
142 errx(1, "waited %d secs, giving up: pcap_open_live(): %s",
145 verbosef("waited %d secs, interface is not up", waited
);
149 else errx(1, "pcap_open_live(): %s", errbuf
);
152 /* Work out the linktype and what snaplen we need. */
153 linktype
= pcap_datalink(iface
->pcap
);
154 verbosef("linktype is %d", linktype
);
155 if ((linktype
== DLT_EN10MB
) && opt_want_macs
)
156 hosts_db_show_macs
= 1;
157 iface
->linkhdr
= getlinkhdr(linktype
);
158 if (iface
->linkhdr
== NULL
)
159 errx(1, "unknown linktype %d", linktype
);
160 if (iface
->linkhdr
->decoder
== NULL
)
161 errx(1, "no decoder for linktype %d", linktype
);
162 snaplen
= getsnaplen(iface
->linkhdr
);
163 if (opt_want_pppoe
) {
164 snaplen
+= PPPOE_HDR_LEN
;
165 if (linktype
!= DLT_EN10MB
)
166 errx(1, "can't do PPPoE decoding on a non-Ethernet linktype");
168 verbosef("calculated snaplen minimum %d", snaplen
);
170 /* FIXME: actually due to libpcap moving to mmap (!!!)
171 * work out which version and fix the way we do capture
175 /* Ubuntu 9.04 has a problem where requesting snaplen <= 60 will
176 * give us 42 bytes, and we need at least 54 for TCP headers.
178 * Hack to set minimum snaplen to tcpdump's default:
180 snaplen
= MAX(snaplen
, 96);
182 if (opt_want_snaplen
> -1)
183 snaplen
= opt_want_snaplen
;
184 verbosef("using snaplen %d", snaplen
);
186 /* Close and re-open pcap to use the new snaplen. */
187 pcap_close(iface
->pcap
);
188 errbuf
[0] = '\0'; /* zero length string */
189 iface
->pcap
= pcap_open_live(
196 if (iface
->pcap
== NULL
)
197 errx(1, "pcap_open_live(): %s", errbuf
);
199 if (errbuf
[0] != '\0') /* not zero length anymore -> warning */
200 warnx("pcap_open_live() warning: %s", errbuf
);
205 verbosef("capturing in promiscuous mode");
207 verbosef("capturing in non-promiscuous mode");
209 cap_set_filter(iface
->pcap
, iface
->filter
);
210 iface
->fd
= pcap_fileno(iface
->pcap
);
212 /* set non-blocking */
214 if (pcap_setnonblock(iface
->pcap
, 1, errbuf
) == -1)
215 errx(1, "pcap_setnonblock(): %s", errbuf
);
219 if (ioctl(iface
->fd
, FIONBIO
, &one
) == -1)
220 err(1, "ioctl(iface->fd, FIONBIO)");
226 /* Deny all writes to the socket */
227 struct bpf_insn bpf_wfilter
[] = { BPF_STMT(BPF_RET
+BPF_K
, 0) };
228 int wf_len
= sizeof(bpf_wfilter
) / sizeof(struct bpf_insn
);
229 struct bpf_program pr
;
232 pr
.bf_insns
= bpf_wfilter
;
234 if (ioctl(iface
->fd
, BIOCSETWF
, &pr
) == -1)
235 err(1, "ioctl(iface->fd, BIOCSETFW)");
236 verbosef("filtered out BPF writes");
241 /* set "locked" flag (no reset) */
242 if (ioctl(iface
->fd
, BIOCLOCK
) == -1)
243 err(1, "ioctl(iface->fd, BIOCLOCK)");
244 verbosef("locked down BPF for security");
248 void cap_start(const int promisc
) {
249 struct str
*ifs
= str_make();
251 assert(STAILQ_EMPTY(&cap_ifs
));
252 if (STAILQ_EMPTY(&cli_ifnames
))
253 errx(1, "no interfaces specified");
255 /* For each ifname */
256 while (!STAILQ_EMPTY(&cli_ifnames
)) {
257 struct strnode
*ifname
, *filter
= NULL
;
258 struct cap_iface
*iface
= xmalloc(sizeof(*iface
));
260 ifname
= STAILQ_FIRST(&cli_ifnames
);
261 STAILQ_REMOVE_HEAD(&cli_ifnames
, entries
);
263 if (!STAILQ_EMPTY(&cli_filters
)) {
264 filter
= STAILQ_FIRST(&cli_filters
);
265 STAILQ_REMOVE_HEAD(&cli_filters
, entries
);
268 iface
->name
= ifname
->str
;
269 iface
->filter
= (filter
== NULL
) ? NULL
: filter
->str
;
272 iface
->linkhdr
= NULL
;
273 localip_init(&iface
->local_ips
);
274 STAILQ_INSERT_TAIL(&cap_ifs
, iface
, entries
);
275 cap_start_one(iface
, promisc
);
278 if (filter
) free(filter
);
280 if (str_len(ifs
) == 0)
281 str_append(ifs
, iface
->name
);
283 str_appendf(ifs
, ", %s", iface
->name
);
285 verbosef("all capture interfaces prepared");
287 /* Deallocate extra filters, if any. */
288 while (!STAILQ_EMPTY(&cli_filters
)) {
289 struct strnode
*filter
= STAILQ_FIRST(&cli_filters
);
291 verbosef("ignoring extraneous filter '%s'", filter
->str
);
292 STAILQ_REMOVE_HEAD(&cli_filters
, entries
);
296 str_appendn(ifs
, "", 1); /* NUL terminate */
299 str_extract(ifs
, &_
, &title_interfaces
);
304 # define _unused_on_linux_ _unused_
305 # define _unused_otherwise_
307 # define _unused_on_linux_
308 # define _unused_otherwise_ _unused_
312 * Set pcap_fd in the given fd_set.
314 void cap_fd_set(fd_set
*read_set _unused_on_linux_
,
315 int *max_fd _unused_on_linux_
,
316 struct timeval
*timeout _unused_otherwise_
,
318 assert(*need_timeout
== 0); /* we're first to get a shot at the fd_set */
322 * Linux's BPF is immediate, so don't select() as it will lead to horrible
323 * performance. Instead, use a timeout for buffering.
327 timeout
->tv_usec
= CAP_TIMEOUT_MSEC
* 1000;
330 struct cap_iface
*iface
;
331 STAILQ_FOREACH(iface
, &cap_ifs
, entries
) {
332 /* We have a BSD-like BPF, we can select() on it. */
333 FD_SET(iface
->fd
, read_set
);
334 *max_fd
= MAX(*max_fd
, iface
->fd
);
340 unsigned int cap_pkts_recv
= 0, cap_pkts_drop
= 0;
342 static void cap_stats_update(void) {
343 struct cap_iface
*iface
;
347 STAILQ_FOREACH(iface
, &cap_ifs
, entries
) {
349 if (pcap_stats(iface
->pcap
, &ps
) != 0) {
350 warnx("pcap_stats('%s'): %s", iface
->name
, pcap_geterr(iface
->pcap
));
353 cap_pkts_recv
+= ps
.ps_recv
;
354 cap_pkts_drop
+= ps
.ps_drop
;
358 /* Print hexdump of received packet to stdout, for debugging. */
359 static void hexdump(const u_char
*buf
,
361 const struct linkhdr
*linkhdr
) {
364 printf("packet of %u bytes:\n", len
);
365 for (i
=0, col
=0; i
<len
; i
++) {
366 if (col
== 0) printf(" ");
367 printf("%02x", buf
[i
]);
368 if (i
+1 == linkhdr
->hdrlen
)
369 printf("|"); /* marks end of link headers (e.g. ethernet) */
378 if (col
!= 0) printf("\n");
382 /* Callback function for pcap_dispatch() which chains to the decoder specified
383 * in the linkhdr struct.
385 static void callback(u_char
*user
,
386 const struct pcap_pkthdr
*pheader
,
387 const u_char
*pdata
) {
388 const struct cap_iface
* const iface
= (struct cap_iface
*)user
;
389 struct pktsummary sm
;
391 if (opt_want_hexdump
)
392 hexdump(pdata
, pheader
->caplen
, iface
->linkhdr
);
393 memset(&sm
, 0, sizeof(sm
));
394 if (iface
->linkhdr
->decoder(pheader
, pdata
, &sm
))
395 acct_for(&sm
, &iface
->local_ips
);
398 /* Process any packets currently in the capture buffer. */
399 void cap_poll(fd_set
*read_set _unused_on_linux_
) {
400 struct cap_iface
*iface
;
402 STAILQ_FOREACH(iface
, &cap_ifs
, entries
) {
403 /* Once per capture poll, check our IP address. It's used in accounting
404 * for traffic graphs.
406 localip_update(iface
->name
, &iface
->local_ips
);
415 -1, /* count = entire buffer */
417 (u_char
*)iface
); /* user = struct to pass to callback */
420 warnx("pcap_dispatch('%s'): %s",
421 iface
->name
, pcap_geterr(iface
->pcap
));
425 2 * CAP_TIMEOUT_MSEC
* 1000000,
426 "pcap_dispatch took too long");
428 if (0) /* debugging */
429 verbosef("iface '%s' got %d pkts", iface
->name
, ret
);
432 /* keep looping until we've dispatched all the outstanding packets */
436 /* we get them all on the first shot */
444 void cap_stop(void) {
445 while (!STAILQ_EMPTY(&cap_ifs
)) {
446 struct cap_iface
*iface
= STAILQ_FIRST(&cap_ifs
);
448 STAILQ_REMOVE_HEAD(&cap_ifs
, entries
);
449 pcap_close(iface
->pcap
);
450 localip_free(&iface
->local_ips
);
453 free(title_interfaces
);
454 title_interfaces
= NULL
;
457 /* Run through entire capfile. */
458 void cap_from_file(const char *capfile
) {
459 char errbuf
[PCAP_ERRBUF_SIZE
];
461 struct cap_iface iface
;
467 iface
.linkhdr
= NULL
;
468 localip_init(&iface
.local_ips
);
470 /* Process cmdline filters. */
471 if (!STAILQ_EMPTY(&cli_filters
))
472 iface
.filter
= STAILQ_FIRST(&cli_filters
)->str
;
473 while (!STAILQ_EMPTY(&cli_filters
)) {
474 struct strnode
*n
= STAILQ_FIRST(&cli_filters
);
475 STAILQ_REMOVE_HEAD(&cli_filters
, entries
);
479 /* Open packet capture descriptor. */
480 errbuf
[0] = '\0'; /* zero length string */
481 iface
.pcap
= pcap_open_offline(capfile
, errbuf
);
483 if (iface
.pcap
== NULL
)
484 errx(1, "pcap_open_offline(): %s", errbuf
);
486 if (errbuf
[0] != '\0') /* not zero length anymore -> warning */
487 warnx("pcap_open_offline() warning: %s", errbuf
);
489 /* Work out the linktype. */
490 linktype
= pcap_datalink(iface
.pcap
);
491 iface
.linkhdr
= getlinkhdr(linktype
);
492 if (iface
.linkhdr
== NULL
)
493 errx(1, "unknown linktype %d", linktype
);
494 if (iface
.linkhdr
->decoder
== NULL
)
495 errx(1, "no decoder for linktype %d", linktype
);
497 cap_set_filter(iface
.pcap
, iface
.filter
);
502 -1, /* count, -1 = entire buffer */
504 (u_char
*)&iface
); /* user */
507 errx(1, "pcap_dispatch(): %s", pcap_geterr(iface
.pcap
));
509 localip_free(&iface
.local_ips
);
510 pcap_close(iface
.pcap
);
513 /* vim:set ts=3 sw=3 tw=78 expandtab: */