nft.c 72.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/*
 * (C) 2012 by Pablo Neira Ayuso <pablo@netfilter.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published
 * by the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This code has been sponsored by Sophos Astaro <http://www.sophos.com>
 */

#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdbool.h>
#include <errno.h>
#include <netdb.h>	/* getprotobynumber */
#include <time.h>
#include <stdarg.h>
#include <inttypes.h>
22
#include <assert.h>
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

#include <xtables.h>
#include <libiptc/libxtc.h>
#include <libiptc/xtcshared.h>

#include <stdlib.h>
#include <string.h>

#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter_ipv6/ip6_tables.h>
#include <netinet/ip6.h>

#include <linux/netlink.h>
#include <linux/netfilter/nfnetlink.h>
#include <linux/netfilter/nf_tables.h>
#include <linux/netfilter/nf_tables_compat.h>

41
42
#include <linux/netfilter/xt_limit.h>

43
44
45
46
47
48
#include <libmnl/libmnl.h>
#include <libnftnl/table.h>
#include <libnftnl/chain.h>
#include <libnftnl/rule.h>
#include <libnftnl/expr.h>
#include <libnftnl/set.h>
49
#include <libnftnl/udata.h>
50
#include <libnftnl/batch.h>
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66

#include <netinet/in.h>	/* inet_ntoa */
#include <arpa/inet.h>

#include "nft.h"
#include "xshared.h" /* proto_to_name */
#include "nft-shared.h"
#include "xtables-config-parser.h"

static void *nft_fn;

int mnl_talk(struct nft_handle *h, struct nlmsghdr *nlh,
	     int (*cb)(const struct nlmsghdr *nlh, void *data),
	     void *data)
{
	int ret;
67
	char buf[16536];
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86

	if (mnl_socket_sendto(h->nl, nlh, nlh->nlmsg_len) < 0)
		return -1;

	ret = mnl_socket_recvfrom(h->nl, buf, sizeof(buf));
	while (ret > 0) {
		ret = mnl_cb_run(buf, ret, h->seq, h->portid, cb, data);
		if (ret <= 0)
			break;

		ret = mnl_socket_recvfrom(h->nl, buf, sizeof(buf));
	}
	if (ret == -1) {
		return -1;
	}

	return 0;
}

87
#define NFT_NLMSG_MAXSIZE (UINT16_MAX + getpagesize())
88
89
90
91
92
93
94

/* selected batch page is 256 Kbytes long to load ruleset of
 * half a million rules without hitting -EMSGSIZE due to large
 * iovec.
 */
#define BATCH_PAGE_SIZE getpagesize() * 32

95
static struct nftnl_batch *mnl_batch_init(void)
96
{
97
	struct nftnl_batch *batch;
98

99
100
	batch = nftnl_batch_alloc(BATCH_PAGE_SIZE, NFT_NLMSG_MAXSIZE);
	if (batch == NULL)
101
102
		return NULL;

103
	return batch;
104
105
}

106
static void mnl_nft_batch_continue(struct nftnl_batch *batch)
107
{
108
109
	assert(nftnl_batch_update(batch) >= 0);
}
110

111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
static uint32_t mnl_batch_begin(struct nftnl_batch *batch, uint32_t seqnum)
{
	nftnl_batch_begin(nftnl_batch_buffer(batch), seqnum);
	mnl_nft_batch_continue(batch);

	return seqnum;
}

static void mnl_batch_end(struct nftnl_batch *batch, uint32_t seqnum)
{
	nftnl_batch_end(nftnl_batch_buffer(batch), seqnum);
	mnl_nft_batch_continue(batch);
}

static void mnl_batch_reset(struct nftnl_batch *batch)
{
	nftnl_batch_free(batch);
}
129

130
131
132
133
134
135
136
137
138
139
struct mnl_err {
	struct list_head	head;
	int			err;
	uint32_t		seqnum;
};

static void mnl_err_list_node_add(struct list_head *err_list, int error,
				  int seqnum)
{
	struct mnl_err *err = malloc(sizeof(struct mnl_err));
140

141
142
143
144
145
146
147
148
149
	err->seqnum = seqnum;
	err->err = error;
	list_add_tail(&err->head, err_list);
}

static void mnl_err_list_free(struct mnl_err *err)
{
	list_del(&err->head);
	free(err);
150
151
152
153
}

static int nlbuffsiz;

154
155
static void mnl_set_sndbuffer(const struct mnl_socket *nl,
			      struct nftnl_batch *batch)
156
157
158
{
	int newbuffsiz;

159
	if (nftnl_batch_iovec_len(batch) * BATCH_PAGE_SIZE <= nlbuffsiz)
160
161
		return;

162
	newbuffsiz = nftnl_batch_iovec_len(batch) * BATCH_PAGE_SIZE;
163
164
165
166
167
168
169
170
171

	/* Rise sender buffer length to avoid hitting -EMSGSIZE */
	if (setsockopt(mnl_socket_get_fd(nl), SOL_SOCKET, SO_SNDBUFFORCE,
		       &newbuffsiz, sizeof(socklen_t)) < 0)
		return;

	nlbuffsiz = newbuffsiz;
}

172
173
static ssize_t mnl_nft_socket_sendmsg(const struct mnl_socket *nf_sock,
				      struct nftnl_batch *batch)
174
175
176
177
{
	static const struct sockaddr_nl snl = {
		.nl_family = AF_NETLINK
	};
178
179
	uint32_t iov_len = nftnl_batch_iovec_len(batch);
	struct iovec iov[iov_len];
180
181
182
183
	struct msghdr msg = {
		.msg_name	= (struct sockaddr *) &snl,
		.msg_namelen	= sizeof(snl),
		.msg_iov	= iov,
184
		.msg_iovlen	= iov_len,
185
186
	};

187
188
	mnl_set_sndbuffer(nf_sock, batch);
	nftnl_batch_iovec(batch, iov, iov_len);
189

190
	return sendmsg(mnl_socket_get_fd(nf_sock), &msg, 0);
191
192
}

193
194
static int mnl_batch_talk(const struct mnl_socket *nf_sock,
			  struct nftnl_batch *batch, struct list_head *err_list)
195
{
196
197
	const struct mnl_socket *nl = nf_sock;
	int ret, fd = mnl_socket_get_fd(nl), portid = mnl_socket_get_portid(nl);
198
199
200
201
202
203
204
205
	char rcv_buf[MNL_SOCKET_BUFFER_SIZE];
	fd_set readfds;
	struct timeval tv = {
		.tv_sec		= 0,
		.tv_usec	= 0
	};
	int err = 0;

206
	ret = mnl_nft_socket_sendmsg(nf_sock, batch);
207
208
209
210
211
212
213
214
215
216
217
218
	if (ret == -1)
		return -1;

	FD_ZERO(&readfds);
	FD_SET(fd, &readfds);

	/* receive and digest all the acknowledgments from the kernel. */
	ret = select(fd+1, &readfds, NULL, NULL, &tv);
	if (ret == -1)
		return -1;

	while (ret > 0 && FD_ISSET(fd, &readfds)) {
219
220
221
		struct nlmsghdr *nlh = (struct nlmsghdr *)rcv_buf;

		ret = mnl_socket_recvfrom(nl, rcv_buf, sizeof(rcv_buf));
222
223
224
		if (ret == -1)
			return -1;

225
226
227
228
229
230
		ret = mnl_cb_run(rcv_buf, ret, 0, portid, NULL, NULL);
		/* Continue on error, make sure we get all acknowledgments */
		if (ret == -1) {
			mnl_err_list_node_add(err_list, errno, nlh->nlmsg_seq);
			err = -1;
		}
231
232
233
234
235
236
237
238

		ret = select(fd+1, &readfds, NULL, NULL, &tv);
		if (ret == -1)
			return -1;

		FD_ZERO(&readfds);
		FD_SET(fd, &readfds);
	}
239
	return err;
240
241
242
243
}

enum obj_update_type {
	NFT_COMPAT_TABLE_ADD,
244
	NFT_COMPAT_TABLE_FLUSH,
245
246
247
	NFT_COMPAT_CHAIN_ADD,
	NFT_COMPAT_CHAIN_USER_ADD,
	NFT_COMPAT_CHAIN_USER_DEL,
248
	NFT_COMPAT_CHAIN_USER_FLUSH,
249
250
	NFT_COMPAT_CHAIN_UPDATE,
	NFT_COMPAT_CHAIN_RENAME,
251
	NFT_COMPAT_CHAIN_ZERO,
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
	NFT_COMPAT_RULE_APPEND,
	NFT_COMPAT_RULE_INSERT,
	NFT_COMPAT_RULE_REPLACE,
	NFT_COMPAT_RULE_DELETE,
	NFT_COMPAT_RULE_FLUSH,
};

enum obj_action {
	NFT_COMPAT_COMMIT,
	NFT_COMPAT_ABORT,
};

struct obj_update {
	struct list_head	head;
	enum obj_update_type	type;
267
	unsigned int		seq;
268
269
270
	union {
		struct nftnl_table	*table;
		struct nftnl_chain	*chain;
271
		struct nftnl_rule	*rule;
272
273
		void			*ptr;
	};
274
275
276
	struct {
		unsigned int		lineno;
	} error;
277
278
};

279
280
281
282
283
284
285
286
287
288
289
290
291
292
static int mnl_append_error(const struct nft_handle *h,
			    const struct obj_update *o,
			    const struct mnl_err *err,
			    char *buf, unsigned int len)
{
	static const char *type_name[] = {
		[NFT_COMPAT_TABLE_ADD] = "TABLE_ADD",
		[NFT_COMPAT_TABLE_FLUSH] = "TABLE_FLUSH",
		[NFT_COMPAT_CHAIN_ADD] = "CHAIN_ADD",
		[NFT_COMPAT_CHAIN_USER_ADD] = "CHAIN_USER_ADD",
		[NFT_COMPAT_CHAIN_USER_DEL] = "CHAIN_USER_DEL",
		[NFT_COMPAT_CHAIN_USER_FLUSH] = "CHAIN_USER_FLUSH",
		[NFT_COMPAT_CHAIN_UPDATE] = "CHAIN_UPDATE",
		[NFT_COMPAT_CHAIN_RENAME] = "CHAIN_RENAME",
293
		[NFT_COMPAT_CHAIN_ZERO] = "CHAIN_ZERO",
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
		[NFT_COMPAT_RULE_APPEND] = "RULE_APPEND",
		[NFT_COMPAT_RULE_INSERT] = "RULE_INSERT",
		[NFT_COMPAT_RULE_REPLACE] = "RULE_REPLACE",
		[NFT_COMPAT_RULE_DELETE] = "RULE_DELETE",
		[NFT_COMPAT_RULE_FLUSH] = "RULE_FLUSH",
	};
	char errmsg[256];
	char tcr[128];

	if (o->error.lineno)
		snprintf(errmsg, sizeof(errmsg), "\nline %u: %s failed (%s)",
			 o->error.lineno, type_name[o->type], strerror(err->err));
	else
		snprintf(errmsg, sizeof(errmsg), " %s failed (%s)",
			 type_name[o->type], strerror(err->err));

	switch (o->type) {
	case NFT_COMPAT_TABLE_ADD:
	case NFT_COMPAT_TABLE_FLUSH:
		snprintf(tcr, sizeof(tcr), "table %s",
			 nftnl_table_get_str(o->table, NFTNL_TABLE_NAME));
		break;
	case NFT_COMPAT_CHAIN_ADD:
317
	case NFT_COMPAT_CHAIN_ZERO:
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
	case NFT_COMPAT_CHAIN_USER_ADD:
	case NFT_COMPAT_CHAIN_USER_DEL:
	case NFT_COMPAT_CHAIN_USER_FLUSH:
	case NFT_COMPAT_CHAIN_UPDATE:
	case NFT_COMPAT_CHAIN_RENAME:
		snprintf(tcr, sizeof(tcr), "chain %s",
			 nftnl_chain_get_str(o->chain, NFTNL_CHAIN_NAME));
		break;
	case NFT_COMPAT_RULE_APPEND:
	case NFT_COMPAT_RULE_INSERT:
	case NFT_COMPAT_RULE_REPLACE:
	case NFT_COMPAT_RULE_DELETE:
	case NFT_COMPAT_RULE_FLUSH:
		snprintf(tcr, sizeof(tcr), "rule in chain %s",
			 nftnl_rule_get_str(o->rule, NFTNL_RULE_CHAIN));
#if 0
		{
335
			nft_rule_print_save(o->rule, NFT_RULE_APPEND, FMT_NOCOUNTS);
336
337
338
339
340
341
342
343
		}
#endif
		break;
	}

	return snprintf(buf, len, "%s: %s", errmsg, tcr);
}

