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