nft.c 81.5 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
#include <libmnl/libmnl.h>
44
#include <libnftnl/gen.h>
45
46
47
48
49
#include <libnftnl/table.h>
#include <libnftnl/chain.h>
#include <libnftnl/rule.h>
#include <libnftnl/expr.h>
#include <libnftnl/set.h>
50
#include <libnftnl/udata.h>
51
#include <libnftnl/batch.h>
52
53
54
55
56
57

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

#include "nft.h"
#include "xshared.h" /* proto_to_name */
58
#include "nft-cache.h"
59
#include "nft-shared.h"
60
#include "nft-bridge.h" /* EBT_NOPROTO */
61
62
63
64
65
66
67
68

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;
69
	char buf[32768];
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

	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;
}

89
#define NFT_NLMSG_MAXSIZE (UINT16_MAX + getpagesize())
90
91
92
93
94
95
96

/* 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

97
static struct nftnl_batch *mnl_batch_init(void)
98
{
99
	struct nftnl_batch *batch;
100

101
102
	batch = nftnl_batch_alloc(BATCH_PAGE_SIZE, NFT_NLMSG_MAXSIZE);
	if (batch == NULL)
103
104
		return NULL;

105
	return batch;
106
107
}

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

113
static uint32_t mnl_batch_begin(struct nftnl_batch *batch, uint32_t genid, uint32_t seqnum)
114
{
115
116
117
118
119
120
	struct nlmsghdr *nlh;

	nlh = nftnl_batch_begin(nftnl_batch_buffer(batch), seqnum);

	mnl_attr_put_u32(nlh, NFTA_GEN_ID, htonl(genid));

121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
	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);
}
136

137
138
139
140
141
142
143
144
145
146
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));
147

148
149
150
151
152
153
154
155
156
	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);
157
158
}

159
static void mnl_set_sndbuffer(struct nft_handle *h)
160
{
161
	int newbuffsiz = nftnl_batch_iovec_len(h->batch) * BATCH_PAGE_SIZE;
162

163
	if (newbuffsiz <= h->nlsndbuffsiz)
164
165
166
		return;

	/* Rise sender buffer length to avoid hitting -EMSGSIZE */
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
	if (setsockopt(mnl_socket_get_fd(h->nl), SOL_SOCKET, SO_SNDBUFFORCE,
		       &newbuffsiz, sizeof(socklen_t)) < 0)
		return;

	h->nlsndbuffsiz = newbuffsiz;
}

static void mnl_set_rcvbuffer(struct nft_handle *h, int numcmds)
{
	int newbuffsiz = getpagesize() * numcmds;

	if (newbuffsiz <= h->nlrcvbuffsiz)
		return;

	/* Rise receiver buffer length to avoid hitting -ENOBUFS */
	if (setsockopt(mnl_socket_get_fd(h->nl), SOL_SOCKET, SO_RCVBUFFORCE,
183
184
185
		       &newbuffsiz, sizeof(socklen_t)) < 0)
		return;

186
	h->nlrcvbuffsiz = newbuffsiz;
187
188
}

189
static ssize_t mnl_nft_socket_sendmsg(struct nft_handle *h, int numcmds)
190
191
192
193
{
	static const struct sockaddr_nl snl = {
		.nl_family = AF_NETLINK
	};
194
	uint32_t iov_len = nftnl_batch_iovec_len(h->batch);
195
	struct iovec iov[iov_len];
196
197
198
199
	struct msghdr msg = {
		.msg_name	= (struct sockaddr *) &snl,
		.msg_namelen	= sizeof(snl),
		.msg_iov	= iov,
200
		.msg_iovlen	= iov_len,
201
202
	};

203
204
205
	mnl_set_sndbuffer(h);
	mnl_set_rcvbuffer(h, numcmds);
	nftnl_batch_iovec(h->batch, iov, iov_len);
206

207
	return sendmsg(mnl_socket_get_fd(h->nl), &msg, 0);
208
209
}

210
static int mnl_batch_talk(struct nft_handle *h, int numcmds)
211
{
212
	const struct mnl_socket *nl = h->nl;
213
	int ret, fd = mnl_socket_get_fd(nl), portid = mnl_socket_get_portid(nl);
214
215
216
217
218
219
220
221
	char rcv_buf[MNL_SOCKET_BUFFER_SIZE];
	fd_set readfds;
	struct timeval tv = {
		.tv_sec		= 0,
		.tv_usec	= 0
	};
	int err = 0;

222
	ret = mnl_nft_socket_sendmsg(h, numcmds);
223
224
225
226
227
228
229
230
231
232
233
234
	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)) {
235
236
237
		struct nlmsghdr *nlh = (struct nlmsghdr *)rcv_buf;

		ret = mnl_socket_recvfrom(nl, rcv_buf, sizeof(rcv_buf));
238
239
240
		if (ret == -1)
			return -1;

241
242
243
		ret = mnl_cb_run(rcv_buf, ret, 0, portid, NULL, NULL);
		/* Continue on error, make sure we get all acknowledgments */
		if (ret == -1) {
244
245
			mnl_err_list_node_add(&h->err_list, errno,
					      nlh->nlmsg_seq);
246
247
			err = -1;
		}
248
249
250
251
252
253
254
255

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

		FD_ZERO(&readfds);
		FD_SET(fd, &readfds);
	}
256
	return err;
257
258
259
260
261
262
263
264
265
}

enum obj_action {
	NFT_COMPAT_COMMIT,
	NFT_COMPAT_ABORT,
};

struct obj_update {
	struct list_head	head;
266
267
268
	enum obj_update_type	type:8;
	uint8_t			skip:1;
	uint8_t			implicit:1;
269
	unsigned int		seq;
270
271
272
	union {
		struct nftnl_table	*table;
		struct nftnl_chain	*chain;
273
		struct nftnl_rule	*rule;
274
		struct nftnl_set	*set;
275
276
		void			*ptr;
	};
277
278
279
	struct {
		unsigned int		lineno;
	} error;
280
281
};

282
283
284
285
286
287
288
289
290
291
292
293
294
295
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",
296
		[NFT_COMPAT_CHAIN_ZERO] = "CHAIN_ZERO",
297
298
299
300
301
		[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",
302
		[NFT_COMPAT_SET_ADD] = "SET_ADD",
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
	};
	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:
321
	case NFT_COMPAT_CHAIN_ZERO:
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
	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
		{
339
			nft_rule_print_save(h, o->rule, NFT_RULE_APPEND, FMT_NOCOUNTS);
340
341
342
		}
#endif
		break;
343
344
345
346
	case NFT_COMPAT_SET_ADD:
		snprintf(tcr, sizeof(tcr), "set %s",
			 nftnl_set_get_str(o->set, NFTNL_SET_NAME));
		break;
347
348
349
350
351
352
353
354
355
	case NFT_COMPAT_RULE_LIST:
	case NFT_COMPAT_RULE_CHECK:
	case NFT_COMPAT_CHAIN_RESTORE:
	case NFT_COMPAT_RULE_SAVE:
	case NFT_COMPAT_RULE_ZERO:
	case NFT_COMPAT_BRIDGE_USER_CHAIN_UPDATE:
	case NFT_COMPAT_TABLE_NEW:
		assert(0);
		break;
356
357
358
359
360
	}

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

361
static struct obj_update *batch_add(struct nft_handle *h, enum obj_update_type type, void *ptr)
362
363
364
365
366
{
	struct obj_update *obj;

	obj = calloc(1, sizeof(struct obj_update));
	if (obj == NULL)
367
		return NULL;
368
369

	obj->ptr = ptr;
370
	obj->error.lineno = h->error.lineno;
371
372
373
374
	obj->type = type;
	list_add_tail(&obj->head, &h->obj_list);
	h->obj_list_num++;

375
	return obj;
376
377
}

378
379
380
static struct obj_update *
batch_table_add(struct nft_handle *h, enum obj_update_type type,
		struct nftnl_table *t)
381
382
383
384
{
	return batch_add(h, type, t);
}

385
386
387
388
389
390
391
static struct obj_update *
batch_set_add(struct nft_handle *h, enum obj_update_type type,
	      struct nftnl_set *s)
{
	return batch_add(h, type, s);
}

392
393
394
static int batch_chain_add(struct nft_handle *h, enum obj_update_type type,
			   struct nftnl_chain *c)
{
395
	return batch_add(h, type, c) ? 0 : -1;
396
397
}

398
399
static struct obj_update *
batch_rule_add(struct nft_handle *h, enum obj_update_type type,
400
401
402
403
404
			  struct nftnl_rule *r)
{
	return batch_add(h, type, r);
}

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
432
433
434
435
436
static void batch_obj_del(struct nft_handle *h, struct obj_update *o);

static void batch_chain_flush(struct nft_handle *h,
			      const char *table, const char *chain)
{
	struct obj_update *obj, *tmp;

	list_for_each_entry_safe(obj, tmp, &h->obj_list, head) {
		struct nftnl_rule *r = obj->ptr;

		switch (obj->type) {
		case NFT_COMPAT_RULE_APPEND:
		case NFT_COMPAT_RULE_INSERT:
		case NFT_COMPAT_RULE_REPLACE:
		case NFT_COMPAT_RULE_DELETE:
			break;
		default:
			continue;
		}

		if (table &&
		    strcmp(table, nftnl_rule_get_str(r, NFTNL_RULE_TABLE)))
			continue;

		if (chain &&
		    strcmp(chain, nftnl_rule_get_str(r, NFTNL_RULE_CHAIN)))
			continue;

		batch_obj_del(h, obj);
	}
}

437
const struct builtin_table xtables_ipv4[NFT_TABLE_MAX] = {
438
	[NFT_TABLE_RAW] = {
439
		.name	= "raw",
440
		.type	= NFT_TABLE_RAW,
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
		.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,
			},
		},
	},
456
	[NFT_TABLE_MANGLE] = {
457
		.name	= "mangle",
458
		.type	= NFT_TABLE_MANGLE,
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
		.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,
			},
		},
	},
492
	[NFT_TABLE_FILTER] = {
493
		.name	= "filter",
494
		.type	= NFT_TABLE_FILTER,
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
		.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,
			},
		},
	},
516
	[NFT_TABLE_SECURITY] = {
517
		.name	= "security",
518
		.type	= NFT_TABLE_SECURITY,
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
		.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,
			},
		},
	},
540
	[NFT_TABLE_NAT] = {
541
		.name	= "nat",
542
		.type	= NFT_TABLE_NAT,
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
		.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>

574
const struct builtin_table xtables_arp[NFT_TABLE_MAX] = {
575
	[NFT_TABLE_FILTER] = {
576
	.name   = "filter",
577
	.type	= NFT_TABLE_FILTER,
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
	.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>

597
const struct builtin_table xtables_bridge[NFT_TABLE_MAX] = {
598
	[NFT_TABLE_FILTER] = {
599
		.name = "filter",
600
		.type	= NFT_TABLE_FILTER,
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
		.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,
			},
		},
	},
622
	[NFT_TABLE_NAT] = {
623
		.name = "nat",
624
		.type	= NFT_TABLE_NAT,
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
		.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,
			},
		},
	},
};

648
649
650
651
652
653
static bool nft_table_initialized(const struct nft_handle *h,
				  enum nft_table_type type)
{
	return h->cache->table[type].initialized;
}

654
static int nft_table_builtin_add(struct nft_handle *h,
655
				 const struct builtin_table *_t)
656
657
658
659
{
	struct nftnl_table *t;
	int ret;

660
	if (nft_table_initialized(h, _t->type))
661
662
663
664
665
666
		return 0;

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

667
	nftnl_table_set_str(t, NFTNL_TABLE_NAME, _t->name);
668

669
	ret = batch_table_add(h, NFT_COMPAT_TABLE_ADD, t) ? 0 : - 1;
670
671
672
673
674

	return ret;
}