344
345
346
347
348
349
350
351
352
static int batch_add(struct nft_handle *h, enum obj_update_type type, void *ptr)
{
	struct obj_update *obj;

	obj = calloc(1, sizeof(struct obj_update));
	if (obj == NULL)
		return -1;

	obj->ptr = ptr;
353
	obj->error.lineno = h->error.lineno;
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
	obj->type = type;
	list_add_tail(&obj->head, &h->obj_list);
	h->obj_list_num++;

	return 0;
}

static int batch_table_add(struct nft_handle *h, enum obj_update_type type,
			   struct nftnl_table *t)
{
	return batch_add(h, type, t);
}

static int batch_chain_add(struct nft_handle *h, enum obj_update_type type,
			   struct nftnl_chain *c)
{
	return batch_add(h, type, c);
}

static int batch_rule_add(struct nft_handle *h, enum obj_update_type type,
			  struct nftnl_rule *r)
{
	return batch_add(h, type, r);
}

379
380
struct builtin_table xtables_ipv4[NFT_TABLE_MAX] = {
	[NFT_TABLE_RAW] = {
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
		.name	= "raw",
		.chains = {
			{
				.name	= "PREROUTING",
				.type	= "filter",
				.prio	= -300,	/* NF_IP_PRI_RAW */
				.hook	= NF_INET_PRE_ROUTING,
			},
			{
				.name	= "OUTPUT",
				.type	= "filter",
				.prio	= -300,	/* NF_IP_PRI_RAW */
				.hook	= NF_INET_LOCAL_OUT,
			},
		},
	},
397
	[NFT_TABLE_MANGLE] = {
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
		.name	= "mangle",
		.chains = {
			{
				.name	= "PREROUTING",
				.type	= "filter",
				.prio	= -150,	/* NF_IP_PRI_MANGLE */
				.hook	= NF_INET_PRE_ROUTING,
			},
			{
				.name	= "INPUT",
				.type	= "filter",
				.prio	= -150,	/* NF_IP_PRI_MANGLE */
				.hook	= NF_INET_LOCAL_IN,
			},
			{
				.name	= "FORWARD",
				.type	= "filter",
				.prio	= -150,	/* NF_IP_PRI_MANGLE */
				.hook	= NF_INET_FORWARD,
			},
			{
				.name	= "OUTPUT",
				.type	= "route",
				.prio	= -150,	/* NF_IP_PRI_MANGLE */
				.hook	= NF_INET_LOCAL_OUT,
			},
			{
				.name	= "POSTROUTING",
				.type	= "filter",
				.prio	= -150,	/* NF_IP_PRI_MANGLE */
				.hook	= NF_INET_POST_ROUTING,
			},
		},
	},
432
	[NFT_TABLE_FILTER] = {
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
		.name	= "filter",
		.chains = {
			{
				.name	= "INPUT",
				.type	= "filter",
				.prio	= 0,	/* NF_IP_PRI_FILTER */
				.hook	= NF_INET_LOCAL_IN,
			},
			{
				.name	= "FORWARD",
				.type	= "filter",
				.prio	= 0,	/* NF_IP_PRI_FILTER */
				.hook	= NF_INET_FORWARD,
			},
			{
				.name	= "OUTPUT",
				.type	= "filter",
				.prio	= 0,	/* NF_IP_PRI_FILTER */
				.hook	= NF_INET_LOCAL_OUT,
			},
		},
	},
455
	[NFT_TABLE_SECURITY] = {
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
		.name	= "security",
		.chains = {
			{
				.name	= "INPUT",
				.type	= "filter",
				.prio	= 150,	/* NF_IP_PRI_SECURITY */
				.hook	= NF_INET_LOCAL_IN,
			},
			{
				.name	= "FORWARD",
				.type	= "filter",
				.prio	= 150,	/* NF_IP_PRI_SECURITY */
				.hook	= NF_INET_FORWARD,
			},
			{
				.name	= "OUTPUT",
				.type	= "filter",
				.prio	= 150,	/* NF_IP_PRI_SECURITY */
				.hook	= NF_INET_LOCAL_OUT,
			},
		},
	},
478
	[NFT_TABLE_NAT] = {
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
		.name	= "nat",
		.chains = {
			{
				.name	= "PREROUTING",
				.type	= "nat",
				.prio	= -100, /* NF_IP_PRI_NAT_DST */
				.hook	= NF_INET_PRE_ROUTING,
			},
			{
				.name	= "INPUT",
				.type	= "nat",
				.prio	= 100, /* NF_IP_PRI_NAT_SRC */
				.hook	= NF_INET_LOCAL_IN,
			},
			{
				.name	= "POSTROUTING",
				.type	= "nat",
				.prio	= 100, /* NF_IP_PRI_NAT_SRC */
				.hook	= NF_INET_POST_ROUTING,
			},
			{
				.name	= "OUTPUT",
				.type	= "nat",
				.prio	= -100, /* NF_IP_PRI_NAT_DST */
				.hook	= NF_INET_LOCAL_OUT,
			},
		},
	},
};

#include <linux/netfilter_arp.h>

511
512
struct builtin_table xtables_arp[NFT_TABLE_MAX] = {
	[NFT_TABLE_FILTER] = {
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
	.name   = "filter",
	.chains = {
			{
				.name   = "INPUT",
				.type   = "filter",
				.prio   = NF_IP_PRI_FILTER,
				.hook   = NF_ARP_IN,
			},
			{
				.name   = "OUTPUT",
				.type   = "filter",
				.prio   = NF_IP_PRI_FILTER,
				.hook   = NF_ARP_OUT,
			},
		},
	},
};

#include <linux/netfilter_bridge.h>

533
534
struct builtin_table xtables_bridge[NFT_TABLE_MAX] = {
	[NFT_TABLE_FILTER] = {
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
		.name = "filter",
		.chains = {
			{
				.name   = "INPUT",
				.type   = "filter",
				.prio   = NF_BR_PRI_FILTER_BRIDGED,
				.hook   = NF_BR_LOCAL_IN,
			},
			{
				.name   = "FORWARD",
				.type   = "filter",
				.prio   = NF_BR_PRI_FILTER_BRIDGED,
				.hook   = NF_BR_FORWARD,
			},
			{
				.name   = "OUTPUT",
				.type   = "filter",
				.prio   = NF_BR_PRI_FILTER_BRIDGED,
				.hook   = NF_BR_LOCAL_OUT,
			},
		},
	},
557
	[NFT_TABLE_NAT] = {
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
		.name = "nat",
		.chains = {
			{
				.name   = "PREROUTING",
				.type   = "filter",
				.prio   = NF_BR_PRI_NAT_DST_BRIDGED,
				.hook   = NF_BR_PRE_ROUTING,
			},
			{
				.name   = "OUTPUT",
				.type   = "filter",
				.prio   = NF_BR_PRI_NAT_DST_OTHER,
				.hook   = NF_BR_LOCAL_OUT,
			},
			{
				.name   = "POSTROUTING",
				.type   = "filter",
				.prio   = NF_BR_PRI_NAT_SRC,
				.hook   = NF_BR_POST_ROUTING,
			},
		},
	},
};

static int nft_table_builtin_add(struct nft_handle *h,
				 struct builtin_table *_t)
{
	struct nftnl_table *t;
	int ret;

	if (_t->initialized)
		return 0;

	t = nftnl_table_alloc();
	if (t == NULL)
		return -1;

	nftnl_table_set(t, NFTNL_TABLE_NAME, (char *)_t->name);

597
	ret = batch_table_add(h, NFT_COMPAT_TABLE_ADD, t);
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631

	return ret;
}

static struct nftnl_chain *
nft_chain_builtin_alloc(struct builtin_table *table,
			struct builtin_chain *chain, int policy)
{
	struct nftnl_chain *c;

	c = nftnl_chain_alloc();
	if (c == NULL)
		return NULL;

	nftnl_chain_set(c, NFTNL_CHAIN_TABLE, (char *)table->name);
	nftnl_chain_set(c, NFTNL_CHAIN_NAME, (char *)chain->name);
	nftnl_chain_set_u32(c, NFTNL_CHAIN_HOOKNUM, chain->hook);
	nftnl_chain_set_u32(c, NFTNL_CHAIN_PRIO, chain->prio);
	nftnl_chain_set_u32(c, NFTNL_CHAIN_POLICY, policy);
	nftnl_chain_set(c, NFTNL_CHAIN_TYPE, (char *)chain->type);

	return c;
}

static void nft_chain_builtin_add(struct nft_handle *h,
				  struct builtin_table *table,
				  struct builtin_chain *chain)
{
	struct nftnl_chain *c;

	c = nft_chain_builtin_alloc(table, chain, NF_ACCEPT);
	if (c == NULL)
		return;

632
	batch_chain_add(h, NFT_COMPAT_CHAIN_ADD, c);
633
634
635
}

/* find if built-in table already exists */
636
struct builtin_table *
637
638
639
640
641
nft_table_builtin_find(struct nft_handle *h, const char *table)
{
	int i;
	bool found = false;

642
	for (i = 0; i < NFT_TABLE_MAX; i++) {
643
644
645
646
647
648
649
650
651
652
653
654
655
656
		if (h->tables[i].name == NULL)
			continue;

		if (strcmp(h->tables[i].name, table) != 0)
			continue;

		found = true;
		break;
	}

	return found ? &h->tables[i] : NULL;
}

/* find if built-in chain already exists */
657
struct builtin_chain *
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
nft_chain_builtin_find(struct builtin_table *t, const char *chain)
{
	int i;
	bool found = false;

	for (i=0; i<NF_IP_NUMHOOKS && t->chains[i].name != NULL; i++) {
		if (strcmp(t->chains[i].name, chain) != 0)
			continue;

		found = true;
		break;
	}
	return found ? &t->chains[i] : NULL;
}

static void nft_chain_builtin_init(struct nft_handle *h,
				   struct builtin_table *table)
{
676
	struct nftnl_chain_list *list = nft_chain_list_get(h);
677
	struct nftnl_chain *c;
678
	int i;
679
680

	/* Initialize built-in chains if they don't exist yet */
681
	for (i=0; i < NF_INET_NUMHOOKS && table->chains[i].name != NULL; i++) {
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696

		c = nft_chain_list_find(list, table->name,
					table->chains[i].name);
		if (c != NULL)
			continue;

		nft_chain_builtin_add(h, table, &table->chains[i]);
	}
}

static int nft_xt_builtin_init(struct nft_handle *h, const char *table)
{
	struct builtin_table *t;

	t = nft_table_builtin_find(h, table);
697
698
699
700
701
702
703
704
705
	if (t == NULL)
		return -1;

	if (t->initialized)
		return 0;

	if (nft_table_builtin_add(h, t) < 0)
		return -1;

706
	nft_chain_builtin_init(h, t);
707
708
709
710

	t->initialized = true;

	return 0;
711
712
713
714
715
716
717
718
719
720
}

static bool nft_chain_builtin(struct nftnl_chain *c)
{
	/* Check if this chain has hook number, in that case is built-in.
	 * Should we better export the flags to user-space via nf_tables?
	 */
	return nftnl_chain_get(c, NFTNL_CHAIN_HOOKNUM) != NULL;
}

721
static int nft_restart(struct nft_handle *h)
722
{
723
	mnl_socket_close(h->nl);
724

725
726
727
	h->nl = mnl_socket_open(NETLINK_NETFILTER);
	if (h->nl == NULL)
		return -1;
728

729
730
	if (mnl_socket_bind(h->nl, 0, MNL_SOCKET_AUTOPID) < 0)
		return -1;
731

732
	h->portid = mnl_socket_get_portid(h->nl);
733

734
	return 0;
735
736
737
738
739
740
741
742
}

int nft_init(struct nft_handle *h, struct builtin_table *t)
{
	h->nl = mnl_socket_open(NETLINK_NETFILTER);
	if (h->nl == NULL)
		return -1;

743
744
	if (mnl_socket_bind(h->nl, 0, MNL_SOCKET_AUTOPID) < 0) {
		mnl_socket_close(h->nl);
745
		return -1;
746
	}
747
748
749
750
751

	h->portid = mnl_socket_get_portid(h->nl);
	h->tables = t;

	INIT_LIST_HEAD(&h->obj_list);
752
753
754
755
	INIT_LIST_HEAD(&h->err_list);

	return 0;
}
756

757
758
759
760
761
762
763
764
static int __flush_rule_cache(struct nftnl_rule *r, void *data)
{
	const char *tablename = data;

	if (!strcmp(nftnl_rule_get_str(r, NFTNL_RULE_TABLE), tablename)) {
		nftnl_rule_list_del(r);
		nftnl_rule_free(r);
	}
765
766
767
768

	return 0;
}

769
static void flush_rule_cache(struct nft_handle *h, const char *tablename)
770
771
772
773
{
	if (!h->rule_cache)
		return;

774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
	if (tablename) {
		nftnl_rule_list_foreach(h->rule_cache, __flush_rule_cache,
					(void *)tablename);
	} else {
		nftnl_rule_list_free(h->rule_cache);
		h->rule_cache = NULL;
	}
}

