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