static struct nftnl_chain *
675
676
nft_chain_builtin_alloc(const struct builtin_table *table,
			const struct builtin_chain *chain, int policy)
677
678
679
680
681
682
683
{
	struct nftnl_chain *c;

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

684
685
	nftnl_chain_set_str(c, NFTNL_CHAIN_TABLE, table->name);
	nftnl_chain_set_str(c, NFTNL_CHAIN_NAME, chain->name);
686
687
688
	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);
689
	nftnl_chain_set_str(c, NFTNL_CHAIN_TYPE, chain->type);
690
691
692
693
694

	return c;
}

static void nft_chain_builtin_add(struct nft_handle *h,
695
696
				  const struct builtin_table *table,
				  const struct builtin_chain *chain)
697
698
699
700
701
702
703
{
	struct nftnl_chain *c;

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

704
	batch_chain_add(h, NFT_COMPAT_CHAIN_ADD, c);
705
	nftnl_chain_list_add_tail(c, h->cache->table[table->type].chains);
706
707
}

708
709
710
/* find if built-in table already exists */
const struct builtin_table *
nft_table_builtin_find(struct nft_handle *h, const char *table)
711
712
713
714
{
	int i;
	bool found = false;

715
	for (i = 0; i < NFT_TABLE_MAX; i++) {
716
		if (h->tables[i].name == NULL)
717
718
			continue;

719
		if (strcmp(h->tables[i].name, table) != 0)
720
721
722
723
724
725
			continue;

		found = true;
		break;
	}

726
	return found ? &h->tables[i] : NULL;
727
728
729
}

/* find if built-in chain already exists */
730
731
const struct builtin_chain *
nft_chain_builtin_find(const struct builtin_table *t, const char *chain)
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
{
	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,
747
				   const struct builtin_table *table)
748
{
749
	struct nftnl_chain_list *list;
750
	struct nftnl_chain *c;
751
	int i;
752
753

	/* Initialize built-in chains if they don't exist yet */
754
	for (i=0; i < NF_INET_NUMHOOKS && table->chains[i].name != NULL; i++) {
755
756
757
758
		list = nft_chain_list_get(h, table->name,
					  table->chains[i].name);
		if (!list)
			continue;
759

760
		c = nftnl_chain_list_lookup_byname(list, table->chains[i].name);
761
762
763
764
765
766
767
768
769
		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)
{
770
	const struct builtin_table *t;
771

772
773
774
	if (!h->cache_init)
		return 0;

775
	t = nft_table_builtin_find(h, table);
776
777
778
	if (t == NULL)
		return -1;

779
	if (nft_table_initialized(h, t->type))
780
781
782
783
784
		return 0;

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

785
786
787
	if (h->cache_req.level < NFT_CL_CHAINS)
		return 0;

788
	nft_chain_builtin_init(h, t);
789

790
	h->cache->table[t->type].initialized = true;
791
792

	return 0;
793
794
795
796
797
798
799
800
801
802
}

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;
}

803
int nft_restart(struct nft_handle *h)
804
{
805
	mnl_socket_close(h->nl);
806

807
808
809
	h->nl = mnl_socket_open(NETLINK_NETFILTER);
	if (h->nl == NULL)
		return -1;
810

811
812
	if (mnl_socket_bind(h->nl, 0, MNL_SOCKET_AUTOPID) < 0)
		return -1;
813

814
	h->portid = mnl_socket_get_portid(h->nl);
815
816
	h->nlsndbuffsiz = 0;
	h->nlrcvbuffsiz = 0;
817

818
	return 0;
819
820
}

821
int nft_init(struct nft_handle *h, int family, const struct builtin_table *t)
822
{
823
824
	memset(h, 0, sizeof(*h));

825
826
827
828
	h->nl = mnl_socket_open(NETLINK_NETFILTER);
	if (h->nl == NULL)
		return -1;

829
830
	if (mnl_socket_bind(h->nl, 0, MNL_SOCKET_AUTOPID) < 0) {
		mnl_socket_close(h->nl);
831
		return -1;
832
	}
833

834
835
836
837
	h->ops = nft_family_ops_lookup(family);
	if (!h->ops)
		xtables_error(PARAMETER_PROBLEM, "Unknown family");

838
839
	h->portid = mnl_socket_get_portid(h->nl);
	h->tables = t;
840
	h->cache = &h->__cache[0];
841
	h->family = family;
842
843

	INIT_LIST_HEAD(&h->obj_list);
844
	INIT_LIST_HEAD(&h->err_list);
845
846
	INIT_LIST_HEAD(&h->cmd_list);
	INIT_LIST_HEAD(&h->cache_req.chain_list);
847
848
849

	return 0;
}
850
851
852

void nft_fini(struct nft_handle *h)
{
853
854
855
856
857
858
859
860
861
862
863
864
	struct list_head *pos, *n;

	list_for_each_safe(pos, n, &h->cmd_list)
		nft_cmd_free(list_entry(pos, struct nft_cmd, head));

	list_for_each_safe(pos, n, &h->obj_list)
		batch_obj_del(h, list_entry(pos, struct obj_update, head));

	list_for_each_safe(pos, n, &h->err_list)
		mnl_err_list_free(list_entry(pos, struct mnl_err, head));

	nft_release_cache(h);
865
866
867
868
869
870
871
872
	mnl_socket_close(h->nl);
}

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

873
	nftnl_chain_snprintf(tmp, sizeof(tmp), c, 0, 0);
874
875
876
877
878
879
880
881
882
883
884
	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;
885
886
	const struct builtin_table *_t;
	const struct builtin_chain *_c;
887
888

	_t = nft_table_builtin_find(h, table);
889
890
891
892
893
	if (!_t) {
		errno = ENXIO;
		return NULL;
	}

894
	/* if this built-in table does not exists, create it */
895
	nft_table_builtin_add(h, _t);
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930

	_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);
931
932
	else
		errno = EINVAL;
933
934
935
936

	if (c == NULL)
		return 0;

937
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_UPDATE, c);
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959

	/* 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;
}

960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
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;
}

996
997
998
999
1000
1001
static struct nftnl_set *add_anon_set(struct nft_handle *h, const char *table,
				      uint32_t flags, uint32_t key_type,
				      uint32_t key_len, uint32_t size)
{
	static uint32_t set_id = 0;
	struct nftnl_set *s;
1002
	struct nft_cmd *cmd;
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017

	s = nftnl_set_alloc();
	if (!s)
		return NULL;

	nftnl_set_set_u32(s, NFTNL_SET_FAMILY, h->family);
	nftnl_set_set_str(s, NFTNL_SET_TABLE, table);
	nftnl_set_set_str(s, NFTNL_SET_NAME, "__set%d");
	nftnl_set_set_u32(s, NFTNL_SET_ID, ++set_id);
	nftnl_set_set_u32(s, NFTNL_SET_FLAGS,
			  NFT_SET_ANONYMOUS | NFT_SET_CONSTANT | flags);
	nftnl_set_set_u32(s, NFTNL_SET_KEY_TYPE, key_type);
	nftnl_set_set_u32(s, NFTNL_SET_KEY_LEN, key_len);
	nftnl_set_set_u32(s, NFTNL_SET_DESC_SIZE, size);

1018
1019
1020
1021
1022
1023
1024
1025
	cmd = nft_cmd_new(h, NFT_COMPAT_SET_ADD, table, NULL, NULL, -1, false);
	if (!cmd) {
		nftnl_set_free(s);
		return NULL;
	}
	cmd->obj.set = s;

	return s;
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
}

static struct nftnl_expr *
gen_payload(uint32_t base, uint32_t offset, uint32_t len, uint32_t dreg)
{
	struct nftnl_expr *e = nftnl_expr_alloc("payload");

	if (!e)
		return NULL;
	nftnl_expr_set_u32(e, NFTNL_EXPR_PAYLOAD_BASE, base);
	nftnl_expr_set_u32(e, NFTNL_EXPR_PAYLOAD_OFFSET, offset);
	nftnl_expr_set_u32(e, NFTNL_EXPR_PAYLOAD_LEN, len);
	nftnl_expr_set_u32(e, NFTNL_EXPR_PAYLOAD_DREG, dreg);
	return e;
}

static struct nftnl_expr *
gen_lookup(uint32_t sreg, const char *set_name, uint32_t set_id, uint32_t flags)
{
	struct nftnl_expr *e = nftnl_expr_alloc("lookup");

	if (!e)
		return NULL;
	nftnl_expr_set_u32(e, NFTNL_EXPR_LOOKUP_SREG, sreg);
	nftnl_expr_set_str(e, NFTNL_EXPR_LOOKUP_SET, set_name);
	nftnl_expr_set_u32(e, NFTNL_EXPR_LOOKUP_SET_ID, set_id);
	nftnl_expr_set_u32(e, NFTNL_EXPR_LOOKUP_FLAGS, flags);
	return e;
}

/* simplified nftables:include/netlink.h, netlink_padded_len() */
#define NETLINK_ALIGN		4

/* from nftables:include/datatype.h, TYPE_BITS */
#define CONCAT_TYPE_BITS	6

/* from nftables:include/datatype.h, enum datatypes */
#define NFT_DATATYPE_IPADDR	7
#define NFT_DATATYPE_ETHERADDR	9

static int __add_nft_among(struct nft_handle *h, const char *table,
			   struct nftnl_rule *r, struct nft_among_pair *pairs,
			   int cnt, bool dst, bool inv, bool ip)
{
	uint32_t set_id, type = NFT_DATATYPE_ETHERADDR, len = ETH_ALEN;
	/* { !dst, dst } */
	static const int eth_addr_off[] = {
		offsetof(struct ether_header, ether_shost),
		offsetof(struct ether_header, ether_dhost)
	};
	static const int ip_addr_off[] = {
		offsetof(struct iphdr, saddr),
		offsetof(struct iphdr, daddr)
	};
	struct nftnl_expr *e;
	struct nftnl_set *s;
1082
	uint32_t flags = 0;
1083
1084
1085
1086
1087
1088
	int idx = 0;

	if (ip) {
		type = type << CONCAT_TYPE_BITS | NFT_DATATYPE_IPADDR;
		len += sizeof(struct in_addr) + NETLINK_ALIGN - 1;
		len &= ~(NETLINK_ALIGN - 1);
1089
		flags = NFT_SET_INTERVAL;
1090
1091
	}

1092
	s = add_anon_set(h, table, flags, type, len, cnt);
1093
1094
1095
1096
	if (!s)
		return -ENOMEM;
	set_id = nftnl_set_get_u32(s, NFTNL_SET_ID);

1097
1098
1099
1100
1101
1102
1103
	if (ip) {
		uint8_t field_len[2] = { ETH_ALEN, sizeof(struct in_addr) };

		nftnl_set_set_data(s, NFTNL_SET_DESC_CONCAT,
				   field_len, sizeof(field_len));
	}

1104
1105
1106
1107
1108
1109
1110
	for (idx = 0; idx < cnt; idx++) {
		struct nftnl_set_elem *elem = nftnl_set_elem_alloc();

		if (!elem)
			return -ENOMEM;
		nftnl_set_elem_set(elem, NFTNL_SET_ELEM_KEY,
				   &pairs[idx], len);
1111
1112
1113
1114
1115
1116
1117
1118
1119
		if (ip) {
			struct in_addr tmp = pairs[idx].in;

			if (tmp.s_addr == INADDR_ANY)
				pairs[idx].in.s_addr = INADDR_BROADCAST;
			nftnl_set_elem_set(elem, NFTNL_SET_ELEM_KEY_END,
					   &pairs[idx], len);
			pairs[idx].in = tmp;
		}
1120
1121
1122
1123
1124
1125
1126
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
1169
1170
		nftnl_set_elem_add(s, elem);
	}

	e = gen_payload(NFT_PAYLOAD_LL_HEADER,
			eth_addr_off[dst], ETH_ALEN, NFT_REG_1);
	if (!e)
		return -ENOMEM;
	nftnl_rule_add_expr(r, e);

	if (ip) {
		e = gen_payload(NFT_PAYLOAD_NETWORK_HEADER, ip_addr_off[dst],
				sizeof(struct in_addr), NFT_REG32_02);
		if (!e)
			return -ENOMEM;
		nftnl_rule_add_expr(r, e);
	}

	e = gen_lookup(NFT_REG_1, "__set%d", set_id, inv);
	if (!e)
		return -ENOMEM;
	nftnl_rule_add_expr(r, e);

	return 0;
}