static int __flush_chain_cache(struct nftnl_chain *c, void *data)
{
	const char *tablename = data;

	if (!strcmp(nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE), tablename)) {
		nftnl_chain_list_del(c);
		nftnl_chain_free(c);
	}

	return 0;
}

static void flush_chain_cache(struct nft_handle *h, const char *tablename)
{
	if (!h->chain_cache)
		return;

	if (tablename) {
		nftnl_chain_list_foreach(h->chain_cache, __flush_chain_cache,
					 (void *)tablename);
	} else {
		nftnl_chain_list_free(h->chain_cache);
		h->chain_cache = NULL;
	}
807
808
}

809
810
void nft_fini(struct nft_handle *h)
{
811
812
	flush_chain_cache(h, NULL);
	flush_rule_cache(h, NULL);
813
814
815
816
817
818
819
820
	mnl_socket_close(h->nl);
}

static void nft_chain_print_debug(struct nftnl_chain *c, struct nlmsghdr *nlh)
{
#ifdef NLDEBUG
	char tmp[1024];

821
	nftnl_chain_snprintf(tmp, sizeof(tmp), c, 0, 0);
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
	printf("DEBUG: chain: %s\n", tmp);
	mnl_nlmsg_fprintf(stdout, nlh, nlh->nlmsg_len, sizeof(struct nfgenmsg));
#endif
}

static struct nftnl_chain *nft_chain_new(struct nft_handle *h,
				       const char *table, const char *chain,
				       int policy,
				       const struct xt_counters *counters)
{
	struct nftnl_chain *c;
	struct builtin_table *_t;
	struct builtin_chain *_c;

	_t = nft_table_builtin_find(h, table);
837
838
839
840
841
	if (!_t) {
		errno = ENXIO;
		return NULL;
	}

842
	/* if this built-in table does not exists, create it */
843
	nft_table_builtin_add(h, _t);
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

	_c = nft_chain_builtin_find(_t, chain);
	if (_c != NULL) {
		/* This is a built-in chain */
		c = nft_chain_builtin_alloc(_t, _c, policy);
		if (c == NULL)
			return NULL;
	} else {
		errno = ENOENT;
		return NULL;
	}

	if (counters) {
		nftnl_chain_set_u64(c, NFTNL_CHAIN_BYTES,
					counters->bcnt);
		nftnl_chain_set_u64(c, NFTNL_CHAIN_PACKETS,
					counters->pcnt);
	}

	return c;
}

int nft_chain_set(struct nft_handle *h, const char *table,
		  const char *chain, const char *policy,
		  const struct xt_counters *counters)
{
	struct nftnl_chain *c = NULL;
	int ret;

	nft_fn = nft_chain_set;

	if (strcmp(policy, "DROP") == 0)
		c = nft_chain_new(h, table, chain, NF_DROP, counters);
	else if (strcmp(policy, "ACCEPT") == 0)
		c = nft_chain_new(h, table, chain, NF_ACCEPT, counters);
879
880
	else
		errno = EINVAL;
881
882
883
884

	if (c == NULL)
		return 0;

885
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_UPDATE, c);
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907

	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

static int __add_match(struct nftnl_expr *e, struct xt_entry_match *m)
{
	void *info;

	nftnl_expr_set(e, NFTNL_EXPR_MT_NAME, m->u.user.name, strlen(m->u.user.name));
	nftnl_expr_set_u32(e, NFTNL_EXPR_MT_REV, m->u.user.revision);

	info = calloc(1, m->u.match_size);
	if (info == NULL)
		return -ENOMEM;

	memcpy(info, m->data, m->u.match_size - sizeof(*m));
	nftnl_expr_set(e, NFTNL_EXPR_MT_INFO, info, m->u.match_size - sizeof(*m));

	return 0;
}

908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
static int add_nft_limit(struct nftnl_rule *r, struct xt_entry_match *m)
{
	struct xt_rateinfo *rinfo = (void *)m->data;
	static const uint32_t mult[] = {
		XT_LIMIT_SCALE*24*60*60,	/* day */
		XT_LIMIT_SCALE*60*60,		/* hour */
		XT_LIMIT_SCALE*60,		/* min */
		XT_LIMIT_SCALE,			/* sec */
	};
	struct nftnl_expr *expr;
	int i;

	expr = nftnl_expr_alloc("limit");
	if (!expr)
		return -ENOMEM;

	for (i = 1; i < ARRAY_SIZE(mult); i++) {
		if (rinfo->avg > mult[i] ||
		    mult[i] / rinfo->avg < mult[i] % rinfo->avg)
			break;
	}

	nftnl_expr_set_u32(expr, NFTNL_EXPR_LIMIT_TYPE, NFT_LIMIT_PKTS);
	nftnl_expr_set_u32(expr, NFTNL_EXPR_LIMIT_FLAGS, 0);

	nftnl_expr_set_u64(expr, NFTNL_EXPR_LIMIT_RATE,
			   mult[i - 1] / rinfo->avg);
        nftnl_expr_set_u64(expr, NFTNL_EXPR_LIMIT_UNIT,
			   mult[i - 1] / XT_LIMIT_SCALE);

	nftnl_expr_set_u32(expr, NFTNL_EXPR_LIMIT_BURST, rinfo->burst);

	nftnl_rule_add_expr(r, expr);
	return 0;
}

944
945
946
947
948
int add_match(struct nftnl_rule *r, struct xt_entry_match *m)
{
	struct nftnl_expr *expr;
	int ret;

949
950
951
	if (!strcmp(m->u.user.name, "limit"))
		return add_nft_limit(r, m);

952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
	expr = nftnl_expr_alloc("match");
	if (expr == NULL)
		return -ENOMEM;

	ret = __add_match(expr, m);
	nftnl_rule_add_expr(r, expr);

	return ret;
}

static int __add_target(struct nftnl_expr *e, struct xt_entry_target *t)
{
	void *info;

	nftnl_expr_set(e, NFTNL_EXPR_TG_NAME, t->u.user.name,
			  strlen(t->u.user.name));
	nftnl_expr_set_u32(e, NFTNL_EXPR_TG_REV, t->u.user.revision);

	info = calloc(1, t->u.target_size);
	if (info == NULL)
		return -ENOMEM;

	memcpy(info, t->data, t->u.target_size - sizeof(*t));
	nftnl_expr_set(e, NFTNL_EXPR_TG_INFO, info, t->u.target_size - sizeof(*t));

	return 0;
}

980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
static int add_meta_nftrace(struct nftnl_rule *r)
{
	struct nftnl_expr *expr;

	expr = nftnl_expr_alloc("immediate");
	if (expr == NULL)
		return -ENOMEM;

	nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_DREG, NFT_REG32_01);
	nftnl_expr_set_u8(expr, NFTNL_EXPR_IMM_DATA, 1);
	nftnl_rule_add_expr(r, expr);

	expr = nftnl_expr_alloc("meta");
	if (expr == NULL)
		return -ENOMEM;
	nftnl_expr_set_u32(expr, NFTNL_EXPR_META_KEY, NFT_META_NFTRACE);
	nftnl_expr_set_u32(expr, NFTNL_EXPR_META_SREG, NFT_REG32_01);

	nftnl_rule_add_expr(r, expr);
	return 0;
}

1002
1003
1004
1005
1006
int add_target(struct nftnl_rule *r, struct xt_entry_target *t)
{
	struct nftnl_expr *expr;
	int ret;

1007
1008
1009
	if (strcmp(t->u.user.name, "TRACE") == 0)
		return add_meta_nftrace(r);

1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
	expr = nftnl_expr_alloc("target");
	if (expr == NULL)
		return -ENOMEM;

	ret = __add_target(expr, t);
	nftnl_rule_add_expr(r, expr);

	return ret;
}

int add_jumpto(struct nftnl_rule *r, const char *name, int verdict)
{
	struct nftnl_expr *expr;

	expr = nftnl_expr_alloc("immediate");
	if (expr == NULL)
		return -ENOMEM;

	nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_DREG, NFT_REG_VERDICT);
	nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_VERDICT, verdict);
	nftnl_expr_set_str(expr, NFTNL_EXPR_IMM_CHAIN, (char *)name);
	nftnl_rule_add_expr(r, expr);

	return 0;
}

int add_verdict(struct nftnl_rule *r, int verdict)
{
	struct nftnl_expr *expr;

	expr = nftnl_expr_alloc("immediate");
	if (expr == NULL)
		return -ENOMEM;

	nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_DREG, NFT_REG_VERDICT);
	nftnl_expr_set_u32(expr, NFTNL_EXPR_IMM_VERDICT, verdict);
	nftnl_rule_add_expr(r, expr);

	return 0;
}

int add_action(struct nftnl_rule *r, struct iptables_command_state *cs,
	       bool goto_set)
{
       int ret = 0;

       /* If no target at all, add nothing (default to continue) */
       if (cs->target != NULL) {
	       /* Standard target? */
	       if (strcmp(cs->jumpto, XTC_LABEL_ACCEPT) == 0)
		       ret = add_verdict(r, NF_ACCEPT);
	       else if (strcmp(cs->jumpto, XTC_LABEL_DROP) == 0)
		       ret = add_verdict(r, NF_DROP);
	       else if (strcmp(cs->jumpto, XTC_LABEL_RETURN) == 0)
		       ret = add_verdict(r, NFT_RETURN);
	       else
		       ret = add_target(r, cs->target->t);
       } else if (strlen(cs->jumpto) > 0) {
	       /* Not standard, then it's a go / jump to chain */
	       if (goto_set)
		       ret = add_jumpto(r, cs->jumpto, NFT_GOTO);
	       else
		       ret = add_jumpto(r, cs->jumpto, NFT_JUMP);
       }
       return ret;
}

static void nft_rule_print_debug(struct nftnl_rule *r, struct nlmsghdr *nlh)
{
#ifdef NLDEBUG
	char tmp[1024];

1082
	nftnl_rule_snprintf(tmp, sizeof(tmp), r, 0, 0);
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
	printf("DEBUG: rule: %s\n", tmp);
	mnl_nlmsg_fprintf(stdout, nlh, nlh->nlmsg_len, sizeof(struct nfgenmsg));
#endif
}

int add_counters(struct nftnl_rule *r, uint64_t packets, uint64_t bytes)
{
	struct nftnl_expr *expr;

	expr = nftnl_expr_alloc("counter");
	if (expr == NULL)
		return -ENOMEM;

	nftnl_expr_set_u64(expr, NFTNL_EXPR_CTR_PACKETS, packets);
	nftnl_expr_set_u64(expr, NFTNL_EXPR_CTR_BYTES, bytes);

	nftnl_rule_add_expr(r, expr);

	return 0;
}

1104
1105
1106
1107
1108
1109
1110
1111
1112
enum udata_type {
	UDATA_TYPE_COMMENT,
	__UDATA_TYPE_MAX,
};
#define UDATA_TYPE_MAX (__UDATA_TYPE_MAX - 1)

int add_comment(struct nftnl_rule *r, const char *comment)
{
	struct nftnl_udata_buf *udata;
1113
1114
1115
1116
	uint32_t len;

	if (nftnl_rule_get_data(r, NFTNL_RULE_USERDATA, &len))
		return -EALREADY;
1117
1118
1119
1120
1121

	udata = nftnl_udata_buf_alloc(NFT_USERDATA_MAXLEN);
	if (!udata)
		return -ENOMEM;

1122
1123
1124
	if (strnlen(comment, 255) == 255)
		return -ENOSPC;

1125
1126
	if (!nftnl_udata_put_strz(udata, UDATA_TYPE_COMMENT, comment))
		return -ENOMEM;
1127

1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
	nftnl_rule_set_data(r, NFTNL_RULE_USERDATA,
			    nftnl_udata_buf_data(udata),
			    nftnl_udata_buf_len(udata));

	nftnl_udata_buf_free(udata);

	return 0;
}

static int parse_udata_cb(const struct nftnl_udata *attr, void *data)
{
	unsigned char *value = nftnl_udata_get(attr);
	uint8_t type = nftnl_udata_type(attr);
	uint8_t len = nftnl_udata_len(attr);
	const struct nftnl_udata **tb = data;

	switch (type) {
	case UDATA_TYPE_COMMENT:
		if (value[len - 1] != '\0')
			return -1;
		break;
	default:
		return 0;
	}
	tb[type] = attr;
	return 0;
}

char *get_comment(const void *data, uint32_t data_len)
{
	const struct nftnl_udata *tb[UDATA_TYPE_MAX + 1] = {};

	if (nftnl_udata_parse(data, data_len, parse_udata_cb, tb) < 0)
		return NULL;

	if (!tb[UDATA_TYPE_COMMENT])
		return NULL;

	return nftnl_udata_get(tb[UDATA_TYPE_COMMENT]);
}

