OSDN Git Service

Merge branch 'i2c/for-current' of git://git.kernel.org/pub/scm/linux/kernel/git/wsa...
[uclinux-h8/linux.git] / net / netfilter / nf_tables_api.c
1 /*
2  * Copyright (c) 2007-2009 Patrick McHardy <kaber@trash.net>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * Development of this code funded by Astaro AG (http://www.astaro.com/)
9  */
10
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/list.h>
14 #include <linux/skbuff.h>
15 #include <linux/netlink.h>
16 #include <linux/vmalloc.h>
17 #include <linux/rhashtable.h>
18 #include <linux/netfilter.h>
19 #include <linux/netfilter/nfnetlink.h>
20 #include <linux/netfilter/nf_tables.h>
21 #include <net/netfilter/nf_flow_table.h>
22 #include <net/netfilter/nf_tables_core.h>
23 #include <net/netfilter/nf_tables.h>
24 #include <net/net_namespace.h>
25 #include <net/sock.h>
26
27 static LIST_HEAD(nf_tables_expressions);
28 static LIST_HEAD(nf_tables_objects);
29 static LIST_HEAD(nf_tables_flowtables);
30 static LIST_HEAD(nf_tables_destroy_list);
31 static DEFINE_SPINLOCK(nf_tables_destroy_list_lock);
32 static u64 table_handle;
33
34 enum {
35         NFT_VALIDATE_SKIP       = 0,
36         NFT_VALIDATE_NEED,
37         NFT_VALIDATE_DO,
38 };
39
40 static u32 nft_chain_hash(const void *data, u32 len, u32 seed);
41 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed);
42 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *, const void *);
43
44 static const struct rhashtable_params nft_chain_ht_params = {
45         .head_offset            = offsetof(struct nft_chain, rhlhead),
46         .key_offset             = offsetof(struct nft_chain, name),
47         .hashfn                 = nft_chain_hash,
48         .obj_hashfn             = nft_chain_hash_obj,
49         .obj_cmpfn              = nft_chain_hash_cmp,
50         .locks_mul              = 1,
51         .automatic_shrinking    = true,
52 };
53
54 static void nft_validate_state_update(struct net *net, u8 new_validate_state)
55 {
56         switch (net->nft.validate_state) {
57         case NFT_VALIDATE_SKIP:
58                 WARN_ON_ONCE(new_validate_state == NFT_VALIDATE_DO);
59                 break;
60         case NFT_VALIDATE_NEED:
61                 break;
62         case NFT_VALIDATE_DO:
63                 if (new_validate_state == NFT_VALIDATE_NEED)
64                         return;
65         }
66
67         net->nft.validate_state = new_validate_state;
68 }
69 static void nf_tables_trans_destroy_work(struct work_struct *w);
70 static DECLARE_WORK(trans_destroy_work, nf_tables_trans_destroy_work);
71
72 static void nft_ctx_init(struct nft_ctx *ctx,
73                          struct net *net,
74                          const struct sk_buff *skb,
75                          const struct nlmsghdr *nlh,
76                          u8 family,
77                          struct nft_table *table,
78                          struct nft_chain *chain,
79                          const struct nlattr * const *nla)
80 {
81         ctx->net        = net;
82         ctx->family     = family;
83         ctx->level      = 0;
84         ctx->table      = table;
85         ctx->chain      = chain;
86         ctx->nla        = nla;
87         ctx->portid     = NETLINK_CB(skb).portid;
88         ctx->report     = nlmsg_report(nlh);
89         ctx->seq        = nlh->nlmsg_seq;
90 }
91
92 static struct nft_trans *nft_trans_alloc_gfp(const struct nft_ctx *ctx,
93                                              int msg_type, u32 size, gfp_t gfp)
94 {
95         struct nft_trans *trans;
96
97         trans = kzalloc(sizeof(struct nft_trans) + size, gfp);
98         if (trans == NULL)
99                 return NULL;
100
101         trans->msg_type = msg_type;
102         trans->ctx      = *ctx;
103
104         return trans;
105 }
106
107 static struct nft_trans *nft_trans_alloc(const struct nft_ctx *ctx,
108                                          int msg_type, u32 size)
109 {
110         return nft_trans_alloc_gfp(ctx, msg_type, size, GFP_KERNEL);
111 }
112
113 static void nft_trans_destroy(struct nft_trans *trans)
114 {
115         list_del(&trans->list);
116         kfree(trans);
117 }
118
119 static void nft_set_trans_bind(const struct nft_ctx *ctx, struct nft_set *set)
120 {
121         struct net *net = ctx->net;
122         struct nft_trans *trans;
123
124         if (!nft_set_is_anonymous(set))
125                 return;
126
127         list_for_each_entry_reverse(trans, &net->nft.commit_list, list) {
128                 if (trans->msg_type == NFT_MSG_NEWSET &&
129                     nft_trans_set(trans) == set) {
130                         nft_trans_set_bound(trans) = true;
131                         break;
132                 }
133         }
134 }
135
136 static int nf_tables_register_hook(struct net *net,
137                                    const struct nft_table *table,
138                                    struct nft_chain *chain)
139 {
140         const struct nft_base_chain *basechain;
141         const struct nf_hook_ops *ops;
142
143         if (table->flags & NFT_TABLE_F_DORMANT ||
144             !nft_is_base_chain(chain))
145                 return 0;
146
147         basechain = nft_base_chain(chain);
148         ops = &basechain->ops;
149
150         if (basechain->type->ops_register)
151                 return basechain->type->ops_register(net, ops);
152
153         return nf_register_net_hook(net, ops);
154 }
155
156 static void nf_tables_unregister_hook(struct net *net,
157                                       const struct nft_table *table,
158                                       struct nft_chain *chain)
159 {
160         const struct nft_base_chain *basechain;
161         const struct nf_hook_ops *ops;
162
163         if (table->flags & NFT_TABLE_F_DORMANT ||
164             !nft_is_base_chain(chain))
165                 return;
166         basechain = nft_base_chain(chain);
167         ops = &basechain->ops;
168
169         if (basechain->type->ops_unregister)
170                 return basechain->type->ops_unregister(net, ops);
171
172         nf_unregister_net_hook(net, ops);
173 }
174
175 static int nft_trans_table_add(struct nft_ctx *ctx, int msg_type)
176 {
177         struct nft_trans *trans;
178
179         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_table));
180         if (trans == NULL)
181                 return -ENOMEM;
182
183         if (msg_type == NFT_MSG_NEWTABLE)
184                 nft_activate_next(ctx->net, ctx->table);
185
186         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
187         return 0;
188 }
189
190 static int nft_deltable(struct nft_ctx *ctx)
191 {
192         int err;
193
194         err = nft_trans_table_add(ctx, NFT_MSG_DELTABLE);
195         if (err < 0)
196                 return err;
197
198         nft_deactivate_next(ctx->net, ctx->table);
199         return err;
200 }
201
202 static int nft_trans_chain_add(struct nft_ctx *ctx, int msg_type)
203 {
204         struct nft_trans *trans;
205
206         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_chain));
207         if (trans == NULL)
208                 return -ENOMEM;
209
210         if (msg_type == NFT_MSG_NEWCHAIN)
211                 nft_activate_next(ctx->net, ctx->chain);
212
213         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
214         return 0;
215 }
216
217 static int nft_delchain(struct nft_ctx *ctx)
218 {
219         int err;
220
221         err = nft_trans_chain_add(ctx, NFT_MSG_DELCHAIN);
222         if (err < 0)
223                 return err;
224
225         ctx->table->use--;
226         nft_deactivate_next(ctx->net, ctx->chain);
227
228         return err;
229 }
230
231 static void nft_rule_expr_activate(const struct nft_ctx *ctx,
232                                    struct nft_rule *rule)
233 {
234         struct nft_expr *expr;
235
236         expr = nft_expr_first(rule);
237         while (expr != nft_expr_last(rule) && expr->ops) {
238                 if (expr->ops->activate)
239                         expr->ops->activate(ctx, expr);
240
241                 expr = nft_expr_next(expr);
242         }
243 }
244
245 static void nft_rule_expr_deactivate(const struct nft_ctx *ctx,
246                                      struct nft_rule *rule,
247                                      enum nft_trans_phase phase)
248 {
249         struct nft_expr *expr;
250
251         expr = nft_expr_first(rule);
252         while (expr != nft_expr_last(rule) && expr->ops) {
253                 if (expr->ops->deactivate)
254                         expr->ops->deactivate(ctx, expr, phase);
255
256                 expr = nft_expr_next(expr);
257         }
258 }
259
260 static int
261 nf_tables_delrule_deactivate(struct nft_ctx *ctx, struct nft_rule *rule)
262 {
263         /* You cannot delete the same rule twice */
264         if (nft_is_active_next(ctx->net, rule)) {
265                 nft_deactivate_next(ctx->net, rule);
266                 ctx->chain->use--;
267                 return 0;
268         }
269         return -ENOENT;
270 }
271
272 static struct nft_trans *nft_trans_rule_add(struct nft_ctx *ctx, int msg_type,
273                                             struct nft_rule *rule)
274 {
275         struct nft_trans *trans;
276
277         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_rule));
278         if (trans == NULL)
279                 return NULL;
280
281         if (msg_type == NFT_MSG_NEWRULE && ctx->nla[NFTA_RULE_ID] != NULL) {
282                 nft_trans_rule_id(trans) =
283                         ntohl(nla_get_be32(ctx->nla[NFTA_RULE_ID]));
284         }
285         nft_trans_rule(trans) = rule;
286         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
287
288         return trans;
289 }
290
291 static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
292 {
293         struct nft_trans *trans;
294         int err;
295
296         trans = nft_trans_rule_add(ctx, NFT_MSG_DELRULE, rule);
297         if (trans == NULL)
298                 return -ENOMEM;
299
300         err = nf_tables_delrule_deactivate(ctx, rule);
301         if (err < 0) {
302                 nft_trans_destroy(trans);
303                 return err;
304         }
305         nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_PREPARE);
306
307         return 0;
308 }
309
310 static int nft_delrule_by_chain(struct nft_ctx *ctx)
311 {
312         struct nft_rule *rule;
313         int err;
314
315         list_for_each_entry(rule, &ctx->chain->rules, list) {
316                 err = nft_delrule(ctx, rule);
317                 if (err < 0)
318                         return err;
319         }
320         return 0;
321 }
322
323 static int nft_trans_set_add(const struct nft_ctx *ctx, int msg_type,
324                              struct nft_set *set)
325 {
326         struct nft_trans *trans;
327
328         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_set));
329         if (trans == NULL)
330                 return -ENOMEM;
331
332         if (msg_type == NFT_MSG_NEWSET && ctx->nla[NFTA_SET_ID] != NULL) {
333                 nft_trans_set_id(trans) =
334                         ntohl(nla_get_be32(ctx->nla[NFTA_SET_ID]));
335                 nft_activate_next(ctx->net, set);
336         }
337         nft_trans_set(trans) = set;
338         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
339
340         return 0;
341 }
342
343 static int nft_delset(const struct nft_ctx *ctx, struct nft_set *set)
344 {
345         int err;
346
347         err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set);
348         if (err < 0)
349                 return err;
350
351         nft_deactivate_next(ctx->net, set);
352         ctx->table->use--;
353
354         return err;
355 }
356
357 static int nft_trans_obj_add(struct nft_ctx *ctx, int msg_type,
358                              struct nft_object *obj)
359 {
360         struct nft_trans *trans;
361
362         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_obj));
363         if (trans == NULL)
364                 return -ENOMEM;
365
366         if (msg_type == NFT_MSG_NEWOBJ)
367                 nft_activate_next(ctx->net, obj);
368
369         nft_trans_obj(trans) = obj;
370         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
371
372         return 0;
373 }
374
375 static int nft_delobj(struct nft_ctx *ctx, struct nft_object *obj)
376 {
377         int err;
378
379         err = nft_trans_obj_add(ctx, NFT_MSG_DELOBJ, obj);
380         if (err < 0)
381                 return err;
382
383         nft_deactivate_next(ctx->net, obj);
384         ctx->table->use--;
385
386         return err;
387 }
388
389 static int nft_trans_flowtable_add(struct nft_ctx *ctx, int msg_type,
390                                    struct nft_flowtable *flowtable)
391 {
392         struct nft_trans *trans;
393
394         trans = nft_trans_alloc(ctx, msg_type,
395                                 sizeof(struct nft_trans_flowtable));
396         if (trans == NULL)
397                 return -ENOMEM;
398
399         if (msg_type == NFT_MSG_NEWFLOWTABLE)
400                 nft_activate_next(ctx->net, flowtable);
401
402         nft_trans_flowtable(trans) = flowtable;
403         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
404
405         return 0;
406 }
407
408 static int nft_delflowtable(struct nft_ctx *ctx,
409                             struct nft_flowtable *flowtable)
410 {
411         int err;
412
413         err = nft_trans_flowtable_add(ctx, NFT_MSG_DELFLOWTABLE, flowtable);
414         if (err < 0)
415                 return err;
416
417         nft_deactivate_next(ctx->net, flowtable);
418         ctx->table->use--;
419
420         return err;
421 }
422
423 /*
424  * Tables
425  */
426
427 static struct nft_table *nft_table_lookup(const struct net *net,
428                                           const struct nlattr *nla,
429                                           u8 family, u8 genmask)
430 {
431         struct nft_table *table;
432
433         if (nla == NULL)
434                 return ERR_PTR(-EINVAL);
435
436         list_for_each_entry_rcu(table, &net->nft.tables, list) {
437                 if (!nla_strcmp(nla, table->name) &&
438                     table->family == family &&
439                     nft_active_genmask(table, genmask))
440                         return table;
441         }
442
443         return ERR_PTR(-ENOENT);
444 }
445
446 static struct nft_table *nft_table_lookup_byhandle(const struct net *net,
447                                                    const struct nlattr *nla,
448                                                    u8 genmask)
449 {
450         struct nft_table *table;
451
452         list_for_each_entry(table, &net->nft.tables, list) {
453                 if (be64_to_cpu(nla_get_be64(nla)) == table->handle &&
454                     nft_active_genmask(table, genmask))
455                         return table;
456         }
457
458         return ERR_PTR(-ENOENT);
459 }
460
461 static inline u64 nf_tables_alloc_handle(struct nft_table *table)
462 {
463         return ++table->hgenerator;
464 }
465
466 static const struct nft_chain_type *chain_type[NFPROTO_NUMPROTO][NFT_CHAIN_T_MAX];
467
468 static const struct nft_chain_type *
469 __nf_tables_chain_type_lookup(const struct nlattr *nla, u8 family)
470 {
471         int i;
472
473         for (i = 0; i < NFT_CHAIN_T_MAX; i++) {
474                 if (chain_type[family][i] != NULL &&
475                     !nla_strcmp(nla, chain_type[family][i]->name))
476                         return chain_type[family][i];
477         }
478         return NULL;
479 }
480
481 /*
482  * Loading a module requires dropping mutex that guards the
483  * transaction.
484  * We first need to abort any pending transactions as once
485  * mutex is unlocked a different client could start a new
486  * transaction.  It must not see any 'future generation'
487  * changes * as these changes will never happen.
488  */
489 #ifdef CONFIG_MODULES
490 static int __nf_tables_abort(struct net *net);
491
492 static void nft_request_module(struct net *net, const char *fmt, ...)
493 {
494         char module_name[MODULE_NAME_LEN];
495         va_list args;
496         int ret;
497
498         __nf_tables_abort(net);
499
500         va_start(args, fmt);
501         ret = vsnprintf(module_name, MODULE_NAME_LEN, fmt, args);
502         va_end(args);
503         if (WARN(ret >= MODULE_NAME_LEN, "truncated: '%s' (len %d)", module_name, ret))
504                 return;
505
506         mutex_unlock(&net->nft.commit_mutex);
507         request_module("%s", module_name);
508         mutex_lock(&net->nft.commit_mutex);
509 }
510 #endif
511
512 static void lockdep_nfnl_nft_mutex_not_held(void)
513 {
514 #ifdef CONFIG_PROVE_LOCKING
515         WARN_ON_ONCE(lockdep_nfnl_is_held(NFNL_SUBSYS_NFTABLES));
516 #endif
517 }
518
519 static const struct nft_chain_type *
520 nf_tables_chain_type_lookup(struct net *net, const struct nlattr *nla,
521                             u8 family, bool autoload)
522 {
523         const struct nft_chain_type *type;
524
525         type = __nf_tables_chain_type_lookup(nla, family);
526         if (type != NULL)
527                 return type;
528
529         lockdep_nfnl_nft_mutex_not_held();
530 #ifdef CONFIG_MODULES
531         if (autoload) {
532                 nft_request_module(net, "nft-chain-%u-%.*s", family,
533                                    nla_len(nla), (const char *)nla_data(nla));
534                 type = __nf_tables_chain_type_lookup(nla, family);
535                 if (type != NULL)
536                         return ERR_PTR(-EAGAIN);
537         }
538 #endif
539         return ERR_PTR(-ENOENT);
540 }
541
542 static const struct nla_policy nft_table_policy[NFTA_TABLE_MAX + 1] = {
543         [NFTA_TABLE_NAME]       = { .type = NLA_STRING,
544                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
545         [NFTA_TABLE_FLAGS]      = { .type = NLA_U32 },
546         [NFTA_TABLE_HANDLE]     = { .type = NLA_U64 },
547 };
548
549 static int nf_tables_fill_table_info(struct sk_buff *skb, struct net *net,
550                                      u32 portid, u32 seq, int event, u32 flags,
551                                      int family, const struct nft_table *table)
552 {
553         struct nlmsghdr *nlh;
554         struct nfgenmsg *nfmsg;
555
556         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
557         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
558         if (nlh == NULL)
559                 goto nla_put_failure;
560
561         nfmsg = nlmsg_data(nlh);
562         nfmsg->nfgen_family     = family;
563         nfmsg->version          = NFNETLINK_V0;
564         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
565
566         if (nla_put_string(skb, NFTA_TABLE_NAME, table->name) ||
567             nla_put_be32(skb, NFTA_TABLE_FLAGS, htonl(table->flags)) ||
568             nla_put_be32(skb, NFTA_TABLE_USE, htonl(table->use)) ||
569             nla_put_be64(skb, NFTA_TABLE_HANDLE, cpu_to_be64(table->handle),
570                          NFTA_TABLE_PAD))
571                 goto nla_put_failure;
572
573         nlmsg_end(skb, nlh);
574         return 0;
575
576 nla_put_failure:
577         nlmsg_trim(skb, nlh);
578         return -1;
579 }
580
581 static void nf_tables_table_notify(const struct nft_ctx *ctx, int event)
582 {
583         struct sk_buff *skb;
584         int err;
585
586         if (!ctx->report &&
587             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
588                 return;
589
590         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
591         if (skb == NULL)
592                 goto err;
593
594         err = nf_tables_fill_table_info(skb, ctx->net, ctx->portid, ctx->seq,
595                                         event, 0, ctx->family, ctx->table);
596         if (err < 0) {
597                 kfree_skb(skb);
598                 goto err;
599         }
600
601         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
602                        ctx->report, GFP_KERNEL);
603         return;
604 err:
605         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
606 }
607
608 static int nf_tables_dump_tables(struct sk_buff *skb,
609                                  struct netlink_callback *cb)
610 {
611         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
612         const struct nft_table *table;
613         unsigned int idx = 0, s_idx = cb->args[0];
614         struct net *net = sock_net(skb->sk);
615         int family = nfmsg->nfgen_family;
616
617         rcu_read_lock();
618         cb->seq = net->nft.base_seq;
619
620         list_for_each_entry_rcu(table, &net->nft.tables, list) {
621                 if (family != NFPROTO_UNSPEC && family != table->family)
622                         continue;
623
624                 if (idx < s_idx)
625                         goto cont;
626                 if (idx > s_idx)
627                         memset(&cb->args[1], 0,
628                                sizeof(cb->args) - sizeof(cb->args[0]));
629                 if (!nft_is_active(net, table))
630                         continue;
631                 if (nf_tables_fill_table_info(skb, net,
632                                               NETLINK_CB(cb->skb).portid,
633                                               cb->nlh->nlmsg_seq,
634                                               NFT_MSG_NEWTABLE, NLM_F_MULTI,
635                                               table->family, table) < 0)
636                         goto done;
637
638                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
639 cont:
640                 idx++;
641         }
642 done:
643         rcu_read_unlock();
644         cb->args[0] = idx;
645         return skb->len;
646 }
647
648 static int nft_netlink_dump_start_rcu(struct sock *nlsk, struct sk_buff *skb,
649                                       const struct nlmsghdr *nlh,
650                                       struct netlink_dump_control *c)
651 {
652         int err;
653
654         if (!try_module_get(THIS_MODULE))
655                 return -EINVAL;
656
657         rcu_read_unlock();
658         err = netlink_dump_start(nlsk, skb, nlh, c);
659         rcu_read_lock();
660         module_put(THIS_MODULE);
661
662         return err;
663 }
664
665 /* called with rcu_read_lock held */
666 static int nf_tables_gettable(struct net *net, struct sock *nlsk,
667                               struct sk_buff *skb, const struct nlmsghdr *nlh,
668                               const struct nlattr * const nla[],
669                               struct netlink_ext_ack *extack)
670 {
671         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
672         u8 genmask = nft_genmask_cur(net);
673         const struct nft_table *table;
674         struct sk_buff *skb2;
675         int family = nfmsg->nfgen_family;
676         int err;
677
678         if (nlh->nlmsg_flags & NLM_F_DUMP) {
679                 struct netlink_dump_control c = {
680                         .dump = nf_tables_dump_tables,
681                         .module = THIS_MODULE,
682                 };
683
684                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
685         }
686
687         table = nft_table_lookup(net, nla[NFTA_TABLE_NAME], family, genmask);
688         if (IS_ERR(table)) {
689                 NL_SET_BAD_ATTR(extack, nla[NFTA_TABLE_NAME]);
690                 return PTR_ERR(table);
691         }
692
693         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
694         if (!skb2)
695                 return -ENOMEM;
696
697         err = nf_tables_fill_table_info(skb2, net, NETLINK_CB(skb).portid,
698                                         nlh->nlmsg_seq, NFT_MSG_NEWTABLE, 0,
699                                         family, table);
700         if (err < 0)
701                 goto err;
702
703         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
704
705 err:
706         kfree_skb(skb2);
707         return err;
708 }
709
710 static void nft_table_disable(struct net *net, struct nft_table *table, u32 cnt)
711 {
712         struct nft_chain *chain;
713         u32 i = 0;
714
715         list_for_each_entry(chain, &table->chains, list) {
716                 if (!nft_is_active_next(net, chain))
717                         continue;
718                 if (!nft_is_base_chain(chain))
719                         continue;
720
721                 if (cnt && i++ == cnt)
722                         break;
723
724                 nf_unregister_net_hook(net, &nft_base_chain(chain)->ops);
725         }
726 }
727
728 static int nf_tables_table_enable(struct net *net, struct nft_table *table)
729 {
730         struct nft_chain *chain;
731         int err, i = 0;
732
733         list_for_each_entry(chain, &table->chains, list) {
734                 if (!nft_is_active_next(net, chain))
735                         continue;
736                 if (!nft_is_base_chain(chain))
737                         continue;
738
739                 err = nf_register_net_hook(net, &nft_base_chain(chain)->ops);
740                 if (err < 0)
741                         goto err;
742
743                 i++;
744         }
745         return 0;
746 err:
747         if (i)
748                 nft_table_disable(net, table, i);
749         return err;
750 }
751
752 static void nf_tables_table_disable(struct net *net, struct nft_table *table)
753 {
754         nft_table_disable(net, table, 0);
755 }
756
757 static int nf_tables_updtable(struct nft_ctx *ctx)
758 {
759         struct nft_trans *trans;
760         u32 flags;
761         int ret = 0;
762
763         if (!ctx->nla[NFTA_TABLE_FLAGS])
764                 return 0;
765
766         flags = ntohl(nla_get_be32(ctx->nla[NFTA_TABLE_FLAGS]));
767         if (flags & ~NFT_TABLE_F_DORMANT)
768                 return -EINVAL;
769
770         if (flags == ctx->table->flags)
771                 return 0;
772
773         trans = nft_trans_alloc(ctx, NFT_MSG_NEWTABLE,
774                                 sizeof(struct nft_trans_table));
775         if (trans == NULL)
776                 return -ENOMEM;
777
778         if ((flags & NFT_TABLE_F_DORMANT) &&
779             !(ctx->table->flags & NFT_TABLE_F_DORMANT)) {
780                 nft_trans_table_enable(trans) = false;
781         } else if (!(flags & NFT_TABLE_F_DORMANT) &&
782                    ctx->table->flags & NFT_TABLE_F_DORMANT) {
783                 ret = nf_tables_table_enable(ctx->net, ctx->table);
784                 if (ret >= 0) {
785                         ctx->table->flags &= ~NFT_TABLE_F_DORMANT;
786                         nft_trans_table_enable(trans) = true;
787                 }
788         }
789         if (ret < 0)
790                 goto err;
791
792         nft_trans_table_update(trans) = true;
793         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
794         return 0;
795 err:
796         nft_trans_destroy(trans);
797         return ret;
798 }
799
800 static u32 nft_chain_hash(const void *data, u32 len, u32 seed)
801 {
802         const char *name = data;
803
804         return jhash(name, strlen(name), seed);
805 }
806
807 static u32 nft_chain_hash_obj(const void *data, u32 len, u32 seed)
808 {
809         const struct nft_chain *chain = data;
810
811         return nft_chain_hash(chain->name, 0, seed);
812 }
813
814 static int nft_chain_hash_cmp(struct rhashtable_compare_arg *arg,
815                               const void *ptr)
816 {
817         const struct nft_chain *chain = ptr;
818         const char *name = arg->key;
819
820         return strcmp(chain->name, name);
821 }
822
823 static int nf_tables_newtable(struct net *net, struct sock *nlsk,
824                               struct sk_buff *skb, const struct nlmsghdr *nlh,
825                               const struct nlattr * const nla[],
826                               struct netlink_ext_ack *extack)
827 {
828         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
829         u8 genmask = nft_genmask_next(net);
830         int family = nfmsg->nfgen_family;
831         const struct nlattr *attr;
832         struct nft_table *table;
833         u32 flags = 0;
834         struct nft_ctx ctx;
835         int err;
836
837         lockdep_assert_held(&net->nft.commit_mutex);
838         attr = nla[NFTA_TABLE_NAME];
839         table = nft_table_lookup(net, attr, family, genmask);
840         if (IS_ERR(table)) {
841                 if (PTR_ERR(table) != -ENOENT)
842                         return PTR_ERR(table);
843         } else {
844                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
845                         NL_SET_BAD_ATTR(extack, attr);
846                         return -EEXIST;
847                 }
848                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
849                         return -EOPNOTSUPP;
850
851                 nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
852                 return nf_tables_updtable(&ctx);
853         }
854
855         if (nla[NFTA_TABLE_FLAGS]) {
856                 flags = ntohl(nla_get_be32(nla[NFTA_TABLE_FLAGS]));
857                 if (flags & ~NFT_TABLE_F_DORMANT)
858                         return -EINVAL;
859         }
860
861         err = -ENOMEM;
862         table = kzalloc(sizeof(*table), GFP_KERNEL);
863         if (table == NULL)
864                 goto err_kzalloc;
865
866         table->name = nla_strdup(attr, GFP_KERNEL);
867         if (table->name == NULL)
868                 goto err_strdup;
869
870         err = rhltable_init(&table->chains_ht, &nft_chain_ht_params);
871         if (err)
872                 goto err_chain_ht;
873
874         INIT_LIST_HEAD(&table->chains);
875         INIT_LIST_HEAD(&table->sets);
876         INIT_LIST_HEAD(&table->objects);
877         INIT_LIST_HEAD(&table->flowtables);
878         table->family = family;
879         table->flags = flags;
880         table->handle = ++table_handle;
881
882         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
883         err = nft_trans_table_add(&ctx, NFT_MSG_NEWTABLE);
884         if (err < 0)
885                 goto err_trans;
886
887         list_add_tail_rcu(&table->list, &net->nft.tables);
888         return 0;
889 err_trans:
890         rhltable_destroy(&table->chains_ht);
891 err_chain_ht:
892         kfree(table->name);
893 err_strdup:
894         kfree(table);
895 err_kzalloc:
896         return err;
897 }
898
899 static int nft_flush_table(struct nft_ctx *ctx)
900 {
901         struct nft_flowtable *flowtable, *nft;
902         struct nft_chain *chain, *nc;
903         struct nft_object *obj, *ne;
904         struct nft_set *set, *ns;
905         int err;
906
907         list_for_each_entry(chain, &ctx->table->chains, list) {
908                 if (!nft_is_active_next(ctx->net, chain))
909                         continue;
910
911                 ctx->chain = chain;
912
913                 err = nft_delrule_by_chain(ctx);
914                 if (err < 0)
915                         goto out;
916         }
917
918         list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
919                 if (!nft_is_active_next(ctx->net, set))
920                         continue;
921
922                 if (nft_set_is_anonymous(set) &&
923                     !list_empty(&set->bindings))
924                         continue;
925
926                 err = nft_delset(ctx, set);
927                 if (err < 0)
928                         goto out;
929         }
930
931         list_for_each_entry_safe(flowtable, nft, &ctx->table->flowtables, list) {
932                 err = nft_delflowtable(ctx, flowtable);
933                 if (err < 0)
934                         goto out;
935         }
936
937         list_for_each_entry_safe(obj, ne, &ctx->table->objects, list) {
938                 err = nft_delobj(ctx, obj);
939                 if (err < 0)
940                         goto out;
941         }
942
943         list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
944                 if (!nft_is_active_next(ctx->net, chain))
945                         continue;
946
947                 ctx->chain = chain;
948
949                 err = nft_delchain(ctx);
950                 if (err < 0)
951                         goto out;
952         }
953
954         err = nft_deltable(ctx);
955 out:
956         return err;
957 }
958
959 static int nft_flush(struct nft_ctx *ctx, int family)
960 {
961         struct nft_table *table, *nt;
962         const struct nlattr * const *nla = ctx->nla;
963         int err = 0;
964
965         list_for_each_entry_safe(table, nt, &ctx->net->nft.tables, list) {
966                 if (family != AF_UNSPEC && table->family != family)
967                         continue;
968
969                 ctx->family = table->family;
970
971                 if (!nft_is_active_next(ctx->net, table))
972                         continue;
973
974                 if (nla[NFTA_TABLE_NAME] &&
975                     nla_strcmp(nla[NFTA_TABLE_NAME], table->name) != 0)
976                         continue;
977
978                 ctx->table = table;
979
980                 err = nft_flush_table(ctx);
981                 if (err < 0)
982                         goto out;
983         }
984 out:
985         return err;
986 }
987
988 static int nf_tables_deltable(struct net *net, struct sock *nlsk,
989                               struct sk_buff *skb, const struct nlmsghdr *nlh,
990                               const struct nlattr * const nla[],
991                               struct netlink_ext_ack *extack)
992 {
993         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
994         u8 genmask = nft_genmask_next(net);
995         int family = nfmsg->nfgen_family;
996         const struct nlattr *attr;
997         struct nft_table *table;
998         struct nft_ctx ctx;
999
1000         nft_ctx_init(&ctx, net, skb, nlh, 0, NULL, NULL, nla);
1001         if (family == AF_UNSPEC ||
1002             (!nla[NFTA_TABLE_NAME] && !nla[NFTA_TABLE_HANDLE]))
1003                 return nft_flush(&ctx, family);
1004
1005         if (nla[NFTA_TABLE_HANDLE]) {
1006                 attr = nla[NFTA_TABLE_HANDLE];
1007                 table = nft_table_lookup_byhandle(net, attr, genmask);
1008         } else {
1009                 attr = nla[NFTA_TABLE_NAME];
1010                 table = nft_table_lookup(net, attr, family, genmask);
1011         }
1012
1013         if (IS_ERR(table)) {
1014                 NL_SET_BAD_ATTR(extack, attr);
1015                 return PTR_ERR(table);
1016         }
1017
1018         if (nlh->nlmsg_flags & NLM_F_NONREC &&
1019             table->use > 0)
1020                 return -EBUSY;
1021
1022         ctx.family = family;
1023         ctx.table = table;
1024
1025         return nft_flush_table(&ctx);
1026 }
1027
1028 static void nf_tables_table_destroy(struct nft_ctx *ctx)
1029 {
1030         if (WARN_ON(ctx->table->use > 0))
1031                 return;
1032
1033         rhltable_destroy(&ctx->table->chains_ht);
1034         kfree(ctx->table->name);
1035         kfree(ctx->table);
1036 }
1037
1038 void nft_register_chain_type(const struct nft_chain_type *ctype)
1039 {
1040         if (WARN_ON(ctype->family >= NFPROTO_NUMPROTO))
1041                 return;
1042
1043         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1044         if (WARN_ON(chain_type[ctype->family][ctype->type] != NULL)) {
1045                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1046                 return;
1047         }
1048         chain_type[ctype->family][ctype->type] = ctype;
1049         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1050 }
1051 EXPORT_SYMBOL_GPL(nft_register_chain_type);
1052
1053 void nft_unregister_chain_type(const struct nft_chain_type *ctype)
1054 {
1055         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1056         chain_type[ctype->family][ctype->type] = NULL;
1057         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1058 }
1059 EXPORT_SYMBOL_GPL(nft_unregister_chain_type);
1060
1061 /*
1062  * Chains
1063  */
1064
1065 static struct nft_chain *
1066 nft_chain_lookup_byhandle(const struct nft_table *table, u64 handle, u8 genmask)
1067 {
1068         struct nft_chain *chain;
1069
1070         list_for_each_entry(chain, &table->chains, list) {
1071                 if (chain->handle == handle &&
1072                     nft_active_genmask(chain, genmask))
1073                         return chain;
1074         }
1075
1076         return ERR_PTR(-ENOENT);
1077 }
1078
1079 static bool lockdep_commit_lock_is_held(struct net *net)
1080 {
1081 #ifdef CONFIG_PROVE_LOCKING
1082         return lockdep_is_held(&net->nft.commit_mutex);
1083 #else
1084         return true;
1085 #endif
1086 }
1087
1088 static struct nft_chain *nft_chain_lookup(struct net *net,
1089                                           struct nft_table *table,
1090                                           const struct nlattr *nla, u8 genmask)
1091 {
1092         char search[NFT_CHAIN_MAXNAMELEN + 1];
1093         struct rhlist_head *tmp, *list;
1094         struct nft_chain *chain;
1095
1096         if (nla == NULL)
1097                 return ERR_PTR(-EINVAL);
1098
1099         nla_strlcpy(search, nla, sizeof(search));
1100
1101         WARN_ON(!rcu_read_lock_held() &&
1102                 !lockdep_commit_lock_is_held(net));
1103
1104         chain = ERR_PTR(-ENOENT);
1105         rcu_read_lock();
1106         list = rhltable_lookup(&table->chains_ht, search, nft_chain_ht_params);
1107         if (!list)
1108                 goto out_unlock;
1109
1110         rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
1111                 if (nft_active_genmask(chain, genmask))
1112                         goto out_unlock;
1113         }
1114         chain = ERR_PTR(-ENOENT);
1115 out_unlock:
1116         rcu_read_unlock();
1117         return chain;
1118 }
1119
1120 static const struct nla_policy nft_chain_policy[NFTA_CHAIN_MAX + 1] = {
1121         [NFTA_CHAIN_TABLE]      = { .type = NLA_STRING,
1122                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
1123         [NFTA_CHAIN_HANDLE]     = { .type = NLA_U64 },
1124         [NFTA_CHAIN_NAME]       = { .type = NLA_STRING,
1125                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
1126         [NFTA_CHAIN_HOOK]       = { .type = NLA_NESTED },
1127         [NFTA_CHAIN_POLICY]     = { .type = NLA_U32 },
1128         [NFTA_CHAIN_TYPE]       = { .type = NLA_STRING },
1129         [NFTA_CHAIN_COUNTERS]   = { .type = NLA_NESTED },
1130 };
1131
1132 static const struct nla_policy nft_hook_policy[NFTA_HOOK_MAX + 1] = {
1133         [NFTA_HOOK_HOOKNUM]     = { .type = NLA_U32 },
1134         [NFTA_HOOK_PRIORITY]    = { .type = NLA_U32 },
1135         [NFTA_HOOK_DEV]         = { .type = NLA_STRING,
1136                                     .len = IFNAMSIZ - 1 },
1137 };
1138
1139 static int nft_dump_stats(struct sk_buff *skb, struct nft_stats __percpu *stats)
1140 {
1141         struct nft_stats *cpu_stats, total;
1142         struct nlattr *nest;
1143         unsigned int seq;
1144         u64 pkts, bytes;
1145         int cpu;
1146
1147         memset(&total, 0, sizeof(total));
1148         for_each_possible_cpu(cpu) {
1149                 cpu_stats = per_cpu_ptr(stats, cpu);
1150                 do {
1151                         seq = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
1152                         pkts = cpu_stats->pkts;
1153                         bytes = cpu_stats->bytes;
1154                 } while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, seq));
1155                 total.pkts += pkts;
1156                 total.bytes += bytes;
1157         }
1158         nest = nla_nest_start(skb, NFTA_CHAIN_COUNTERS);
1159         if (nest == NULL)
1160                 goto nla_put_failure;
1161
1162         if (nla_put_be64(skb, NFTA_COUNTER_PACKETS, cpu_to_be64(total.pkts),
1163                          NFTA_COUNTER_PAD) ||
1164             nla_put_be64(skb, NFTA_COUNTER_BYTES, cpu_to_be64(total.bytes),
1165                          NFTA_COUNTER_PAD))
1166                 goto nla_put_failure;
1167
1168         nla_nest_end(skb, nest);
1169         return 0;
1170
1171 nla_put_failure:
1172         return -ENOSPC;
1173 }
1174
1175 static int nf_tables_fill_chain_info(struct sk_buff *skb, struct net *net,
1176                                      u32 portid, u32 seq, int event, u32 flags,
1177                                      int family, const struct nft_table *table,
1178                                      const struct nft_chain *chain)
1179 {
1180         struct nlmsghdr *nlh;
1181         struct nfgenmsg *nfmsg;
1182
1183         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
1184         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
1185         if (nlh == NULL)
1186                 goto nla_put_failure;
1187
1188         nfmsg = nlmsg_data(nlh);
1189         nfmsg->nfgen_family     = family;
1190         nfmsg->version          = NFNETLINK_V0;
1191         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
1192
1193         if (nla_put_string(skb, NFTA_CHAIN_TABLE, table->name))
1194                 goto nla_put_failure;
1195         if (nla_put_be64(skb, NFTA_CHAIN_HANDLE, cpu_to_be64(chain->handle),
1196                          NFTA_CHAIN_PAD))
1197                 goto nla_put_failure;
1198         if (nla_put_string(skb, NFTA_CHAIN_NAME, chain->name))
1199                 goto nla_put_failure;
1200
1201         if (nft_is_base_chain(chain)) {
1202                 const struct nft_base_chain *basechain = nft_base_chain(chain);
1203                 const struct nf_hook_ops *ops = &basechain->ops;
1204                 struct nlattr *nest;
1205
1206                 nest = nla_nest_start(skb, NFTA_CHAIN_HOOK);
1207                 if (nest == NULL)
1208                         goto nla_put_failure;
1209                 if (nla_put_be32(skb, NFTA_HOOK_HOOKNUM, htonl(ops->hooknum)))
1210                         goto nla_put_failure;
1211                 if (nla_put_be32(skb, NFTA_HOOK_PRIORITY, htonl(ops->priority)))
1212                         goto nla_put_failure;
1213                 if (basechain->dev_name[0] &&
1214                     nla_put_string(skb, NFTA_HOOK_DEV, basechain->dev_name))
1215                         goto nla_put_failure;
1216                 nla_nest_end(skb, nest);
1217
1218                 if (nla_put_be32(skb, NFTA_CHAIN_POLICY,
1219                                  htonl(basechain->policy)))
1220                         goto nla_put_failure;
1221
1222                 if (nla_put_string(skb, NFTA_CHAIN_TYPE, basechain->type->name))
1223                         goto nla_put_failure;
1224
1225                 if (rcu_access_pointer(basechain->stats) &&
1226                     nft_dump_stats(skb, rcu_dereference(basechain->stats)))
1227                         goto nla_put_failure;
1228         }
1229
1230         if (nla_put_be32(skb, NFTA_CHAIN_USE, htonl(chain->use)))
1231                 goto nla_put_failure;
1232
1233         nlmsg_end(skb, nlh);
1234         return 0;
1235
1236 nla_put_failure:
1237         nlmsg_trim(skb, nlh);
1238         return -1;
1239 }
1240
1241 static void nf_tables_chain_notify(const struct nft_ctx *ctx, int event)
1242 {
1243         struct sk_buff *skb;
1244         int err;
1245
1246         if (!ctx->report &&
1247             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1248                 return;
1249
1250         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1251         if (skb == NULL)
1252                 goto err;
1253
1254         err = nf_tables_fill_chain_info(skb, ctx->net, ctx->portid, ctx->seq,
1255                                         event, 0, ctx->family, ctx->table,
1256                                         ctx->chain);
1257         if (err < 0) {
1258                 kfree_skb(skb);
1259                 goto err;
1260         }
1261
1262         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1263                        ctx->report, GFP_KERNEL);
1264         return;
1265 err:
1266         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
1267 }
1268
1269 static int nf_tables_dump_chains(struct sk_buff *skb,
1270                                  struct netlink_callback *cb)
1271 {
1272         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1273         const struct nft_table *table;
1274         const struct nft_chain *chain;
1275         unsigned int idx = 0, s_idx = cb->args[0];
1276         struct net *net = sock_net(skb->sk);
1277         int family = nfmsg->nfgen_family;
1278
1279         rcu_read_lock();
1280         cb->seq = net->nft.base_seq;
1281
1282         list_for_each_entry_rcu(table, &net->nft.tables, list) {
1283                 if (family != NFPROTO_UNSPEC && family != table->family)
1284                         continue;
1285
1286                 list_for_each_entry_rcu(chain, &table->chains, list) {
1287                         if (idx < s_idx)
1288                                 goto cont;
1289                         if (idx > s_idx)
1290                                 memset(&cb->args[1], 0,
1291                                        sizeof(cb->args) - sizeof(cb->args[0]));
1292                         if (!nft_is_active(net, chain))
1293                                 continue;
1294                         if (nf_tables_fill_chain_info(skb, net,
1295                                                       NETLINK_CB(cb->skb).portid,
1296                                                       cb->nlh->nlmsg_seq,
1297                                                       NFT_MSG_NEWCHAIN,
1298                                                       NLM_F_MULTI,
1299                                                       table->family, table,
1300                                                       chain) < 0)
1301                                 goto done;
1302
1303                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1304 cont:
1305                         idx++;
1306                 }
1307         }
1308 done:
1309         rcu_read_unlock();
1310         cb->args[0] = idx;
1311         return skb->len;
1312 }
1313
1314 /* called with rcu_read_lock held */
1315 static int nf_tables_getchain(struct net *net, struct sock *nlsk,
1316                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1317                               const struct nlattr * const nla[],
1318                               struct netlink_ext_ack *extack)
1319 {
1320         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1321         u8 genmask = nft_genmask_cur(net);
1322         const struct nft_chain *chain;
1323         struct nft_table *table;
1324         struct sk_buff *skb2;
1325         int family = nfmsg->nfgen_family;
1326         int err;
1327
1328         if (nlh->nlmsg_flags & NLM_F_DUMP) {
1329                 struct netlink_dump_control c = {
1330                         .dump = nf_tables_dump_chains,
1331                         .module = THIS_MODULE,
1332                 };
1333
1334                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
1335         }
1336
1337         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1338         if (IS_ERR(table)) {
1339                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1340                 return PTR_ERR(table);
1341         }
1342
1343         chain = nft_chain_lookup(net, table, nla[NFTA_CHAIN_NAME], genmask);
1344         if (IS_ERR(chain)) {
1345                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_NAME]);
1346                 return PTR_ERR(chain);
1347         }
1348
1349         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
1350         if (!skb2)
1351                 return -ENOMEM;
1352
1353         err = nf_tables_fill_chain_info(skb2, net, NETLINK_CB(skb).portid,
1354                                         nlh->nlmsg_seq, NFT_MSG_NEWCHAIN, 0,
1355                                         family, table, chain);
1356         if (err < 0)
1357                 goto err;
1358
1359         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
1360
1361 err:
1362         kfree_skb(skb2);
1363         return err;
1364 }
1365
1366 static const struct nla_policy nft_counter_policy[NFTA_COUNTER_MAX + 1] = {
1367         [NFTA_COUNTER_PACKETS]  = { .type = NLA_U64 },
1368         [NFTA_COUNTER_BYTES]    = { .type = NLA_U64 },
1369 };
1370
1371 static struct nft_stats __percpu *nft_stats_alloc(const struct nlattr *attr)
1372 {
1373         struct nlattr *tb[NFTA_COUNTER_MAX+1];
1374         struct nft_stats __percpu *newstats;
1375         struct nft_stats *stats;
1376         int err;
1377
1378         err = nla_parse_nested(tb, NFTA_COUNTER_MAX, attr, nft_counter_policy,
1379                                NULL);
1380         if (err < 0)
1381                 return ERR_PTR(err);
1382
1383         if (!tb[NFTA_COUNTER_BYTES] || !tb[NFTA_COUNTER_PACKETS])
1384                 return ERR_PTR(-EINVAL);
1385
1386         newstats = netdev_alloc_pcpu_stats(struct nft_stats);
1387         if (newstats == NULL)
1388                 return ERR_PTR(-ENOMEM);
1389
1390         /* Restore old counters on this cpu, no problem. Per-cpu statistics
1391          * are not exposed to userspace.
1392          */
1393         preempt_disable();
1394         stats = this_cpu_ptr(newstats);
1395         stats->bytes = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_BYTES]));
1396         stats->pkts = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_PACKETS]));
1397         preempt_enable();
1398
1399         return newstats;
1400 }
1401
1402 static void nft_chain_stats_replace(struct net *net,
1403                                     struct nft_base_chain *chain,
1404                                     struct nft_stats __percpu *newstats)
1405 {
1406         struct nft_stats __percpu *oldstats;
1407
1408         if (newstats == NULL)
1409                 return;
1410
1411         if (rcu_access_pointer(chain->stats)) {
1412                 oldstats = rcu_dereference_protected(chain->stats,
1413                                         lockdep_commit_lock_is_held(net));
1414                 rcu_assign_pointer(chain->stats, newstats);
1415                 synchronize_rcu();
1416                 free_percpu(oldstats);
1417         } else {
1418                 rcu_assign_pointer(chain->stats, newstats);
1419                 static_branch_inc(&nft_counters_enabled);
1420         }
1421 }
1422
1423 static void nf_tables_chain_free_chain_rules(struct nft_chain *chain)
1424 {
1425         struct nft_rule **g0 = rcu_dereference_raw(chain->rules_gen_0);
1426         struct nft_rule **g1 = rcu_dereference_raw(chain->rules_gen_1);
1427
1428         if (g0 != g1)
1429                 kvfree(g1);
1430         kvfree(g0);
1431
1432         /* should be NULL either via abort or via successful commit */
1433         WARN_ON_ONCE(chain->rules_next);
1434         kvfree(chain->rules_next);
1435 }
1436
1437 static void nf_tables_chain_destroy(struct nft_ctx *ctx)
1438 {
1439         struct nft_chain *chain = ctx->chain;
1440
1441         if (WARN_ON(chain->use > 0))
1442                 return;
1443
1444         /* no concurrent access possible anymore */
1445         nf_tables_chain_free_chain_rules(chain);
1446
1447         if (nft_is_base_chain(chain)) {
1448                 struct nft_base_chain *basechain = nft_base_chain(chain);
1449
1450                 module_put(basechain->type->owner);
1451                 if (rcu_access_pointer(basechain->stats)) {
1452                         static_branch_dec(&nft_counters_enabled);
1453                         free_percpu(rcu_dereference_raw(basechain->stats));
1454                 }
1455                 kfree(chain->name);
1456                 kfree(basechain);
1457         } else {
1458                 kfree(chain->name);
1459                 kfree(chain);
1460         }
1461 }
1462
1463 struct nft_chain_hook {
1464         u32                             num;
1465         s32                             priority;
1466         const struct nft_chain_type     *type;
1467         struct net_device               *dev;
1468 };
1469
1470 static int nft_chain_parse_hook(struct net *net,
1471                                 const struct nlattr * const nla[],
1472                                 struct nft_chain_hook *hook, u8 family,
1473                                 bool autoload)
1474 {
1475         struct nlattr *ha[NFTA_HOOK_MAX + 1];
1476         const struct nft_chain_type *type;
1477         struct net_device *dev;
1478         int err;
1479
1480         lockdep_assert_held(&net->nft.commit_mutex);
1481         lockdep_nfnl_nft_mutex_not_held();
1482
1483         err = nla_parse_nested(ha, NFTA_HOOK_MAX, nla[NFTA_CHAIN_HOOK],
1484                                nft_hook_policy, NULL);
1485         if (err < 0)
1486                 return err;
1487
1488         if (ha[NFTA_HOOK_HOOKNUM] == NULL ||
1489             ha[NFTA_HOOK_PRIORITY] == NULL)
1490                 return -EINVAL;
1491
1492         hook->num = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
1493         hook->priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
1494
1495         type = chain_type[family][NFT_CHAIN_T_DEFAULT];
1496         if (nla[NFTA_CHAIN_TYPE]) {
1497                 type = nf_tables_chain_type_lookup(net, nla[NFTA_CHAIN_TYPE],
1498                                                    family, autoload);
1499                 if (IS_ERR(type))
1500                         return PTR_ERR(type);
1501         }
1502         if (!(type->hook_mask & (1 << hook->num)))
1503                 return -EOPNOTSUPP;
1504
1505         if (type->type == NFT_CHAIN_T_NAT &&
1506             hook->priority <= NF_IP_PRI_CONNTRACK)
1507                 return -EOPNOTSUPP;
1508
1509         if (!try_module_get(type->owner))
1510                 return -ENOENT;
1511
1512         hook->type = type;
1513
1514         hook->dev = NULL;
1515         if (family == NFPROTO_NETDEV) {
1516                 char ifname[IFNAMSIZ];
1517
1518                 if (!ha[NFTA_HOOK_DEV]) {
1519                         module_put(type->owner);
1520                         return -EOPNOTSUPP;
1521                 }
1522
1523                 nla_strlcpy(ifname, ha[NFTA_HOOK_DEV], IFNAMSIZ);
1524                 dev = __dev_get_by_name(net, ifname);
1525                 if (!dev) {
1526                         module_put(type->owner);
1527                         return -ENOENT;
1528                 }
1529                 hook->dev = dev;
1530         } else if (ha[NFTA_HOOK_DEV]) {
1531                 module_put(type->owner);
1532                 return -EOPNOTSUPP;
1533         }
1534
1535         return 0;
1536 }
1537
1538 static void nft_chain_release_hook(struct nft_chain_hook *hook)
1539 {
1540         module_put(hook->type->owner);
1541 }
1542
1543 struct nft_rules_old {
1544         struct rcu_head h;
1545         struct nft_rule **start;
1546 };
1547
1548 static struct nft_rule **nf_tables_chain_alloc_rules(const struct nft_chain *chain,
1549                                                      unsigned int alloc)
1550 {
1551         if (alloc > INT_MAX)
1552                 return NULL;
1553
1554         alloc += 1;     /* NULL, ends rules */
1555         if (sizeof(struct nft_rule *) > INT_MAX / alloc)
1556                 return NULL;
1557
1558         alloc *= sizeof(struct nft_rule *);
1559         alloc += sizeof(struct nft_rules_old);
1560
1561         return kvmalloc(alloc, GFP_KERNEL);
1562 }
1563
1564 static int nf_tables_addchain(struct nft_ctx *ctx, u8 family, u8 genmask,
1565                               u8 policy)
1566 {
1567         const struct nlattr * const *nla = ctx->nla;
1568         struct nft_table *table = ctx->table;
1569         struct nft_base_chain *basechain;
1570         struct nft_stats __percpu *stats;
1571         struct net *net = ctx->net;
1572         struct nft_chain *chain;
1573         struct nft_rule **rules;
1574         int err;
1575
1576         if (table->use == UINT_MAX)
1577                 return -EOVERFLOW;
1578
1579         if (nla[NFTA_CHAIN_HOOK]) {
1580                 struct nft_chain_hook hook;
1581                 struct nf_hook_ops *ops;
1582
1583                 err = nft_chain_parse_hook(net, nla, &hook, family, true);
1584                 if (err < 0)
1585                         return err;
1586
1587                 basechain = kzalloc(sizeof(*basechain), GFP_KERNEL);
1588                 if (basechain == NULL) {
1589                         nft_chain_release_hook(&hook);
1590                         return -ENOMEM;
1591                 }
1592
1593                 if (hook.dev != NULL)
1594                         strncpy(basechain->dev_name, hook.dev->name, IFNAMSIZ);
1595
1596                 if (nla[NFTA_CHAIN_COUNTERS]) {
1597                         stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1598                         if (IS_ERR(stats)) {
1599                                 nft_chain_release_hook(&hook);
1600                                 kfree(basechain);
1601                                 return PTR_ERR(stats);
1602                         }
1603                         rcu_assign_pointer(basechain->stats, stats);
1604                         static_branch_inc(&nft_counters_enabled);
1605                 }
1606
1607                 basechain->type = hook.type;
1608                 chain = &basechain->chain;
1609
1610                 ops             = &basechain->ops;
1611                 ops->pf         = family;
1612                 ops->hooknum    = hook.num;
1613                 ops->priority   = hook.priority;
1614                 ops->priv       = chain;
1615                 ops->hook       = hook.type->hooks[ops->hooknum];
1616                 ops->dev        = hook.dev;
1617
1618                 chain->flags |= NFT_BASE_CHAIN;
1619                 basechain->policy = policy;
1620         } else {
1621                 chain = kzalloc(sizeof(*chain), GFP_KERNEL);
1622                 if (chain == NULL)
1623                         return -ENOMEM;
1624         }
1625         ctx->chain = chain;
1626
1627         INIT_LIST_HEAD(&chain->rules);
1628         chain->handle = nf_tables_alloc_handle(table);
1629         chain->table = table;
1630         chain->name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1631         if (!chain->name) {
1632                 err = -ENOMEM;
1633                 goto err1;
1634         }
1635
1636         rules = nf_tables_chain_alloc_rules(chain, 0);
1637         if (!rules) {
1638                 err = -ENOMEM;
1639                 goto err1;
1640         }
1641
1642         *rules = NULL;
1643         rcu_assign_pointer(chain->rules_gen_0, rules);
1644         rcu_assign_pointer(chain->rules_gen_1, rules);
1645
1646         err = nf_tables_register_hook(net, table, chain);
1647         if (err < 0)
1648                 goto err1;
1649
1650         err = rhltable_insert_key(&table->chains_ht, chain->name,
1651                                   &chain->rhlhead, nft_chain_ht_params);
1652         if (err)
1653                 goto err2;
1654
1655         err = nft_trans_chain_add(ctx, NFT_MSG_NEWCHAIN);
1656         if (err < 0) {
1657                 rhltable_remove(&table->chains_ht, &chain->rhlhead,
1658                                 nft_chain_ht_params);
1659                 goto err2;
1660         }
1661
1662         table->use++;
1663         list_add_tail_rcu(&chain->list, &table->chains);
1664
1665         return 0;
1666 err2:
1667         nf_tables_unregister_hook(net, table, chain);
1668 err1:
1669         nf_tables_chain_destroy(ctx);
1670
1671         return err;
1672 }
1673
1674 static int nf_tables_updchain(struct nft_ctx *ctx, u8 genmask, u8 policy)
1675 {
1676         const struct nlattr * const *nla = ctx->nla;
1677         struct nft_table *table = ctx->table;
1678         struct nft_chain *chain = ctx->chain;
1679         struct nft_base_chain *basechain;
1680         struct nft_stats *stats = NULL;
1681         struct nft_chain_hook hook;
1682         struct nf_hook_ops *ops;
1683         struct nft_trans *trans;
1684         int err;
1685
1686         if (nla[NFTA_CHAIN_HOOK]) {
1687                 if (!nft_is_base_chain(chain))
1688                         return -EBUSY;
1689
1690                 err = nft_chain_parse_hook(ctx->net, nla, &hook, ctx->family,
1691                                            false);
1692                 if (err < 0)
1693                         return err;
1694
1695                 basechain = nft_base_chain(chain);
1696                 if (basechain->type != hook.type) {
1697                         nft_chain_release_hook(&hook);
1698                         return -EBUSY;
1699                 }
1700
1701                 ops = &basechain->ops;
1702                 if (ops->hooknum != hook.num ||
1703                     ops->priority != hook.priority ||
1704                     ops->dev != hook.dev) {
1705                         nft_chain_release_hook(&hook);
1706                         return -EBUSY;
1707                 }
1708                 nft_chain_release_hook(&hook);
1709         }
1710
1711         if (nla[NFTA_CHAIN_HANDLE] &&
1712             nla[NFTA_CHAIN_NAME]) {
1713                 struct nft_chain *chain2;
1714
1715                 chain2 = nft_chain_lookup(ctx->net, table,
1716                                           nla[NFTA_CHAIN_NAME], genmask);
1717                 if (!IS_ERR(chain2))
1718                         return -EEXIST;
1719         }
1720
1721         if (nla[NFTA_CHAIN_COUNTERS]) {
1722                 if (!nft_is_base_chain(chain))
1723                         return -EOPNOTSUPP;
1724
1725                 stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1726                 if (IS_ERR(stats))
1727                         return PTR_ERR(stats);
1728         }
1729
1730         err = -ENOMEM;
1731         trans = nft_trans_alloc(ctx, NFT_MSG_NEWCHAIN,
1732                                 sizeof(struct nft_trans_chain));
1733         if (trans == NULL)
1734                 goto err;
1735
1736         nft_trans_chain_stats(trans) = stats;
1737         nft_trans_chain_update(trans) = true;
1738
1739         if (nla[NFTA_CHAIN_POLICY])
1740                 nft_trans_chain_policy(trans) = policy;
1741         else
1742                 nft_trans_chain_policy(trans) = -1;
1743
1744         if (nla[NFTA_CHAIN_HANDLE] &&
1745             nla[NFTA_CHAIN_NAME]) {
1746                 struct nft_trans *tmp;
1747                 char *name;
1748
1749                 err = -ENOMEM;
1750                 name = nla_strdup(nla[NFTA_CHAIN_NAME], GFP_KERNEL);
1751                 if (!name)
1752                         goto err;
1753
1754                 err = -EEXIST;
1755                 list_for_each_entry(tmp, &ctx->net->nft.commit_list, list) {
1756                         if (tmp->msg_type == NFT_MSG_NEWCHAIN &&
1757                             tmp->ctx.table == table &&
1758                             nft_trans_chain_update(tmp) &&
1759                             nft_trans_chain_name(tmp) &&
1760                             strcmp(name, nft_trans_chain_name(tmp)) == 0) {
1761                                 kfree(name);
1762                                 goto err;
1763                         }
1764                 }
1765
1766                 nft_trans_chain_name(trans) = name;
1767         }
1768         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
1769
1770         return 0;
1771 err:
1772         free_percpu(stats);
1773         kfree(trans);
1774         return err;
1775 }
1776
1777 static int nf_tables_newchain(struct net *net, struct sock *nlsk,
1778                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1779                               const struct nlattr * const nla[],
1780                               struct netlink_ext_ack *extack)
1781 {
1782         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1783         u8 genmask = nft_genmask_next(net);
1784         int family = nfmsg->nfgen_family;
1785         const struct nlattr *attr;
1786         struct nft_table *table;
1787         struct nft_chain *chain;
1788         u8 policy = NF_ACCEPT;
1789         struct nft_ctx ctx;
1790         u64 handle = 0;
1791
1792         lockdep_assert_held(&net->nft.commit_mutex);
1793
1794         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1795         if (IS_ERR(table)) {
1796                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1797                 return PTR_ERR(table);
1798         }
1799
1800         chain = NULL;
1801         attr = nla[NFTA_CHAIN_NAME];
1802
1803         if (nla[NFTA_CHAIN_HANDLE]) {
1804                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_CHAIN_HANDLE]));
1805                 chain = nft_chain_lookup_byhandle(table, handle, genmask);
1806                 if (IS_ERR(chain)) {
1807                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_HANDLE]);
1808                         return PTR_ERR(chain);
1809                 }
1810                 attr = nla[NFTA_CHAIN_HANDLE];
1811         } else {
1812                 chain = nft_chain_lookup(net, table, attr, genmask);
1813                 if (IS_ERR(chain)) {
1814                         if (PTR_ERR(chain) != -ENOENT) {
1815                                 NL_SET_BAD_ATTR(extack, attr);
1816                                 return PTR_ERR(chain);
1817                         }
1818                         chain = NULL;
1819                 }
1820         }
1821
1822         if (nla[NFTA_CHAIN_POLICY]) {
1823                 if (chain != NULL &&
1824                     !nft_is_base_chain(chain)) {
1825                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
1826                         return -EOPNOTSUPP;
1827                 }
1828
1829                 if (chain == NULL &&
1830                     nla[NFTA_CHAIN_HOOK] == NULL) {
1831                         NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_POLICY]);
1832                         return -EOPNOTSUPP;
1833                 }
1834
1835                 policy = ntohl(nla_get_be32(nla[NFTA_CHAIN_POLICY]));
1836                 switch (policy) {
1837                 case NF_DROP:
1838                 case NF_ACCEPT:
1839                         break;
1840                 default:
1841                         return -EINVAL;
1842                 }
1843         }
1844
1845         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
1846
1847         if (chain != NULL) {
1848                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
1849                         NL_SET_BAD_ATTR(extack, attr);
1850                         return -EEXIST;
1851                 }
1852                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
1853                         return -EOPNOTSUPP;
1854
1855                 return nf_tables_updchain(&ctx, genmask, policy);
1856         }
1857
1858         return nf_tables_addchain(&ctx, family, genmask, policy);
1859 }
1860
1861 static int nf_tables_delchain(struct net *net, struct sock *nlsk,
1862                               struct sk_buff *skb, const struct nlmsghdr *nlh,
1863                               const struct nlattr * const nla[],
1864                               struct netlink_ext_ack *extack)
1865 {
1866         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1867         u8 genmask = nft_genmask_next(net);
1868         int family = nfmsg->nfgen_family;
1869         const struct nlattr *attr;
1870         struct nft_table *table;
1871         struct nft_chain *chain;
1872         struct nft_rule *rule;
1873         struct nft_ctx ctx;
1874         u64 handle;
1875         u32 use;
1876         int err;
1877
1878         table = nft_table_lookup(net, nla[NFTA_CHAIN_TABLE], family, genmask);
1879         if (IS_ERR(table)) {
1880                 NL_SET_BAD_ATTR(extack, nla[NFTA_CHAIN_TABLE]);
1881                 return PTR_ERR(table);
1882         }
1883
1884         if (nla[NFTA_CHAIN_HANDLE]) {
1885                 attr = nla[NFTA_CHAIN_HANDLE];
1886                 handle = be64_to_cpu(nla_get_be64(attr));
1887                 chain = nft_chain_lookup_byhandle(table, handle, genmask);
1888         } else {
1889                 attr = nla[NFTA_CHAIN_NAME];
1890                 chain = nft_chain_lookup(net, table, attr, genmask);
1891         }
1892         if (IS_ERR(chain)) {
1893                 NL_SET_BAD_ATTR(extack, attr);
1894                 return PTR_ERR(chain);
1895         }
1896
1897         if (nlh->nlmsg_flags & NLM_F_NONREC &&
1898             chain->use > 0)
1899                 return -EBUSY;
1900
1901         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
1902
1903         use = chain->use;
1904         list_for_each_entry(rule, &chain->rules, list) {
1905                 if (!nft_is_active_next(net, rule))
1906                         continue;
1907                 use--;
1908
1909                 err = nft_delrule(&ctx, rule);
1910                 if (err < 0)
1911                         return err;
1912         }
1913
1914         /* There are rules and elements that are still holding references to us,
1915          * we cannot do a recursive removal in this case.
1916          */
1917         if (use > 0) {
1918                 NL_SET_BAD_ATTR(extack, attr);
1919                 return -EBUSY;
1920         }
1921
1922         return nft_delchain(&ctx);
1923 }
1924
1925 /*
1926  * Expressions
1927  */
1928
1929 /**
1930  *      nft_register_expr - register nf_tables expr type
1931  *      @ops: expr type
1932  *
1933  *      Registers the expr type for use with nf_tables. Returns zero on
1934  *      success or a negative errno code otherwise.
1935  */
1936 int nft_register_expr(struct nft_expr_type *type)
1937 {
1938         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1939         if (type->family == NFPROTO_UNSPEC)
1940                 list_add_tail_rcu(&type->list, &nf_tables_expressions);
1941         else
1942                 list_add_rcu(&type->list, &nf_tables_expressions);
1943         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1944         return 0;
1945 }
1946 EXPORT_SYMBOL_GPL(nft_register_expr);
1947
1948 /**
1949  *      nft_unregister_expr - unregister nf_tables expr type
1950  *      @ops: expr type
1951  *
1952  *      Unregisters the expr typefor use with nf_tables.
1953  */
1954 void nft_unregister_expr(struct nft_expr_type *type)
1955 {
1956         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1957         list_del_rcu(&type->list);
1958         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1959 }
1960 EXPORT_SYMBOL_GPL(nft_unregister_expr);
1961
1962 static const struct nft_expr_type *__nft_expr_type_get(u8 family,
1963                                                        struct nlattr *nla)
1964 {
1965         const struct nft_expr_type *type;
1966
1967         list_for_each_entry(type, &nf_tables_expressions, list) {
1968                 if (!nla_strcmp(nla, type->name) &&
1969                     (!type->family || type->family == family))
1970                         return type;
1971         }
1972         return NULL;
1973 }
1974
1975 static const struct nft_expr_type *nft_expr_type_get(struct net *net,
1976                                                      u8 family,
1977                                                      struct nlattr *nla)
1978 {
1979         const struct nft_expr_type *type;
1980
1981         if (nla == NULL)
1982                 return ERR_PTR(-EINVAL);
1983
1984         type = __nft_expr_type_get(family, nla);
1985         if (type != NULL && try_module_get(type->owner))
1986                 return type;
1987
1988         lockdep_nfnl_nft_mutex_not_held();
1989 #ifdef CONFIG_MODULES
1990         if (type == NULL) {
1991                 nft_request_module(net, "nft-expr-%u-%.*s", family,
1992                                    nla_len(nla), (char *)nla_data(nla));
1993                 if (__nft_expr_type_get(family, nla))
1994                         return ERR_PTR(-EAGAIN);
1995
1996                 nft_request_module(net, "nft-expr-%.*s",
1997                                    nla_len(nla), (char *)nla_data(nla));
1998                 if (__nft_expr_type_get(family, nla))
1999                         return ERR_PTR(-EAGAIN);
2000         }
2001 #endif
2002         return ERR_PTR(-ENOENT);
2003 }
2004
2005 static const struct nla_policy nft_expr_policy[NFTA_EXPR_MAX + 1] = {
2006         [NFTA_EXPR_NAME]        = { .type = NLA_STRING },
2007         [NFTA_EXPR_DATA]        = { .type = NLA_NESTED },
2008 };
2009
2010 static int nf_tables_fill_expr_info(struct sk_buff *skb,
2011                                     const struct nft_expr *expr)
2012 {
2013         if (nla_put_string(skb, NFTA_EXPR_NAME, expr->ops->type->name))
2014                 goto nla_put_failure;
2015
2016         if (expr->ops->dump) {
2017                 struct nlattr *data = nla_nest_start(skb, NFTA_EXPR_DATA);
2018                 if (data == NULL)
2019                         goto nla_put_failure;
2020                 if (expr->ops->dump(skb, expr) < 0)
2021                         goto nla_put_failure;
2022                 nla_nest_end(skb, data);
2023         }
2024
2025         return skb->len;
2026
2027 nla_put_failure:
2028         return -1;
2029 };
2030
2031 int nft_expr_dump(struct sk_buff *skb, unsigned int attr,
2032                   const struct nft_expr *expr)
2033 {
2034         struct nlattr *nest;
2035
2036         nest = nla_nest_start(skb, attr);
2037         if (!nest)
2038                 goto nla_put_failure;
2039         if (nf_tables_fill_expr_info(skb, expr) < 0)
2040                 goto nla_put_failure;
2041         nla_nest_end(skb, nest);
2042         return 0;
2043
2044 nla_put_failure:
2045         return -1;
2046 }
2047
2048 struct nft_expr_info {
2049         const struct nft_expr_ops       *ops;
2050         struct nlattr                   *tb[NFT_EXPR_MAXATTR + 1];
2051 };
2052
2053 static int nf_tables_expr_parse(const struct nft_ctx *ctx,
2054                                 const struct nlattr *nla,
2055                                 struct nft_expr_info *info)
2056 {
2057         const struct nft_expr_type *type;
2058         const struct nft_expr_ops *ops;
2059         struct nlattr *tb[NFTA_EXPR_MAX + 1];
2060         int err;
2061
2062         err = nla_parse_nested(tb, NFTA_EXPR_MAX, nla, nft_expr_policy, NULL);
2063         if (err < 0)
2064                 return err;
2065
2066         type = nft_expr_type_get(ctx->net, ctx->family, tb[NFTA_EXPR_NAME]);
2067         if (IS_ERR(type))
2068                 return PTR_ERR(type);
2069
2070         if (tb[NFTA_EXPR_DATA]) {
2071                 err = nla_parse_nested(info->tb, type->maxattr,
2072                                        tb[NFTA_EXPR_DATA], type->policy, NULL);
2073                 if (err < 0)
2074                         goto err1;
2075         } else
2076                 memset(info->tb, 0, sizeof(info->tb[0]) * (type->maxattr + 1));
2077
2078         if (type->select_ops != NULL) {
2079                 ops = type->select_ops(ctx,
2080                                        (const struct nlattr * const *)info->tb);
2081                 if (IS_ERR(ops)) {
2082                         err = PTR_ERR(ops);
2083                         goto err1;
2084                 }
2085         } else
2086                 ops = type->ops;
2087
2088         info->ops = ops;
2089         return 0;
2090
2091 err1:
2092         module_put(type->owner);
2093         return err;
2094 }
2095
2096 static int nf_tables_newexpr(const struct nft_ctx *ctx,
2097                              const struct nft_expr_info *info,
2098                              struct nft_expr *expr)
2099 {
2100         const struct nft_expr_ops *ops = info->ops;
2101         int err;
2102
2103         expr->ops = ops;
2104         if (ops->init) {
2105                 err = ops->init(ctx, expr, (const struct nlattr **)info->tb);
2106                 if (err < 0)
2107                         goto err1;
2108         }
2109
2110         return 0;
2111 err1:
2112         expr->ops = NULL;
2113         return err;
2114 }
2115
2116 static void nf_tables_expr_destroy(const struct nft_ctx *ctx,
2117                                    struct nft_expr *expr)
2118 {
2119         if (expr->ops->destroy)
2120                 expr->ops->destroy(ctx, expr);
2121         module_put(expr->ops->type->owner);
2122 }
2123
2124 struct nft_expr *nft_expr_init(const struct nft_ctx *ctx,
2125                                const struct nlattr *nla)
2126 {
2127         struct nft_expr_info info;
2128         struct nft_expr *expr;
2129         int err;
2130
2131         err = nf_tables_expr_parse(ctx, nla, &info);
2132         if (err < 0)
2133                 goto err1;
2134
2135         err = -ENOMEM;
2136         expr = kzalloc(info.ops->size, GFP_KERNEL);
2137         if (expr == NULL)
2138                 goto err2;
2139
2140         err = nf_tables_newexpr(ctx, &info, expr);
2141         if (err < 0)
2142                 goto err3;
2143
2144         return expr;
2145 err3:
2146         kfree(expr);
2147 err2:
2148         module_put(info.ops->type->owner);
2149 err1:
2150         return ERR_PTR(err);
2151 }
2152
2153 void nft_expr_destroy(const struct nft_ctx *ctx, struct nft_expr *expr)
2154 {
2155         nf_tables_expr_destroy(ctx, expr);
2156         kfree(expr);
2157 }
2158
2159 /*
2160  * Rules
2161  */
2162
2163 static struct nft_rule *__nft_rule_lookup(const struct nft_chain *chain,
2164                                           u64 handle)
2165 {
2166         struct nft_rule *rule;
2167
2168         // FIXME: this sucks
2169         list_for_each_entry_rcu(rule, &chain->rules, list) {
2170                 if (handle == rule->handle)
2171                         return rule;
2172         }
2173
2174         return ERR_PTR(-ENOENT);
2175 }
2176
2177 static struct nft_rule *nft_rule_lookup(const struct nft_chain *chain,
2178                                         const struct nlattr *nla)
2179 {
2180         if (nla == NULL)
2181                 return ERR_PTR(-EINVAL);
2182
2183         return __nft_rule_lookup(chain, be64_to_cpu(nla_get_be64(nla)));
2184 }
2185
2186 static const struct nla_policy nft_rule_policy[NFTA_RULE_MAX + 1] = {
2187         [NFTA_RULE_TABLE]       = { .type = NLA_STRING,
2188                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
2189         [NFTA_RULE_CHAIN]       = { .type = NLA_STRING,
2190                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
2191         [NFTA_RULE_HANDLE]      = { .type = NLA_U64 },
2192         [NFTA_RULE_EXPRESSIONS] = { .type = NLA_NESTED },
2193         [NFTA_RULE_COMPAT]      = { .type = NLA_NESTED },
2194         [NFTA_RULE_POSITION]    = { .type = NLA_U64 },
2195         [NFTA_RULE_USERDATA]    = { .type = NLA_BINARY,
2196                                     .len = NFT_USERDATA_MAXLEN },
2197         [NFTA_RULE_ID]          = { .type = NLA_U32 },
2198 };
2199
2200 static int nf_tables_fill_rule_info(struct sk_buff *skb, struct net *net,
2201                                     u32 portid, u32 seq, int event,
2202                                     u32 flags, int family,
2203                                     const struct nft_table *table,
2204                                     const struct nft_chain *chain,
2205                                     const struct nft_rule *rule)
2206 {
2207         struct nlmsghdr *nlh;
2208         struct nfgenmsg *nfmsg;
2209         const struct nft_expr *expr, *next;
2210         struct nlattr *list;
2211         const struct nft_rule *prule;
2212         u16 type = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
2213
2214         nlh = nlmsg_put(skb, portid, seq, type, sizeof(struct nfgenmsg), flags);
2215         if (nlh == NULL)
2216                 goto nla_put_failure;
2217
2218         nfmsg = nlmsg_data(nlh);
2219         nfmsg->nfgen_family     = family;
2220         nfmsg->version          = NFNETLINK_V0;
2221         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
2222
2223         if (nla_put_string(skb, NFTA_RULE_TABLE, table->name))
2224                 goto nla_put_failure;
2225         if (nla_put_string(skb, NFTA_RULE_CHAIN, chain->name))
2226                 goto nla_put_failure;
2227         if (nla_put_be64(skb, NFTA_RULE_HANDLE, cpu_to_be64(rule->handle),
2228                          NFTA_RULE_PAD))
2229                 goto nla_put_failure;
2230
2231         if ((event != NFT_MSG_DELRULE) && (rule->list.prev != &chain->rules)) {
2232                 prule = list_prev_entry(rule, list);
2233                 if (nla_put_be64(skb, NFTA_RULE_POSITION,
2234                                  cpu_to_be64(prule->handle),
2235                                  NFTA_RULE_PAD))
2236                         goto nla_put_failure;
2237         }
2238
2239         list = nla_nest_start(skb, NFTA_RULE_EXPRESSIONS);
2240         if (list == NULL)
2241                 goto nla_put_failure;
2242         nft_rule_for_each_expr(expr, next, rule) {
2243                 if (nft_expr_dump(skb, NFTA_LIST_ELEM, expr) < 0)
2244                         goto nla_put_failure;
2245         }
2246         nla_nest_end(skb, list);
2247
2248         if (rule->udata) {
2249                 struct nft_userdata *udata = nft_userdata(rule);
2250                 if (nla_put(skb, NFTA_RULE_USERDATA, udata->len + 1,
2251                             udata->data) < 0)
2252                         goto nla_put_failure;
2253         }
2254
2255         nlmsg_end(skb, nlh);
2256         return 0;
2257
2258 nla_put_failure:
2259         nlmsg_trim(skb, nlh);
2260         return -1;
2261 }
2262
2263 static void nf_tables_rule_notify(const struct nft_ctx *ctx,
2264                                   const struct nft_rule *rule, int event)
2265 {
2266         struct sk_buff *skb;
2267         int err;
2268
2269         if (!ctx->report &&
2270             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
2271                 return;
2272
2273         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
2274         if (skb == NULL)
2275                 goto err;
2276
2277         err = nf_tables_fill_rule_info(skb, ctx->net, ctx->portid, ctx->seq,
2278                                        event, 0, ctx->family, ctx->table,
2279                                        ctx->chain, rule);
2280         if (err < 0) {
2281                 kfree_skb(skb);
2282                 goto err;
2283         }
2284
2285         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
2286                        ctx->report, GFP_KERNEL);
2287         return;
2288 err:
2289         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
2290 }
2291
2292 struct nft_rule_dump_ctx {
2293         char *table;
2294         char *chain;
2295 };
2296
2297 static int __nf_tables_dump_rules(struct sk_buff *skb,
2298                                   unsigned int *idx,
2299                                   struct netlink_callback *cb,
2300                                   const struct nft_table *table,
2301                                   const struct nft_chain *chain)
2302 {
2303         struct net *net = sock_net(skb->sk);
2304         unsigned int s_idx = cb->args[0];
2305         const struct nft_rule *rule;
2306
2307         list_for_each_entry_rcu(rule, &chain->rules, list) {
2308                 if (!nft_is_active(net, rule))
2309                         goto cont;
2310                 if (*idx < s_idx)
2311                         goto cont;
2312                 if (*idx > s_idx) {
2313                         memset(&cb->args[1], 0,
2314                                         sizeof(cb->args) - sizeof(cb->args[0]));
2315                 }
2316                 if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
2317                                         cb->nlh->nlmsg_seq,
2318                                         NFT_MSG_NEWRULE,
2319                                         NLM_F_MULTI | NLM_F_APPEND,
2320                                         table->family,
2321                                         table, chain, rule) < 0)
2322                         return 1;
2323
2324                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
2325 cont:
2326                 (*idx)++;
2327         }
2328         return 0;
2329 }
2330
2331 static int nf_tables_dump_rules(struct sk_buff *skb,
2332                                 struct netlink_callback *cb)
2333 {
2334         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
2335         const struct nft_rule_dump_ctx *ctx = cb->data;
2336         struct nft_table *table;
2337         const struct nft_chain *chain;
2338         unsigned int idx = 0;
2339         struct net *net = sock_net(skb->sk);
2340         int family = nfmsg->nfgen_family;
2341
2342         rcu_read_lock();
2343         cb->seq = net->nft.base_seq;
2344
2345         list_for_each_entry_rcu(table, &net->nft.tables, list) {
2346                 if (family != NFPROTO_UNSPEC && family != table->family)
2347                         continue;
2348
2349                 if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0)
2350                         continue;
2351
2352                 if (ctx && ctx->table && ctx->chain) {
2353                         struct rhlist_head *list, *tmp;
2354
2355                         list = rhltable_lookup(&table->chains_ht, ctx->chain,
2356                                                nft_chain_ht_params);
2357                         if (!list)
2358                                 goto done;
2359
2360                         rhl_for_each_entry_rcu(chain, tmp, list, rhlhead) {
2361                                 if (!nft_is_active(net, chain))
2362                                         continue;
2363                                 __nf_tables_dump_rules(skb, &idx,
2364                                                        cb, table, chain);
2365                                 break;
2366                         }
2367                         goto done;
2368                 }
2369
2370                 list_for_each_entry_rcu(chain, &table->chains, list) {
2371                         if (__nf_tables_dump_rules(skb, &idx, cb, table, chain))
2372                                 goto done;
2373                 }
2374
2375                 if (ctx && ctx->table)
2376                         break;
2377         }
2378 done:
2379         rcu_read_unlock();
2380
2381         cb->args[0] = idx;
2382         return skb->len;
2383 }
2384
2385 static int nf_tables_dump_rules_start(struct netlink_callback *cb)
2386 {
2387         const struct nlattr * const *nla = cb->data;
2388         struct nft_rule_dump_ctx *ctx = NULL;
2389
2390         if (nla[NFTA_RULE_TABLE] || nla[NFTA_RULE_CHAIN]) {
2391                 ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
2392                 if (!ctx)
2393                         return -ENOMEM;
2394
2395                 if (nla[NFTA_RULE_TABLE]) {
2396                         ctx->table = nla_strdup(nla[NFTA_RULE_TABLE],
2397                                                         GFP_ATOMIC);
2398                         if (!ctx->table) {
2399                                 kfree(ctx);
2400                                 return -ENOMEM;
2401                         }
2402                 }
2403                 if (nla[NFTA_RULE_CHAIN]) {
2404                         ctx->chain = nla_strdup(nla[NFTA_RULE_CHAIN],
2405                                                 GFP_ATOMIC);
2406                         if (!ctx->chain) {
2407                                 kfree(ctx->table);
2408                                 kfree(ctx);
2409                                 return -ENOMEM;
2410                         }
2411                 }
2412         }
2413
2414         cb->data = ctx;
2415         return 0;
2416 }
2417
2418 static int nf_tables_dump_rules_done(struct netlink_callback *cb)
2419 {
2420         struct nft_rule_dump_ctx *ctx = cb->data;
2421
2422         if (ctx) {
2423                 kfree(ctx->table);
2424                 kfree(ctx->chain);
2425                 kfree(ctx);
2426         }
2427         return 0;
2428 }
2429
2430 /* called with rcu_read_lock held */
2431 static int nf_tables_getrule(struct net *net, struct sock *nlsk,
2432                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2433                              const struct nlattr * const nla[],
2434                              struct netlink_ext_ack *extack)
2435 {
2436         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2437         u8 genmask = nft_genmask_cur(net);
2438         const struct nft_chain *chain;
2439         const struct nft_rule *rule;
2440         struct nft_table *table;
2441         struct sk_buff *skb2;
2442         int family = nfmsg->nfgen_family;
2443         int err;
2444
2445         if (nlh->nlmsg_flags & NLM_F_DUMP) {
2446                 struct netlink_dump_control c = {
2447                         .start= nf_tables_dump_rules_start,
2448                         .dump = nf_tables_dump_rules,
2449                         .done = nf_tables_dump_rules_done,
2450                         .module = THIS_MODULE,
2451                         .data = (void *)nla,
2452                 };
2453
2454                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
2455         }
2456
2457         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2458         if (IS_ERR(table)) {
2459                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2460                 return PTR_ERR(table);
2461         }
2462
2463         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2464         if (IS_ERR(chain)) {
2465                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2466                 return PTR_ERR(chain);
2467         }
2468
2469         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2470         if (IS_ERR(rule)) {
2471                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2472                 return PTR_ERR(rule);
2473         }
2474
2475         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
2476         if (!skb2)
2477                 return -ENOMEM;
2478
2479         err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
2480                                        nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
2481                                        family, table, chain, rule);
2482         if (err < 0)
2483                 goto err;
2484
2485         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
2486
2487 err:
2488         kfree_skb(skb2);
2489         return err;
2490 }
2491
2492 static void nf_tables_rule_destroy(const struct nft_ctx *ctx,
2493                                    struct nft_rule *rule)
2494 {
2495         struct nft_expr *expr, *next;
2496
2497         /*
2498          * Careful: some expressions might not be initialized in case this
2499          * is called on error from nf_tables_newrule().
2500          */
2501         expr = nft_expr_first(rule);
2502         while (expr != nft_expr_last(rule) && expr->ops) {
2503                 next = nft_expr_next(expr);
2504                 nf_tables_expr_destroy(ctx, expr);
2505                 expr = next;
2506         }
2507         kfree(rule);
2508 }
2509
2510 static void nf_tables_rule_release(const struct nft_ctx *ctx,
2511                                    struct nft_rule *rule)
2512 {
2513         nft_rule_expr_deactivate(ctx, rule, NFT_TRANS_RELEASE);
2514         nf_tables_rule_destroy(ctx, rule);
2515 }
2516
2517 int nft_chain_validate(const struct nft_ctx *ctx, const struct nft_chain *chain)
2518 {
2519         struct nft_expr *expr, *last;
2520         const struct nft_data *data;
2521         struct nft_rule *rule;
2522         int err;
2523
2524         if (ctx->level == NFT_JUMP_STACK_SIZE)
2525                 return -EMLINK;
2526
2527         list_for_each_entry(rule, &chain->rules, list) {
2528                 if (!nft_is_active_next(ctx->net, rule))
2529                         continue;
2530
2531                 nft_rule_for_each_expr(expr, last, rule) {
2532                         if (!expr->ops->validate)
2533                                 continue;
2534
2535                         err = expr->ops->validate(ctx, expr, &data);
2536                         if (err < 0)
2537                                 return err;
2538                 }
2539         }
2540
2541         return 0;
2542 }
2543 EXPORT_SYMBOL_GPL(nft_chain_validate);
2544
2545 static int nft_table_validate(struct net *net, const struct nft_table *table)
2546 {
2547         struct nft_chain *chain;
2548         struct nft_ctx ctx = {
2549                 .net    = net,
2550                 .family = table->family,
2551         };
2552         int err;
2553
2554         list_for_each_entry(chain, &table->chains, list) {
2555                 if (!nft_is_base_chain(chain))
2556                         continue;
2557
2558                 ctx.chain = chain;
2559                 err = nft_chain_validate(&ctx, chain);
2560                 if (err < 0)
2561                         return err;
2562         }
2563
2564         return 0;
2565 }
2566
2567 #define NFT_RULE_MAXEXPRS       128
2568
2569 static int nf_tables_newrule(struct net *net, struct sock *nlsk,
2570                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2571                              const struct nlattr * const nla[],
2572                              struct netlink_ext_ack *extack)
2573 {
2574         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2575         u8 genmask = nft_genmask_next(net);
2576         struct nft_expr_info *info = NULL;
2577         int family = nfmsg->nfgen_family;
2578         struct nft_table *table;
2579         struct nft_chain *chain;
2580         struct nft_rule *rule, *old_rule = NULL;
2581         struct nft_userdata *udata;
2582         struct nft_trans *trans = NULL;
2583         struct nft_expr *expr;
2584         struct nft_ctx ctx;
2585         struct nlattr *tmp;
2586         unsigned int size, i, n, ulen = 0, usize = 0;
2587         int err, rem;
2588         u64 handle, pos_handle;
2589
2590         lockdep_assert_held(&net->nft.commit_mutex);
2591
2592         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2593         if (IS_ERR(table)) {
2594                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2595                 return PTR_ERR(table);
2596         }
2597
2598         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2599         if (IS_ERR(chain)) {
2600                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2601                 return PTR_ERR(chain);
2602         }
2603
2604         if (nla[NFTA_RULE_HANDLE]) {
2605                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
2606                 rule = __nft_rule_lookup(chain, handle);
2607                 if (IS_ERR(rule)) {
2608                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2609                         return PTR_ERR(rule);
2610                 }
2611
2612                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
2613                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2614                         return -EEXIST;
2615                 }
2616                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
2617                         old_rule = rule;
2618                 else
2619                         return -EOPNOTSUPP;
2620         } else {
2621                 if (!(nlh->nlmsg_flags & NLM_F_CREATE) ||
2622                     nlh->nlmsg_flags & NLM_F_REPLACE)
2623                         return -EINVAL;
2624                 handle = nf_tables_alloc_handle(table);
2625
2626                 if (chain->use == UINT_MAX)
2627                         return -EOVERFLOW;
2628
2629                 if (nla[NFTA_RULE_POSITION]) {
2630                         pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
2631                         old_rule = __nft_rule_lookup(chain, pos_handle);
2632                         if (IS_ERR(old_rule)) {
2633                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION]);
2634                                 return PTR_ERR(old_rule);
2635                         }
2636                 }
2637         }
2638
2639         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2640
2641         n = 0;
2642         size = 0;
2643         if (nla[NFTA_RULE_EXPRESSIONS]) {
2644                 info = kvmalloc_array(NFT_RULE_MAXEXPRS,
2645                                       sizeof(struct nft_expr_info),
2646                                       GFP_KERNEL);
2647                 if (!info)
2648                         return -ENOMEM;
2649
2650                 nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
2651                         err = -EINVAL;
2652                         if (nla_type(tmp) != NFTA_LIST_ELEM)
2653                                 goto err1;
2654                         if (n == NFT_RULE_MAXEXPRS)
2655                                 goto err1;
2656                         err = nf_tables_expr_parse(&ctx, tmp, &info[n]);
2657                         if (err < 0)
2658                                 goto err1;
2659                         size += info[n].ops->size;
2660                         n++;
2661                 }
2662         }
2663         /* Check for overflow of dlen field */
2664         err = -EFBIG;
2665         if (size >= 1 << 12)
2666                 goto err1;
2667
2668         if (nla[NFTA_RULE_USERDATA]) {
2669                 ulen = nla_len(nla[NFTA_RULE_USERDATA]);
2670                 if (ulen > 0)
2671                         usize = sizeof(struct nft_userdata) + ulen;
2672         }
2673
2674         err = -ENOMEM;
2675         rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL);
2676         if (rule == NULL)
2677                 goto err1;
2678
2679         nft_activate_next(net, rule);
2680
2681         rule->handle = handle;
2682         rule->dlen   = size;
2683         rule->udata  = ulen ? 1 : 0;
2684
2685         if (ulen) {
2686                 udata = nft_userdata(rule);
2687                 udata->len = ulen - 1;
2688                 nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
2689         }
2690
2691         expr = nft_expr_first(rule);
2692         for (i = 0; i < n; i++) {
2693                 err = nf_tables_newexpr(&ctx, &info[i], expr);
2694                 if (err < 0)
2695                         goto err2;
2696
2697                 if (info[i].ops->validate)
2698                         nft_validate_state_update(net, NFT_VALIDATE_NEED);
2699
2700                 info[i].ops = NULL;
2701                 expr = nft_expr_next(expr);
2702         }
2703
2704         if (nlh->nlmsg_flags & NLM_F_REPLACE) {
2705                 trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
2706                 if (trans == NULL) {
2707                         err = -ENOMEM;
2708                         goto err2;
2709                 }
2710                 err = nft_delrule(&ctx, old_rule);
2711                 if (err < 0) {
2712                         nft_trans_destroy(trans);
2713                         goto err2;
2714                 }
2715
2716                 list_add_tail_rcu(&rule->list, &old_rule->list);
2717         } else {
2718                 if (nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule) == NULL) {
2719                         err = -ENOMEM;
2720                         goto err2;
2721                 }
2722
2723                 if (nlh->nlmsg_flags & NLM_F_APPEND) {
2724                         if (old_rule)
2725                                 list_add_rcu(&rule->list, &old_rule->list);
2726                         else
2727                                 list_add_tail_rcu(&rule->list, &chain->rules);
2728                  } else {
2729                         if (old_rule)
2730                                 list_add_tail_rcu(&rule->list, &old_rule->list);
2731                         else
2732                                 list_add_rcu(&rule->list, &chain->rules);
2733                 }
2734         }
2735         kvfree(info);
2736         chain->use++;
2737
2738         if (net->nft.validate_state == NFT_VALIDATE_DO)
2739                 return nft_table_validate(net, table);
2740
2741         return 0;
2742 err2:
2743         nf_tables_rule_release(&ctx, rule);
2744 err1:
2745         for (i = 0; i < n; i++) {
2746                 if (info[i].ops != NULL)
2747                         module_put(info[i].ops->type->owner);
2748         }
2749         kvfree(info);
2750         return err;
2751 }
2752
2753 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2754                                              const struct nlattr *nla)
2755 {
2756         u32 id = ntohl(nla_get_be32(nla));
2757         struct nft_trans *trans;
2758
2759         list_for_each_entry(trans, &net->nft.commit_list, list) {
2760                 struct nft_rule *rule = nft_trans_rule(trans);
2761
2762                 if (trans->msg_type == NFT_MSG_NEWRULE &&
2763                     id == nft_trans_rule_id(trans))
2764                         return rule;
2765         }
2766         return ERR_PTR(-ENOENT);
2767 }
2768
2769 static int nf_tables_delrule(struct net *net, struct sock *nlsk,
2770                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2771                              const struct nlattr * const nla[],
2772                              struct netlink_ext_ack *extack)
2773 {
2774         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2775         u8 genmask = nft_genmask_next(net);
2776         struct nft_table *table;
2777         struct nft_chain *chain = NULL;
2778         struct nft_rule *rule;
2779         int family = nfmsg->nfgen_family, err = 0;
2780         struct nft_ctx ctx;
2781
2782         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2783         if (IS_ERR(table)) {
2784                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2785                 return PTR_ERR(table);
2786         }
2787
2788         if (nla[NFTA_RULE_CHAIN]) {
2789                 chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
2790                                          genmask);
2791                 if (IS_ERR(chain)) {
2792                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2793                         return PTR_ERR(chain);
2794                 }
2795         }
2796
2797         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2798
2799         if (chain) {
2800                 if (nla[NFTA_RULE_HANDLE]) {
2801                         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2802                         if (IS_ERR(rule)) {
2803                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2804                                 return PTR_ERR(rule);
2805                         }
2806
2807                         err = nft_delrule(&ctx, rule);
2808                 } else if (nla[NFTA_RULE_ID]) {
2809                         rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_ID]);
2810                         if (IS_ERR(rule)) {
2811                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_ID]);
2812                                 return PTR_ERR(rule);
2813                         }
2814
2815                         err = nft_delrule(&ctx, rule);
2816                 } else {
2817                         err = nft_delrule_by_chain(&ctx);
2818                 }
2819         } else {
2820                 list_for_each_entry(chain, &table->chains, list) {
2821                         if (!nft_is_active_next(net, chain))
2822                                 continue;
2823
2824                         ctx.chain = chain;
2825                         err = nft_delrule_by_chain(&ctx);
2826                         if (err < 0)
2827                                 break;
2828                 }
2829         }
2830
2831         return err;
2832 }
2833
2834 /*
2835  * Sets
2836  */
2837
2838 static LIST_HEAD(nf_tables_set_types);
2839
2840 int nft_register_set(struct nft_set_type *type)
2841 {
2842         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2843         list_add_tail_rcu(&type->list, &nf_tables_set_types);
2844         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2845         return 0;
2846 }
2847 EXPORT_SYMBOL_GPL(nft_register_set);
2848
2849 void nft_unregister_set(struct nft_set_type *type)
2850 {
2851         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2852         list_del_rcu(&type->list);
2853         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2854 }
2855 EXPORT_SYMBOL_GPL(nft_unregister_set);
2856
2857 #define NFT_SET_FEATURES        (NFT_SET_INTERVAL | NFT_SET_MAP | \
2858                                  NFT_SET_TIMEOUT | NFT_SET_OBJECT | \
2859                                  NFT_SET_EVAL)
2860
2861 static bool nft_set_ops_candidate(const struct nft_set_type *type, u32 flags)
2862 {
2863         return (flags & type->features) == (flags & NFT_SET_FEATURES);
2864 }
2865
2866 /*
2867  * Select a set implementation based on the data characteristics and the
2868  * given policy. The total memory use might not be known if no size is
2869  * given, in that case the amount of memory per element is used.
2870  */
2871 static const struct nft_set_ops *
2872 nft_select_set_ops(const struct nft_ctx *ctx,
2873                    const struct nlattr * const nla[],
2874                    const struct nft_set_desc *desc,
2875                    enum nft_set_policies policy)
2876 {
2877         const struct nft_set_ops *ops, *bops;
2878         struct nft_set_estimate est, best;
2879         const struct nft_set_type *type;
2880         u32 flags = 0;
2881
2882         lockdep_assert_held(&ctx->net->nft.commit_mutex);
2883         lockdep_nfnl_nft_mutex_not_held();
2884 #ifdef CONFIG_MODULES
2885         if (list_empty(&nf_tables_set_types)) {
2886                 nft_request_module(ctx->net, "nft-set");
2887                 if (!list_empty(&nf_tables_set_types))
2888                         return ERR_PTR(-EAGAIN);
2889         }
2890 #endif
2891         if (nla[NFTA_SET_FLAGS] != NULL)
2892                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
2893
2894         bops        = NULL;
2895         best.size   = ~0;
2896         best.lookup = ~0;
2897         best.space  = ~0;
2898
2899         list_for_each_entry(type, &nf_tables_set_types, list) {
2900                 ops = &type->ops;
2901
2902                 if (!nft_set_ops_candidate(type, flags))
2903                         continue;
2904                 if (!ops->estimate(desc, flags, &est))
2905                         continue;
2906
2907                 switch (policy) {
2908                 case NFT_SET_POL_PERFORMANCE:
2909                         if (est.lookup < best.lookup)
2910                                 break;
2911                         if (est.lookup == best.lookup &&
2912                             est.space < best.space)
2913                                 break;
2914                         continue;
2915                 case NFT_SET_POL_MEMORY:
2916                         if (!desc->size) {
2917                                 if (est.space < best.space)
2918                                         break;
2919                                 if (est.space == best.space &&
2920                                     est.lookup < best.lookup)
2921                                         break;
2922                         } else if (est.size < best.size || !bops) {
2923                                 break;
2924                         }
2925                         continue;
2926                 default:
2927                         break;
2928                 }
2929
2930                 if (!try_module_get(type->owner))
2931                         continue;
2932                 if (bops != NULL)
2933                         module_put(to_set_type(bops)->owner);
2934
2935                 bops = ops;
2936                 best = est;
2937         }
2938
2939         if (bops != NULL)
2940                 return bops;
2941
2942         return ERR_PTR(-EOPNOTSUPP);
2943 }
2944
2945 static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
2946         [NFTA_SET_TABLE]                = { .type = NLA_STRING,
2947                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
2948         [NFTA_SET_NAME]                 = { .type = NLA_STRING,
2949                                             .len = NFT_SET_MAXNAMELEN - 1 },
2950         [NFTA_SET_FLAGS]                = { .type = NLA_U32 },
2951         [NFTA_SET_KEY_TYPE]             = { .type = NLA_U32 },
2952         [NFTA_SET_KEY_LEN]              = { .type = NLA_U32 },
2953         [NFTA_SET_DATA_TYPE]            = { .type = NLA_U32 },
2954         [NFTA_SET_DATA_LEN]             = { .type = NLA_U32 },
2955         [NFTA_SET_POLICY]               = { .type = NLA_U32 },
2956         [NFTA_SET_DESC]                 = { .type = NLA_NESTED },
2957         [NFTA_SET_ID]                   = { .type = NLA_U32 },
2958         [NFTA_SET_TIMEOUT]              = { .type = NLA_U64 },
2959         [NFTA_SET_GC_INTERVAL]          = { .type = NLA_U32 },
2960         [NFTA_SET_USERDATA]             = { .type = NLA_BINARY,
2961                                             .len  = NFT_USERDATA_MAXLEN },
2962         [NFTA_SET_OBJ_TYPE]             = { .type = NLA_U32 },
2963         [NFTA_SET_HANDLE]               = { .type = NLA_U64 },
2964 };
2965
2966 static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
2967         [NFTA_SET_DESC_SIZE]            = { .type = NLA_U32 },
2968 };
2969
2970 static int nft_ctx_init_from_setattr(struct nft_ctx *ctx, struct net *net,
2971                                      const struct sk_buff *skb,
2972                                      const struct nlmsghdr *nlh,
2973                                      const struct nlattr * const nla[],
2974                                      struct netlink_ext_ack *extack,
2975                                      u8 genmask)
2976 {
2977         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2978         int family = nfmsg->nfgen_family;
2979         struct nft_table *table = NULL;
2980
2981         if (nla[NFTA_SET_TABLE] != NULL) {
2982                 table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
2983                                          genmask);
2984                 if (IS_ERR(table)) {
2985                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
2986                         return PTR_ERR(table);
2987                 }
2988         }
2989
2990         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
2991         return 0;
2992 }
2993
2994 static struct nft_set *nft_set_lookup(const struct nft_table *table,
2995                                       const struct nlattr *nla, u8 genmask)
2996 {
2997         struct nft_set *set;
2998
2999         if (nla == NULL)
3000                 return ERR_PTR(-EINVAL);
3001
3002         list_for_each_entry_rcu(set, &table->sets, list) {
3003                 if (!nla_strcmp(nla, set->name) &&
3004                     nft_active_genmask(set, genmask))
3005                         return set;
3006         }
3007         return ERR_PTR(-ENOENT);
3008 }
3009
3010 static struct nft_set *nft_set_lookup_byhandle(const struct nft_table *table,
3011                                                const struct nlattr *nla,
3012                                                u8 genmask)
3013 {
3014         struct nft_set *set;
3015
3016         list_for_each_entry(set, &table->sets, list) {
3017                 if (be64_to_cpu(nla_get_be64(nla)) == set->handle &&
3018                     nft_active_genmask(set, genmask))
3019                         return set;
3020         }
3021         return ERR_PTR(-ENOENT);
3022 }
3023
3024 static struct nft_set *nft_set_lookup_byid(const struct net *net,
3025                                            const struct nlattr *nla, u8 genmask)
3026 {
3027         struct nft_trans *trans;
3028         u32 id = ntohl(nla_get_be32(nla));
3029
3030         list_for_each_entry(trans, &net->nft.commit_list, list) {
3031                 if (trans->msg_type == NFT_MSG_NEWSET) {
3032                         struct nft_set *set = nft_trans_set(trans);
3033
3034                         if (id == nft_trans_set_id(trans) &&
3035                             nft_active_genmask(set, genmask))
3036                                 return set;
3037                 }
3038         }
3039         return ERR_PTR(-ENOENT);
3040 }
3041
3042 struct nft_set *nft_set_lookup_global(const struct net *net,
3043                                       const struct nft_table *table,
3044                                       const struct nlattr *nla_set_name,
3045                                       const struct nlattr *nla_set_id,
3046                                       u8 genmask)
3047 {
3048         struct nft_set *set;
3049
3050         set = nft_set_lookup(table, nla_set_name, genmask);
3051         if (IS_ERR(set)) {
3052                 if (!nla_set_id)
3053                         return set;
3054
3055                 set = nft_set_lookup_byid(net, nla_set_id, genmask);
3056         }
3057         return set;
3058 }
3059 EXPORT_SYMBOL_GPL(nft_set_lookup_global);
3060
3061 static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
3062                                     const char *name)
3063 {
3064         const struct nft_set *i;
3065         const char *p;
3066         unsigned long *inuse;
3067         unsigned int n = 0, min = 0;
3068
3069         p = strchr(name, '%');
3070         if (p != NULL) {
3071                 if (p[1] != 'd' || strchr(p + 2, '%'))
3072                         return -EINVAL;
3073
3074                 inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
3075                 if (inuse == NULL)
3076                         return -ENOMEM;
3077 cont:
3078                 list_for_each_entry(i, &ctx->table->sets, list) {
3079                         int tmp;
3080
3081                         if (!nft_is_active_next(ctx->net, set))
3082                                 continue;
3083                         if (!sscanf(i->name, name, &tmp))
3084                                 continue;
3085                         if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
3086                                 continue;
3087
3088                         set_bit(tmp - min, inuse);
3089                 }
3090
3091                 n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
3092                 if (n >= BITS_PER_BYTE * PAGE_SIZE) {
3093                         min += BITS_PER_BYTE * PAGE_SIZE;
3094                         memset(inuse, 0, PAGE_SIZE);
3095                         goto cont;
3096                 }
3097                 free_page((unsigned long)inuse);
3098         }
3099
3100         set->name = kasprintf(GFP_KERNEL, name, min + n);
3101         if (!set->name)
3102                 return -ENOMEM;
3103
3104         list_for_each_entry(i, &ctx->table->sets, list) {
3105                 if (!nft_is_active_next(ctx->net, i))
3106                         continue;
3107                 if (!strcmp(set->name, i->name)) {
3108                         kfree(set->name);
3109                         return -ENFILE;
3110                 }
3111         }
3112         return 0;
3113 }
3114
3115 static int nf_msecs_to_jiffies64(const struct nlattr *nla, u64 *result)
3116 {
3117         u64 ms = be64_to_cpu(nla_get_be64(nla));
3118         u64 max = (u64)(~((u64)0));
3119
3120         max = div_u64(max, NSEC_PER_MSEC);
3121         if (ms >= max)
3122                 return -ERANGE;
3123
3124         ms *= NSEC_PER_MSEC;
3125         *result = nsecs_to_jiffies64(ms);
3126         return 0;
3127 }
3128
3129 static __be64 nf_jiffies64_to_msecs(u64 input)
3130 {
3131         u64 ms = jiffies64_to_nsecs(input);
3132
3133         return cpu_to_be64(div_u64(ms, NSEC_PER_MSEC));
3134 }
3135
3136 static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
3137                               const struct nft_set *set, u16 event, u16 flags)
3138 {
3139         struct nfgenmsg *nfmsg;
3140         struct nlmsghdr *nlh;
3141         struct nlattr *desc;
3142         u32 portid = ctx->portid;
3143         u32 seq = ctx->seq;
3144
3145         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
3146         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3147                         flags);
3148         if (nlh == NULL)
3149                 goto nla_put_failure;
3150
3151         nfmsg = nlmsg_data(nlh);
3152         nfmsg->nfgen_family     = ctx->family;
3153         nfmsg->version          = NFNETLINK_V0;
3154         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
3155
3156         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
3157                 goto nla_put_failure;
3158         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
3159                 goto nla_put_failure;
3160         if (nla_put_be64(skb, NFTA_SET_HANDLE, cpu_to_be64(set->handle),
3161                          NFTA_SET_PAD))
3162                 goto nla_put_failure;
3163         if (set->flags != 0)
3164                 if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
3165                         goto nla_put_failure;
3166
3167         if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
3168                 goto nla_put_failure;
3169         if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
3170                 goto nla_put_failure;
3171         if (set->flags & NFT_SET_MAP) {
3172                 if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
3173                         goto nla_put_failure;
3174                 if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
3175                         goto nla_put_failure;
3176         }
3177         if (set->flags & NFT_SET_OBJECT &&
3178             nla_put_be32(skb, NFTA_SET_OBJ_TYPE, htonl(set->objtype)))
3179                 goto nla_put_failure;
3180
3181         if (set->timeout &&
3182             nla_put_be64(skb, NFTA_SET_TIMEOUT,
3183                          nf_jiffies64_to_msecs(set->timeout),
3184                          NFTA_SET_PAD))
3185                 goto nla_put_failure;
3186         if (set->gc_int &&
3187             nla_put_be32(skb, NFTA_SET_GC_INTERVAL, htonl(set->gc_int)))
3188                 goto nla_put_failure;
3189
3190         if (set->policy != NFT_SET_POL_PERFORMANCE) {
3191                 if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
3192                         goto nla_put_failure;
3193         }
3194
3195         if (nla_put(skb, NFTA_SET_USERDATA, set->udlen, set->udata))
3196                 goto nla_put_failure;
3197
3198         desc = nla_nest_start(skb, NFTA_SET_DESC);
3199         if (desc == NULL)
3200                 goto nla_put_failure;
3201         if (set->size &&
3202             nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
3203                 goto nla_put_failure;
3204         nla_nest_end(skb, desc);
3205
3206         nlmsg_end(skb, nlh);
3207         return 0;
3208
3209 nla_put_failure:
3210         nlmsg_trim(skb, nlh);
3211         return -1;
3212 }
3213
3214 static void nf_tables_set_notify(const struct nft_ctx *ctx,
3215                                  const struct nft_set *set, int event,
3216                                  gfp_t gfp_flags)
3217 {
3218         struct sk_buff *skb;
3219         u32 portid = ctx->portid;
3220         int err;
3221
3222         if (!ctx->report &&
3223             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
3224                 return;
3225
3226         skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
3227         if (skb == NULL)
3228                 goto err;
3229
3230         err = nf_tables_fill_set(skb, ctx, set, event, 0);
3231         if (err < 0) {
3232                 kfree_skb(skb);
3233                 goto err;
3234         }
3235
3236         nfnetlink_send(skb, ctx->net, portid, NFNLGRP_NFTABLES, ctx->report,
3237                        gfp_flags);
3238         return;
3239 err:
3240         nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
3241 }
3242
3243 static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
3244 {
3245         const struct nft_set *set;
3246         unsigned int idx, s_idx = cb->args[0];
3247         struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
3248         struct net *net = sock_net(skb->sk);
3249         struct nft_ctx *ctx = cb->data, ctx_set;
3250
3251         if (cb->args[1])
3252                 return skb->len;
3253
3254         rcu_read_lock();
3255         cb->seq = net->nft.base_seq;
3256
3257         list_for_each_entry_rcu(table, &net->nft.tables, list) {
3258                 if (ctx->family != NFPROTO_UNSPEC &&
3259                     ctx->family != table->family)
3260                         continue;
3261
3262                 if (ctx->table && ctx->table != table)
3263                         continue;
3264
3265                 if (cur_table) {
3266                         if (cur_table != table)
3267                                 continue;
3268
3269                         cur_table = NULL;
3270                 }
3271                 idx = 0;
3272                 list_for_each_entry_rcu(set, &table->sets, list) {
3273                         if (idx < s_idx)
3274                                 goto cont;
3275                         if (!nft_is_active(net, set))
3276                                 goto cont;
3277
3278                         ctx_set = *ctx;
3279                         ctx_set.table = table;
3280                         ctx_set.family = table->family;
3281
3282                         if (nf_tables_fill_set(skb, &ctx_set, set,
3283                                                NFT_MSG_NEWSET,
3284                                                NLM_F_MULTI) < 0) {
3285                                 cb->args[0] = idx;
3286                                 cb->args[2] = (unsigned long) table;
3287                                 goto done;
3288                         }
3289                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3290 cont:
3291                         idx++;
3292                 }
3293                 if (s_idx)
3294                         s_idx = 0;
3295         }
3296         cb->args[1] = 1;
3297 done:
3298         rcu_read_unlock();
3299         return skb->len;
3300 }
3301
3302 static int nf_tables_dump_sets_start(struct netlink_callback *cb)
3303 {
3304         struct nft_ctx *ctx_dump = NULL;
3305
3306         ctx_dump = kmemdup(cb->data, sizeof(*ctx_dump), GFP_ATOMIC);
3307         if (ctx_dump == NULL)
3308                 return -ENOMEM;
3309
3310         cb->data = ctx_dump;
3311         return 0;
3312 }
3313
3314 static int nf_tables_dump_sets_done(struct netlink_callback *cb)
3315 {
3316         kfree(cb->data);
3317         return 0;
3318 }
3319
3320 /* called with rcu_read_lock held */
3321 static int nf_tables_getset(struct net *net, struct sock *nlsk,
3322                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3323                             const struct nlattr * const nla[],
3324                             struct netlink_ext_ack *extack)
3325 {
3326         u8 genmask = nft_genmask_cur(net);
3327         const struct nft_set *set;
3328         struct nft_ctx ctx;
3329         struct sk_buff *skb2;
3330         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3331         int err;
3332
3333         /* Verify existence before starting dump */
3334         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3335                                         genmask);
3336         if (err < 0)
3337                 return err;
3338
3339         if (nlh->nlmsg_flags & NLM_F_DUMP) {
3340                 struct netlink_dump_control c = {
3341                         .start = nf_tables_dump_sets_start,
3342                         .dump = nf_tables_dump_sets,
3343                         .done = nf_tables_dump_sets_done,
3344                         .data = &ctx,
3345                         .module = THIS_MODULE,
3346                 };
3347
3348                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
3349         }
3350
3351         /* Only accept unspec with dump */
3352         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3353                 return -EAFNOSUPPORT;
3354         if (!nla[NFTA_SET_TABLE])
3355                 return -EINVAL;
3356
3357         set = nft_set_lookup(ctx.table, nla[NFTA_SET_NAME], genmask);
3358         if (IS_ERR(set))
3359                 return PTR_ERR(set);
3360
3361         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
3362         if (skb2 == NULL)
3363                 return -ENOMEM;
3364
3365         err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
3366         if (err < 0)
3367                 goto err;
3368
3369         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
3370
3371 err:
3372         kfree_skb(skb2);
3373         return err;
3374 }
3375
3376 static int nf_tables_set_desc_parse(const struct nft_ctx *ctx,
3377                                     struct nft_set_desc *desc,
3378                                     const struct nlattr *nla)
3379 {
3380         struct nlattr *da[NFTA_SET_DESC_MAX + 1];
3381         int err;
3382
3383         err = nla_parse_nested(da, NFTA_SET_DESC_MAX, nla,
3384                                nft_set_desc_policy, NULL);
3385         if (err < 0)
3386                 return err;
3387
3388         if (da[NFTA_SET_DESC_SIZE] != NULL)
3389                 desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
3390
3391         return 0;
3392 }
3393
3394 static int nf_tables_newset(struct net *net, struct sock *nlsk,
3395                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3396                             const struct nlattr * const nla[],
3397                             struct netlink_ext_ack *extack)
3398 {
3399         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3400         u8 genmask = nft_genmask_next(net);
3401         int family = nfmsg->nfgen_family;
3402         const struct nft_set_ops *ops;
3403         struct nft_table *table;
3404         struct nft_set *set;
3405         struct nft_ctx ctx;
3406         char *name;
3407         u64 size;
3408         u64 timeout;
3409         u32 ktype, dtype, flags, policy, gc_int, objtype;
3410         struct nft_set_desc desc;
3411         unsigned char *udata;
3412         u16 udlen;
3413         int err;
3414
3415         if (nla[NFTA_SET_TABLE] == NULL ||
3416             nla[NFTA_SET_NAME] == NULL ||
3417             nla[NFTA_SET_KEY_LEN] == NULL ||
3418             nla[NFTA_SET_ID] == NULL)
3419                 return -EINVAL;
3420
3421         memset(&desc, 0, sizeof(desc));
3422
3423         ktype = NFT_DATA_VALUE;
3424         if (nla[NFTA_SET_KEY_TYPE] != NULL) {
3425                 ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
3426                 if ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
3427                         return -EINVAL;
3428         }
3429
3430         desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
3431         if (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)
3432                 return -EINVAL;
3433
3434         flags = 0;
3435         if (nla[NFTA_SET_FLAGS] != NULL) {
3436                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3437                 if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
3438                               NFT_SET_INTERVAL | NFT_SET_TIMEOUT |
3439                               NFT_SET_MAP | NFT_SET_EVAL |
3440                               NFT_SET_OBJECT))
3441                         return -EINVAL;
3442                 /* Only one of these operations is supported */
3443                 if ((flags & (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT)) ==
3444                              (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT))
3445                         return -EOPNOTSUPP;
3446         }
3447
3448         dtype = 0;
3449         if (nla[NFTA_SET_DATA_TYPE] != NULL) {
3450                 if (!(flags & NFT_SET_MAP))
3451                         return -EINVAL;
3452
3453                 dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
3454                 if ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
3455                     dtype != NFT_DATA_VERDICT)
3456                         return -EINVAL;
3457
3458                 if (dtype != NFT_DATA_VERDICT) {
3459                         if (nla[NFTA_SET_DATA_LEN] == NULL)
3460                                 return -EINVAL;
3461                         desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
3462                         if (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)
3463                                 return -EINVAL;
3464                 } else
3465                         desc.dlen = sizeof(struct nft_verdict);
3466         } else if (flags & NFT_SET_MAP)
3467                 return -EINVAL;
3468
3469         if (nla[NFTA_SET_OBJ_TYPE] != NULL) {
3470                 if (!(flags & NFT_SET_OBJECT))
3471                         return -EINVAL;
3472
3473                 objtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));
3474                 if (objtype == NFT_OBJECT_UNSPEC ||
3475                     objtype > NFT_OBJECT_MAX)
3476                         return -EINVAL;
3477         } else if (flags & NFT_SET_OBJECT)
3478                 return -EINVAL;
3479         else
3480                 objtype = NFT_OBJECT_UNSPEC;
3481
3482         timeout = 0;
3483         if (nla[NFTA_SET_TIMEOUT] != NULL) {
3484                 if (!(flags & NFT_SET_TIMEOUT))
3485                         return -EINVAL;
3486
3487                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);
3488                 if (err)
3489                         return err;
3490         }
3491         gc_int = 0;
3492         if (nla[NFTA_SET_GC_INTERVAL] != NULL) {
3493                 if (!(flags & NFT_SET_TIMEOUT))
3494                         return -EINVAL;
3495                 gc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));
3496         }
3497
3498         policy = NFT_SET_POL_PERFORMANCE;
3499         if (nla[NFTA_SET_POLICY] != NULL)
3500                 policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
3501
3502         if (nla[NFTA_SET_DESC] != NULL) {
3503                 err = nf_tables_set_desc_parse(&ctx, &desc, nla[NFTA_SET_DESC]);
3504                 if (err < 0)
3505                         return err;
3506         }
3507
3508         table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask);
3509         if (IS_ERR(table)) {
3510                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3511                 return PTR_ERR(table);
3512         }
3513
3514         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
3515
3516         set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
3517         if (IS_ERR(set)) {
3518                 if (PTR_ERR(set) != -ENOENT) {
3519                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3520                         return PTR_ERR(set);
3521                 }
3522         } else {
3523                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
3524                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3525                         return -EEXIST;
3526                 }
3527                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
3528                         return -EOPNOTSUPP;
3529
3530                 return 0;
3531         }
3532
3533         if (!(nlh->nlmsg_flags & NLM_F_CREATE))
3534                 return -ENOENT;
3535
3536         ops = nft_select_set_ops(&ctx, nla, &desc, policy);
3537         if (IS_ERR(ops))
3538                 return PTR_ERR(ops);
3539
3540         udlen = 0;
3541         if (nla[NFTA_SET_USERDATA])
3542                 udlen = nla_len(nla[NFTA_SET_USERDATA]);
3543
3544         size = 0;
3545         if (ops->privsize != NULL)
3546                 size = ops->privsize(nla, &desc);
3547
3548         set = kvzalloc(sizeof(*set) + size + udlen, GFP_KERNEL);
3549         if (!set) {
3550                 err = -ENOMEM;
3551                 goto err1;
3552         }
3553
3554         name = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);
3555         if (!name) {
3556                 err = -ENOMEM;
3557                 goto err2;
3558         }
3559
3560         err = nf_tables_set_alloc_name(&ctx, set, name);
3561         kfree(name);
3562         if (err < 0)
3563                 goto err2;
3564
3565         udata = NULL;
3566         if (udlen) {
3567                 udata = set->data + size;
3568                 nla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);
3569         }
3570
3571         INIT_LIST_HEAD(&set->bindings);
3572         set->table = table;
3573         write_pnet(&set->net, net);
3574         set->ops   = ops;
3575         set->ktype = ktype;
3576         set->klen  = desc.klen;
3577         set->dtype = dtype;
3578         set->objtype = objtype;
3579         set->dlen  = desc.dlen;
3580         set->flags = flags;
3581         set->size  = desc.size;
3582         set->policy = policy;
3583         set->udlen  = udlen;
3584         set->udata  = udata;
3585         set->timeout = timeout;
3586         set->gc_int = gc_int;
3587         set->handle = nf_tables_alloc_handle(table);
3588
3589         err = ops->init(set, &desc, nla);
3590         if (err < 0)
3591                 goto err3;
3592
3593         err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
3594         if (err < 0)
3595                 goto err4;
3596
3597         list_add_tail_rcu(&set->list, &table->sets);
3598         table->use++;
3599         return 0;
3600
3601 err4:
3602         ops->destroy(set);
3603 err3:
3604         kfree(set->name);
3605 err2:
3606         kvfree(set);
3607 err1:
3608         module_put(to_set_type(ops)->owner);
3609         return err;
3610 }
3611
3612 static void nft_set_destroy(struct nft_set *set)
3613 {
3614         set->ops->destroy(set);
3615         module_put(to_set_type(set->ops)->owner);
3616         kfree(set->name);
3617         kvfree(set);
3618 }
3619
3620 static int nf_tables_delset(struct net *net, struct sock *nlsk,
3621                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3622                             const struct nlattr * const nla[],
3623                             struct netlink_ext_ack *extack)
3624 {
3625         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3626         u8 genmask = nft_genmask_next(net);
3627         const struct nlattr *attr;
3628         struct nft_set *set;
3629         struct nft_ctx ctx;
3630         int err;
3631
3632         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3633                 return -EAFNOSUPPORT;
3634         if (nla[NFTA_SET_TABLE] == NULL)
3635                 return -EINVAL;
3636
3637         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3638                                         genmask);
3639         if (err < 0)
3640                 return err;
3641
3642         if (nla[NFTA_SET_HANDLE]) {
3643                 attr = nla[NFTA_SET_HANDLE];
3644                 set = nft_set_lookup_byhandle(ctx.table, attr, genmask);
3645         } else {
3646                 attr = nla[NFTA_SET_NAME];
3647                 set = nft_set_lookup(ctx.table, attr, genmask);
3648         }
3649
3650         if (IS_ERR(set)) {
3651                 NL_SET_BAD_ATTR(extack, attr);
3652                 return PTR_ERR(set);
3653         }
3654         if (!list_empty(&set->bindings) ||
3655             (nlh->nlmsg_flags & NLM_F_NONREC && atomic_read(&set->nelems) > 0)) {
3656                 NL_SET_BAD_ATTR(extack, attr);
3657                 return -EBUSY;
3658         }
3659
3660         return nft_delset(&ctx, set);
3661 }
3662
3663 static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
3664                                         struct nft_set *set,
3665                                         const struct nft_set_iter *iter,
3666                                         struct nft_set_elem *elem)
3667 {
3668         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3669         enum nft_registers dreg;
3670
3671         dreg = nft_type_to_reg(set->dtype);
3672         return nft_validate_register_store(ctx, dreg, nft_set_ext_data(ext),
3673                                            set->dtype == NFT_DATA_VERDICT ?
3674                                            NFT_DATA_VERDICT : NFT_DATA_VALUE,
3675                                            set->dlen);
3676 }
3677
3678 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
3679                        struct nft_set_binding *binding)
3680 {
3681         struct nft_set_binding *i;
3682         struct nft_set_iter iter;
3683
3684         if (!list_empty(&set->bindings) && nft_set_is_anonymous(set))
3685                 return -EBUSY;
3686
3687         if (binding->flags & NFT_SET_MAP) {
3688                 /* If the set is already bound to the same chain all
3689                  * jumps are already validated for that chain.
3690                  */
3691                 list_for_each_entry(i, &set->bindings, list) {
3692                         if (i->flags & NFT_SET_MAP &&
3693                             i->chain == binding->chain)
3694                                 goto bind;
3695                 }
3696
3697                 iter.genmask    = nft_genmask_next(ctx->net);
3698                 iter.skip       = 0;
3699                 iter.count      = 0;
3700                 iter.err        = 0;
3701                 iter.fn         = nf_tables_bind_check_setelem;
3702
3703                 set->ops->walk(ctx, set, &iter);
3704                 if (iter.err < 0)
3705                         return iter.err;
3706         }
3707 bind:
3708         binding->chain = ctx->chain;
3709         list_add_tail_rcu(&binding->list, &set->bindings);
3710         nft_set_trans_bind(ctx, set);
3711
3712         return 0;
3713 }
3714 EXPORT_SYMBOL_GPL(nf_tables_bind_set);
3715
3716 void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
3717                           struct nft_set_binding *binding, bool event)
3718 {
3719         list_del_rcu(&binding->list);
3720
3721         if (list_empty(&set->bindings) && nft_set_is_anonymous(set)) {
3722                 list_del_rcu(&set->list);
3723                 if (event)
3724                         nf_tables_set_notify(ctx, set, NFT_MSG_DELSET,
3725                                              GFP_KERNEL);
3726         }
3727 }
3728 EXPORT_SYMBOL_GPL(nf_tables_unbind_set);
3729
3730 void nf_tables_destroy_set(const struct nft_ctx *ctx, struct nft_set *set)
3731 {
3732         if (list_empty(&set->bindings) && nft_set_is_anonymous(set))
3733                 nft_set_destroy(set);
3734 }
3735 EXPORT_SYMBOL_GPL(nf_tables_destroy_set);
3736
3737 const struct nft_set_ext_type nft_set_ext_types[] = {
3738         [NFT_SET_EXT_KEY]               = {
3739                 .align  = __alignof__(u32),
3740         },
3741         [NFT_SET_EXT_DATA]              = {
3742                 .align  = __alignof__(u32),
3743         },
3744         [NFT_SET_EXT_EXPR]              = {
3745                 .align  = __alignof__(struct nft_expr),
3746         },
3747         [NFT_SET_EXT_OBJREF]            = {
3748                 .len    = sizeof(struct nft_object *),
3749                 .align  = __alignof__(struct nft_object *),
3750         },
3751         [NFT_SET_EXT_FLAGS]             = {
3752                 .len    = sizeof(u8),
3753                 .align  = __alignof__(u8),
3754         },
3755         [NFT_SET_EXT_TIMEOUT]           = {
3756                 .len    = sizeof(u64),
3757                 .align  = __alignof__(u64),
3758         },
3759         [NFT_SET_EXT_EXPIRATION]        = {
3760                 .len    = sizeof(u64),
3761                 .align  = __alignof__(u64),
3762         },
3763         [NFT_SET_EXT_USERDATA]          = {
3764                 .len    = sizeof(struct nft_userdata),
3765                 .align  = __alignof__(struct nft_userdata),
3766         },
3767 };
3768 EXPORT_SYMBOL_GPL(nft_set_ext_types);
3769
3770 /*
3771  * Set elements
3772  */
3773
3774 static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
3775         [NFTA_SET_ELEM_KEY]             = { .type = NLA_NESTED },
3776         [NFTA_SET_ELEM_DATA]            = { .type = NLA_NESTED },
3777         [NFTA_SET_ELEM_FLAGS]           = { .type = NLA_U32 },
3778         [NFTA_SET_ELEM_TIMEOUT]         = { .type = NLA_U64 },
3779         [NFTA_SET_ELEM_USERDATA]        = { .type = NLA_BINARY,
3780                                             .len = NFT_USERDATA_MAXLEN },
3781         [NFTA_SET_ELEM_EXPR]            = { .type = NLA_NESTED },
3782         [NFTA_SET_ELEM_OBJREF]          = { .type = NLA_STRING },
3783 };
3784
3785 static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
3786         [NFTA_SET_ELEM_LIST_TABLE]      = { .type = NLA_STRING,
3787                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
3788         [NFTA_SET_ELEM_LIST_SET]        = { .type = NLA_STRING,
3789                                             .len = NFT_SET_MAXNAMELEN - 1 },
3790         [NFTA_SET_ELEM_LIST_ELEMENTS]   = { .type = NLA_NESTED },
3791         [NFTA_SET_ELEM_LIST_SET_ID]     = { .type = NLA_U32 },
3792 };
3793
3794 static int nft_ctx_init_from_elemattr(struct nft_ctx *ctx, struct net *net,
3795                                       const struct sk_buff *skb,
3796                                       const struct nlmsghdr *nlh,
3797                                       const struct nlattr * const nla[],
3798                                       struct netlink_ext_ack *extack,
3799                                       u8 genmask)
3800 {
3801         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3802         int family = nfmsg->nfgen_family;
3803         struct nft_table *table;
3804
3805         table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
3806                                  genmask);
3807         if (IS_ERR(table)) {
3808                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
3809                 return PTR_ERR(table);
3810         }
3811
3812         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3813         return 0;
3814 }
3815
3816 static int nf_tables_fill_setelem(struct sk_buff *skb,
3817                                   const struct nft_set *set,
3818                                   const struct nft_set_elem *elem)
3819 {
3820         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3821         unsigned char *b = skb_tail_pointer(skb);
3822         struct nlattr *nest;
3823
3824         nest = nla_nest_start(skb, NFTA_LIST_ELEM);
3825         if (nest == NULL)
3826                 goto nla_put_failure;
3827
3828         if (nft_data_dump(skb, NFTA_SET_ELEM_KEY, nft_set_ext_key(ext),
3829                           NFT_DATA_VALUE, set->klen) < 0)
3830                 goto nla_put_failure;
3831
3832         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
3833             nft_data_dump(skb, NFTA_SET_ELEM_DATA, nft_set_ext_data(ext),
3834                           set->dtype == NFT_DATA_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE,
3835                           set->dlen) < 0)
3836                 goto nla_put_failure;
3837
3838         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR) &&
3839             nft_expr_dump(skb, NFTA_SET_ELEM_EXPR, nft_set_ext_expr(ext)) < 0)
3840                 goto nla_put_failure;
3841
3842         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
3843             nla_put_string(skb, NFTA_SET_ELEM_OBJREF,
3844                            (*nft_set_ext_obj(ext))->name) < 0)
3845                 goto nla_put_failure;
3846
3847         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
3848             nla_put_be32(skb, NFTA_SET_ELEM_FLAGS,
3849                          htonl(*nft_set_ext_flags(ext))))
3850                 goto nla_put_failure;
3851
3852         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT) &&
3853             nla_put_be64(skb, NFTA_SET_ELEM_TIMEOUT,
3854                          nf_jiffies64_to_msecs(*nft_set_ext_timeout(ext)),
3855                          NFTA_SET_ELEM_PAD))
3856                 goto nla_put_failure;
3857
3858         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
3859                 u64 expires, now = get_jiffies_64();
3860
3861                 expires = *nft_set_ext_expiration(ext);
3862                 if (time_before64(now, expires))
3863                         expires -= now;
3864                 else
3865                         expires = 0;
3866
3867                 if (nla_put_be64(skb, NFTA_SET_ELEM_EXPIRATION,
3868                                  nf_jiffies64_to_msecs(expires),
3869                                  NFTA_SET_ELEM_PAD))
3870                         goto nla_put_failure;
3871         }
3872
3873         if (nft_set_ext_exists(ext, NFT_SET_EXT_USERDATA)) {
3874                 struct nft_userdata *udata;
3875
3876                 udata = nft_set_ext_userdata(ext);
3877                 if (nla_put(skb, NFTA_SET_ELEM_USERDATA,
3878                             udata->len + 1, udata->data))
3879                         goto nla_put_failure;
3880         }
3881
3882         nla_nest_end(skb, nest);
3883         return 0;
3884
3885 nla_put_failure:
3886         nlmsg_trim(skb, b);
3887         return -EMSGSIZE;
3888 }
3889
3890 struct nft_set_dump_args {
3891         const struct netlink_callback   *cb;
3892         struct nft_set_iter             iter;
3893         struct sk_buff                  *skb;
3894 };
3895
3896 static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
3897                                   struct nft_set *set,
3898                                   const struct nft_set_iter *iter,
3899                                   struct nft_set_elem *elem)
3900 {
3901         struct nft_set_dump_args *args;
3902
3903         args = container_of(iter, struct nft_set_dump_args, iter);
3904         return nf_tables_fill_setelem(args->skb, set, elem);
3905 }
3906
3907 struct nft_set_dump_ctx {
3908         const struct nft_set    *set;
3909         struct nft_ctx          ctx;
3910 };
3911
3912 static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
3913 {
3914         struct nft_set_dump_ctx *dump_ctx = cb->data;
3915         struct net *net = sock_net(skb->sk);
3916         struct nft_table *table;
3917         struct nft_set *set;
3918         struct nft_set_dump_args args;
3919         bool set_found = false;
3920         struct nfgenmsg *nfmsg;
3921         struct nlmsghdr *nlh;
3922         struct nlattr *nest;
3923         u32 portid, seq;
3924         int event;
3925
3926         rcu_read_lock();
3927         list_for_each_entry_rcu(table, &net->nft.tables, list) {
3928                 if (dump_ctx->ctx.family != NFPROTO_UNSPEC &&
3929                     dump_ctx->ctx.family != table->family)
3930                         continue;
3931
3932                 if (table != dump_ctx->ctx.table)
3933                         continue;
3934
3935                 list_for_each_entry_rcu(set, &table->sets, list) {
3936                         if (set == dump_ctx->set) {
3937                                 set_found = true;
3938                                 break;
3939                         }
3940                 }
3941                 break;
3942         }
3943
3944         if (!set_found) {
3945                 rcu_read_unlock();
3946                 return -ENOENT;
3947         }
3948
3949         event  = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWSETELEM);
3950         portid = NETLINK_CB(cb->skb).portid;
3951         seq    = cb->nlh->nlmsg_seq;
3952
3953         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3954                         NLM_F_MULTI);
3955         if (nlh == NULL)
3956                 goto nla_put_failure;
3957
3958         nfmsg = nlmsg_data(nlh);
3959         nfmsg->nfgen_family = table->family;
3960         nfmsg->version      = NFNETLINK_V0;
3961         nfmsg->res_id       = htons(net->nft.base_seq & 0xffff);
3962
3963         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, table->name))
3964                 goto nla_put_failure;
3965         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
3966                 goto nla_put_failure;
3967
3968         nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
3969         if (nest == NULL)
3970                 goto nla_put_failure;
3971
3972         args.cb                 = cb;
3973         args.skb                = skb;
3974         args.iter.genmask       = nft_genmask_cur(net);
3975         args.iter.skip          = cb->args[0];
3976         args.iter.count         = 0;
3977         args.iter.err           = 0;
3978         args.iter.fn            = nf_tables_dump_setelem;
3979         set->ops->walk(&dump_ctx->ctx, set, &args.iter);
3980         rcu_read_unlock();
3981
3982         nla_nest_end(skb, nest);
3983         nlmsg_end(skb, nlh);
3984
3985         if (args.iter.err && args.iter.err != -EMSGSIZE)
3986                 return args.iter.err;
3987         if (args.iter.count == cb->args[0])
3988                 return 0;
3989
3990         cb->args[0] = args.iter.count;
3991         return skb->len;
3992
3993 nla_put_failure:
3994         rcu_read_unlock();
3995         return -ENOSPC;
3996 }
3997
3998 static int nf_tables_dump_set_start(struct netlink_callback *cb)
3999 {
4000         struct nft_set_dump_ctx *dump_ctx = cb->data;
4001
4002         cb->data = kmemdup(dump_ctx, sizeof(*dump_ctx), GFP_ATOMIC);
4003
4004         return cb->data ? 0 : -ENOMEM;
4005 }
4006
4007 static int nf_tables_dump_set_done(struct netlink_callback *cb)
4008 {
4009         kfree(cb->data);
4010         return 0;
4011 }
4012
4013 static int nf_tables_fill_setelem_info(struct sk_buff *skb,
4014                                        const struct nft_ctx *ctx, u32 seq,
4015                                        u32 portid, int event, u16 flags,
4016                                        const struct nft_set *set,
4017                                        const struct nft_set_elem *elem)
4018 {
4019         struct nfgenmsg *nfmsg;
4020         struct nlmsghdr *nlh;
4021         struct nlattr *nest;
4022         int err;
4023
4024         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
4025         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4026                         flags);
4027         if (nlh == NULL)
4028                 goto nla_put_failure;
4029
4030         nfmsg = nlmsg_data(nlh);
4031         nfmsg->nfgen_family     = ctx->family;
4032         nfmsg->version          = NFNETLINK_V0;
4033         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
4034
4035         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
4036                 goto nla_put_failure;
4037         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
4038                 goto nla_put_failure;
4039
4040         nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4041         if (nest == NULL)
4042                 goto nla_put_failure;
4043
4044         err = nf_tables_fill_setelem(skb, set, elem);
4045         if (err < 0)
4046                 goto nla_put_failure;
4047
4048         nla_nest_end(skb, nest);
4049
4050         nlmsg_end(skb, nlh);
4051         return 0;
4052
4053 nla_put_failure:
4054         nlmsg_trim(skb, nlh);
4055         return -1;
4056 }
4057
4058 static int nft_setelem_parse_flags(const struct nft_set *set,
4059                                    const struct nlattr *attr, u32 *flags)
4060 {
4061         if (attr == NULL)
4062                 return 0;
4063
4064         *flags = ntohl(nla_get_be32(attr));
4065         if (*flags & ~NFT_SET_ELEM_INTERVAL_END)
4066                 return -EINVAL;
4067         if (!(set->flags & NFT_SET_INTERVAL) &&
4068             *flags & NFT_SET_ELEM_INTERVAL_END)
4069                 return -EINVAL;
4070
4071         return 0;
4072 }
4073
4074 static int nft_get_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4075                             const struct nlattr *attr)
4076 {
4077         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4078         struct nft_data_desc desc;
4079         struct nft_set_elem elem;
4080         struct sk_buff *skb;
4081         uint32_t flags = 0;
4082         void *priv;
4083         int err;
4084
4085         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
4086                                nft_set_elem_policy, NULL);
4087         if (err < 0)
4088                 return err;
4089
4090         if (!nla[NFTA_SET_ELEM_KEY])
4091                 return -EINVAL;
4092
4093         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4094         if (err < 0)
4095                 return err;
4096
4097         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4098                             nla[NFTA_SET_ELEM_KEY]);
4099         if (err < 0)
4100                 return err;
4101
4102         err = -EINVAL;
4103         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4104                 return err;
4105
4106         priv = set->ops->get(ctx->net, set, &elem, flags);
4107         if (IS_ERR(priv))
4108                 return PTR_ERR(priv);
4109
4110         elem.priv = priv;
4111
4112         err = -ENOMEM;
4113         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_ATOMIC);
4114         if (skb == NULL)
4115                 goto err1;
4116
4117         err = nf_tables_fill_setelem_info(skb, ctx, ctx->seq, ctx->portid,
4118                                           NFT_MSG_NEWSETELEM, 0, set, &elem);
4119         if (err < 0)
4120                 goto err2;
4121
4122         err = nfnetlink_unicast(skb, ctx->net, ctx->portid, MSG_DONTWAIT);
4123         /* This avoids a loop in nfnetlink. */
4124         if (err < 0)
4125                 goto err1;
4126
4127         return 0;
4128 err2:
4129         kfree_skb(skb);
4130 err1:
4131         /* this avoids a loop in nfnetlink. */
4132         return err == -EAGAIN ? -ENOBUFS : err;
4133 }
4134
4135 /* called with rcu_read_lock held */
4136 static int nf_tables_getsetelem(struct net *net, struct sock *nlsk,
4137                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4138                                 const struct nlattr * const nla[],
4139                                 struct netlink_ext_ack *extack)
4140 {
4141         u8 genmask = nft_genmask_cur(net);
4142         struct nft_set *set;
4143         struct nlattr *attr;
4144         struct nft_ctx ctx;
4145         int rem, err = 0;
4146
4147         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4148                                          genmask);
4149         if (err < 0)
4150                 return err;
4151
4152         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4153         if (IS_ERR(set))
4154                 return PTR_ERR(set);
4155
4156         if (nlh->nlmsg_flags & NLM_F_DUMP) {
4157                 struct netlink_dump_control c = {
4158                         .start = nf_tables_dump_set_start,
4159                         .dump = nf_tables_dump_set,
4160                         .done = nf_tables_dump_set_done,
4161                         .module = THIS_MODULE,
4162                 };
4163                 struct nft_set_dump_ctx dump_ctx = {
4164                         .set = set,
4165                         .ctx = ctx,
4166                 };
4167
4168                 c.data = &dump_ctx;
4169                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
4170         }
4171
4172         if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
4173                 return -EINVAL;
4174
4175         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4176                 err = nft_get_set_elem(&ctx, set, attr);
4177                 if (err < 0)
4178                         break;
4179         }
4180
4181         return err;
4182 }
4183
4184 static void nf_tables_setelem_notify(const struct nft_ctx *ctx,
4185                                      const struct nft_set *set,
4186                                      const struct nft_set_elem *elem,
4187                                      int event, u16 flags)
4188 {
4189         struct net *net = ctx->net;
4190         u32 portid = ctx->portid;
4191         struct sk_buff *skb;
4192         int err;
4193
4194         if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
4195                 return;
4196
4197         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
4198         if (skb == NULL)
4199                 goto err;
4200
4201         err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
4202                                           set, elem);
4203         if (err < 0) {
4204                 kfree_skb(skb);
4205                 goto err;
4206         }
4207
4208         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, ctx->report,
4209                        GFP_KERNEL);
4210         return;
4211 err:
4212         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
4213 }
4214
4215 static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
4216                                               int msg_type,
4217                                               struct nft_set *set)
4218 {
4219         struct nft_trans *trans;
4220
4221         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
4222         if (trans == NULL)
4223                 return NULL;
4224
4225         nft_trans_elem_set(trans) = set;
4226         return trans;
4227 }
4228
4229 void *nft_set_elem_init(const struct nft_set *set,
4230                         const struct nft_set_ext_tmpl *tmpl,
4231                         const u32 *key, const u32 *data,
4232                         u64 timeout, gfp_t gfp)
4233 {
4234         struct nft_set_ext *ext;
4235         void *elem;
4236
4237         elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);
4238         if (elem == NULL)
4239                 return NULL;
4240
4241         ext = nft_set_elem_ext(set, elem);
4242         nft_set_ext_init(ext, tmpl);
4243
4244         memcpy(nft_set_ext_key(ext), key, set->klen);
4245         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4246                 memcpy(nft_set_ext_data(ext), data, set->dlen);
4247         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION))
4248                 *nft_set_ext_expiration(ext) =
4249                         get_jiffies_64() + timeout;
4250         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT))
4251                 *nft_set_ext_timeout(ext) = timeout;
4252
4253         return elem;
4254 }
4255
4256 void nft_set_elem_destroy(const struct nft_set *set, void *elem,
4257                           bool destroy_expr)
4258 {
4259         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4260         struct nft_ctx ctx = {
4261                 .net    = read_pnet(&set->net),
4262                 .family = set->table->family,
4263         };
4264
4265         nft_data_release(nft_set_ext_key(ext), NFT_DATA_VALUE);
4266         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4267                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4268         if (destroy_expr && nft_set_ext_exists(ext, NFT_SET_EXT_EXPR)) {
4269                 struct nft_expr *expr = nft_set_ext_expr(ext);
4270
4271                 if (expr->ops->destroy_clone) {
4272                         expr->ops->destroy_clone(&ctx, expr);
4273                         module_put(expr->ops->type->owner);
4274                 } else {
4275                         nf_tables_expr_destroy(&ctx, expr);
4276                 }
4277         }
4278         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4279                 (*nft_set_ext_obj(ext))->use--;
4280         kfree(elem);
4281 }
4282 EXPORT_SYMBOL_GPL(nft_set_elem_destroy);
4283
4284 /* Only called from commit path, nft_set_elem_deactivate() already deals with
4285  * the refcounting from the preparation phase.
4286  */
4287 static void nf_tables_set_elem_destroy(const struct nft_ctx *ctx,
4288                                        const struct nft_set *set, void *elem)
4289 {
4290         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4291
4292         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR))
4293                 nf_tables_expr_destroy(ctx, nft_set_ext_expr(ext));
4294         kfree(elem);
4295 }
4296
4297 static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4298                             const struct nlattr *attr, u32 nlmsg_flags)
4299 {
4300         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4301         u8 genmask = nft_genmask_next(ctx->net);
4302         struct nft_data_desc d1, d2;
4303         struct nft_set_ext_tmpl tmpl;
4304         struct nft_set_ext *ext, *ext2;
4305         struct nft_set_elem elem;
4306         struct nft_set_binding *binding;
4307         struct nft_object *obj = NULL;
4308         struct nft_userdata *udata;
4309         struct nft_data data;
4310         enum nft_registers dreg;
4311         struct nft_trans *trans;
4312         u32 flags = 0;
4313         u64 timeout;
4314         u8 ulen;
4315         int err;
4316
4317         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
4318                                nft_set_elem_policy, NULL);
4319         if (err < 0)
4320                 return err;
4321
4322         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4323                 return -EINVAL;
4324
4325         nft_set_ext_prepare(&tmpl);
4326
4327         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4328         if (err < 0)
4329                 return err;
4330         if (flags != 0)
4331                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4332
4333         if (set->flags & NFT_SET_MAP) {
4334                 if (nla[NFTA_SET_ELEM_DATA] == NULL &&
4335                     !(flags & NFT_SET_ELEM_INTERVAL_END))
4336                         return -EINVAL;
4337                 if (nla[NFTA_SET_ELEM_DATA] != NULL &&
4338                     flags & NFT_SET_ELEM_INTERVAL_END)
4339                         return -EINVAL;
4340         } else {
4341                 if (nla[NFTA_SET_ELEM_DATA] != NULL)
4342                         return -EINVAL;
4343         }
4344
4345         timeout = 0;
4346         if (nla[NFTA_SET_ELEM_TIMEOUT] != NULL) {
4347                 if (!(set->flags & NFT_SET_TIMEOUT))
4348                         return -EINVAL;
4349                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_TIMEOUT],
4350                                             &timeout);
4351                 if (err)
4352                         return err;
4353         } else if (set->flags & NFT_SET_TIMEOUT) {
4354                 timeout = set->timeout;
4355         }
4356
4357         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &d1,
4358                             nla[NFTA_SET_ELEM_KEY]);
4359         if (err < 0)
4360                 goto err1;
4361         err = -EINVAL;
4362         if (d1.type != NFT_DATA_VALUE || d1.len != set->klen)
4363                 goto err2;
4364
4365         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, d1.len);
4366         if (timeout > 0) {
4367                 nft_set_ext_add(&tmpl, NFT_SET_EXT_EXPIRATION);
4368                 if (timeout != set->timeout)
4369                         nft_set_ext_add(&tmpl, NFT_SET_EXT_TIMEOUT);
4370         }
4371
4372         if (nla[NFTA_SET_ELEM_OBJREF] != NULL) {
4373                 if (!(set->flags & NFT_SET_OBJECT)) {
4374                         err = -EINVAL;
4375                         goto err2;
4376                 }
4377                 obj = nft_obj_lookup(ctx->table, nla[NFTA_SET_ELEM_OBJREF],
4378                                      set->objtype, genmask);
4379                 if (IS_ERR(obj)) {
4380                         err = PTR_ERR(obj);
4381                         goto err2;
4382                 }
4383                 nft_set_ext_add(&tmpl, NFT_SET_EXT_OBJREF);
4384         }
4385
4386         if (nla[NFTA_SET_ELEM_DATA] != NULL) {
4387                 err = nft_data_init(ctx, &data, sizeof(data), &d2,
4388                                     nla[NFTA_SET_ELEM_DATA]);
4389                 if (err < 0)
4390                         goto err2;
4391
4392                 err = -EINVAL;
4393                 if (set->dtype != NFT_DATA_VERDICT && d2.len != set->dlen)
4394                         goto err3;
4395
4396                 dreg = nft_type_to_reg(set->dtype);
4397                 list_for_each_entry(binding, &set->bindings, list) {
4398                         struct nft_ctx bind_ctx = {
4399                                 .net    = ctx->net,
4400                                 .family = ctx->family,
4401                                 .table  = ctx->table,
4402                                 .chain  = (struct nft_chain *)binding->chain,
4403                         };
4404
4405                         if (!(binding->flags & NFT_SET_MAP))
4406                                 continue;
4407
4408                         err = nft_validate_register_store(&bind_ctx, dreg,
4409                                                           &data,
4410                                                           d2.type, d2.len);
4411                         if (err < 0)
4412                                 goto err3;
4413
4414                         if (d2.type == NFT_DATA_VERDICT &&
4415                             (data.verdict.code == NFT_GOTO ||
4416                              data.verdict.code == NFT_JUMP))
4417                                 nft_validate_state_update(ctx->net,
4418                                                           NFT_VALIDATE_NEED);
4419                 }
4420
4421                 nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, d2.len);
4422         }
4423
4424         /* The full maximum length of userdata can exceed the maximum
4425          * offset value (U8_MAX) for following extensions, therefor it
4426          * must be the last extension added.
4427          */
4428         ulen = 0;
4429         if (nla[NFTA_SET_ELEM_USERDATA] != NULL) {
4430                 ulen = nla_len(nla[NFTA_SET_ELEM_USERDATA]);
4431                 if (ulen > 0)
4432                         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_USERDATA,
4433                                                ulen);
4434         }
4435
4436         err = -ENOMEM;
4437         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, data.data,
4438                                       timeout, GFP_KERNEL);
4439         if (elem.priv == NULL)
4440                 goto err3;
4441
4442         ext = nft_set_elem_ext(set, elem.priv);
4443         if (flags)
4444                 *nft_set_ext_flags(ext) = flags;
4445         if (ulen > 0) {
4446                 udata = nft_set_ext_userdata(ext);
4447                 udata->len = ulen - 1;
4448                 nla_memcpy(&udata->data, nla[NFTA_SET_ELEM_USERDATA], ulen);
4449         }
4450         if (obj) {
4451                 *nft_set_ext_obj(ext) = obj;
4452                 obj->use++;
4453         }
4454
4455         trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
4456         if (trans == NULL)
4457                 goto err4;
4458
4459         ext->genmask = nft_genmask_cur(ctx->net) | NFT_SET_ELEM_BUSY_MASK;
4460         err = set->ops->insert(ctx->net, set, &elem, &ext2);
4461         if (err) {
4462                 if (err == -EEXIST) {
4463                         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) ^
4464                             nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) ||
4465                             nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) ^
4466                             nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF)) {
4467                                 err = -EBUSY;
4468                                 goto err5;
4469                         }
4470                         if ((nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
4471                              nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) &&
4472                              memcmp(nft_set_ext_data(ext),
4473                                     nft_set_ext_data(ext2), set->dlen) != 0) ||
4474                             (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
4475                              nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF) &&
4476                              *nft_set_ext_obj(ext) != *nft_set_ext_obj(ext2)))
4477                                 err = -EBUSY;
4478                         else if (!(nlmsg_flags & NLM_F_EXCL))
4479                                 err = 0;
4480                 }
4481                 goto err5;
4482         }
4483
4484         if (set->size &&
4485             !atomic_add_unless(&set->nelems, 1, set->size + set->ndeact)) {
4486                 err = -ENFILE;
4487                 goto err6;
4488         }
4489
4490         nft_trans_elem(trans) = elem;
4491         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4492         return 0;
4493
4494 err6:
4495         set->ops->remove(ctx->net, set, &elem);
4496 err5:
4497         kfree(trans);
4498 err4:
4499         if (obj)
4500                 obj->use--;
4501         kfree(elem.priv);
4502 err3:
4503         if (nla[NFTA_SET_ELEM_DATA] != NULL)
4504                 nft_data_release(&data, d2.type);
4505 err2:
4506         nft_data_release(&elem.key.val, d1.type);
4507 err1:
4508         return err;
4509 }
4510
4511 static int nf_tables_newsetelem(struct net *net, struct sock *nlsk,
4512                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4513                                 const struct nlattr * const nla[],
4514                                 struct netlink_ext_ack *extack)
4515 {
4516         u8 genmask = nft_genmask_next(net);
4517         const struct nlattr *attr;
4518         struct nft_set *set;
4519         struct nft_ctx ctx;
4520         int rem, err;
4521
4522         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
4523                 return -EINVAL;
4524
4525         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4526                                          genmask);
4527         if (err < 0)
4528                 return err;
4529
4530         set = nft_set_lookup_global(net, ctx.table, nla[NFTA_SET_ELEM_LIST_SET],
4531                                     nla[NFTA_SET_ELEM_LIST_SET_ID], genmask);
4532         if (IS_ERR(set))
4533                 return PTR_ERR(set);
4534
4535         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4536                 return -EBUSY;
4537
4538         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4539                 err = nft_add_set_elem(&ctx, set, attr, nlh->nlmsg_flags);
4540                 if (err < 0)
4541                         return err;
4542         }
4543
4544         if (net->nft.validate_state == NFT_VALIDATE_DO)
4545                 return nft_table_validate(net, ctx.table);
4546
4547         return 0;
4548 }
4549
4550 /**
4551  *      nft_data_hold - hold a nft_data item
4552  *
4553  *      @data: struct nft_data to release
4554  *      @type: type of data
4555  *
4556  *      Hold a nft_data item. NFT_DATA_VALUE types can be silently discarded,
4557  *      NFT_DATA_VERDICT bumps the reference to chains in case of NFT_JUMP and
4558  *      NFT_GOTO verdicts. This function must be called on active data objects
4559  *      from the second phase of the commit protocol.
4560  */
4561 void nft_data_hold(const struct nft_data *data, enum nft_data_types type)
4562 {
4563         if (type == NFT_DATA_VERDICT) {
4564                 switch (data->verdict.code) {
4565                 case NFT_JUMP:
4566                 case NFT_GOTO:
4567                         data->verdict.chain->use++;
4568                         break;
4569                 }
4570         }
4571 }
4572
4573 static void nft_set_elem_activate(const struct net *net,
4574                                   const struct nft_set *set,
4575                                   struct nft_set_elem *elem)
4576 {
4577         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4578
4579         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4580                 nft_data_hold(nft_set_ext_data(ext), set->dtype);
4581         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4582                 (*nft_set_ext_obj(ext))->use++;
4583 }
4584
4585 static void nft_set_elem_deactivate(const struct net *net,
4586                                     const struct nft_set *set,
4587                                     struct nft_set_elem *elem)
4588 {
4589         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4590
4591         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4592                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4593         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4594                 (*nft_set_ext_obj(ext))->use--;
4595 }
4596
4597 static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
4598                            const struct nlattr *attr)
4599 {
4600         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4601         struct nft_set_ext_tmpl tmpl;
4602         struct nft_data_desc desc;
4603         struct nft_set_elem elem;
4604         struct nft_set_ext *ext;
4605         struct nft_trans *trans;
4606         u32 flags = 0;
4607         void *priv;
4608         int err;
4609
4610         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
4611                                nft_set_elem_policy, NULL);
4612         if (err < 0)
4613                 goto err1;
4614
4615         err = -EINVAL;
4616         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4617                 goto err1;
4618
4619         nft_set_ext_prepare(&tmpl);
4620
4621         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4622         if (err < 0)
4623                 return err;
4624         if (flags != 0)
4625                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4626
4627         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4628                             nla[NFTA_SET_ELEM_KEY]);
4629         if (err < 0)
4630                 goto err1;
4631
4632         err = -EINVAL;
4633         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4634                 goto err2;
4635
4636         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, desc.len);
4637
4638         err = -ENOMEM;
4639         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, NULL, 0,
4640                                       GFP_KERNEL);
4641         if (elem.priv == NULL)
4642                 goto err2;
4643
4644         ext = nft_set_elem_ext(set, elem.priv);
4645         if (flags)
4646                 *nft_set_ext_flags(ext) = flags;
4647
4648         trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
4649         if (trans == NULL) {
4650                 err = -ENOMEM;
4651                 goto err3;
4652         }
4653
4654         priv = set->ops->deactivate(ctx->net, set, &elem);
4655         if (priv == NULL) {
4656                 err = -ENOENT;
4657                 goto err4;
4658         }
4659         kfree(elem.priv);
4660         elem.priv = priv;
4661
4662         nft_set_elem_deactivate(ctx->net, set, &elem);
4663
4664         nft_trans_elem(trans) = elem;
4665         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4666         return 0;
4667
4668 err4:
4669         kfree(trans);
4670 err3:
4671         kfree(elem.priv);
4672 err2:
4673         nft_data_release(&elem.key.val, desc.type);
4674 err1:
4675         return err;
4676 }
4677
4678 static int nft_flush_set(const struct nft_ctx *ctx,
4679                          struct nft_set *set,
4680                          const struct nft_set_iter *iter,
4681                          struct nft_set_elem *elem)
4682 {
4683         struct nft_trans *trans;
4684         int err;
4685
4686         trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
4687                                     sizeof(struct nft_trans_elem), GFP_ATOMIC);
4688         if (!trans)
4689                 return -ENOMEM;
4690
4691         if (!set->ops->flush(ctx->net, set, elem->priv)) {
4692                 err = -ENOENT;
4693                 goto err1;
4694         }
4695         set->ndeact++;
4696
4697         nft_set_elem_deactivate(ctx->net, set, elem);
4698         nft_trans_elem_set(trans) = set;
4699         nft_trans_elem(trans) = *elem;
4700         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4701
4702         return 0;
4703 err1:
4704         kfree(trans);
4705         return err;
4706 }
4707
4708 static int nf_tables_delsetelem(struct net *net, struct sock *nlsk,
4709                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4710                                 const struct nlattr * const nla[],
4711                                 struct netlink_ext_ack *extack)
4712 {
4713         u8 genmask = nft_genmask_next(net);
4714         const struct nlattr *attr;
4715         struct nft_set *set;
4716         struct nft_ctx ctx;
4717         int rem, err = 0;
4718
4719         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4720                                          genmask);
4721         if (err < 0)
4722                 return err;
4723
4724         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4725         if (IS_ERR(set))
4726                 return PTR_ERR(set);
4727         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4728                 return -EBUSY;
4729
4730         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL) {
4731                 struct nft_set_iter iter = {
4732                         .genmask        = genmask,
4733                         .fn             = nft_flush_set,
4734                 };
4735                 set->ops->walk(&ctx, set, &iter);
4736
4737                 return iter.err;
4738         }
4739
4740         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4741                 err = nft_del_setelem(&ctx, set, attr);
4742                 if (err < 0)
4743                         break;
4744
4745                 set->ndeact++;
4746         }
4747         return err;
4748 }
4749
4750 void nft_set_gc_batch_release(struct rcu_head *rcu)
4751 {
4752         struct nft_set_gc_batch *gcb;
4753         unsigned int i;
4754
4755         gcb = container_of(rcu, struct nft_set_gc_batch, head.rcu);
4756         for (i = 0; i < gcb->head.cnt; i++)
4757                 nft_set_elem_destroy(gcb->head.set, gcb->elems[i], true);
4758         kfree(gcb);
4759 }
4760 EXPORT_SYMBOL_GPL(nft_set_gc_batch_release);
4761
4762 struct nft_set_gc_batch *nft_set_gc_batch_alloc(const struct nft_set *set,
4763                                                 gfp_t gfp)
4764 {
4765         struct nft_set_gc_batch *gcb;
4766
4767         gcb = kzalloc(sizeof(*gcb), gfp);
4768         if (gcb == NULL)
4769                 return gcb;
4770         gcb->head.set = set;
4771         return gcb;
4772 }
4773 EXPORT_SYMBOL_GPL(nft_set_gc_batch_alloc);
4774
4775 /*
4776  * Stateful objects
4777  */
4778
4779 /**
4780  *      nft_register_obj- register nf_tables stateful object type
4781  *      @obj: object type
4782  *
4783  *      Registers the object type for use with nf_tables. Returns zero on
4784  *      success or a negative errno code otherwise.
4785  */
4786 int nft_register_obj(struct nft_object_type *obj_type)
4787 {
4788         if (obj_type->type == NFT_OBJECT_UNSPEC)
4789                 return -EINVAL;
4790
4791         nfnl_lock(NFNL_SUBSYS_NFTABLES);
4792         list_add_rcu(&obj_type->list, &nf_tables_objects);
4793         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4794         return 0;
4795 }
4796 EXPORT_SYMBOL_GPL(nft_register_obj);
4797
4798 /**
4799  *      nft_unregister_obj - unregister nf_tables object type
4800  *      @obj: object type
4801  *
4802  *      Unregisters the object type for use with nf_tables.
4803  */
4804 void nft_unregister_obj(struct nft_object_type *obj_type)
4805 {
4806         nfnl_lock(NFNL_SUBSYS_NFTABLES);
4807         list_del_rcu(&obj_type->list);
4808         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4809 }
4810 EXPORT_SYMBOL_GPL(nft_unregister_obj);
4811
4812 struct nft_object *nft_obj_lookup(const struct nft_table *table,
4813                                   const struct nlattr *nla, u32 objtype,
4814                                   u8 genmask)
4815 {
4816         struct nft_object *obj;
4817
4818         list_for_each_entry_rcu(obj, &table->objects, list) {
4819                 if (!nla_strcmp(nla, obj->name) &&
4820                     objtype == obj->ops->type->type &&
4821                     nft_active_genmask(obj, genmask))
4822                         return obj;
4823         }
4824         return ERR_PTR(-ENOENT);
4825 }
4826 EXPORT_SYMBOL_GPL(nft_obj_lookup);
4827
4828 static struct nft_object *nft_obj_lookup_byhandle(const struct nft_table *table,
4829                                                   const struct nlattr *nla,
4830                                                   u32 objtype, u8 genmask)
4831 {
4832         struct nft_object *obj;
4833
4834         list_for_each_entry(obj, &table->objects, list) {
4835                 if (be64_to_cpu(nla_get_be64(nla)) == obj->handle &&
4836                     objtype == obj->ops->type->type &&
4837                     nft_active_genmask(obj, genmask))
4838                         return obj;
4839         }
4840         return ERR_PTR(-ENOENT);
4841 }
4842
4843 static const struct nla_policy nft_obj_policy[NFTA_OBJ_MAX + 1] = {
4844         [NFTA_OBJ_TABLE]        = { .type = NLA_STRING,
4845                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
4846         [NFTA_OBJ_NAME]         = { .type = NLA_STRING,
4847                                     .len = NFT_OBJ_MAXNAMELEN - 1 },
4848         [NFTA_OBJ_TYPE]         = { .type = NLA_U32 },
4849         [NFTA_OBJ_DATA]         = { .type = NLA_NESTED },
4850         [NFTA_OBJ_HANDLE]       = { .type = NLA_U64},
4851 };
4852
4853 static struct nft_object *nft_obj_init(const struct nft_ctx *ctx,
4854                                        const struct nft_object_type *type,
4855                                        const struct nlattr *attr)
4856 {
4857         struct nlattr **tb;
4858         const struct nft_object_ops *ops;
4859         struct nft_object *obj;
4860         int err = -ENOMEM;
4861
4862         tb = kmalloc_array(type->maxattr + 1, sizeof(*tb), GFP_KERNEL);
4863         if (!tb)
4864                 goto err1;
4865
4866         if (attr) {
4867                 err = nla_parse_nested(tb, type->maxattr, attr, type->policy,
4868                                        NULL);
4869                 if (err < 0)
4870                         goto err2;
4871         } else {
4872                 memset(tb, 0, sizeof(tb[0]) * (type->maxattr + 1));
4873         }
4874
4875         if (type->select_ops) {
4876                 ops = type->select_ops(ctx, (const struct nlattr * const *)tb);
4877                 if (IS_ERR(ops)) {
4878                         err = PTR_ERR(ops);
4879                         goto err2;
4880                 }
4881         } else {
4882                 ops = type->ops;
4883         }
4884
4885         err = -ENOMEM;
4886         obj = kzalloc(sizeof(*obj) + ops->size, GFP_KERNEL);
4887         if (!obj)
4888                 goto err2;
4889
4890         err = ops->init(ctx, (const struct nlattr * const *)tb, obj);
4891         if (err < 0)
4892                 goto err3;
4893
4894         obj->ops = ops;
4895
4896         kfree(tb);
4897         return obj;
4898 err3:
4899         kfree(obj);
4900 err2:
4901         kfree(tb);
4902 err1:
4903         return ERR_PTR(err);
4904 }
4905
4906 static int nft_object_dump(struct sk_buff *skb, unsigned int attr,
4907                            struct nft_object *obj, bool reset)
4908 {
4909         struct nlattr *nest;
4910
4911         nest = nla_nest_start(skb, attr);
4912         if (!nest)
4913                 goto nla_put_failure;
4914         if (obj->ops->dump(skb, obj, reset) < 0)
4915                 goto nla_put_failure;
4916         nla_nest_end(skb, nest);
4917         return 0;
4918
4919 nla_put_failure:
4920         return -1;
4921 }
4922
4923 static const struct nft_object_type *__nft_obj_type_get(u32 objtype)
4924 {
4925         const struct nft_object_type *type;
4926
4927         list_for_each_entry(type, &nf_tables_objects, list) {
4928                 if (objtype == type->type)
4929                         return type;
4930         }
4931         return NULL;
4932 }
4933
4934 static const struct nft_object_type *
4935 nft_obj_type_get(struct net *net, u32 objtype)
4936 {
4937         const struct nft_object_type *type;
4938
4939         type = __nft_obj_type_get(objtype);
4940         if (type != NULL && try_module_get(type->owner))
4941                 return type;
4942
4943         lockdep_nfnl_nft_mutex_not_held();
4944 #ifdef CONFIG_MODULES
4945         if (type == NULL) {
4946                 nft_request_module(net, "nft-obj-%u", objtype);
4947                 if (__nft_obj_type_get(objtype))
4948                         return ERR_PTR(-EAGAIN);
4949         }
4950 #endif
4951         return ERR_PTR(-ENOENT);
4952 }
4953
4954 static int nf_tables_newobj(struct net *net, struct sock *nlsk,
4955                             struct sk_buff *skb, const struct nlmsghdr *nlh,
4956                             const struct nlattr * const nla[],
4957                             struct netlink_ext_ack *extack)
4958 {
4959         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
4960         const struct nft_object_type *type;
4961         u8 genmask = nft_genmask_next(net);
4962         int family = nfmsg->nfgen_family;
4963         struct nft_table *table;
4964         struct nft_object *obj;
4965         struct nft_ctx ctx;
4966         u32 objtype;
4967         int err;
4968
4969         if (!nla[NFTA_OBJ_TYPE] ||
4970             !nla[NFTA_OBJ_NAME] ||
4971             !nla[NFTA_OBJ_DATA])
4972                 return -EINVAL;
4973
4974         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
4975         if (IS_ERR(table)) {
4976                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
4977                 return PTR_ERR(table);
4978         }
4979
4980         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
4981         obj = nft_obj_lookup(table, nla[NFTA_OBJ_NAME], objtype, genmask);
4982         if (IS_ERR(obj)) {
4983                 err = PTR_ERR(obj);
4984                 if (err != -ENOENT) {
4985                         NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
4986                         return err;
4987                 }
4988         } else {
4989                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
4990                         NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
4991                         return -EEXIST;
4992                 }
4993                 return 0;
4994         }
4995
4996         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
4997
4998         type = nft_obj_type_get(net, objtype);
4999         if (IS_ERR(type))
5000                 return PTR_ERR(type);
5001
5002         obj = nft_obj_init(&ctx, type, nla[NFTA_OBJ_DATA]);
5003         if (IS_ERR(obj)) {
5004                 err = PTR_ERR(obj);
5005                 goto err1;
5006         }
5007         obj->table = table;
5008         obj->handle = nf_tables_alloc_handle(table);
5009
5010         obj->name = nla_strdup(nla[NFTA_OBJ_NAME], GFP_KERNEL);
5011         if (!obj->name) {
5012                 err = -ENOMEM;
5013                 goto err2;
5014         }
5015
5016         err = nft_trans_obj_add(&ctx, NFT_MSG_NEWOBJ, obj);
5017         if (err < 0)
5018                 goto err3;
5019
5020         list_add_tail_rcu(&obj->list, &table->objects);
5021         table->use++;
5022         return 0;
5023 err3:
5024         kfree(obj->name);
5025 err2:
5026         if (obj->ops->destroy)
5027                 obj->ops->destroy(&ctx, obj);
5028         kfree(obj);
5029 err1:
5030         module_put(type->owner);
5031         return err;
5032 }
5033
5034 static int nf_tables_fill_obj_info(struct sk_buff *skb, struct net *net,
5035                                    u32 portid, u32 seq, int event, u32 flags,
5036                                    int family, const struct nft_table *table,
5037                                    struct nft_object *obj, bool reset)
5038 {
5039         struct nfgenmsg *nfmsg;
5040         struct nlmsghdr *nlh;
5041
5042         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5043         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5044         if (nlh == NULL)
5045                 goto nla_put_failure;
5046
5047         nfmsg = nlmsg_data(nlh);
5048         nfmsg->nfgen_family     = family;
5049         nfmsg->version          = NFNETLINK_V0;
5050         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5051
5052         if (nla_put_string(skb, NFTA_OBJ_TABLE, table->name) ||
5053             nla_put_string(skb, NFTA_OBJ_NAME, obj->name) ||
5054             nla_put_be32(skb, NFTA_OBJ_TYPE, htonl(obj->ops->type->type)) ||
5055             nla_put_be32(skb, NFTA_OBJ_USE, htonl(obj->use)) ||
5056             nft_object_dump(skb, NFTA_OBJ_DATA, obj, reset) ||
5057             nla_put_be64(skb, NFTA_OBJ_HANDLE, cpu_to_be64(obj->handle),
5058                          NFTA_OBJ_PAD))
5059                 goto nla_put_failure;
5060
5061         nlmsg_end(skb, nlh);
5062         return 0;
5063
5064 nla_put_failure:
5065         nlmsg_trim(skb, nlh);
5066         return -1;
5067 }
5068
5069 struct nft_obj_filter {
5070         char            *table;
5071         u32             type;
5072 };
5073
5074 static int nf_tables_dump_obj(struct sk_buff *skb, struct netlink_callback *cb)
5075 {
5076         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5077         const struct nft_table *table;
5078         unsigned int idx = 0, s_idx = cb->args[0];
5079         struct nft_obj_filter *filter = cb->data;
5080         struct net *net = sock_net(skb->sk);
5081         int family = nfmsg->nfgen_family;
5082         struct nft_object *obj;
5083         bool reset = false;
5084
5085         if (NFNL_MSG_TYPE(cb->nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5086                 reset = true;
5087
5088         rcu_read_lock();
5089         cb->seq = net->nft.base_seq;
5090
5091         list_for_each_entry_rcu(table, &net->nft.tables, list) {
5092                 if (family != NFPROTO_UNSPEC && family != table->family)
5093                         continue;
5094
5095                 list_for_each_entry_rcu(obj, &table->objects, list) {
5096                         if (!nft_is_active(net, obj))
5097                                 goto cont;
5098                         if (idx < s_idx)
5099                                 goto cont;
5100                         if (idx > s_idx)
5101                                 memset(&cb->args[1], 0,
5102                                        sizeof(cb->args) - sizeof(cb->args[0]));
5103                         if (filter && filter->table &&
5104                             strcmp(filter->table, table->name))
5105                                 goto cont;
5106                         if (filter &&
5107                             filter->type != NFT_OBJECT_UNSPEC &&
5108                             obj->ops->type->type != filter->type)
5109                                 goto cont;
5110
5111                         if (nf_tables_fill_obj_info(skb, net, NETLINK_CB(cb->skb).portid,
5112                                                     cb->nlh->nlmsg_seq,
5113                                                     NFT_MSG_NEWOBJ,
5114                                                     NLM_F_MULTI | NLM_F_APPEND,
5115                                                     table->family, table,
5116                                                     obj, reset) < 0)
5117                                 goto done;
5118
5119                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5120 cont:
5121                         idx++;
5122                 }
5123         }
5124 done:
5125         rcu_read_unlock();
5126
5127         cb->args[0] = idx;
5128         return skb->len;
5129 }
5130
5131 static int nf_tables_dump_obj_start(struct netlink_callback *cb)
5132 {
5133         const struct nlattr * const *nla = cb->data;
5134         struct nft_obj_filter *filter = NULL;
5135
5136         if (nla[NFTA_OBJ_TABLE] || nla[NFTA_OBJ_TYPE]) {
5137                 filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5138                 if (!filter)
5139                         return -ENOMEM;
5140
5141                 if (nla[NFTA_OBJ_TABLE]) {
5142                         filter->table = nla_strdup(nla[NFTA_OBJ_TABLE], GFP_ATOMIC);
5143                         if (!filter->table) {
5144                                 kfree(filter);
5145                                 return -ENOMEM;
5146                         }
5147                 }
5148
5149                 if (nla[NFTA_OBJ_TYPE])
5150                         filter->type = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5151         }
5152
5153         cb->data = filter;
5154         return 0;
5155 }
5156
5157 static int nf_tables_dump_obj_done(struct netlink_callback *cb)
5158 {
5159         struct nft_obj_filter *filter = cb->data;
5160
5161         if (filter) {
5162                 kfree(filter->table);
5163                 kfree(filter);
5164         }
5165
5166         return 0;
5167 }
5168
5169 /* called with rcu_read_lock held */
5170 static int nf_tables_getobj(struct net *net, struct sock *nlsk,
5171                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5172                             const struct nlattr * const nla[],
5173                             struct netlink_ext_ack *extack)
5174 {
5175         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5176         u8 genmask = nft_genmask_cur(net);
5177         int family = nfmsg->nfgen_family;
5178         const struct nft_table *table;
5179         struct nft_object *obj;
5180         struct sk_buff *skb2;
5181         bool reset = false;
5182         u32 objtype;
5183         int err;
5184
5185         if (nlh->nlmsg_flags & NLM_F_DUMP) {
5186                 struct netlink_dump_control c = {
5187                         .start = nf_tables_dump_obj_start,
5188                         .dump = nf_tables_dump_obj,
5189                         .done = nf_tables_dump_obj_done,
5190                         .module = THIS_MODULE,
5191                         .data = (void *)nla,
5192                 };
5193
5194                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
5195         }
5196
5197         if (!nla[NFTA_OBJ_NAME] ||
5198             !nla[NFTA_OBJ_TYPE])
5199                 return -EINVAL;
5200
5201         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5202         if (IS_ERR(table)) {
5203                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5204                 return PTR_ERR(table);
5205         }
5206
5207         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5208         obj = nft_obj_lookup(table, nla[NFTA_OBJ_NAME], objtype, genmask);
5209         if (IS_ERR(obj)) {
5210                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5211                 return PTR_ERR(obj);
5212         }
5213
5214         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
5215         if (!skb2)
5216                 return -ENOMEM;
5217
5218         if (NFNL_MSG_TYPE(nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5219                 reset = true;
5220
5221         err = nf_tables_fill_obj_info(skb2, net, NETLINK_CB(skb).portid,
5222                                       nlh->nlmsg_seq, NFT_MSG_NEWOBJ, 0,
5223                                       family, table, obj, reset);
5224         if (err < 0)
5225                 goto err;
5226
5227         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
5228 err:
5229         kfree_skb(skb2);
5230         return err;
5231 }
5232
5233 static void nft_obj_destroy(const struct nft_ctx *ctx, struct nft_object *obj)
5234 {
5235         if (obj->ops->destroy)
5236                 obj->ops->destroy(ctx, obj);
5237
5238         module_put(obj->ops->type->owner);
5239         kfree(obj->name);
5240         kfree(obj);
5241 }
5242
5243 static int nf_tables_delobj(struct net *net, struct sock *nlsk,
5244                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5245                             const struct nlattr * const nla[],
5246                             struct netlink_ext_ack *extack)
5247 {
5248         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5249         u8 genmask = nft_genmask_next(net);
5250         int family = nfmsg->nfgen_family;
5251         const struct nlattr *attr;
5252         struct nft_table *table;
5253         struct nft_object *obj;
5254         struct nft_ctx ctx;
5255         u32 objtype;
5256
5257         if (!nla[NFTA_OBJ_TYPE] ||
5258             (!nla[NFTA_OBJ_NAME] && !nla[NFTA_OBJ_HANDLE]))
5259                 return -EINVAL;
5260
5261         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5262         if (IS_ERR(table)) {
5263                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5264                 return PTR_ERR(table);
5265         }
5266
5267         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5268         if (nla[NFTA_OBJ_HANDLE]) {
5269                 attr = nla[NFTA_OBJ_HANDLE];
5270                 obj = nft_obj_lookup_byhandle(table, attr, objtype, genmask);
5271         } else {
5272                 attr = nla[NFTA_OBJ_NAME];
5273                 obj = nft_obj_lookup(table, attr, objtype, genmask);
5274         }
5275
5276         if (IS_ERR(obj)) {
5277                 NL_SET_BAD_ATTR(extack, attr);
5278                 return PTR_ERR(obj);
5279         }
5280         if (obj->use > 0) {
5281                 NL_SET_BAD_ATTR(extack, attr);
5282                 return -EBUSY;
5283         }
5284
5285         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5286
5287         return nft_delobj(&ctx, obj);
5288 }
5289
5290 void nft_obj_notify(struct net *net, struct nft_table *table,
5291                     struct nft_object *obj, u32 portid, u32 seq, int event,
5292                     int family, int report, gfp_t gfp)
5293 {
5294         struct sk_buff *skb;
5295         int err;
5296
5297         if (!report &&
5298             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
5299                 return;
5300
5301         skb = nlmsg_new(NLMSG_GOODSIZE, gfp);
5302         if (skb == NULL)
5303                 goto err;
5304
5305         err = nf_tables_fill_obj_info(skb, net, portid, seq, event, 0, family,
5306                                       table, obj, false);
5307         if (err < 0) {
5308                 kfree_skb(skb);
5309                 goto err;
5310         }
5311
5312         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, report, gfp);
5313         return;
5314 err:
5315         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
5316 }
5317 EXPORT_SYMBOL_GPL(nft_obj_notify);
5318
5319 static void nf_tables_obj_notify(const struct nft_ctx *ctx,
5320                                  struct nft_object *obj, int event)
5321 {
5322         nft_obj_notify(ctx->net, ctx->table, obj, ctx->portid, ctx->seq, event,
5323                        ctx->family, ctx->report, GFP_KERNEL);
5324 }
5325
5326 /*
5327  * Flow tables
5328  */
5329 void nft_register_flowtable_type(struct nf_flowtable_type *type)
5330 {
5331         nfnl_lock(NFNL_SUBSYS_NFTABLES);
5332         list_add_tail_rcu(&type->list, &nf_tables_flowtables);
5333         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5334 }
5335 EXPORT_SYMBOL_GPL(nft_register_flowtable_type);
5336
5337 void nft_unregister_flowtable_type(struct nf_flowtable_type *type)
5338 {
5339         nfnl_lock(NFNL_SUBSYS_NFTABLES);
5340         list_del_rcu(&type->list);
5341         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5342 }
5343 EXPORT_SYMBOL_GPL(nft_unregister_flowtable_type);
5344
5345 static const struct nla_policy nft_flowtable_policy[NFTA_FLOWTABLE_MAX + 1] = {
5346         [NFTA_FLOWTABLE_TABLE]          = { .type = NLA_STRING,
5347                                             .len = NFT_NAME_MAXLEN - 1 },
5348         [NFTA_FLOWTABLE_NAME]           = { .type = NLA_STRING,
5349                                             .len = NFT_NAME_MAXLEN - 1 },
5350         [NFTA_FLOWTABLE_HOOK]           = { .type = NLA_NESTED },
5351         [NFTA_FLOWTABLE_HANDLE]         = { .type = NLA_U64 },
5352 };
5353
5354 struct nft_flowtable *nft_flowtable_lookup(const struct nft_table *table,
5355                                            const struct nlattr *nla, u8 genmask)
5356 {
5357         struct nft_flowtable *flowtable;
5358
5359         list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5360                 if (!nla_strcmp(nla, flowtable->name) &&
5361                     nft_active_genmask(flowtable, genmask))
5362                         return flowtable;
5363         }
5364         return ERR_PTR(-ENOENT);
5365 }
5366 EXPORT_SYMBOL_GPL(nft_flowtable_lookup);
5367
5368 static struct nft_flowtable *
5369 nft_flowtable_lookup_byhandle(const struct nft_table *table,
5370                               const struct nlattr *nla, u8 genmask)
5371 {
5372        struct nft_flowtable *flowtable;
5373
5374        list_for_each_entry(flowtable, &table->flowtables, list) {
5375                if (be64_to_cpu(nla_get_be64(nla)) == flowtable->handle &&
5376                    nft_active_genmask(flowtable, genmask))
5377                        return flowtable;
5378        }
5379        return ERR_PTR(-ENOENT);
5380 }
5381
5382 static int nf_tables_parse_devices(const struct nft_ctx *ctx,
5383                                    const struct nlattr *attr,
5384                                    struct net_device *dev_array[], int *len)
5385 {
5386         const struct nlattr *tmp;
5387         struct net_device *dev;
5388         char ifname[IFNAMSIZ];
5389         int rem, n = 0, err;
5390
5391         nla_for_each_nested(tmp, attr, rem) {
5392                 if (nla_type(tmp) != NFTA_DEVICE_NAME) {
5393                         err = -EINVAL;
5394                         goto err1;
5395                 }
5396
5397                 nla_strlcpy(ifname, tmp, IFNAMSIZ);
5398                 dev = __dev_get_by_name(ctx->net, ifname);
5399                 if (!dev) {
5400                         err = -ENOENT;
5401                         goto err1;
5402                 }
5403
5404                 dev_array[n++] = dev;
5405                 if (n == NFT_FLOWTABLE_DEVICE_MAX) {
5406                         err = -EFBIG;
5407                         goto err1;
5408                 }
5409         }
5410         if (!len)
5411                 return -EINVAL;
5412
5413         err = 0;
5414 err1:
5415         *len = n;
5416         return err;
5417 }
5418
5419 static const struct nla_policy nft_flowtable_hook_policy[NFTA_FLOWTABLE_HOOK_MAX + 1] = {
5420         [NFTA_FLOWTABLE_HOOK_NUM]       = { .type = NLA_U32 },
5421         [NFTA_FLOWTABLE_HOOK_PRIORITY]  = { .type = NLA_U32 },
5422         [NFTA_FLOWTABLE_HOOK_DEVS]      = { .type = NLA_NESTED },
5423 };
5424
5425 static int nf_tables_flowtable_parse_hook(const struct nft_ctx *ctx,
5426                                           const struct nlattr *attr,
5427                                           struct nft_flowtable *flowtable)
5428 {
5429         struct net_device *dev_array[NFT_FLOWTABLE_DEVICE_MAX];
5430         struct nlattr *tb[NFTA_FLOWTABLE_HOOK_MAX + 1];
5431         struct nf_hook_ops *ops;
5432         int hooknum, priority;
5433         int err, n = 0, i;
5434
5435         err = nla_parse_nested(tb, NFTA_FLOWTABLE_HOOK_MAX, attr,
5436                                nft_flowtable_hook_policy, NULL);
5437         if (err < 0)
5438                 return err;
5439
5440         if (!tb[NFTA_FLOWTABLE_HOOK_NUM] ||
5441             !tb[NFTA_FLOWTABLE_HOOK_PRIORITY] ||
5442             !tb[NFTA_FLOWTABLE_HOOK_DEVS])
5443                 return -EINVAL;
5444
5445         hooknum = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_NUM]));
5446         if (hooknum != NF_NETDEV_INGRESS)
5447                 return -EINVAL;
5448
5449         priority = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_PRIORITY]));
5450
5451         err = nf_tables_parse_devices(ctx, tb[NFTA_FLOWTABLE_HOOK_DEVS],
5452                                       dev_array, &n);
5453         if (err < 0)
5454                 return err;
5455
5456         ops = kcalloc(n, sizeof(struct nf_hook_ops), GFP_KERNEL);
5457         if (!ops)
5458                 return -ENOMEM;
5459
5460         flowtable->hooknum      = hooknum;
5461         flowtable->priority     = priority;
5462         flowtable->ops          = ops;
5463         flowtable->ops_len      = n;
5464
5465         for (i = 0; i < n; i++) {
5466                 flowtable->ops[i].pf            = NFPROTO_NETDEV;
5467                 flowtable->ops[i].hooknum       = hooknum;
5468                 flowtable->ops[i].priority      = priority;
5469                 flowtable->ops[i].priv          = &flowtable->data;
5470                 flowtable->ops[i].hook          = flowtable->data.type->hook;
5471                 flowtable->ops[i].dev           = dev_array[i];
5472         }
5473
5474         return err;
5475 }
5476
5477 static const struct nf_flowtable_type *__nft_flowtable_type_get(u8 family)
5478 {
5479         const struct nf_flowtable_type *type;
5480
5481         list_for_each_entry(type, &nf_tables_flowtables, list) {
5482                 if (family == type->family)
5483                         return type;
5484         }
5485         return NULL;
5486 }
5487
5488 static const struct nf_flowtable_type *
5489 nft_flowtable_type_get(struct net *net, u8 family)
5490 {
5491         const struct nf_flowtable_type *type;
5492
5493         type = __nft_flowtable_type_get(family);
5494         if (type != NULL && try_module_get(type->owner))
5495                 return type;
5496
5497         lockdep_nfnl_nft_mutex_not_held();
5498 #ifdef CONFIG_MODULES
5499         if (type == NULL) {
5500                 nft_request_module(net, "nf-flowtable-%u", family);
5501                 if (__nft_flowtable_type_get(family))
5502                         return ERR_PTR(-EAGAIN);
5503         }
5504 #endif
5505         return ERR_PTR(-ENOENT);
5506 }
5507
5508 static void nft_unregister_flowtable_net_hooks(struct net *net,
5509                                                struct nft_flowtable *flowtable)
5510 {
5511         int i;
5512
5513         for (i = 0; i < flowtable->ops_len; i++) {
5514                 if (!flowtable->ops[i].dev)
5515                         continue;
5516
5517                 nf_unregister_net_hook(net, &flowtable->ops[i]);
5518         }
5519 }
5520
5521 static int nf_tables_newflowtable(struct net *net, struct sock *nlsk,
5522                                   struct sk_buff *skb,
5523                                   const struct nlmsghdr *nlh,
5524                                   const struct nlattr * const nla[],
5525                                   struct netlink_ext_ack *extack)
5526 {
5527         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5528         const struct nf_flowtable_type *type;
5529         struct nft_flowtable *flowtable, *ft;
5530         u8 genmask = nft_genmask_next(net);
5531         int family = nfmsg->nfgen_family;
5532         struct nft_table *table;
5533         struct nft_ctx ctx;
5534         int err, i, k;
5535
5536         if (!nla[NFTA_FLOWTABLE_TABLE] ||
5537             !nla[NFTA_FLOWTABLE_NAME] ||
5538             !nla[NFTA_FLOWTABLE_HOOK])
5539                 return -EINVAL;
5540
5541         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5542                                  genmask);
5543         if (IS_ERR(table)) {
5544                 NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5545                 return PTR_ERR(table);
5546         }
5547
5548         flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
5549                                          genmask);
5550         if (IS_ERR(flowtable)) {
5551                 err = PTR_ERR(flowtable);
5552                 if (err != -ENOENT) {
5553                         NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5554                         return err;
5555                 }
5556         } else {
5557                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
5558                         NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5559                         return -EEXIST;
5560                 }
5561
5562                 return 0;
5563         }
5564
5565         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5566
5567         flowtable = kzalloc(sizeof(*flowtable), GFP_KERNEL);
5568         if (!flowtable)
5569                 return -ENOMEM;
5570
5571         flowtable->table = table;
5572         flowtable->handle = nf_tables_alloc_handle(table);
5573
5574         flowtable->name = nla_strdup(nla[NFTA_FLOWTABLE_NAME], GFP_KERNEL);
5575         if (!flowtable->name) {
5576                 err = -ENOMEM;
5577                 goto err1;
5578         }
5579
5580         type = nft_flowtable_type_get(net, family);
5581         if (IS_ERR(type)) {
5582                 err = PTR_ERR(type);
5583                 goto err2;
5584         }
5585
5586         flowtable->data.type = type;
5587         err = type->init(&flowtable->data);
5588         if (err < 0)
5589                 goto err3;
5590
5591         err = nf_tables_flowtable_parse_hook(&ctx, nla[NFTA_FLOWTABLE_HOOK],
5592                                              flowtable);
5593         if (err < 0)
5594                 goto err4;
5595
5596         for (i = 0; i < flowtable->ops_len; i++) {
5597                 if (!flowtable->ops[i].dev)
5598                         continue;
5599
5600                 list_for_each_entry(ft, &table->flowtables, list) {
5601                         for (k = 0; k < ft->ops_len; k++) {
5602                                 if (!ft->ops[k].dev)
5603                                         continue;
5604
5605                                 if (flowtable->ops[i].dev == ft->ops[k].dev &&
5606                                     flowtable->ops[i].pf == ft->ops[k].pf) {
5607                                         err = -EBUSY;
5608                                         goto err5;
5609                                 }
5610                         }
5611                 }
5612
5613                 err = nf_register_net_hook(net, &flowtable->ops[i]);
5614                 if (err < 0)
5615                         goto err5;
5616         }
5617
5618         err = nft_trans_flowtable_add(&ctx, NFT_MSG_NEWFLOWTABLE, flowtable);
5619         if (err < 0)
5620                 goto err6;
5621
5622         list_add_tail_rcu(&flowtable->list, &table->flowtables);
5623         table->use++;
5624
5625         return 0;
5626 err6:
5627         i = flowtable->ops_len;
5628 err5:
5629         for (k = i - 1; k >= 0; k--)
5630                 nf_unregister_net_hook(net, &flowtable->ops[k]);
5631
5632         kfree(flowtable->ops);
5633 err4:
5634         flowtable->data.type->free(&flowtable->data);
5635 err3:
5636         module_put(type->owner);
5637 err2:
5638         kfree(flowtable->name);
5639 err1:
5640         kfree(flowtable);
5641         return err;
5642 }
5643
5644 static int nf_tables_delflowtable(struct net *net, struct sock *nlsk,
5645                                   struct sk_buff *skb,
5646                                   const struct nlmsghdr *nlh,
5647                                   const struct nlattr * const nla[],
5648                                   struct netlink_ext_ack *extack)
5649 {
5650         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5651         u8 genmask = nft_genmask_next(net);
5652         int family = nfmsg->nfgen_family;
5653         struct nft_flowtable *flowtable;
5654         const struct nlattr *attr;
5655         struct nft_table *table;
5656         struct nft_ctx ctx;
5657
5658         if (!nla[NFTA_FLOWTABLE_TABLE] ||
5659             (!nla[NFTA_FLOWTABLE_NAME] &&
5660              !nla[NFTA_FLOWTABLE_HANDLE]))
5661                 return -EINVAL;
5662
5663         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5664                                  genmask);
5665         if (IS_ERR(table)) {
5666                 NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5667                 return PTR_ERR(table);
5668         }
5669
5670         if (nla[NFTA_FLOWTABLE_HANDLE]) {
5671                 attr = nla[NFTA_FLOWTABLE_HANDLE];
5672                 flowtable = nft_flowtable_lookup_byhandle(table, attr, genmask);
5673         } else {
5674                 attr = nla[NFTA_FLOWTABLE_NAME];
5675                 flowtable = nft_flowtable_lookup(table, attr, genmask);
5676         }
5677
5678         if (IS_ERR(flowtable)) {
5679                 NL_SET_BAD_ATTR(extack, attr);
5680                 return PTR_ERR(flowtable);
5681         }
5682         if (flowtable->use > 0) {
5683                 NL_SET_BAD_ATTR(extack, attr);
5684                 return -EBUSY;
5685         }
5686
5687         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5688
5689         return nft_delflowtable(&ctx, flowtable);
5690 }
5691
5692 static int nf_tables_fill_flowtable_info(struct sk_buff *skb, struct net *net,
5693                                          u32 portid, u32 seq, int event,
5694                                          u32 flags, int family,
5695                                          struct nft_flowtable *flowtable)
5696 {
5697         struct nlattr *nest, *nest_devs;
5698         struct nfgenmsg *nfmsg;
5699         struct nlmsghdr *nlh;
5700         int i;
5701
5702         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5703         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5704         if (nlh == NULL)
5705                 goto nla_put_failure;
5706
5707         nfmsg = nlmsg_data(nlh);
5708         nfmsg->nfgen_family     = family;
5709         nfmsg->version          = NFNETLINK_V0;
5710         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5711
5712         if (nla_put_string(skb, NFTA_FLOWTABLE_TABLE, flowtable->table->name) ||
5713             nla_put_string(skb, NFTA_FLOWTABLE_NAME, flowtable->name) ||
5714             nla_put_be32(skb, NFTA_FLOWTABLE_USE, htonl(flowtable->use)) ||
5715             nla_put_be64(skb, NFTA_FLOWTABLE_HANDLE, cpu_to_be64(flowtable->handle),
5716                          NFTA_FLOWTABLE_PAD))
5717                 goto nla_put_failure;
5718
5719         nest = nla_nest_start(skb, NFTA_FLOWTABLE_HOOK);
5720         if (!nest)
5721                 goto nla_put_failure;
5722         if (nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_NUM, htonl(flowtable->hooknum)) ||
5723             nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_PRIORITY, htonl(flowtable->priority)))
5724                 goto nla_put_failure;
5725
5726         nest_devs = nla_nest_start(skb, NFTA_FLOWTABLE_HOOK_DEVS);
5727         if (!nest_devs)
5728                 goto nla_put_failure;
5729
5730         for (i = 0; i < flowtable->ops_len; i++) {
5731                 const struct net_device *dev = READ_ONCE(flowtable->ops[i].dev);
5732
5733                 if (dev &&
5734                     nla_put_string(skb, NFTA_DEVICE_NAME, dev->name))
5735                         goto nla_put_failure;
5736         }
5737         nla_nest_end(skb, nest_devs);
5738         nla_nest_end(skb, nest);
5739
5740         nlmsg_end(skb, nlh);
5741         return 0;
5742
5743 nla_put_failure:
5744         nlmsg_trim(skb, nlh);
5745         return -1;
5746 }
5747
5748 struct nft_flowtable_filter {
5749         char            *table;
5750 };
5751
5752 static int nf_tables_dump_flowtable(struct sk_buff *skb,
5753                                     struct netlink_callback *cb)
5754 {
5755         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5756         struct nft_flowtable_filter *filter = cb->data;
5757         unsigned int idx = 0, s_idx = cb->args[0];
5758         struct net *net = sock_net(skb->sk);
5759         int family = nfmsg->nfgen_family;
5760         struct nft_flowtable *flowtable;
5761         const struct nft_table *table;
5762
5763         rcu_read_lock();
5764         cb->seq = net->nft.base_seq;
5765
5766         list_for_each_entry_rcu(table, &net->nft.tables, list) {
5767                 if (family != NFPROTO_UNSPEC && family != table->family)
5768                         continue;
5769
5770                 list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5771                         if (!nft_is_active(net, flowtable))
5772                                 goto cont;
5773                         if (idx < s_idx)
5774                                 goto cont;
5775                         if (idx > s_idx)
5776                                 memset(&cb->args[1], 0,
5777                                        sizeof(cb->args) - sizeof(cb->args[0]));
5778                         if (filter && filter->table &&
5779                             strcmp(filter->table, table->name))
5780                                 goto cont;
5781
5782                         if (nf_tables_fill_flowtable_info(skb, net, NETLINK_CB(cb->skb).portid,
5783                                                           cb->nlh->nlmsg_seq,
5784                                                           NFT_MSG_NEWFLOWTABLE,
5785                                                           NLM_F_MULTI | NLM_F_APPEND,
5786                                                           table->family, flowtable) < 0)
5787                                 goto done;
5788
5789                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5790 cont:
5791                         idx++;
5792                 }
5793         }
5794 done:
5795         rcu_read_unlock();
5796
5797         cb->args[0] = idx;
5798         return skb->len;
5799 }
5800
5801 static int nf_tables_dump_flowtable_start(struct netlink_callback *cb)
5802 {
5803         const struct nlattr * const *nla = cb->data;
5804         struct nft_flowtable_filter *filter = NULL;
5805
5806         if (nla[NFTA_FLOWTABLE_TABLE]) {
5807                 filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5808                 if (!filter)
5809                         return -ENOMEM;
5810
5811                 filter->table = nla_strdup(nla[NFTA_FLOWTABLE_TABLE],
5812                                            GFP_ATOMIC);
5813                 if (!filter->table) {
5814                         kfree(filter);
5815                         return -ENOMEM;
5816                 }
5817         }
5818
5819         cb->data = filter;
5820         return 0;
5821 }
5822
5823 static int nf_tables_dump_flowtable_done(struct netlink_callback *cb)
5824 {
5825         struct nft_flowtable_filter *filter = cb->data;
5826
5827         if (!filter)
5828                 return 0;
5829
5830         kfree(filter->table);
5831         kfree(filter);
5832
5833         return 0;
5834 }
5835
5836 /* called with rcu_read_lock held */
5837 static int nf_tables_getflowtable(struct net *net, struct sock *nlsk,
5838                                   struct sk_buff *skb,
5839                                   const struct nlmsghdr *nlh,
5840                                   const struct nlattr * const nla[],
5841                                   struct netlink_ext_ack *extack)
5842 {
5843         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5844         u8 genmask = nft_genmask_cur(net);
5845         int family = nfmsg->nfgen_family;
5846         struct nft_flowtable *flowtable;
5847         const struct nft_table *table;
5848         struct sk_buff *skb2;
5849         int err;
5850
5851         if (nlh->nlmsg_flags & NLM_F_DUMP) {
5852                 struct netlink_dump_control c = {
5853                         .start = nf_tables_dump_flowtable_start,
5854                         .dump = nf_tables_dump_flowtable,
5855                         .done = nf_tables_dump_flowtable_done,
5856                         .module = THIS_MODULE,
5857                         .data = (void *)nla,
5858                 };
5859
5860                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
5861         }
5862
5863         if (!nla[NFTA_FLOWTABLE_NAME])
5864                 return -EINVAL;
5865
5866         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5867                                  genmask);
5868         if (IS_ERR(table))
5869                 return PTR_ERR(table);
5870
5871         flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
5872                                          genmask);
5873         if (IS_ERR(flowtable))
5874                 return PTR_ERR(flowtable);
5875
5876         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
5877         if (!skb2)
5878                 return -ENOMEM;
5879
5880         err = nf_tables_fill_flowtable_info(skb2, net, NETLINK_CB(skb).portid,
5881                                             nlh->nlmsg_seq,
5882                                             NFT_MSG_NEWFLOWTABLE, 0, family,
5883                                             flowtable);
5884         if (err < 0)
5885                 goto err;
5886
5887         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
5888 err:
5889         kfree_skb(skb2);
5890         return err;
5891 }
5892
5893 static void nf_tables_flowtable_notify(struct nft_ctx *ctx,
5894                                        struct nft_flowtable *flowtable,
5895                                        int event)
5896 {
5897         struct sk_buff *skb;
5898         int err;
5899
5900         if (ctx->report &&
5901             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
5902                 return;
5903
5904         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
5905         if (skb == NULL)
5906                 goto err;
5907
5908         err = nf_tables_fill_flowtable_info(skb, ctx->net, ctx->portid,
5909                                             ctx->seq, event, 0,
5910                                             ctx->family, flowtable);
5911         if (err < 0) {
5912                 kfree_skb(skb);
5913                 goto err;
5914         }
5915
5916         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
5917                        ctx->report, GFP_KERNEL);
5918         return;
5919 err:
5920         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
5921 }
5922
5923 static void nf_tables_flowtable_destroy(struct nft_flowtable *flowtable)
5924 {
5925         kfree(flowtable->ops);
5926         kfree(flowtable->name);
5927         flowtable->data.type->free(&flowtable->data);
5928         module_put(flowtable->data.type->owner);
5929         kfree(flowtable);
5930 }
5931
5932 static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net,
5933                                    u32 portid, u32 seq)
5934 {
5935         struct nlmsghdr *nlh;
5936         struct nfgenmsg *nfmsg;
5937         char buf[TASK_COMM_LEN];
5938         int event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWGEN);
5939
5940         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), 0);
5941         if (nlh == NULL)
5942                 goto nla_put_failure;
5943
5944         nfmsg = nlmsg_data(nlh);
5945         nfmsg->nfgen_family     = AF_UNSPEC;
5946         nfmsg->version          = NFNETLINK_V0;
5947         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5948
5949         if (nla_put_be32(skb, NFTA_GEN_ID, htonl(net->nft.base_seq)) ||
5950             nla_put_be32(skb, NFTA_GEN_PROC_PID, htonl(task_pid_nr(current))) ||
5951             nla_put_string(skb, NFTA_GEN_PROC_NAME, get_task_comm(buf, current)))
5952                 goto nla_put_failure;
5953
5954         nlmsg_end(skb, nlh);
5955         return 0;
5956
5957 nla_put_failure:
5958         nlmsg_trim(skb, nlh);
5959         return -EMSGSIZE;
5960 }
5961
5962 static void nft_flowtable_event(unsigned long event, struct net_device *dev,
5963                                 struct nft_flowtable *flowtable)
5964 {
5965         int i;
5966
5967         for (i = 0; i < flowtable->ops_len; i++) {
5968                 if (flowtable->ops[i].dev != dev)
5969                         continue;
5970
5971                 nf_unregister_net_hook(dev_net(dev), &flowtable->ops[i]);
5972                 flowtable->ops[i].dev = NULL;
5973                 break;
5974         }
5975 }
5976
5977 static int nf_tables_flowtable_event(struct notifier_block *this,
5978                                      unsigned long event, void *ptr)
5979 {
5980         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
5981         struct nft_flowtable *flowtable;
5982         struct nft_table *table;
5983         struct net *net;
5984
5985         if (event != NETDEV_UNREGISTER)
5986                 return 0;
5987
5988         net = dev_net(dev);
5989         mutex_lock(&net->nft.commit_mutex);
5990         list_for_each_entry(table, &net->nft.tables, list) {
5991                 list_for_each_entry(flowtable, &table->flowtables, list) {
5992                         nft_flowtable_event(event, dev, flowtable);
5993                 }
5994         }
5995         mutex_unlock(&net->nft.commit_mutex);
5996
5997         return NOTIFY_DONE;
5998 }
5999
6000 static struct notifier_block nf_tables_flowtable_notifier = {
6001         .notifier_call  = nf_tables_flowtable_event,
6002 };
6003
6004 static void nf_tables_gen_notify(struct net *net, struct sk_buff *skb,
6005                                  int event)
6006 {
6007         struct nlmsghdr *nlh = nlmsg_hdr(skb);
6008         struct sk_buff *skb2;
6009         int err;
6010
6011         if (nlmsg_report(nlh) &&
6012             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
6013                 return;
6014
6015         skb2 = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
6016         if (skb2 == NULL)
6017                 goto err;
6018
6019         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6020                                       nlh->nlmsg_seq);
6021         if (err < 0) {
6022                 kfree_skb(skb2);
6023                 goto err;
6024         }
6025
6026         nfnetlink_send(skb2, net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6027                        nlmsg_report(nlh), GFP_KERNEL);
6028         return;
6029 err:
6030         nfnetlink_set_err(net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6031                           -ENOBUFS);
6032 }
6033
6034 static int nf_tables_getgen(struct net *net, struct sock *nlsk,
6035                             struct sk_buff *skb, const struct nlmsghdr *nlh,
6036                             const struct nlattr * const nla[],
6037                             struct netlink_ext_ack *extack)
6038 {
6039         struct sk_buff *skb2;
6040         int err;
6041
6042         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
6043         if (skb2 == NULL)
6044                 return -ENOMEM;
6045
6046         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6047                                       nlh->nlmsg_seq);
6048         if (err < 0)
6049                 goto err;
6050
6051         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
6052 err:
6053         kfree_skb(skb2);
6054         return err;
6055 }
6056
6057 static const struct nfnl_callback nf_tables_cb[NFT_MSG_MAX] = {
6058         [NFT_MSG_NEWTABLE] = {
6059                 .call_batch     = nf_tables_newtable,
6060                 .attr_count     = NFTA_TABLE_MAX,
6061                 .policy         = nft_table_policy,
6062         },
6063         [NFT_MSG_GETTABLE] = {
6064                 .call_rcu       = nf_tables_gettable,
6065                 .attr_count     = NFTA_TABLE_MAX,
6066                 .policy         = nft_table_policy,
6067         },
6068         [NFT_MSG_DELTABLE] = {
6069                 .call_batch     = nf_tables_deltable,
6070                 .attr_count     = NFTA_TABLE_MAX,
6071                 .policy         = nft_table_policy,
6072         },
6073         [NFT_MSG_NEWCHAIN] = {
6074                 .call_batch     = nf_tables_newchain,
6075                 .attr_count     = NFTA_CHAIN_MAX,
6076                 .policy         = nft_chain_policy,
6077         },
6078         [NFT_MSG_GETCHAIN] = {
6079                 .call_rcu       = nf_tables_getchain,
6080                 .attr_count     = NFTA_CHAIN_MAX,
6081                 .policy         = nft_chain_policy,
6082         },
6083         [NFT_MSG_DELCHAIN] = {
6084                 .call_batch     = nf_tables_delchain,
6085                 .attr_count     = NFTA_CHAIN_MAX,
6086                 .policy         = nft_chain_policy,
6087         },
6088         [NFT_MSG_NEWRULE] = {
6089                 .call_batch     = nf_tables_newrule,
6090                 .attr_count     = NFTA_RULE_MAX,
6091                 .policy         = nft_rule_policy,
6092         },
6093         [NFT_MSG_GETRULE] = {
6094                 .call_rcu       = nf_tables_getrule,
6095                 .attr_count     = NFTA_RULE_MAX,
6096                 .policy         = nft_rule_policy,
6097         },
6098         [NFT_MSG_DELRULE] = {
6099                 .call_batch     = nf_tables_delrule,
6100                 .attr_count     = NFTA_RULE_MAX,
6101                 .policy         = nft_rule_policy,
6102         },
6103         [NFT_MSG_NEWSET] = {
6104                 .call_batch     = nf_tables_newset,
6105                 .attr_count     = NFTA_SET_MAX,
6106                 .policy         = nft_set_policy,
6107         },
6108         [NFT_MSG_GETSET] = {
6109                 .call_rcu       = nf_tables_getset,
6110                 .attr_count     = NFTA_SET_MAX,
6111                 .policy         = nft_set_policy,
6112         },
6113         [NFT_MSG_DELSET] = {
6114                 .call_batch     = nf_tables_delset,
6115                 .attr_count     = NFTA_SET_MAX,
6116                 .policy         = nft_set_policy,
6117         },
6118         [NFT_MSG_NEWSETELEM] = {
6119                 .call_batch     = nf_tables_newsetelem,
6120                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6121                 .policy         = nft_set_elem_list_policy,
6122         },
6123         [NFT_MSG_GETSETELEM] = {
6124                 .call_rcu       = nf_tables_getsetelem,
6125                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6126                 .policy         = nft_set_elem_list_policy,
6127         },
6128         [NFT_MSG_DELSETELEM] = {
6129                 .call_batch     = nf_tables_delsetelem,
6130                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6131                 .policy         = nft_set_elem_list_policy,
6132         },
6133         [NFT_MSG_GETGEN] = {
6134                 .call_rcu       = nf_tables_getgen,
6135         },
6136         [NFT_MSG_NEWOBJ] = {
6137                 .call_batch     = nf_tables_newobj,
6138                 .attr_count     = NFTA_OBJ_MAX,
6139                 .policy         = nft_obj_policy,
6140         },
6141         [NFT_MSG_GETOBJ] = {
6142                 .call_rcu       = nf_tables_getobj,
6143                 .attr_count     = NFTA_OBJ_MAX,
6144                 .policy         = nft_obj_policy,
6145         },
6146         [NFT_MSG_DELOBJ] = {
6147                 .call_batch     = nf_tables_delobj,
6148                 .attr_count     = NFTA_OBJ_MAX,
6149                 .policy         = nft_obj_policy,
6150         },
6151         [NFT_MSG_GETOBJ_RESET] = {
6152                 .call_rcu       = nf_tables_getobj,
6153                 .attr_count     = NFTA_OBJ_MAX,
6154                 .policy         = nft_obj_policy,
6155         },
6156         [NFT_MSG_NEWFLOWTABLE] = {
6157                 .call_batch     = nf_tables_newflowtable,
6158                 .attr_count     = NFTA_FLOWTABLE_MAX,
6159                 .policy         = nft_flowtable_policy,
6160         },
6161         [NFT_MSG_GETFLOWTABLE] = {
6162                 .call_rcu       = nf_tables_getflowtable,
6163                 .attr_count     = NFTA_FLOWTABLE_MAX,
6164                 .policy         = nft_flowtable_policy,
6165         },
6166         [NFT_MSG_DELFLOWTABLE] = {
6167                 .call_batch     = nf_tables_delflowtable,
6168                 .attr_count     = NFTA_FLOWTABLE_MAX,
6169                 .policy         = nft_flowtable_policy,
6170         },
6171 };
6172
6173 static int nf_tables_validate(struct net *net)
6174 {
6175         struct nft_table *table;
6176
6177         switch (net->nft.validate_state) {
6178         case NFT_VALIDATE_SKIP:
6179                 break;
6180         case NFT_VALIDATE_NEED:
6181                 nft_validate_state_update(net, NFT_VALIDATE_DO);
6182                 /* fall through */
6183         case NFT_VALIDATE_DO:
6184                 list_for_each_entry(table, &net->nft.tables, list) {
6185                         if (nft_table_validate(net, table) < 0)
6186                                 return -EAGAIN;
6187                 }
6188                 break;
6189         }
6190
6191         return 0;
6192 }
6193
6194 static void nft_chain_commit_update(struct nft_trans *trans)
6195 {
6196         struct nft_base_chain *basechain;
6197
6198         if (nft_trans_chain_name(trans)) {
6199                 rhltable_remove(&trans->ctx.table->chains_ht,
6200                                 &trans->ctx.chain->rhlhead,
6201                                 nft_chain_ht_params);
6202                 swap(trans->ctx.chain->name, nft_trans_chain_name(trans));
6203                 rhltable_insert_key(&trans->ctx.table->chains_ht,
6204                                     trans->ctx.chain->name,
6205                                     &trans->ctx.chain->rhlhead,
6206                                     nft_chain_ht_params);
6207         }
6208
6209         if (!nft_is_base_chain(trans->ctx.chain))
6210                 return;
6211
6212         basechain = nft_base_chain(trans->ctx.chain);
6213         nft_chain_stats_replace(trans->ctx.net, basechain,
6214                                 nft_trans_chain_stats(trans));
6215
6216         switch (nft_trans_chain_policy(trans)) {
6217         case NF_DROP:
6218         case NF_ACCEPT:
6219                 basechain->policy = nft_trans_chain_policy(trans);
6220                 break;
6221         }
6222 }
6223
6224 static void nft_commit_release(struct nft_trans *trans)
6225 {
6226         switch (trans->msg_type) {
6227         case NFT_MSG_DELTABLE:
6228                 nf_tables_table_destroy(&trans->ctx);
6229                 break;
6230         case NFT_MSG_NEWCHAIN:
6231                 kfree(nft_trans_chain_name(trans));
6232                 break;
6233         case NFT_MSG_DELCHAIN:
6234                 nf_tables_chain_destroy(&trans->ctx);
6235                 break;
6236         case NFT_MSG_DELRULE:
6237                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6238                 break;
6239         case NFT_MSG_DELSET:
6240                 nft_set_destroy(nft_trans_set(trans));
6241                 break;
6242         case NFT_MSG_DELSETELEM:
6243                 nf_tables_set_elem_destroy(&trans->ctx,
6244                                            nft_trans_elem_set(trans),
6245                                            nft_trans_elem(trans).priv);
6246                 break;
6247         case NFT_MSG_DELOBJ:
6248                 nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6249                 break;
6250         case NFT_MSG_DELFLOWTABLE:
6251                 nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6252                 break;
6253         }
6254
6255         if (trans->put_net)
6256                 put_net(trans->ctx.net);
6257
6258         kfree(trans);
6259 }
6260
6261 static void nf_tables_trans_destroy_work(struct work_struct *w)
6262 {
6263         struct nft_trans *trans, *next;
6264         LIST_HEAD(head);
6265
6266         spin_lock(&nf_tables_destroy_list_lock);
6267         list_splice_init(&nf_tables_destroy_list, &head);
6268         spin_unlock(&nf_tables_destroy_list_lock);
6269
6270         if (list_empty(&head))
6271                 return;
6272
6273         synchronize_rcu();
6274
6275         list_for_each_entry_safe(trans, next, &head, list) {
6276                 list_del(&trans->list);
6277                 nft_commit_release(trans);
6278         }
6279 }
6280
6281 static int nf_tables_commit_chain_prepare(struct net *net, struct nft_chain *chain)
6282 {
6283         struct nft_rule *rule;
6284         unsigned int alloc = 0;
6285         int i;
6286
6287         /* already handled or inactive chain? */
6288         if (chain->rules_next || !nft_is_active_next(net, chain))
6289                 return 0;
6290
6291         rule = list_entry(&chain->rules, struct nft_rule, list);
6292         i = 0;
6293
6294         list_for_each_entry_continue(rule, &chain->rules, list) {
6295                 if (nft_is_active_next(net, rule))
6296                         alloc++;
6297         }
6298
6299         chain->rules_next = nf_tables_chain_alloc_rules(chain, alloc);
6300         if (!chain->rules_next)
6301                 return -ENOMEM;
6302
6303         list_for_each_entry_continue(rule, &chain->rules, list) {
6304                 if (nft_is_active_next(net, rule))
6305                         chain->rules_next[i++] = rule;
6306         }
6307
6308         chain->rules_next[i] = NULL;
6309         return 0;
6310 }
6311
6312 static void nf_tables_commit_chain_prepare_cancel(struct net *net)
6313 {
6314         struct nft_trans *trans, *next;
6315
6316         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6317                 struct nft_chain *chain = trans->ctx.chain;
6318
6319                 if (trans->msg_type == NFT_MSG_NEWRULE ||
6320                     trans->msg_type == NFT_MSG_DELRULE) {
6321                         kvfree(chain->rules_next);
6322                         chain->rules_next = NULL;
6323                 }
6324         }
6325 }
6326
6327 static void __nf_tables_commit_chain_free_rules_old(struct rcu_head *h)
6328 {
6329         struct nft_rules_old *o = container_of(h, struct nft_rules_old, h);
6330
6331         kvfree(o->start);
6332 }
6333
6334 static void nf_tables_commit_chain_free_rules_old(struct nft_rule **rules)
6335 {
6336         struct nft_rule **r = rules;
6337         struct nft_rules_old *old;
6338
6339         while (*r)
6340                 r++;
6341
6342         r++;    /* rcu_head is after end marker */
6343         old = (void *) r;
6344         old->start = rules;
6345
6346         call_rcu(&old->h, __nf_tables_commit_chain_free_rules_old);
6347 }
6348
6349 static void nf_tables_commit_chain(struct net *net, struct nft_chain *chain)
6350 {
6351         struct nft_rule **g0, **g1;
6352         bool next_genbit;
6353
6354         next_genbit = nft_gencursor_next(net);
6355
6356         g0 = rcu_dereference_protected(chain->rules_gen_0,
6357                                        lockdep_commit_lock_is_held(net));
6358         g1 = rcu_dereference_protected(chain->rules_gen_1,
6359                                        lockdep_commit_lock_is_held(net));
6360
6361         /* No changes to this chain? */
6362         if (chain->rules_next == NULL) {
6363                 /* chain had no change in last or next generation */
6364                 if (g0 == g1)
6365                         return;
6366                 /*
6367                  * chain had no change in this generation; make sure next
6368                  * one uses same rules as current generation.
6369                  */
6370                 if (next_genbit) {
6371                         rcu_assign_pointer(chain->rules_gen_1, g0);
6372                         nf_tables_commit_chain_free_rules_old(g1);
6373                 } else {
6374                         rcu_assign_pointer(chain->rules_gen_0, g1);
6375                         nf_tables_commit_chain_free_rules_old(g0);
6376                 }
6377
6378                 return;
6379         }
6380
6381         if (next_genbit)
6382                 rcu_assign_pointer(chain->rules_gen_1, chain->rules_next);
6383         else
6384                 rcu_assign_pointer(chain->rules_gen_0, chain->rules_next);
6385
6386         chain->rules_next = NULL;
6387
6388         if (g0 == g1)
6389                 return;
6390
6391         if (next_genbit)
6392                 nf_tables_commit_chain_free_rules_old(g1);
6393         else
6394                 nf_tables_commit_chain_free_rules_old(g0);
6395 }
6396
6397 static void nft_chain_del(struct nft_chain *chain)
6398 {
6399         struct nft_table *table = chain->table;
6400
6401         WARN_ON_ONCE(rhltable_remove(&table->chains_ht, &chain->rhlhead,
6402                                      nft_chain_ht_params));
6403         list_del_rcu(&chain->list);
6404 }
6405
6406 static void nf_tables_commit_release(struct net *net)
6407 {
6408         struct nft_trans *trans;
6409
6410         /* all side effects have to be made visible.
6411          * For example, if a chain named 'foo' has been deleted, a
6412          * new transaction must not find it anymore.
6413          *
6414          * Memory reclaim happens asynchronously from work queue
6415          * to prevent expensive synchronize_rcu() in commit phase.
6416          */
6417         if (list_empty(&net->nft.commit_list)) {
6418                 mutex_unlock(&net->nft.commit_mutex);
6419                 return;
6420         }
6421
6422         trans = list_last_entry(&net->nft.commit_list,
6423                                 struct nft_trans, list);
6424         get_net(trans->ctx.net);
6425         WARN_ON_ONCE(trans->put_net);
6426
6427         trans->put_net = true;
6428         spin_lock(&nf_tables_destroy_list_lock);
6429         list_splice_tail_init(&net->nft.commit_list, &nf_tables_destroy_list);
6430         spin_unlock(&nf_tables_destroy_list_lock);
6431
6432         mutex_unlock(&net->nft.commit_mutex);
6433
6434         schedule_work(&trans_destroy_work);
6435 }
6436
6437 static int nf_tables_commit(struct net *net, struct sk_buff *skb)
6438 {
6439         struct nft_trans *trans, *next;
6440         struct nft_trans_elem *te;
6441         struct nft_chain *chain;
6442         struct nft_table *table;
6443
6444         /* 0. Validate ruleset, otherwise roll back for error reporting. */
6445         if (nf_tables_validate(net) < 0)
6446                 return -EAGAIN;
6447
6448         /* 1.  Allocate space for next generation rules_gen_X[] */
6449         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6450                 int ret;
6451
6452                 if (trans->msg_type == NFT_MSG_NEWRULE ||
6453                     trans->msg_type == NFT_MSG_DELRULE) {
6454                         chain = trans->ctx.chain;
6455
6456                         ret = nf_tables_commit_chain_prepare(net, chain);
6457                         if (ret < 0) {
6458                                 nf_tables_commit_chain_prepare_cancel(net);
6459                                 return ret;
6460                         }
6461                 }
6462         }
6463
6464         /* step 2.  Make rules_gen_X visible to packet path */
6465         list_for_each_entry(table, &net->nft.tables, list) {
6466                 list_for_each_entry(chain, &table->chains, list)
6467                         nf_tables_commit_chain(net, chain);
6468         }
6469
6470         /*
6471          * Bump generation counter, invalidate any dump in progress.
6472          * Cannot fail after this point.
6473          */
6474         while (++net->nft.base_seq == 0);
6475
6476         /* step 3. Start new generation, rules_gen_X now in use. */
6477         net->nft.gencursor = nft_gencursor_next(net);
6478
6479         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6480                 switch (trans->msg_type) {
6481                 case NFT_MSG_NEWTABLE:
6482                         if (nft_trans_table_update(trans)) {
6483                                 if (!nft_trans_table_enable(trans)) {
6484                                         nf_tables_table_disable(net,
6485                                                                 trans->ctx.table);
6486                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6487                                 }
6488                         } else {
6489                                 nft_clear(net, trans->ctx.table);
6490                         }
6491                         nf_tables_table_notify(&trans->ctx, NFT_MSG_NEWTABLE);
6492                         nft_trans_destroy(trans);
6493                         break;
6494                 case NFT_MSG_DELTABLE:
6495                         list_del_rcu(&trans->ctx.table->list);
6496                         nf_tables_table_notify(&trans->ctx, NFT_MSG_DELTABLE);
6497                         break;
6498                 case NFT_MSG_NEWCHAIN:
6499                         if (nft_trans_chain_update(trans)) {
6500                                 nft_chain_commit_update(trans);
6501                                 nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6502                                 /* trans destroyed after rcu grace period */
6503                         } else {
6504                                 nft_clear(net, trans->ctx.chain);
6505                                 nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6506                                 nft_trans_destroy(trans);
6507                         }
6508                         break;
6509                 case NFT_MSG_DELCHAIN:
6510                         nft_chain_del(trans->ctx.chain);
6511                         nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN);
6512                         nf_tables_unregister_hook(trans->ctx.net,
6513                                                   trans->ctx.table,
6514                                                   trans->ctx.chain);
6515                         break;
6516                 case NFT_MSG_NEWRULE:
6517                         nft_clear(trans->ctx.net, nft_trans_rule(trans));
6518                         nf_tables_rule_notify(&trans->ctx,
6519                                               nft_trans_rule(trans),
6520                                               NFT_MSG_NEWRULE);
6521                         nft_trans_destroy(trans);
6522                         break;
6523                 case NFT_MSG_DELRULE:
6524                         list_del_rcu(&nft_trans_rule(trans)->list);
6525                         nf_tables_rule_notify(&trans->ctx,
6526                                               nft_trans_rule(trans),
6527                                               NFT_MSG_DELRULE);
6528                         nft_rule_expr_deactivate(&trans->ctx,
6529                                                  nft_trans_rule(trans),
6530                                                  NFT_TRANS_COMMIT);
6531                         break;
6532                 case NFT_MSG_NEWSET:
6533                         nft_clear(net, nft_trans_set(trans));
6534                         /* This avoids hitting -EBUSY when deleting the table
6535                          * from the transaction.
6536                          */
6537                         if (nft_set_is_anonymous(nft_trans_set(trans)) &&
6538                             !list_empty(&nft_trans_set(trans)->bindings))
6539                                 trans->ctx.table->use--;
6540
6541                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6542                                              NFT_MSG_NEWSET, GFP_KERNEL);
6543                         nft_trans_destroy(trans);
6544                         break;
6545                 case NFT_MSG_DELSET:
6546                         list_del_rcu(&nft_trans_set(trans)->list);
6547                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6548                                              NFT_MSG_DELSET, GFP_KERNEL);
6549                         break;
6550                 case NFT_MSG_NEWSETELEM:
6551                         te = (struct nft_trans_elem *)trans->data;
6552
6553                         te->set->ops->activate(net, te->set, &te->elem);
6554                         nf_tables_setelem_notify(&trans->ctx, te->set,
6555                                                  &te->elem,
6556                                                  NFT_MSG_NEWSETELEM, 0);
6557                         nft_trans_destroy(trans);
6558                         break;
6559                 case NFT_MSG_DELSETELEM:
6560                         te = (struct nft_trans_elem *)trans->data;
6561
6562                         nf_tables_setelem_notify(&trans->ctx, te->set,
6563                                                  &te->elem,
6564                                                  NFT_MSG_DELSETELEM, 0);
6565                         te->set->ops->remove(net, te->set, &te->elem);
6566                         atomic_dec(&te->set->nelems);
6567                         te->set->ndeact--;
6568                         break;
6569                 case NFT_MSG_NEWOBJ:
6570                         nft_clear(net, nft_trans_obj(trans));
6571                         nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6572                                              NFT_MSG_NEWOBJ);
6573                         nft_trans_destroy(trans);
6574                         break;
6575                 case NFT_MSG_DELOBJ:
6576                         list_del_rcu(&nft_trans_obj(trans)->list);
6577                         nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6578                                              NFT_MSG_DELOBJ);
6579                         break;
6580                 case NFT_MSG_NEWFLOWTABLE:
6581                         nft_clear(net, nft_trans_flowtable(trans));
6582                         nf_tables_flowtable_notify(&trans->ctx,
6583                                                    nft_trans_flowtable(trans),
6584                                                    NFT_MSG_NEWFLOWTABLE);
6585                         nft_trans_destroy(trans);
6586                         break;
6587                 case NFT_MSG_DELFLOWTABLE:
6588                         list_del_rcu(&nft_trans_flowtable(trans)->list);
6589                         nf_tables_flowtable_notify(&trans->ctx,
6590                                                    nft_trans_flowtable(trans),
6591                                                    NFT_MSG_DELFLOWTABLE);
6592                         nft_unregister_flowtable_net_hooks(net,
6593                                         nft_trans_flowtable(trans));
6594                         break;
6595                 }
6596         }
6597
6598         nf_tables_gen_notify(net, skb, NFT_MSG_NEWGEN);
6599         nf_tables_commit_release(net);
6600
6601         return 0;
6602 }
6603
6604 static void nf_tables_abort_release(struct nft_trans *trans)
6605 {
6606         switch (trans->msg_type) {
6607         case NFT_MSG_NEWTABLE:
6608                 nf_tables_table_destroy(&trans->ctx);
6609                 break;
6610         case NFT_MSG_NEWCHAIN:
6611                 nf_tables_chain_destroy(&trans->ctx);
6612                 break;
6613         case NFT_MSG_NEWRULE:
6614                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6615                 break;
6616         case NFT_MSG_NEWSET:
6617                 if (!nft_trans_set_bound(trans))
6618                         nft_set_destroy(nft_trans_set(trans));
6619                 break;
6620         case NFT_MSG_NEWSETELEM:
6621                 nft_set_elem_destroy(nft_trans_elem_set(trans),
6622                                      nft_trans_elem(trans).priv, true);
6623                 break;
6624         case NFT_MSG_NEWOBJ:
6625                 nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6626                 break;
6627         case NFT_MSG_NEWFLOWTABLE:
6628                 nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6629                 break;
6630         }
6631         kfree(trans);
6632 }
6633
6634 static int __nf_tables_abort(struct net *net)
6635 {
6636         struct nft_trans *trans, *next;
6637         struct nft_trans_elem *te;
6638
6639         list_for_each_entry_safe_reverse(trans, next, &net->nft.commit_list,
6640                                          list) {
6641                 switch (trans->msg_type) {
6642                 case NFT_MSG_NEWTABLE:
6643                         if (nft_trans_table_update(trans)) {
6644                                 if (nft_trans_table_enable(trans)) {
6645                                         nf_tables_table_disable(net,
6646                                                                 trans->ctx.table);
6647                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6648                                 }
6649                                 nft_trans_destroy(trans);
6650                         } else {
6651                                 list_del_rcu(&trans->ctx.table->list);
6652                         }
6653                         break;
6654                 case NFT_MSG_DELTABLE:
6655                         nft_clear(trans->ctx.net, trans->ctx.table);
6656                         nft_trans_destroy(trans);
6657                         break;
6658                 case NFT_MSG_NEWCHAIN:
6659                         if (nft_trans_chain_update(trans)) {
6660                                 free_percpu(nft_trans_chain_stats(trans));
6661                                 kfree(nft_trans_chain_name(trans));
6662                                 nft_trans_destroy(trans);
6663                         } else {
6664                                 trans->ctx.table->use--;
6665                                 nft_chain_del(trans->ctx.chain);
6666                                 nf_tables_unregister_hook(trans->ctx.net,
6667                                                           trans->ctx.table,
6668                                                           trans->ctx.chain);
6669                         }
6670                         break;
6671                 case NFT_MSG_DELCHAIN:
6672                         trans->ctx.table->use++;
6673                         nft_clear(trans->ctx.net, trans->ctx.chain);
6674                         nft_trans_destroy(trans);
6675                         break;
6676                 case NFT_MSG_NEWRULE:
6677                         trans->ctx.chain->use--;
6678                         list_del_rcu(&nft_trans_rule(trans)->list);
6679                         nft_rule_expr_deactivate(&trans->ctx,
6680                                                  nft_trans_rule(trans),
6681                                                  NFT_TRANS_ABORT);
6682                         break;
6683                 case NFT_MSG_DELRULE:
6684                         trans->ctx.chain->use++;
6685                         nft_clear(trans->ctx.net, nft_trans_rule(trans));
6686                         nft_rule_expr_activate(&trans->ctx, nft_trans_rule(trans));
6687                         nft_trans_destroy(trans);
6688                         break;
6689                 case NFT_MSG_NEWSET:
6690                         trans->ctx.table->use--;
6691                         if (!nft_trans_set_bound(trans))
6692                                 list_del_rcu(&nft_trans_set(trans)->list);
6693                         break;
6694                 case NFT_MSG_DELSET:
6695                         trans->ctx.table->use++;
6696                         nft_clear(trans->ctx.net, nft_trans_set(trans));
6697                         nft_trans_destroy(trans);
6698                         break;
6699                 case NFT_MSG_NEWSETELEM:
6700                         te = (struct nft_trans_elem *)trans->data;
6701
6702                         te->set->ops->remove(net, te->set, &te->elem);
6703                         atomic_dec(&te->set->nelems);
6704                         break;
6705                 case NFT_MSG_DELSETELEM:
6706                         te = (struct nft_trans_elem *)trans->data;
6707
6708                         nft_set_elem_activate(net, te->set, &te->elem);
6709                         te->set->ops->activate(net, te->set, &te->elem);
6710                         te->set->ndeact--;
6711
6712                         nft_trans_destroy(trans);
6713                         break;
6714                 case NFT_MSG_NEWOBJ:
6715                         trans->ctx.table->use--;
6716                         list_del_rcu(&nft_trans_obj(trans)->list);
6717                         break;
6718                 case NFT_MSG_DELOBJ:
6719                         trans->ctx.table->use++;
6720                         nft_clear(trans->ctx.net, nft_trans_obj(trans));
6721                         nft_trans_destroy(trans);
6722                         break;
6723                 case NFT_MSG_NEWFLOWTABLE:
6724                         trans->ctx.table->use--;
6725                         list_del_rcu(&nft_trans_flowtable(trans)->list);
6726                         nft_unregister_flowtable_net_hooks(net,
6727                                         nft_trans_flowtable(trans));
6728                         break;
6729                 case NFT_MSG_DELFLOWTABLE:
6730                         trans->ctx.table->use++;
6731                         nft_clear(trans->ctx.net, nft_trans_flowtable(trans));
6732                         nft_trans_destroy(trans);
6733                         break;
6734                 }
6735         }
6736
6737         synchronize_rcu();
6738
6739         list_for_each_entry_safe_reverse(trans, next,
6740                                          &net->nft.commit_list, list) {
6741                 list_del(&trans->list);
6742                 nf_tables_abort_release(trans);
6743         }
6744
6745         return 0;
6746 }
6747
6748 static void nf_tables_cleanup(struct net *net)
6749 {
6750         nft_validate_state_update(net, NFT_VALIDATE_SKIP);
6751 }
6752
6753 static int nf_tables_abort(struct net *net, struct sk_buff *skb)
6754 {
6755         int ret = __nf_tables_abort(net);
6756
6757         mutex_unlock(&net->nft.commit_mutex);
6758
6759         return ret;
6760 }
6761
6762 static bool nf_tables_valid_genid(struct net *net, u32 genid)
6763 {
6764         bool genid_ok;
6765
6766         mutex_lock(&net->nft.commit_mutex);
6767
6768         genid_ok = genid == 0 || net->nft.base_seq == genid;
6769         if (!genid_ok)
6770                 mutex_unlock(&net->nft.commit_mutex);
6771
6772         /* else, commit mutex has to be released by commit or abort function */
6773         return genid_ok;
6774 }
6775
6776 static const struct nfnetlink_subsystem nf_tables_subsys = {
6777         .name           = "nf_tables",
6778         .subsys_id      = NFNL_SUBSYS_NFTABLES,
6779         .cb_count       = NFT_MSG_MAX,
6780         .cb             = nf_tables_cb,
6781         .commit         = nf_tables_commit,
6782         .abort          = nf_tables_abort,
6783         .cleanup        = nf_tables_cleanup,
6784         .valid_genid    = nf_tables_valid_genid,
6785         .owner          = THIS_MODULE,
6786 };
6787
6788 int nft_chain_validate_dependency(const struct nft_chain *chain,
6789                                   enum nft_chain_types type)
6790 {
6791         const struct nft_base_chain *basechain;
6792
6793         if (nft_is_base_chain(chain)) {
6794                 basechain = nft_base_chain(chain);
6795                 if (basechain->type->type != type)
6796                         return -EOPNOTSUPP;
6797         }
6798         return 0;
6799 }
6800 EXPORT_SYMBOL_GPL(nft_chain_validate_dependency);
6801
6802 int nft_chain_validate_hooks(const struct nft_chain *chain,
6803                              unsigned int hook_flags)
6804 {
6805         struct nft_base_chain *basechain;
6806
6807         if (nft_is_base_chain(chain)) {
6808                 basechain = nft_base_chain(chain);
6809
6810                 if ((1 << basechain->ops.hooknum) & hook_flags)
6811                         return 0;
6812
6813                 return -EOPNOTSUPP;
6814         }
6815
6816         return 0;
6817 }
6818 EXPORT_SYMBOL_GPL(nft_chain_validate_hooks);
6819
6820 /*
6821  * Loop detection - walk through the ruleset beginning at the destination chain
6822  * of a new jump until either the source chain is reached (loop) or all
6823  * reachable chains have been traversed.
6824  *
6825  * The loop check is performed whenever a new jump verdict is added to an
6826  * expression or verdict map or a verdict map is bound to a new chain.
6827  */
6828
6829 static int nf_tables_check_loops(const struct nft_ctx *ctx,
6830                                  const struct nft_chain *chain);
6831
6832 static int nf_tables_loop_check_setelem(const struct nft_ctx *ctx,
6833                                         struct nft_set *set,
6834                                         const struct nft_set_iter *iter,
6835                                         struct nft_set_elem *elem)
6836 {
6837         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
6838         const struct nft_data *data;
6839
6840         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
6841             *nft_set_ext_flags(ext) & NFT_SET_ELEM_INTERVAL_END)
6842                 return 0;
6843
6844         data = nft_set_ext_data(ext);
6845         switch (data->verdict.code) {
6846         case NFT_JUMP:
6847         case NFT_GOTO:
6848                 return nf_tables_check_loops(ctx, data->verdict.chain);
6849         default:
6850                 return 0;
6851         }
6852 }
6853
6854 static int nf_tables_check_loops(const struct nft_ctx *ctx,
6855                                  const struct nft_chain *chain)
6856 {
6857         const struct nft_rule *rule;
6858         const struct nft_expr *expr, *last;
6859         struct nft_set *set;
6860         struct nft_set_binding *binding;
6861         struct nft_set_iter iter;
6862
6863         if (ctx->chain == chain)
6864                 return -ELOOP;
6865
6866         list_for_each_entry(rule, &chain->rules, list) {
6867                 nft_rule_for_each_expr(expr, last, rule) {
6868                         struct nft_immediate_expr *priv;
6869                         const struct nft_data *data;
6870                         int err;
6871
6872                         if (strcmp(expr->ops->type->name, "immediate"))
6873                                 continue;
6874
6875                         priv = nft_expr_priv(expr);
6876                         if (priv->dreg != NFT_REG_VERDICT)
6877                                 continue;
6878
6879                         data = &priv->data;
6880                         switch (data->verdict.code) {
6881                         case NFT_JUMP:
6882                         case NFT_GOTO:
6883                                 err = nf_tables_check_loops(ctx,
6884                                                         data->verdict.chain);
6885                                 if (err < 0)
6886                                         return err;
6887                         default:
6888                                 break;
6889                         }
6890                 }
6891         }
6892
6893         list_for_each_entry(set, &ctx->table->sets, list) {
6894                 if (!nft_is_active_next(ctx->net, set))
6895                         continue;
6896                 if (!(set->flags & NFT_SET_MAP) ||
6897                     set->dtype != NFT_DATA_VERDICT)
6898                         continue;
6899
6900                 list_for_each_entry(binding, &set->bindings, list) {
6901                         if (!(binding->flags & NFT_SET_MAP) ||
6902                             binding->chain != chain)
6903                                 continue;
6904
6905                         iter.genmask    = nft_genmask_next(ctx->net);
6906                         iter.skip       = 0;
6907                         iter.count      = 0;
6908                         iter.err        = 0;
6909                         iter.fn         = nf_tables_loop_check_setelem;
6910
6911                         set->ops->walk(ctx, set, &iter);
6912                         if (iter.err < 0)
6913                                 return iter.err;
6914                 }
6915         }
6916
6917         return 0;
6918 }
6919
6920 /**
6921  *      nft_parse_u32_check - fetch u32 attribute and check for maximum value
6922  *
6923  *      @attr: netlink attribute to fetch value from
6924  *      @max: maximum value to be stored in dest
6925  *      @dest: pointer to the variable
6926  *
6927  *      Parse, check and store a given u32 netlink attribute into variable.
6928  *      This function returns -ERANGE if the value goes over maximum value.
6929  *      Otherwise a 0 is returned and the attribute value is stored in the
6930  *      destination variable.
6931  */
6932 int nft_parse_u32_check(const struct nlattr *attr, int max, u32 *dest)
6933 {
6934         u32 val;
6935
6936         val = ntohl(nla_get_be32(attr));
6937         if (val > max)
6938                 return -ERANGE;
6939
6940         *dest = val;
6941         return 0;
6942 }
6943 EXPORT_SYMBOL_GPL(nft_parse_u32_check);
6944
6945 /**
6946  *      nft_parse_register - parse a register value from a netlink attribute
6947  *
6948  *      @attr: netlink attribute
6949  *
6950  *      Parse and translate a register value from a netlink attribute.
6951  *      Registers used to be 128 bit wide, these register numbers will be
6952  *      mapped to the corresponding 32 bit register numbers.
6953  */
6954 unsigned int nft_parse_register(const struct nlattr *attr)
6955 {
6956         unsigned int reg;
6957
6958         reg = ntohl(nla_get_be32(attr));
6959         switch (reg) {
6960         case NFT_REG_VERDICT...NFT_REG_4:
6961                 return reg * NFT_REG_SIZE / NFT_REG32_SIZE;
6962         default:
6963                 return reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;
6964         }
6965 }
6966 EXPORT_SYMBOL_GPL(nft_parse_register);
6967
6968 /**
6969  *      nft_dump_register - dump a register value to a netlink attribute
6970  *
6971  *      @skb: socket buffer
6972  *      @attr: attribute number
6973  *      @reg: register number
6974  *
6975  *      Construct a netlink attribute containing the register number. For
6976  *      compatibility reasons, register numbers being a multiple of 4 are
6977  *      translated to the corresponding 128 bit register numbers.
6978  */
6979 int nft_dump_register(struct sk_buff *skb, unsigned int attr, unsigned int reg)
6980 {
6981         if (reg % (NFT_REG_SIZE / NFT_REG32_SIZE) == 0)
6982                 reg = reg / (NFT_REG_SIZE / NFT_REG32_SIZE);
6983         else
6984                 reg = reg - NFT_REG_SIZE / NFT_REG32_SIZE + NFT_REG32_00;
6985
6986         return nla_put_be32(skb, attr, htonl(reg));
6987 }
6988 EXPORT_SYMBOL_GPL(nft_dump_register);
6989
6990 /**
6991  *      nft_validate_register_load - validate a load from a register
6992  *
6993  *      @reg: the register number
6994  *      @len: the length of the data
6995  *
6996  *      Validate that the input register is one of the general purpose
6997  *      registers and that the length of the load is within the bounds.
6998  */
6999 int nft_validate_register_load(enum nft_registers reg, unsigned int len)
7000 {
7001         if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7002                 return -EINVAL;
7003         if (len == 0)
7004                 return -EINVAL;
7005         if (reg * NFT_REG32_SIZE + len > FIELD_SIZEOF(struct nft_regs, data))
7006                 return -ERANGE;
7007
7008         return 0;
7009 }
7010 EXPORT_SYMBOL_GPL(nft_validate_register_load);
7011
7012 /**
7013  *      nft_validate_register_store - validate an expressions' register store
7014  *
7015  *      @ctx: context of the expression performing the load
7016  *      @reg: the destination register number
7017  *      @data: the data to load
7018  *      @type: the data type
7019  *      @len: the length of the data
7020  *
7021  *      Validate that a data load uses the appropriate data type for
7022  *      the destination register and the length is within the bounds.
7023  *      A value of NULL for the data means that its runtime gathered
7024  *      data.
7025  */
7026 int nft_validate_register_store(const struct nft_ctx *ctx,
7027                                 enum nft_registers reg,
7028                                 const struct nft_data *data,
7029                                 enum nft_data_types type, unsigned int len)
7030 {
7031         int err;
7032
7033         switch (reg) {
7034         case NFT_REG_VERDICT:
7035                 if (type != NFT_DATA_VERDICT)
7036                         return -EINVAL;
7037
7038                 if (data != NULL &&
7039                     (data->verdict.code == NFT_GOTO ||
7040                      data->verdict.code == NFT_JUMP)) {
7041                         err = nf_tables_check_loops(ctx, data->verdict.chain);
7042                         if (err < 0)
7043                                 return err;
7044                 }
7045
7046                 return 0;
7047         default:
7048                 if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7049                         return -EINVAL;
7050                 if (len == 0)
7051                         return -EINVAL;
7052                 if (reg * NFT_REG32_SIZE + len >
7053                     FIELD_SIZEOF(struct nft_regs, data))
7054                         return -ERANGE;
7055
7056                 if (data != NULL && type != NFT_DATA_VALUE)
7057                         return -EINVAL;
7058                 return 0;
7059         }
7060 }
7061 EXPORT_SYMBOL_GPL(nft_validate_register_store);
7062
7063 static const struct nla_policy nft_verdict_policy[NFTA_VERDICT_MAX + 1] = {
7064         [NFTA_VERDICT_CODE]     = { .type = NLA_U32 },
7065         [NFTA_VERDICT_CHAIN]    = { .type = NLA_STRING,
7066                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
7067 };
7068
7069 static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
7070                             struct nft_data_desc *desc, const struct nlattr *nla)
7071 {
7072         u8 genmask = nft_genmask_next(ctx->net);
7073         struct nlattr *tb[NFTA_VERDICT_MAX + 1];
7074         struct nft_chain *chain;
7075         int err;
7076
7077         err = nla_parse_nested(tb, NFTA_VERDICT_MAX, nla, nft_verdict_policy,
7078                                NULL);
7079         if (err < 0)
7080                 return err;
7081
7082         if (!tb[NFTA_VERDICT_CODE])
7083                 return -EINVAL;
7084         data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
7085
7086         switch (data->verdict.code) {
7087         default:
7088                 switch (data->verdict.code & NF_VERDICT_MASK) {
7089                 case NF_ACCEPT:
7090                 case NF_DROP:
7091                 case NF_QUEUE:
7092                         break;
7093                 default:
7094                         return -EINVAL;
7095                 }
7096                 /* fall through */
7097         case NFT_CONTINUE:
7098         case NFT_BREAK:
7099         case NFT_RETURN:
7100                 break;
7101         case NFT_JUMP:
7102         case NFT_GOTO:
7103                 if (!tb[NFTA_VERDICT_CHAIN])
7104                         return -EINVAL;
7105                 chain = nft_chain_lookup(ctx->net, ctx->table,
7106                                          tb[NFTA_VERDICT_CHAIN], genmask);
7107                 if (IS_ERR(chain))
7108                         return PTR_ERR(chain);
7109                 if (nft_is_base_chain(chain))
7110                         return -EOPNOTSUPP;
7111
7112                 chain->use++;
7113                 data->verdict.chain = chain;
7114                 break;
7115         }
7116
7117         desc->len = sizeof(data->verdict);
7118         desc->type = NFT_DATA_VERDICT;
7119         return 0;
7120 }
7121
7122 static void nft_verdict_uninit(const struct nft_data *data)
7123 {
7124         switch (data->verdict.code) {
7125         case NFT_JUMP:
7126         case NFT_GOTO:
7127                 data->verdict.chain->use--;
7128                 break;
7129         }
7130 }
7131
7132 int nft_verdict_dump(struct sk_buff *skb, int type, const struct nft_verdict *v)
7133 {
7134         struct nlattr *nest;
7135
7136         nest = nla_nest_start(skb, type);
7137         if (!nest)
7138                 goto nla_put_failure;
7139
7140         if (nla_put_be32(skb, NFTA_VERDICT_CODE, htonl(v->code)))
7141                 goto nla_put_failure;
7142
7143         switch (v->code) {
7144         case NFT_JUMP:
7145         case NFT_GOTO:
7146                 if (nla_put_string(skb, NFTA_VERDICT_CHAIN,
7147                                    v->chain->name))
7148                         goto nla_put_failure;
7149         }
7150         nla_nest_end(skb, nest);
7151         return 0;
7152
7153 nla_put_failure:
7154         return -1;
7155 }
7156
7157 static int nft_value_init(const struct nft_ctx *ctx,
7158                           struct nft_data *data, unsigned int size,
7159                           struct nft_data_desc *desc, const struct nlattr *nla)
7160 {
7161         unsigned int len;
7162
7163         len = nla_len(nla);
7164         if (len == 0)
7165                 return -EINVAL;
7166         if (len > size)
7167                 return -EOVERFLOW;
7168
7169         nla_memcpy(data->data, nla, len);
7170         desc->type = NFT_DATA_VALUE;
7171         desc->len  = len;
7172         return 0;
7173 }
7174
7175 static int nft_value_dump(struct sk_buff *skb, const struct nft_data *data,
7176                           unsigned int len)
7177 {
7178         return nla_put(skb, NFTA_DATA_VALUE, len, data->data);
7179 }
7180
7181 static const struct nla_policy nft_data_policy[NFTA_DATA_MAX + 1] = {
7182         [NFTA_DATA_VALUE]       = { .type = NLA_BINARY },
7183         [NFTA_DATA_VERDICT]     = { .type = NLA_NESTED },
7184 };
7185
7186 /**
7187  *      nft_data_init - parse nf_tables data netlink attributes
7188  *
7189  *      @ctx: context of the expression using the data
7190  *      @data: destination struct nft_data
7191  *      @size: maximum data length
7192  *      @desc: data description
7193  *      @nla: netlink attribute containing data
7194  *
7195  *      Parse the netlink data attributes and initialize a struct nft_data.
7196  *      The type and length of data are returned in the data description.
7197  *
7198  *      The caller can indicate that it only wants to accept data of type
7199  *      NFT_DATA_VALUE by passing NULL for the ctx argument.
7200  */
7201 int nft_data_init(const struct nft_ctx *ctx,
7202                   struct nft_data *data, unsigned int size,
7203                   struct nft_data_desc *desc, const struct nlattr *nla)
7204 {
7205         struct nlattr *tb[NFTA_DATA_MAX + 1];
7206         int err;
7207
7208         err = nla_parse_nested(tb, NFTA_DATA_MAX, nla, nft_data_policy, NULL);
7209         if (err < 0)
7210                 return err;
7211
7212         if (tb[NFTA_DATA_VALUE])
7213                 return nft_value_init(ctx, data, size, desc,
7214                                       tb[NFTA_DATA_VALUE]);
7215         if (tb[NFTA_DATA_VERDICT] && ctx != NULL)
7216                 return nft_verdict_init(ctx, data, desc, tb[NFTA_DATA_VERDICT]);
7217         return -EINVAL;
7218 }
7219 EXPORT_SYMBOL_GPL(nft_data_init);
7220
7221 /**
7222  *      nft_data_release - release a nft_data item
7223  *
7224  *      @data: struct nft_data to release
7225  *      @type: type of data
7226  *
7227  *      Release a nft_data item. NFT_DATA_VALUE types can be silently discarded,
7228  *      all others need to be released by calling this function.
7229  */
7230 void nft_data_release(const struct nft_data *data, enum nft_data_types type)
7231 {
7232         if (type < NFT_DATA_VERDICT)
7233                 return;
7234         switch (type) {
7235         case NFT_DATA_VERDICT:
7236                 return nft_verdict_uninit(data);
7237         default:
7238                 WARN_ON(1);
7239         }
7240 }
7241 EXPORT_SYMBOL_GPL(nft_data_release);
7242
7243 int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
7244                   enum nft_data_types type, unsigned int len)
7245 {
7246         struct nlattr *nest;
7247         int err;
7248
7249         nest = nla_nest_start(skb, attr);
7250         if (nest == NULL)
7251                 return -1;
7252
7253         switch (type) {
7254         case NFT_DATA_VALUE:
7255                 err = nft_value_dump(skb, data, len);
7256                 break;
7257         case NFT_DATA_VERDICT:
7258                 err = nft_verdict_dump(skb, NFTA_DATA_VERDICT, &data->verdict);
7259                 break;
7260         default:
7261                 err = -EINVAL;
7262                 WARN_ON(1);
7263         }
7264
7265         nla_nest_end(skb, nest);
7266         return err;
7267 }
7268 EXPORT_SYMBOL_GPL(nft_data_dump);
7269
7270 int __nft_release_basechain(struct nft_ctx *ctx)
7271 {
7272         struct nft_rule *rule, *nr;
7273
7274         if (WARN_ON(!nft_is_base_chain(ctx->chain)))
7275                 return 0;
7276
7277         nf_tables_unregister_hook(ctx->net, ctx->chain->table, ctx->chain);
7278         list_for_each_entry_safe(rule, nr, &ctx->chain->rules, list) {
7279                 list_del(&rule->list);
7280                 ctx->chain->use--;
7281                 nf_tables_rule_release(ctx, rule);
7282         }
7283         nft_chain_del(ctx->chain);
7284         ctx->table->use--;
7285         nf_tables_chain_destroy(ctx);
7286
7287         return 0;
7288 }
7289 EXPORT_SYMBOL_GPL(__nft_release_basechain);
7290
7291 static void __nft_release_tables(struct net *net)
7292 {
7293         struct nft_flowtable *flowtable, *nf;
7294         struct nft_table *table, *nt;
7295         struct nft_chain *chain, *nc;
7296         struct nft_object *obj, *ne;
7297         struct nft_rule *rule, *nr;
7298         struct nft_set *set, *ns;
7299         struct nft_ctx ctx = {
7300                 .net    = net,
7301                 .family = NFPROTO_NETDEV,
7302         };
7303
7304         list_for_each_entry_safe(table, nt, &net->nft.tables, list) {
7305                 ctx.family = table->family;
7306
7307                 list_for_each_entry(chain, &table->chains, list)
7308                         nf_tables_unregister_hook(net, table, chain);
7309                 /* No packets are walking on these chains anymore. */
7310                 ctx.table = table;
7311                 list_for_each_entry(chain, &table->chains, list) {
7312                         ctx.chain = chain;
7313                         list_for_each_entry_safe(rule, nr, &chain->rules, list) {
7314                                 list_del(&rule->list);
7315                                 chain->use--;
7316                                 nf_tables_rule_release(&ctx, rule);
7317                         }
7318                 }
7319                 list_for_each_entry_safe(flowtable, nf, &table->flowtables, list) {
7320                         list_del(&flowtable->list);
7321                         table->use--;
7322                         nf_tables_flowtable_destroy(flowtable);
7323                 }
7324                 list_for_each_entry_safe(set, ns, &table->sets, list) {
7325                         list_del(&set->list);
7326                         table->use--;
7327                         nft_set_destroy(set);
7328                 }
7329                 list_for_each_entry_safe(obj, ne, &table->objects, list) {
7330                         list_del(&obj->list);
7331                         table->use--;
7332                         nft_obj_destroy(&ctx, obj);
7333                 }
7334                 list_for_each_entry_safe(chain, nc, &table->chains, list) {
7335                         ctx.chain = chain;
7336                         nft_chain_del(chain);
7337                         table->use--;
7338                         nf_tables_chain_destroy(&ctx);
7339                 }
7340                 list_del(&table->list);
7341                 nf_tables_table_destroy(&ctx);
7342         }
7343 }
7344
7345 static int __net_init nf_tables_init_net(struct net *net)
7346 {
7347         INIT_LIST_HEAD(&net->nft.tables);
7348         INIT_LIST_HEAD(&net->nft.commit_list);
7349         mutex_init(&net->nft.commit_mutex);
7350         net->nft.base_seq = 1;
7351         net->nft.validate_state = NFT_VALIDATE_SKIP;
7352
7353         return 0;
7354 }
7355
7356 static void __net_exit nf_tables_exit_net(struct net *net)
7357 {
7358         mutex_lock(&net->nft.commit_mutex);
7359         if (!list_empty(&net->nft.commit_list))
7360                 __nf_tables_abort(net);
7361         __nft_release_tables(net);
7362         mutex_unlock(&net->nft.commit_mutex);
7363         WARN_ON_ONCE(!list_empty(&net->nft.tables));
7364 }
7365
7366 static struct pernet_operations nf_tables_net_ops = {
7367         .init   = nf_tables_init_net,
7368         .exit   = nf_tables_exit_net,
7369 };
7370
7371 static int __init nf_tables_module_init(void)
7372 {
7373         int err;
7374
7375         spin_lock_init(&nf_tables_destroy_list_lock);
7376         err = register_pernet_subsys(&nf_tables_net_ops);
7377         if (err < 0)
7378                 return err;
7379
7380         err = nft_chain_filter_init();
7381         if (err < 0)
7382                 goto err1;
7383
7384         err = nf_tables_core_module_init();
7385         if (err < 0)
7386                 goto err2;
7387
7388         err = register_netdevice_notifier(&nf_tables_flowtable_notifier);
7389         if (err < 0)
7390                 goto err3;
7391
7392         /* must be last */
7393         err = nfnetlink_subsys_register(&nf_tables_subsys);
7394         if (err < 0)
7395                 goto err4;
7396
7397         return err;
7398 err4:
7399         unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7400 err3:
7401         nf_tables_core_module_exit();
7402 err2:
7403         nft_chain_filter_fini();
7404 err1:
7405         unregister_pernet_subsys(&nf_tables_net_ops);
7406         return err;
7407 }
7408
7409 static void __exit nf_tables_module_exit(void)
7410 {
7411         nfnetlink_subsys_unregister(&nf_tables_subsys);
7412         unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7413         nft_chain_filter_fini();
7414         unregister_pernet_subsys(&nf_tables_net_ops);
7415         cancel_work_sync(&trans_destroy_work);
7416         rcu_barrier();
7417         nf_tables_core_module_exit();
7418 }
7419
7420 module_init(nf_tables_module_init);
7421 module_exit(nf_tables_module_exit);
7422
7423 MODULE_LICENSE("GPL");
7424 MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
7425 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_NFTABLES);