static int add_nft_among(struct nft_handle *h,
			 struct nftnl_rule *r, struct xt_entry_match *m)
{
	struct nft_among_data *data = (struct nft_among_data *)m->data;
	const char *table = nftnl_rule_get(r, NFTNL_RULE_TABLE);

	if ((data->src.cnt && data->src.ip) ||
	    (data->dst.cnt && data->dst.ip)) {
		uint16_t eth_p_ip = htons(ETH_P_IP);

		add_meta(r, NFT_META_PROTOCOL);
		add_cmp_ptr(r, NFT_CMP_EQ, &eth_p_ip, 2);
	}

	if (data->src.cnt)
		__add_nft_among(h, table, r, data->pairs, data->src.cnt,
				false, data->src.inv, data->src.ip);
	if (data->dst.cnt)
		__add_nft_among(h, table, r, data->pairs + data->src.cnt,
				data->dst.cnt, true, data->dst.inv,
				data->dst.ip);
	return 0;
}

int add_match(struct nft_handle *h,
	      struct nftnl_rule *r, struct xt_entry_match *m)
1171
1172
1173
1174
{
	struct nftnl_expr *expr;
	int ret;

1175
1176
	if (!strcmp(m->u.user.name, "limit"))
		return add_nft_limit(r, m);
1177
1178
	else if (!strcmp(m->u.user.name, "among"))
		return add_nft_among(h, r, m);
1179

1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
	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;
}

1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
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;
}

1230
1231
1232
1233
1234
int add_target(struct nftnl_rule *r, struct xt_entry_target *t)
{
	struct nftnl_expr *expr;
	int ret;

1235
1236
1237
	if (strcmp(t->u.user.name, "TRACE") == 0)
		return add_meta_nftrace(r);

1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
	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];

1310
	nftnl_rule_snprintf(tmp, sizeof(tmp), r, 0, 0);
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
	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;
}

1332
1333
enum udata_type {
	UDATA_TYPE_COMMENT,
1334
	UDATA_TYPE_EBTABLES_POLICY,
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
	__UDATA_TYPE_MAX,
};
#define UDATA_TYPE_MAX (__UDATA_TYPE_MAX - 1)

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;
1351
1352
	case UDATA_TYPE_EBTABLES_POLICY:
		break;
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
	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]);
}

1373
1374
1375
1376
1377
1378
1379
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);
}

1380
struct nftnl_rule *
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
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);
1391
1392
	nftnl_rule_set_str(r, NFTNL_RULE_TABLE, table);
	nftnl_rule_set_str(r, NFTNL_RULE_CHAIN, chain);
1393

1394
	if (h->ops->add(h, r, data) < 0)
1395
1396
1397
1398
1399
1400
1401
1402
		goto err;

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

1403
1404
static struct nftnl_chain *
nft_chain_find(struct nft_handle *h, const char *table, const char *chain);
1405

1406
1407
int
nft_rule_append(struct nft_handle *h, const char *chain, const char *table,
1408
		struct nftnl_rule *r, struct nftnl_rule *ref, bool verbose)
1409
{
1410
	struct nftnl_chain *c;
1411
1412
	int type;

1413
1414
	nft_xt_builtin_init(h, table);

1415
1416
	nft_fn = nft_rule_append;

1417
1418
1419
	if (ref) {
		nftnl_rule_set_u64(r, NFTNL_RULE_HANDLE,
				   nftnl_rule_get_u64(ref, NFTNL_RULE_HANDLE));
1420
1421
1422
1423
		type = NFT_COMPAT_RULE_REPLACE;
	} else
		type = NFT_COMPAT_RULE_APPEND;

1424
	if (batch_rule_add(h, type, r) == NULL)
1425
		return 0;
1426

1427
	if (verbose)
1428
		h->ops->print_rule(h, r, 0, FMT_PRINT_RULE);
1429

1430
1431
	if (ref) {
		nftnl_chain_rule_insert_at(r, ref);
1432
1433
		nftnl_chain_rule_del(ref);
		nftnl_rule_free(ref);
1434
1435
1436
1437
1438
1439
1440
1441
	} else {
		c = nft_chain_find(h, table, chain);
		if (!c) {
			errno = ENOENT;
			return 0;
		}
		nftnl_chain_rule_add_tail(r, c);
	}
1442

1443
1444
1445
1446
	return 1;
}

void
1447
1448
nft_rule_print_save(struct nft_handle *h, const struct nftnl_rule *r,
		    enum nft_rule_print type, unsigned int format)
1449
1450
{
	const char *chain = nftnl_rule_get_str(r, NFTNL_RULE_CHAIN);
1451
	struct iptables_command_state cs = {};
1452
	struct nft_family_ops *ops = h->ops;
1453

1454
	ops->rule_to_cs(h, r, &cs);
1455

1456
1457
1458
	if (!(format & (FMT_NOCOUNTS | FMT_C_COUNTS)))
		printf("[%llu:%llu] ", (unsigned long long)cs.counters.pcnt,
				       (unsigned long long)cs.counters.bcnt);
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469

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

1470
1471
	if (ops->save_rule)
		ops->save_rule(&cs, format);
1472

1473
1474
	if (ops->clear_cs)
		ops->clear_cs(&cs);
1475
1476
}

1477
1478
1479
1480
1481
1482
1483
1484
static bool nft_rule_is_policy_rule(struct nftnl_rule *r)
{
	const struct nftnl_udata *tb[UDATA_TYPE_MAX + 1] = {};
	const void *data;
	uint32_t len;

	if (!nftnl_rule_is_set(r, NFTNL_RULE_USERDATA))
		return false;
1485

1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
	data = nftnl_rule_get_data(r, NFTNL_RULE_USERDATA, &len);
	if (nftnl_udata_parse(data, len, parse_udata_cb, tb) < 0)
		return NULL;

	if (!tb[UDATA_TYPE_EBTABLES_POLICY] ||
	    nftnl_udata_get_u32(tb[UDATA_TYPE_EBTABLES_POLICY]) != 1)
		return false;

	return true;
}

static struct nftnl_rule *nft_chain_last_rule(struct nftnl_chain *c)
1498
{
1499
1500
	struct nftnl_rule *r = NULL, *last;
	struct nftnl_rule_iter *iter;
1501

1502
1503
1504
	iter = nftnl_rule_iter_create(c);
	if (!iter)
		return NULL;
1505

1506
1507
1508
1509
1510
	do {
		last = r;
		r = nftnl_rule_iter_next(iter);
	} while (r);
	nftnl_rule_iter_destroy(iter);
1511

1512
1513
	return last;
}
1514

1515
1516
void nft_bridge_chain_postprocess(struct nft_handle *h,
				  struct nftnl_chain *c)
1517
1518
1519
1520
1521
{
	struct nftnl_rule *last = nft_chain_last_rule(c);
	struct nftnl_expr_iter *iter;
	struct nftnl_expr *expr;
	int verdict;
1522

1523
1524
	if (!last || !nft_rule_is_policy_rule(last))
		return;
1525

1526
1527
1528
	iter = nftnl_expr_iter_create(last);
	if (!iter)
		return;
1529

1530
1531
1532
1533
	expr = nftnl_expr_iter_next(iter);
	if (!expr ||
	    strcmp("counter", nftnl_expr_get_str(expr, NFTNL_EXPR_NAME)))
		goto out_iter;
1534

1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
	expr = nftnl_expr_iter_next(iter);
	if (!expr ||
	    strcmp("immediate", nftnl_expr_get_str(expr, NFTNL_EXPR_NAME)) ||
	    !nftnl_expr_is_set(expr, NFTNL_EXPR_IMM_VERDICT))
		goto out_iter;

	verdict = nftnl_expr_get_u32(expr, NFTNL_EXPR_IMM_VERDICT);
	switch (verdict) {
	case NF_ACCEPT:
	case NF_DROP:
		break;
	default:
		goto out_iter;
	}
1549

1550
1551
1552
1553
1554
1555
	nftnl_chain_set_u32(c, NFTNL_CHAIN_POLICY, verdict);
	if (batch_rule_add(h, NFT_COMPAT_RULE_DELETE, last) == NULL)
		fprintf(stderr, "Failed to delete old policy rule\n");
	nftnl_chain_rule_del(last);
out_iter:
	nftnl_expr_iter_destroy(iter);
1556
}
1557
1558
1559
static const char *policy_name[NF_ACCEPT+1] = {
	[NF_DROP] = "DROP",
	[NF_ACCEPT] = "ACCEPT",
1560
1561
};

1562
int nft_chain_save(struct nft_handle *h, struct nftnl_chain_list *list)
1563
{
1564
	struct nft_family_ops *ops = h->ops;
1565
1566
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;
1567

1568
1569
	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
1570
1571
		return 0;

1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		const char *policy = NULL;

		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];
		} else if (h->family == NFPROTO_BRIDGE) {
			if (nftnl_chain_is_set(c, NFTNL_CHAIN_POLICY)) {
				uint32_t pol;

				pol = nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY);
				policy = policy_name[pol];
			} else {
				policy = "RETURN";
			}
		}

		if (ops->save_chain)
			ops->save_chain(c, policy);

		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);

	return 1;
}
1603

1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
static int nft_chain_save_rules(struct nft_handle *h,
				struct nftnl_chain *c, unsigned int format)
{
	struct nftnl_rule_iter *iter;
	struct nftnl_rule *r;

	iter = nftnl_rule_iter_create(c);
	if (iter == NULL)
		return 1;

	r = nftnl_rule_iter_next(iter);
	while (r != NULL) {
1616
		nft_rule_print_save(h, r, NFT_RULE_APPEND, format);
1617
1618
1619
1620
		r = nftnl_rule_iter_next(iter);
	}

	nftnl_rule_iter_destroy(iter);
1621
1622
1623
	return 0;
}

