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