1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
void add_compat(struct nftnl_rule *r, uint32_t proto, bool inv)
{
	nftnl_rule_set_u32(r, NFTNL_RULE_COMPAT_PROTO, proto);
	nftnl_rule_set_u32(r, NFTNL_RULE_COMPAT_FLAGS,
			      inv ? NFT_RULE_COMPAT_F_INV : 0);
}

static struct nftnl_rule *
nft_rule_new(struct nft_handle *h, const char *chain, const char *table,
	     void *data)
{
	struct nftnl_rule *r;

	r = nftnl_rule_alloc();
	if (r == NULL)
		return NULL;

	nftnl_rule_set_u32(r, NFTNL_RULE_FAMILY, h->family);
	nftnl_rule_set(r, NFTNL_RULE_TABLE, (char *)table);
	nftnl_rule_set(r, NFTNL_RULE_CHAIN, (char *)chain);

	if (h->ops->add(r, data) < 0)
		goto err;

	return r;
err:
	nftnl_rule_free(r);
	return NULL;
}

1199
1200
static struct nftnl_rule_list *nft_rule_list_get(struct nft_handle *h);

1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
int
nft_rule_append(struct nft_handle *h, const char *chain, const char *table,
		void *data, uint64_t handle, bool verbose)
{
	struct nftnl_rule *r;
	int type;

	/* If built-in chains don't exist for this table, create them */
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0)
		nft_xt_builtin_init(h, table);

	nft_fn = nft_rule_append;

	r = nft_rule_new(h, chain, table, data);
	if (r == NULL)
		return 0;

	if (handle > 0) {
		nftnl_rule_set(r, NFTNL_RULE_HANDLE, &handle);
		type = NFT_COMPAT_RULE_REPLACE;
	} else
		type = NFT_COMPAT_RULE_APPEND;

1224
	if (batch_rule_add(h, type, r) < 0) {
1225
		nftnl_rule_free(r);
1226
1227
		return 0;
	}
1228

1229
1230
1231
1232
1233
	if (verbose)
		h->ops->print_rule(r, 0, FMT_PRINT_RULE);

	if (!nft_rule_list_get(h))
		return 0;
1234
1235
1236

	nftnl_rule_list_add_tail(r, h->rule_cache);

1237
1238
1239
1240
	return 1;
}

void
1241
nft_rule_print_save(const struct nftnl_rule *r, enum nft_rule_print type,
1242
1243
1244
1245
		    unsigned int format)
{
	const char *chain = nftnl_rule_get_str(r, NFTNL_RULE_CHAIN);
	int family = nftnl_rule_get_u32(r, NFTNL_RULE_FAMILY);
1246
	struct iptables_command_state cs = {};
1247
1248
1249
	struct nft_family_ops *ops;

	ops = nft_family_ops_lookup(family);
1250
	ops->rule_to_cs(r, &cs);
1251

1252
1253
	if (!(format & (FMT_NOCOUNTS | FMT_C_COUNTS)) && ops->save_counters)
		ops->save_counters(&cs);
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264

	/* print chain name */
	switch(type) {
	case NFT_RULE_APPEND:
		printf("-A %s ", chain);
		break;
	case NFT_RULE_DEL:
		printf("-D %s ", chain);
		break;
	}

1265
1266
	if (ops->save_rule)
		ops->save_rule(&cs, format);
1267

1268
1269
	if (ops->clear_cs)
		ops->clear_cs(&cs);
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
}

static int nftnl_chain_list_cb(const struct nlmsghdr *nlh, void *data)
{
	struct nftnl_chain *c;
	struct nftnl_chain_list *list = data;

	c = nftnl_chain_alloc();
	if (c == NULL)
		goto err;

	if (nftnl_chain_nlmsg_parse(nlh, c) < 0)
		goto out;

	nftnl_chain_list_add_tail(c, list);

	return MNL_CB_OK;
out:
	nftnl_chain_free(c);
err:
	return MNL_CB_OK;
}

1293
struct nftnl_chain_list *nft_chain_list_get(struct nft_handle *h)
1294
{
1295
	char buf[16536];
1296
1297
	struct nlmsghdr *nlh;
	struct nftnl_chain_list *list;
1298
	int ret;
1299

1300
1301
1302
	if (h->chain_cache)
		return h->chain_cache;
retry:
1303
1304
1305
1306
1307
1308
1309
1310
1311
	list = nftnl_chain_list_alloc();
	if (list == NULL) {
		errno = ENOMEM;
		return NULL;
	}

	nlh = nftnl_chain_nlmsg_build_hdr(buf, NFT_MSG_GETCHAIN, h->family,
					NLM_F_DUMP, h->seq);

1312
1313
1314
1315
1316
1317
1318
1319
	ret = mnl_talk(h, nlh, nftnl_chain_list_cb, list);
	if (ret < 0 && errno == EINTR) {
		assert(nft_restart(h) >= 0);
		nftnl_chain_list_free(list);
		goto retry;
	}

	h->chain_cache = list;
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332

	return list;
}

static const char *policy_name[NF_ACCEPT+1] = {
	[NF_DROP] = "DROP",
	[NF_ACCEPT] = "ACCEPT",
};

int nft_chain_save(struct nft_handle *h, struct nftnl_chain_list *list,
		   const char *table)
{
	struct nftnl_chain_list_iter *iter;
1333
	struct nft_family_ops *ops;
1334
1335
	struct nftnl_chain *c;

1336
1337
	ops = nft_family_ops_lookup(h->family);

1338
1339
1340
1341
1342
1343
1344
1345
	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		return 0;

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *chain_table =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
1346
		const char *policy = NULL;
1347
1348
1349
1350

		if (strcmp(table, chain_table) != 0)
			goto next;

1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
		if (nft_chain_builtin(c)) {
			uint32_t pol = NF_ACCEPT;

			if (nftnl_chain_get(c, NFTNL_CHAIN_POLICY))
				pol = nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY);
			policy = policy_name[pol];
		}

		if (ops->save_chain)
			ops->save_chain(c, policy);
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
next:
		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);

	return 1;
}

static int nftnl_rule_list_cb(const struct nlmsghdr *nlh, void *data)
{
	struct nftnl_rule *r;
	struct nftnl_rule_list *list = data;

	r = nftnl_rule_alloc();
	if (r == NULL)
		goto err;

	if (nftnl_rule_nlmsg_parse(nlh, r) < 0)
		goto out;

	nftnl_rule_list_add_tail(r, list);

	return MNL_CB_OK;
out:
	nftnl_rule_free(r);
	nftnl_rule_list_free(list);
err:
	return MNL_CB_OK;
}

static struct nftnl_rule_list *nft_rule_list_get(struct nft_handle *h)
{
1394
	char buf[16536];
1395
1396
1397
1398
	struct nlmsghdr *nlh;
	struct nftnl_rule_list *list;
	int ret;

1399
1400
1401
	if (h->rule_cache)
		return h->rule_cache;

1402
retry:
1403
1404
1405
1406
1407
1408
1409
1410
1411
	list = nftnl_rule_list_alloc();
	if (list == NULL)
		return 0;

	nlh = nftnl_rule_nlmsg_build_hdr(buf, NFT_MSG_GETRULE, h->family,
					NLM_F_DUMP, h->seq);

	ret = mnl_talk(h, nlh, nftnl_rule_list_cb, list);
	if (ret < 0) {
1412
1413
1414
1415
1416
1417
		if (errno == EINTR) {
			assert(nft_restart(h) >= 0);
			nftnl_rule_list_free(list);
			goto retry;
		}

1418
1419
1420
1421
		nftnl_rule_list_free(list);
		return NULL;
	}

1422
	h->rule_cache = list;
1423
1424
1425
	return list;
}

1426
int nft_rule_save(struct nft_handle *h, const char *table, unsigned int format)
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
{
	struct nftnl_rule_list *list;
	struct nftnl_rule_list_iter *iter;
	struct nftnl_rule *r;

	list = nft_rule_list_get(h);
	if (list == NULL)
		return 0;

	iter = nftnl_rule_list_iter_create(list);
	if (iter == NULL)
		return 0;

	r = nftnl_rule_list_iter_next(iter);
	while (r != NULL) {
		const char *rule_table =
			nftnl_rule_get_str(r, NFTNL_RULE_TABLE);

		if (strcmp(table, rule_table) != 0)
			goto next;

1448
		nft_rule_print_save(r, NFT_RULE_APPEND, format);
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475

next:
		r = nftnl_rule_list_iter_next(iter);
	}

	nftnl_rule_list_iter_destroy(iter);

	/* the core expects 1 for success and 0 for error */
	return 1;
}

static void
__nft_rule_flush(struct nft_handle *h, const char *table, const char *chain)
{
	struct nftnl_rule *r;

	r = nftnl_rule_alloc();
	if (r == NULL)
		return;

	nftnl_rule_set(r, NFTNL_RULE_TABLE, (char *)table);
	nftnl_rule_set(r, NFTNL_RULE_CHAIN, (char *)chain);

	if (batch_rule_add(h, NFT_COMPAT_RULE_FLUSH, r) < 0)
		nftnl_rule_free(r);
}

1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
struct chain_user_flush_data {
	struct nft_handle	*handle;
	const char		*table;
	const char		*chain;
};

static int __nft_chain_user_flush(struct nftnl_chain *c, void *data)
{
	const char *table_name = nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
	const char *chain_name = nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
	struct chain_user_flush_data *d = data;
	struct nft_handle *h = d->handle;
	const char *table = d->table;
	const char *chain = d->chain;

	if (strcmp(table, table_name) != 0)
		return 0;

	if (strcmp(chain, chain_name) != 0)
		return 0;

1497
1498
	if (!nftnl_chain_is_set(c, NFTNL_CHAIN_HOOKNUM))
		__nft_rule_flush(h, table, chain);
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518

	return 0;
}

int nft_chain_user_flush(struct nft_handle *h, struct nftnl_chain_list *list,
			 const char *table, const char *chain)
{
	struct chain_user_flush_data d = {
		.handle = h,
		.table	= table,
		.chain  = chain,
	};

	nft_fn = nft_chain_user_flush;

	nftnl_chain_list_foreach(list, __nft_chain_user_flush, &d);

	return 1;
}

1519
1520
int nft_rule_flush(struct nft_handle *h, const char *chain, const char *table,
		   bool verbose)
1521
{
1522
	int ret = 0;
1523
1524
1525
1526
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;

1527
1528
1529
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0)
		nft_xt_builtin_init(h, table);

1530
1531
	nft_fn = nft_rule_flush;

1532
	list = nft_chain_list_get(h);
1533
	if (list == NULL) {
1534
		ret = 1;
1535
1536
1537
1538
		goto err;
	}

	iter = nftnl_chain_list_iter_create(list);
1539
1540
	if (iter == NULL) {
		ret = 1;
1541
		goto err;
1542
	}
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *table_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
		const char *chain_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);

		if (strcmp(table, table_name) != 0)
			goto next;

		if (chain != NULL && strcmp(chain, chain_name) != 0)
			goto next;

1557
1558
1559
		if (verbose)
			fprintf(stdout, "Flushing chain `%s'\n", chain_name);

1560
1561
1562
1563
1564
1565
1566
1567
		__nft_rule_flush(h, table_name, chain_name);

		if (chain != NULL)
			break;
next:
		c = nftnl_chain_list_iter_next(iter);
	}
	nftnl_chain_list_iter_destroy(iter);
1568
	flush_rule_cache(h, table);
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
err:
	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

int nft_chain_user_add(struct nft_handle *h, const char *chain, const char *table)
{
	struct nftnl_chain *c;
	int ret;

	nft_fn = nft_chain_user_add;

	/* If built-in chains don't exist for this table, create them */
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0)
		nft_xt_builtin_init(h, table);

	c = nftnl_chain_alloc();
	if (c == NULL)
		return 0;

	nftnl_chain_set(c, NFTNL_CHAIN_TABLE, (char *)table);
	nftnl_chain_set(c, NFTNL_CHAIN_NAME, (char *)chain);

1592
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_USER_ADD, c);
1593

1594
	nft_chain_list_get(h);
1595
1596

	nftnl_chain_list_add(c, h->chain_cache);
1597
1598
1599
1600
1601

	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

1602
1603
1604
1605
1606
/* From linux/netlink.h */
#ifndef NLM_F_NONREC
#define NLM_F_NONREC	0x100	/* Do not delete recursively    */
#endif

1607
1608
int nft_chain_user_del(struct nft_handle *h, const char *chain,
		       const char *table, bool verbose)
