Merge tag 'm68k-for-v4.20-tag2' of git://git.kernel.org/pub/scm/linux/kernel/git...
[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                                 struct netlink_callback *cb)
2300 {
2301         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
2302         const struct nft_rule_dump_ctx *ctx = cb->data;
2303         const struct nft_table *table;
2304         const struct nft_chain *chain;
2305         const struct nft_rule *rule;
2306         unsigned int idx = 0, s_idx = cb->args[0];
2307         struct net *net = sock_net(skb->sk);
2308         int family = nfmsg->nfgen_family;
2309
2310         rcu_read_lock();
2311         cb->seq = net->nft.base_seq;
2312
2313         list_for_each_entry_rcu(table, &net->nft.tables, list) {
2314                 if (family != NFPROTO_UNSPEC && family != table->family)
2315                         continue;
2316
2317                 if (ctx && ctx->table && strcmp(ctx->table, table->name) != 0)
2318                         continue;
2319
2320                 list_for_each_entry_rcu(chain, &table->chains, list) {
2321                         if (ctx && ctx->chain &&
2322                             strcmp(ctx->chain, chain->name) != 0)
2323                                 continue;
2324
2325                         list_for_each_entry_rcu(rule, &chain->rules, list) {
2326                                 if (!nft_is_active(net, rule))
2327                                         goto cont;
2328                                 if (idx < s_idx)
2329                                         goto cont;
2330                                 if (idx > s_idx)
2331                                         memset(&cb->args[1], 0,
2332                                                sizeof(cb->args) - sizeof(cb->args[0]));
2333                                 if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
2334                                                               cb->nlh->nlmsg_seq,
2335                                                               NFT_MSG_NEWRULE,
2336                                                               NLM_F_MULTI | NLM_F_APPEND,
2337                                                               table->family,
2338                                                               table, chain, rule) < 0)
2339                                         goto done;
2340
2341                                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
2342 cont:
2343                                 idx++;
2344                         }
2345                 }
2346         }
2347 done:
2348         rcu_read_unlock();
2349
2350         cb->args[0] = idx;
2351         return skb->len;
2352 }
2353
2354 static int nf_tables_dump_rules_start(struct netlink_callback *cb)
2355 {
2356         const struct nlattr * const *nla = cb->data;
2357         struct nft_rule_dump_ctx *ctx = NULL;
2358
2359         if (nla[NFTA_RULE_TABLE] || nla[NFTA_RULE_CHAIN]) {
2360                 ctx = kzalloc(sizeof(*ctx), GFP_ATOMIC);
2361                 if (!ctx)
2362                         return -ENOMEM;
2363
2364                 if (nla[NFTA_RULE_TABLE]) {
2365                         ctx->table = nla_strdup(nla[NFTA_RULE_TABLE],
2366                                                         GFP_ATOMIC);
2367                         if (!ctx->table) {
2368                                 kfree(ctx);
2369                                 return -ENOMEM;
2370                         }
2371                 }
2372                 if (nla[NFTA_RULE_CHAIN]) {
2373                         ctx->chain = nla_strdup(nla[NFTA_RULE_CHAIN],
2374                                                 GFP_ATOMIC);
2375                         if (!ctx->chain) {
2376                                 kfree(ctx->table);
2377                                 kfree(ctx);
2378                                 return -ENOMEM;
2379                         }
2380                 }
2381         }
2382
2383         cb->data = ctx;
2384         return 0;
2385 }
2386
2387 static int nf_tables_dump_rules_done(struct netlink_callback *cb)
2388 {
2389         struct nft_rule_dump_ctx *ctx = cb->data;
2390
2391         if (ctx) {
2392                 kfree(ctx->table);
2393                 kfree(ctx->chain);
2394                 kfree(ctx);
2395         }
2396         return 0;
2397 }
2398
2399 /* called with rcu_read_lock held */
2400 static int nf_tables_getrule(struct net *net, struct sock *nlsk,
2401                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2402                              const struct nlattr * const nla[],
2403                              struct netlink_ext_ack *extack)
2404 {
2405         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2406         u8 genmask = nft_genmask_cur(net);
2407         const struct nft_chain *chain;
2408         const struct nft_rule *rule;
2409         struct nft_table *table;
2410         struct sk_buff *skb2;
2411         int family = nfmsg->nfgen_family;
2412         int err;
2413
2414         if (nlh->nlmsg_flags & NLM_F_DUMP) {
2415                 struct netlink_dump_control c = {
2416                         .start= nf_tables_dump_rules_start,
2417                         .dump = nf_tables_dump_rules,
2418                         .done = nf_tables_dump_rules_done,
2419                         .module = THIS_MODULE,
2420                         .data = (void *)nla,
2421                 };
2422
2423                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
2424         }
2425
2426         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2427         if (IS_ERR(table)) {
2428                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2429                 return PTR_ERR(table);
2430         }
2431
2432         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2433         if (IS_ERR(chain)) {
2434                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2435                 return PTR_ERR(chain);
2436         }
2437
2438         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2439         if (IS_ERR(rule)) {
2440                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2441                 return PTR_ERR(rule);
2442         }
2443
2444         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
2445         if (!skb2)
2446                 return -ENOMEM;
2447
2448         err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
2449                                        nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
2450                                        family, table, chain, rule);
2451         if (err < 0)
2452                 goto err;
2453
2454         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
2455
2456 err:
2457         kfree_skb(skb2);
2458         return err;
2459 }
2460
2461 static void nf_tables_rule_destroy(const struct nft_ctx *ctx,
2462                                    struct nft_rule *rule)
2463 {
2464         struct nft_expr *expr, *next;
2465
2466         /*
2467          * Careful: some expressions might not be initialized in case this
2468          * is called on error from nf_tables_newrule().
2469          */
2470         expr = nft_expr_first(rule);
2471         while (expr != nft_expr_last(rule) && expr->ops) {
2472                 next = nft_expr_next(expr);
2473                 nf_tables_expr_destroy(ctx, expr);
2474                 expr = next;
2475         }
2476         kfree(rule);
2477 }
2478
2479 static void nf_tables_rule_release(const struct nft_ctx *ctx,
2480                                    struct nft_rule *rule)
2481 {
2482         nft_rule_expr_deactivate(ctx, rule);
2483         nf_tables_rule_destroy(ctx, rule);
2484 }
2485
2486 int nft_chain_validate(const struct nft_ctx *ctx, const struct nft_chain *chain)
2487 {
2488         struct nft_expr *expr, *last;
2489         const struct nft_data *data;
2490         struct nft_rule *rule;
2491         int err;
2492
2493         if (ctx->level == NFT_JUMP_STACK_SIZE)
2494                 return -EMLINK;
2495
2496         list_for_each_entry(rule, &chain->rules, list) {
2497                 if (!nft_is_active_next(ctx->net, rule))
2498                         continue;
2499
2500                 nft_rule_for_each_expr(expr, last, rule) {
2501                         if (!expr->ops->validate)
2502                                 continue;
2503
2504                         err = expr->ops->validate(ctx, expr, &data);
2505                         if (err < 0)
2506                                 return err;
2507                 }
2508         }
2509
2510         return 0;
2511 }
2512 EXPORT_SYMBOL_GPL(nft_chain_validate);
2513
2514 static int nft_table_validate(struct net *net, const struct nft_table *table)
2515 {
2516         struct nft_chain *chain;
2517         struct nft_ctx ctx = {
2518                 .net    = net,
2519                 .family = table->family,
2520         };
2521         int err;
2522
2523         list_for_each_entry(chain, &table->chains, list) {
2524                 if (!nft_is_base_chain(chain))
2525                         continue;
2526
2527                 ctx.chain = chain;
2528                 err = nft_chain_validate(&ctx, chain);
2529                 if (err < 0)
2530                         return err;
2531         }
2532
2533         return 0;
2534 }
2535
2536 #define NFT_RULE_MAXEXPRS       128
2537
2538 static int nf_tables_newrule(struct net *net, struct sock *nlsk,
2539                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2540                              const struct nlattr * const nla[],
2541                              struct netlink_ext_ack *extack)
2542 {
2543         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2544         u8 genmask = nft_genmask_next(net);
2545         struct nft_expr_info *info = NULL;
2546         int family = nfmsg->nfgen_family;
2547         struct nft_table *table;
2548         struct nft_chain *chain;
2549         struct nft_rule *rule, *old_rule = NULL;
2550         struct nft_userdata *udata;
2551         struct nft_trans *trans = NULL;
2552         struct nft_expr *expr;
2553         struct nft_ctx ctx;
2554         struct nlattr *tmp;
2555         unsigned int size, i, n, ulen = 0, usize = 0;
2556         int err, rem;
2557         u64 handle, pos_handle;
2558
2559         lockdep_assert_held(&net->nft.commit_mutex);
2560
2561         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2562         if (IS_ERR(table)) {
2563                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2564                 return PTR_ERR(table);
2565         }
2566
2567         chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN], genmask);
2568         if (IS_ERR(chain)) {
2569                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2570                 return PTR_ERR(chain);
2571         }
2572
2573         if (nla[NFTA_RULE_HANDLE]) {
2574                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
2575                 rule = __nft_rule_lookup(chain, handle);
2576                 if (IS_ERR(rule)) {
2577                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2578                         return PTR_ERR(rule);
2579                 }
2580
2581                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
2582                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2583                         return -EEXIST;
2584                 }
2585                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
2586                         old_rule = rule;
2587                 else
2588                         return -EOPNOTSUPP;
2589         } else {
2590                 if (!(nlh->nlmsg_flags & NLM_F_CREATE) ||
2591                     nlh->nlmsg_flags & NLM_F_REPLACE)
2592                         return -EINVAL;
2593                 handle = nf_tables_alloc_handle(table);
2594
2595                 if (chain->use == UINT_MAX)
2596                         return -EOVERFLOW;
2597
2598                 if (nla[NFTA_RULE_POSITION]) {
2599                         pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
2600                         old_rule = __nft_rule_lookup(chain, pos_handle);
2601                         if (IS_ERR(old_rule)) {
2602                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_POSITION]);
2603                                 return PTR_ERR(old_rule);
2604                         }
2605                 }
2606         }
2607
2608         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2609
2610         n = 0;
2611         size = 0;
2612         if (nla[NFTA_RULE_EXPRESSIONS]) {
2613                 info = kvmalloc_array(NFT_RULE_MAXEXPRS,
2614                                       sizeof(struct nft_expr_info),
2615                                       GFP_KERNEL);
2616                 if (!info)
2617                         return -ENOMEM;
2618
2619                 nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
2620                         err = -EINVAL;
2621                         if (nla_type(tmp) != NFTA_LIST_ELEM)
2622                                 goto err1;
2623                         if (n == NFT_RULE_MAXEXPRS)
2624                                 goto err1;
2625                         err = nf_tables_expr_parse(&ctx, tmp, &info[n]);
2626                         if (err < 0)
2627                                 goto err1;
2628                         size += info[n].ops->size;
2629                         n++;
2630                 }
2631         }
2632         /* Check for overflow of dlen field */
2633         err = -EFBIG;
2634         if (size >= 1 << 12)
2635                 goto err1;
2636
2637         if (nla[NFTA_RULE_USERDATA]) {
2638                 ulen = nla_len(nla[NFTA_RULE_USERDATA]);
2639                 if (ulen > 0)
2640                         usize = sizeof(struct nft_userdata) + ulen;
2641         }
2642
2643         err = -ENOMEM;
2644         rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL);
2645         if (rule == NULL)
2646                 goto err1;
2647
2648         nft_activate_next(net, rule);
2649
2650         rule->handle = handle;
2651         rule->dlen   = size;
2652         rule->udata  = ulen ? 1 : 0;
2653
2654         if (ulen) {
2655                 udata = nft_userdata(rule);
2656                 udata->len = ulen - 1;
2657                 nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
2658         }
2659
2660         expr = nft_expr_first(rule);
2661         for (i = 0; i < n; i++) {
2662                 err = nf_tables_newexpr(&ctx, &info[i], expr);
2663                 if (err < 0)
2664                         goto err2;
2665
2666                 if (info[i].ops->validate)
2667                         nft_validate_state_update(net, NFT_VALIDATE_NEED);
2668
2669                 info[i].ops = NULL;
2670                 expr = nft_expr_next(expr);
2671         }
2672
2673         if (nlh->nlmsg_flags & NLM_F_REPLACE) {
2674                 trans = nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule);
2675                 if (trans == NULL) {
2676                         err = -ENOMEM;
2677                         goto err2;
2678                 }
2679                 err = nft_delrule(&ctx, old_rule);
2680                 if (err < 0) {
2681                         nft_trans_destroy(trans);
2682                         goto err2;
2683                 }
2684
2685                 list_add_tail_rcu(&rule->list, &old_rule->list);
2686         } else {
2687                 if (nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule) == NULL) {
2688                         err = -ENOMEM;
2689                         goto err2;
2690                 }
2691
2692                 if (nlh->nlmsg_flags & NLM_F_APPEND) {
2693                         if (old_rule)
2694                                 list_add_rcu(&rule->list, &old_rule->list);
2695                         else
2696                                 list_add_tail_rcu(&rule->list, &chain->rules);
2697                  } else {
2698                         if (old_rule)
2699                                 list_add_tail_rcu(&rule->list, &old_rule->list);
2700                         else
2701                                 list_add_rcu(&rule->list, &chain->rules);
2702                 }
2703         }
2704         kvfree(info);
2705         chain->use++;
2706
2707         if (net->nft.validate_state == NFT_VALIDATE_DO)
2708                 return nft_table_validate(net, table);
2709
2710         return 0;
2711 err2:
2712         nf_tables_rule_release(&ctx, rule);
2713 err1:
2714         for (i = 0; i < n; i++) {
2715                 if (info[i].ops != NULL)
2716                         module_put(info[i].ops->type->owner);
2717         }
2718         kvfree(info);
2719         return err;
2720 }
2721
2722 static struct nft_rule *nft_rule_lookup_byid(const struct net *net,
2723                                              const struct nlattr *nla)
2724 {
2725         u32 id = ntohl(nla_get_be32(nla));
2726         struct nft_trans *trans;
2727
2728         list_for_each_entry(trans, &net->nft.commit_list, list) {
2729                 struct nft_rule *rule = nft_trans_rule(trans);
2730
2731                 if (trans->msg_type == NFT_MSG_NEWRULE &&
2732                     id == nft_trans_rule_id(trans))
2733                         return rule;
2734         }
2735         return ERR_PTR(-ENOENT);
2736 }
2737
2738 static int nf_tables_delrule(struct net *net, struct sock *nlsk,
2739                              struct sk_buff *skb, const struct nlmsghdr *nlh,
2740                              const struct nlattr * const nla[],
2741                              struct netlink_ext_ack *extack)
2742 {
2743         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2744         u8 genmask = nft_genmask_next(net);
2745         struct nft_table *table;
2746         struct nft_chain *chain = NULL;
2747         struct nft_rule *rule;
2748         int family = nfmsg->nfgen_family, err = 0;
2749         struct nft_ctx ctx;
2750
2751         table = nft_table_lookup(net, nla[NFTA_RULE_TABLE], family, genmask);
2752         if (IS_ERR(table)) {
2753                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_TABLE]);
2754                 return PTR_ERR(table);
2755         }
2756
2757         if (nla[NFTA_RULE_CHAIN]) {
2758                 chain = nft_chain_lookup(net, table, nla[NFTA_RULE_CHAIN],
2759                                          genmask);
2760                 if (IS_ERR(chain)) {
2761                         NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_CHAIN]);
2762                         return PTR_ERR(chain);
2763                 }
2764         }
2765
2766         nft_ctx_init(&ctx, net, skb, nlh, family, table, chain, nla);
2767
2768         if (chain) {
2769                 if (nla[NFTA_RULE_HANDLE]) {
2770                         rule = nft_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
2771                         if (IS_ERR(rule)) {
2772                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_HANDLE]);
2773                                 return PTR_ERR(rule);
2774                         }
2775
2776                         err = nft_delrule(&ctx, rule);
2777                 } else if (nla[NFTA_RULE_ID]) {
2778                         rule = nft_rule_lookup_byid(net, nla[NFTA_RULE_ID]);
2779                         if (IS_ERR(rule)) {
2780                                 NL_SET_BAD_ATTR(extack, nla[NFTA_RULE_ID]);
2781                                 return PTR_ERR(rule);
2782                         }
2783
2784                         err = nft_delrule(&ctx, rule);
2785                 } else {
2786                         err = nft_delrule_by_chain(&ctx);
2787                 }
2788         } else {
2789                 list_for_each_entry(chain, &table->chains, list) {
2790                         if (!nft_is_active_next(net, chain))
2791                                 continue;
2792
2793                         ctx.chain = chain;
2794                         err = nft_delrule_by_chain(&ctx);
2795                         if (err < 0)
2796                                 break;
2797                 }
2798         }
2799
2800         return err;
2801 }
2802
2803 /*
2804  * Sets
2805  */
2806
2807 static LIST_HEAD(nf_tables_set_types);
2808
2809 int nft_register_set(struct nft_set_type *type)
2810 {
2811         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2812         list_add_tail_rcu(&type->list, &nf_tables_set_types);
2813         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2814         return 0;
2815 }
2816 EXPORT_SYMBOL_GPL(nft_register_set);
2817
2818 void nft_unregister_set(struct nft_set_type *type)
2819 {
2820         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2821         list_del_rcu(&type->list);
2822         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2823 }
2824 EXPORT_SYMBOL_GPL(nft_unregister_set);
2825
2826 #define NFT_SET_FEATURES        (NFT_SET_INTERVAL | NFT_SET_MAP | \
2827                                  NFT_SET_TIMEOUT | NFT_SET_OBJECT | \
2828                                  NFT_SET_EVAL)
2829
2830 static bool nft_set_ops_candidate(const struct nft_set_type *type, u32 flags)
2831 {
2832         return (flags & type->features) == (flags & NFT_SET_FEATURES);
2833 }
2834
2835 /*
2836  * Select a set implementation based on the data characteristics and the
2837  * given policy. The total memory use might not be known if no size is
2838  * given, in that case the amount of memory per element is used.
2839  */
2840 static const struct nft_set_ops *
2841 nft_select_set_ops(const struct nft_ctx *ctx,
2842                    const struct nlattr * const nla[],
2843                    const struct nft_set_desc *desc,
2844                    enum nft_set_policies policy)
2845 {
2846         const struct nft_set_ops *ops, *bops;
2847         struct nft_set_estimate est, best;
2848         const struct nft_set_type *type;
2849         u32 flags = 0;
2850
2851         lockdep_assert_held(&ctx->net->nft.commit_mutex);
2852         lockdep_nfnl_nft_mutex_not_held();
2853 #ifdef CONFIG_MODULES
2854         if (list_empty(&nf_tables_set_types)) {
2855                 nft_request_module(ctx->net, "nft-set");
2856                 if (!list_empty(&nf_tables_set_types))
2857                         return ERR_PTR(-EAGAIN);
2858         }
2859 #endif
2860         if (nla[NFTA_SET_FLAGS] != NULL)
2861                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
2862
2863         bops        = NULL;
2864         best.size   = ~0;
2865         best.lookup = ~0;
2866         best.space  = ~0;
2867
2868         list_for_each_entry(type, &nf_tables_set_types, list) {
2869                 ops = &type->ops;
2870
2871                 if (!nft_set_ops_candidate(type, flags))
2872                         continue;
2873                 if (!ops->estimate(desc, flags, &est))
2874                         continue;
2875
2876                 switch (policy) {
2877                 case NFT_SET_POL_PERFORMANCE:
2878                         if (est.lookup < best.lookup)
2879                                 break;
2880                         if (est.lookup == best.lookup &&
2881                             est.space < best.space)
2882                                 break;
2883                         continue;
2884                 case NFT_SET_POL_MEMORY:
2885                         if (!desc->size) {
2886                                 if (est.space < best.space)
2887                                         break;
2888                                 if (est.space == best.space &&
2889                                     est.lookup < best.lookup)
2890                                         break;
2891                         } else if (est.size < best.size || !bops) {
2892                                 break;
2893                         }
2894                         continue;
2895                 default:
2896                         break;
2897                 }
2898
2899                 if (!try_module_get(type->owner))
2900                         continue;
2901                 if (bops != NULL)
2902                         module_put(to_set_type(bops)->owner);
2903
2904                 bops = ops;
2905                 best = est;
2906         }
2907
2908         if (bops != NULL)
2909                 return bops;
2910
2911         return ERR_PTR(-EOPNOTSUPP);
2912 }
2913
2914 static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
2915         [NFTA_SET_TABLE]                = { .type = NLA_STRING,
2916                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
2917         [NFTA_SET_NAME]                 = { .type = NLA_STRING,
2918                                             .len = NFT_SET_MAXNAMELEN - 1 },
2919         [NFTA_SET_FLAGS]                = { .type = NLA_U32 },
2920         [NFTA_SET_KEY_TYPE]             = { .type = NLA_U32 },
2921         [NFTA_SET_KEY_LEN]              = { .type = NLA_U32 },
2922         [NFTA_SET_DATA_TYPE]            = { .type = NLA_U32 },
2923         [NFTA_SET_DATA_LEN]             = { .type = NLA_U32 },
2924         [NFTA_SET_POLICY]               = { .type = NLA_U32 },
2925         [NFTA_SET_DESC]                 = { .type = NLA_NESTED },
2926         [NFTA_SET_ID]                   = { .type = NLA_U32 },
2927         [NFTA_SET_TIMEOUT]              = { .type = NLA_U64 },
2928         [NFTA_SET_GC_INTERVAL]          = { .type = NLA_U32 },
2929         [NFTA_SET_USERDATA]             = { .type = NLA_BINARY,
2930                                             .len  = NFT_USERDATA_MAXLEN },
2931         [NFTA_SET_OBJ_TYPE]             = { .type = NLA_U32 },
2932         [NFTA_SET_HANDLE]               = { .type = NLA_U64 },
2933 };
2934
2935 static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
2936         [NFTA_SET_DESC_SIZE]            = { .type = NLA_U32 },
2937 };
2938
2939 static int nft_ctx_init_from_setattr(struct nft_ctx *ctx, struct net *net,
2940                                      const struct sk_buff *skb,
2941                                      const struct nlmsghdr *nlh,
2942                                      const struct nlattr * const nla[],
2943                                      struct netlink_ext_ack *extack,
2944                                      u8 genmask)
2945 {
2946         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2947         int family = nfmsg->nfgen_family;
2948         struct nft_table *table = NULL;
2949
2950         if (nla[NFTA_SET_TABLE] != NULL) {
2951                 table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family,
2952                                          genmask);
2953                 if (IS_ERR(table)) {
2954                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
2955                         return PTR_ERR(table);
2956                 }
2957         }
2958
2959         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
2960         return 0;
2961 }
2962
2963 static struct nft_set *nft_set_lookup(const struct nft_table *table,
2964                                       const struct nlattr *nla, u8 genmask)
2965 {
2966         struct nft_set *set;
2967
2968         if (nla == NULL)
2969                 return ERR_PTR(-EINVAL);
2970
2971         list_for_each_entry_rcu(set, &table->sets, list) {
2972                 if (!nla_strcmp(nla, set->name) &&
2973                     nft_active_genmask(set, genmask))
2974                         return set;
2975         }
2976         return ERR_PTR(-ENOENT);
2977 }
2978
2979 static struct nft_set *nft_set_lookup_byhandle(const struct nft_table *table,
2980                                                const struct nlattr *nla,
2981                                                u8 genmask)
2982 {
2983         struct nft_set *set;
2984
2985         list_for_each_entry(set, &table->sets, list) {
2986                 if (be64_to_cpu(nla_get_be64(nla)) == set->handle &&
2987                     nft_active_genmask(set, genmask))
2988                         return set;
2989         }
2990         return ERR_PTR(-ENOENT);
2991 }
2992
2993 static struct nft_set *nft_set_lookup_byid(const struct net *net,
2994                                            const struct nlattr *nla, u8 genmask)
2995 {
2996         struct nft_trans *trans;
2997         u32 id = ntohl(nla_get_be32(nla));
2998
2999         list_for_each_entry(trans, &net->nft.commit_list, list) {
3000                 if (trans->msg_type == NFT_MSG_NEWSET) {
3001                         struct nft_set *set = nft_trans_set(trans);
3002
3003                         if (id == nft_trans_set_id(trans) &&
3004                             nft_active_genmask(set, genmask))
3005                                 return set;
3006                 }
3007         }
3008         return ERR_PTR(-ENOENT);
3009 }
3010
3011 struct nft_set *nft_set_lookup_global(const struct net *net,
3012                                       const struct nft_table *table,
3013                                       const struct nlattr *nla_set_name,
3014                                       const struct nlattr *nla_set_id,
3015                                       u8 genmask)
3016 {
3017         struct nft_set *set;
3018
3019         set = nft_set_lookup(table, nla_set_name, genmask);
3020         if (IS_ERR(set)) {
3021                 if (!nla_set_id)
3022                         return set;
3023
3024                 set = nft_set_lookup_byid(net, nla_set_id, genmask);
3025         }
3026         return set;
3027 }
3028 EXPORT_SYMBOL_GPL(nft_set_lookup_global);
3029
3030 static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
3031                                     const char *name)
3032 {
3033         const struct nft_set *i;
3034         const char *p;
3035         unsigned long *inuse;
3036         unsigned int n = 0, min = 0;
3037
3038         p = strchr(name, '%');
3039         if (p != NULL) {
3040                 if (p[1] != 'd' || strchr(p + 2, '%'))
3041                         return -EINVAL;
3042
3043                 inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
3044                 if (inuse == NULL)
3045                         return -ENOMEM;
3046 cont:
3047                 list_for_each_entry(i, &ctx->table->sets, list) {
3048                         int tmp;
3049
3050                         if (!nft_is_active_next(ctx->net, set))
3051                                 continue;
3052                         if (!sscanf(i->name, name, &tmp))
3053                                 continue;
3054                         if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
3055                                 continue;
3056
3057                         set_bit(tmp - min, inuse);
3058                 }
3059
3060                 n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
3061                 if (n >= BITS_PER_BYTE * PAGE_SIZE) {
3062                         min += BITS_PER_BYTE * PAGE_SIZE;
3063                         memset(inuse, 0, PAGE_SIZE);
3064                         goto cont;
3065                 }
3066                 free_page((unsigned long)inuse);
3067         }
3068
3069         set->name = kasprintf(GFP_KERNEL, name, min + n);
3070         if (!set->name)
3071                 return -ENOMEM;
3072
3073         list_for_each_entry(i, &ctx->table->sets, list) {
3074                 if (!nft_is_active_next(ctx->net, i))
3075                         continue;
3076                 if (!strcmp(set->name, i->name)) {
3077                         kfree(set->name);
3078                         return -ENFILE;
3079                 }
3080         }
3081         return 0;
3082 }
3083
3084 static int nf_msecs_to_jiffies64(const struct nlattr *nla, u64 *result)
3085 {
3086         u64 ms = be64_to_cpu(nla_get_be64(nla));
3087         u64 max = (u64)(~((u64)0));
3088
3089         max = div_u64(max, NSEC_PER_MSEC);
3090         if (ms >= max)
3091                 return -ERANGE;
3092
3093         ms *= NSEC_PER_MSEC;
3094         *result = nsecs_to_jiffies64(ms);
3095         return 0;
3096 }
3097
3098 static __be64 nf_jiffies64_to_msecs(u64 input)
3099 {
3100         u64 ms = jiffies64_to_nsecs(input);
3101
3102         return cpu_to_be64(div_u64(ms, NSEC_PER_MSEC));
3103 }
3104
3105 static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
3106                               const struct nft_set *set, u16 event, u16 flags)
3107 {
3108         struct nfgenmsg *nfmsg;
3109         struct nlmsghdr *nlh;
3110         struct nlattr *desc;
3111         u32 portid = ctx->portid;
3112         u32 seq = ctx->seq;
3113
3114         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
3115         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3116                         flags);
3117         if (nlh == NULL)
3118                 goto nla_put_failure;
3119
3120         nfmsg = nlmsg_data(nlh);
3121         nfmsg->nfgen_family     = ctx->family;
3122         nfmsg->version          = NFNETLINK_V0;
3123         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
3124
3125         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
3126                 goto nla_put_failure;
3127         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
3128                 goto nla_put_failure;
3129         if (nla_put_be64(skb, NFTA_SET_HANDLE, cpu_to_be64(set->handle),
3130                          NFTA_SET_PAD))
3131                 goto nla_put_failure;
3132         if (set->flags != 0)
3133                 if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
3134                         goto nla_put_failure;
3135
3136         if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
3137                 goto nla_put_failure;
3138         if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
3139                 goto nla_put_failure;
3140         if (set->flags & NFT_SET_MAP) {
3141                 if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
3142                         goto nla_put_failure;
3143                 if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
3144                         goto nla_put_failure;
3145         }
3146         if (set->flags & NFT_SET_OBJECT &&
3147             nla_put_be32(skb, NFTA_SET_OBJ_TYPE, htonl(set->objtype)))
3148                 goto nla_put_failure;
3149
3150         if (set->timeout &&
3151             nla_put_be64(skb, NFTA_SET_TIMEOUT,
3152                          nf_jiffies64_to_msecs(set->timeout),
3153                          NFTA_SET_PAD))
3154                 goto nla_put_failure;
3155         if (set->gc_int &&
3156             nla_put_be32(skb, NFTA_SET_GC_INTERVAL, htonl(set->gc_int)))
3157                 goto nla_put_failure;
3158
3159         if (set->policy != NFT_SET_POL_PERFORMANCE) {
3160                 if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
3161                         goto nla_put_failure;
3162         }
3163
3164         if (nla_put(skb, NFTA_SET_USERDATA, set->udlen, set->udata))
3165                 goto nla_put_failure;
3166
3167         desc = nla_nest_start(skb, NFTA_SET_DESC);
3168         if (desc == NULL)
3169                 goto nla_put_failure;
3170         if (set->size &&
3171             nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
3172                 goto nla_put_failure;
3173         nla_nest_end(skb, desc);
3174
3175         nlmsg_end(skb, nlh);
3176         return 0;
3177
3178 nla_put_failure:
3179         nlmsg_trim(skb, nlh);
3180         return -1;
3181 }
3182
3183 static void nf_tables_set_notify(const struct nft_ctx *ctx,
3184                                  const struct nft_set *set, int event,
3185                                  gfp_t gfp_flags)
3186 {
3187         struct sk_buff *skb;
3188         u32 portid = ctx->portid;
3189         int err;
3190
3191         if (!ctx->report &&
3192             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
3193                 return;
3194
3195         skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
3196         if (skb == NULL)
3197                 goto err;
3198
3199         err = nf_tables_fill_set(skb, ctx, set, event, 0);
3200         if (err < 0) {
3201                 kfree_skb(skb);
3202                 goto err;
3203         }
3204
3205         nfnetlink_send(skb, ctx->net, portid, NFNLGRP_NFTABLES, ctx->report,
3206                        gfp_flags);
3207         return;
3208 err:
3209         nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
3210 }
3211
3212 static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
3213 {
3214         const struct nft_set *set;
3215         unsigned int idx, s_idx = cb->args[0];
3216         struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
3217         struct net *net = sock_net(skb->sk);
3218         struct nft_ctx *ctx = cb->data, ctx_set;
3219
3220         if (cb->args[1])
3221                 return skb->len;
3222
3223         rcu_read_lock();
3224         cb->seq = net->nft.base_seq;
3225
3226         list_for_each_entry_rcu(table, &net->nft.tables, list) {
3227                 if (ctx->family != NFPROTO_UNSPEC &&
3228                     ctx->family != table->family)
3229                         continue;
3230
3231                 if (ctx->table && ctx->table != table)
3232                         continue;
3233
3234                 if (cur_table) {
3235                         if (cur_table != table)
3236                                 continue;
3237
3238                         cur_table = NULL;
3239                 }
3240                 idx = 0;
3241                 list_for_each_entry_rcu(set, &table->sets, list) {
3242                         if (idx < s_idx)
3243                                 goto cont;
3244                         if (!nft_is_active(net, set))
3245                                 goto cont;
3246
3247                         ctx_set = *ctx;
3248                         ctx_set.table = table;
3249                         ctx_set.family = table->family;
3250
3251                         if (nf_tables_fill_set(skb, &ctx_set, set,
3252                                                NFT_MSG_NEWSET,
3253                                                NLM_F_MULTI) < 0) {
3254                                 cb->args[0] = idx;
3255                                 cb->args[2] = (unsigned long) table;
3256                                 goto done;
3257                         }
3258                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
3259 cont:
3260                         idx++;
3261                 }
3262                 if (s_idx)
3263                         s_idx = 0;
3264         }
3265         cb->args[1] = 1;
3266 done:
3267         rcu_read_unlock();
3268         return skb->len;
3269 }
3270
3271 static int nf_tables_dump_sets_start(struct netlink_callback *cb)
3272 {
3273         struct nft_ctx *ctx_dump = NULL;
3274
3275         ctx_dump = kmemdup(cb->data, sizeof(*ctx_dump), GFP_ATOMIC);
3276         if (ctx_dump == NULL)
3277                 return -ENOMEM;
3278
3279         cb->data = ctx_dump;
3280         return 0;
3281 }
3282
3283 static int nf_tables_dump_sets_done(struct netlink_callback *cb)
3284 {
3285         kfree(cb->data);
3286         return 0;
3287 }
3288
3289 /* called with rcu_read_lock held */
3290 static int nf_tables_getset(struct net *net, struct sock *nlsk,
3291                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3292                             const struct nlattr * const nla[],
3293                             struct netlink_ext_ack *extack)
3294 {
3295         u8 genmask = nft_genmask_cur(net);
3296         const struct nft_set *set;
3297         struct nft_ctx ctx;
3298         struct sk_buff *skb2;
3299         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3300         int err;
3301
3302         /* Verify existence before starting dump */
3303         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3304                                         genmask);
3305         if (err < 0)
3306                 return err;
3307
3308         if (nlh->nlmsg_flags & NLM_F_DUMP) {
3309                 struct netlink_dump_control c = {
3310                         .start = nf_tables_dump_sets_start,
3311                         .dump = nf_tables_dump_sets,
3312                         .done = nf_tables_dump_sets_done,
3313                         .data = &ctx,
3314                         .module = THIS_MODULE,
3315                 };
3316
3317                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
3318         }
3319
3320         /* Only accept unspec with dump */
3321         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3322                 return -EAFNOSUPPORT;
3323         if (!nla[NFTA_SET_TABLE])
3324                 return -EINVAL;
3325
3326         set = nft_set_lookup(ctx.table, nla[NFTA_SET_NAME], genmask);
3327         if (IS_ERR(set))
3328                 return PTR_ERR(set);
3329
3330         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
3331         if (skb2 == NULL)
3332                 return -ENOMEM;
3333
3334         err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
3335         if (err < 0)
3336                 goto err;
3337
3338         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
3339
3340 err:
3341         kfree_skb(skb2);
3342         return err;
3343 }
3344
3345 static int nf_tables_set_desc_parse(const struct nft_ctx *ctx,
3346                                     struct nft_set_desc *desc,
3347                                     const struct nlattr *nla)
3348 {
3349         struct nlattr *da[NFTA_SET_DESC_MAX + 1];
3350         int err;
3351
3352         err = nla_parse_nested(da, NFTA_SET_DESC_MAX, nla,
3353                                nft_set_desc_policy, NULL);
3354         if (err < 0)
3355                 return err;
3356
3357         if (da[NFTA_SET_DESC_SIZE] != NULL)
3358                 desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
3359
3360         return 0;
3361 }
3362
3363 static int nf_tables_newset(struct net *net, struct sock *nlsk,
3364                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3365                             const struct nlattr * const nla[],
3366                             struct netlink_ext_ack *extack)
3367 {
3368         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3369         u8 genmask = nft_genmask_next(net);
3370         int family = nfmsg->nfgen_family;
3371         const struct nft_set_ops *ops;
3372         struct nft_table *table;
3373         struct nft_set *set;
3374         struct nft_ctx ctx;
3375         char *name;
3376         u64 size;
3377         u64 timeout;
3378         u32 ktype, dtype, flags, policy, gc_int, objtype;
3379         struct nft_set_desc desc;
3380         unsigned char *udata;
3381         u16 udlen;
3382         int err;
3383
3384         if (nla[NFTA_SET_TABLE] == NULL ||
3385             nla[NFTA_SET_NAME] == NULL ||
3386             nla[NFTA_SET_KEY_LEN] == NULL ||
3387             nla[NFTA_SET_ID] == NULL)
3388                 return -EINVAL;
3389
3390         memset(&desc, 0, sizeof(desc));
3391
3392         ktype = NFT_DATA_VALUE;
3393         if (nla[NFTA_SET_KEY_TYPE] != NULL) {
3394                 ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
3395                 if ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
3396                         return -EINVAL;
3397         }
3398
3399         desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
3400         if (desc.klen == 0 || desc.klen > NFT_DATA_VALUE_MAXLEN)
3401                 return -EINVAL;
3402
3403         flags = 0;
3404         if (nla[NFTA_SET_FLAGS] != NULL) {
3405                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
3406                 if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
3407                               NFT_SET_INTERVAL | NFT_SET_TIMEOUT |
3408                               NFT_SET_MAP | NFT_SET_EVAL |
3409                               NFT_SET_OBJECT))
3410                         return -EINVAL;
3411                 /* Only one of these operations is supported */
3412                 if ((flags & (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT)) ==
3413                              (NFT_SET_MAP | NFT_SET_EVAL | NFT_SET_OBJECT))
3414                         return -EOPNOTSUPP;
3415         }
3416
3417         dtype = 0;
3418         if (nla[NFTA_SET_DATA_TYPE] != NULL) {
3419                 if (!(flags & NFT_SET_MAP))
3420                         return -EINVAL;
3421
3422                 dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
3423                 if ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
3424                     dtype != NFT_DATA_VERDICT)
3425                         return -EINVAL;
3426
3427                 if (dtype != NFT_DATA_VERDICT) {
3428                         if (nla[NFTA_SET_DATA_LEN] == NULL)
3429                                 return -EINVAL;
3430                         desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
3431                         if (desc.dlen == 0 || desc.dlen > NFT_DATA_VALUE_MAXLEN)
3432                                 return -EINVAL;
3433                 } else
3434                         desc.dlen = sizeof(struct nft_verdict);
3435         } else if (flags & NFT_SET_MAP)
3436                 return -EINVAL;
3437
3438         if (nla[NFTA_SET_OBJ_TYPE] != NULL) {
3439                 if (!(flags & NFT_SET_OBJECT))
3440                         return -EINVAL;
3441
3442                 objtype = ntohl(nla_get_be32(nla[NFTA_SET_OBJ_TYPE]));
3443                 if (objtype == NFT_OBJECT_UNSPEC ||
3444                     objtype > NFT_OBJECT_MAX)
3445                         return -EINVAL;
3446         } else if (flags & NFT_SET_OBJECT)
3447                 return -EINVAL;
3448         else
3449                 objtype = NFT_OBJECT_UNSPEC;
3450
3451         timeout = 0;
3452         if (nla[NFTA_SET_TIMEOUT] != NULL) {
3453                 if (!(flags & NFT_SET_TIMEOUT))
3454                         return -EINVAL;
3455
3456                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_TIMEOUT], &timeout);
3457                 if (err)
3458                         return err;
3459         }
3460         gc_int = 0;
3461         if (nla[NFTA_SET_GC_INTERVAL] != NULL) {
3462                 if (!(flags & NFT_SET_TIMEOUT))
3463                         return -EINVAL;
3464                 gc_int = ntohl(nla_get_be32(nla[NFTA_SET_GC_INTERVAL]));
3465         }
3466
3467         policy = NFT_SET_POL_PERFORMANCE;
3468         if (nla[NFTA_SET_POLICY] != NULL)
3469                 policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
3470
3471         if (nla[NFTA_SET_DESC] != NULL) {
3472                 err = nf_tables_set_desc_parse(&ctx, &desc, nla[NFTA_SET_DESC]);
3473                 if (err < 0)
3474                         return err;
3475         }
3476
3477         table = nft_table_lookup(net, nla[NFTA_SET_TABLE], family, genmask);
3478         if (IS_ERR(table)) {
3479                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_TABLE]);
3480                 return PTR_ERR(table);
3481         }
3482
3483         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
3484
3485         set = nft_set_lookup(table, nla[NFTA_SET_NAME], genmask);
3486         if (IS_ERR(set)) {
3487                 if (PTR_ERR(set) != -ENOENT) {
3488                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3489                         return PTR_ERR(set);
3490                 }
3491         } else {
3492                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
3493                         NL_SET_BAD_ATTR(extack, nla[NFTA_SET_NAME]);
3494                         return -EEXIST;
3495                 }
3496                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
3497                         return -EOPNOTSUPP;
3498
3499                 return 0;
3500         }
3501
3502         if (!(nlh->nlmsg_flags & NLM_F_CREATE))
3503                 return -ENOENT;
3504
3505         ops = nft_select_set_ops(&ctx, nla, &desc, policy);
3506         if (IS_ERR(ops))
3507                 return PTR_ERR(ops);
3508
3509         udlen = 0;
3510         if (nla[NFTA_SET_USERDATA])
3511                 udlen = nla_len(nla[NFTA_SET_USERDATA]);
3512
3513         size = 0;
3514         if (ops->privsize != NULL)
3515                 size = ops->privsize(nla, &desc);
3516
3517         set = kvzalloc(sizeof(*set) + size + udlen, GFP_KERNEL);
3518         if (!set) {
3519                 err = -ENOMEM;
3520                 goto err1;
3521         }
3522
3523         name = nla_strdup(nla[NFTA_SET_NAME], GFP_KERNEL);
3524         if (!name) {
3525                 err = -ENOMEM;
3526                 goto err2;
3527         }
3528
3529         err = nf_tables_set_alloc_name(&ctx, set, name);
3530         kfree(name);
3531         if (err < 0)
3532                 goto err2;
3533
3534         udata = NULL;
3535         if (udlen) {
3536                 udata = set->data + size;
3537                 nla_memcpy(udata, nla[NFTA_SET_USERDATA], udlen);
3538         }
3539
3540         INIT_LIST_HEAD(&set->bindings);
3541         set->table = table;
3542         write_pnet(&set->net, net);
3543         set->ops   = ops;
3544         set->ktype = ktype;
3545         set->klen  = desc.klen;
3546         set->dtype = dtype;
3547         set->objtype = objtype;
3548         set->dlen  = desc.dlen;
3549         set->flags = flags;
3550         set->size  = desc.size;
3551         set->policy = policy;
3552         set->udlen  = udlen;
3553         set->udata  = udata;
3554         set->timeout = timeout;
3555         set->gc_int = gc_int;
3556         set->handle = nf_tables_alloc_handle(table);
3557
3558         err = ops->init(set, &desc, nla);
3559         if (err < 0)
3560                 goto err3;
3561
3562         err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
3563         if (err < 0)
3564                 goto err4;
3565
3566         list_add_tail_rcu(&set->list, &table->sets);
3567         table->use++;
3568         return 0;
3569
3570 err4:
3571         ops->destroy(set);
3572 err3:
3573         kfree(set->name);
3574 err2:
3575         kvfree(set);
3576 err1:
3577         module_put(to_set_type(ops)->owner);
3578         return err;
3579 }
3580
3581 static void nft_set_destroy(struct nft_set *set)
3582 {
3583         set->ops->destroy(set);
3584         module_put(to_set_type(set->ops)->owner);
3585         kfree(set->name);
3586         kvfree(set);
3587 }
3588
3589 static int nf_tables_delset(struct net *net, struct sock *nlsk,
3590                             struct sk_buff *skb, const struct nlmsghdr *nlh,
3591                             const struct nlattr * const nla[],
3592                             struct netlink_ext_ack *extack)
3593 {
3594         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3595         u8 genmask = nft_genmask_next(net);
3596         const struct nlattr *attr;
3597         struct nft_set *set;
3598         struct nft_ctx ctx;
3599         int err;
3600
3601         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
3602                 return -EAFNOSUPPORT;
3603         if (nla[NFTA_SET_TABLE] == NULL)
3604                 return -EINVAL;
3605
3606         err = nft_ctx_init_from_setattr(&ctx, net, skb, nlh, nla, extack,
3607                                         genmask);
3608         if (err < 0)
3609                 return err;
3610
3611         if (nla[NFTA_SET_HANDLE]) {
3612                 attr = nla[NFTA_SET_HANDLE];
3613                 set = nft_set_lookup_byhandle(ctx.table, attr, genmask);
3614         } else {
3615                 attr = nla[NFTA_SET_NAME];
3616                 set = nft_set_lookup(ctx.table, attr, genmask);
3617         }
3618
3619         if (IS_ERR(set)) {
3620                 NL_SET_BAD_ATTR(extack, attr);
3621                 return PTR_ERR(set);
3622         }
3623         if (!list_empty(&set->bindings) ||
3624             (nlh->nlmsg_flags & NLM_F_NONREC && atomic_read(&set->nelems) > 0)) {
3625                 NL_SET_BAD_ATTR(extack, attr);
3626                 return -EBUSY;
3627         }
3628
3629         return nft_delset(&ctx, set);
3630 }
3631
3632 static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
3633                                         struct nft_set *set,
3634                                         const struct nft_set_iter *iter,
3635                                         struct nft_set_elem *elem)
3636 {
3637         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3638         enum nft_registers dreg;
3639
3640         dreg = nft_type_to_reg(set->dtype);
3641         return nft_validate_register_store(ctx, dreg, nft_set_ext_data(ext),
3642                                            set->dtype == NFT_DATA_VERDICT ?
3643                                            NFT_DATA_VERDICT : NFT_DATA_VALUE,
3644                                            set->dlen);
3645 }
3646
3647 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
3648                        struct nft_set_binding *binding)
3649 {
3650         struct nft_set_binding *i;
3651         struct nft_set_iter iter;
3652
3653         if (!list_empty(&set->bindings) && nft_set_is_anonymous(set))
3654                 return -EBUSY;
3655
3656         if (binding->flags & NFT_SET_MAP) {
3657                 /* If the set is already bound to the same chain all
3658                  * jumps are already validated for that chain.
3659                  */
3660                 list_for_each_entry(i, &set->bindings, list) {
3661                         if (i->flags & NFT_SET_MAP &&
3662                             i->chain == binding->chain)
3663                                 goto bind;
3664                 }
3665
3666                 iter.genmask    = nft_genmask_next(ctx->net);
3667                 iter.skip       = 0;
3668                 iter.count      = 0;
3669                 iter.err        = 0;
3670                 iter.fn         = nf_tables_bind_check_setelem;
3671
3672                 set->ops->walk(ctx, set, &iter);
3673                 if (iter.err < 0)
3674                         return iter.err;
3675         }
3676 bind:
3677         binding->chain = ctx->chain;
3678         list_add_tail_rcu(&binding->list, &set->bindings);
3679         return 0;
3680 }
3681 EXPORT_SYMBOL_GPL(nf_tables_bind_set);
3682
3683 void nf_tables_rebind_set(const struct nft_ctx *ctx, struct nft_set *set,
3684                           struct nft_set_binding *binding)
3685 {
3686         if (list_empty(&set->bindings) && nft_set_is_anonymous(set) &&
3687             nft_is_active(ctx->net, set))
3688                 list_add_tail_rcu(&set->list, &ctx->table->sets);
3689
3690         list_add_tail_rcu(&binding->list, &set->bindings);
3691 }
3692 EXPORT_SYMBOL_GPL(nf_tables_rebind_set);
3693
3694 void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
3695                           struct nft_set_binding *binding)
3696 {
3697         list_del_rcu(&binding->list);
3698
3699         if (list_empty(&set->bindings) && nft_set_is_anonymous(set) &&
3700             nft_is_active(ctx->net, set))
3701                 list_del_rcu(&set->list);
3702 }
3703 EXPORT_SYMBOL_GPL(nf_tables_unbind_set);
3704
3705 void nf_tables_destroy_set(const struct nft_ctx *ctx, struct nft_set *set)
3706 {
3707         if (list_empty(&set->bindings) && nft_set_is_anonymous(set) &&
3708             nft_is_active(ctx->net, set)) {
3709                 nf_tables_set_notify(ctx, set, NFT_MSG_DELSET, GFP_ATOMIC);
3710                 nft_set_destroy(set);
3711         }
3712 }
3713 EXPORT_SYMBOL_GPL(nf_tables_destroy_set);
3714
3715 const struct nft_set_ext_type nft_set_ext_types[] = {
3716         [NFT_SET_EXT_KEY]               = {
3717                 .align  = __alignof__(u32),
3718         },
3719         [NFT_SET_EXT_DATA]              = {
3720                 .align  = __alignof__(u32),
3721         },
3722         [NFT_SET_EXT_EXPR]              = {
3723                 .align  = __alignof__(struct nft_expr),
3724         },
3725         [NFT_SET_EXT_OBJREF]            = {
3726                 .len    = sizeof(struct nft_object *),
3727                 .align  = __alignof__(struct nft_object *),
3728         },
3729         [NFT_SET_EXT_FLAGS]             = {
3730                 .len    = sizeof(u8),
3731                 .align  = __alignof__(u8),
3732         },
3733         [NFT_SET_EXT_TIMEOUT]           = {
3734                 .len    = sizeof(u64),
3735                 .align  = __alignof__(u64),
3736         },
3737         [NFT_SET_EXT_EXPIRATION]        = {
3738                 .len    = sizeof(u64),
3739                 .align  = __alignof__(u64),
3740         },
3741         [NFT_SET_EXT_USERDATA]          = {
3742                 .len    = sizeof(struct nft_userdata),
3743                 .align  = __alignof__(struct nft_userdata),
3744         },
3745 };
3746 EXPORT_SYMBOL_GPL(nft_set_ext_types);
3747
3748 /*
3749  * Set elements
3750  */
3751
3752 static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
3753         [NFTA_SET_ELEM_KEY]             = { .type = NLA_NESTED },
3754         [NFTA_SET_ELEM_DATA]            = { .type = NLA_NESTED },
3755         [NFTA_SET_ELEM_FLAGS]           = { .type = NLA_U32 },
3756         [NFTA_SET_ELEM_TIMEOUT]         = { .type = NLA_U64 },
3757         [NFTA_SET_ELEM_USERDATA]        = { .type = NLA_BINARY,
3758                                             .len = NFT_USERDATA_MAXLEN },
3759         [NFTA_SET_ELEM_EXPR]            = { .type = NLA_NESTED },
3760         [NFTA_SET_ELEM_OBJREF]          = { .type = NLA_STRING },
3761 };
3762
3763 static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
3764         [NFTA_SET_ELEM_LIST_TABLE]      = { .type = NLA_STRING,
3765                                             .len = NFT_TABLE_MAXNAMELEN - 1 },
3766         [NFTA_SET_ELEM_LIST_SET]        = { .type = NLA_STRING,
3767                                             .len = NFT_SET_MAXNAMELEN - 1 },
3768         [NFTA_SET_ELEM_LIST_ELEMENTS]   = { .type = NLA_NESTED },
3769         [NFTA_SET_ELEM_LIST_SET_ID]     = { .type = NLA_U32 },
3770 };
3771
3772 static int nft_ctx_init_from_elemattr(struct nft_ctx *ctx, struct net *net,
3773                                       const struct sk_buff *skb,
3774                                       const struct nlmsghdr *nlh,
3775                                       const struct nlattr * const nla[],
3776                                       struct netlink_ext_ack *extack,
3777                                       u8 genmask)
3778 {
3779         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
3780         int family = nfmsg->nfgen_family;
3781         struct nft_table *table;
3782
3783         table = nft_table_lookup(net, nla[NFTA_SET_ELEM_LIST_TABLE], family,
3784                                  genmask);
3785         if (IS_ERR(table)) {
3786                 NL_SET_BAD_ATTR(extack, nla[NFTA_SET_ELEM_LIST_TABLE]);
3787                 return PTR_ERR(table);
3788         }
3789
3790         nft_ctx_init(ctx, net, skb, nlh, family, table, NULL, nla);
3791         return 0;
3792 }
3793
3794 static int nf_tables_fill_setelem(struct sk_buff *skb,
3795                                   const struct nft_set *set,
3796                                   const struct nft_set_elem *elem)
3797 {
3798         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
3799         unsigned char *b = skb_tail_pointer(skb);
3800         struct nlattr *nest;
3801
3802         nest = nla_nest_start(skb, NFTA_LIST_ELEM);
3803         if (nest == NULL)
3804                 goto nla_put_failure;
3805
3806         if (nft_data_dump(skb, NFTA_SET_ELEM_KEY, nft_set_ext_key(ext),
3807                           NFT_DATA_VALUE, set->klen) < 0)
3808                 goto nla_put_failure;
3809
3810         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
3811             nft_data_dump(skb, NFTA_SET_ELEM_DATA, nft_set_ext_data(ext),
3812                           set->dtype == NFT_DATA_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE,
3813                           set->dlen) < 0)
3814                 goto nla_put_failure;
3815
3816         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR) &&
3817             nft_expr_dump(skb, NFTA_SET_ELEM_EXPR, nft_set_ext_expr(ext)) < 0)
3818                 goto nla_put_failure;
3819
3820         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
3821             nla_put_string(skb, NFTA_SET_ELEM_OBJREF,
3822                            (*nft_set_ext_obj(ext))->name) < 0)
3823                 goto nla_put_failure;
3824
3825         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
3826             nla_put_be32(skb, NFTA_SET_ELEM_FLAGS,
3827                          htonl(*nft_set_ext_flags(ext))))
3828                 goto nla_put_failure;
3829
3830         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT) &&
3831             nla_put_be64(skb, NFTA_SET_ELEM_TIMEOUT,
3832                          nf_jiffies64_to_msecs(*nft_set_ext_timeout(ext)),
3833                          NFTA_SET_ELEM_PAD))
3834                 goto nla_put_failure;
3835
3836         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION)) {
3837                 u64 expires, now = get_jiffies_64();
3838
3839                 expires = *nft_set_ext_expiration(ext);
3840                 if (time_before64(now, expires))
3841                         expires -= now;
3842                 else
3843                         expires = 0;
3844
3845                 if (nla_put_be64(skb, NFTA_SET_ELEM_EXPIRATION,
3846                                  nf_jiffies64_to_msecs(expires),
3847                                  NFTA_SET_ELEM_PAD))
3848                         goto nla_put_failure;
3849         }
3850
3851         if (nft_set_ext_exists(ext, NFT_SET_EXT_USERDATA)) {
3852                 struct nft_userdata *udata;
3853
3854                 udata = nft_set_ext_userdata(ext);
3855                 if (nla_put(skb, NFTA_SET_ELEM_USERDATA,
3856                             udata->len + 1, udata->data))
3857                         goto nla_put_failure;
3858         }
3859
3860         nla_nest_end(skb, nest);
3861         return 0;
3862
3863 nla_put_failure:
3864         nlmsg_trim(skb, b);
3865         return -EMSGSIZE;
3866 }
3867
3868 struct nft_set_dump_args {
3869         const struct netlink_callback   *cb;
3870         struct nft_set_iter             iter;
3871         struct sk_buff                  *skb;
3872 };
3873
3874 static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
3875                                   struct nft_set *set,
3876                                   const struct nft_set_iter *iter,
3877                                   struct nft_set_elem *elem)
3878 {
3879         struct nft_set_dump_args *args;
3880
3881         args = container_of(iter, struct nft_set_dump_args, iter);
3882         return nf_tables_fill_setelem(args->skb, set, elem);
3883 }
3884
3885 struct nft_set_dump_ctx {
3886         const struct nft_set    *set;
3887         struct nft_ctx          ctx;
3888 };
3889
3890 static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
3891 {
3892         struct nft_set_dump_ctx *dump_ctx = cb->data;
3893         struct net *net = sock_net(skb->sk);
3894         struct nft_table *table;
3895         struct nft_set *set;
3896         struct nft_set_dump_args args;
3897         bool set_found = false;
3898         struct nfgenmsg *nfmsg;
3899         struct nlmsghdr *nlh;
3900         struct nlattr *nest;
3901         u32 portid, seq;
3902         int event;
3903
3904         rcu_read_lock();
3905         list_for_each_entry_rcu(table, &net->nft.tables, list) {
3906                 if (dump_ctx->ctx.family != NFPROTO_UNSPEC &&
3907                     dump_ctx->ctx.family != table->family)
3908                         continue;
3909
3910                 if (table != dump_ctx->ctx.table)
3911                         continue;
3912
3913                 list_for_each_entry_rcu(set, &table->sets, list) {
3914                         if (set == dump_ctx->set) {
3915                                 set_found = true;
3916                                 break;
3917                         }
3918                 }
3919                 break;
3920         }
3921
3922         if (!set_found) {
3923                 rcu_read_unlock();
3924                 return -ENOENT;
3925         }
3926
3927         event  = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWSETELEM);
3928         portid = NETLINK_CB(cb->skb).portid;
3929         seq    = cb->nlh->nlmsg_seq;
3930
3931         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3932                         NLM_F_MULTI);
3933         if (nlh == NULL)
3934                 goto nla_put_failure;
3935
3936         nfmsg = nlmsg_data(nlh);
3937         nfmsg->nfgen_family = table->family;
3938         nfmsg->version      = NFNETLINK_V0;
3939         nfmsg->res_id       = htons(net->nft.base_seq & 0xffff);
3940
3941         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, table->name))
3942                 goto nla_put_failure;
3943         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
3944                 goto nla_put_failure;
3945
3946         nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
3947         if (nest == NULL)
3948                 goto nla_put_failure;
3949
3950         args.cb                 = cb;
3951         args.skb                = skb;
3952         args.iter.genmask       = nft_genmask_cur(net);
3953         args.iter.skip          = cb->args[0];
3954         args.iter.count         = 0;
3955         args.iter.err           = 0;
3956         args.iter.fn            = nf_tables_dump_setelem;
3957         set->ops->walk(&dump_ctx->ctx, set, &args.iter);
3958         rcu_read_unlock();
3959
3960         nla_nest_end(skb, nest);
3961         nlmsg_end(skb, nlh);
3962
3963         if (args.iter.err && args.iter.err != -EMSGSIZE)
3964                 return args.iter.err;
3965         if (args.iter.count == cb->args[0])
3966                 return 0;
3967
3968         cb->args[0] = args.iter.count;
3969         return skb->len;
3970
3971 nla_put_failure:
3972         rcu_read_unlock();
3973         return -ENOSPC;
3974 }
3975
3976 static int nf_tables_dump_set_start(struct netlink_callback *cb)
3977 {
3978         struct nft_set_dump_ctx *dump_ctx = cb->data;
3979
3980         cb->data = kmemdup(dump_ctx, sizeof(*dump_ctx), GFP_ATOMIC);
3981
3982         return cb->data ? 0 : -ENOMEM;
3983 }
3984
3985 static int nf_tables_dump_set_done(struct netlink_callback *cb)
3986 {
3987         kfree(cb->data);
3988         return 0;
3989 }
3990
3991 static int nf_tables_fill_setelem_info(struct sk_buff *skb,
3992                                        const struct nft_ctx *ctx, u32 seq,
3993                                        u32 portid, int event, u16 flags,
3994                                        const struct nft_set *set,
3995                                        const struct nft_set_elem *elem)
3996 {
3997         struct nfgenmsg *nfmsg;
3998         struct nlmsghdr *nlh;
3999         struct nlattr *nest;
4000         int err;
4001
4002         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
4003         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
4004                         flags);
4005         if (nlh == NULL)
4006                 goto nla_put_failure;
4007
4008         nfmsg = nlmsg_data(nlh);
4009         nfmsg->nfgen_family     = ctx->family;
4010         nfmsg->version          = NFNETLINK_V0;
4011         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
4012
4013         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
4014                 goto nla_put_failure;
4015         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
4016                 goto nla_put_failure;
4017
4018         nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
4019         if (nest == NULL)
4020                 goto nla_put_failure;
4021
4022         err = nf_tables_fill_setelem(skb, set, elem);
4023         if (err < 0)
4024                 goto nla_put_failure;
4025
4026         nla_nest_end(skb, nest);
4027
4028         nlmsg_end(skb, nlh);
4029         return 0;
4030
4031 nla_put_failure:
4032         nlmsg_trim(skb, nlh);
4033         return -1;
4034 }
4035
4036 static int nft_setelem_parse_flags(const struct nft_set *set,
4037                                    const struct nlattr *attr, u32 *flags)
4038 {
4039         if (attr == NULL)
4040                 return 0;
4041
4042         *flags = ntohl(nla_get_be32(attr));
4043         if (*flags & ~NFT_SET_ELEM_INTERVAL_END)
4044                 return -EINVAL;
4045         if (!(set->flags & NFT_SET_INTERVAL) &&
4046             *flags & NFT_SET_ELEM_INTERVAL_END)
4047                 return -EINVAL;
4048
4049         return 0;
4050 }
4051
4052 static int nft_get_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4053                             const struct nlattr *attr)
4054 {
4055         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4056         struct nft_data_desc desc;
4057         struct nft_set_elem elem;
4058         struct sk_buff *skb;
4059         uint32_t flags = 0;
4060         void *priv;
4061         int err;
4062
4063         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
4064                                nft_set_elem_policy, NULL);
4065         if (err < 0)
4066                 return err;
4067
4068         if (!nla[NFTA_SET_ELEM_KEY])
4069                 return -EINVAL;
4070
4071         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4072         if (err < 0)
4073                 return err;
4074
4075         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4076                             nla[NFTA_SET_ELEM_KEY]);
4077         if (err < 0)
4078                 return err;
4079
4080         err = -EINVAL;
4081         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4082                 return err;
4083
4084         priv = set->ops->get(ctx->net, set, &elem, flags);
4085         if (IS_ERR(priv))
4086                 return PTR_ERR(priv);
4087
4088         elem.priv = priv;
4089
4090         err = -ENOMEM;
4091         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_ATOMIC);
4092         if (skb == NULL)
4093                 goto err1;
4094
4095         err = nf_tables_fill_setelem_info(skb, ctx, ctx->seq, ctx->portid,
4096                                           NFT_MSG_NEWSETELEM, 0, set, &elem);
4097         if (err < 0)
4098                 goto err2;
4099
4100         err = nfnetlink_unicast(skb, ctx->net, ctx->portid, MSG_DONTWAIT);
4101         /* This avoids a loop in nfnetlink. */
4102         if (err < 0)
4103                 goto err1;
4104
4105         return 0;
4106 err2:
4107         kfree_skb(skb);
4108 err1:
4109         /* this avoids a loop in nfnetlink. */
4110         return err == -EAGAIN ? -ENOBUFS : err;
4111 }
4112
4113 /* called with rcu_read_lock held */
4114 static int nf_tables_getsetelem(struct net *net, struct sock *nlsk,
4115                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4116                                 const struct nlattr * const nla[],
4117                                 struct netlink_ext_ack *extack)
4118 {
4119         u8 genmask = nft_genmask_cur(net);
4120         struct nft_set *set;
4121         struct nlattr *attr;
4122         struct nft_ctx ctx;
4123         int rem, err = 0;
4124
4125         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4126                                          genmask);
4127         if (err < 0)
4128                 return err;
4129
4130         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4131         if (IS_ERR(set))
4132                 return PTR_ERR(set);
4133
4134         if (nlh->nlmsg_flags & NLM_F_DUMP) {
4135                 struct netlink_dump_control c = {
4136                         .start = nf_tables_dump_set_start,
4137                         .dump = nf_tables_dump_set,
4138                         .done = nf_tables_dump_set_done,
4139                         .module = THIS_MODULE,
4140                 };
4141                 struct nft_set_dump_ctx dump_ctx = {
4142                         .set = set,
4143                         .ctx = ctx,
4144                 };
4145
4146                 c.data = &dump_ctx;
4147                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
4148         }
4149
4150         if (!nla[NFTA_SET_ELEM_LIST_ELEMENTS])
4151                 return -EINVAL;
4152
4153         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4154                 err = nft_get_set_elem(&ctx, set, attr);
4155                 if (err < 0)
4156                         break;
4157         }
4158
4159         return err;
4160 }
4161
4162 static void nf_tables_setelem_notify(const struct nft_ctx *ctx,
4163                                      const struct nft_set *set,
4164                                      const struct nft_set_elem *elem,
4165                                      int event, u16 flags)
4166 {
4167         struct net *net = ctx->net;
4168         u32 portid = ctx->portid;
4169         struct sk_buff *skb;
4170         int err;
4171
4172         if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
4173                 return;
4174
4175         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
4176         if (skb == NULL)
4177                 goto err;
4178
4179         err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
4180                                           set, elem);
4181         if (err < 0) {
4182                 kfree_skb(skb);
4183                 goto err;
4184         }
4185
4186         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, ctx->report,
4187                        GFP_KERNEL);
4188         return;
4189 err:
4190         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
4191 }
4192
4193 static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
4194                                               int msg_type,
4195                                               struct nft_set *set)
4196 {
4197         struct nft_trans *trans;
4198
4199         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
4200         if (trans == NULL)
4201                 return NULL;
4202
4203         nft_trans_elem_set(trans) = set;
4204         return trans;
4205 }
4206
4207 void *nft_set_elem_init(const struct nft_set *set,
4208                         const struct nft_set_ext_tmpl *tmpl,
4209                         const u32 *key, const u32 *data,
4210                         u64 timeout, gfp_t gfp)
4211 {
4212         struct nft_set_ext *ext;
4213         void *elem;
4214
4215         elem = kzalloc(set->ops->elemsize + tmpl->len, gfp);
4216         if (elem == NULL)
4217                 return NULL;
4218
4219         ext = nft_set_elem_ext(set, elem);
4220         nft_set_ext_init(ext, tmpl);
4221
4222         memcpy(nft_set_ext_key(ext), key, set->klen);
4223         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4224                 memcpy(nft_set_ext_data(ext), data, set->dlen);
4225         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPIRATION))
4226                 *nft_set_ext_expiration(ext) =
4227                         get_jiffies_64() + timeout;
4228         if (nft_set_ext_exists(ext, NFT_SET_EXT_TIMEOUT))
4229                 *nft_set_ext_timeout(ext) = timeout;
4230
4231         return elem;
4232 }
4233
4234 void nft_set_elem_destroy(const struct nft_set *set, void *elem,
4235                           bool destroy_expr)
4236 {
4237         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4238         struct nft_ctx ctx = {
4239                 .net    = read_pnet(&set->net),
4240                 .family = set->table->family,
4241         };
4242
4243         nft_data_release(nft_set_ext_key(ext), NFT_DATA_VALUE);
4244         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4245                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4246         if (destroy_expr && nft_set_ext_exists(ext, NFT_SET_EXT_EXPR)) {
4247                 struct nft_expr *expr = nft_set_ext_expr(ext);
4248
4249                 if (expr->ops->destroy_clone) {
4250                         expr->ops->destroy_clone(&ctx, expr);
4251                         module_put(expr->ops->type->owner);
4252                 } else {
4253                         nf_tables_expr_destroy(&ctx, expr);
4254                 }
4255         }
4256         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4257                 (*nft_set_ext_obj(ext))->use--;
4258         kfree(elem);
4259 }
4260 EXPORT_SYMBOL_GPL(nft_set_elem_destroy);
4261
4262 /* Only called from commit path, nft_set_elem_deactivate() already deals with
4263  * the refcounting from the preparation phase.
4264  */
4265 static void nf_tables_set_elem_destroy(const struct nft_ctx *ctx,
4266                                        const struct nft_set *set, void *elem)
4267 {
4268         struct nft_set_ext *ext = nft_set_elem_ext(set, elem);
4269
4270         if (nft_set_ext_exists(ext, NFT_SET_EXT_EXPR))
4271                 nf_tables_expr_destroy(ctx, nft_set_ext_expr(ext));
4272         kfree(elem);
4273 }
4274
4275 static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
4276                             const struct nlattr *attr, u32 nlmsg_flags)
4277 {
4278         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4279         u8 genmask = nft_genmask_next(ctx->net);
4280         struct nft_data_desc d1, d2;
4281         struct nft_set_ext_tmpl tmpl;
4282         struct nft_set_ext *ext, *ext2;
4283         struct nft_set_elem elem;
4284         struct nft_set_binding *binding;
4285         struct nft_object *obj = NULL;
4286         struct nft_userdata *udata;
4287         struct nft_data data;
4288         enum nft_registers dreg;
4289         struct nft_trans *trans;
4290         u32 flags = 0;
4291         u64 timeout;
4292         u8 ulen;
4293         int err;
4294
4295         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
4296                                nft_set_elem_policy, NULL);
4297         if (err < 0)
4298                 return err;
4299
4300         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4301                 return -EINVAL;
4302
4303         nft_set_ext_prepare(&tmpl);
4304
4305         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4306         if (err < 0)
4307                 return err;
4308         if (flags != 0)
4309                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4310
4311         if (set->flags & NFT_SET_MAP) {
4312                 if (nla[NFTA_SET_ELEM_DATA] == NULL &&
4313                     !(flags & NFT_SET_ELEM_INTERVAL_END))
4314                         return -EINVAL;
4315                 if (nla[NFTA_SET_ELEM_DATA] != NULL &&
4316                     flags & NFT_SET_ELEM_INTERVAL_END)
4317                         return -EINVAL;
4318         } else {
4319                 if (nla[NFTA_SET_ELEM_DATA] != NULL)
4320                         return -EINVAL;
4321         }
4322
4323         timeout = 0;
4324         if (nla[NFTA_SET_ELEM_TIMEOUT] != NULL) {
4325                 if (!(set->flags & NFT_SET_TIMEOUT))
4326                         return -EINVAL;
4327                 err = nf_msecs_to_jiffies64(nla[NFTA_SET_ELEM_TIMEOUT],
4328                                             &timeout);
4329                 if (err)
4330                         return err;
4331         } else if (set->flags & NFT_SET_TIMEOUT) {
4332                 timeout = set->timeout;
4333         }
4334
4335         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &d1,
4336                             nla[NFTA_SET_ELEM_KEY]);
4337         if (err < 0)
4338                 goto err1;
4339         err = -EINVAL;
4340         if (d1.type != NFT_DATA_VALUE || d1.len != set->klen)
4341                 goto err2;
4342
4343         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, d1.len);
4344         if (timeout > 0) {
4345                 nft_set_ext_add(&tmpl, NFT_SET_EXT_EXPIRATION);
4346                 if (timeout != set->timeout)
4347                         nft_set_ext_add(&tmpl, NFT_SET_EXT_TIMEOUT);
4348         }
4349
4350         if (nla[NFTA_SET_ELEM_OBJREF] != NULL) {
4351                 if (!(set->flags & NFT_SET_OBJECT)) {
4352                         err = -EINVAL;
4353                         goto err2;
4354                 }
4355                 obj = nft_obj_lookup(ctx->table, nla[NFTA_SET_ELEM_OBJREF],
4356                                      set->objtype, genmask);
4357                 if (IS_ERR(obj)) {
4358                         err = PTR_ERR(obj);
4359                         goto err2;
4360                 }
4361                 nft_set_ext_add(&tmpl, NFT_SET_EXT_OBJREF);
4362         }
4363
4364         if (nla[NFTA_SET_ELEM_DATA] != NULL) {
4365                 err = nft_data_init(ctx, &data, sizeof(data), &d2,
4366                                     nla[NFTA_SET_ELEM_DATA]);
4367                 if (err < 0)
4368                         goto err2;
4369
4370                 err = -EINVAL;
4371                 if (set->dtype != NFT_DATA_VERDICT && d2.len != set->dlen)
4372                         goto err3;
4373
4374                 dreg = nft_type_to_reg(set->dtype);
4375                 list_for_each_entry(binding, &set->bindings, list) {
4376                         struct nft_ctx bind_ctx = {
4377                                 .net    = ctx->net,
4378                                 .family = ctx->family,
4379                                 .table  = ctx->table,
4380                                 .chain  = (struct nft_chain *)binding->chain,
4381                         };
4382
4383                         if (!(binding->flags & NFT_SET_MAP))
4384                                 continue;
4385
4386                         err = nft_validate_register_store(&bind_ctx, dreg,
4387                                                           &data,
4388                                                           d2.type, d2.len);
4389                         if (err < 0)
4390                                 goto err3;
4391
4392                         if (d2.type == NFT_DATA_VERDICT &&
4393                             (data.verdict.code == NFT_GOTO ||
4394                              data.verdict.code == NFT_JUMP))
4395                                 nft_validate_state_update(ctx->net,
4396                                                           NFT_VALIDATE_NEED);
4397                 }
4398
4399                 nft_set_ext_add_length(&tmpl, NFT_SET_EXT_DATA, d2.len);
4400         }
4401
4402         /* The full maximum length of userdata can exceed the maximum
4403          * offset value (U8_MAX) for following extensions, therefor it
4404          * must be the last extension added.
4405          */
4406         ulen = 0;
4407         if (nla[NFTA_SET_ELEM_USERDATA] != NULL) {
4408                 ulen = nla_len(nla[NFTA_SET_ELEM_USERDATA]);
4409                 if (ulen > 0)
4410                         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_USERDATA,
4411                                                ulen);
4412         }
4413
4414         err = -ENOMEM;
4415         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, data.data,
4416                                       timeout, GFP_KERNEL);
4417         if (elem.priv == NULL)
4418                 goto err3;
4419
4420         ext = nft_set_elem_ext(set, elem.priv);
4421         if (flags)
4422                 *nft_set_ext_flags(ext) = flags;
4423         if (ulen > 0) {
4424                 udata = nft_set_ext_userdata(ext);
4425                 udata->len = ulen - 1;
4426                 nla_memcpy(&udata->data, nla[NFTA_SET_ELEM_USERDATA], ulen);
4427         }
4428         if (obj) {
4429                 *nft_set_ext_obj(ext) = obj;
4430                 obj->use++;
4431         }
4432
4433         trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
4434         if (trans == NULL)
4435                 goto err4;
4436
4437         ext->genmask = nft_genmask_cur(ctx->net) | NFT_SET_ELEM_BUSY_MASK;
4438         err = set->ops->insert(ctx->net, set, &elem, &ext2);
4439         if (err) {
4440                 if (err == -EEXIST) {
4441                         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA) ^
4442                             nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) ||
4443                             nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) ^
4444                             nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF)) {
4445                                 err = -EBUSY;
4446                                 goto err5;
4447                         }
4448                         if ((nft_set_ext_exists(ext, NFT_SET_EXT_DATA) &&
4449                              nft_set_ext_exists(ext2, NFT_SET_EXT_DATA) &&
4450                              memcmp(nft_set_ext_data(ext),
4451                                     nft_set_ext_data(ext2), set->dlen) != 0) ||
4452                             (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF) &&
4453                              nft_set_ext_exists(ext2, NFT_SET_EXT_OBJREF) &&
4454                              *nft_set_ext_obj(ext) != *nft_set_ext_obj(ext2)))
4455                                 err = -EBUSY;
4456                         else if (!(nlmsg_flags & NLM_F_EXCL))
4457                                 err = 0;
4458                 }
4459                 goto err5;
4460         }
4461
4462         if (set->size &&
4463             !atomic_add_unless(&set->nelems, 1, set->size + set->ndeact)) {
4464                 err = -ENFILE;
4465                 goto err6;
4466         }
4467
4468         nft_trans_elem(trans) = elem;
4469         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4470         return 0;
4471
4472 err6:
4473         set->ops->remove(ctx->net, set, &elem);
4474 err5:
4475         kfree(trans);
4476 err4:
4477         kfree(elem.priv);
4478 err3:
4479         if (nla[NFTA_SET_ELEM_DATA] != NULL)
4480                 nft_data_release(&data, d2.type);
4481 err2:
4482         nft_data_release(&elem.key.val, d1.type);
4483 err1:
4484         return err;
4485 }
4486
4487 static int nf_tables_newsetelem(struct net *net, struct sock *nlsk,
4488                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4489                                 const struct nlattr * const nla[],
4490                                 struct netlink_ext_ack *extack)
4491 {
4492         u8 genmask = nft_genmask_next(net);
4493         const struct nlattr *attr;
4494         struct nft_set *set;
4495         struct nft_ctx ctx;
4496         int rem, err;
4497
4498         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
4499                 return -EINVAL;
4500
4501         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4502                                          genmask);
4503         if (err < 0)
4504                 return err;
4505
4506         set = nft_set_lookup_global(net, ctx.table, nla[NFTA_SET_ELEM_LIST_SET],
4507                                     nla[NFTA_SET_ELEM_LIST_SET_ID], genmask);
4508         if (IS_ERR(set))
4509                 return PTR_ERR(set);
4510
4511         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4512                 return -EBUSY;
4513
4514         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4515                 err = nft_add_set_elem(&ctx, set, attr, nlh->nlmsg_flags);
4516                 if (err < 0)
4517                         return err;
4518         }
4519
4520         if (net->nft.validate_state == NFT_VALIDATE_DO)
4521                 return nft_table_validate(net, ctx.table);
4522
4523         return 0;
4524 }
4525
4526 /**
4527  *      nft_data_hold - hold a nft_data item
4528  *
4529  *      @data: struct nft_data to release
4530  *      @type: type of data
4531  *
4532  *      Hold a nft_data item. NFT_DATA_VALUE types can be silently discarded,
4533  *      NFT_DATA_VERDICT bumps the reference to chains in case of NFT_JUMP and
4534  *      NFT_GOTO verdicts. This function must be called on active data objects
4535  *      from the second phase of the commit protocol.
4536  */
4537 void nft_data_hold(const struct nft_data *data, enum nft_data_types type)
4538 {
4539         if (type == NFT_DATA_VERDICT) {
4540                 switch (data->verdict.code) {
4541                 case NFT_JUMP:
4542                 case NFT_GOTO:
4543                         data->verdict.chain->use++;
4544                         break;
4545                 }
4546         }
4547 }
4548
4549 static void nft_set_elem_activate(const struct net *net,
4550                                   const struct nft_set *set,
4551                                   struct nft_set_elem *elem)
4552 {
4553         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4554
4555         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4556                 nft_data_hold(nft_set_ext_data(ext), set->dtype);
4557         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4558                 (*nft_set_ext_obj(ext))->use++;
4559 }
4560
4561 static void nft_set_elem_deactivate(const struct net *net,
4562                                     const struct nft_set *set,
4563                                     struct nft_set_elem *elem)
4564 {
4565         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
4566
4567         if (nft_set_ext_exists(ext, NFT_SET_EXT_DATA))
4568                 nft_data_release(nft_set_ext_data(ext), set->dtype);
4569         if (nft_set_ext_exists(ext, NFT_SET_EXT_OBJREF))
4570                 (*nft_set_ext_obj(ext))->use--;
4571 }
4572
4573 static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
4574                            const struct nlattr *attr)
4575 {
4576         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
4577         struct nft_set_ext_tmpl tmpl;
4578         struct nft_data_desc desc;
4579         struct nft_set_elem elem;
4580         struct nft_set_ext *ext;
4581         struct nft_trans *trans;
4582         u32 flags = 0;
4583         void *priv;
4584         int err;
4585
4586         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
4587                                nft_set_elem_policy, NULL);
4588         if (err < 0)
4589                 goto err1;
4590
4591         err = -EINVAL;
4592         if (nla[NFTA_SET_ELEM_KEY] == NULL)
4593                 goto err1;
4594
4595         nft_set_ext_prepare(&tmpl);
4596
4597         err = nft_setelem_parse_flags(set, nla[NFTA_SET_ELEM_FLAGS], &flags);
4598         if (err < 0)
4599                 return err;
4600         if (flags != 0)
4601                 nft_set_ext_add(&tmpl, NFT_SET_EXT_FLAGS);
4602
4603         err = nft_data_init(ctx, &elem.key.val, sizeof(elem.key), &desc,
4604                             nla[NFTA_SET_ELEM_KEY]);
4605         if (err < 0)
4606                 goto err1;
4607
4608         err = -EINVAL;
4609         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
4610                 goto err2;
4611
4612         nft_set_ext_add_length(&tmpl, NFT_SET_EXT_KEY, desc.len);
4613
4614         err = -ENOMEM;
4615         elem.priv = nft_set_elem_init(set, &tmpl, elem.key.val.data, NULL, 0,
4616                                       GFP_KERNEL);
4617         if (elem.priv == NULL)
4618                 goto err2;
4619
4620         ext = nft_set_elem_ext(set, elem.priv);
4621         if (flags)
4622                 *nft_set_ext_flags(ext) = flags;
4623
4624         trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
4625         if (trans == NULL) {
4626                 err = -ENOMEM;
4627                 goto err3;
4628         }
4629
4630         priv = set->ops->deactivate(ctx->net, set, &elem);
4631         if (priv == NULL) {
4632                 err = -ENOENT;
4633                 goto err4;
4634         }
4635         kfree(elem.priv);
4636         elem.priv = priv;
4637
4638         nft_set_elem_deactivate(ctx->net, set, &elem);
4639
4640         nft_trans_elem(trans) = elem;
4641         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4642         return 0;
4643
4644 err4:
4645         kfree(trans);
4646 err3:
4647         kfree(elem.priv);
4648 err2:
4649         nft_data_release(&elem.key.val, desc.type);
4650 err1:
4651         return err;
4652 }
4653
4654 static int nft_flush_set(const struct nft_ctx *ctx,
4655                          struct nft_set *set,
4656                          const struct nft_set_iter *iter,
4657                          struct nft_set_elem *elem)
4658 {
4659         struct nft_trans *trans;
4660         int err;
4661
4662         trans = nft_trans_alloc_gfp(ctx, NFT_MSG_DELSETELEM,
4663                                     sizeof(struct nft_trans_elem), GFP_ATOMIC);
4664         if (!trans)
4665                 return -ENOMEM;
4666
4667         if (!set->ops->flush(ctx->net, set, elem->priv)) {
4668                 err = -ENOENT;
4669                 goto err1;
4670         }
4671         set->ndeact++;
4672
4673         nft_set_elem_deactivate(ctx->net, set, elem);
4674         nft_trans_elem_set(trans) = set;
4675         nft_trans_elem(trans) = *elem;
4676         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
4677
4678         return 0;
4679 err1:
4680         kfree(trans);
4681         return err;
4682 }
4683
4684 static int nf_tables_delsetelem(struct net *net, struct sock *nlsk,
4685                                 struct sk_buff *skb, const struct nlmsghdr *nlh,
4686                                 const struct nlattr * const nla[],
4687                                 struct netlink_ext_ack *extack)
4688 {
4689         u8 genmask = nft_genmask_next(net);
4690         const struct nlattr *attr;
4691         struct nft_set *set;
4692         struct nft_ctx ctx;
4693         int rem, err = 0;
4694
4695         err = nft_ctx_init_from_elemattr(&ctx, net, skb, nlh, nla, extack,
4696                                          genmask);
4697         if (err < 0)
4698                 return err;
4699
4700         set = nft_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET], genmask);
4701         if (IS_ERR(set))
4702                 return PTR_ERR(set);
4703         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
4704                 return -EBUSY;
4705
4706         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL) {
4707                 struct nft_set_iter iter = {
4708                         .genmask        = genmask,
4709                         .fn             = nft_flush_set,
4710                 };
4711                 set->ops->walk(&ctx, set, &iter);
4712
4713                 return iter.err;
4714         }
4715
4716         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
4717                 err = nft_del_setelem(&ctx, set, attr);
4718                 if (err < 0)
4719                         break;
4720
4721                 set->ndeact++;
4722         }
4723         return err;
4724 }
4725
4726 void nft_set_gc_batch_release(struct rcu_head *rcu)
4727 {
4728         struct nft_set_gc_batch *gcb;
4729         unsigned int i;
4730
4731         gcb = container_of(rcu, struct nft_set_gc_batch, head.rcu);
4732         for (i = 0; i < gcb->head.cnt; i++)
4733                 nft_set_elem_destroy(gcb->head.set, gcb->elems[i], true);
4734         kfree(gcb);
4735 }
4736 EXPORT_SYMBOL_GPL(nft_set_gc_batch_release);
4737
4738 struct nft_set_gc_batch *nft_set_gc_batch_alloc(const struct nft_set *set,
4739                                                 gfp_t gfp)
4740 {
4741         struct nft_set_gc_batch *gcb;
4742
4743         gcb = kzalloc(sizeof(*gcb), gfp);
4744         if (gcb == NULL)
4745                 return gcb;
4746         gcb->head.set = set;
4747         return gcb;
4748 }
4749 EXPORT_SYMBOL_GPL(nft_set_gc_batch_alloc);
4750
4751 /*
4752  * Stateful objects
4753  */
4754
4755 /**
4756  *      nft_register_obj- register nf_tables stateful object type
4757  *      @obj: object type
4758  *
4759  *      Registers the object type for use with nf_tables. Returns zero on
4760  *      success or a negative errno code otherwise.
4761  */
4762 int nft_register_obj(struct nft_object_type *obj_type)
4763 {
4764         if (obj_type->type == NFT_OBJECT_UNSPEC)
4765                 return -EINVAL;
4766
4767         nfnl_lock(NFNL_SUBSYS_NFTABLES);
4768         list_add_rcu(&obj_type->list, &nf_tables_objects);
4769         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4770         return 0;
4771 }
4772 EXPORT_SYMBOL_GPL(nft_register_obj);
4773
4774 /**
4775  *      nft_unregister_obj - unregister nf_tables object type
4776  *      @obj: object type
4777  *
4778  *      Unregisters the object type for use with nf_tables.
4779  */
4780 void nft_unregister_obj(struct nft_object_type *obj_type)
4781 {
4782         nfnl_lock(NFNL_SUBSYS_NFTABLES);
4783         list_del_rcu(&obj_type->list);
4784         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
4785 }
4786 EXPORT_SYMBOL_GPL(nft_unregister_obj);
4787
4788 struct nft_object *nft_obj_lookup(const struct nft_table *table,
4789                                   const struct nlattr *nla, u32 objtype,
4790                                   u8 genmask)
4791 {
4792         struct nft_object *obj;
4793
4794         list_for_each_entry_rcu(obj, &table->objects, list) {
4795                 if (!nla_strcmp(nla, obj->name) &&
4796                     objtype == obj->ops->type->type &&
4797                     nft_active_genmask(obj, genmask))
4798                         return obj;
4799         }
4800         return ERR_PTR(-ENOENT);
4801 }
4802 EXPORT_SYMBOL_GPL(nft_obj_lookup);
4803
4804 static struct nft_object *nft_obj_lookup_byhandle(const struct nft_table *table,
4805                                                   const struct nlattr *nla,
4806                                                   u32 objtype, u8 genmask)
4807 {
4808         struct nft_object *obj;
4809
4810         list_for_each_entry(obj, &table->objects, list) {
4811                 if (be64_to_cpu(nla_get_be64(nla)) == obj->handle &&
4812                     objtype == obj->ops->type->type &&
4813                     nft_active_genmask(obj, genmask))
4814                         return obj;
4815         }
4816         return ERR_PTR(-ENOENT);
4817 }
4818
4819 static const struct nla_policy nft_obj_policy[NFTA_OBJ_MAX + 1] = {
4820         [NFTA_OBJ_TABLE]        = { .type = NLA_STRING,
4821                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
4822         [NFTA_OBJ_NAME]         = { .type = NLA_STRING,
4823                                     .len = NFT_OBJ_MAXNAMELEN - 1 },
4824         [NFTA_OBJ_TYPE]         = { .type = NLA_U32 },
4825         [NFTA_OBJ_DATA]         = { .type = NLA_NESTED },
4826         [NFTA_OBJ_HANDLE]       = { .type = NLA_U64},
4827 };
4828
4829 static struct nft_object *nft_obj_init(const struct nft_ctx *ctx,
4830                                        const struct nft_object_type *type,
4831                                        const struct nlattr *attr)
4832 {
4833         struct nlattr **tb;
4834         const struct nft_object_ops *ops;
4835         struct nft_object *obj;
4836         int err = -ENOMEM;
4837
4838         tb = kmalloc_array(type->maxattr + 1, sizeof(*tb), GFP_KERNEL);
4839         if (!tb)
4840                 goto err1;
4841
4842         if (attr) {
4843                 err = nla_parse_nested(tb, type->maxattr, attr, type->policy,
4844                                        NULL);
4845                 if (err < 0)
4846                         goto err2;
4847         } else {
4848                 memset(tb, 0, sizeof(tb[0]) * (type->maxattr + 1));
4849         }
4850
4851         if (type->select_ops) {
4852                 ops = type->select_ops(ctx, (const struct nlattr * const *)tb);
4853                 if (IS_ERR(ops)) {
4854                         err = PTR_ERR(ops);
4855                         goto err2;
4856                 }
4857         } else {
4858                 ops = type->ops;
4859         }
4860
4861         err = -ENOMEM;
4862         obj = kzalloc(sizeof(*obj) + ops->size, GFP_KERNEL);
4863         if (!obj)
4864                 goto err2;
4865
4866         err = ops->init(ctx, (const struct nlattr * const *)tb, obj);
4867         if (err < 0)
4868                 goto err3;
4869
4870         obj->ops = ops;
4871
4872         kfree(tb);
4873         return obj;
4874 err3:
4875         kfree(obj);
4876 err2:
4877         kfree(tb);
4878 err1:
4879         return ERR_PTR(err);
4880 }
4881
4882 static int nft_object_dump(struct sk_buff *skb, unsigned int attr,
4883                            struct nft_object *obj, bool reset)
4884 {
4885         struct nlattr *nest;
4886
4887         nest = nla_nest_start(skb, attr);
4888         if (!nest)
4889                 goto nla_put_failure;
4890         if (obj->ops->dump(skb, obj, reset) < 0)
4891                 goto nla_put_failure;
4892         nla_nest_end(skb, nest);
4893         return 0;
4894
4895 nla_put_failure:
4896         return -1;
4897 }
4898
4899 static const struct nft_object_type *__nft_obj_type_get(u32 objtype)
4900 {
4901         const struct nft_object_type *type;
4902
4903         list_for_each_entry(type, &nf_tables_objects, list) {
4904                 if (objtype == type->type)
4905                         return type;
4906         }
4907         return NULL;
4908 }
4909
4910 static const struct nft_object_type *
4911 nft_obj_type_get(struct net *net, u32 objtype)
4912 {
4913         const struct nft_object_type *type;
4914
4915         type = __nft_obj_type_get(objtype);
4916         if (type != NULL && try_module_get(type->owner))
4917                 return type;
4918
4919         lockdep_nfnl_nft_mutex_not_held();
4920 #ifdef CONFIG_MODULES
4921         if (type == NULL) {
4922                 nft_request_module(net, "nft-obj-%u", objtype);
4923                 if (__nft_obj_type_get(objtype))
4924                         return ERR_PTR(-EAGAIN);
4925         }
4926 #endif
4927         return ERR_PTR(-ENOENT);
4928 }
4929
4930 static int nf_tables_newobj(struct net *net, struct sock *nlsk,
4931                             struct sk_buff *skb, const struct nlmsghdr *nlh,
4932                             const struct nlattr * const nla[],
4933                             struct netlink_ext_ack *extack)
4934 {
4935         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
4936         const struct nft_object_type *type;
4937         u8 genmask = nft_genmask_next(net);
4938         int family = nfmsg->nfgen_family;
4939         struct nft_table *table;
4940         struct nft_object *obj;
4941         struct nft_ctx ctx;
4942         u32 objtype;
4943         int err;
4944
4945         if (!nla[NFTA_OBJ_TYPE] ||
4946             !nla[NFTA_OBJ_NAME] ||
4947             !nla[NFTA_OBJ_DATA])
4948                 return -EINVAL;
4949
4950         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
4951         if (IS_ERR(table)) {
4952                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
4953                 return PTR_ERR(table);
4954         }
4955
4956         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
4957         obj = nft_obj_lookup(table, nla[NFTA_OBJ_NAME], objtype, genmask);
4958         if (IS_ERR(obj)) {
4959                 err = PTR_ERR(obj);
4960                 if (err != -ENOENT) {
4961                         NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
4962                         return err;
4963                 }
4964         } else {
4965                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
4966                         NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
4967                         return -EEXIST;
4968                 }
4969                 return 0;
4970         }
4971
4972         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
4973
4974         type = nft_obj_type_get(net, objtype);
4975         if (IS_ERR(type))
4976                 return PTR_ERR(type);
4977
4978         obj = nft_obj_init(&ctx, type, nla[NFTA_OBJ_DATA]);
4979         if (IS_ERR(obj)) {
4980                 err = PTR_ERR(obj);
4981                 goto err1;
4982         }
4983         obj->table = table;
4984         obj->handle = nf_tables_alloc_handle(table);
4985
4986         obj->name = nla_strdup(nla[NFTA_OBJ_NAME], GFP_KERNEL);
4987         if (!obj->name) {
4988                 err = -ENOMEM;
4989                 goto err2;
4990         }
4991
4992         err = nft_trans_obj_add(&ctx, NFT_MSG_NEWOBJ, obj);
4993         if (err < 0)
4994                 goto err3;
4995
4996         list_add_tail_rcu(&obj->list, &table->objects);
4997         table->use++;
4998         return 0;
4999 err3:
5000         kfree(obj->name);
5001 err2:
5002         if (obj->ops->destroy)
5003                 obj->ops->destroy(&ctx, obj);
5004         kfree(obj);
5005 err1:
5006         module_put(type->owner);
5007         return err;
5008 }
5009
5010 static int nf_tables_fill_obj_info(struct sk_buff *skb, struct net *net,
5011                                    u32 portid, u32 seq, int event, u32 flags,
5012                                    int family, const struct nft_table *table,
5013                                    struct nft_object *obj, bool reset)
5014 {
5015         struct nfgenmsg *nfmsg;
5016         struct nlmsghdr *nlh;
5017
5018         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5019         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5020         if (nlh == NULL)
5021                 goto nla_put_failure;
5022
5023         nfmsg = nlmsg_data(nlh);
5024         nfmsg->nfgen_family     = family;
5025         nfmsg->version          = NFNETLINK_V0;
5026         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5027
5028         if (nla_put_string(skb, NFTA_OBJ_TABLE, table->name) ||
5029             nla_put_string(skb, NFTA_OBJ_NAME, obj->name) ||
5030             nla_put_be32(skb, NFTA_OBJ_TYPE, htonl(obj->ops->type->type)) ||
5031             nla_put_be32(skb, NFTA_OBJ_USE, htonl(obj->use)) ||
5032             nft_object_dump(skb, NFTA_OBJ_DATA, obj, reset) ||
5033             nla_put_be64(skb, NFTA_OBJ_HANDLE, cpu_to_be64(obj->handle),
5034                          NFTA_OBJ_PAD))
5035                 goto nla_put_failure;
5036
5037         nlmsg_end(skb, nlh);
5038         return 0;
5039
5040 nla_put_failure:
5041         nlmsg_trim(skb, nlh);
5042         return -1;
5043 }
5044
5045 struct nft_obj_filter {
5046         char            *table;
5047         u32             type;
5048 };
5049
5050 static int nf_tables_dump_obj(struct sk_buff *skb, struct netlink_callback *cb)
5051 {
5052         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5053         const struct nft_table *table;
5054         unsigned int idx = 0, s_idx = cb->args[0];
5055         struct nft_obj_filter *filter = cb->data;
5056         struct net *net = sock_net(skb->sk);
5057         int family = nfmsg->nfgen_family;
5058         struct nft_object *obj;
5059         bool reset = false;
5060
5061         if (NFNL_MSG_TYPE(cb->nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5062                 reset = true;
5063
5064         rcu_read_lock();
5065         cb->seq = net->nft.base_seq;
5066
5067         list_for_each_entry_rcu(table, &net->nft.tables, list) {
5068                 if (family != NFPROTO_UNSPEC && family != table->family)
5069                         continue;
5070
5071                 list_for_each_entry_rcu(obj, &table->objects, list) {
5072                         if (!nft_is_active(net, obj))
5073                                 goto cont;
5074                         if (idx < s_idx)
5075                                 goto cont;
5076                         if (idx > s_idx)
5077                                 memset(&cb->args[1], 0,
5078                                        sizeof(cb->args) - sizeof(cb->args[0]));
5079                         if (filter && filter->table &&
5080                             strcmp(filter->table, table->name))
5081                                 goto cont;
5082                         if (filter &&
5083                             filter->type != NFT_OBJECT_UNSPEC &&
5084                             obj->ops->type->type != filter->type)
5085                                 goto cont;
5086
5087                         if (nf_tables_fill_obj_info(skb, net, NETLINK_CB(cb->skb).portid,
5088                                                     cb->nlh->nlmsg_seq,
5089                                                     NFT_MSG_NEWOBJ,
5090                                                     NLM_F_MULTI | NLM_F_APPEND,
5091                                                     table->family, table,
5092                                                     obj, reset) < 0)
5093                                 goto done;
5094
5095                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5096 cont:
5097                         idx++;
5098                 }
5099         }
5100 done:
5101         rcu_read_unlock();
5102
5103         cb->args[0] = idx;
5104         return skb->len;
5105 }
5106
5107 static int nf_tables_dump_obj_start(struct netlink_callback *cb)
5108 {
5109         const struct nlattr * const *nla = cb->data;
5110         struct nft_obj_filter *filter = NULL;
5111
5112         if (nla[NFTA_OBJ_TABLE] || nla[NFTA_OBJ_TYPE]) {
5113                 filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5114                 if (!filter)
5115                         return -ENOMEM;
5116
5117                 if (nla[NFTA_OBJ_TABLE]) {
5118                         filter->table = nla_strdup(nla[NFTA_OBJ_TABLE], GFP_ATOMIC);
5119                         if (!filter->table) {
5120                                 kfree(filter);
5121                                 return -ENOMEM;
5122                         }
5123                 }
5124
5125                 if (nla[NFTA_OBJ_TYPE])
5126                         filter->type = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5127         }
5128
5129         cb->data = filter;
5130         return 0;
5131 }
5132
5133 static int nf_tables_dump_obj_done(struct netlink_callback *cb)
5134 {
5135         struct nft_obj_filter *filter = cb->data;
5136
5137         if (filter) {
5138                 kfree(filter->table);
5139                 kfree(filter);
5140         }
5141
5142         return 0;
5143 }
5144
5145 /* called with rcu_read_lock held */
5146 static int nf_tables_getobj(struct net *net, struct sock *nlsk,
5147                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5148                             const struct nlattr * const nla[],
5149                             struct netlink_ext_ack *extack)
5150 {
5151         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5152         u8 genmask = nft_genmask_cur(net);
5153         int family = nfmsg->nfgen_family;
5154         const struct nft_table *table;
5155         struct nft_object *obj;
5156         struct sk_buff *skb2;
5157         bool reset = false;
5158         u32 objtype;
5159         int err;
5160
5161         if (nlh->nlmsg_flags & NLM_F_DUMP) {
5162                 struct netlink_dump_control c = {
5163                         .start = nf_tables_dump_obj_start,
5164                         .dump = nf_tables_dump_obj,
5165                         .done = nf_tables_dump_obj_done,
5166                         .module = THIS_MODULE,
5167                         .data = (void *)nla,
5168                 };
5169
5170                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
5171         }
5172
5173         if (!nla[NFTA_OBJ_NAME] ||
5174             !nla[NFTA_OBJ_TYPE])
5175                 return -EINVAL;
5176
5177         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5178         if (IS_ERR(table)) {
5179                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5180                 return PTR_ERR(table);
5181         }
5182
5183         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5184         obj = nft_obj_lookup(table, nla[NFTA_OBJ_NAME], objtype, genmask);
5185         if (IS_ERR(obj)) {
5186                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_NAME]);
5187                 return PTR_ERR(obj);
5188         }
5189
5190         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
5191         if (!skb2)
5192                 return -ENOMEM;
5193
5194         if (NFNL_MSG_TYPE(nlh->nlmsg_type) == NFT_MSG_GETOBJ_RESET)
5195                 reset = true;
5196
5197         err = nf_tables_fill_obj_info(skb2, net, NETLINK_CB(skb).portid,
5198                                       nlh->nlmsg_seq, NFT_MSG_NEWOBJ, 0,
5199                                       family, table, obj, reset);
5200         if (err < 0)
5201                 goto err;
5202
5203         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
5204 err:
5205         kfree_skb(skb2);
5206         return err;
5207 }
5208
5209 static void nft_obj_destroy(const struct nft_ctx *ctx, struct nft_object *obj)
5210 {
5211         if (obj->ops->destroy)
5212                 obj->ops->destroy(ctx, obj);
5213
5214         module_put(obj->ops->type->owner);
5215         kfree(obj->name);
5216         kfree(obj);
5217 }
5218
5219 static int nf_tables_delobj(struct net *net, struct sock *nlsk,
5220                             struct sk_buff *skb, const struct nlmsghdr *nlh,
5221                             const struct nlattr * const nla[],
5222                             struct netlink_ext_ack *extack)
5223 {
5224         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5225         u8 genmask = nft_genmask_next(net);
5226         int family = nfmsg->nfgen_family;
5227         const struct nlattr *attr;
5228         struct nft_table *table;
5229         struct nft_object *obj;
5230         struct nft_ctx ctx;
5231         u32 objtype;
5232
5233         if (!nla[NFTA_OBJ_TYPE] ||
5234             (!nla[NFTA_OBJ_NAME] && !nla[NFTA_OBJ_HANDLE]))
5235                 return -EINVAL;
5236
5237         table = nft_table_lookup(net, nla[NFTA_OBJ_TABLE], family, genmask);
5238         if (IS_ERR(table)) {
5239                 NL_SET_BAD_ATTR(extack, nla[NFTA_OBJ_TABLE]);
5240                 return PTR_ERR(table);
5241         }
5242
5243         objtype = ntohl(nla_get_be32(nla[NFTA_OBJ_TYPE]));
5244         if (nla[NFTA_OBJ_HANDLE]) {
5245                 attr = nla[NFTA_OBJ_HANDLE];
5246                 obj = nft_obj_lookup_byhandle(table, attr, objtype, genmask);
5247         } else {
5248                 attr = nla[NFTA_OBJ_NAME];
5249                 obj = nft_obj_lookup(table, attr, objtype, genmask);
5250         }
5251
5252         if (IS_ERR(obj)) {
5253                 NL_SET_BAD_ATTR(extack, attr);
5254                 return PTR_ERR(obj);
5255         }
5256         if (obj->use > 0) {
5257                 NL_SET_BAD_ATTR(extack, attr);
5258                 return -EBUSY;
5259         }
5260
5261         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5262
5263         return nft_delobj(&ctx, obj);
5264 }
5265
5266 void nft_obj_notify(struct net *net, struct nft_table *table,
5267                     struct nft_object *obj, u32 portid, u32 seq, int event,
5268                     int family, int report, gfp_t gfp)
5269 {
5270         struct sk_buff *skb;
5271         int err;
5272
5273         if (!report &&
5274             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
5275                 return;
5276
5277         skb = nlmsg_new(NLMSG_GOODSIZE, gfp);
5278         if (skb == NULL)
5279                 goto err;
5280
5281         err = nf_tables_fill_obj_info(skb, net, portid, seq, event, 0, family,
5282                                       table, obj, false);
5283         if (err < 0) {
5284                 kfree_skb(skb);
5285                 goto err;
5286         }
5287
5288         nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, report, gfp);
5289         return;
5290 err:
5291         nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, -ENOBUFS);
5292 }
5293 EXPORT_SYMBOL_GPL(nft_obj_notify);
5294
5295 static void nf_tables_obj_notify(const struct nft_ctx *ctx,
5296                                  struct nft_object *obj, int event)
5297 {
5298         nft_obj_notify(ctx->net, ctx->table, obj, ctx->portid, ctx->seq, event,
5299                        ctx->family, ctx->report, GFP_KERNEL);
5300 }
5301
5302 /*
5303  * Flow tables
5304  */
5305 void nft_register_flowtable_type(struct nf_flowtable_type *type)
5306 {
5307         nfnl_lock(NFNL_SUBSYS_NFTABLES);
5308         list_add_tail_rcu(&type->list, &nf_tables_flowtables);
5309         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5310 }
5311 EXPORT_SYMBOL_GPL(nft_register_flowtable_type);
5312
5313 void nft_unregister_flowtable_type(struct nf_flowtable_type *type)
5314 {
5315         nfnl_lock(NFNL_SUBSYS_NFTABLES);
5316         list_del_rcu(&type->list);
5317         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
5318 }
5319 EXPORT_SYMBOL_GPL(nft_unregister_flowtable_type);
5320
5321 static const struct nla_policy nft_flowtable_policy[NFTA_FLOWTABLE_MAX + 1] = {
5322         [NFTA_FLOWTABLE_TABLE]          = { .type = NLA_STRING,
5323                                             .len = NFT_NAME_MAXLEN - 1 },
5324         [NFTA_FLOWTABLE_NAME]           = { .type = NLA_STRING,
5325                                             .len = NFT_NAME_MAXLEN - 1 },
5326         [NFTA_FLOWTABLE_HOOK]           = { .type = NLA_NESTED },
5327         [NFTA_FLOWTABLE_HANDLE]         = { .type = NLA_U64 },
5328 };
5329
5330 struct nft_flowtable *nft_flowtable_lookup(const struct nft_table *table,
5331                                            const struct nlattr *nla, u8 genmask)
5332 {
5333         struct nft_flowtable *flowtable;
5334
5335         list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5336                 if (!nla_strcmp(nla, flowtable->name) &&
5337                     nft_active_genmask(flowtable, genmask))
5338                         return flowtable;
5339         }
5340         return ERR_PTR(-ENOENT);
5341 }
5342 EXPORT_SYMBOL_GPL(nft_flowtable_lookup);
5343
5344 static struct nft_flowtable *
5345 nft_flowtable_lookup_byhandle(const struct nft_table *table,
5346                               const struct nlattr *nla, u8 genmask)
5347 {
5348        struct nft_flowtable *flowtable;
5349
5350        list_for_each_entry(flowtable, &table->flowtables, list) {
5351                if (be64_to_cpu(nla_get_be64(nla)) == flowtable->handle &&
5352                    nft_active_genmask(flowtable, genmask))
5353                        return flowtable;
5354        }
5355        return ERR_PTR(-ENOENT);
5356 }
5357
5358 static int nf_tables_parse_devices(const struct nft_ctx *ctx,
5359                                    const struct nlattr *attr,
5360                                    struct net_device *dev_array[], int *len)
5361 {
5362         const struct nlattr *tmp;
5363         struct net_device *dev;
5364         char ifname[IFNAMSIZ];
5365         int rem, n = 0, err;
5366
5367         nla_for_each_nested(tmp, attr, rem) {
5368                 if (nla_type(tmp) != NFTA_DEVICE_NAME) {
5369                         err = -EINVAL;
5370                         goto err1;
5371                 }
5372
5373                 nla_strlcpy(ifname, tmp, IFNAMSIZ);
5374                 dev = __dev_get_by_name(ctx->net, ifname);
5375                 if (!dev) {
5376                         err = -ENOENT;
5377                         goto err1;
5378                 }
5379
5380                 dev_array[n++] = dev;
5381                 if (n == NFT_FLOWTABLE_DEVICE_MAX) {
5382                         err = -EFBIG;
5383                         goto err1;
5384                 }
5385         }
5386         if (!len)
5387                 return -EINVAL;
5388
5389         err = 0;
5390 err1:
5391         *len = n;
5392         return err;
5393 }
5394
5395 static const struct nla_policy nft_flowtable_hook_policy[NFTA_FLOWTABLE_HOOK_MAX + 1] = {
5396         [NFTA_FLOWTABLE_HOOK_NUM]       = { .type = NLA_U32 },
5397         [NFTA_FLOWTABLE_HOOK_PRIORITY]  = { .type = NLA_U32 },
5398         [NFTA_FLOWTABLE_HOOK_DEVS]      = { .type = NLA_NESTED },
5399 };
5400
5401 static int nf_tables_flowtable_parse_hook(const struct nft_ctx *ctx,
5402                                           const struct nlattr *attr,
5403                                           struct nft_flowtable *flowtable)
5404 {
5405         struct net_device *dev_array[NFT_FLOWTABLE_DEVICE_MAX];
5406         struct nlattr *tb[NFTA_FLOWTABLE_HOOK_MAX + 1];
5407         struct nf_hook_ops *ops;
5408         int hooknum, priority;
5409         int err, n = 0, i;
5410
5411         err = nla_parse_nested(tb, NFTA_FLOWTABLE_HOOK_MAX, attr,
5412                                nft_flowtable_hook_policy, NULL);
5413         if (err < 0)
5414                 return err;
5415
5416         if (!tb[NFTA_FLOWTABLE_HOOK_NUM] ||
5417             !tb[NFTA_FLOWTABLE_HOOK_PRIORITY] ||
5418             !tb[NFTA_FLOWTABLE_HOOK_DEVS])
5419                 return -EINVAL;
5420
5421         hooknum = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_NUM]));
5422         if (hooknum != NF_NETDEV_INGRESS)
5423                 return -EINVAL;
5424
5425         priority = ntohl(nla_get_be32(tb[NFTA_FLOWTABLE_HOOK_PRIORITY]));
5426
5427         err = nf_tables_parse_devices(ctx, tb[NFTA_FLOWTABLE_HOOK_DEVS],
5428                                       dev_array, &n);
5429         if (err < 0)
5430                 return err;
5431
5432         ops = kcalloc(n, sizeof(struct nf_hook_ops), GFP_KERNEL);
5433         if (!ops)
5434                 return -ENOMEM;
5435
5436         flowtable->hooknum      = hooknum;
5437         flowtable->priority     = priority;
5438         flowtable->ops          = ops;
5439         flowtable->ops_len      = n;
5440
5441         for (i = 0; i < n; i++) {
5442                 flowtable->ops[i].pf            = NFPROTO_NETDEV;
5443                 flowtable->ops[i].hooknum       = hooknum;
5444                 flowtable->ops[i].priority      = priority;
5445                 flowtable->ops[i].priv          = &flowtable->data;
5446                 flowtable->ops[i].hook          = flowtable->data.type->hook;
5447                 flowtable->ops[i].dev           = dev_array[i];
5448         }
5449
5450         return err;
5451 }
5452
5453 static const struct nf_flowtable_type *__nft_flowtable_type_get(u8 family)
5454 {
5455         const struct nf_flowtable_type *type;
5456
5457         list_for_each_entry(type, &nf_tables_flowtables, list) {
5458                 if (family == type->family)
5459                         return type;
5460         }
5461         return NULL;
5462 }
5463
5464 static const struct nf_flowtable_type *
5465 nft_flowtable_type_get(struct net *net, u8 family)
5466 {
5467         const struct nf_flowtable_type *type;
5468
5469         type = __nft_flowtable_type_get(family);
5470         if (type != NULL && try_module_get(type->owner))
5471                 return type;
5472
5473         lockdep_nfnl_nft_mutex_not_held();
5474 #ifdef CONFIG_MODULES
5475         if (type == NULL) {
5476                 nft_request_module(net, "nf-flowtable-%u", family);
5477                 if (__nft_flowtable_type_get(family))
5478                         return ERR_PTR(-EAGAIN);
5479         }
5480 #endif
5481         return ERR_PTR(-ENOENT);
5482 }
5483
5484 static void nft_unregister_flowtable_net_hooks(struct net *net,
5485                                                struct nft_flowtable *flowtable)
5486 {
5487         int i;
5488
5489         for (i = 0; i < flowtable->ops_len; i++) {
5490                 if (!flowtable->ops[i].dev)
5491                         continue;
5492
5493                 nf_unregister_net_hook(net, &flowtable->ops[i]);
5494         }
5495 }
5496
5497 static int nf_tables_newflowtable(struct net *net, struct sock *nlsk,
5498                                   struct sk_buff *skb,
5499                                   const struct nlmsghdr *nlh,
5500                                   const struct nlattr * const nla[],
5501                                   struct netlink_ext_ack *extack)
5502 {
5503         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5504         const struct nf_flowtable_type *type;
5505         struct nft_flowtable *flowtable, *ft;
5506         u8 genmask = nft_genmask_next(net);
5507         int family = nfmsg->nfgen_family;
5508         struct nft_table *table;
5509         struct nft_ctx ctx;
5510         int err, i, k;
5511
5512         if (!nla[NFTA_FLOWTABLE_TABLE] ||
5513             !nla[NFTA_FLOWTABLE_NAME] ||
5514             !nla[NFTA_FLOWTABLE_HOOK])
5515                 return -EINVAL;
5516
5517         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5518                                  genmask);
5519         if (IS_ERR(table)) {
5520                 NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5521                 return PTR_ERR(table);
5522         }
5523
5524         flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
5525                                          genmask);
5526         if (IS_ERR(flowtable)) {
5527                 err = PTR_ERR(flowtable);
5528                 if (err != -ENOENT) {
5529                         NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5530                         return err;
5531                 }
5532         } else {
5533                 if (nlh->nlmsg_flags & NLM_F_EXCL) {
5534                         NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_NAME]);
5535                         return -EEXIST;
5536                 }
5537
5538                 return 0;
5539         }
5540
5541         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5542
5543         flowtable = kzalloc(sizeof(*flowtable), GFP_KERNEL);
5544         if (!flowtable)
5545                 return -ENOMEM;
5546
5547         flowtable->table = table;
5548         flowtable->handle = nf_tables_alloc_handle(table);
5549
5550         flowtable->name = nla_strdup(nla[NFTA_FLOWTABLE_NAME], GFP_KERNEL);
5551         if (!flowtable->name) {
5552                 err = -ENOMEM;
5553                 goto err1;
5554         }
5555
5556         type = nft_flowtable_type_get(net, family);
5557         if (IS_ERR(type)) {
5558                 err = PTR_ERR(type);
5559                 goto err2;
5560         }
5561
5562         flowtable->data.type = type;
5563         err = type->init(&flowtable->data);
5564         if (err < 0)
5565                 goto err3;
5566
5567         err = nf_tables_flowtable_parse_hook(&ctx, nla[NFTA_FLOWTABLE_HOOK],
5568                                              flowtable);
5569         if (err < 0)
5570                 goto err4;
5571
5572         for (i = 0; i < flowtable->ops_len; i++) {
5573                 if (!flowtable->ops[i].dev)
5574                         continue;
5575
5576                 list_for_each_entry(ft, &table->flowtables, list) {
5577                         for (k = 0; k < ft->ops_len; k++) {
5578                                 if (!ft->ops[k].dev)
5579                                         continue;
5580
5581                                 if (flowtable->ops[i].dev == ft->ops[k].dev &&
5582                                     flowtable->ops[i].pf == ft->ops[k].pf) {
5583                                         err = -EBUSY;
5584                                         goto err5;
5585                                 }
5586                         }
5587                 }
5588
5589                 err = nf_register_net_hook(net, &flowtable->ops[i]);
5590                 if (err < 0)
5591                         goto err5;
5592         }
5593
5594         err = nft_trans_flowtable_add(&ctx, NFT_MSG_NEWFLOWTABLE, flowtable);
5595         if (err < 0)
5596                 goto err6;
5597
5598         list_add_tail_rcu(&flowtable->list, &table->flowtables);
5599         table->use++;
5600
5601         return 0;
5602 err6:
5603         i = flowtable->ops_len;
5604 err5:
5605         for (k = i - 1; k >= 0; k--)
5606                 nf_unregister_net_hook(net, &flowtable->ops[k]);
5607
5608         kfree(flowtable->ops);
5609 err4:
5610         flowtable->data.type->free(&flowtable->data);
5611 err3:
5612         module_put(type->owner);
5613 err2:
5614         kfree(flowtable->name);
5615 err1:
5616         kfree(flowtable);
5617         return err;
5618 }
5619
5620 static int nf_tables_delflowtable(struct net *net, struct sock *nlsk,
5621                                   struct sk_buff *skb,
5622                                   const struct nlmsghdr *nlh,
5623                                   const struct nlattr * const nla[],
5624                                   struct netlink_ext_ack *extack)
5625 {
5626         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5627         u8 genmask = nft_genmask_next(net);
5628         int family = nfmsg->nfgen_family;
5629         struct nft_flowtable *flowtable;
5630         const struct nlattr *attr;
5631         struct nft_table *table;
5632         struct nft_ctx ctx;
5633
5634         if (!nla[NFTA_FLOWTABLE_TABLE] ||
5635             (!nla[NFTA_FLOWTABLE_NAME] &&
5636              !nla[NFTA_FLOWTABLE_HANDLE]))
5637                 return -EINVAL;
5638
5639         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5640                                  genmask);
5641         if (IS_ERR(table)) {
5642                 NL_SET_BAD_ATTR(extack, nla[NFTA_FLOWTABLE_TABLE]);
5643                 return PTR_ERR(table);
5644         }
5645
5646         if (nla[NFTA_FLOWTABLE_HANDLE]) {
5647                 attr = nla[NFTA_FLOWTABLE_HANDLE];
5648                 flowtable = nft_flowtable_lookup_byhandle(table, attr, genmask);
5649         } else {
5650                 attr = nla[NFTA_FLOWTABLE_NAME];
5651                 flowtable = nft_flowtable_lookup(table, attr, genmask);
5652         }
5653
5654         if (IS_ERR(flowtable)) {
5655                 NL_SET_BAD_ATTR(extack, attr);
5656                 return PTR_ERR(flowtable);
5657         }
5658         if (flowtable->use > 0) {
5659                 NL_SET_BAD_ATTR(extack, attr);
5660                 return -EBUSY;
5661         }
5662
5663         nft_ctx_init(&ctx, net, skb, nlh, family, table, NULL, nla);
5664
5665         return nft_delflowtable(&ctx, flowtable);
5666 }
5667
5668 static int nf_tables_fill_flowtable_info(struct sk_buff *skb, struct net *net,
5669                                          u32 portid, u32 seq, int event,
5670                                          u32 flags, int family,
5671                                          struct nft_flowtable *flowtable)
5672 {
5673         struct nlattr *nest, *nest_devs;
5674         struct nfgenmsg *nfmsg;
5675         struct nlmsghdr *nlh;
5676         int i;
5677
5678         event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, event);
5679         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
5680         if (nlh == NULL)
5681                 goto nla_put_failure;
5682
5683         nfmsg = nlmsg_data(nlh);
5684         nfmsg->nfgen_family     = family;
5685         nfmsg->version          = NFNETLINK_V0;
5686         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5687
5688         if (nla_put_string(skb, NFTA_FLOWTABLE_TABLE, flowtable->table->name) ||
5689             nla_put_string(skb, NFTA_FLOWTABLE_NAME, flowtable->name) ||
5690             nla_put_be32(skb, NFTA_FLOWTABLE_USE, htonl(flowtable->use)) ||
5691             nla_put_be64(skb, NFTA_FLOWTABLE_HANDLE, cpu_to_be64(flowtable->handle),
5692                          NFTA_FLOWTABLE_PAD))
5693                 goto nla_put_failure;
5694
5695         nest = nla_nest_start(skb, NFTA_FLOWTABLE_HOOK);
5696         if (nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_NUM, htonl(flowtable->hooknum)) ||
5697             nla_put_be32(skb, NFTA_FLOWTABLE_HOOK_PRIORITY, htonl(flowtable->priority)))
5698                 goto nla_put_failure;
5699
5700         nest_devs = nla_nest_start(skb, NFTA_FLOWTABLE_HOOK_DEVS);
5701         if (!nest_devs)
5702                 goto nla_put_failure;
5703
5704         for (i = 0; i < flowtable->ops_len; i++) {
5705                 const struct net_device *dev = READ_ONCE(flowtable->ops[i].dev);
5706
5707                 if (dev &&
5708                     nla_put_string(skb, NFTA_DEVICE_NAME, dev->name))
5709                         goto nla_put_failure;
5710         }
5711         nla_nest_end(skb, nest_devs);
5712         nla_nest_end(skb, nest);
5713
5714         nlmsg_end(skb, nlh);
5715         return 0;
5716
5717 nla_put_failure:
5718         nlmsg_trim(skb, nlh);
5719         return -1;
5720 }
5721
5722 struct nft_flowtable_filter {
5723         char            *table;
5724 };
5725
5726 static int nf_tables_dump_flowtable(struct sk_buff *skb,
5727                                     struct netlink_callback *cb)
5728 {
5729         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
5730         struct nft_flowtable_filter *filter = cb->data;
5731         unsigned int idx = 0, s_idx = cb->args[0];
5732         struct net *net = sock_net(skb->sk);
5733         int family = nfmsg->nfgen_family;
5734         struct nft_flowtable *flowtable;
5735         const struct nft_table *table;
5736
5737         rcu_read_lock();
5738         cb->seq = net->nft.base_seq;
5739
5740         list_for_each_entry_rcu(table, &net->nft.tables, list) {
5741                 if (family != NFPROTO_UNSPEC && family != table->family)
5742                         continue;
5743
5744                 list_for_each_entry_rcu(flowtable, &table->flowtables, list) {
5745                         if (!nft_is_active(net, flowtable))
5746                                 goto cont;
5747                         if (idx < s_idx)
5748                                 goto cont;
5749                         if (idx > s_idx)
5750                                 memset(&cb->args[1], 0,
5751                                        sizeof(cb->args) - sizeof(cb->args[0]));
5752                         if (filter && filter->table &&
5753                             strcmp(filter->table, table->name))
5754                                 goto cont;
5755
5756                         if (nf_tables_fill_flowtable_info(skb, net, NETLINK_CB(cb->skb).portid,
5757                                                           cb->nlh->nlmsg_seq,
5758                                                           NFT_MSG_NEWFLOWTABLE,
5759                                                           NLM_F_MULTI | NLM_F_APPEND,
5760                                                           table->family, flowtable) < 0)
5761                                 goto done;
5762
5763                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
5764 cont:
5765                         idx++;
5766                 }
5767         }
5768 done:
5769         rcu_read_unlock();
5770
5771         cb->args[0] = idx;
5772         return skb->len;
5773 }
5774
5775 static int nf_tables_dump_flowtable_start(struct netlink_callback *cb)
5776 {
5777         const struct nlattr * const *nla = cb->data;
5778         struct nft_flowtable_filter *filter = NULL;
5779
5780         if (nla[NFTA_FLOWTABLE_TABLE]) {
5781                 filter = kzalloc(sizeof(*filter), GFP_ATOMIC);
5782                 if (!filter)
5783                         return -ENOMEM;
5784
5785                 filter->table = nla_strdup(nla[NFTA_FLOWTABLE_TABLE],
5786                                            GFP_ATOMIC);
5787                 if (!filter->table) {
5788                         kfree(filter);
5789                         return -ENOMEM;
5790                 }
5791         }
5792
5793         cb->data = filter;
5794         return 0;
5795 }
5796
5797 static int nf_tables_dump_flowtable_done(struct netlink_callback *cb)
5798 {
5799         struct nft_flowtable_filter *filter = cb->data;
5800
5801         if (!filter)
5802                 return 0;
5803
5804         kfree(filter->table);
5805         kfree(filter);
5806
5807         return 0;
5808 }
5809
5810 /* called with rcu_read_lock held */
5811 static int nf_tables_getflowtable(struct net *net, struct sock *nlsk,
5812                                   struct sk_buff *skb,
5813                                   const struct nlmsghdr *nlh,
5814                                   const struct nlattr * const nla[],
5815                                   struct netlink_ext_ack *extack)
5816 {
5817         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
5818         u8 genmask = nft_genmask_cur(net);
5819         int family = nfmsg->nfgen_family;
5820         struct nft_flowtable *flowtable;
5821         const struct nft_table *table;
5822         struct sk_buff *skb2;
5823         int err;
5824
5825         if (nlh->nlmsg_flags & NLM_F_DUMP) {
5826                 struct netlink_dump_control c = {
5827                         .start = nf_tables_dump_flowtable_start,
5828                         .dump = nf_tables_dump_flowtable,
5829                         .done = nf_tables_dump_flowtable_done,
5830                         .module = THIS_MODULE,
5831                         .data = (void *)nla,
5832                 };
5833
5834                 return nft_netlink_dump_start_rcu(nlsk, skb, nlh, &c);
5835         }
5836
5837         if (!nla[NFTA_FLOWTABLE_NAME])
5838                 return -EINVAL;
5839
5840         table = nft_table_lookup(net, nla[NFTA_FLOWTABLE_TABLE], family,
5841                                  genmask);
5842         if (IS_ERR(table))
5843                 return PTR_ERR(table);
5844
5845         flowtable = nft_flowtable_lookup(table, nla[NFTA_FLOWTABLE_NAME],
5846                                          genmask);
5847         if (IS_ERR(flowtable))
5848                 return PTR_ERR(flowtable);
5849
5850         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
5851         if (!skb2)
5852                 return -ENOMEM;
5853
5854         err = nf_tables_fill_flowtable_info(skb2, net, NETLINK_CB(skb).portid,
5855                                             nlh->nlmsg_seq,
5856                                             NFT_MSG_NEWFLOWTABLE, 0, family,
5857                                             flowtable);
5858         if (err < 0)
5859                 goto err;
5860
5861         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
5862 err:
5863         kfree_skb(skb2);
5864         return err;
5865 }
5866
5867 static void nf_tables_flowtable_notify(struct nft_ctx *ctx,
5868                                        struct nft_flowtable *flowtable,
5869                                        int event)
5870 {
5871         struct sk_buff *skb;
5872         int err;
5873
5874         if (ctx->report &&
5875             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
5876                 return;
5877
5878         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
5879         if (skb == NULL)
5880                 goto err;
5881
5882         err = nf_tables_fill_flowtable_info(skb, ctx->net, ctx->portid,
5883                                             ctx->seq, event, 0,
5884                                             ctx->family, flowtable);
5885         if (err < 0) {
5886                 kfree_skb(skb);
5887                 goto err;
5888         }
5889
5890         nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
5891                        ctx->report, GFP_KERNEL);
5892         return;
5893 err:
5894         nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES, -ENOBUFS);
5895 }
5896
5897 static void nf_tables_flowtable_destroy(struct nft_flowtable *flowtable)
5898 {
5899         kfree(flowtable->ops);
5900         kfree(flowtable->name);
5901         flowtable->data.type->free(&flowtable->data);
5902         module_put(flowtable->data.type->owner);
5903         kfree(flowtable);
5904 }
5905
5906 static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net,
5907                                    u32 portid, u32 seq)
5908 {
5909         struct nlmsghdr *nlh;
5910         struct nfgenmsg *nfmsg;
5911         char buf[TASK_COMM_LEN];
5912         int event = nfnl_msg_type(NFNL_SUBSYS_NFTABLES, NFT_MSG_NEWGEN);
5913
5914         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), 0);
5915         if (nlh == NULL)
5916                 goto nla_put_failure;
5917
5918         nfmsg = nlmsg_data(nlh);
5919         nfmsg->nfgen_family     = AF_UNSPEC;
5920         nfmsg->version          = NFNETLINK_V0;
5921         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
5922
5923         if (nla_put_be32(skb, NFTA_GEN_ID, htonl(net->nft.base_seq)) ||
5924             nla_put_be32(skb, NFTA_GEN_PROC_PID, htonl(task_pid_nr(current))) ||
5925             nla_put_string(skb, NFTA_GEN_PROC_NAME, get_task_comm(buf, current)))
5926                 goto nla_put_failure;
5927
5928         nlmsg_end(skb, nlh);
5929         return 0;
5930
5931 nla_put_failure:
5932         nlmsg_trim(skb, nlh);
5933         return -EMSGSIZE;
5934 }
5935
5936 static void nft_flowtable_event(unsigned long event, struct net_device *dev,
5937                                 struct nft_flowtable *flowtable)
5938 {
5939         int i;
5940
5941         for (i = 0; i < flowtable->ops_len; i++) {
5942                 if (flowtable->ops[i].dev != dev)
5943                         continue;
5944
5945                 nf_unregister_net_hook(dev_net(dev), &flowtable->ops[i]);
5946                 flowtable->ops[i].dev = NULL;
5947                 break;
5948         }
5949 }
5950
5951 static int nf_tables_flowtable_event(struct notifier_block *this,
5952                                      unsigned long event, void *ptr)
5953 {
5954         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
5955         struct nft_flowtable *flowtable;
5956         struct nft_table *table;
5957         struct net *net;
5958
5959         if (event != NETDEV_UNREGISTER)
5960                 return 0;
5961
5962         net = dev_net(dev);
5963         mutex_lock(&net->nft.commit_mutex);
5964         list_for_each_entry(table, &net->nft.tables, list) {
5965                 list_for_each_entry(flowtable, &table->flowtables, list) {
5966                         nft_flowtable_event(event, dev, flowtable);
5967                 }
5968         }
5969         mutex_unlock(&net->nft.commit_mutex);
5970
5971         return NOTIFY_DONE;
5972 }
5973
5974 static struct notifier_block nf_tables_flowtable_notifier = {
5975         .notifier_call  = nf_tables_flowtable_event,
5976 };
5977
5978 static void nf_tables_gen_notify(struct net *net, struct sk_buff *skb,
5979                                  int event)
5980 {
5981         struct nlmsghdr *nlh = nlmsg_hdr(skb);
5982         struct sk_buff *skb2;
5983         int err;
5984
5985         if (nlmsg_report(nlh) &&
5986             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
5987                 return;
5988
5989         skb2 = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
5990         if (skb2 == NULL)
5991                 goto err;
5992
5993         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
5994                                       nlh->nlmsg_seq);
5995         if (err < 0) {
5996                 kfree_skb(skb2);
5997                 goto err;
5998         }
5999
6000         nfnetlink_send(skb2, net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6001                        nlmsg_report(nlh), GFP_KERNEL);
6002         return;
6003 err:
6004         nfnetlink_set_err(net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
6005                           -ENOBUFS);
6006 }
6007
6008 static int nf_tables_getgen(struct net *net, struct sock *nlsk,
6009                             struct sk_buff *skb, const struct nlmsghdr *nlh,
6010                             const struct nlattr * const nla[],
6011                             struct netlink_ext_ack *extack)
6012 {
6013         struct sk_buff *skb2;
6014         int err;
6015
6016         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_ATOMIC);
6017         if (skb2 == NULL)
6018                 return -ENOMEM;
6019
6020         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
6021                                       nlh->nlmsg_seq);
6022         if (err < 0)
6023                 goto err;
6024
6025         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
6026 err:
6027         kfree_skb(skb2);
6028         return err;
6029 }
6030
6031 static const struct nfnl_callback nf_tables_cb[NFT_MSG_MAX] = {
6032         [NFT_MSG_NEWTABLE] = {
6033                 .call_batch     = nf_tables_newtable,
6034                 .attr_count     = NFTA_TABLE_MAX,
6035                 .policy         = nft_table_policy,
6036         },
6037         [NFT_MSG_GETTABLE] = {
6038                 .call_rcu       = nf_tables_gettable,
6039                 .attr_count     = NFTA_TABLE_MAX,
6040                 .policy         = nft_table_policy,
6041         },
6042         [NFT_MSG_DELTABLE] = {
6043                 .call_batch     = nf_tables_deltable,
6044                 .attr_count     = NFTA_TABLE_MAX,
6045                 .policy         = nft_table_policy,
6046         },
6047         [NFT_MSG_NEWCHAIN] = {
6048                 .call_batch     = nf_tables_newchain,
6049                 .attr_count     = NFTA_CHAIN_MAX,
6050                 .policy         = nft_chain_policy,
6051         },
6052         [NFT_MSG_GETCHAIN] = {
6053                 .call_rcu       = nf_tables_getchain,
6054                 .attr_count     = NFTA_CHAIN_MAX,
6055                 .policy         = nft_chain_policy,
6056         },
6057         [NFT_MSG_DELCHAIN] = {
6058                 .call_batch     = nf_tables_delchain,
6059                 .attr_count     = NFTA_CHAIN_MAX,
6060                 .policy         = nft_chain_policy,
6061         },
6062         [NFT_MSG_NEWRULE] = {
6063                 .call_batch     = nf_tables_newrule,
6064                 .attr_count     = NFTA_RULE_MAX,
6065                 .policy         = nft_rule_policy,
6066         },
6067         [NFT_MSG_GETRULE] = {
6068                 .call_rcu       = nf_tables_getrule,
6069                 .attr_count     = NFTA_RULE_MAX,
6070                 .policy         = nft_rule_policy,
6071         },
6072         [NFT_MSG_DELRULE] = {
6073                 .call_batch     = nf_tables_delrule,
6074                 .attr_count     = NFTA_RULE_MAX,
6075                 .policy         = nft_rule_policy,
6076         },
6077         [NFT_MSG_NEWSET] = {
6078                 .call_batch     = nf_tables_newset,
6079                 .attr_count     = NFTA_SET_MAX,
6080                 .policy         = nft_set_policy,
6081         },
6082         [NFT_MSG_GETSET] = {
6083                 .call_rcu       = nf_tables_getset,
6084                 .attr_count     = NFTA_SET_MAX,
6085                 .policy         = nft_set_policy,
6086         },
6087         [NFT_MSG_DELSET] = {
6088                 .call_batch     = nf_tables_delset,
6089                 .attr_count     = NFTA_SET_MAX,
6090                 .policy         = nft_set_policy,
6091         },
6092         [NFT_MSG_NEWSETELEM] = {
6093                 .call_batch     = nf_tables_newsetelem,
6094                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6095                 .policy         = nft_set_elem_list_policy,
6096         },
6097         [NFT_MSG_GETSETELEM] = {
6098                 .call_rcu       = nf_tables_getsetelem,
6099                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6100                 .policy         = nft_set_elem_list_policy,
6101         },
6102         [NFT_MSG_DELSETELEM] = {
6103                 .call_batch     = nf_tables_delsetelem,
6104                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
6105                 .policy         = nft_set_elem_list_policy,
6106         },
6107         [NFT_MSG_GETGEN] = {
6108                 .call_rcu       = nf_tables_getgen,
6109         },
6110         [NFT_MSG_NEWOBJ] = {
6111                 .call_batch     = nf_tables_newobj,
6112                 .attr_count     = NFTA_OBJ_MAX,
6113                 .policy         = nft_obj_policy,
6114         },
6115         [NFT_MSG_GETOBJ] = {
6116                 .call_rcu       = nf_tables_getobj,
6117                 .attr_count     = NFTA_OBJ_MAX,
6118                 .policy         = nft_obj_policy,
6119         },
6120         [NFT_MSG_DELOBJ] = {
6121                 .call_batch     = nf_tables_delobj,
6122                 .attr_count     = NFTA_OBJ_MAX,
6123                 .policy         = nft_obj_policy,
6124         },
6125         [NFT_MSG_GETOBJ_RESET] = {
6126                 .call_rcu       = nf_tables_getobj,
6127                 .attr_count     = NFTA_OBJ_MAX,
6128                 .policy         = nft_obj_policy,
6129         },
6130         [NFT_MSG_NEWFLOWTABLE] = {
6131                 .call_batch     = nf_tables_newflowtable,
6132                 .attr_count     = NFTA_FLOWTABLE_MAX,
6133                 .policy         = nft_flowtable_policy,
6134         },
6135         [NFT_MSG_GETFLOWTABLE] = {
6136                 .call_rcu       = nf_tables_getflowtable,
6137                 .attr_count     = NFTA_FLOWTABLE_MAX,
6138                 .policy         = nft_flowtable_policy,
6139         },
6140         [NFT_MSG_DELFLOWTABLE] = {
6141                 .call_batch     = nf_tables_delflowtable,
6142                 .attr_count     = NFTA_FLOWTABLE_MAX,
6143                 .policy         = nft_flowtable_policy,
6144         },
6145 };
6146
6147 static int nf_tables_validate(struct net *net)
6148 {
6149         struct nft_table *table;
6150
6151         switch (net->nft.validate_state) {
6152         case NFT_VALIDATE_SKIP:
6153                 break;
6154         case NFT_VALIDATE_NEED:
6155                 nft_validate_state_update(net, NFT_VALIDATE_DO);
6156                 /* fall through */
6157         case NFT_VALIDATE_DO:
6158                 list_for_each_entry(table, &net->nft.tables, list) {
6159                         if (nft_table_validate(net, table) < 0)
6160                                 return -EAGAIN;
6161                 }
6162                 break;
6163         }
6164
6165         return 0;
6166 }
6167
6168 static void nft_chain_commit_update(struct nft_trans *trans)
6169 {
6170         struct nft_base_chain *basechain;
6171
6172         if (nft_trans_chain_name(trans)) {
6173                 rhltable_remove(&trans->ctx.table->chains_ht,
6174                                 &trans->ctx.chain->rhlhead,
6175                                 nft_chain_ht_params);
6176                 swap(trans->ctx.chain->name, nft_trans_chain_name(trans));
6177                 rhltable_insert_key(&trans->ctx.table->chains_ht,
6178                                     trans->ctx.chain->name,
6179                                     &trans->ctx.chain->rhlhead,
6180                                     nft_chain_ht_params);
6181         }
6182
6183         if (!nft_is_base_chain(trans->ctx.chain))
6184                 return;
6185
6186         basechain = nft_base_chain(trans->ctx.chain);
6187         nft_chain_stats_replace(trans->ctx.net, basechain,
6188                                 nft_trans_chain_stats(trans));
6189
6190         switch (nft_trans_chain_policy(trans)) {
6191         case NF_DROP:
6192         case NF_ACCEPT:
6193                 basechain->policy = nft_trans_chain_policy(trans);
6194                 break;
6195         }
6196 }
6197
6198 static void nft_commit_release(struct nft_trans *trans)
6199 {
6200         switch (trans->msg_type) {
6201         case NFT_MSG_DELTABLE:
6202                 nf_tables_table_destroy(&trans->ctx);
6203                 break;
6204         case NFT_MSG_NEWCHAIN:
6205                 kfree(nft_trans_chain_name(trans));
6206                 break;
6207         case NFT_MSG_DELCHAIN:
6208                 nf_tables_chain_destroy(&trans->ctx);
6209                 break;
6210         case NFT_MSG_DELRULE:
6211                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6212                 break;
6213         case NFT_MSG_DELSET:
6214                 nft_set_destroy(nft_trans_set(trans));
6215                 break;
6216         case NFT_MSG_DELSETELEM:
6217                 nf_tables_set_elem_destroy(&trans->ctx,
6218                                            nft_trans_elem_set(trans),
6219                                            nft_trans_elem(trans).priv);
6220                 break;
6221         case NFT_MSG_DELOBJ:
6222                 nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6223                 break;
6224         case NFT_MSG_DELFLOWTABLE:
6225                 nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6226                 break;
6227         }
6228
6229         if (trans->put_net)
6230                 put_net(trans->ctx.net);
6231
6232         kfree(trans);
6233 }
6234
6235 static void nf_tables_trans_destroy_work(struct work_struct *w)
6236 {
6237         struct nft_trans *trans, *next;
6238         LIST_HEAD(head);
6239
6240         spin_lock(&nf_tables_destroy_list_lock);
6241         list_splice_init(&nf_tables_destroy_list, &head);
6242         spin_unlock(&nf_tables_destroy_list_lock);
6243
6244         if (list_empty(&head))
6245                 return;
6246
6247         synchronize_rcu();
6248
6249         list_for_each_entry_safe(trans, next, &head, list) {
6250                 list_del(&trans->list);
6251                 nft_commit_release(trans);
6252         }
6253 }
6254
6255 static int nf_tables_commit_chain_prepare(struct net *net, struct nft_chain *chain)
6256 {
6257         struct nft_rule *rule;
6258         unsigned int alloc = 0;
6259         int i;
6260
6261         /* already handled or inactive chain? */
6262         if (chain->rules_next || !nft_is_active_next(net, chain))
6263                 return 0;
6264
6265         rule = list_entry(&chain->rules, struct nft_rule, list);
6266         i = 0;
6267
6268         list_for_each_entry_continue(rule, &chain->rules, list) {
6269                 if (nft_is_active_next(net, rule))
6270                         alloc++;
6271         }
6272
6273         chain->rules_next = nf_tables_chain_alloc_rules(chain, alloc);
6274         if (!chain->rules_next)
6275                 return -ENOMEM;
6276
6277         list_for_each_entry_continue(rule, &chain->rules, list) {
6278                 if (nft_is_active_next(net, rule))
6279                         chain->rules_next[i++] = rule;
6280         }
6281
6282         chain->rules_next[i] = NULL;
6283         return 0;
6284 }
6285
6286 static void nf_tables_commit_chain_prepare_cancel(struct net *net)
6287 {
6288         struct nft_trans *trans, *next;
6289
6290         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6291                 struct nft_chain *chain = trans->ctx.chain;
6292
6293                 if (trans->msg_type == NFT_MSG_NEWRULE ||
6294                     trans->msg_type == NFT_MSG_DELRULE) {
6295                         kvfree(chain->rules_next);
6296                         chain->rules_next = NULL;
6297                 }
6298         }
6299 }
6300
6301 static void __nf_tables_commit_chain_free_rules_old(struct rcu_head *h)
6302 {
6303         struct nft_rules_old *o = container_of(h, struct nft_rules_old, h);
6304
6305         kvfree(o->start);
6306 }
6307
6308 static void nf_tables_commit_chain_free_rules_old(struct nft_rule **rules)
6309 {
6310         struct nft_rule **r = rules;
6311         struct nft_rules_old *old;
6312
6313         while (*r)
6314                 r++;
6315
6316         r++;    /* rcu_head is after end marker */
6317         old = (void *) r;
6318         old->start = rules;
6319
6320         call_rcu(&old->h, __nf_tables_commit_chain_free_rules_old);
6321 }
6322
6323 static void nf_tables_commit_chain(struct net *net, struct nft_chain *chain)
6324 {
6325         struct nft_rule **g0, **g1;
6326         bool next_genbit;
6327
6328         next_genbit = nft_gencursor_next(net);
6329
6330         g0 = rcu_dereference_protected(chain->rules_gen_0,
6331                                        lockdep_commit_lock_is_held(net));
6332         g1 = rcu_dereference_protected(chain->rules_gen_1,
6333                                        lockdep_commit_lock_is_held(net));
6334
6335         /* No changes to this chain? */
6336         if (chain->rules_next == NULL) {
6337                 /* chain had no change in last or next generation */
6338                 if (g0 == g1)
6339                         return;
6340                 /*
6341                  * chain had no change in this generation; make sure next
6342                  * one uses same rules as current generation.
6343                  */
6344                 if (next_genbit) {
6345                         rcu_assign_pointer(chain->rules_gen_1, g0);
6346                         nf_tables_commit_chain_free_rules_old(g1);
6347                 } else {
6348                         rcu_assign_pointer(chain->rules_gen_0, g1);
6349                         nf_tables_commit_chain_free_rules_old(g0);
6350                 }
6351
6352                 return;
6353         }
6354
6355         if (next_genbit)
6356                 rcu_assign_pointer(chain->rules_gen_1, chain->rules_next);
6357         else
6358                 rcu_assign_pointer(chain->rules_gen_0, chain->rules_next);
6359
6360         chain->rules_next = NULL;
6361
6362         if (g0 == g1)
6363                 return;
6364
6365         if (next_genbit)
6366                 nf_tables_commit_chain_free_rules_old(g1);
6367         else
6368                 nf_tables_commit_chain_free_rules_old(g0);
6369 }
6370
6371 static void nft_chain_del(struct nft_chain *chain)
6372 {
6373         struct nft_table *table = chain->table;
6374
6375         WARN_ON_ONCE(rhltable_remove(&table->chains_ht, &chain->rhlhead,
6376                                      nft_chain_ht_params));
6377         list_del_rcu(&chain->list);
6378 }
6379
6380 static void nf_tables_commit_release(struct net *net)
6381 {
6382         struct nft_trans *trans;
6383
6384         /* all side effects have to be made visible.
6385          * For example, if a chain named 'foo' has been deleted, a
6386          * new transaction must not find it anymore.
6387          *
6388          * Memory reclaim happens asynchronously from work queue
6389          * to prevent expensive synchronize_rcu() in commit phase.
6390          */
6391         if (list_empty(&net->nft.commit_list)) {
6392                 mutex_unlock(&net->nft.commit_mutex);
6393                 return;
6394         }
6395
6396         trans = list_last_entry(&net->nft.commit_list,
6397                                 struct nft_trans, list);
6398         get_net(trans->ctx.net);
6399         WARN_ON_ONCE(trans->put_net);
6400
6401         trans->put_net = true;
6402         spin_lock(&nf_tables_destroy_list_lock);
6403         list_splice_tail_init(&net->nft.commit_list, &nf_tables_destroy_list);
6404         spin_unlock(&nf_tables_destroy_list_lock);
6405
6406         mutex_unlock(&net->nft.commit_mutex);
6407
6408         schedule_work(&trans_destroy_work);
6409 }
6410
6411 static int nf_tables_commit(struct net *net, struct sk_buff *skb)
6412 {
6413         struct nft_trans *trans, *next;
6414         struct nft_trans_elem *te;
6415         struct nft_chain *chain;
6416         struct nft_table *table;
6417
6418         /* 0. Validate ruleset, otherwise roll back for error reporting. */
6419         if (nf_tables_validate(net) < 0)
6420                 return -EAGAIN;
6421
6422         /* 1.  Allocate space for next generation rules_gen_X[] */
6423         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6424                 int ret;
6425
6426                 if (trans->msg_type == NFT_MSG_NEWRULE ||
6427                     trans->msg_type == NFT_MSG_DELRULE) {
6428                         chain = trans->ctx.chain;
6429
6430                         ret = nf_tables_commit_chain_prepare(net, chain);
6431                         if (ret < 0) {
6432                                 nf_tables_commit_chain_prepare_cancel(net);
6433                                 return ret;
6434                         }
6435                 }
6436         }
6437
6438         /* step 2.  Make rules_gen_X visible to packet path */
6439         list_for_each_entry(table, &net->nft.tables, list) {
6440                 list_for_each_entry(chain, &table->chains, list)
6441                         nf_tables_commit_chain(net, chain);
6442         }
6443
6444         /*
6445          * Bump generation counter, invalidate any dump in progress.
6446          * Cannot fail after this point.
6447          */
6448         while (++net->nft.base_seq == 0);
6449
6450         /* step 3. Start new generation, rules_gen_X now in use. */
6451         net->nft.gencursor = nft_gencursor_next(net);
6452
6453         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
6454                 switch (trans->msg_type) {
6455                 case NFT_MSG_NEWTABLE:
6456                         if (nft_trans_table_update(trans)) {
6457                                 if (!nft_trans_table_enable(trans)) {
6458                                         nf_tables_table_disable(net,
6459                                                                 trans->ctx.table);
6460                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6461                                 }
6462                         } else {
6463                                 nft_clear(net, trans->ctx.table);
6464                         }
6465                         nf_tables_table_notify(&trans->ctx, NFT_MSG_NEWTABLE);
6466                         nft_trans_destroy(trans);
6467                         break;
6468                 case NFT_MSG_DELTABLE:
6469                         list_del_rcu(&trans->ctx.table->list);
6470                         nf_tables_table_notify(&trans->ctx, NFT_MSG_DELTABLE);
6471                         break;
6472                 case NFT_MSG_NEWCHAIN:
6473                         if (nft_trans_chain_update(trans)) {
6474                                 nft_chain_commit_update(trans);
6475                                 nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6476                                 /* trans destroyed after rcu grace period */
6477                         } else {
6478                                 nft_clear(net, trans->ctx.chain);
6479                                 nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
6480                                 nft_trans_destroy(trans);
6481                         }
6482                         break;
6483                 case NFT_MSG_DELCHAIN:
6484                         nft_chain_del(trans->ctx.chain);
6485                         nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN);
6486                         nf_tables_unregister_hook(trans->ctx.net,
6487                                                   trans->ctx.table,
6488                                                   trans->ctx.chain);
6489                         break;
6490                 case NFT_MSG_NEWRULE:
6491                         nft_clear(trans->ctx.net, nft_trans_rule(trans));
6492                         nf_tables_rule_notify(&trans->ctx,
6493                                               nft_trans_rule(trans),
6494                                               NFT_MSG_NEWRULE);
6495                         nft_trans_destroy(trans);
6496                         break;
6497                 case NFT_MSG_DELRULE:
6498                         list_del_rcu(&nft_trans_rule(trans)->list);
6499                         nf_tables_rule_notify(&trans->ctx,
6500                                               nft_trans_rule(trans),
6501                                               NFT_MSG_DELRULE);
6502                         break;
6503                 case NFT_MSG_NEWSET:
6504                         nft_clear(net, nft_trans_set(trans));
6505                         /* This avoids hitting -EBUSY when deleting the table
6506                          * from the transaction.
6507                          */
6508                         if (nft_set_is_anonymous(nft_trans_set(trans)) &&
6509                             !list_empty(&nft_trans_set(trans)->bindings))
6510                                 trans->ctx.table->use--;
6511
6512                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6513                                              NFT_MSG_NEWSET, GFP_KERNEL);
6514                         nft_trans_destroy(trans);
6515                         break;
6516                 case NFT_MSG_DELSET:
6517                         list_del_rcu(&nft_trans_set(trans)->list);
6518                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
6519                                              NFT_MSG_DELSET, GFP_KERNEL);
6520                         break;
6521                 case NFT_MSG_NEWSETELEM:
6522                         te = (struct nft_trans_elem *)trans->data;
6523
6524                         te->set->ops->activate(net, te->set, &te->elem);
6525                         nf_tables_setelem_notify(&trans->ctx, te->set,
6526                                                  &te->elem,
6527                                                  NFT_MSG_NEWSETELEM, 0);
6528                         nft_trans_destroy(trans);
6529                         break;
6530                 case NFT_MSG_DELSETELEM:
6531                         te = (struct nft_trans_elem *)trans->data;
6532
6533                         nf_tables_setelem_notify(&trans->ctx, te->set,
6534                                                  &te->elem,
6535                                                  NFT_MSG_DELSETELEM, 0);
6536                         te->set->ops->remove(net, te->set, &te->elem);
6537                         atomic_dec(&te->set->nelems);
6538                         te->set->ndeact--;
6539                         break;
6540                 case NFT_MSG_NEWOBJ:
6541                         nft_clear(net, nft_trans_obj(trans));
6542                         nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6543                                              NFT_MSG_NEWOBJ);
6544                         nft_trans_destroy(trans);
6545                         break;
6546                 case NFT_MSG_DELOBJ:
6547                         list_del_rcu(&nft_trans_obj(trans)->list);
6548                         nf_tables_obj_notify(&trans->ctx, nft_trans_obj(trans),
6549                                              NFT_MSG_DELOBJ);
6550                         break;
6551                 case NFT_MSG_NEWFLOWTABLE:
6552                         nft_clear(net, nft_trans_flowtable(trans));
6553                         nf_tables_flowtable_notify(&trans->ctx,
6554                                                    nft_trans_flowtable(trans),
6555                                                    NFT_MSG_NEWFLOWTABLE);
6556                         nft_trans_destroy(trans);
6557                         break;
6558                 case NFT_MSG_DELFLOWTABLE:
6559                         list_del_rcu(&nft_trans_flowtable(trans)->list);
6560                         nf_tables_flowtable_notify(&trans->ctx,
6561                                                    nft_trans_flowtable(trans),
6562                                                    NFT_MSG_DELFLOWTABLE);
6563                         nft_unregister_flowtable_net_hooks(net,
6564                                         nft_trans_flowtable(trans));
6565                         break;
6566                 }
6567         }
6568
6569         nf_tables_gen_notify(net, skb, NFT_MSG_NEWGEN);
6570         nf_tables_commit_release(net);
6571
6572         return 0;
6573 }
6574
6575 static void nf_tables_abort_release(struct nft_trans *trans)
6576 {
6577         switch (trans->msg_type) {
6578         case NFT_MSG_NEWTABLE:
6579                 nf_tables_table_destroy(&trans->ctx);
6580                 break;
6581         case NFT_MSG_NEWCHAIN:
6582                 nf_tables_chain_destroy(&trans->ctx);
6583                 break;
6584         case NFT_MSG_NEWRULE:
6585                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
6586                 break;
6587         case NFT_MSG_NEWSET:
6588                 nft_set_destroy(nft_trans_set(trans));
6589                 break;
6590         case NFT_MSG_NEWSETELEM:
6591                 nft_set_elem_destroy(nft_trans_elem_set(trans),
6592                                      nft_trans_elem(trans).priv, true);
6593                 break;
6594         case NFT_MSG_NEWOBJ:
6595                 nft_obj_destroy(&trans->ctx, nft_trans_obj(trans));
6596                 break;
6597         case NFT_MSG_NEWFLOWTABLE:
6598                 nf_tables_flowtable_destroy(nft_trans_flowtable(trans));
6599                 break;
6600         }
6601         kfree(trans);
6602 }
6603
6604 static int __nf_tables_abort(struct net *net)
6605 {
6606         struct nft_trans *trans, *next;
6607         struct nft_trans_elem *te;
6608
6609         list_for_each_entry_safe_reverse(trans, next, &net->nft.commit_list,
6610                                          list) {
6611                 switch (trans->msg_type) {
6612                 case NFT_MSG_NEWTABLE:
6613                         if (nft_trans_table_update(trans)) {
6614                                 if (nft_trans_table_enable(trans)) {
6615                                         nf_tables_table_disable(net,
6616                                                                 trans->ctx.table);
6617                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
6618                                 }
6619                                 nft_trans_destroy(trans);
6620                         } else {
6621                                 list_del_rcu(&trans->ctx.table->list);
6622                         }
6623                         break;
6624                 case NFT_MSG_DELTABLE:
6625                         nft_clear(trans->ctx.net, trans->ctx.table);
6626                         nft_trans_destroy(trans);
6627                         break;
6628                 case NFT_MSG_NEWCHAIN:
6629                         if (nft_trans_chain_update(trans)) {
6630                                 free_percpu(nft_trans_chain_stats(trans));
6631                                 kfree(nft_trans_chain_name(trans));
6632                                 nft_trans_destroy(trans);
6633                         } else {
6634                                 trans->ctx.table->use--;
6635                                 nft_chain_del(trans->ctx.chain);
6636                                 nf_tables_unregister_hook(trans->ctx.net,
6637                                                           trans->ctx.table,
6638                                                           trans->ctx.chain);
6639                         }
6640                         break;
6641                 case NFT_MSG_DELCHAIN:
6642                         trans->ctx.table->use++;
6643                         nft_clear(trans->ctx.net, trans->ctx.chain);
6644                         nft_trans_destroy(trans);
6645                         break;
6646                 case NFT_MSG_NEWRULE:
6647                         trans->ctx.chain->use--;
6648                         list_del_rcu(&nft_trans_rule(trans)->list);
6649                         nft_rule_expr_deactivate(&trans->ctx, nft_trans_rule(trans));
6650                         break;
6651                 case NFT_MSG_DELRULE:
6652                         trans->ctx.chain->use++;
6653                         nft_clear(trans->ctx.net, nft_trans_rule(trans));
6654                         nft_rule_expr_activate(&trans->ctx, nft_trans_rule(trans));
6655                         nft_trans_destroy(trans);
6656                         break;
6657                 case NFT_MSG_NEWSET:
6658                         trans->ctx.table->use--;
6659                         list_del_rcu(&nft_trans_set(trans)->list);
6660                         break;
6661                 case NFT_MSG_DELSET:
6662                         trans->ctx.table->use++;
6663                         nft_clear(trans->ctx.net, nft_trans_set(trans));
6664                         nft_trans_destroy(trans);
6665                         break;
6666                 case NFT_MSG_NEWSETELEM:
6667                         te = (struct nft_trans_elem *)trans->data;
6668
6669                         te->set->ops->remove(net, te->set, &te->elem);
6670                         atomic_dec(&te->set->nelems);
6671                         break;
6672                 case NFT_MSG_DELSETELEM:
6673                         te = (struct nft_trans_elem *)trans->data;
6674
6675                         nft_set_elem_activate(net, te->set, &te->elem);
6676                         te->set->ops->activate(net, te->set, &te->elem);
6677                         te->set->ndeact--;
6678
6679                         nft_trans_destroy(trans);
6680                         break;
6681                 case NFT_MSG_NEWOBJ:
6682                         trans->ctx.table->use--;
6683                         list_del_rcu(&nft_trans_obj(trans)->list);
6684                         break;
6685                 case NFT_MSG_DELOBJ:
6686                         trans->ctx.table->use++;
6687                         nft_clear(trans->ctx.net, nft_trans_obj(trans));
6688                         nft_trans_destroy(trans);
6689                         break;
6690                 case NFT_MSG_NEWFLOWTABLE:
6691                         trans->ctx.table->use--;
6692                         list_del_rcu(&nft_trans_flowtable(trans)->list);
6693                         nft_unregister_flowtable_net_hooks(net,
6694                                         nft_trans_flowtable(trans));
6695                         break;
6696                 case NFT_MSG_DELFLOWTABLE:
6697                         trans->ctx.table->use++;
6698                         nft_clear(trans->ctx.net, nft_trans_flowtable(trans));
6699                         nft_trans_destroy(trans);
6700                         break;
6701                 }
6702         }
6703
6704         synchronize_rcu();
6705
6706         list_for_each_entry_safe_reverse(trans, next,
6707                                          &net->nft.commit_list, list) {
6708                 list_del(&trans->list);
6709                 nf_tables_abort_release(trans);
6710         }
6711
6712         return 0;
6713 }
6714
6715 static void nf_tables_cleanup(struct net *net)
6716 {
6717         nft_validate_state_update(net, NFT_VALIDATE_SKIP);
6718 }
6719
6720 static int nf_tables_abort(struct net *net, struct sk_buff *skb)
6721 {
6722         int ret = __nf_tables_abort(net);
6723
6724         mutex_unlock(&net->nft.commit_mutex);
6725
6726         return ret;
6727 }
6728
6729 static bool nf_tables_valid_genid(struct net *net, u32 genid)
6730 {
6731         bool genid_ok;
6732
6733         mutex_lock(&net->nft.commit_mutex);
6734
6735         genid_ok = genid == 0 || net->nft.base_seq == genid;
6736         if (!genid_ok)
6737                 mutex_unlock(&net->nft.commit_mutex);
6738
6739         /* else, commit mutex has to be released by commit or abort function */
6740         return genid_ok;
6741 }
6742
6743 static const struct nfnetlink_subsystem nf_tables_subsys = {
6744         .name           = "nf_tables",
6745         .subsys_id      = NFNL_SUBSYS_NFTABLES,
6746         .cb_count       = NFT_MSG_MAX,
6747         .cb             = nf_tables_cb,
6748         .commit         = nf_tables_commit,
6749         .abort          = nf_tables_abort,
6750         .cleanup        = nf_tables_cleanup,
6751         .valid_genid    = nf_tables_valid_genid,
6752         .owner          = THIS_MODULE,
6753 };
6754
6755 int nft_chain_validate_dependency(const struct nft_chain *chain,
6756                                   enum nft_chain_types type)
6757 {
6758         const struct nft_base_chain *basechain;
6759
6760         if (nft_is_base_chain(chain)) {
6761                 basechain = nft_base_chain(chain);
6762                 if (basechain->type->type != type)
6763                         return -EOPNOTSUPP;
6764         }
6765         return 0;
6766 }
6767 EXPORT_SYMBOL_GPL(nft_chain_validate_dependency);
6768
6769 int nft_chain_validate_hooks(const struct nft_chain *chain,
6770                              unsigned int hook_flags)
6771 {
6772         struct nft_base_chain *basechain;
6773
6774         if (nft_is_base_chain(chain)) {
6775                 basechain = nft_base_chain(chain);
6776
6777                 if ((1 << basechain->ops.hooknum) & hook_flags)
6778                         return 0;
6779
6780                 return -EOPNOTSUPP;
6781         }
6782
6783         return 0;
6784 }
6785 EXPORT_SYMBOL_GPL(nft_chain_validate_hooks);
6786
6787 /*
6788  * Loop detection - walk through the ruleset beginning at the destination chain
6789  * of a new jump until either the source chain is reached (loop) or all
6790  * reachable chains have been traversed.
6791  *
6792  * The loop check is performed whenever a new jump verdict is added to an
6793  * expression or verdict map or a verdict map is bound to a new chain.
6794  */
6795
6796 static int nf_tables_check_loops(const struct nft_ctx *ctx,
6797                                  const struct nft_chain *chain);
6798
6799 static int nf_tables_loop_check_setelem(const struct nft_ctx *ctx,
6800                                         struct nft_set *set,
6801                                         const struct nft_set_iter *iter,
6802                                         struct nft_set_elem *elem)
6803 {
6804         const struct nft_set_ext *ext = nft_set_elem_ext(set, elem->priv);
6805         const struct nft_data *data;
6806
6807         if (nft_set_ext_exists(ext, NFT_SET_EXT_FLAGS) &&
6808             *nft_set_ext_flags(ext) & NFT_SET_ELEM_INTERVAL_END)
6809                 return 0;
6810
6811         data = nft_set_ext_data(ext);
6812         switch (data->verdict.code) {
6813         case NFT_JUMP:
6814         case NFT_GOTO:
6815                 return nf_tables_check_loops(ctx, data->verdict.chain);
6816         default:
6817                 return 0;
6818         }
6819 }
6820
6821 static int nf_tables_check_loops(const struct nft_ctx *ctx,
6822                                  const struct nft_chain *chain)
6823 {
6824         const struct nft_rule *rule;
6825         const struct nft_expr *expr, *last;
6826         struct nft_set *set;
6827         struct nft_set_binding *binding;
6828         struct nft_set_iter iter;
6829
6830         if (ctx->chain == chain)
6831                 return -ELOOP;
6832
6833         list_for_each_entry(rule, &chain->rules, list) {
6834                 nft_rule_for_each_expr(expr, last, rule) {
6835                         struct nft_immediate_expr *priv;
6836                         const struct nft_data *data;
6837                         int err;
6838
6839                         if (strcmp(expr->ops->type->name, "immediate"))
6840                                 continue;
6841
6842                         priv = nft_expr_priv(expr);
6843                         if (priv->dreg != NFT_REG_VERDICT)
6844                                 continue;
6845
6846                         data = &priv->data;
6847                         switch (data->verdict.code) {
6848                         case NFT_JUMP:
6849                         case NFT_GOTO:
6850                                 err = nf_tables_check_loops(ctx,
6851                                                         data->verdict.chain);
6852                                 if (err < 0)
6853                                         return err;
6854                         default:
6855                                 break;
6856                         }
6857                 }
6858         }
6859
6860         list_for_each_entry(set, &ctx->table->sets, list) {
6861                 if (!nft_is_active_next(ctx->net, set))
6862                         continue;
6863                 if (!(set->flags & NFT_SET_MAP) ||
6864                     set->dtype != NFT_DATA_VERDICT)
6865                         continue;
6866
6867                 list_for_each_entry(binding, &set->bindings, list) {
6868                         if (!(binding->flags & NFT_SET_MAP) ||
6869                             binding->chain != chain)
6870                                 continue;
6871
6872                         iter.genmask    = nft_genmask_next(ctx->net);
6873                         iter.skip       = 0;
6874                         iter.count      = 0;
6875                         iter.err        = 0;
6876                         iter.fn         = nf_tables_loop_check_setelem;
6877
6878                         set->ops->walk(ctx, set, &iter);
6879                         if (iter.err < 0)
6880                                 return iter.err;
6881                 }
6882         }
6883
6884         return 0;
6885 }
6886
6887 /**
6888  *      nft_parse_u32_check - fetch u32 attribute and check for maximum value
6889  *
6890  *      @attr: netlink attribute to fetch value from
6891  *      @max: maximum value to be stored in dest
6892  *      @dest: pointer to the variable
6893  *
6894  *      Parse, check and store a given u32 netlink attribute into variable.
6895  *      This function returns -ERANGE if the value goes over maximum value.
6896  *      Otherwise a 0 is returned and the attribute value is stored in the
6897  *      destination variable.
6898  */
6899 int nft_parse_u32_check(const struct nlattr *attr, int max, u32 *dest)
6900 {
6901         u32 val;
6902
6903         val = ntohl(nla_get_be32(attr));
6904         if (val > max)
6905                 return -ERANGE;
6906
6907         *dest = val;
6908         return 0;
6909 }
6910 EXPORT_SYMBOL_GPL(nft_parse_u32_check);
6911
6912 /**
6913  *      nft_parse_register - parse a register value from a netlink attribute
6914  *
6915  *      @attr: netlink attribute
6916  *
6917  *      Parse and translate a register value from a netlink attribute.
6918  *      Registers used to be 128 bit wide, these register numbers will be
6919  *      mapped to the corresponding 32 bit register numbers.
6920  */
6921 unsigned int nft_parse_register(const struct nlattr *attr)
6922 {
6923         unsigned int reg;
6924
6925         reg = ntohl(nla_get_be32(attr));
6926         switch (reg) {
6927         case NFT_REG_VERDICT...NFT_REG_4:
6928                 return reg * NFT_REG_SIZE / NFT_REG32_SIZE;
6929         default:
6930                 return reg + NFT_REG_SIZE / NFT_REG32_SIZE - NFT_REG32_00;
6931         }
6932 }
6933 EXPORT_SYMBOL_GPL(nft_parse_register);
6934
6935 /**
6936  *      nft_dump_register - dump a register value to a netlink attribute
6937  *
6938  *      @skb: socket buffer
6939  *      @attr: attribute number
6940  *      @reg: register number
6941  *
6942  *      Construct a netlink attribute containing the register number. For
6943  *      compatibility reasons, register numbers being a multiple of 4 are
6944  *      translated to the corresponding 128 bit register numbers.
6945  */
6946 int nft_dump_register(struct sk_buff *skb, unsigned int attr, unsigned int reg)
6947 {
6948         if (reg % (NFT_REG_SIZE / NFT_REG32_SIZE) == 0)
6949                 reg = reg / (NFT_REG_SIZE / NFT_REG32_SIZE);
6950         else
6951                 reg = reg - NFT_REG_SIZE / NFT_REG32_SIZE + NFT_REG32_00;
6952
6953         return nla_put_be32(skb, attr, htonl(reg));
6954 }
6955 EXPORT_SYMBOL_GPL(nft_dump_register);
6956
6957 /**
6958  *      nft_validate_register_load - validate a load from a register
6959  *
6960  *      @reg: the register number
6961  *      @len: the length of the data
6962  *
6963  *      Validate that the input register is one of the general purpose
6964  *      registers and that the length of the load is within the bounds.
6965  */
6966 int nft_validate_register_load(enum nft_registers reg, unsigned int len)
6967 {
6968         if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
6969                 return -EINVAL;
6970         if (len == 0)
6971                 return -EINVAL;
6972         if (reg * NFT_REG32_SIZE + len > FIELD_SIZEOF(struct nft_regs, data))
6973                 return -ERANGE;
6974
6975         return 0;
6976 }
6977 EXPORT_SYMBOL_GPL(nft_validate_register_load);
6978
6979 /**
6980  *      nft_validate_register_store - validate an expressions' register store
6981  *
6982  *      @ctx: context of the expression performing the load
6983  *      @reg: the destination register number
6984  *      @data: the data to load
6985  *      @type: the data type
6986  *      @len: the length of the data
6987  *
6988  *      Validate that a data load uses the appropriate data type for
6989  *      the destination register and the length is within the bounds.
6990  *      A value of NULL for the data means that its runtime gathered
6991  *      data.
6992  */
6993 int nft_validate_register_store(const struct nft_ctx *ctx,
6994                                 enum nft_registers reg,
6995                                 const struct nft_data *data,
6996                                 enum nft_data_types type, unsigned int len)
6997 {
6998         int err;
6999
7000         switch (reg) {
7001         case NFT_REG_VERDICT:
7002                 if (type != NFT_DATA_VERDICT)
7003                         return -EINVAL;
7004
7005                 if (data != NULL &&
7006                     (data->verdict.code == NFT_GOTO ||
7007                      data->verdict.code == NFT_JUMP)) {
7008                         err = nf_tables_check_loops(ctx, data->verdict.chain);
7009                         if (err < 0)
7010                                 return err;
7011                 }
7012
7013                 return 0;
7014         default:
7015                 if (reg < NFT_REG_1 * NFT_REG_SIZE / NFT_REG32_SIZE)
7016                         return -EINVAL;
7017                 if (len == 0)
7018                         return -EINVAL;
7019                 if (reg * NFT_REG32_SIZE + len >
7020                     FIELD_SIZEOF(struct nft_regs, data))
7021                         return -ERANGE;
7022
7023                 if (data != NULL && type != NFT_DATA_VALUE)
7024                         return -EINVAL;
7025                 return 0;
7026         }
7027 }
7028 EXPORT_SYMBOL_GPL(nft_validate_register_store);
7029
7030 static const struct nla_policy nft_verdict_policy[NFTA_VERDICT_MAX + 1] = {
7031         [NFTA_VERDICT_CODE]     = { .type = NLA_U32 },
7032         [NFTA_VERDICT_CHAIN]    = { .type = NLA_STRING,
7033                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
7034 };
7035
7036 static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
7037                             struct nft_data_desc *desc, const struct nlattr *nla)
7038 {
7039         u8 genmask = nft_genmask_next(ctx->net);
7040         struct nlattr *tb[NFTA_VERDICT_MAX + 1];
7041         struct nft_chain *chain;
7042         int err;
7043
7044         err = nla_parse_nested(tb, NFTA_VERDICT_MAX, nla, nft_verdict_policy,
7045                                NULL);
7046         if (err < 0)
7047                 return err;
7048
7049         if (!tb[NFTA_VERDICT_CODE])
7050                 return -EINVAL;
7051         data->verdict.code = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
7052
7053         switch (data->verdict.code) {
7054         default:
7055                 switch (data->verdict.code & NF_VERDICT_MASK) {
7056                 case NF_ACCEPT:
7057                 case NF_DROP:
7058                 case NF_QUEUE:
7059                         break;
7060                 default:
7061                         return -EINVAL;
7062                 }
7063                 /* fall through */
7064         case NFT_CONTINUE:
7065         case NFT_BREAK:
7066         case NFT_RETURN:
7067                 break;
7068         case NFT_JUMP:
7069         case NFT_GOTO:
7070                 if (!tb[NFTA_VERDICT_CHAIN])
7071                         return -EINVAL;
7072                 chain = nft_chain_lookup(ctx->net, ctx->table,
7073                                          tb[NFTA_VERDICT_CHAIN], genmask);
7074                 if (IS_ERR(chain))
7075                         return PTR_ERR(chain);
7076                 if (nft_is_base_chain(chain))
7077                         return -EOPNOTSUPP;
7078
7079                 chain->use++;
7080                 data->verdict.chain = chain;
7081                 break;
7082         }
7083
7084         desc->len = sizeof(data->verdict);
7085         desc->type = NFT_DATA_VERDICT;
7086         return 0;
7087 }
7088
7089 static void nft_verdict_uninit(const struct nft_data *data)
7090 {
7091         switch (data->verdict.code) {
7092         case NFT_JUMP:
7093         case NFT_GOTO:
7094                 data->verdict.chain->use--;
7095                 break;
7096         }
7097 }
7098
7099 int nft_verdict_dump(struct sk_buff *skb, int type, const struct nft_verdict *v)
7100 {
7101         struct nlattr *nest;
7102
7103         nest = nla_nest_start(skb, type);
7104         if (!nest)
7105                 goto nla_put_failure;
7106
7107         if (nla_put_be32(skb, NFTA_VERDICT_CODE, htonl(v->code)))
7108                 goto nla_put_failure;
7109
7110         switch (v->code) {
7111         case NFT_JUMP:
7112         case NFT_GOTO:
7113                 if (nla_put_string(skb, NFTA_VERDICT_CHAIN,
7114                                    v->chain->name))
7115                         goto nla_put_failure;
7116         }
7117         nla_nest_end(skb, nest);
7118         return 0;
7119
7120 nla_put_failure:
7121         return -1;
7122 }
7123
7124 static int nft_value_init(const struct nft_ctx *ctx,
7125                           struct nft_data *data, unsigned int size,
7126                           struct nft_data_desc *desc, const struct nlattr *nla)
7127 {
7128         unsigned int len;
7129
7130         len = nla_len(nla);
7131         if (len == 0)
7132                 return -EINVAL;
7133         if (len > size)
7134                 return -EOVERFLOW;
7135
7136         nla_memcpy(data->data, nla, len);
7137         desc->type = NFT_DATA_VALUE;
7138         desc->len  = len;
7139         return 0;
7140 }
7141
7142 static int nft_value_dump(struct sk_buff *skb, const struct nft_data *data,
7143                           unsigned int len)
7144 {
7145         return nla_put(skb, NFTA_DATA_VALUE, len, data->data);
7146 }
7147
7148 static const struct nla_policy nft_data_policy[NFTA_DATA_MAX + 1] = {
7149         [NFTA_DATA_VALUE]       = { .type = NLA_BINARY },
7150         [NFTA_DATA_VERDICT]     = { .type = NLA_NESTED },
7151 };
7152
7153 /**
7154  *      nft_data_init - parse nf_tables data netlink attributes
7155  *
7156  *      @ctx: context of the expression using the data
7157  *      @data: destination struct nft_data
7158  *      @size: maximum data length
7159  *      @desc: data description
7160  *      @nla: netlink attribute containing data
7161  *
7162  *      Parse the netlink data attributes and initialize a struct nft_data.
7163  *      The type and length of data are returned in the data description.
7164  *
7165  *      The caller can indicate that it only wants to accept data of type
7166  *      NFT_DATA_VALUE by passing NULL for the ctx argument.
7167  */
7168 int nft_data_init(const struct nft_ctx *ctx,
7169                   struct nft_data *data, unsigned int size,
7170                   struct nft_data_desc *desc, const struct nlattr *nla)
7171 {
7172         struct nlattr *tb[NFTA_DATA_MAX + 1];
7173         int err;
7174
7175         err = nla_parse_nested(tb, NFTA_DATA_MAX, nla, nft_data_policy, NULL);
7176         if (err < 0)
7177                 return err;
7178
7179         if (tb[NFTA_DATA_VALUE])
7180                 return nft_value_init(ctx, data, size, desc,
7181                                       tb[NFTA_DATA_VALUE]);
7182         if (tb[NFTA_DATA_VERDICT] && ctx != NULL)
7183                 return nft_verdict_init(ctx, data, desc, tb[NFTA_DATA_VERDICT]);
7184         return -EINVAL;
7185 }
7186 EXPORT_SYMBOL_GPL(nft_data_init);
7187
7188 /**
7189  *      nft_data_release - release a nft_data item
7190  *
7191  *      @data: struct nft_data to release
7192  *      @type: type of data
7193  *
7194  *      Release a nft_data item. NFT_DATA_VALUE types can be silently discarded,
7195  *      all others need to be released by calling this function.
7196  */
7197 void nft_data_release(const struct nft_data *data, enum nft_data_types type)
7198 {
7199         if (type < NFT_DATA_VERDICT)
7200                 return;
7201         switch (type) {
7202         case NFT_DATA_VERDICT:
7203                 return nft_verdict_uninit(data);
7204         default:
7205                 WARN_ON(1);
7206         }
7207 }
7208 EXPORT_SYMBOL_GPL(nft_data_release);
7209
7210 int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
7211                   enum nft_data_types type, unsigned int len)
7212 {
7213         struct nlattr *nest;
7214         int err;
7215
7216         nest = nla_nest_start(skb, attr);
7217         if (nest == NULL)
7218                 return -1;
7219
7220         switch (type) {
7221         case NFT_DATA_VALUE:
7222                 err = nft_value_dump(skb, data, len);
7223                 break;
7224         case NFT_DATA_VERDICT:
7225                 err = nft_verdict_dump(skb, NFTA_DATA_VERDICT, &data->verdict);
7226                 break;
7227         default:
7228                 err = -EINVAL;
7229                 WARN_ON(1);
7230         }
7231
7232         nla_nest_end(skb, nest);
7233         return err;
7234 }
7235 EXPORT_SYMBOL_GPL(nft_data_dump);
7236
7237 int __nft_release_basechain(struct nft_ctx *ctx)
7238 {
7239         struct nft_rule *rule, *nr;
7240
7241         if (WARN_ON(!nft_is_base_chain(ctx->chain)))
7242                 return 0;
7243
7244         nf_tables_unregister_hook(ctx->net, ctx->chain->table, ctx->chain);
7245         list_for_each_entry_safe(rule, nr, &ctx->chain->rules, list) {
7246                 list_del(&rule->list);
7247                 ctx->chain->use--;
7248                 nf_tables_rule_release(ctx, rule);
7249         }
7250         nft_chain_del(ctx->chain);
7251         ctx->table->use--;
7252         nf_tables_chain_destroy(ctx);
7253
7254         return 0;
7255 }
7256 EXPORT_SYMBOL_GPL(__nft_release_basechain);
7257
7258 static void __nft_release_tables(struct net *net)
7259 {
7260         struct nft_flowtable *flowtable, *nf;
7261         struct nft_table *table, *nt;
7262         struct nft_chain *chain, *nc;
7263         struct nft_object *obj, *ne;
7264         struct nft_rule *rule, *nr;
7265         struct nft_set *set, *ns;
7266         struct nft_ctx ctx = {
7267                 .net    = net,
7268                 .family = NFPROTO_NETDEV,
7269         };
7270
7271         list_for_each_entry_safe(table, nt, &net->nft.tables, list) {
7272                 ctx.family = table->family;
7273
7274                 list_for_each_entry(chain, &table->chains, list)
7275                         nf_tables_unregister_hook(net, table, chain);
7276                 /* No packets are walking on these chains anymore. */
7277                 ctx.table = table;
7278                 list_for_each_entry(chain, &table->chains, list) {
7279                         ctx.chain = chain;
7280                         list_for_each_entry_safe(rule, nr, &chain->rules, list) {
7281                                 list_del(&rule->list);
7282                                 chain->use--;
7283                                 nf_tables_rule_release(&ctx, rule);
7284                         }
7285                 }
7286                 list_for_each_entry_safe(flowtable, nf, &table->flowtables, list) {
7287                         list_del(&flowtable->list);
7288                         table->use--;
7289                         nf_tables_flowtable_destroy(flowtable);
7290                 }
7291                 list_for_each_entry_safe(set, ns, &table->sets, list) {
7292                         list_del(&set->list);
7293                         table->use--;
7294                         nft_set_destroy(set);
7295                 }
7296                 list_for_each_entry_safe(obj, ne, &table->objects, list) {
7297                         list_del(&obj->list);
7298                         table->use--;
7299                         nft_obj_destroy(&ctx, obj);
7300                 }
7301                 list_for_each_entry_safe(chain, nc, &table->chains, list) {
7302                         ctx.chain = chain;
7303                         nft_chain_del(chain);
7304                         table->use--;
7305                         nf_tables_chain_destroy(&ctx);
7306                 }
7307                 list_del(&table->list);
7308                 nf_tables_table_destroy(&ctx);
7309         }
7310 }
7311
7312 static int __net_init nf_tables_init_net(struct net *net)
7313 {
7314         INIT_LIST_HEAD(&net->nft.tables);
7315         INIT_LIST_HEAD(&net->nft.commit_list);
7316         mutex_init(&net->nft.commit_mutex);
7317         net->nft.base_seq = 1;
7318         net->nft.validate_state = NFT_VALIDATE_SKIP;
7319
7320         return 0;
7321 }
7322
7323 static void __net_exit nf_tables_exit_net(struct net *net)
7324 {
7325         mutex_lock(&net->nft.commit_mutex);
7326         if (!list_empty(&net->nft.commit_list))
7327                 __nf_tables_abort(net);
7328         __nft_release_tables(net);
7329         mutex_unlock(&net->nft.commit_mutex);
7330         WARN_ON_ONCE(!list_empty(&net->nft.tables));
7331 }
7332
7333 static struct pernet_operations nf_tables_net_ops = {
7334         .init   = nf_tables_init_net,
7335         .exit   = nf_tables_exit_net,
7336 };
7337
7338 static int __init nf_tables_module_init(void)
7339 {
7340         int err;
7341
7342         spin_lock_init(&nf_tables_destroy_list_lock);
7343         err = register_pernet_subsys(&nf_tables_net_ops);
7344         if (err < 0)
7345                 return err;
7346
7347         err = nft_chain_filter_init();
7348         if (err < 0)
7349                 goto err1;
7350
7351         err = nf_tables_core_module_init();
7352         if (err < 0)
7353                 goto err2;
7354
7355         err = register_netdevice_notifier(&nf_tables_flowtable_notifier);
7356         if (err < 0)
7357                 goto err3;
7358
7359         /* must be last */
7360         err = nfnetlink_subsys_register(&nf_tables_subsys);
7361         if (err < 0)
7362                 goto err4;
7363
7364         return err;
7365 err4:
7366         unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7367 err3:
7368         nf_tables_core_module_exit();
7369 err2:
7370         nft_chain_filter_fini();
7371 err1:
7372         unregister_pernet_subsys(&nf_tables_net_ops);
7373         return err;
7374 }
7375
7376 static void __exit nf_tables_module_exit(void)
7377 {
7378         nfnetlink_subsys_unregister(&nf_tables_subsys);
7379         unregister_netdevice_notifier(&nf_tables_flowtable_notifier);
7380         nft_chain_filter_fini();
7381         unregister_pernet_subsys(&nf_tables_net_ops);
7382         cancel_work_sync(&trans_destroy_work);
7383         rcu_barrier();
7384         nf_tables_core_module_exit();
7385 }
7386
7387 module_init(nf_tables_module_init);
7388 module_exit(nf_tables_module_exit);
7389
7390 MODULE_LICENSE("GPL");
7391 MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
7392 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_NFTABLES);