1624
int nft_rule_save(struct nft_handle *h, const char *table, unsigned int format)
1625
{
1626
1627
1628
1629
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain_list *list;
	struct nftnl_chain *c;
	int ret = 0;
1630

1631
	list = nft_chain_list_get(h, table, NULL);
1632
1633
	if (!list)
		return 0;
1634

1635
1636
1637
	iter = nftnl_chain_list_iter_create(list);
	if (!iter)
		return 0;
1638

1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
	c = nftnl_chain_list_iter_next(iter);
	while (c) {
		ret = nft_chain_save_rules(h, c, format);
		if (ret != 0)
			break;

		c = nftnl_chain_list_iter_next(iter);
	}

	nftnl_chain_list_iter_destroy(iter);

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

1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
struct nftnl_set *nft_set_batch_lookup_byid(struct nft_handle *h,
					    uint32_t set_id)
{
	struct obj_update *n;

	list_for_each_entry(n, &h->obj_list, head) {
		if (n->type == NFT_COMPAT_SET_ADD &&
		    nftnl_set_get_u32(n->set, NFTNL_SET_ID) == set_id)
			return n->set;
	}

	return NULL;
}

1668
1669
1670
1671
1672
1673
1674
static void
__nft_rule_flush(struct nft_handle *h, const char *table,
		 const char *chain, bool verbose, bool implicit)
{
	struct obj_update *obj;
	struct nftnl_rule *r;

1675
	if (verbose && chain)
1676
1677
1678
1679
1680
1681
		fprintf(stdout, "Flushing chain `%s'\n", chain);

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

1682
1683
1684
	nftnl_rule_set_str(r, NFTNL_RULE_TABLE, table);
	if (chain)
		nftnl_rule_set_str(r, NFTNL_RULE_CHAIN, chain);
1685
1686
1687
1688
1689
1690
1691
1692

	obj = batch_rule_add(h, NFT_COMPAT_RULE_FLUSH, r);
	if (!obj) {
		nftnl_rule_free(r);
		return;
	}

	obj->implicit = implicit;
1693
1694
}

1695
1696
int nft_rule_flush(struct nft_handle *h, const char *chain, const char *table,
		   bool verbose)
1697
1698
{
	struct nftnl_chain_list_iter *iter;
1699
1700
1701
	struct nftnl_chain_list *list;
	struct nftnl_chain *c = NULL;
	int ret = 0;
1702

1703
	nft_xt_builtin_init(h, table);
1704

1705
1706
	nft_fn = nft_rule_flush;

1707
1708
1709
1710
1711
1712
	if (chain || verbose) {
		list = nft_chain_list_get(h, table, chain);
		if (list == NULL) {
			ret = 1;
			goto err;
		}
1713
1714
	}

1715
1716
	if (chain) {
		c = nftnl_chain_list_lookup_byname(list, chain);
1717
1718
		if (!c) {
			errno = ENOENT;
1719
			return 0;
1720
1721
		}
	}
1722

1723
	if (chain || !verbose) {
1724
		batch_chain_flush(h, table, chain);
1725
		__nft_rule_flush(h, table, chain, verbose, false);
1726
		flush_rule_cache(h, table, c);
1727
1728
1729
		return 1;
	}

1730
	iter = nftnl_chain_list_iter_create(list);
1731
1732
	if (iter == NULL) {
		ret = 1;
1733
		goto err;
1734
	}
1735
1736
1737

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
1738
		chain = nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
1739

1740
		batch_chain_flush(h, table, chain);
1741
1742
		__nft_rule_flush(h, table, chain, verbose, false);
		flush_rule_cache(h, table, c);
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
		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;
}

int nft_chain_user_add(struct nft_handle *h, const char *chain, const char *table)
{
1753
	struct nftnl_chain_list *list;
1754
1755
1756
1757
1758
	struct nftnl_chain *c;
	int ret;

	nft_fn = nft_chain_user_add;

1759
	nft_xt_builtin_init(h, table);
1760

1761
1762
1763
1764
1765
	if (nft_chain_exists(h, table, chain)) {
		errno = EEXIST;
		return 0;
	}

1766
1767
1768
1769
	c = nftnl_chain_alloc();
	if (c == NULL)
		return 0;

1770
1771
	nftnl_chain_set_str(c, NFTNL_CHAIN_TABLE, table);
	nftnl_chain_set_str(c, NFTNL_CHAIN_NAME, chain);
1772
1773
	if (h->family == NFPROTO_BRIDGE)
		nftnl_chain_set_u32(c, NFTNL_CHAIN_POLICY, NF_ACCEPT);
1774

1775
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_USER_ADD, c);
1776

1777
	list = nft_chain_list_get(h, table, chain);
1778
1779
	if (list)
		nftnl_chain_list_add(c, list);
1780
1781
1782
1783
1784

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

1785
int nft_chain_restore(struct nft_handle *h, const char *chain, const char *table)
1786
1787
1788
{
	struct nftnl_chain_list *list;
	struct nftnl_chain *c;
1789
1790
	bool created = false;
	int ret;
1791

1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
	c = nft_chain_find(h, table, chain);
	if (c) {
		/* Apparently -n still flushes existing user defined
		 * chains that are redefined.
		 */
		if (h->noflush)
			__nft_rule_flush(h, table, chain, false, true);
	} else {
		c = nftnl_chain_alloc();
		if (!c)
1802
			return 0;
1803

1804
1805
		nftnl_chain_set_str(c, NFTNL_CHAIN_TABLE, table);
		nftnl_chain_set_str(c, NFTNL_CHAIN_NAME, chain);
1806
1807
		created = true;
	}
1808

1809
1810
	if (h->family == NFPROTO_BRIDGE)
		nftnl_chain_set_u32(c, NFTNL_CHAIN_POLICY, NF_ACCEPT);
1811

1812
	if (!created)
1813
		return 1;
1814

1815
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_USER_ADD, c);
1816

1817
	list = nft_chain_list_get(h, table, chain);
1818
1819
	if (list)
		nftnl_chain_list_add(c, list);
1820

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

1825
1826
1827
1828
/* From linux/netlink.h */
#ifndef NLM_F_NONREC
#define NLM_F_NONREC	0x100	/* Do not delete recursively    */
#endif
1829

1830
1831
1832
1833
1834
struct chain_user_del_data {
	struct nft_handle	*handle;
	bool			verbose;
	int			builtin_err;
};
1835

1836
1837
1838
1839
1840
static int __nft_chain_user_del(struct nftnl_chain *c, void *data)
{
	struct chain_user_del_data *d = data;
	struct nft_handle *h = d->handle;
	int ret;
1841

1842
1843
1844
	/* don't delete built-in chain */
	if (nft_chain_builtin(c))
		return d->builtin_err;
1845

1846
1847
1848
	if (d->verbose)
		fprintf(stdout, "Deleting chain `%s'\n",
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME));
1849

1850
1851
1852
1853
1854
	/* XXX This triggers a fast lookup from the kernel. */
	nftnl_chain_unset(c, NFTNL_CHAIN_HANDLE);
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_USER_DEL, c);
	if (ret)
		return -1;
1855

1856
1857
	nftnl_chain_list_del(c);
	return 0;
1858
1859
}

1860
1861
int nft_chain_user_del(struct nft_handle *h, const char *chain,
		       const char *table, bool verbose)
1862
{
1863
1864
1865
1866
1867
	struct chain_user_del_data d = {
		.handle = h,
		.verbose = verbose,
	};
	struct nftnl_chain_list *list;
1868
	struct nftnl_chain *c;
1869
	int ret = 0;
1870

1871
	nft_fn = nft_chain_user_del;
1872

1873
	list = nft_chain_list_get(h, table, chain);
1874
1875
	if (list == NULL)
		return 0;
1876

1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
	if (chain) {
		c = nftnl_chain_list_lookup_byname(list, chain);
		if (!c) {
			errno = ENOENT;
			return 0;
		}
		d.builtin_err = -2;
		ret = __nft_chain_user_del(c, &d);
		if (ret == -2)
			errno = EINVAL;
		goto out;
1888
	}
1889
1890
1891
1892
1893

	ret = nftnl_chain_list_foreach(list, __nft_chain_user_del, &d);
out:
	/* the core expects 1 for success and 0 for error */
	return ret == 0 ? 1 : 0;
1894
1895
1896
1897
1898
1899
1900
}

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

1901
	list = nft_chain_list_get(h, table, chain);
1902
1903
1904
	if (list == NULL)
		return NULL;

1905
	return nftnl_chain_list_lookup_byname(list, chain);
1906
1907
}

1908
1909
1910
bool nft_chain_exists(struct nft_handle *h,
		      const char *table, const char *chain)
{
1911
	const struct builtin_table *t = nft_table_builtin_find(h, table);
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922

	/* 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);
}

1923
1924
1925
1926
1927
1928
1929
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;

1930
1931
1932
1933
1934
1935
	nft_fn = nft_chain_user_rename;

	if (nft_chain_exists(h, table, newname)) {
		errno = EEXIST;
		return 0;
	}
1936

1937
	nft_xt_builtin_init(h, table);
1938
1939
1940
1941
1942
1943
1944
1945

	/* 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;
1946
		return 0;
1947
1948
1949
1950
1951
1952
	}
	handle = nftnl_chain_get_u64(c, NFTNL_CHAIN_HANDLE);

	/* Now prepare the new name for the chain */
	c = nftnl_chain_alloc();
	if (c == NULL)
1953
		return 0;
1954

1955
1956
	nftnl_chain_set_str(c, NFTNL_CHAIN_TABLE, table);
	nftnl_chain_set_str(c, NFTNL_CHAIN_NAME, newname);
1957
1958
	nftnl_chain_set_u64(c, NFTNL_CHAIN_HANDLE, handle);

1959
	ret = batch_chain_add(h, NFT_COMPAT_CHAIN_RENAME, c);
1960
1961
1962
1963
1964
1965
1966
1967

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

bool nft_table_find(struct nft_handle *h, const char *tablename)
{
	struct nftnl_table_list_iter *iter;
1968
	struct nftnl_table_list *list;
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
	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);

1985
1986
1987
1988
		if (strcmp(tablename, this_tablename) == 0) {
			ret = true;
			break;
		}
1989
1990
1991
1992

		t = nftnl_table_list_iter_next(iter);
	}

1993
	nftnl_table_list_iter_destroy(iter);
1994
1995
1996
1997
1998
1999

err:
	return ret;
}

int nft_for_each_table(struct nft_handle *h,
2000
2001
		       int (*func)(struct nft_handle *h, const char *tablename, void *data),
		       void *data)
2002
2003
2004
2005
2006
2007
{
	struct nftnl_table_list *list;
	struct nftnl_table_list_iter *iter;
	struct nftnl_table *t;

	list = nftnl_table_list_get(h);
2008
2009
	if (list == NULL)
		return -1;
2010
2011
2012

	iter = nftnl_table_list_iter_create(list);
	if (iter == NULL)
2013
		return -1;
2014
2015
2016
2017
2018
2019

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

2020
		func(h, tablename, data);
2021
2022
2023
2024

		t = nftnl_table_list_iter_next(iter);
	}

2025
	nftnl_table_list_iter_destroy(iter);
2026
2027
	return 0;
}
2028

2029
static int __nft_table_flush(struct nft_handle *h, const char *table, bool exists)
2030
{
2031
2032
	const struct builtin_table *_t;
	struct obj_update *obj;
2033
2034
2035
2036
2037
2038
2039
2040
	struct nftnl_table *t;

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

	nftnl_table_set_str(t, NFTNL_TABLE_NAME, table);

2041
2042
2043
2044
2045
2046
2047
2048
	obj = batch_table_add(h, NFT_COMPAT_TABLE_FLUSH, t);
	if (!obj) {
		nftnl_table_free(t);
		return -1;
	}

	if (!exists)
		obj->skip = 1;
2049
2050

	_t = nft_table_builtin_find(h, table);
2051
	assert(_t);
2052
	h->cache->table[_t->type].initialized = false;
2053
2054
2055
2056

	flush_chain_cache(h, table);

	return 0;
2057
2058
}

2059
int nft_table_flush(struct nft_handle *h, const char *table)
2060
{
2061
2062
2063
	struct nftnl_table_list_iter *iter;
	struct nftnl_table_list *list;
	struct nftnl_table *t;
2064
	bool exists = false;
2065
	int ret = 0;
2066

2067
	nft_fn = nft_table_flush;
2068

2069
2070
2071
2072
2073
	list = nftnl_table_list_get(h);
	if (list == NULL) {
		ret = -1;
		goto err_out;
	}
2074

2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
	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);
2085

2086
2087
2088
2089
		if (strcmp(table_name, table) == 0) {
			exists = true;
			break;
		}
2090

2091
		t = nftnl_table_list_iter_next(iter);
2092
2093
	}

2094
	ret = __nft_table_flush(h, table, exists);
