Home | History | Annotate | Line # | Download | only in npfd
npfd_log.c revision 1.10
      1 /*	$NetBSD: npfd_log.c,v 1.10 2017/03/25 11:00:27 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2015 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Mindaugas Rasiukevicius.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     29  * POSSIBILITY OF SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 __RCSID("$NetBSD: npfd_log.c,v 1.10 2017/03/25 11:00:27 christos Exp $");
     34 
     35 #include <sys/types.h>
     36 #include <sys/param.h>
     37 #include <sys/stat.h>
     38 
     39 #include <net/if.h>
     40 
     41 #include <stdio.h>
     42 #include <err.h>
     43 #include <inttypes.h>
     44 #include <limits.h>
     45 #include <stdlib.h>
     46 #include <unistd.h>
     47 #include <syslog.h>
     48 #include <stdbool.h>
     49 
     50 #include <pcap/pcap.h>
     51 #include "npfd.h"
     52 
     53 struct npfd_log {
     54 	char ifname[IFNAMSIZ];
     55 	char path[MAXPATHLEN];
     56 	pcap_t *pcap;
     57 	pcap_dumper_t *dumper;
     58 };
     59 
     60 static void
     61 npfd_log_setfilter(npfd_log_t *ctx, const char *filter)
     62 {
     63 	struct bpf_program bprog;
     64 
     65 	if (pcap_compile(ctx->pcap, &bprog, filter, 1, 0) == -1)
     66 		errx(EXIT_FAILURE, "pcap_compile failed for `%s': %s", filter,
     67 		    pcap_geterr(ctx->pcap));
     68 	if (pcap_setfilter(ctx->pcap, &bprog) == -1)
     69 		errx(EXIT_FAILURE, "pcap_setfilter failed: %s",
     70 		    pcap_geterr(ctx->pcap));
     71 	pcap_freecode(&bprog);
     72 }
     73 
     74 static FILE *
     75 npfd_log_gethdr(npfd_log_t *ctx, struct pcap_file_header*hdr)
     76 {
     77 	FILE *fp = fopen(ctx->path, "r");
     78 
     79 	hdr->magic = 0;
     80 	if (fp == NULL)
     81 		return NULL;
     82 
     83 #define TCPDUMP_MAGIC 0xa1b2c3d4
     84 
     85 	switch (fread(hdr, sizeof(*hdr), 1, fp)) {
     86 	case 0:
     87 		hdr->magic = 0;
     88 		fclose(fp);
     89 		return NULL;
     90 	case 1:
     91 		if (hdr->magic != TCPDUMP_MAGIC ||
     92 		    hdr->version_major != PCAP_VERSION_MAJOR ||
     93 		    hdr->version_minor != PCAP_VERSION_MINOR ||
     94 		    hdr->sigfigs != (u_int)pcap_get_tstamp_precision(ctx->pcap))
     95 			goto out;
     96 		break;
     97 	default:
     98 		goto out;
     99 	}
    100 
    101 	return fp;
    102 out:
    103 	fclose(fp);
    104 	hdr->magic = (uint32_t)-1;
    105 	return NULL;
    106 }
    107 
    108 static int
    109 npfd_log_getsnaplen(npfd_log_t *ctx)
    110 {
    111 	struct pcap_file_header hdr;
    112 	FILE *fp = npfd_log_gethdr(ctx, &hdr);
    113 	if (fp == NULL)
    114 		return hdr.magic == (uint32_t)-1 ? -1 : 0;
    115 	fclose(fp);
    116 	return hdr.snaplen;
    117 }
    118 
    119 static int
    120 npfd_log_validate(npfd_log_t *ctx)
    121 {
    122 	struct pcap_file_header hdr;
    123 	FILE *fp = npfd_log_gethdr(ctx, &hdr);
    124 	size_t o, no;
    125 
    126 	if (fp == NULL) {
    127 		if (hdr.magic == 0)
    128 			return 0;
    129 		goto rename;
    130 	}
    131 
    132 	struct stat st;
    133 	if (fstat(fileno(fp), &st) == -1)
    134 		goto rename;
    135 
    136 	size_t count = 0;
    137 	for (o = sizeof(hdr);; count++) {
    138 		struct {
    139 			uint32_t sec;
    140 			uint32_t usec;
    141 			uint32_t caplen;
    142 			uint32_t len;
    143 		} pkt;
    144 		switch (fread(&pkt, sizeof(pkt), 1, fp)) {
    145 		case 0:
    146 			syslog(LOG_INFO, "%zu packets read from `%s'", count,
    147 			    ctx->path);
    148 			fclose(fp);
    149 			return hdr.snaplen;
    150 		case 1:
    151 			no = o + sizeof(pkt) + pkt.caplen;
    152 			if (pkt.caplen > hdr.snaplen)
    153 				goto fix;
    154 			if (no > (size_t)st.st_size)
    155 				goto fix;
    156 			if (fseeko(fp, pkt.caplen, SEEK_CUR) != 0)
    157 				goto fix;
    158 			o = no;
    159 			break;
    160 		default:
    161 			goto fix;
    162 		}
    163 	}
    164 
    165 fix:
    166 	fclose(fp);
    167 	no = st.st_size - o;
    168 	syslog(LOG_INFO, "%zu packets read from `%s', %zu extra bytes",
    169 	    count, ctx->path, no);
    170 	if (no < 10240) {
    171 		syslog(LOG_WARNING,
    172 		    "Incomplete last packet in `%s', truncating",
    173 		    ctx->path);
    174 		if (truncate(ctx->path, (off_t)o) == -1) {
    175 			syslog(LOG_ERR, "Cannot truncate `%s': %m", ctx->path);
    176 			goto rename;
    177 		}
    178 	} else {
    179 		syslog(LOG_ERR, "Corrupt file `%s'", ctx->path);
    180 		goto rename;
    181 	}
    182 	fclose(fp);
    183 	return hdr.snaplen;
    184 rename:
    185 	fclose(fp);
    186 	char tmp[MAXPATHLEN];
    187 	snprintf(tmp, sizeof(tmp), "%s.XXXXXX", ctx->path);
    188 	int fd;
    189 	if ((fd = mkstemp(tmp)) == -1) {
    190 		syslog(LOG_ERR, "Can't make temp file `%s': %m", tmp);
    191 		return -1;
    192 	}
    193 	close(fd);
    194 	if (rename(ctx->path, tmp) == -1) {
    195 		syslog(LOG_ERR, "Can't rename `%s' to `%s': %m",
    196 		    ctx->path, tmp);
    197 		return -1;
    198 	}
    199 	syslog(LOG_ERR, "Renamed to `%s'", tmp);
    200 	return 0;
    201 }
    202 
    203 
    204 npfd_log_t *
    205 npfd_log_create(const char *filename, const char *ifname, const char *filter,
    206     int snaplen)
    207 {
    208 	npfd_log_t *ctx;
    209 	char errbuf[PCAP_ERRBUF_SIZE];
    210 
    211 	if ((ctx = calloc(1, sizeof(*ctx))) == NULL)
    212 		err(EXIT_FAILURE, "malloc failed");
    213 
    214 	/*
    215 	 * Open a live capture handle in non-blocking mode.
    216 	 */
    217 	snprintf(ctx->ifname, sizeof(ctx->ifname), "%s", ifname);
    218 	ctx->pcap = pcap_create(ctx->ifname, errbuf);
    219 	if (ctx->pcap == NULL)
    220 		errx(EXIT_FAILURE, "pcap_create failed: %s", errbuf);
    221 
    222 	if (pcap_setnonblock(ctx->pcap, 1, errbuf) == -1)
    223 		errx(EXIT_FAILURE, "pcap_setnonblock failed: %s", errbuf);
    224 
    225 	if (filename == NULL)
    226 		snprintf(ctx->path, sizeof(ctx->path), NPFD_LOG_PATH "/%s.pcap",
    227 		    ctx->ifname);
    228 	else
    229 		snprintf(ctx->path, sizeof(ctx->path), "%s", filename);
    230 
    231 	int sl = npfd_log_getsnaplen(ctx);
    232 	if (sl == -1)
    233 		errx(EXIT_FAILURE, "corrupt log file `%s'", ctx->path);
    234 
    235 	if (sl != 0 && sl != snaplen) {
    236 		warnx("Overriding snaplen from %d to %d from `%s'", snaplen,
    237 		    sl, filename);
    238 		snaplen = sl;
    239 	}
    240 
    241 	if (pcap_set_snaplen(ctx->pcap, snaplen) == -1)
    242 		errx(EXIT_FAILURE, "pcap_set_snaplen failed: %s",
    243 		    pcap_geterr(ctx->pcap));
    244 
    245 	if (pcap_set_timeout(ctx->pcap, 1000) == -1)
    246 		errx(EXIT_FAILURE, "pcap_set_timeout failed: %s",
    247 		    pcap_geterr(ctx->pcap));
    248 
    249 	if (pcap_activate(ctx->pcap) == -1)
    250 		errx(EXIT_FAILURE, "pcap_activate failed: %s",
    251 		    pcap_geterr(ctx->pcap));
    252 
    253 	if (filter)
    254 		npfd_log_setfilter(ctx, filter);
    255 
    256 
    257 	npfd_log_reopen(ctx, false);
    258 	return ctx;
    259 }
    260 
    261 bool
    262 npfd_log_reopen(npfd_log_t *ctx, bool die)
    263 {
    264 	mode_t omask = umask(077);
    265 
    266 	if (ctx->dumper)
    267 		pcap_dump_close(ctx->dumper);
    268 	/*
    269 	 * Open a log file to write for a given interface and dump there.
    270 	 */
    271 	switch (npfd_log_validate(ctx)) {
    272 	case -1:
    273 		syslog(LOG_ERR, "Giving up");
    274 		exit(EXIT_FAILURE);
    275 		/*NOTREACHED*/
    276 	case 0:
    277 		ctx->dumper = pcap_dump_open(ctx->pcap, ctx->path);
    278 		break;
    279 	default:
    280 		ctx->dumper = pcap_dump_open_append(ctx->pcap, ctx->path);
    281 		break;
    282 	}
    283 	(void)umask(omask);
    284 
    285 	if (ctx->dumper == NULL) {
    286 		if (die)
    287 			errx(EXIT_FAILURE, "pcap_dump_open failed for `%s': %s",
    288 			    ctx->path, pcap_geterr(ctx->pcap));
    289 		syslog(LOG_ERR, "pcap_dump_open failed for `%s': %s",
    290 		    ctx->path, pcap_geterr(ctx->pcap));
    291 		return false;
    292 	}
    293 	return true;
    294 }
    295 
    296 void
    297 npfd_log_destroy(npfd_log_t *ctx)
    298 {
    299 	if (ctx->dumper)
    300 		pcap_dump_close(ctx->dumper);
    301 	if (ctx->pcap)
    302 		pcap_close(ctx->pcap);
    303 	free(ctx);
    304 }
    305 
    306 int
    307 npfd_log_getsock(npfd_log_t *ctx)
    308 {
    309 	return pcap_get_selectable_fd(ctx->pcap);
    310 }
    311 
    312 void
    313 npfd_log_flush(npfd_log_t *ctx)
    314 {
    315 	if (!ctx->dumper)
    316 		return;
    317 	if (pcap_dump_flush(ctx->dumper) == -1)
    318 		syslog(LOG_ERR, "pcap_dump_flush failed for `%s': %m",
    319 		    ctx->path);
    320 }
    321 
    322 
    323 void
    324 npfd_log(npfd_log_t *ctx)
    325 {
    326 	pcap_dumper_t *dumper = ctx->dumper;
    327 
    328 	pcap_dispatch(ctx->pcap, PCAP_NPACKETS, pcap_dump, (void *)dumper);
    329 }
    330 
    331 void
    332 npfd_log_stats(npfd_log_t *ctx)
    333 {
    334 	pcap_t *pcap = ctx->pcap;
    335 	struct pcap_stat ps;
    336 
    337 	if (pcap_stats(pcap, &ps) == -1) {
    338 		syslog(LOG_ERR, "pcap_stats failed: %s", pcap_geterr(pcap));
    339 		return;
    340 	}
    341 	syslog(LOG_INFO, "packet statistics: %s: %u received, %u dropped",
    342 	    ctx->ifname, ps.ps_recv, ps.ps_drop);
    343 }
    344