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