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