ongrep

A cleaned up fork of ngrep for OpenBSD
git clone git://git.sgregoratto.me/ongrep
Log | Files | Refs | README | LICENSE

commit d0c17df8f9a7f017023aef80702ac41e33ade245
parent ebb4be69e99ab8f89058405c70ec6a4089f03674
Author: Stephen Gregoratto <dev@sgregoratto.me>
Date:   Wed, 24 Jun 2020 20:59:19 +1000

Properly check pcap return vals, drop pcap_lookupdev

Rewrite setup_pcap_source to use pcap_findalldevs instead of the
deprecated pcap_lookupdev. Changed the function to return -1 on err.
Also went and properly check error return values.

Diffstat:
Mngrep.c | 41++++++++++++++++++++++++++++-------------
1 file changed, 28 insertions(+), 13 deletions(-)

diff --git a/ngrep.c b/ngrep.c @@ -273,7 +273,7 @@ main(int argc, char **argv) match_data = argv[optind++]; /* Setup PCAP input */ - if (setup_pcap_source()) + if (setup_pcap_source() == -1) clean_exit(-1); /* @@ -314,12 +314,12 @@ main(int argc, char **argv) /* Misc */ if (dump_file) { - pd_dump = pcap_dump_open(pd, dump_file); - if (!pd_dump) { + if ((pd_dump = pcap_dump_open(pd, dump_file)) == NULL) { warnx("pcap_dump_open: %s", pcap_geterr(pd)); clean_exit(-2); - } else + } else { printf("output: %s\n", dump_file); + } } update_windowsize(0); @@ -335,26 +335,38 @@ int setup_pcap_source(void) { if (read_file) { - if (!(pd = pcap_open_offline(read_file, pc_err))) { + if ((pd = pcap_open_offline(read_file, pc_err)) == NULL) { warnx("pcap_open_offline: %s", pc_err); - return 1; + return -1; } live_read = 0; printf("input: %s\n", read_file); } else { char *dev; + pcap_if_t *devs = NULL; if (usedev != NULL) { dev = usedev; - } else if ((dev = pcap_lookupdev(pc_err)) == NULL) { - warnx("pcap_lookupdev: %s", pc_err); - return 1; + } else { + if (pcap_findalldevs(&devs, pc_err) == PCAP_ERROR) { + warnx("pcap_findalldevs: %s", pc_err); + return -1; + } + if (devs == NULL) { + warnx("pcap_findalldevs: no devices found"); + return -1; + } + + dev = devs->name; } - if ((pd = pcap_open_live(dev, snaplen, promisc, to, pc_err)) == NULL) { + + pd = pcap_open_live(dev, snaplen, promisc, to, pc_err); + if (pd == NULL) { warnx("pcap_open_live: %s", pc_err); - return 1; + return -1; } - if (pcap_lookupnet(dev, &net.s_addr, &mask.s_addr, pc_err) == -1) { + if (pcap_lookupnet(dev, &net.s_addr, &mask.s_addr, pc_err) == + PCAP_ERROR) { warnx("pcap_lookupnet: %s", pc_err); memset(&net, 0, sizeof(net)); memset(&mask, 0, sizeof(mask)); @@ -366,6 +378,8 @@ setup_pcap_source(void) inet_ntoa(net), inet_ntoa(mask)); printf("\n"); } + + pcap_freealldevs(devs); } switch (pcap_datalink(pd)) { @@ -403,8 +417,9 @@ setup_pcap_source(void) default: warnx("fatal: unsupported interface type %u", pcap_datalink(pd)); - return 1; + return -1; } + return 0; }