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