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