xref: /netbsd-src/usr.sbin/npf/npfctl/npfctl.c (revision e6c7e151de239c49d2e38720a061ed9d1fa99309)
1 /*-
2  * Copyright (c) 2009-2014 The NetBSD Foundation, Inc.
3  * All rights reserved.
4  *
5  * This material is based upon work partially supported by The
6  * NetBSD Foundation under a contract with Mindaugas Rasiukevicius.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
19  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
20  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
21  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27  * POSSIBILITY OF SUCH DAMAGE.
28  */
29 
30 #include <sys/cdefs.h>
31 __RCSID("$NetBSD: npfctl.c,v 1.63 2019/09/30 00:37:11 rmind Exp $");
32 
33 #include <sys/stat.h>
34 #include <sys/types.h>
35 #include <sys/mman.h>
36 #ifdef __NetBSD__
37 #include <sha1.h>
38 #include <sys/ioctl.h>
39 #include <sys/module.h>
40 #define SHA_DIGEST_LENGTH SHA1_DIGEST_LENGTH
41 #else
42 #include <openssl/sha.h>
43 #endif
44 
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <err.h>
49 #include <fcntl.h>
50 #include <unistd.h>
51 #include <errno.h>
52 
53 #include <arpa/inet.h>
54 
55 #include "npfctl.h"
56 
57 enum {
58 	NPFCTL_START,
59 	NPFCTL_STOP,
60 	NPFCTL_RELOAD,
61 	NPFCTL_SHOWCONF,
62 	NPFCTL_FLUSH,
63 	NPFCTL_VALIDATE,
64 	NPFCTL_TABLE,
65 	NPFCTL_RULE,
66 	NPFCTL_STATS,
67 	NPFCTL_SAVE,
68 	NPFCTL_LOAD,
69 	NPFCTL_DEBUG,
70 	NPFCTL_CONN_LIST,
71 };
72 
73 static const struct operations_s {
74 	const char *		cmd;
75 	int			action;
76 } operations[] = {
77 	/* Start, stop, reload */
78 	{	"start",	NPFCTL_START		},
79 	{	"stop",		NPFCTL_STOP		},
80 	{	"reload",	NPFCTL_RELOAD		},
81 	{	"show",		NPFCTL_SHOWCONF,	},
82 	{	"flush",	NPFCTL_FLUSH		},
83 	/* Table */
84 	{	"table",	NPFCTL_TABLE		},
85 	/* Rule */
86 	{	"rule",		NPFCTL_RULE		},
87 	/* Stats */
88 	{	"stats",	NPFCTL_STATS		},
89 	/* Full state save/load */
90 	{	"save",		NPFCTL_SAVE		},
91 	{	"load",		NPFCTL_LOAD		},
92 	{	"list",		NPFCTL_CONN_LIST	},
93 	/* Misc. */
94 	{	"valid",	NPFCTL_VALIDATE		},
95 	{	"debug",	NPFCTL_DEBUG		},
96 	/* --- */
97 	{	NULL,		0			}
98 };
99 
100 bool
101 join(char *buf, size_t buflen, int count, char **args, const char *sep)
102 {
103 	const u_int seplen = strlen(sep);
104 	char *s = buf, *p = NULL;
105 
106 	for (int i = 0; i < count; i++) {
107 		size_t len;
108 
109 		p = stpncpy(s, args[i], buflen);
110 		len = p - s + seplen;
111 		if (len >= buflen) {
112 			return false;
113 		}
114 		buflen -= len;
115 		strcpy(p, sep);
116 		s = p + seplen;
117 	}
118 	*p = '\0';
119 	return true;
120 }
121 
122 __dead static void
123 usage(void)
124 {
125 	const char *progname = getprogname();
126 
127 	fprintf(stderr,
128 	    "Usage:\t%s start | stop | flush | show | stats\n",
129 	    progname);
130 	fprintf(stderr,
131 	    "\t%s validate | reload [<rule-file>]\n",
132 	    progname);
133 	fprintf(stderr,
134 	    "\t%s rule \"rule-name\" { add | rem } <rule-syntax>\n",
135 	    progname);
136 	fprintf(stderr,
137 	    "\t%s rule \"rule-name\" rem-id <rule-id>\n",
138 	    progname);
139 	fprintf(stderr,
140 	    "\t%s rule \"rule-name\" { list | flush }\n",
141 	    progname);
142 	fprintf(stderr,
143 	    "\t%s table \"table-name\" { add | rem | test } <address/mask>\n",
144 	    progname);
145 	fprintf(stderr,
146 	    "\t%s table \"table-name\" { list | flush }\n",
147 	    progname);
148 	fprintf(stderr,
149 	    "\t%s table \"table-name\" replace [-n \"name\"]"
150 	    " [-t <type>] <table-file>\n",
151 	    progname);
152 	fprintf(stderr,
153 	    "\t%s save | load\n",
154 	    progname);
155 	fprintf(stderr,
156 	    "\t%s list [-46hNnw] [-i <ifname>]\n",
157 	    progname);
158 	fprintf(stderr,
159 	    "\t%s debug [<rule-file>] [<raw-output>]\n",
160 	    progname);
161 	exit(EXIT_FAILURE);
162 }
163 
164 static int
165 npfctl_print_stats(int fd)
166 {
167 	static const struct stats_s {
168 		/* Note: -1 indicates a new section. */
169 		int		index;
170 		const char *	name;
171 	} stats[] = {
172 		{ -1, "Packets passed"					},
173 		{ NPF_STAT_PASS_DEFAULT,	"default pass"		},
174 		{ NPF_STAT_PASS_RULESET,	"ruleset pass"		},
175 		{ NPF_STAT_PASS_CONN,		"state pass"		},
176 
177 		{ -1, "Packets blocked"					},
178 		{ NPF_STAT_BLOCK_DEFAULT,	"default block"		},
179 		{ NPF_STAT_BLOCK_RULESET,	"ruleset block"		},
180 
181 		{ -1, "State and NAT entries"				},
182 		{ NPF_STAT_CONN_CREATE,		"state allocations"},
183 		{ NPF_STAT_CONN_DESTROY,	"state destructions"},
184 		{ NPF_STAT_NAT_CREATE,		"NAT entry allocations"	},
185 		{ NPF_STAT_NAT_DESTROY,		"NAT entry destructions"},
186 
187 		{ -1, "Network buffers"					},
188 		{ NPF_STAT_NBUF_NONCONTIG,	"non-contiguous cases"	},
189 		{ NPF_STAT_NBUF_CONTIG_FAIL,	"contig alloc failures"	},
190 
191 		{ -1, "Invalid packet state cases"			},
192 		{ NPF_STAT_INVALID_STATE,	"cases in total"	},
193 		{ NPF_STAT_INVALID_STATE_TCP1,	"TCP case I"		},
194 		{ NPF_STAT_INVALID_STATE_TCP2,	"TCP case II"		},
195 		{ NPF_STAT_INVALID_STATE_TCP3,	"TCP case III"		},
196 
197 		{ -1, "Packet race cases"				},
198 		{ NPF_STAT_RACE_NAT,		"NAT association race"	},
199 		{ NPF_STAT_RACE_CONN,		"duplicate state race"	},
200 
201 		{ -1, "Fragmentation"					},
202 		{ NPF_STAT_FRAGMENTS,		"fragments"		},
203 		{ NPF_STAT_REASSEMBLY,		"reassembled"		},
204 		{ NPF_STAT_REASSFAIL,		"failed reassembly"	},
205 
206 		{ -1, "Other"						},
207 		{ NPF_STAT_ERROR,		"unexpected errors"	},
208 	};
209 	uint64_t *st = ecalloc(1, NPF_STATS_SIZE);
210 
211 	if (ioctl(fd, IOC_NPF_STATS, &st) != 0) {
212 		err(EXIT_FAILURE, "ioctl(IOC_NPF_STATS)");
213 	}
214 
215 	for (unsigned i = 0; i < __arraycount(stats); i++) {
216 		const char *sname = stats[i].name;
217 		int sidx = stats[i].index;
218 
219 		if (sidx == -1) {
220 			printf("%s:\n", sname);
221 		} else {
222 			printf("\t%"PRIu64" %s\n", st[sidx], sname);
223 		}
224 	}
225 
226 	free(st);
227 	return 0;
228 }
229 
230 void
231 npfctl_print_error(const npf_error_t *ne)
232 {
233 	const char *srcfile = ne->source_file;
234 
235 	if (ne->error_msg) {
236 		errx(EXIT_FAILURE, "%s", ne->error_msg);
237 	}
238 	if (srcfile) {
239 		warnx("source %s line %d", srcfile, ne->source_line);
240 	}
241 	if (ne->id) {
242 		warnx("object: %" PRIi64, ne->id);
243 	}
244 }
245 
246 char *
247 npfctl_print_addrmask(int alen, const char *fmt, const npf_addr_t *addr,
248     npf_netmask_t mask)
249 {
250 	const unsigned buflen = 256;
251 	char *buf = ecalloc(1, buflen);
252 	struct sockaddr_storage ss;
253 
254 	memset(&ss, 0, sizeof(ss));
255 
256 	switch (alen) {
257 	case 4: {
258 		struct sockaddr_in *sin = (void *)&ss;
259 		sin->sin_family = AF_INET;
260 		memcpy(&sin->sin_addr, addr, sizeof(sin->sin_addr));
261 		break;
262 	}
263 	case 16: {
264 		struct sockaddr_in6 *sin6 = (void *)&ss;
265 		sin6->sin6_family = AF_INET6;
266 		memcpy(&sin6->sin6_addr, addr, sizeof(sin6->sin6_addr));
267 		break;
268 	}
269 	default:
270 		assert(false);
271 	}
272 	sockaddr_snprintf(buf, buflen, fmt, (const void *)&ss);
273 	if (mask && mask != NPF_NO_NETMASK) {
274 		const unsigned len = strlen(buf);
275 		snprintf(&buf[len], buflen - len, "/%u", mask);
276 	}
277 	return buf;
278 }
279 
280 static int
281 npfctl_table_type(const char *typename)
282 {
283 	static const struct tbltype_s {
284 		const char *	name;
285 		unsigned	type;
286 	} tbltypes[] = {
287 		{ "ipset",	NPF_TABLE_IPSET	},
288 		{ "lpm",	NPF_TABLE_LPM	},
289 		{ "const",	NPF_TABLE_CONST	},
290 		{ NULL,		0		}
291 	};
292 
293 	for (unsigned i = 0; tbltypes[i].name != NULL; i++) {
294 		if (strcmp(typename, tbltypes[i].name) == 0) {
295 			return tbltypes[i].type;
296 		}
297 	}
298 	return 0;
299 }
300 
301 static void
302 npfctl_table_replace(int fd, int argc, char **argv)
303 {
304 	const char *name, *newname, *path, *typename = NULL;
305 	int c, tid = -1;
306 	FILE *fp;
307 	nl_config_t *ncf;
308 	nl_table_t *t;
309 	u_int type = 0;
310 
311 	name = newname = argv[0];
312 	optind = 2;
313 	while ((c = getopt(argc, argv, "n:t:")) != -1) {
314 		switch (c) {
315 		case 't':
316 			typename = optarg;
317 			break;
318 		case 'n':
319 			newname = optarg;
320 			break;
321 		default:
322 			fprintf(stderr,
323 			    "Usage: %s table \"table-name\" replace "
324 			    "[-n \"name\"] [-t <type>] <table-file>\n",
325 			    getprogname());
326 			exit(EXIT_FAILURE);
327 		}
328 	}
329 	argc -= optind;
330 	argv += optind;
331 
332 	if (typename && (type = npfctl_table_type(typename)) == 0) {
333 		errx(EXIT_FAILURE, "unsupported table type '%s'", typename);
334 	}
335 
336 	if (argc != 1) {
337 		usage();
338 	}
339 
340 	path = argv[0];
341 	if (strcmp(path, "-") == 0) {
342 		path = "stdin";
343 		fp = stdin;
344 	} else if ((fp = fopen(path, "r")) == NULL) {
345 		err(EXIT_FAILURE, "open '%s'", path);
346 	}
347 
348 	/* Get existing config to lookup ID of existing table */
349 	if ((ncf = npf_config_retrieve(fd)) == NULL) {
350 		err(EXIT_FAILURE, "npf_config_retrieve()");
351 	}
352 	if ((t = npfctl_table_getbyname(ncf, name)) == NULL) {
353 		errx(EXIT_FAILURE,
354 		    "table '%s' not found in the active configuration", name);
355 	}
356 	tid = npf_table_getid(t);
357 	if (!type) {
358 		type = npf_table_gettype(t);
359 	}
360 	npf_config_destroy(ncf);
361 
362 	if ((t = npfctl_load_table(newname, tid, type, path, fp)) == NULL) {
363 		err(EXIT_FAILURE, "table load failed");
364 	}
365 
366 	if (npf_table_replace(fd, t, NULL)) {
367 		err(EXIT_FAILURE, "npf_table_replace(<%s>)", name);
368 	}
369 }
370 
371 static void
372 npfctl_table(int fd, int argc, char **argv)
373 {
374 	static const struct tblops_s {
375 		const char *	cmd;
376 		int		action;
377 	} tblops[] = {
378 		{ "add",	NPF_CMD_TABLE_ADD		},
379 		{ "rem",	NPF_CMD_TABLE_REMOVE		},
380 		{ "del",	NPF_CMD_TABLE_REMOVE		},
381 		{ "test",	NPF_CMD_TABLE_LOOKUP		},
382 		{ "list",	NPF_CMD_TABLE_LIST		},
383 		{ "flush",	NPF_CMD_TABLE_FLUSH		},
384 		{ NULL,		0				}
385 	};
386 	npf_ioctl_table_t nct;
387 	fam_addr_mask_t fam;
388 	size_t buflen = 512;
389 	char *cmd, *arg;
390 	int n, alen;
391 
392 	/* Default action is list. */
393 	memset(&nct, 0, sizeof(npf_ioctl_table_t));
394 	nct.nct_name = argv[0];
395 	cmd = argv[1];
396 
397 	for (n = 0; tblops[n].cmd != NULL; n++) {
398 		if (strcmp(cmd, tblops[n].cmd) != 0) {
399 			continue;
400 		}
401 		nct.nct_cmd = tblops[n].action;
402 		break;
403 	}
404 	if (tblops[n].cmd == NULL) {
405 		errx(EXIT_FAILURE, "invalid command '%s'", cmd);
406 	}
407 
408 	switch (nct.nct_cmd) {
409 	case NPF_CMD_TABLE_LIST:
410 	case NPF_CMD_TABLE_FLUSH:
411 		arg = NULL;
412 		break;
413 	default:
414 		if (argc < 3) {
415 			usage();
416 		}
417 		arg = argv[2];
418 	}
419 
420 again:
421 	switch (nct.nct_cmd) {
422 	case NPF_CMD_TABLE_LIST:
423 		nct.nct_data.buf.buf = ecalloc(1, buflen);
424 		nct.nct_data.buf.len = buflen;
425 		break;
426 	case NPF_CMD_TABLE_FLUSH:
427 		break;
428 	default:
429 		if (!npfctl_parse_cidr(arg, &fam, &alen)) {
430 			errx(EXIT_FAILURE, "invalid CIDR '%s'", arg);
431 		}
432 		nct.nct_data.ent.alen = alen;
433 		memcpy(&nct.nct_data.ent.addr, &fam.fam_addr, alen);
434 		nct.nct_data.ent.mask = fam.fam_mask;
435 	}
436 
437 	if (ioctl(fd, IOC_NPF_TABLE, &nct) != -1) {
438 		errno = 0;
439 	}
440 	switch (errno) {
441 	case 0:
442 		break;
443 	case EEXIST:
444 		errx(EXIT_FAILURE, "entry already exists or is conflicting");
445 	case ENOENT:
446 		errx(EXIT_FAILURE, "not found");
447 	case EINVAL:
448 		errx(EXIT_FAILURE, "invalid address, mask or table ID");
449 	case ENOMEM:
450 		if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
451 			/* XXX */
452 			free(nct.nct_data.buf.buf);
453 			buflen <<= 1;
454 			goto again;
455 		}
456 		/* FALLTHROUGH */
457 	default:
458 		err(EXIT_FAILURE, "ioctl(IOC_NPF_TABLE)");
459 	}
460 
461 	if (nct.nct_cmd == NPF_CMD_TABLE_LIST) {
462 		npf_ioctl_ent_t *ent = nct.nct_data.buf.buf;
463 		char *buf;
464 
465 		while (nct.nct_data.buf.len--) {
466 			if (!ent->alen)
467 				break;
468 			buf = npfctl_print_addrmask(ent->alen, "%a",
469 			    &ent->addr, ent->mask);
470 			puts(buf);
471 			ent++;
472 		}
473 		free(nct.nct_data.buf.buf);
474 	} else {
475 		printf("%s: %s\n", getprogname(),
476 		    nct.nct_cmd == NPF_CMD_TABLE_LOOKUP ?
477 		    "match" : "success");
478 	}
479 }
480 
481 static nl_rule_t *
482 npfctl_parse_rule(int argc, char **argv, parse_entry_t entry)
483 {
484 	char rule_string[1024];
485 	nl_rule_t *rl;
486 
487 	/* Get the rule string and parse it. */
488 	if (!join(rule_string, sizeof(rule_string), argc, argv, " ")) {
489 		errx(EXIT_FAILURE, "command too long");
490 	}
491 	npfctl_parse_string(rule_string, entry);
492 	if ((rl = npfctl_rule_ref()) == NULL) {
493 		errx(EXIT_FAILURE, "could not parse the rule");
494 	}
495 	return rl;
496 }
497 
498 #ifdef __NetBSD__
499 static unsigned char *
500 SHA1(const unsigned char *d, size_t l, unsigned char *md)
501 {
502 	SHA1_CTX c;
503 
504 	SHA1Init(&c);
505 	SHA1Update(&c, d, l);
506 	SHA1Final(md, &c);
507 	return md;
508 }
509 #endif
510 
511 static void
512 npfctl_generate_key(nl_rule_t *rl, void *key)
513 {
514 	void *meta;
515 	size_t len;
516 
517 	if ((meta = npf_rule_export(rl, &len)) == NULL) {
518 		errx(EXIT_FAILURE, "error generating rule key");
519 	}
520 	__CTASSERT(NPF_RULE_MAXKEYLEN >= SHA_DIGEST_LENGTH);
521 	memset(key, 0, NPF_RULE_MAXKEYLEN);
522 	SHA1(meta, len, key);
523 	free(meta);
524 }
525 
526 int
527 npfctl_nat_ruleset_p(const char *name, bool *natset)
528 {
529 	const size_t preflen = sizeof(NPF_RULESET_MAP_PREF) - 1;
530 	*natset = strncmp(name, NPF_RULESET_MAP_PREF, preflen) == 0;
531 	return (*natset && strlen(name) <= preflen) ? -1 : 0;
532 }
533 
534 static void
535 npfctl_rule(int fd, int argc, char **argv)
536 {
537 	static const struct ruleops_s {
538 		const char *	cmd;
539 		int		action;
540 		bool		extra_arg;
541 	} ruleops[] = {
542 		{ "add",	NPF_CMD_RULE_ADD,	true	},
543 		{ "rem",	NPF_CMD_RULE_REMKEY,	true	},
544 		{ "del",	NPF_CMD_RULE_REMKEY,	true	},
545 		{ "rem-id",	NPF_CMD_RULE_REMOVE,	true	},
546 		{ "list",	NPF_CMD_RULE_LIST,	false	},
547 		{ "flush",	NPF_CMD_RULE_FLUSH,	false	},
548 		{ NULL,		0,			0	}
549 	};
550 	uint8_t key[NPF_RULE_MAXKEYLEN];
551 	const char *ruleset_name = argv[0];
552 	const char *cmd = argv[1];
553 	int error, action = 0;
554 	bool extra_arg, natset;
555 	parse_entry_t entry;
556 	uint64_t rule_id;
557 	nl_rule_t *rl;
558 
559 	for (unsigned n = 0; ruleops[n].cmd != NULL; n++) {
560 		if (strcmp(cmd, ruleops[n].cmd) == 0) {
561 			action = ruleops[n].action;
562 			extra_arg = ruleops[n].extra_arg;
563 			break;
564 		}
565 	}
566 	argc -= 2;
567 	argv += 2;
568 
569 	if (!action || (extra_arg && argc == 0)) {
570 		usage();
571 	}
572 
573 	if (npfctl_nat_ruleset_p(ruleset_name, &natset) != 0) {
574 		errx(EXIT_FAILURE,
575 		    "invalid NAT ruleset name (note: the name must be "
576 		    "prefixed with `" NPF_RULESET_MAP_PREF "`)");
577 	}
578 	entry = natset ? NPFCTL_PARSE_MAP : NPFCTL_PARSE_RULE;
579 
580 	switch (action) {
581 	case NPF_CMD_RULE_ADD:
582 		rl = npfctl_parse_rule(argc, argv, entry);
583 		npfctl_generate_key(rl, key);
584 		npf_rule_setkey(rl, key, sizeof(key));
585 		error = npf_ruleset_add(fd, ruleset_name, rl, &rule_id);
586 		break;
587 	case NPF_CMD_RULE_REMKEY:
588 		rl = npfctl_parse_rule(argc, argv, entry);
589 		npfctl_generate_key(rl, key);
590 		error = npf_ruleset_remkey(fd, ruleset_name, key, sizeof(key));
591 		break;
592 	case NPF_CMD_RULE_REMOVE:
593 		rule_id = strtoull(argv[0], NULL, 16);
594 		error = npf_ruleset_remove(fd, ruleset_name, rule_id);
595 		break;
596 	case NPF_CMD_RULE_LIST:
597 		error = npfctl_ruleset_show(fd, ruleset_name);
598 		break;
599 	case NPF_CMD_RULE_FLUSH:
600 		error = npf_ruleset_flush(fd, ruleset_name);
601 		break;
602 	default:
603 		abort();
604 	}
605 
606 	switch (error) {
607 	case 0:
608 		/* Success. */
609 		break;
610 	case ESRCH:
611 		errx(EXIT_FAILURE, "ruleset \"%s\" not found", ruleset_name);
612 	case ENOENT:
613 		errx(EXIT_FAILURE, "rule was not found");
614 	default:
615 		errx(EXIT_FAILURE, "rule operation: %s", strerror(error));
616 	}
617 	if (action == NPF_CMD_RULE_ADD) {
618 		printf("OK %" PRIx64 "\n", rule_id);
619 	}
620 }
621 
622 static bool bpfjit = true;
623 
624 void
625 npfctl_bpfjit(bool onoff)
626 {
627 	bpfjit = onoff;
628 }
629 
630 static void
631 npfctl_preload_bpfjit(void)
632 {
633 #ifdef __NetBSD__
634 	modctl_load_t args = {
635 		.ml_filename = "bpfjit",
636 		.ml_flags = MODCTL_NO_PROP,
637 		.ml_props = NULL,
638 		.ml_propslen = 0
639 	};
640 
641 	if (!bpfjit)
642 		return;
643 
644 	if (modctl(MODCTL_LOAD, &args) != 0 && errno != EEXIST) {
645 		static const char *p = "; performance will be degraded";
646 		if (errno == ENOENT)
647 			warnx("the bpfjit module seems to be missing%s", p);
648 		else
649 			warn("error loading the bpfjit module%s", p);
650 		warnx("To disable this warning `set bpf.jit off' in "
651 		    "/etc/npf.conf");
652 	}
653 #endif
654 }
655 
656 static int
657 npfctl_load(int fd)
658 {
659 	nl_config_t *ncf;
660 	npf_error_t errinfo;
661 	struct stat sb;
662 	size_t blen;
663 	void *blob;
664 	int error;
665 
666 	/*
667 	 * The file may change while reading - we are not handling this,
668 	 * leaving this responsibility for the caller.
669 	 */
670 	if (stat(NPF_DB_PATH, &sb) == -1) {
671 		err(EXIT_FAILURE, "stat");
672 	}
673 	if ((blen = sb.st_size) == 0) {
674 		err(EXIT_FAILURE, "saved configuration file is empty");
675 	}
676 	if ((blob = mmap(NULL, blen, PROT_READ,
677 	    MAP_FILE | MAP_PRIVATE, fd, 0)) == MAP_FAILED) {
678 		err(EXIT_FAILURE, "mmap");
679 	}
680 	ncf = npf_config_import(blob, blen);
681 	munmap(blob, blen);
682 	if (ncf == NULL) {
683 		return errno;
684 	}
685 
686 	/*
687 	 * Configuration imported - submit it now.
688 	 **/
689 	errno = error = npf_config_submit(ncf, fd, &errinfo);
690 	if (error) {
691 		npfctl_print_error(&errinfo);
692 	}
693 	npf_config_destroy(ncf);
694 	return error;
695 }
696 
697 struct npf_conn_filter {
698 	uint16_t	alen;
699 	const char *	ifname;
700 	bool		nat;
701 	bool		wide;
702 	bool		name;
703 	int		width;
704 	FILE *		fp;
705 };
706 
707 static int
708 npfctl_conn_print(unsigned alen, const npf_addr_t *a, const in_port_t *p,
709     const char *ifname, void *v)
710 {
711 	struct npf_conn_filter *fil = v;
712 	FILE *fp = fil->fp;
713 	char *src, *dst;
714 
715 	if (fil->ifname && strcmp(ifname, fil->ifname) != 0)
716 		return 0;
717 	if (fil->alen && alen != fil->alen)
718 		return 0;
719 	if (fil->nat && !p[2])
720 		return 0;
721 
722 	int w = fil->width;
723 	const char *fmt = fil->name ? "%A" :
724 	    (alen == sizeof(struct in_addr) ? "%a" : "[%a]");
725 	src = npfctl_print_addrmask(alen, fmt, &a[0], NPF_NO_NETMASK);
726 	dst = npfctl_print_addrmask(alen, fmt, &a[1], NPF_NO_NETMASK);
727 
728 	if (fil->wide) {
729 		fprintf(fp, "%s:%d %s:%d", src, p[0], dst, p[1]);
730 	} else {
731 		fprintf(fp, "%*.*s:%-5d %*.*s:%-5d", w, w, src, p[0],
732 		    w, w, dst, p[1]);
733 	}
734 	free(src);
735 	free(dst);
736 	if (!p[2]) {
737 		fputc('\n', fp);
738 		return 1;
739 	}
740 	fprintf(fp, " via %s:%d\n", ifname, p[2]);
741 	return 1;
742 }
743 
744 static int
745 npfctl_conn_list(int fd, int argc, char **argv)
746 {
747 	struct npf_conn_filter f;
748 	int c, w, header = true;
749 
750 	memset(&f, 0, sizeof(f));
751 	argc--;
752 	argv++;
753 
754 	while ((c = getopt(argc, argv, "46hi:nNw")) != -1) {
755 		switch (c) {
756 		case '4':
757 			f.alen = sizeof(struct in_addr);
758 			break;
759 		case '6':
760 			f.alen = sizeof(struct in6_addr);
761 			break;
762 		case 'h':
763 			header = false;
764 			break;
765 		case 'i':
766 			f.ifname = optarg;
767 			break;
768 		case 'n':
769 			f.nat = true;
770 			break;
771 		case 'N':
772 			f.name = true;
773 			break;
774 		case 'w':
775 			f.wide = true;
776 			break;
777 		default:
778 			fprintf(stderr,
779 			    "Usage: %s list [-46hnNw] [-i <ifname>]\n",
780 			    getprogname());
781 			exit(EXIT_FAILURE);
782 		}
783 	}
784 	f.width = f.alen == sizeof(struct in_addr) ? 25 : 41;
785 	w = f.width + 6;
786 	f.fp = stdout;
787 
788 	if (header) {
789 		fprintf(f.fp, "%*.*s %*.*s\n",
790 		    w, w, "From address:port ", w, w, "To address:port ");
791 	}
792 	npf_conn_list(fd, npfctl_conn_print, &f);
793 	return 0;
794 }
795 
796 static int
797 npfctl_open_dev(const char *path)
798 {
799 	int fd, kernver;
800 
801 	fd = open(path, O_RDONLY);
802 	if (fd == -1) {
803 		err(EXIT_FAILURE, "cannot open '%s'", path);
804 	}
805 	if (ioctl(fd, IOC_NPF_VERSION, &kernver) == -1) {
806 		err(EXIT_FAILURE, "ioctl(IOC_NPF_VERSION)");
807 	}
808 	if (kernver != NPF_VERSION) {
809 		errx(EXIT_FAILURE,
810 		    "incompatible NPF interface version (%d, kernel %d)\n"
811 		    "Hint: update %s?", NPF_VERSION, kernver,
812 		    kernver > NPF_VERSION ? "userland" : "kernel");
813 	}
814 	return fd;
815 }
816 
817 static void
818 npfctl(int action, int argc, char **argv)
819 {
820 	int fd, boolval, ret = 0;
821 	const char *fun = "";
822 	nl_config_t *ncf;
823 
824 	switch (action) {
825 	case NPFCTL_VALIDATE:
826 	case NPFCTL_DEBUG:
827 		fd = 0;
828 		break;
829 	default:
830 		fd = npfctl_open_dev(NPF_DEV_PATH);
831 	}
832 
833 	switch (action) {
834 	case NPFCTL_START:
835 		boolval = true;
836 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
837 		fun = "ioctl(IOC_NPF_SWITCH)";
838 		break;
839 	case NPFCTL_STOP:
840 		boolval = false;
841 		ret = ioctl(fd, IOC_NPF_SWITCH, &boolval);
842 		fun = "ioctl(IOC_NPF_SWITCH)";
843 		break;
844 	case NPFCTL_RELOAD:
845 		npfctl_config_init(false);
846 		npfctl_parse_file(argc < 3 ? NPF_CONF_PATH : argv[2]);
847 		npfctl_preload_bpfjit();
848 		errno = ret = npfctl_config_send(fd);
849 		fun = "npfctl_config_send";
850 		break;
851 	case NPFCTL_SHOWCONF:
852 		ret = npfctl_config_show(fd);
853 		fun = "npfctl_config_show";
854 		break;
855 	case NPFCTL_FLUSH:
856 		ret = npf_config_flush(fd);
857 		fun = "npf_config_flush";
858 		break;
859 	case NPFCTL_TABLE:
860 		if ((argc -= 2) < 2) {
861 			usage();
862 		}
863 		argv += 2;
864 		if (strcmp(argv[1], "replace") == 0) {
865 			npfctl_table_replace(fd, argc, argv);
866 		} else {
867 			npfctl_table(fd, argc, argv);
868 		}
869 		break;
870 	case NPFCTL_RULE:
871 		if ((argc -= 2) < 2) {
872 			usage();
873 		}
874 		argv += 2;
875 		npfctl_rule(fd, argc, argv);
876 		break;
877 	case NPFCTL_LOAD:
878 		npfctl_preload_bpfjit();
879 		ret = npfctl_load(fd);
880 		fun = "npfctl_config_load";
881 		break;
882 	case NPFCTL_SAVE:
883 		ncf = npf_config_retrieve(fd);
884 		if (ncf) {
885 			npfctl_config_save(ncf, NPF_DB_PATH);
886 			npf_config_destroy(ncf);
887 		} else {
888 			ret = errno;
889 		}
890 		fun = "npfctl_config_save";
891 		break;
892 	case NPFCTL_STATS:
893 		ret = npfctl_print_stats(fd);
894 		fun = "npfctl_print_stats";
895 		break;
896 	case NPFCTL_CONN_LIST:
897 		ret = npfctl_conn_list(fd, argc, argv);
898 		fun = "npfctl_conn_list";
899 		break;
900 	case NPFCTL_VALIDATE:
901 		npfctl_config_init(false);
902 		npfctl_parse_file(argc > 2 ? argv[2] : NPF_CONF_PATH);
903 		ret = npfctl_config_show(0);
904 		fun = "npfctl_config_show";
905 		break;
906 	case NPFCTL_DEBUG:
907 		npfctl_config_init(true);
908 		npfctl_parse_file(argc > 2 ? argv[2] : NPF_CONF_PATH);
909 		npfctl_config_debug(argc > 3 ? argv[3] : "/tmp/npf.nvlist");
910 		break;
911 	}
912 	if (ret) {
913 		err(EXIT_FAILURE, "%s", fun);
914 	}
915 	if (fd) {
916 		close(fd);
917 	}
918 }
919 
920 int
921 main(int argc, char **argv)
922 {
923 	char *cmd;
924 
925 	if (argc < 2) {
926 		usage();
927 	}
928 	npfctl_show_init();
929 	cmd = argv[1];
930 
931 	/* Find and call the subroutine. */
932 	for (int n = 0; operations[n].cmd != NULL; n++) {
933 		const char *opcmd = operations[n].cmd;
934 		if (strncmp(cmd, opcmd, strlen(opcmd)) != 0)
935 			continue;
936 		npfctl(operations[n].action, argc, argv);
937 		return EXIT_SUCCESS;
938 	}
939 	usage();
940 }
941