2095
2096
2097
2098
2099
2100
2101
2102
2103
	nftnl_table_list_iter_destroy(iter);
err_table_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)
{
2104
	nft_xt_builtin_init(h, table);
2105
2106
}

2107
static int __nft_rule_del(struct nft_handle *h, struct nftnl_rule *r)
2108
{
2109
	struct obj_update *obj;
2110
2111
2112

	nftnl_rule_list_del(r);

2113
2114
2115
	if (!nftnl_rule_get_u64(r, NFTNL_RULE_HANDLE))
		nftnl_rule_set_u32(r, NFTNL_RULE_ID, ++h->rule_id);

2116
2117
	obj = batch_rule_add(h, NFT_COMPAT_RULE_DELETE, r);
	if (!obj) {
2118
2119
2120
2121
2122
2123
		nftnl_rule_free(r);
		return -1;
	}
	return 1;
}

2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
static bool nft_rule_cmp(struct nft_handle *h, struct nftnl_rule *r,
			 struct nftnl_rule *rule)
{
	struct iptables_command_state _cs = {}, this = {}, *cs = &_cs;
	bool ret = false;

	h->ops->rule_to_cs(h, r, &this);
	h->ops->rule_to_cs(h, rule, cs);

	DEBUGP("comparing with... ");
#ifdef DEBUG_DEL
	nft_rule_print_save(h, r, NFT_RULE_APPEND, 0);
#endif
	if (!h->ops->is_same(cs, &this))
		goto out;

	if (!compare_matches(cs->matches, this.matches)) {
		DEBUGP("Different matches\n");
		goto out;
	}

	if (!compare_targets(cs->target, this.target)) {
		DEBUGP("Different target\n");
		goto out;
	}

	if ((!cs->target || !this.target) &&
	    strcmp(cs->jumpto, this.jumpto) != 0) {
		DEBUGP("Different verdict\n");
		goto out;
	}

	ret = true;
out:
	h->ops->clear_cs(&this);
	h->ops->clear_cs(cs);
	return ret;
}

2163
static struct nftnl_rule *
2164
2165
nft_rule_find(struct nft_handle *h, struct nftnl_chain *c,
	      struct nftnl_rule *rule, int rulenum)
2166
2167
{
	struct nftnl_rule *r;
2168
	struct nftnl_rule_iter *iter;
2169
2170
	bool found = false;

2171
2172
2173
2174
2175
	if (rulenum >= 0)
		/* Delete by rule number case */
		return nftnl_rule_lookup_byindex(c, rulenum);

	iter = nftnl_rule_iter_create(c);
2176
2177
2178
	if (iter == NULL)
		return 0;

2179
	r = nftnl_rule_iter_next(iter);
2180
	while (r != NULL) {
2181
		found = nft_rule_cmp(h, r, rule);
2182
2183
2184
		if (found)
			break;
		r = nftnl_rule_iter_next(iter);
2185
2186
	}

2187
	nftnl_rule_iter_destroy(iter);
2188
2189
2190
2191
2192

	return found ? r : NULL;
}

int nft_rule_check(struct nft_handle *h, const char *chain,
2193
		   const char *table, struct nftnl_rule *rule, bool verbose)
2194
{
2195
	struct nftnl_chain *c;
2196
	struct nftnl_rule *r;
2197
2198
2199

	nft_fn = nft_rule_check;

2200
2201
2202
2203
	c = nft_chain_find(h, table, chain);
	if (!c)
		goto fail_enoent;

2204
	r = nft_rule_find(h, c, rule, -1);
2205
2206
	if (r == NULL)
		goto fail_enoent;
2207

2208
	if (verbose)
2209
		h->ops->print_rule(h, r, 0, FMT_PRINT_RULE);
2210

2211
	return 1;
2212
2213
2214
fail_enoent:
	errno = ENOENT;
	return 0;
2215
2216
2217
}

int nft_rule_delete(struct nft_handle *h, const char *chain,
2218
		    const char *table, struct nftnl_rule *rule, bool verbose)
2219
2220
{
	int ret = 0;
2221
	struct nftnl_chain *c;
2222
2223
2224
2225
	struct nftnl_rule *r;

	nft_fn = nft_rule_delete;

2226
2227
2228
	c = nft_chain_find(h, table, chain);
	if (!c) {
		errno = ENOENT;
2229
		return 0;
2230
	}
2231

2232
	r = nft_rule_find(h, c, rule, -1);
2233
	if (r != NULL) {
2234
		ret =__nft_rule_del(h, r);
2235
2236
		if (ret < 0)
			errno = ENOMEM;
2237
		if (verbose)
2238
			h->ops->print_rule(h, r, 0, FMT_PRINT_RULE);
2239
2240
2241
2242
2243
2244
	} else
		errno = ENOENT;

	return ret;
}

2245
static struct nftnl_rule *
2246
nft_rule_add(struct nft_handle *h, const char *chain,
2247
	     const char *table, struct nftnl_rule *r,
2248
	     struct nftnl_rule *ref, bool verbose)
2249
{
2250
	uint64_t ref_id;
2251

2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
	if (ref) {
		ref_id = nftnl_rule_get_u64(ref, NFTNL_RULE_HANDLE);
		if (ref_id > 0) {
			nftnl_rule_set_u64(r, NFTNL_RULE_POSITION, ref_id);
			DEBUGP("adding after rule handle %"PRIu64"\n", ref_id);
		} else {
			ref_id = nftnl_rule_get_u32(ref, NFTNL_RULE_ID);
			if (!ref_id) {
				ref_id = ++h->rule_id;
				nftnl_rule_set_u32(ref, NFTNL_RULE_ID, ref_id);
			}
			nftnl_rule_set_u32(r, NFTNL_RULE_POSITION_ID, ref_id);
			DEBUGP("adding after rule ID %"PRIu64"\n", ref_id);
		}
	}
2267

2268
	if (!batch_rule_add(h, NFT_COMPAT_RULE_INSERT, r))
2269
		return NULL;
2270

2271
	if (verbose)
2272
		h->ops->print_rule(h, r, 0, FMT_PRINT_RULE);
2273

2274
	return r;
2275
2276
2277
}

int nft_rule_insert(struct nft_handle *h, const char *chain,
2278
2279
		    const char *table, struct nftnl_rule *new_rule, int rulenum,
		    bool verbose)
2280
{
2281
	struct nftnl_rule *r = NULL;
2282
	struct nftnl_chain *c;
2283

2284
	nft_xt_builtin_init(h, table);
2285
2286
2287

	nft_fn = nft_rule_insert;

2288
2289
2290
2291
2292
	c = nft_chain_find(h, table, chain);
	if (!c) {
		errno = ENOENT;
		goto err;
	}
2293

2294
	if (rulenum > 0) {
2295
		r = nft_rule_find(h, c, new_rule, rulenum);
2296
2297
2298
2299
		if (r == NULL) {
			/* special case: iptables allows to insert into
			 * rule_count + 1 position.
			 */
2300
			r = nft_rule_find(h, c, new_rule, rulenum - 1);
2301
			if (r != NULL)
2302
2303
				return nft_rule_append(h, chain, table,
						       new_rule, NULL, verbose);
2304

2305
			errno = E2BIG;
2306
2307
2308
2309
			goto err;
		}
	}

2310
	new_rule = nft_rule_add(h, chain, table, new_rule, r, verbose);
2311
2312
2313
	if (!new_rule)
		goto err;

2314
2315
	if (r)
		nftnl_chain_rule_insert_at(new_rule, r);
2316
	else
2317
		nftnl_chain_rule_add(new_rule, c);
2318
2319

	return 1;
2320
2321
2322
2323
2324
2325
2326
2327
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;
2328
	struct nftnl_chain *c;
2329
2330
2331
2332
	struct nftnl_rule *r;

	nft_fn = nft_rule_delete_num;

2333
2334
2335
	c = nft_chain_find(h, table, chain);
	if (!c) {
		errno = ENOENT;
2336
		return 0;
2337
	}
2338

2339
	r = nft_rule_find(h, c, NULL, rulenum);
2340
2341
	if (r != NULL) {
		DEBUGP("deleting rule by number %d\n", rulenum);
2342
		ret = __nft_rule_del(h, r);
2343
2344
2345
		if (ret < 0)
			errno = ENOMEM;
	} else
2346
		errno = E2BIG;
2347
2348
2349
2350
2351

	return ret;
}

int nft_rule_replace(struct nft_handle *h, const char *chain,
2352
2353
		     const char *table, struct nftnl_rule *rule,
		     int rulenum, bool verbose)
2354
2355
{
	int ret = 0;
2356
	struct nftnl_chain *c;
2357
2358
2359
2360
	struct nftnl_rule *r;

	nft_fn = nft_rule_replace;

2361
2362
2363
	c = nft_chain_find(h, table, chain);
	if (!c) {
		errno = ENOENT;
2364
		return 0;
2365
	}
2366

2367
	r = nft_rule_find(h, c, rule, rulenum);
2368
2369
2370
2371
2372
	if (r != NULL) {
		DEBUGP("replacing rule with handle=%llu\n",
			(unsigned long long)
			nftnl_rule_get_u64(r, NFTNL_RULE_HANDLE));

2373
		ret = nft_rule_append(h, chain, table, rule, r, verbose);
2374
	} else
2375
		errno = E2BIG;
2376
2377
2378
2379
2380

	return ret;
}

static int
2381
__nft_rule_list(struct nft_handle *h, struct nftnl_chain *c,
2382
		int rulenum, unsigned int format,
2383
2384
		void (*cb)(struct nft_handle *h, struct nftnl_rule *r,
			   unsigned int num, unsigned int format))
2385
{
2386
	struct nftnl_rule_iter *iter;
2387
	struct nftnl_rule *r;
2388
	int rule_ctr = 0;
2389

2390
2391
2392
2393
2394
2395
2396
	if (rulenum > 0) {
		r = nftnl_rule_lookup_byindex(c, rulenum - 1);
		if (!r)
			/* iptables-legacy returns 0 when listing for
			 * valid chain but invalid rule number
			 */
			return 1;
2397
		cb(h, r, rulenum, format);
2398
2399
		return 1;
	}
2400

2401
	iter = nftnl_rule_iter_create(c);
2402
	if (iter == NULL)
2403
		return 0;
2404

2405
	r = nftnl_rule_iter_next(iter);
2406
	while (r != NULL) {
2407
		cb(h, r, ++rule_ctr, format);
2408
		r = nftnl_rule_iter_next(iter);
2409
2410
	}

2411
	nftnl_rule_iter_destroy(iter);
2412
2413
	return 1;
}
2414

2415
static int nft_rule_count(struct nft_handle *h, struct nftnl_chain *c)
2416
{
2417
	struct nftnl_rule_iter *iter;
2418
2419
2420
	struct nftnl_rule *r;
	int rule_ctr = 0;

2421
	iter = nftnl_rule_iter_create(c);
2422
2423
2424
	if (iter == NULL)
		return 0;

2425
	r = nftnl_rule_iter_next(iter);
2426
2427
	while (r != NULL) {
		rule_ctr++;
2428
		r = nftnl_rule_iter_next(iter);
2429
2430
	}

2431
	nftnl_rule_iter_destroy(iter);
2432
	return rule_ctr;
2433
2434
}

2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
static void __nft_print_header(struct nft_handle *h,
			       struct nftnl_chain *c, unsigned int format)
{
	const char *chain_name = nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
	bool basechain = !!nftnl_chain_get(c, NFTNL_CHAIN_HOOKNUM);
	uint32_t refs = nftnl_chain_get_u32(c, NFTNL_CHAIN_USE);
	uint32_t entries = nft_rule_count(h, c);
	struct xt_counters ctrs = {
		.pcnt = nftnl_chain_get_u64(c, NFTNL_CHAIN_PACKETS),
		.bcnt = nftnl_chain_get_u64(c, NFTNL_CHAIN_BYTES),
	};
	const char *pname = NULL;