1609
1610
1611
1612
1613
1614
1615
{
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;
	int ret = 0;
	int deleted_ctr = 0;

1616
1617
	nft_fn = nft_chain_user_del;

1618
	list = nft_chain_list_get(h);
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
	if (list == NULL)
		goto err;

	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		goto err;

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *table_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
		const char *chain_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);

		/* don't delete built-in chain */
		if (nft_chain_builtin(c))
			goto next;

		if (strcmp(table, table_name) != 0)
			goto next;

		if (chain != NULL && strcmp(chain, chain_name) != 0)
			goto next;

1643
1644
1645
		if (verbose)
			fprintf(stdout, "Deleting chain `%s'\n", chain);

1646
		ret = batch_chain_add(h, NFT_COMPAT_CHAIN_USER_DEL, c);
1647
1648
1649
1650
1651

		if (ret < 0)
			break;

		deleted_ctr++;
1652
		nftnl_chain_list_del(c);
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663

		if (chain != NULL)
			break;
next:
		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);
err:

	/* chain not found */
1664
	if (chain != NULL && deleted_ctr == 0) {
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
		ret = -1;
		errno = ENOENT;
	}

	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

struct nftnl_chain *
nft_chain_list_find(struct nftnl_chain_list *list,
		    const char *table, const char *chain)
{
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;

	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		return NULL;

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *table_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
		const char *chain_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);

		if (strcmp(table, table_name) != 0)
			goto next;

		if (strcmp(chain, chain_name) != 0)
			goto next;

		nftnl_chain_list_iter_destroy(iter);
		return c;
next:
		c = nftnl_chain_list_iter_next(iter);
	}
	nftnl_chain_list_iter_destroy(iter);
	return NULL;
}

static struct nftnl_chain *
nft_chain_find(struct nft_handle *h, const char *table, const char *chain)
{
	struct nftnl_chain_list *list;

1711
	list = nft_chain_list_get(h);
1712
1713
1714
1715
1716
1717
	if (list == NULL)
		return NULL;

	return nft_chain_list_find(list, table, chain);
}

1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
bool nft_chain_exists(struct nft_handle *h,
		      const char *table, const char *chain)
{
	struct builtin_table *t = nft_table_builtin_find(h, table);

	/* xtables does not support custom tables */
	if (!t)
		return false;

	if (nft_chain_builtin_find(t, chain))
		return true;

	return !!nft_chain_find(h, table, chain);
}

1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
int nft_chain_user_rename(struct nft_handle *h,const char *chain,
			  const char *table, const char *newname)
{
	struct nftnl_chain *c;
	uint64_t handle;
	int ret;

	nft_fn = nft_chain_user_add;

	/* If built-in chains don't exist for this table, create them */
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0)
		nft_xt_builtin_init(h, table);

	/* Config load changed errno. Ensure genuine info for our callers. */
	errno = 0;

	/* Find the old chain to be renamed */
	c = nft_chain_find(h, table, chain);
	if (c == NULL) {
		errno = ENOENT;
1753
		return 0;
1754
1755
1756
1757
1758
1759
	}
	handle = nftnl_chain_get_u64(c, NFTNL_CHAIN_HANDLE);

	/* Now prepare the new name for the chain */
	c = nftnl_chain_alloc();
	if (c == NULL)
1760
		return 0;
1761
1762
1763
1764
1765

	nftnl_chain_set(c, NFTNL_CHAIN_TABLE, (char *)table);
	nftnl_chain_set(c, NFTNL_CHAIN_NAME, (char *)newname);
	nftnl_chain_set_u64(c, NFTNL_CHAIN_HANDLE, handle);

1766
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_RENAME, c);
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794

	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

static int nftnl_table_list_cb(const struct nlmsghdr *nlh, void *data)
{
	struct nftnl_table *t;
	struct nftnl_table_list *list = data;

	t = nftnl_table_alloc();
	if (t == NULL)
		goto err;

	if (nftnl_table_nlmsg_parse(nlh, t) < 0)
		goto out;

	nftnl_table_list_add_tail(t, list);

	return MNL_CB_OK;
out:
	nftnl_table_free(t);
err:
	return MNL_CB_OK;
}

static struct nftnl_table_list *nftnl_table_list_get(struct nft_handle *h)
{
1795
	char buf[16536];
1796
1797
	struct nlmsghdr *nlh;
	struct nftnl_table_list *list;
1798
	int ret;
1799

1800
retry:
1801
1802
1803
1804
1805
1806
1807
	list = nftnl_table_list_alloc();
	if (list == NULL)
		return 0;

	nlh = nftnl_rule_nlmsg_build_hdr(buf, NFT_MSG_GETTABLE, h->family,
					NLM_F_DUMP, h->seq);

1808
1809
1810
1811
1812
1813
	ret = mnl_talk(h, nlh, nftnl_table_list_cb, list);
	if (ret < 0 && errno == EINTR) {
		assert(nft_restart(h) >= 0);
		nftnl_table_list_free(list);
		goto retry;
	}
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837

	return list;
}

bool nft_table_find(struct nft_handle *h, const char *tablename)
{
	struct nftnl_table_list *list;
	struct nftnl_table_list_iter *iter;
	struct nftnl_table *t;
	bool ret = false;

	list = nftnl_table_list_get(h);
	if (list == NULL)
		goto err;

	iter = nftnl_table_list_iter_create(list);
	if (iter == NULL)
		goto err;

	t = nftnl_table_list_iter_next(iter);
	while (t != NULL) {
		const char *this_tablename =
			nftnl_table_get(t, NFTNL_TABLE_NAME);

1838
1839
1840
1841
		if (strcmp(tablename, this_tablename) == 0) {
			ret = true;
			break;
		}
1842
1843
1844
1845

		t = nftnl_table_list_iter_next(iter);
	}

1846
	nftnl_table_list_iter_destroy(iter);
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
	nftnl_table_list_free(list);

err:
	return ret;
}

int nft_for_each_table(struct nft_handle *h,
		       int (*func)(struct nft_handle *h, const char *tablename, bool counters),
		       bool counters)
{
	struct nftnl_table_list *list;
	struct nftnl_table_list_iter *iter;
	struct nftnl_table *t;

	list = nftnl_table_list_get(h);
1862
1863
	if (list == NULL)
		return -1;
1864
1865
1866

	iter = nftnl_table_list_iter_create(list);
	if (iter == NULL)
1867
		return -1;
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878

	t = nftnl_table_list_iter_next(iter);
	while (t != NULL) {
		const char *tablename =
			nftnl_table_get(t, NFTNL_TABLE_NAME);

		func(h, tablename, counters);

		t = nftnl_table_list_iter_next(iter);
	}

1879
	nftnl_table_list_iter_destroy(iter);
1880
	nftnl_table_list_free(list);
1881
1882
	return 0;
}
1883

1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
static int __nft_table_flush(struct nft_handle *h, const char *table)
{
	struct builtin_table *_t;
	struct nftnl_table *t;

	t = nftnl_table_alloc();
	if (t == NULL)
		return -1;

	nftnl_table_set_str(t, NFTNL_TABLE_NAME, table);

	batch_table_add(h, NFT_COMPAT_TABLE_FLUSH, t);

	_t = nft_table_builtin_find(h, table);
1898
	assert(_t);
1899
1900
1901
1902
1903
1904
	_t->initialized = false;

	flush_chain_cache(h, table);
	flush_rule_cache(h, table);

	return 0;
1905
1906
}

1907
int nft_table_flush(struct nft_handle *h, const char *table)
1908
{
1909
1910
1911
1912
	struct nftnl_table_list_iter *iter;
	struct nftnl_table_list *list;
	struct nftnl_table *t;
	int ret = 0;
1913

1914
	nft_fn = nft_table_flush;
1915

1916
1917
1918
1919
1920
	list = nftnl_table_list_get(h);
	if (list == NULL) {
		ret = -1;
		goto err_out;
	}
1921

1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
	iter = nftnl_table_list_iter_create(list);
	if (iter == NULL) {
		ret = -1;
		goto err_table_list;
	}

	t = nftnl_table_list_iter_next(iter);
	while (t != NULL) {
		const char *table_name =
			nftnl_table_get_str(t, NFTNL_TABLE_NAME);
1932

1933
		if (strcmp(table_name, table) != 0)
1934
1935
			goto next;

1936
1937
1938
		ret = __nft_table_flush(h, table);
		if (ret < 0)
			goto err_table_iter;
1939
next:
1940
		t = nftnl_table_list_iter_next(iter);
1941
1942
	}

1943
1944
1945
1946
1947
	if (!h->rule_cache) {
		h->rule_cache = nftnl_rule_list_alloc();
		if (h->rule_cache == NULL)
			return -1;
	}
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961

err_table_iter:
	nftnl_table_list_iter_destroy(iter);
err_table_list:
	nftnl_table_list_free(list);
err_out:
	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

void nft_table_new(struct nft_handle *h, const char *table)
{
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0)
		nft_xt_builtin_init(h, table);
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
}

static int __nft_rule_del(struct nft_handle *h, struct nftnl_rule_list *list,
			  struct nftnl_rule *r)
{
	int ret;

	nftnl_rule_list_del(r);

	ret = batch_rule_add(h, NFT_COMPAT_RULE_DELETE, r);
	if (ret < 0) {
		nftnl_rule_free(r);
		return -1;
	}
	return 1;
}

static struct nftnl_rule *
nft_rule_find(struct nft_handle *h, struct nftnl_rule_list *list,
	      const char *chain, const char *table, void *data, int rulenum)
{
	struct nftnl_rule *r;
	struct nftnl_rule_list_iter *iter;
	int rule_ctr = 0;
	bool found = false;

	iter = nftnl_rule_list_iter_create(list);
	if (iter == NULL)
		return 0;

	r = nftnl_rule_list_iter_next(iter);
	while (r != NULL) {
		const char *rule_table =
			nftnl_rule_get_str(r, NFTNL_RULE_TABLE);
		const char *rule_chain =
			nftnl_rule_get_str(r, NFTNL_RULE_CHAIN);

		if (strcmp(table, rule_table) != 0 ||
		    strcmp(chain, rule_chain) != 0) {
			DEBUGP("different chain / table\n");
			goto next;
		}

		if (rulenum >= 0) {
			/* Delete by rule number case */
			if (rule_ctr == rulenum) {
			    found = true;
			    break;
			}
		} else {
			found = h->ops->rule_find(h->ops, r, data);
			if (found)
				break;
		}
		rule_ctr++;
next:
		r = nftnl_rule_list_iter_next(iter);
	}

	nftnl_rule_list_iter_destroy(iter);

	return found ? r : NULL;
}

int nft_rule_check(struct nft_handle *h, const char *chain,
		   const char *table, void *data, bool verbose)
{
	struct nftnl_rule_list *list;
2030
	struct nftnl_rule *r;
2031
2032
2033

	nft_fn = nft_rule_check;

2034
	list = nft_rule_list_get(h);
2035
2036
2037
	if (list == NULL)
		return 0;

2038
2039
	r = nft_rule_find(h, list, chain, table, data, -1);
	if (r == NULL) {
2040
		errno = ENOENT;
2041
2042
2043
2044
		return 0;
	}
	if (verbose)
		h->ops->print_rule(r, 0, FMT_PRINT_RULE);
2045

2046
	return 1;
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
}

int nft_rule_delete(struct nft_handle *h, const char *chain,
		    const char *table, void *data, bool verbose)
{
	int ret = 0;
	struct nftnl_rule *r;
	struct nftnl_rule_list *list;

	nft_fn = nft_rule_delete;

2058
	list = nft_rule_list_get(h);
2059
2060
2061
2062
2063
2064
2065
2066
	if (list == NULL)
		return 0;

	r = nft_rule_find(h, list, chain, table, data, -1);
	if (r != NULL) {
		ret =__nft_rule_del(h, list, r);
		if (ret < 0)
			errno = ENOMEM;
2067
2068
		if (verbose)
			h->ops->print_rule(r, 0, FMT_PRINT_RULE);
2069
2070
2071
2072
2073
2074
	} else
		errno = ENOENT;

	return ret;
}

2075
static struct nftnl_rule *
2076
2077
2078
2079
2080
2081
2082
2083
nft_rule_add(struct nft_handle *h, const char *chain,
	     const char *table, struct iptables_command_state *cs,
	     uint64_t handle, bool verbose)
{
	struct nftnl_rule *r;

	r = nft_rule_new(h, chain, table, cs);
	if (r == NULL)
2084
		return NULL;
2085
2086
2087
2088
2089
2090

	if (handle > 0)
		nftnl_rule_set_u64(r, NFTNL_RULE_POSITION, handle);

	if (batch_rule_add(h, NFT_COMPAT_RULE_INSERT, r) < 0) {
		nftnl_rule_free(r);
2091
		return NULL;
2092
2093
	}

2094
2095
2096
	if (verbose)
		h->ops->print_rule(r, 0, FMT_PRINT_RULE);

2097
	return r;
2098
2099
2100
2101
2102
}

