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