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