	if (nftnl_chain_is_set(c, NFTNL_CHAIN_POLICY))
		pname = policy_name[nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY)];

2451
	h->ops->print_header(format, chain_name, pname,
2452
2453
2454
			&ctrs, basechain, refs - entries, entries);
}

2455
2456
2457
int nft_rule_list(struct nft_handle *h, const char *chain, const char *table,
		  int rulenum, unsigned int format)
{
2458
	const struct nft_family_ops *ops = h->ops;
2459
2460
2461
2462
2463
	struct nftnl_chain_list *list;
	struct nftnl_chain_list_iter *iter;
	struct nftnl_chain *c;
	bool found = false;

2464
2465
	nft_xt_builtin_init(h, table);
	nft_assert_table_compatible(h, table, chain);
2466

2467
	list = nft_chain_list_get(h, table, chain);
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
	if (!list)
		return 0;

	if (chain) {
		c = nftnl_chain_list_lookup_byname(list, chain);
		if (!c)
			return 0;

		if (!rulenum) {
			if (ops->print_table_header)
				ops->print_table_header(table);
2479
			__nft_print_header(h, c, format);
2480
2481
		}
		__nft_rule_list(h, c, rulenum, format, ops->print_rule);
2482
2483
2484
2485
2486
		return 1;
	}

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

2489
	if (ops->print_table_header)
2490
2491
2492
2493
2494
2495
2496
		ops->print_table_header(table);

	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		if (found)
			printf("\n");

2497
		__nft_print_header(h, c, format);
2498
		__nft_rule_list(h, c, rulenum, format, ops->print_rule);
2499
2500

		found = true;
2501
2502
2503
2504
2505
2506
2507
		c = nftnl_chain_list_iter_next(iter);
	}
	nftnl_chain_list_iter_destroy(iter);
	return 1;
}

static void
2508
2509
list_save(struct nft_handle *h, struct nftnl_rule *r,
	  unsigned int num, unsigned int format)
2510
{
2511
	nft_rule_print_save(h, r, NFT_RULE_APPEND, format);
2512
2513
}

2514
static int __nftnl_rule_list_chain_save(struct nftnl_chain *c, void *data)
2515
{
2516
2517
2518
	const char *chain_name = nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
	uint32_t policy = nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY);
	int *counters = data;
2519

2520
2521
	if (!nft_chain_builtin(c)) {
		printf("-N %s\n", chain_name);
2522
		return 0;
2523
	}
2524

2525
	/* this is a base chain */
2526

2527
2528
2529
2530
2531
2532
2533
2534
	printf("-P %s %s", chain_name, policy_name[policy]);
	if (*counters)
		printf(" -c %"PRIu64" %"PRIu64,
		       nftnl_chain_get_u64(c, NFTNL_CHAIN_PACKETS),
		       nftnl_chain_get_u64(c, NFTNL_CHAIN_BYTES));
	printf("\n");
	return 0;
}
2535

2536
2537
2538
2539
2540
static int
nftnl_rule_list_chain_save(struct nft_handle *h, const char *chain,
			   struct nftnl_chain_list *list, int counters)
{
	struct nftnl_chain *c;
2541

2542
2543
2544
2545
2546
2547
2548
2549
	if (chain) {
		c = nftnl_chain_list_lookup_byname(list, chain);
		if (!c)
			return 0;

		__nftnl_rule_list_chain_save(c, &counters);
		return 1;
	}
2550

2551
	nftnl_chain_list_foreach(list, __nftnl_rule_list_chain_save, &counters);
2552
2553
2554
2555
2556
2557
2558
2559
	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;
2560
	unsigned int format = 0;
2561
	struct nftnl_chain *c;
2562
2563
	int ret = 0;

2564
2565
	nft_xt_builtin_init(h, table);
	nft_assert_table_compatible(h, table, chain);
2566

2567
	list = nft_chain_list_get(h, table, chain);
2568
2569
2570
2571
2572
2573
	if (!list)
		return 0;

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

2575
2576
2577
2578
2579
	if (counters < 0)
		format = FMT_C_COUNTS;
	else if (counters == 0)
		format = FMT_NOCOUNTS;

2580
2581
2582
2583
	if (chain) {
		c = nftnl_chain_list_lookup_byname(list, chain);
		if (!c)
			return 0;
2584

2585
2586
		return __nft_rule_list(h, c, rulenum, format, list_save);
	}
2587

2588
2589
2590
2591
	/* Now dump out rules in this table */
	iter = nftnl_chain_list_iter_create(list);
	if (iter == NULL)
		return 0;
2592

2593
2594
2595
	c = nftnl_chain_list_iter_next(iter);
	while (c != NULL) {
		ret = __nft_rule_list(h, c, rulenum, format, list_save);
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
		c = nftnl_chain_list_iter_next(iter);
	}
	nftnl_chain_list_iter_destroy(iter);
	return ret;
}

int nft_rule_zero_counters(struct nft_handle *h, const char *chain,
			   const char *table, int rulenum)
{
	struct iptables_command_state cs = {};
2606
	struct nftnl_rule *r, *new_rule;
2607
	struct nftnl_chain *c;
2608
2609
2610
2611
	int ret = 0;

	nft_fn = nft_rule_delete;

2612
2613
	c = nft_chain_find(h, table, chain);
	if (!c)
2614
2615
		return 0;

2616
	r = nft_rule_find(h, c, NULL, rulenum);
2617
2618
2619
2620
2621
2622
	if (r == NULL) {
		errno = ENOENT;
		ret = 1;
		goto error;
	}

2623
	nft_rule_to_iptables_command_state(h, r, &cs);
2624
2625

	cs.counters.pcnt = cs.counters.bcnt = 0;
2626
2627
2628
	new_rule = nft_rule_new(h, chain, table, &cs);
	if (!new_rule)
		return 1;
2629

2630
	ret = nft_rule_append(h, chain, table, new_rule, r, false);
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641

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;

2642
	nlh = nftnl_table_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
2643
2644
2645
2646
					type, h->family, flags, seq);
	nftnl_table_nlmsg_build_payload(nlh, table);
}

2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
static void nft_compat_set_batch_add(struct nft_handle *h, uint16_t type,
				     uint16_t flags, uint32_t seq,
				     struct nftnl_set *set)
{
	struct nlmsghdr *nlh;

	nlh = nftnl_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
					type, h->family, flags, seq);
	nftnl_set_nlmsg_build_payload(nlh, set);
}

static void nft_compat_setelem_batch_add(struct nft_handle *h, uint16_t type,
					 uint16_t flags, uint32_t *seq,
					 struct nftnl_set *set)
{
	struct nftnl_set_elems_iter *iter;
	struct nlmsghdr *nlh;

	iter = nftnl_set_elems_iter_create(set);
	if (!iter)
		return;

	while (nftnl_set_elems_iter_cur(iter)) {
		(*seq)++;
		mnl_nft_batch_continue(h->batch);
		nlh = nftnl_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
					    type, h->family, flags, *seq);
		if (nftnl_set_elems_nlmsg_build_payload_iter(nlh, iter) <= 0)
			break;
	}
	nftnl_set_elems_iter_destroy(iter);
}

2680
2681
2682
2683
2684
2685
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;

2686
	nlh = nftnl_chain_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
					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;

2698
	nlh = nftnl_rule_nlmsg_build_hdr(nftnl_batch_buffer(h->batch),
2699
2700
2701
				       type, h->family, flags, seq);
	nftnl_rule_nlmsg_build_payload(nlh, rule);
	nft_rule_print_debug(rule, nlh);
2702
2703
2704
2705
2706
2707
2708
2709
2710
}

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;
2711
	case NFT_COMPAT_CHAIN_ZERO:
2712
	case NFT_COMPAT_CHAIN_USER_ADD:
2713
	case NFT_COMPAT_CHAIN_ADD:
2714
		break;
2715
	case NFT_COMPAT_CHAIN_USER_DEL:
2716
2717
2718
2719
2720
2721
2722
2723
2724
	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:
		break;
2725
	case NFT_COMPAT_RULE_DELETE:
2726
2727
2728
	case NFT_COMPAT_RULE_FLUSH:
		nftnl_rule_free(o->rule);
		break;
2729
2730
2731
	case NFT_COMPAT_SET_ADD:
		nftnl_set_free(o->set);
		break;
2732
2733
2734
2735
2736
2737
2738
2739
2740
	case NFT_COMPAT_RULE_LIST:
	case NFT_COMPAT_RULE_CHECK:
	case NFT_COMPAT_CHAIN_RESTORE:
	case NFT_COMPAT_RULE_SAVE:
	case NFT_COMPAT_RULE_ZERO:
	case NFT_COMPAT_BRIDGE_USER_CHAIN_UPDATE:
	case NFT_COMPAT_TABLE_NEW:
		assert(0);
		break;
2741
2742
2743
2744
	}
	h->obj_list_num--;
	list_del(&o->head);
	free(o);
2745
2746
}

2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
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
static void nft_refresh_transaction(struct nft_handle *h)
{
	const char *tablename, *chainname;
	const struct nftnl_chain *c;
	struct obj_update *n, *tmp;
	bool exists;

	h->error.lineno = 0;

	list_for_each_entry_safe(n, tmp, &h->obj_list, head) {
		if (n->implicit) {
			batch_obj_del(h, n);
			continue;
		}

		switch (n->type) {
		case NFT_COMPAT_TABLE_FLUSH:
			tablename = nftnl_table_get_str(n->table, NFTNL_TABLE_NAME);
			if (!tablename)
				continue;
			exists = nft_table_find(h, tablename);
			if (exists)
				n->skip = 0;
			else
				n->skip = 1;
			break;
		case NFT_COMPAT_CHAIN_USER_ADD:
			tablename = nftnl_chain_get_str(n->chain, NFTNL_CHAIN_TABLE);
			if (!tablename)
				continue;

			chainname = nftnl_chain_get_str(n->chain, NFTNL_CHAIN_NAME);
			if (!chainname)
				continue;

			if (!h->noflush)
				break;

			c = nft_chain_find(h, tablename, chainname);
			if (c) {
				/* -restore -n flushes existing rules from redefined user-chain */
				__nft_rule_flush(h, tablename,
						 chainname, false, true);
				n->skip = 1;
			} else if (!c) {
				n->skip = 0;
			}
			break;
		case NFT_COMPAT_TABLE_ADD:
		case NFT_COMPAT_CHAIN_ADD:
		case NFT_COMPAT_CHAIN_ZERO:
		case NFT_COMPAT_CHAIN_USER_DEL:
		case NFT_COMPAT_CHAIN_USER_FLUSH:
		case NFT_COMPAT_CHAIN_UPDATE:
		case NFT_COMPAT_CHAIN_RENAME:
		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:
2807
		case NFT_COMPAT_SET_ADD:
2808
2809
2810
2811
2812
2813
2814
		case NFT_COMPAT_RULE_LIST:
		case NFT_COMPAT_RULE_CHECK:
		case NFT_COMPAT_CHAIN_RESTORE:
		case NFT_COMPAT_RULE_SAVE:
		case NFT_COMPAT_RULE_ZERO:
		case NFT_COMPAT_BRIDGE_USER_CHAIN_UPDATE:
		case NFT_COMPAT_TABLE_NEW:
2815
2816
2817
2818
2819
			break;
		}
	}
}

