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