int nft_rule_insert(struct nft_handle *h, const char *chain,
		    const char *table, void *data, int rulenum, bool verbose)
{
2103
	struct nftnl_rule *r, *new_rule;
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
	struct nftnl_rule_list *list;
	uint64_t handle = 0;

	/* If built-in chains don't exist for this table, create them */
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0)
		nft_xt_builtin_init(h, table);

	nft_fn = nft_rule_insert;

	if (rulenum > 0) {
2114
		list = nft_rule_list_get(h);
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
		if (list == NULL)
			goto err;

		r = nft_rule_find(h, list, chain, table, data, rulenum);
		if (r == NULL) {
			/* special case: iptables allows to insert into
			 * rule_count + 1 position.
			 */
			r = nft_rule_find(h, list, chain, table, data,
					  rulenum - 1);
2125
			if (r != NULL)
2126
2127
2128
2129
2130
2131
2132
2133
2134
				return nft_rule_append(h, chain, table, data,
						       0, verbose);

			errno = ENOENT;
			goto err;
		}

		handle = nftnl_rule_get_u64(r, NFTNL_RULE_HANDLE);
		DEBUGP("adding after rule handle %"PRIu64"\n", handle);
2135
2136
	} else {
		nft_rule_list_get(h);
2137
2138
	}

2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
	new_rule = nft_rule_add(h, chain, table, data, handle, verbose);
	if (!new_rule)
		goto err;

	if (handle)
		nftnl_rule_list_insert_at(new_rule, r);
	else
		nftnl_rule_list_add(new_rule, h->rule_cache);

	return 1;
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
err:
	return 0;
}

int nft_rule_delete_num(struct nft_handle *h, const char *chain,
			const char *table, int rulenum, bool verbose)
{
	int ret = 0;
	struct nftnl_rule *r;
	struct nftnl_rule_list *list;

	nft_fn = nft_rule_delete_num;

2162
	list = nft_rule_list_get(h);
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
	if (list == NULL)
		return 0;

	r = nft_rule_find(h, list, chain, table, NULL, rulenum);
	if (r != NULL) {
		DEBUGP("deleting rule by number %d\n", rulenum);
		ret = __nft_rule_del(h, list, r);
		if (ret < 0)
			errno = ENOMEM;
	} else
		errno = ENOENT;

	return ret;
}

int nft_rule_replace(struct nft_handle *h, const char *chain,
		     const char *table, void *data, int rulenum, bool verbose)
{
	int ret = 0;
	struct nftnl_rule *r;
	struct nftnl_rule_list *list;

	nft_fn = nft_rule_replace;

2187
	list = nft_rule_list_get(h);
2188
2189
2190
2191
2192
2193
2194
2195
2196
	if (list == NULL)
		return 0;

	r = nft_rule_find(h, list, chain, table, data, rulenum);
	if (r != NULL) {
		DEBUGP("replacing rule with handle=%llu\n",
			(unsigned long long)
			nftnl_rule_get_u64(r, NFTNL_RULE_HANDLE));

2197
2198
		nftnl_rule_list_del(r);

2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
		ret = nft_rule_append(h, chain, table, data,
				      nftnl_rule_get_u64(r, NFTNL_RULE_HANDLE),
				      verbose);
	} else
		errno = ENOENT;

	return ret;
}

static int
__nft_rule_list(struct nft_handle *h, const char *chain, const char *table,
		int rulenum, unsigned int format,
		void (*cb)(struct nftnl_rule *r, unsigned int num,
			   unsigned int format))
{
	struct nftnl_rule_list *list;
	struct nftnl_rule_list_iter *iter;
	struct nftnl_rule *r;
2217
	int rule_ctr = 0;
2218
2219
2220
2221
2222
2223
2224

	list = nft_rule_list_get(h);
	if (list == NULL)
		return 0;

	iter = nftnl_rule_list_iter_create(list);
	if (iter == NULL)
2225
		return 0;
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245

	r = nftnl_rule_list_iter_next(iter);
	while (r != NULL) {
		const char *rule_table =
			nftnl_rule_get_str(r, NFTNL_RULE_TABLE);
		const char *rule_chain =
			nftnl_rule_get_str(r, NFTNL_RULE_CHAIN);

		if (strcmp(table, rule_table) != 0 ||
		    strcmp(chain, rule_chain) != 0)
			goto next;

		rule_ctr++;

		if (rulenum > 0 && rule_ctr != rulenum) {
			/* List by rule number case */
			goto next;
		}

		cb(r, rule_ctr, format);
2246
		if (rulenum > 0)
2247
2248
2249
2250
2251
2252
2253
			break;

next:
		r = nftnl_rule_list_iter_next(iter);
	}

	nftnl_rule_list_iter_destroy(iter);
2254
2255
	return 1;
}
2256

2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
static int nft_rule_count(struct nft_handle *h,
			  const char *chain, const char *table)
{
	struct nftnl_rule_list_iter *iter;
	struct nftnl_rule_list *list;
	struct nftnl_rule *r;
	int rule_ctr = 0;

	list = nft_rule_list_get(h);
	if (list == NULL)
		return 0;

	iter = nftnl_rule_list_iter_create(list);
	if (iter == NULL)
		return 0;

	r = nftnl_rule_list_iter_next(iter);
	while (r != NULL) {
		const char *rule_table =
			nftnl_rule_get_str(r, NFTNL_RULE_TABLE);
		const char *rule_chain =
			nftnl_rule_get_str(r, NFTNL_RULE_CHAIN);

		if (strcmp(table, rule_table) != 0 ||
		    strcmp(chain, rule_chain) != 0)
			goto next;

		rule_ctr++;
next:
		r = nftnl_rule_list_iter_next(iter);
	}

	nftnl_rule_list_iter_destroy(iter);
	return rule_ctr;
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
}

int nft_rule_list(struct nft_handle *h, const char *chain, const char *table,
		  int rulenum, unsigned int format)
{
	const struct nft_family_ops *ops;
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;
	bool found = false;

	/* If built-in chains don't exist for this table, create them */
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0) {
		nft_xt_builtin_init(h, table);
		/* Force table and chain creation, otherwise first iptables -L
		 * lists no table/chains.
		 */
2308
		if (!list_empty(&h->obj_list)) {
2309
			nft_commit(h);
2310
2311
			flush_chain_cache(h, NULL);
		}
2312
2313
2314
2315
	}

	ops = nft_family_ops_lookup(h->family);

2316
2317
2318
2319
2320
	if (!nft_is_table_compatible(h, table)) {
		xtables_error(OTHER_PROBLEM, "table `%s' is incompatible, use 'nft' tool.\n", table);
		return 0;
	}

2321
2322
	if (chain && rulenum) {
		__nft_rule_list(h, chain, table,
2323
				rulenum, format, ops->print_rule);
2324
2325
2326
		return 1;
	}

2327
	list = nft_chain_list_get(h);
2328
2329
2330
2331
2332

	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		goto err;

2333
	if (!chain && ops->print_table_header)
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
		ops->print_table_header(table);

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *chain_table =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
		const char *chain_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
		uint32_t policy =
			nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY);
		uint32_t refs =
			nftnl_chain_get_u32(c, NFTNL_CHAIN_USE);
		struct xt_counters ctrs = {
			.pcnt = nftnl_chain_get_u64(c, NFTNL_CHAIN_PACKETS),
			.bcnt = nftnl_chain_get_u64(c, NFTNL_CHAIN_BYTES),
		};
		bool basechain = false;
2351
		uint32_t entries;
2352
2353
2354
2355
2356
2357

		if (nftnl_chain_get(c, NFTNL_CHAIN_HOOKNUM))
			basechain = true;

		if (strcmp(table, chain_table) != 0)
			goto next;
2358
2359
2360
2361
2362
2363
		if (chain) {
			if (strcmp(chain, chain_name) != 0)
				goto next;
			else if (ops->print_table_header)
				ops->print_table_header(table);
		}
2364
2365
2366
2367

		if (found)
			printf("\n");

2368
		entries = nft_rule_count(h, chain_name, table);
2369
		ops->print_header(format, chain_name, policy_name[policy],
2370
				  &ctrs, basechain, refs - entries, entries);
2371
2372

		__nft_rule_list(h, chain_name, table,
2373
2374
2375
				rulenum, format, ops->print_rule);

		found = true;
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386

		/* we printed the chain we wanted, stop processing. */
		if (chain)
			break;

next:
		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);
err:
2387
2388
2389
	if (chain && !found)
		return 0;

2390
2391
2392
2393
2394
2395
	return 1;
}

static void
list_save(struct nftnl_rule *r, unsigned int num, unsigned int format)
{
2396
	nft_rule_print_save(r, NFT_RULE_APPEND, format);
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
}

static int
nftnl_rule_list_chain_save(struct nft_handle *h, const char *chain,
			 const char *table, struct nftnl_chain_list *list,
			 int counters)
{
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;

	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		return 0;

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *chain_table =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
		const char *chain_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
		uint32_t policy =
			nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY);

		if (strcmp(table, chain_table) != 0 ||
		    (chain && strcmp(chain, chain_name) != 0))
			goto next;

		/* this is a base chain */
		if (nft_chain_builtin(c)) {
			printf("-P %s %s", chain_name, policy_name[policy]);

			if (counters) {
				printf(" -c %"PRIu64" %"PRIu64"\n",
					nftnl_chain_get_u64(c, NFTNL_CHAIN_PACKETS),
					nftnl_chain_get_u64(c, NFTNL_CHAIN_BYTES));
			} else
				printf("\n");
		} else {
			printf("-N %s\n", chain_name);
		}
next:
		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);

	return 1;
}

int nft_rule_list_save(struct nft_handle *h, const char *chain,
		       const char *table, int rulenum, int counters)
{
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
2451
	unsigned int format = 0;
2452
	struct nftnl_chain *c;
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
	int ret = 0;

	/* If built-in chains don't exist for this table, create them */
	if (nft_xtables_config_load(h, XTABLES_CONFIG_DEFAULT, 0) < 0) {
		nft_xt_builtin_init(h, table);
		/* Force table and chain creation, otherwise first iptables -L
		 * lists no table/chains.
		 */
		if (!list_empty(&h->obj_list)) {
			nft_commit(h);
			flush_chain_cache(h, NULL);
		}
	}

	if (!nft_is_table_compatible(h, table)) {
		xtables_error(OTHER_PROBLEM, "table `%s' is incompatible, use 'nft' tool.\n", table);
		return 0;
	}
2471

2472
	list = nft_chain_list_get(h);
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482

	/* Dump policies and custom chains first */
	if (!rulenum)
		nftnl_rule_list_chain_save(h, chain, table, list, counters);

	/* Now dump out rules in this table */
	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		goto err;

2483
2484
2485
2486
2487
	if (counters < 0)
		format = FMT_C_COUNTS;
	else if (counters == 0)
		format = FMT_NOCOUNTS;

2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *chain_table =
			nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
		const char *chain_name =
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);

		if (strcmp(table, chain_table) != 0)
			goto next;
		if (chain && strcmp(chain, chain_name) != 0)
			goto next;

		ret = __nft_rule_list(h, chain_name, table, rulenum,
2501
				      format, list_save);
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524

		/* we printed the chain we wanted, stop processing. */
		if (chain)
			break;
next:
		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);
err:
	return ret;
}

int nft_rule_zero_counters(struct nft_handle *h, const char *chain,
			   const char *table, int rulenum)
{
	struct iptables_command_state cs = {};
	struct nftnl_rule_list *list;
	struct nftnl_rule *r;
	int ret = 0;

	nft_fn = nft_rule_delete;

2525
	list = nft_rule_list_get(h);
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
	if (list == NULL)
		return 0;

	r = nft_rule_find(h, list, chain, table, NULL, rulenum);
	if (r == NULL) {
		errno = ENOENT;
		ret = 1;
		goto error;
	}

	nft_rule_to_iptables_command_state(r, &cs);

	cs.counters.pcnt = cs.counters.bcnt = 0;

	ret =  nft_rule_append(h, chain, table, &cs,
			       nftnl_rule_get_u64(r, NFTNL_RULE_HANDLE),
			       false);

error:
	return ret;
}

static void nft_compat_table_batch_add(struct nft_handle *h, uint16_t type,
				       uint16_t flags, uint32_t seq,
				       struct nftnl_table *table)
{
	struct nlmsghdr *nlh;

2554
	nlh = nftnl_table_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
					type, h->family, flags, seq);
	nftnl_table_nlmsg_build_payload(nlh, table);
}

static void nft_compat_chain_batch_add(struct nft_handle *h, uint16_t type,
				       uint16_t flags, uint32_t seq,
				       struct nftnl_chain *chain)
{
	struct nlmsghdr *nlh;

2565
	nlh = nftnl_chain_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
					type, h->family, flags, seq);
	nftnl_chain_nlmsg_build_payload(nlh, chain);
	nft_chain_print_debug(chain, nlh);
}