2820
2821
2822
static int nft_action(struct nft_handle *h, int action)
{
	struct obj_update *n, *tmp;
2823
2824
2825
2826
	struct mnl_err *err, *ne;
	unsigned int buflen, i, len;
	bool show_errors = true;
	char errmsg[1024];
2827
	uint32_t seq;
2828
2829
	int ret = 0;

2830
2831
retry:
	seq = 1;
2832
	h->batch = mnl_batch_init();
2833

2834
2835
	mnl_batch_begin(h->batch, h->nft_genid, seq++);
	h->nft_genid++;
2836
2837

	list_for_each_entry(n, &h->obj_list, head) {
2838
2839
2840
2841

		if (n->skip)
			continue;

2842
		n->seq = seq++;
2843
2844
2845
		switch (n->type) {
		case NFT_COMPAT_TABLE_ADD:
			nft_compat_table_batch_add(h, NFT_MSG_NEWTABLE,
2846
						   NLM_F_CREATE, n->seq,
2847
2848
						   n->table);
			break;
2849
2850
2851
2852
2853
		case NFT_COMPAT_TABLE_FLUSH:
			nft_compat_table_batch_add(h, NFT_MSG_DELTABLE,
						   0,
						   n->seq, n->table);
			break;
2854
		case NFT_COMPAT_CHAIN_ADD:
2855
		case NFT_COMPAT_CHAIN_ZERO:
2856
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN,
2857
						   NLM_F_CREATE, n->seq,
2858
2859
2860
2861
						   n->chain);
			break;
		case NFT_COMPAT_CHAIN_USER_ADD:
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN,
2862
						   NLM_F_EXCL, n->seq,
2863
2864
2865
2866
						   n->chain);
			break;
		case NFT_COMPAT_CHAIN_USER_DEL:
			nft_compat_chain_batch_add(h, NFT_MSG_DELCHAIN,
2867
2868
2869
2870
2871
2872
						   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,
2873
						   n->chain);
2874
2875
2876
2877
2878
			break;
		case NFT_COMPAT_CHAIN_UPDATE:
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN,
						   h->restore ?
						     NLM_F_CREATE : 0,
2879
						   n->seq, n->chain);
2880
2881
2882
			break;
		case NFT_COMPAT_CHAIN_RENAME:
			nft_compat_chain_batch_add(h, NFT_MSG_NEWCHAIN, 0,
2883
						   n->seq, n->chain);
2884
2885
2886
2887
			break;
		case NFT_COMPAT_RULE_APPEND:
			nft_compat_rule_batch_add(h, NFT_MSG_NEWRULE,
						  NLM_F_CREATE | NLM_F_APPEND,
2888
						  n->seq, n->rule);
2889
2890
2891
			break;
		case NFT_COMPAT_RULE_INSERT:
			nft_compat_rule_batch_add(h, NFT_MSG_NEWRULE,
2892
						  NLM_F_CREATE, n->seq,
2893
2894
2895
2896
2897
						  n->rule);
			break;
		case NFT_COMPAT_RULE_REPLACE:
			nft_compat_rule_batch_add(h, NFT_MSG_NEWRULE,
						  NLM_F_CREATE | NLM_F_REPLACE,
2898
						  n->seq, n->rule);
2899
2900
2901
2902
			break;
		case NFT_COMPAT_RULE_DELETE:
		case NFT_COMPAT_RULE_FLUSH:
			nft_compat_rule_batch_add(h, NFT_MSG_DELRULE, 0,
2903
						  n->seq, n->rule);
2904
			break;
2905
2906
2907
2908
2909
2910
2911
		case NFT_COMPAT_SET_ADD:
			nft_compat_set_batch_add(h, NFT_MSG_NEWSET,
						 NLM_F_CREATE, n->seq, n->set);
			nft_compat_setelem_batch_add(h, NFT_MSG_NEWSETELEM,
						     NLM_F_CREATE, &n->seq, n->set);
			seq = n->seq;
			break;
2912
2913
2914
2915
2916
2917
2918
2919
		case NFT_COMPAT_RULE_LIST:
		case NFT_COMPAT_RULE_CHECK:
		case NFT_COMPAT_CHAIN_RESTORE:
		case NFT_COMPAT_RULE_SAVE:
		case NFT_COMPAT_RULE_ZERO:
		case NFT_COMPAT_BRIDGE_USER_CHAIN_UPDATE:
		case NFT_COMPAT_TABLE_NEW:
			assert(0);
2920
2921
		}

2922
		mnl_nft_batch_continue(h->batch);
2923
2924
2925
2926
	}

	switch (action) {
	case NFT_COMPAT_COMMIT:
2927
		mnl_batch_end(h->batch, seq++);
2928
2929
2930
2931
2932
		break;
	case NFT_COMPAT_ABORT:
		break;
	}

2933
	errno = 0;
2934
	ret = mnl_batch_talk(h, seq);
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
	if (ret && errno == ERESTART) {
		nft_rebuild_cache(h);

		nft_refresh_transaction(h);

		list_for_each_entry_safe(err, ne, &h->err_list, head)
			mnl_err_list_free(err);

		mnl_batch_reset(h->batch);
		goto retry;
	}
2946
2947
2948

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

2950
2951
2952
2953
	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;
2954

2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
			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);
	}

2969
	nft_release_cache(h);
2970
2971
2972
2973
	mnl_batch_reset(h->batch);

	if (i)
		xtables_error(RESOURCE_PROBLEM, "%s", errmsg);
2974
2975
2976
2977

	return ret == 0 ? 1 : 0;
}

2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
static int ebt_add_policy_rule(struct nftnl_chain *c, void *data)
{
	uint32_t policy = nftnl_chain_get_u32(c, NFTNL_CHAIN_POLICY);
	struct iptables_command_state cs = {
		.eb.bitmask = EBT_NOPROTO,
	};
	struct nftnl_udata_buf *udata;
	struct nft_handle *h = data;
	struct nftnl_rule *r;
	const char *pname;

	if (nftnl_chain_get(c, NFTNL_CHAIN_HOOKNUM))
		return 0; /* ignore base chains */

	if (!nftnl_chain_is_set(c, NFTNL_CHAIN_POLICY))
		return 0;

	nftnl_chain_unset(c, NFTNL_CHAIN_POLICY);

	switch (policy) {
	case NFT_RETURN:
		return 0; /* return policy is default for nft chains */
	case NF_ACCEPT:
		pname = "ACCEPT";
		break;
	case NF_DROP:
		pname = "DROP";
		break;
	default:
		return -1;
	}

	command_jump(&cs, pname);

	r = nft_rule_new(h, nftnl_chain_get_str(c, NFTNL_CHAIN_NAME),
			 nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE), &cs);
3014
3015
	ebt_cs_clean(&cs);

3016
3017
3018
3019
3020
	if (!r)
		return -1;

	udata = nftnl_udata_buf_alloc(NFT_USERDATA_MAXLEN);
	if (!udata)
3021
		goto err_free_rule;
3022
3023

	if (!nftnl_udata_put_u32(udata, UDATA_TYPE_EBTABLES_POLICY, 1))
3024
		goto err_free_rule;
3025
3026
3027
3028
3029
3030

	nftnl_rule_set_data(r, NFTNL_RULE_USERDATA,
			    nftnl_udata_buf_data(udata),
			    nftnl_udata_buf_len(udata));
	nftnl_udata_buf_free(udata);

3031
3032
3033
3034
3035
	if (!batch_rule_add(h, NFT_COMPAT_RULE_APPEND, r))
		goto err_free_rule;

	/* add the rule to chain so it is freed later */
	nftnl_chain_rule_add_tail(r, c);
3036
3037

	return 0;
3038
3039
3040
err_free_rule:
	nftnl_rule_free(r);
	return -1;
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
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
}

int ebt_set_user_chain_policy(struct nft_handle *h, const char *table,
			      const char *chain, const char *policy)
{
	struct nftnl_chain *c = nft_chain_find(h, table, chain);
	int pval;

	if (!c)
		return 0;

	if (!strcmp(policy, "DROP"))
		pval = NF_DROP;
	else if (!strcmp(policy, "ACCEPT"))
		pval = NF_ACCEPT;
	else if (!strcmp(policy, "RETURN"))
		pval = NFT_RETURN;
	else
		return 0;

	nftnl_chain_set_u32(c, NFTNL_CHAIN_POLICY, pval);
	return 1;
}

static void nft_bridge_commit_prepare(struct nft_handle *h)
{
	const struct builtin_table *t;
	struct nftnl_chain_list *list;
	int i;

	for (i = 0; i < NFT_TABLE_MAX; i++) {
		t = &h->tables[i];

		if (!t->name)
			continue;

		list = h->cache->table[t->type].chains;
		if (!list)
			continue;

		nftnl_chain_list_foreach(list, ebt_add_policy_rule, h);
	}
}

3085
3086
static void assert_chain_exists(struct nft_handle *h,
				const char *table, const char *chain)
3087
{
3088
3089
3090
	if (chain && !nft_chain_exists(h, table, chain))
		xtables_error(PARAMETER_PROBLEM,
			      "Chain '%s' does not exist", chain);
3091
3092
}

3093
static int nft_prepare(struct nft_handle *h)
3094
{
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
	struct nft_cmd *cmd, *next;
	int ret = 1;

	nft_cache_build(h);

	list_for_each_entry_safe(cmd, next, &h->cmd_list, head) {
		switch (cmd->command) {
		case NFT_COMPAT_TABLE_FLUSH:
			ret = nft_table_flush(h, cmd->table);
			break;
		case NFT_COMPAT_CHAIN_USER_ADD:
			ret = nft_chain_user_add(h, cmd->chain, cmd->table);
			break;
		case NFT_COMPAT_CHAIN_USER_DEL:
			ret = nft_chain_user_del(h, cmd->chain, cmd->table,
						 cmd->verbose);
			break;
		case NFT_COMPAT_CHAIN_RESTORE:
			ret = nft_chain_restore(h, cmd->chain, cmd->table);
			break;
		case NFT_COMPAT_CHAIN_UPDATE:
			ret = nft_chain_set(h, cmd->table, cmd->chain,
					    cmd->policy, &cmd->counters);
			break;
		case NFT_COMPAT_CHAIN_RENAME:
			ret = nft_chain_user_rename(h, cmd->chain, cmd->table,
						    cmd->rename);
			break;
		case NFT_COMPAT_CHAIN_ZERO:
			ret = nft_chain_zero_counters(h, cmd->chain, cmd->table,
						      cmd->verbose);
			break;
		case NFT_COMPAT_RULE_APPEND:
			assert_chain_exists(h, cmd->table, cmd->jumpto);
			ret = nft_rule_append(h, cmd->chain, cmd->table,
					      cmd->obj.rule, NULL, cmd->verbose);
			break;
		case NFT_COMPAT_RULE_INSERT:
			assert_chain_exists(h, cmd->table, cmd->jumpto);
			ret = nft_rule_insert(h, cmd->chain, cmd->table,
					      cmd->obj.rule, cmd->rulenum,
					      cmd->verbose);
			break;
		case NFT_COMPAT_RULE_REPLACE:
			assert_chain_exists(h, cmd->table, cmd->jumpto);
			ret = nft_rule_replace(h, cmd->chain, cmd->table,
					      cmd->obj.rule, cmd->rulenum,
					      cmd->verbose);
			break;
		case NFT_COMPAT_RULE_DELETE:
			assert_chain_exists(h, cmd->table, cmd->jumpto);
			if (cmd->rulenum >= 0)
				ret = nft_rule_delete_num(h, cmd->chain,
							  cmd->table,
							  cmd->rulenum,
							  cmd->verbose);
			else
				ret = nft_rule_delete(h, cmd->chain, cmd->table,
						      cmd->obj.rule, cmd->verbose);
			break;
		case NFT_COMPAT_RULE_FLUSH:
			ret = nft_rule_flush(h, cmd->chain, cmd->table,
					     cmd->verbose);
			break;
		case NFT_COMPAT_RULE_LIST:
			ret = nft_rule_list(h, cmd->chain, cmd->table,
					    cmd->rulenum, cmd->format);
			break;
		case NFT_COMPAT_RULE_CHECK:
			assert_chain_exists(h, cmd->table, cmd->jumpto);
			ret = nft_rule_check(h, cmd->chain, cmd->table,
					     cmd->obj.rule, cmd->rulenum);
			break;
		case NFT_COMPAT_RULE_ZERO:
			ret = nft_rule_zero_counters(h, cmd->chain, cmd->table,
                                                     cmd->rulenum);
			break;
		case NFT_COMPAT_RULE_SAVE:
			ret = nft_rule_list_save(h, cmd->chain, cmd->table,
						 cmd->rulenum,
						 cmd->counters_save);
			break;
		case NFT_COMPAT_BRIDGE_USER_CHAIN_UPDATE:
			ret = ebt_set_user_chain_policy(h, cmd->table,
							cmd->chain, cmd->policy);
			break;
		case NFT_COMPAT_TABLE_NEW:
			nft_xt_builtin_init(h, cmd->table);
			ret = 1;
			break;
		case NFT_COMPAT_SET_ADD:
			nft_xt_builtin_init(h, cmd->table);
			batch_set_add(h, NFT_COMPAT_SET_ADD, cmd->obj.set);
			ret = 1;
			break;
		case NFT_COMPAT_TABLE_ADD:
		case NFT_COMPAT_CHAIN_ADD:
			assert(0);
			break;
		}

		nft_cmd_free(cmd);

		if (ret == 0)
			return 0;
	}

	return 1;
3203
3204
}

