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