static void nft_compat_rule_batch_add(struct nft_handle *h, uint16_t type,
				      uint16_t flags, uint32_t seq,
				      struct nftnl_rule *rule)
{
	struct nlmsghdr *nlh;

2577
	nlh = nftnl_rule_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
2578
2579
2580
				       type, h->family, flags, seq);
	nftnl_rule_nlmsg_build_payload(nlh, rule);
	nft_rule_print_debug(rule, nlh);
2581
2582
2583
2584
2585
2586
2587
2588
2589
}

static void batch_obj_del(struct nft_handle *h, struct obj_update *o)
{
	switch (o->type) {
	case NFT_COMPAT_TABLE_ADD:
	case NFT_COMPAT_TABLE_FLUSH:
		nftnl_table_free(o->table);
		break;
2590
	case NFT_COMPAT_CHAIN_ZERO:
2591
2592
	case NFT_COMPAT_CHAIN_USER_ADD:
		break;
2593
2594
	case NFT_COMPAT_CHAIN_ADD:
	case NFT_COMPAT_CHAIN_USER_DEL:
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
	case NFT_COMPAT_CHAIN_USER_FLUSH:
	case NFT_COMPAT_CHAIN_UPDATE:
	case NFT_COMPAT_CHAIN_RENAME:
		nftnl_chain_free(o->chain);
		break;
	case NFT_COMPAT_RULE_APPEND:
	case NFT_COMPAT_RULE_INSERT:
	case NFT_COMPAT_RULE_REPLACE:
	case NFT_COMPAT_RULE_DELETE:
		break;
	case NFT_COMPAT_RULE_FLUSH:
		nftnl_rule_free(o->rule);
		break;
	}
	h->obj_list_num--;
	list_del(&o->head);
	free(o);
2612
2613
2614
2615
2616
}

static int nft_action(struct nft_handle *h, int action)
{
	struct obj_update *n, *tmp;
2617
2618
2619
2620
	struct mnl_err *err, *ne;
	unsigned int buflen, i, len;
	bool show_errors = true;
	char errmsg[1024];
2621
2622
2623
	uint32_t seq = 1;
	int ret = 0;

2624
	h->batch = mnl_batch_init();
2625

2626
2627
2628
2629
	mnl_batch_begin(h->batch, seq++);

	list_for_each_entry(n, &h->obj_list, head) {
		n->seq = seq++;
2630
2631
2632
		switch (n->type) {
		case NFT_COMPAT_TABLE_ADD:
			nft_compat_table_batch_add(h, NFT_MSG_NEWTABLE,
2633
						   NLM_F_CREATE, n->seq,
2634
2635
						   n->table);
			break;
2636
2637
2638
2639
2640
		case NFT_COMPAT_TABLE_FLUSH:
			nft_compat_table_batch_add(h, NFT_MSG_DELTABLE,
						   0,
						   n->seq, n->table);
			break;
2641
		case NFT_COMPAT_CHAIN_ADD:
2642
		case NFT_COMPAT_CHAIN_ZERO:
2643
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN,
2644
						   NLM_F_CREATE, n->seq,
2645
2646
2647
2648
						   n->chain);
			break;
		case NFT_COMPAT_CHAIN_USER_ADD:
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN,
2649
						   NLM_F_EXCL, n->seq,
2650
2651
2652
2653
						   n->chain);
			break;
		case NFT_COMPAT_CHAIN_USER_DEL:
			nft_compat_chain_batch_add(h, NFT_MSG_DELCHAIN,
2654
2655
2656
2657
2658
2659
						   NLM_F_NONREC, n->seq,
						   n->chain);
			break;
		case NFT_COMPAT_CHAIN_USER_FLUSH:
			nft_compat_chain_batch_add(h, NFT_MSG_DELCHAIN,
						   0, n->seq,
2660
						   n->chain);
2661
2662
2663
2664
2665
			break;
		case NFT_COMPAT_CHAIN_UPDATE:
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN,
						   h->restore ?
						     NLM_F_CREATE : 0,
2666
						   n->seq, n->chain);
2667
2668
2669
			break;
		case NFT_COMPAT_CHAIN_RENAME:
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN, 0,
2670
						   n->seq, n->chain);
2671
2672
2673
2674
			break;
		case NFT_COMPAT_RULE_APPEND:
			nft_compat_rule_batch_add(h, NFT_MSG_NEWRULE,
						  NLM_F_CREATE | NLM_F_APPEND,
2675
						  n->seq, n->rule);
2676
2677
2678
			break;
		case NFT_COMPAT_RULE_INSERT:
			nft_compat_rule_batch_add(h, NFT_MSG_NEWRULE,
2679
						  NLM_F_CREATE, n->seq,
2680
2681
2682
2683
2684
						  n->rule);
			break;
		case NFT_COMPAT_RULE_REPLACE:
			nft_compat_rule_batch_add(h, NFT_MSG_NEWRULE,
						  NLM_F_CREATE | NLM_F_REPLACE,
2685
						  n->seq, n->rule);
2686
2687
2688
2689
			break;
		case NFT_COMPAT_RULE_DELETE:
		case NFT_COMPAT_RULE_FLUSH:
			nft_compat_rule_batch_add(h, NFT_MSG_DELRULE, 0,
2690
						  n->seq, n->rule);
2691
2692
2693
			break;
		}

2694
		mnl_nft_batch_continue(h->batch);
2695
2696
2697
2698
	}

	switch (action) {
	case NFT_COMPAT_COMMIT:
2699
		mnl_batch_end(h->batch, seq++);
2700
2701
2702
2703
2704
		break;
	case NFT_COMPAT_ABORT:
		break;
	}

2705
2706
2707
2708
	ret = mnl_batch_talk(h->nl, h->batch, &h->err_list);

	i = 0;
	buflen = sizeof(errmsg);
2709

2710
2711
2712
2713
	list_for_each_entry_safe(n, tmp, &h->obj_list, head) {
		list_for_each_entry_safe(err, ne, &h->err_list, head) {
			if (err->seqnum > n->seq)
				break;
2714

2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
			if (err->seqnum == n->seq && show_errors) {
				if (n->error.lineno == 0)
					show_errors = false;
				len = mnl_append_error(h, n, err, errmsg + i, buflen);
				if (len > 0 && len <= buflen) {
					buflen -= len;
					i += len;
				}
			}
			mnl_err_list_free(err);
		}
		batch_obj_del(h, n);
	}

	mnl_batch_reset(h->batch);

	if (i)
		xtables_error(RESOURCE_PROBLEM, "%s", errmsg);
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749

	return ret == 0 ? 1 : 0;
}

int nft_commit(struct nft_handle *h)
{
	return nft_action(h, NFT_COMPAT_COMMIT);
}

int nft_abort(struct nft_handle *h)
{
	return nft_action(h, NFT_COMPAT_ABORT);
}

int nft_compatible_revision(const char *name, uint8_t rev, int opt)
{
	struct mnl_socket *nl;
2750
	char buf[16536];
2751
	struct nlmsghdr *nlh;
2752
2753
	uint32_t portid, seq, type = 0;
	uint32_t pf = AF_INET;
2754
2755
	int ret = 0;

2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
	switch (opt) {
	case IPT_SO_GET_REVISION_MATCH:
		break;
	case IP6T_SO_GET_REVISION_MATCH:
		pf = AF_INET6;
		break;
	case IPT_SO_GET_REVISION_TARGET:
		type = 1;
		break;
	case IP6T_SO_GET_REVISION_TARGET:
2766
		type = 1;
2767
2768
2769
2770
2771
2772
		pf = AF_INET6;
		break;
	default:
		/* No revision support (arp, ebtables), assume latest version ok */
		return 1;
	}
2773
2774
2775
2776
2777
2778
2779

	nlh = mnl_nlmsg_put_header(buf);
	nlh->nlmsg_type = (NFNL_SUBSYS_NFT_COMPAT << 8) | NFNL_MSG_COMPAT_GET;
	nlh->nlmsg_flags = NLM_F_REQUEST | NLM_F_ACK;
	nlh->nlmsg_seq = seq = time(NULL);

	struct nfgenmsg *nfg = mnl_nlmsg_put_extra_header(nlh, sizeof(*nfg));
2780
	nfg->nfgen_family = pf;
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
	nfg->version = NFNETLINK_V0;
	nfg->res_id = 0;

	mnl_attr_put_strz(nlh, NFTA_COMPAT_NAME, name);
	mnl_attr_put_u32(nlh, NFTA_COMPAT_REV, htonl(rev));
	mnl_attr_put_u32(nlh, NFTA_COMPAT_TYPE, htonl(type));

	DEBUGP("requesting `%s' rev=%d type=%d via nft_compat\n",
		name, rev, type);

	nl = mnl_socket_open(NETLINK_NETFILTER);
	if (nl == NULL)
		return 0;

	if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0)
		goto err;

	portid = mnl_socket_get_portid(nl);

	if (mnl_socket_sendto(nl, nlh, nlh->nlmsg_len) < 0)
		goto err;

	ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
	if (ret == -1)
		goto err;

	ret = mnl_cb_run(buf, ret, seq, portid, NULL, NULL);
	if (ret == -1)
		goto err;

err:
	mnl_socket_close(nl);

	return ret < 0 ? 0 : 1;
}

/* Translates errno numbers into more human-readable form than strerror. */
const char *nft_strerror(int err)
{
	unsigned int i;
	static struct table_struct {
		void *fn;
		int err;
		const char *message;
	} table[] =
	  {
	    { nft_chain_user_del, ENOTEMPTY, "Chain is not empty" },
	    { nft_chain_user_del, EINVAL, "Can't delete built-in chain" },
	    { nft_chain_user_del, EBUSY, "Directory not empty" },
	    { nft_chain_user_del, EMLINK,
	      "Can't delete chain with references left" },
	    { nft_chain_user_add, EEXIST, "Chain already exists" },
2833
	    { nft_rule_insert, ENOENT, "Index of insertion too big" },
2834
2835
	    { nft_rule_check, ENOENT, "Bad rule (does a matching rule exist in that chain?)" },
	    { nft_rule_replace, ENOENT, "Index of replacement too big" },
2836
	    { nft_rule_delete_num, ENOENT, "Index of deletion too big" },
2837
2838
2839
2840
2841
2842
2843
/*	    { TC_READ_COUNTER, E2BIG, "Index of counter too big" },
	    { TC_ZERO_COUNTER, E2BIG, "Index of counter too big" }, */
	    /* ENOENT for DELETE probably means no matching rule */
	    { nft_rule_delete, ENOENT,
	      "Bad rule (does a matching rule exist in that chain?)" },
	    { nft_chain_set, ENOENT, "Bad built-in chain name" },
	    { nft_chain_set, EINVAL, "Bad policy name" },
2844
	    { nft_chain_set, ENXIO, "Bad table name" },
2845
	    { NULL, ELOOP, "Loop found in table" },
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
	    { NULL, EPERM, "Permission denied (you must be root)" },
	    { NULL, 0, "Incompatible with this kernel" },
	    { NULL, ENOPROTOOPT, "iptables who? (do you need to insmod?)" },
	    { NULL, ENOSYS, "Will be implemented real soon.  I promise ;)" },
	    { NULL, ENOMEM, "Memory allocation problem" },
	    { NULL, ENOENT, "No chain/target/match by that name" },
	  };

	for (i = 0; i < sizeof(table)/sizeof(struct table_struct); i++) {
		if ((!table[i].fn || table[i].fn == nft_fn)
		    && table[i].err == err)
			return table[i].message;
	}

	return strerror(err);
}

static void xtables_config_perror(uint32_t flags, const char *fmt, ...)
{
	va_list args;

	va_start(args, fmt);

	if (flags & NFT_LOAD_VERBOSE)
		vfprintf(stderr, fmt, args);

	va_end(args);
}

2875
2876
static int __nft_xtables_config_load(struct nft_handle *h, const char *filename,
				     uint32_t flags)