3205
int nft_commit(struct nft_handle *h)
3206
{
3207
3208
3209
3210
	if (!nft_prepare(h))
		return 0;

	return nft_action(h, NFT_COMPAT_COMMIT);
3211
3212
}

3213
int nft_bridge_commit(struct nft_handle *h)
3214
{
3215
3216
	if (!nft_prepare(h))
		return 0;
3217

3218
	nft_bridge_commit_prepare(h);
3219

3220
3221
	return nft_action(h, NFT_COMPAT_COMMIT);
}
3222

3223
3224
3225
int nft_abort(struct nft_handle *h)
{
	struct nft_cmd *cmd, *next;
3226

3227
3228
3229
3230
	list_for_each_entry_safe(cmd, next, &h->cmd_list, head)
		nft_cmd_free(cmd);

	return nft_action(h, NFT_COMPAT_ABORT);
3231
3232
}

3233
3234
3235
int nft_compatible_revision(const char *name, uint8_t rev, int opt)
{
	struct mnl_socket *nl;
3236
	char buf[16536];
3237
	struct nlmsghdr *nlh;
3238
3239
	uint32_t portid, seq, type = 0;
	uint32_t pf = AF_INET;
3240
3241
	int ret = 0;

3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
	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:
3252
		type = 1;
3253
3254
3255
3256
3257
3258
		pf = AF_INET6;
		break;
	default:
		/* No revision support (arp, ebtables), assume latest version ok */
		return 1;
	}
3259
3260
3261
3262
3263
3264
3265

	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));
3266
	nfg->nfgen_family = pf;
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
	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" },
3319
3320
	    { nft_chain_user_rename, EEXIST, "File exists" },
	    { nft_rule_insert, E2BIG, "Index of insertion too big" },
3321
	    { nft_rule_check, ENOENT, "Bad rule (does a matching rule exist in that chain?)" },
3322
3323
	    { nft_rule_replace, E2BIG, "Index of replacement too big" },
	    { nft_rule_delete_num, E2BIG, "Index of deletion too big" },
3324
3325
3326
3327
3328
3329
3330
/*	    { 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" },
3331
	    { nft_chain_set, ENXIO, "Bad table name" },
3332
	    { NULL, ELOOP, "Loop found in table" },
3333
3334
3335
3336
3337
3338
3339
3340
	    { 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" },
	  };

3341
	for (i = 0; i < ARRAY_SIZE(table); i++) {
3342
3343
3344
3345
3346
3347
3348
3349
		if ((!table[i].fn || table[i].fn == nft_fn)
		    && table[i].err == err)
			return table[i].message;
	}

	return strerror(err);
}

3350
static int recover_rule_compat(struct nftnl_rule *r)
3351
{
3352
3353
3354
3355
	struct nftnl_expr_iter *iter;
	struct nftnl_expr *e;
	uint32_t reg;
	int ret = -1;
3356

3357
3358
3359
	iter = nftnl_expr_iter_create(r);
	if (!iter)
		return -1;
3360

3361
3362
3363
3364
next_expr:
	e = nftnl_expr_iter_next(iter);
	if (!e)
		goto out;
3365

3366
3367
3368
	if (strcmp("meta", nftnl_expr_get_str(e, NFTNL_EXPR_NAME)) ||
	    nftnl_expr_get_u32(e, NFTNL_EXPR_META_KEY) != NFT_META_L4PROTO)
		goto next_expr;
3369

3370
	reg = nftnl_expr_get_u32(e, NFTNL_EXPR_META_DREG);
3371

3372
3373
3374
	e = nftnl_expr_iter_next(iter);
	if (!e)
		goto out;
3375

3376
3377
3378
	if (strcmp("cmp", nftnl_expr_get_str(e, NFTNL_EXPR_NAME)) ||
	    reg != nftnl_expr_get_u32(e, NFTNL_EXPR_CMP_SREG))
		goto next_expr;
3379

3380
3381
3382
3383
3384
3385
	add_compat(r, nftnl_expr_get_u8(e, NFTNL_EXPR_CMP_DATA),
		   nftnl_expr_get_u32(e, NFTNL_EXPR_CMP_OP) == NFT_CMP_NEQ);
	ret = 0;
out:
	nftnl_expr_iter_destroy(iter);
	return ret;
3386
3387
}

3388
3389
3390
3391
3392
3393
struct chain_zero_data {
	struct nft_handle	*handle;
	bool			verbose;
};

static int __nft_chain_zero_counters(struct nftnl_chain *c, void *data)
3394
{
3395
3396
3397
	struct chain_zero_data *d = data;
	struct nft_handle *h = d->handle;
	struct nftnl_rule_iter *iter;
3398
3399
	struct nftnl_rule *r;

3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
	if (d->verbose)
		fprintf(stdout, "Zeroing chain `%s'\n",
			nftnl_chain_get_str(c, NFTNL_CHAIN_NAME));

	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);
		nftnl_chain_unset(c, NFTNL_CHAIN_HANDLE);
		if (batch_chain_add(h, NFT_COMPAT_CHAIN_ZERO, c))
			return -1;
	}
3412

3413
3414
3415
	iter = nftnl_rule_iter_create(c);
	if (iter == NULL)
		return -1;
3416

3417
	r = nftnl_rule_iter_next(iter);
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
	while (r != NULL) {
		struct nftnl_expr_iter *ei;
		struct nftnl_expr *e;
		bool zero_needed;

		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.
			 */
3450
			recover_rule_compat(r);
3451
			nftnl_rule_unset(r, NFTNL_RULE_POSITION);
3452
3453
3454
3455
			if (!batch_rule_add(h, NFT_COMPAT_RULE_REPLACE, r)) {
				nftnl_rule_iter_destroy(iter);
				return -1;
			}
3456
		}
3457
		r = nftnl_rule_iter_next(iter);
3458
3459
	}

3460
3461
	nftnl_rule_iter_destroy(iter);
	return 0;
3462
3463
}

3464
3465
int nft_chain_zero_counters(struct nft_handle *h, const char *chain,
			    const char *table, bool verbose)
3466
3467
{
	struct nftnl_chain_list *list;
3468
3469
3470
3471
	struct chain_zero_data d = {
		.handle = h,
		.verbose = verbose,
	};
3472
3473
3474
	struct nftnl_chain *c;
	int ret = 0;

3475
	list = nft_chain_list_get(h, table, chain);
3476
3477
3478
	if (list == NULL)
		goto err;

3479
3480
3481
3482
3483
	if (chain) {
		c = nftnl_chain_list_lookup_byname(list, chain);
		if (!c) {
			errno = ENOENT;
			return 0;
3484
3485
		}

3486
3487
		ret = __nft_chain_zero_counters(c, &d);
		goto err;
3488
3489
	}

3490
	ret = nftnl_chain_list_foreach(list, __nft_chain_zero_counters, &d);
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
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;
}
3503

3504
static const char *supported_exprs[] = {
3505
3506
3507
3508
3509
3510
3511
	"match",
	"target",
	"payload",
	"meta",
	"cmp",
	"bitwise",
	"counter",
3512
3513
	"immediate",
	"lookup",
3514
3515
3516
};


3517
static int nft_is_expr_compatible(struct nftnl_expr *expr, void *data)
3518
{
3519
	const char *name = nftnl_expr_get_str(expr, NFTNL_EXPR_NAME);
3520
3521
	int i;

3522
	for (i = 0; i < ARRAY_SIZE(supported_exprs); i++) {
3523
3524
3525
3526
		if (strcmp(supported_exprs[i], name) == 0)
			return 0;
	}

3527
3528
3529
3530
3531
	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;

3532
	return -1;
3533
3534
}

3535
static int nft_is_rule_compatible(struct nftnl_rule *rule, void *data)
3536
{
3537
	return nftnl_expr_foreach(rule, nft_is_expr_compatible, NULL);
3538
3539
}

3540
static int nft_is_chain_compatible(struct nftnl_chain *c, void *data)
3541
{
3542
3543
3544
3545
	const struct builtin_table *table;
	const struct builtin_chain *chain;
	const char *tname, *cname, *type;
	struct nft_handle *h = data;
3546
	enum nf_inet_hooks hook;
3547
	int prio;
3548

3549
3550
	if (nftnl_rule_foreach(c, nft_is_rule_compatible, NULL))
		return -1;
3551

3552
3553
	if (!nft_chain_builtin(c))
		return 0;
3554

3555
3556
3557
	tname = nftnl_chain_get_str(c, NFTNL_CHAIN_TABLE);
	table = nft_table_builtin_find(h, tname);
	if (!table)
3558
3559
		return -1;

3560
3561
3562
	cname = nftnl_chain_get_str(c, NFTNL_CHAIN_NAME);
	chain = nft_chain_builtin_find(table, cname);
	if (!chain)
3563
3564
		return -1;

3565
3566
3567
3568
3569
3570
3571
	type = nftnl_chain_get_str(c, NFTNL_CHAIN_TYPE);
	prio = nftnl_chain_get_u32(c, NFTNL_CHAIN_PRIO);
	hook = nftnl_chain_get_u32(c, NFTNL_CHAIN_HOOKNUM);
	if (strcmp(type, chain->type) ||
	    prio != chain->prio ||
	    hook != chain->hook)
		return -1;
3572

3573
	return 0;
3574
3575
}

3576
3577
bool nft_is_table_compatible(struct nft_handle *h,
			     const char *table, const char *chain)
3578
{
3579
	struct nftnl_chain_list *clist;
3580

3581
	clist = nft_chain_list_get(h, table, chain);
3582
	if (clist == NULL)
3583
		return false;
3584

3585
	if (nftnl_chain_list_foreach(clist, nft_is_chain_compatible, h))
3586
		return false;
3587

3588
	return true;
3589
}
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608

void nft_assert_table_compatible(struct nft_handle *h,
				 const char *table, const char *chain)
{
	const char *pfx = "", *sfx = "";

	if (nft_is_table_compatible(h, table, chain))
		return;

	if (chain) {
		pfx = "chain `";
		sfx = "' in ";
	} else {
		chain = "";
	}
	xtables_error(OTHER_PROBLEM,
		      "%s%s%stable `%s' is incompatible, use 'nft' tool.\n",
		      pfx, chain, sfx, table);
}