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