2877
{
2878
2879
	struct nftnl_table_list *table_list = NULL;
	struct nftnl_chain_list *chain_list = NULL;
2880
2881
2882
2883
2884
2885
2886
	struct nftnl_table_list_iter *titer = NULL;
	struct nftnl_chain_list_iter *citer = NULL;
	struct nftnl_table *table;
	struct nftnl_chain *chain;
	uint32_t table_family, chain_family;
	bool found = false;

2887
2888
2889
	table_list = nftnl_table_list_alloc();
	chain_list = nftnl_chain_list_alloc();

2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
	if (xtables_config_parse(filename, table_list, chain_list) < 0) {
		if (errno == ENOENT) {
			xtables_config_perror(flags,
				"configuration file `%s' does not exists\n",
				filename);
		} else {
			xtables_config_perror(flags,
				"Fatal error parsing config file: %s\n",
				 strerror(errno));
		}
		goto err;
	}

	/* Stage 1) create tables */
	titer = nftnl_table_list_iter_create(table_list);
	while ((table = nftnl_table_list_iter_next(titer)) != NULL) {
		table_family = nftnl_table_get_u32(table,
						      NFTNL_TABLE_FAMILY);
		if (h->family != table_family)
			continue;

		found = true;

		if (batch_table_add(h, NFT_COMPAT_TABLE_ADD, table) < 0) {
			if (errno == EEXIST) {
				xtables_config_perror(flags,
					"table `%s' already exists, skipping\n",
					(char *)nftnl_table_get(table, NFTNL_TABLE_NAME));
			} else {
				xtables_config_perror(flags,
					"table `%s' cannot be create, reason `%s'. Exitting\n",
					(char *)nftnl_table_get(table, NFTNL_TABLE_NAME),
					strerror(errno));
				goto err;
			}
			continue;
		}
		xtables_config_perror(flags, "table `%s' has been created\n",
			(char *)nftnl_table_get(table, NFTNL_TABLE_NAME));
	}
	nftnl_table_list_iter_destroy(titer);
	nftnl_table_list_free(table_list);

	if (!found)
		goto err;

	/* Stage 2) create chains */
	citer = nftnl_chain_list_iter_create(chain_list);
	while ((chain = nftnl_chain_list_iter_next(citer)) != NULL) {
		chain_family = nftnl_chain_get_u32(chain,
						      NFTNL_CHAIN_TABLE);
		if (h->family != chain_family)
			continue;

		if (batch_chain_add(h, NFT_COMPAT_CHAIN_ADD, chain) < 0) {
			if (errno == EEXIST) {
				xtables_config_perror(flags,
					"chain `%s' already exists in table `%s', skipping\n",
					(char *)nftnl_chain_get(chain, NFTNL_CHAIN_NAME),
					(char *)nftnl_chain_get(chain, NFTNL_CHAIN_TABLE));
			} else {
				xtables_config_perror(flags,
					"chain `%s' cannot be create, reason `%s'. Exitting\n",
					(char *)nftnl_chain_get(chain, NFTNL_CHAIN_NAME),
					strerror(errno));
				goto err;
			}
			continue;
		}

		xtables_config_perror(flags,
			"chain `%s' in table `%s' has been created\n",
			(char *)nftnl_chain_get(chain, NFTNL_CHAIN_NAME),
			(char *)nftnl_chain_get(chain, NFTNL_CHAIN_TABLE));
	}
	nftnl_chain_list_iter_destroy(citer);
	nftnl_chain_list_free(chain_list);

2968
2969
	h->config_done = 1;

2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
	return 0;

err:
	nftnl_table_list_free(table_list);
	nftnl_chain_list_free(chain_list);

	if (titer != NULL)
		nftnl_table_list_iter_destroy(titer);
	if (citer != NULL)
		nftnl_chain_list_iter_destroy(citer);

2981
2982
	h->config_done = -1;

2983
2984
2985
	return -1;
}

2986
2987
2988
2989
2990
2991
2992
2993
2994
int nft_xtables_config_load(struct nft_handle *h, const char *filename,
			    uint32_t flags)
{
	if (!h->config_done)
		return __nft_xtables_config_load(h, filename, flags);

	return h->config_done;
}

2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
static void nft_chain_zero_rule_counters(struct nft_handle *h,
					 struct nftnl_chain *c)
{
	struct nftnl_rule_list_iter *iter;
	struct nftnl_rule_list *list;
	const char *table_name;
	const char *chain_name;
	struct nftnl_rule *r;

	list = nft_rule_list_get(h);
	if (list == NULL)
		return;
	iter = nftnl_rule_list_iter_create(list);
	if (iter == NULL)
		return;

	table_name = nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
	chain_name = nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);

	r = nftnl_rule_list_iter_next(iter);
	while (r != NULL) {
		struct nftnl_expr_iter *ei;
		const char *table_chain;
		const char *rule_chain;
		struct nftnl_expr *e;
		bool zero_needed;

		table_chain = nftnl_rule_get_str(r, NFTNL_RULE_TABLE);
		if (strcmp(table_chain, table_name))
			goto next;

		rule_chain = nftnl_rule_get_str(r, NFTNL_RULE_CHAIN);
		if (strcmp(rule_chain, chain_name))
			goto next;

		ei = nftnl_expr_iter_create(r);
		if (!ei)
			break;

		e = nftnl_expr_iter_next(ei);
	        zero_needed = false;
		while (e != NULL) {
			const char *en = nftnl_expr_get_str(e, NFTNL_EXPR_NAME);

			if (strcmp(en, "counter") == 0 && (
			    nftnl_expr_get_u64(e, NFTNL_EXPR_CTR_PACKETS) ||
			    nftnl_expr_get_u64(e, NFTNL_EXPR_CTR_BYTES))) {
				nftnl_expr_set_u64(e, NFTNL_EXPR_CTR_PACKETS, 0);
				nftnl_expr_set_u64(e, NFTNL_EXPR_CTR_BYTES, 0);
				zero_needed = true;
			}

			e = nftnl_expr_iter_next(ei);
		}

		nftnl_expr_iter_destroy(ei);

		if (zero_needed) {
			/*
			 * Unset RULE_POSITION for older kernels, we want to replace
			 * rule based on its handle only.
			 */
			nftnl_rule_unset(r, NFTNL_RULE_POSITION);
			batch_rule_add(h, NFT_COMPAT_RULE_REPLACE, r);
		}
next:
		r = nftnl_rule_list_iter_next(iter);
	}

	nftnl_rule_list_iter_destroy(iter);
}

3067
3068
int nft_chain_zero_counters(struct nft_handle *h, const char *chain,
			    const char *table, bool verbose)
3069
3070
3071
3072
3073
3074
{
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;
	int ret = 0;

3075
	list = nft_chain_list_get(h);
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
	if (list == NULL)
		goto err;

	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		goto err;

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *chain_name =
			nftnl_chain_get(c, NFTNL_CHAIN_NAME);
		const char *chain_table =
			nftnl_chain_get(c, NFTNL_CHAIN_TABLE);

		if (strcmp(table, chain_table) != 0)
			goto next;

		if (chain != NULL && strcmp(chain, chain_name) != 0)
			goto next;

3096
3097
3098
		if (verbose)
			fprintf(stdout, "Zeroing chain `%s'\n", chain_name);

3099
3100
3101
3102
3103
3104
3105
		if (nftnl_chain_is_set(c, NFTNL_CHAIN_HOOKNUM)) {
			/* zero base chain counters. */
			nftnl_chain_set_u64(c, NFTNL_CHAIN_PACKETS, 0);
			nftnl_chain_set_u64(c, NFTNL_CHAIN_BYTES, 0);
		}

		nft_chain_zero_rule_counters(h, c);
3106
3107
3108

		nftnl_chain_unset(c, NFTNL_CHAIN_HANDLE);

3109
		ret = batch_chain_add(h, NFT_COMPAT_CHAIN_ZERO, c);
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130

		if (chain != NULL)
			break;
next:
		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);

err:
	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
}

uint32_t nft_invflags2cmp(uint32_t invflags, uint32_t flag)
{
	if (invflags & flag)
		return NFT_CMP_NEQ;

	return NFT_CMP_EQ;
}
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145

#define NFT_COMPAT_EXPR_MAX     8

static const char *supported_exprs[NFT_COMPAT_EXPR_MAX] = {
	"match",
	"target",
	"payload",
	"meta",
	"cmp",
	"bitwise",
	"counter",
	"immediate"
};


3146
static int nft_is_expr_compatible(const struct nftnl_expr *expr)
3147
{
3148
	const char *name = nftnl_expr_get_str(expr, NFTNL_EXPR_NAME);
3149
3150
3151
3152
3153
3154
3155
	int i;

	for (i = 0; i < NFT_COMPAT_EXPR_MAX; i++) {
		if (strcmp(supported_exprs[i], name) == 0)
			return 0;
	}

3156
3157
3158
3159
3160
	if (!strcmp(name, "limit") &&
	    nftnl_expr_get_u32(expr, NFTNL_EXPR_LIMIT_TYPE) == NFT_LIMIT_PKTS &&
	    nftnl_expr_get_u32(expr, NFTNL_EXPR_LIMIT_FLAGS) == 0)
		return 0;

3161
3162
3163
	return 1;
}

3164
static bool nft_is_rule_compatible(struct nftnl_rule *rule)
3165
3166
3167
{
	struct nftnl_expr_iter *iter;
	struct nftnl_expr *expr;
3168
	bool compatible = false;
3169
3170
3171

	iter = nftnl_expr_iter_create(rule);
	if (iter == NULL)
3172
		return false;
3173
3174
3175

	expr = nftnl_expr_iter_next(iter);
	while (expr != NULL) {
3176
		if (nft_is_expr_compatible(expr) == 0) {
3177
3178
3179
3180
			expr = nftnl_expr_iter_next(iter);
			continue;
		}

3181
		compatible = true;
3182
3183
3184
3185
		break;
	}

	nftnl_expr_iter_destroy(iter);
3186
	return compatible;
3187
3188
}

3189
3190
static int nft_is_chain_compatible(const struct nft_handle *h,
				   const struct nftnl_chain *chain)
3191
{
3192
	const char *table, *name, *type, *cur_table;
3193
	struct builtin_chain *chains;
3194
3195
3196
3197
3198
3199
3200
3201
	int i, j, prio;
	enum nf_inet_hooks hook;

	table = nftnl_chain_get(chain, NFTNL_CHAIN_TABLE);
	name = nftnl_chain_get(chain, NFTNL_CHAIN_NAME);
	type = nftnl_chain_get(chain, NFTNL_CHAIN_TYPE);
	prio = nftnl_chain_get_u32(chain, NFTNL_CHAIN_PRIO);
	hook = nftnl_chain_get_u32(chain, NFTNL_CHAIN_HOOKNUM);
3202

3203
	for (i = 0; i < NFT_TABLE_MAX; i++) {
3204
3205
		cur_table = h->tables[i].name;
		chains = h->tables[i].chains;
3206

3207
		if (!cur_table || strcmp(table, cur_table) != 0)
3208
3209
3210
			continue;

		for (j = 0; j < NF_INET_NUMHOOKS && chains[j].name; j++) {
3211
3212
3213
3214
3215
3216
			if (strcmp(name, chains[j].name) != 0)
				continue;

			if (strcmp(type, chains[j].type) == 0 &&
			    prio == chains[j].prio &&
			    hook == chains[j].hook)
3217
				return 0;
3218
			break;
3219
3220
3221
3222
3223
3224
		}
	}

	return 1;
}

3225
static int nft_are_chains_compatible(struct nft_handle *h, const char *tablename)
3226
3227
3228
3229
3230
3231
{
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *chain;
	int ret = 0;

3232
	list = nft_chain_list_get(h);
3233
3234
3235
3236
3237
3238
3239
3240
3241
	if (list == NULL)
		return -1;

	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		return -1;

	chain = nftnl_chain_list_iter_next(iter);
	while (chain != NULL) {
3242
3243
3244
3245
3246
3247
		const char *chain_table;

		chain_table = nftnl_chain_get_str(chain, NFTNL_CHAIN_TABLE);

		if (strcmp(chain_table, tablename) ||
		    !nft_chain_builtin(chain))
3248
3249
			goto next;

3250
3251
		ret = nft_is_chain_compatible(h, chain);
		if (ret != 0)
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
			break;
next:
		chain = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);

	return ret;
}

3262
bool nft_is_table_compatible(struct nft_handle *h, const char *tablename)
3263
3264
3265
3266
{
	struct nftnl_rule_list *list;
	struct nftnl_rule_list_iter *iter;
	struct nftnl_rule *rule;
3267
	int ret = 0;
3268

3269
	if (!nft_table_builtin_find(h, tablename))
3270
		return false;
3271

3272
	ret = nft_are_chains_compatible(h, tablename);
3273
	if (ret != 0)
3274
		return false;
3275
3276
3277

	list = nft_rule_list_get(h);
	if (list == NULL)
3278
		return true;
3279
3280
3281

	iter = nftnl_rule_list_iter_create(list);
	if (iter == NULL)
3282
		return true;
3283
3284
3285

	rule = nftnl_rule_list_iter_next(iter);
	while (rule != NULL) {
3286
3287
3288
3289
3290
		const char *table = nftnl_rule_get_str(rule, NFTNL_RULE_TABLE);

		if (strcmp(table, tablename))
			goto next_rule;

3291
3292
3293
		ret = nft_is_rule_compatible(rule);
		if (ret != 0)
			break;
3294
next_rule:
3295
3296
3297
3298
		rule = nftnl_rule_list_iter_next(iter);
	}

	nftnl_rule_list_iter_destroy(iter);
3299
	return ret == 0;
3300
}