Merge git://git.kernel.org/pub/scm/linux/kernel/git/davem/net
[cascardo/linux.git] / net / netfilter / nf_tables_api.c
1 /*
2  * Copyright (c) 2007-2009 Patrick McHardy <kaber@trash.net>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * Development of this code funded by Astaro AG (http://www.astaro.com/)
9  */
10
11 #include <linux/module.h>
12 #include <linux/init.h>
13 #include <linux/list.h>
14 #include <linux/skbuff.h>
15 #include <linux/netlink.h>
16 #include <linux/netfilter.h>
17 #include <linux/netfilter/nfnetlink.h>
18 #include <linux/netfilter/nf_tables.h>
19 #include <net/netfilter/nf_tables_core.h>
20 #include <net/netfilter/nf_tables.h>
21 #include <net/net_namespace.h>
22 #include <net/sock.h>
23
24 static LIST_HEAD(nf_tables_expressions);
25
26 /**
27  *      nft_register_afinfo - register nf_tables address family info
28  *
29  *      @afi: address family info to register
30  *
31  *      Register the address family for use with nf_tables. Returns zero on
32  *      success or a negative errno code otherwise.
33  */
34 int nft_register_afinfo(struct net *net, struct nft_af_info *afi)
35 {
36         INIT_LIST_HEAD(&afi->tables);
37         nfnl_lock(NFNL_SUBSYS_NFTABLES);
38         list_add_tail_rcu(&afi->list, &net->nft.af_info);
39         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
40         return 0;
41 }
42 EXPORT_SYMBOL_GPL(nft_register_afinfo);
43
44 /**
45  *      nft_unregister_afinfo - unregister nf_tables address family info
46  *
47  *      @afi: address family info to unregister
48  *
49  *      Unregister the address family for use with nf_tables.
50  */
51 void nft_unregister_afinfo(struct nft_af_info *afi)
52 {
53         nfnl_lock(NFNL_SUBSYS_NFTABLES);
54         list_del_rcu(&afi->list);
55         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
56 }
57 EXPORT_SYMBOL_GPL(nft_unregister_afinfo);
58
59 static struct nft_af_info *nft_afinfo_lookup(struct net *net, int family)
60 {
61         struct nft_af_info *afi;
62
63         list_for_each_entry(afi, &net->nft.af_info, list) {
64                 if (afi->family == family)
65                         return afi;
66         }
67         return NULL;
68 }
69
70 static struct nft_af_info *
71 nf_tables_afinfo_lookup(struct net *net, int family, bool autoload)
72 {
73         struct nft_af_info *afi;
74
75         afi = nft_afinfo_lookup(net, family);
76         if (afi != NULL)
77                 return afi;
78 #ifdef CONFIG_MODULES
79         if (autoload) {
80                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
81                 request_module("nft-afinfo-%u", family);
82                 nfnl_lock(NFNL_SUBSYS_NFTABLES);
83                 afi = nft_afinfo_lookup(net, family);
84                 if (afi != NULL)
85                         return ERR_PTR(-EAGAIN);
86         }
87 #endif
88         return ERR_PTR(-EAFNOSUPPORT);
89 }
90
91 static void nft_ctx_init(struct nft_ctx *ctx,
92                          const struct sk_buff *skb,
93                          const struct nlmsghdr *nlh,
94                          struct nft_af_info *afi,
95                          struct nft_table *table,
96                          struct nft_chain *chain,
97                          const struct nlattr * const *nla)
98 {
99         ctx->net        = sock_net(skb->sk);
100         ctx->afi        = afi;
101         ctx->table      = table;
102         ctx->chain      = chain;
103         ctx->nla        = nla;
104         ctx->portid     = NETLINK_CB(skb).portid;
105         ctx->report     = nlmsg_report(nlh);
106         ctx->seq        = nlh->nlmsg_seq;
107 }
108
109 static struct nft_trans *nft_trans_alloc(struct nft_ctx *ctx, int msg_type,
110                                          u32 size)
111 {
112         struct nft_trans *trans;
113
114         trans = kzalloc(sizeof(struct nft_trans) + size, GFP_KERNEL);
115         if (trans == NULL)
116                 return NULL;
117
118         trans->msg_type = msg_type;
119         trans->ctx      = *ctx;
120
121         return trans;
122 }
123
124 static void nft_trans_destroy(struct nft_trans *trans)
125 {
126         list_del(&trans->list);
127         kfree(trans);
128 }
129
130 static void nf_tables_unregister_hooks(const struct nft_table *table,
131                                        const struct nft_chain *chain,
132                                        unsigned int hook_nops)
133 {
134         if (!(table->flags & NFT_TABLE_F_DORMANT) &&
135             chain->flags & NFT_BASE_CHAIN)
136                 nf_unregister_hooks(nft_base_chain(chain)->ops, hook_nops);
137 }
138
139 /* Internal table flags */
140 #define NFT_TABLE_INACTIVE      (1 << 15)
141
142 static int nft_trans_table_add(struct nft_ctx *ctx, int msg_type)
143 {
144         struct nft_trans *trans;
145
146         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_table));
147         if (trans == NULL)
148                 return -ENOMEM;
149
150         if (msg_type == NFT_MSG_NEWTABLE)
151                 ctx->table->flags |= NFT_TABLE_INACTIVE;
152
153         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
154         return 0;
155 }
156
157 static int nft_deltable(struct nft_ctx *ctx)
158 {
159         int err;
160
161         err = nft_trans_table_add(ctx, NFT_MSG_DELTABLE);
162         if (err < 0)
163                 return err;
164
165         list_del_rcu(&ctx->table->list);
166         return err;
167 }
168
169 static int nft_trans_chain_add(struct nft_ctx *ctx, int msg_type)
170 {
171         struct nft_trans *trans;
172
173         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_chain));
174         if (trans == NULL)
175                 return -ENOMEM;
176
177         if (msg_type == NFT_MSG_NEWCHAIN)
178                 ctx->chain->flags |= NFT_CHAIN_INACTIVE;
179
180         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
181         return 0;
182 }
183
184 static int nft_delchain(struct nft_ctx *ctx)
185 {
186         int err;
187
188         err = nft_trans_chain_add(ctx, NFT_MSG_DELCHAIN);
189         if (err < 0)
190                 return err;
191
192         ctx->table->use--;
193         list_del_rcu(&ctx->chain->list);
194
195         return err;
196 }
197
198 static inline bool
199 nft_rule_is_active(struct net *net, const struct nft_rule *rule)
200 {
201         return (rule->genmask & (1 << net->nft.gencursor)) == 0;
202 }
203
204 static inline int gencursor_next(struct net *net)
205 {
206         return net->nft.gencursor+1 == 1 ? 1 : 0;
207 }
208
209 static inline int
210 nft_rule_is_active_next(struct net *net, const struct nft_rule *rule)
211 {
212         return (rule->genmask & (1 << gencursor_next(net))) == 0;
213 }
214
215 static inline void
216 nft_rule_activate_next(struct net *net, struct nft_rule *rule)
217 {
218         /* Now inactive, will be active in the future */
219         rule->genmask = (1 << net->nft.gencursor);
220 }
221
222 static inline void
223 nft_rule_deactivate_next(struct net *net, struct nft_rule *rule)
224 {
225         rule->genmask = (1 << gencursor_next(net));
226 }
227
228 static inline void nft_rule_clear(struct net *net, struct nft_rule *rule)
229 {
230         rule->genmask &= ~(1 << gencursor_next(net));
231 }
232
233 static int
234 nf_tables_delrule_deactivate(struct nft_ctx *ctx, struct nft_rule *rule)
235 {
236         /* You cannot delete the same rule twice */
237         if (nft_rule_is_active_next(ctx->net, rule)) {
238                 nft_rule_deactivate_next(ctx->net, rule);
239                 ctx->chain->use--;
240                 return 0;
241         }
242         return -ENOENT;
243 }
244
245 static struct nft_trans *nft_trans_rule_add(struct nft_ctx *ctx, int msg_type,
246                                             struct nft_rule *rule)
247 {
248         struct nft_trans *trans;
249
250         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_rule));
251         if (trans == NULL)
252                 return NULL;
253
254         nft_trans_rule(trans) = rule;
255         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
256
257         return trans;
258 }
259
260 static int nft_delrule(struct nft_ctx *ctx, struct nft_rule *rule)
261 {
262         struct nft_trans *trans;
263         int err;
264
265         trans = nft_trans_rule_add(ctx, NFT_MSG_DELRULE, rule);
266         if (trans == NULL)
267                 return -ENOMEM;
268
269         err = nf_tables_delrule_deactivate(ctx, rule);
270         if (err < 0) {
271                 nft_trans_destroy(trans);
272                 return err;
273         }
274
275         return 0;
276 }
277
278 static int nft_delrule_by_chain(struct nft_ctx *ctx)
279 {
280         struct nft_rule *rule;
281         int err;
282
283         list_for_each_entry(rule, &ctx->chain->rules, list) {
284                 err = nft_delrule(ctx, rule);
285                 if (err < 0)
286                         return err;
287         }
288         return 0;
289 }
290
291 /* Internal set flag */
292 #define NFT_SET_INACTIVE        (1 << 15)
293
294 static int nft_trans_set_add(struct nft_ctx *ctx, int msg_type,
295                              struct nft_set *set)
296 {
297         struct nft_trans *trans;
298
299         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_set));
300         if (trans == NULL)
301                 return -ENOMEM;
302
303         if (msg_type == NFT_MSG_NEWSET && ctx->nla[NFTA_SET_ID] != NULL) {
304                 nft_trans_set_id(trans) =
305                         ntohl(nla_get_be32(ctx->nla[NFTA_SET_ID]));
306                 set->flags |= NFT_SET_INACTIVE;
307         }
308         nft_trans_set(trans) = set;
309         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
310
311         return 0;
312 }
313
314 static int nft_delset(struct nft_ctx *ctx, struct nft_set *set)
315 {
316         int err;
317
318         err = nft_trans_set_add(ctx, NFT_MSG_DELSET, set);
319         if (err < 0)
320                 return err;
321
322         list_del_rcu(&set->list);
323         ctx->table->use--;
324
325         return err;
326 }
327
328 /*
329  * Tables
330  */
331
332 static struct nft_table *nft_table_lookup(const struct nft_af_info *afi,
333                                           const struct nlattr *nla)
334 {
335         struct nft_table *table;
336
337         list_for_each_entry(table, &afi->tables, list) {
338                 if (!nla_strcmp(nla, table->name))
339                         return table;
340         }
341         return NULL;
342 }
343
344 static struct nft_table *nf_tables_table_lookup(const struct nft_af_info *afi,
345                                                 const struct nlattr *nla)
346 {
347         struct nft_table *table;
348
349         if (nla == NULL)
350                 return ERR_PTR(-EINVAL);
351
352         table = nft_table_lookup(afi, nla);
353         if (table != NULL)
354                 return table;
355
356         return ERR_PTR(-ENOENT);
357 }
358
359 static inline u64 nf_tables_alloc_handle(struct nft_table *table)
360 {
361         return ++table->hgenerator;
362 }
363
364 static const struct nf_chain_type *chain_type[AF_MAX][NFT_CHAIN_T_MAX];
365
366 static const struct nf_chain_type *
367 __nf_tables_chain_type_lookup(int family, const struct nlattr *nla)
368 {
369         int i;
370
371         for (i = 0; i < NFT_CHAIN_T_MAX; i++) {
372                 if (chain_type[family][i] != NULL &&
373                     !nla_strcmp(nla, chain_type[family][i]->name))
374                         return chain_type[family][i];
375         }
376         return NULL;
377 }
378
379 static const struct nf_chain_type *
380 nf_tables_chain_type_lookup(const struct nft_af_info *afi,
381                             const struct nlattr *nla,
382                             bool autoload)
383 {
384         const struct nf_chain_type *type;
385
386         type = __nf_tables_chain_type_lookup(afi->family, nla);
387         if (type != NULL)
388                 return type;
389 #ifdef CONFIG_MODULES
390         if (autoload) {
391                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
392                 request_module("nft-chain-%u-%.*s", afi->family,
393                                nla_len(nla), (const char *)nla_data(nla));
394                 nfnl_lock(NFNL_SUBSYS_NFTABLES);
395                 type = __nf_tables_chain_type_lookup(afi->family, nla);
396                 if (type != NULL)
397                         return ERR_PTR(-EAGAIN);
398         }
399 #endif
400         return ERR_PTR(-ENOENT);
401 }
402
403 static const struct nla_policy nft_table_policy[NFTA_TABLE_MAX + 1] = {
404         [NFTA_TABLE_NAME]       = { .type = NLA_STRING,
405                                     .len = NFT_TABLE_MAXNAMELEN - 1 },
406         [NFTA_TABLE_FLAGS]      = { .type = NLA_U32 },
407 };
408
409 static int nf_tables_fill_table_info(struct sk_buff *skb, struct net *net,
410                                      u32 portid, u32 seq, int event, u32 flags,
411                                      int family, const struct nft_table *table)
412 {
413         struct nlmsghdr *nlh;
414         struct nfgenmsg *nfmsg;
415
416         event |= NFNL_SUBSYS_NFTABLES << 8;
417         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
418         if (nlh == NULL)
419                 goto nla_put_failure;
420
421         nfmsg = nlmsg_data(nlh);
422         nfmsg->nfgen_family     = family;
423         nfmsg->version          = NFNETLINK_V0;
424         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
425
426         if (nla_put_string(skb, NFTA_TABLE_NAME, table->name) ||
427             nla_put_be32(skb, NFTA_TABLE_FLAGS, htonl(table->flags)) ||
428             nla_put_be32(skb, NFTA_TABLE_USE, htonl(table->use)))
429                 goto nla_put_failure;
430
431         nlmsg_end(skb, nlh);
432         return 0;
433
434 nla_put_failure:
435         nlmsg_trim(skb, nlh);
436         return -1;
437 }
438
439 static int nf_tables_table_notify(const struct nft_ctx *ctx, int event)
440 {
441         struct sk_buff *skb;
442         int err;
443
444         if (!ctx->report &&
445             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
446                 return 0;
447
448         err = -ENOBUFS;
449         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
450         if (skb == NULL)
451                 goto err;
452
453         err = nf_tables_fill_table_info(skb, ctx->net, ctx->portid, ctx->seq,
454                                         event, 0, ctx->afi->family, ctx->table);
455         if (err < 0) {
456                 kfree_skb(skb);
457                 goto err;
458         }
459
460         err = nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
461                              ctx->report, GFP_KERNEL);
462 err:
463         if (err < 0) {
464                 nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES,
465                                   err);
466         }
467         return err;
468 }
469
470 static int nf_tables_dump_tables(struct sk_buff *skb,
471                                  struct netlink_callback *cb)
472 {
473         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
474         const struct nft_af_info *afi;
475         const struct nft_table *table;
476         unsigned int idx = 0, s_idx = cb->args[0];
477         struct net *net = sock_net(skb->sk);
478         int family = nfmsg->nfgen_family;
479
480         rcu_read_lock();
481         cb->seq = net->nft.base_seq;
482
483         list_for_each_entry_rcu(afi, &net->nft.af_info, list) {
484                 if (family != NFPROTO_UNSPEC && family != afi->family)
485                         continue;
486
487                 list_for_each_entry_rcu(table, &afi->tables, list) {
488                         if (idx < s_idx)
489                                 goto cont;
490                         if (idx > s_idx)
491                                 memset(&cb->args[1], 0,
492                                        sizeof(cb->args) - sizeof(cb->args[0]));
493                         if (nf_tables_fill_table_info(skb, net,
494                                                       NETLINK_CB(cb->skb).portid,
495                                                       cb->nlh->nlmsg_seq,
496                                                       NFT_MSG_NEWTABLE,
497                                                       NLM_F_MULTI,
498                                                       afi->family, table) < 0)
499                                 goto done;
500
501                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
502 cont:
503                         idx++;
504                 }
505         }
506 done:
507         rcu_read_unlock();
508         cb->args[0] = idx;
509         return skb->len;
510 }
511
512 static int nf_tables_gettable(struct sock *nlsk, struct sk_buff *skb,
513                               const struct nlmsghdr *nlh,
514                               const struct nlattr * const nla[])
515 {
516         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
517         const struct nft_af_info *afi;
518         const struct nft_table *table;
519         struct sk_buff *skb2;
520         struct net *net = sock_net(skb->sk);
521         int family = nfmsg->nfgen_family;
522         int err;
523
524         if (nlh->nlmsg_flags & NLM_F_DUMP) {
525                 struct netlink_dump_control c = {
526                         .dump = nf_tables_dump_tables,
527                 };
528                 return netlink_dump_start(nlsk, skb, nlh, &c);
529         }
530
531         afi = nf_tables_afinfo_lookup(net, family, false);
532         if (IS_ERR(afi))
533                 return PTR_ERR(afi);
534
535         table = nf_tables_table_lookup(afi, nla[NFTA_TABLE_NAME]);
536         if (IS_ERR(table))
537                 return PTR_ERR(table);
538         if (table->flags & NFT_TABLE_INACTIVE)
539                 return -ENOENT;
540
541         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
542         if (!skb2)
543                 return -ENOMEM;
544
545         err = nf_tables_fill_table_info(skb2, net, NETLINK_CB(skb).portid,
546                                         nlh->nlmsg_seq, NFT_MSG_NEWTABLE, 0,
547                                         family, table);
548         if (err < 0)
549                 goto err;
550
551         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
552
553 err:
554         kfree_skb(skb2);
555         return err;
556 }
557
558 static int nf_tables_table_enable(const struct nft_af_info *afi,
559                                   struct nft_table *table)
560 {
561         struct nft_chain *chain;
562         int err, i = 0;
563
564         list_for_each_entry(chain, &table->chains, list) {
565                 if (!(chain->flags & NFT_BASE_CHAIN))
566                         continue;
567
568                 err = nf_register_hooks(nft_base_chain(chain)->ops, afi->nops);
569                 if (err < 0)
570                         goto err;
571
572                 i++;
573         }
574         return 0;
575 err:
576         list_for_each_entry(chain, &table->chains, list) {
577                 if (!(chain->flags & NFT_BASE_CHAIN))
578                         continue;
579
580                 if (i-- <= 0)
581                         break;
582
583                 nf_unregister_hooks(nft_base_chain(chain)->ops, afi->nops);
584         }
585         return err;
586 }
587
588 static void nf_tables_table_disable(const struct nft_af_info *afi,
589                                    struct nft_table *table)
590 {
591         struct nft_chain *chain;
592
593         list_for_each_entry(chain, &table->chains, list) {
594                 if (chain->flags & NFT_BASE_CHAIN)
595                         nf_unregister_hooks(nft_base_chain(chain)->ops,
596                                             afi->nops);
597         }
598 }
599
600 static int nf_tables_updtable(struct nft_ctx *ctx)
601 {
602         struct nft_trans *trans;
603         u32 flags;
604         int ret = 0;
605
606         if (!ctx->nla[NFTA_TABLE_FLAGS])
607                 return 0;
608
609         flags = ntohl(nla_get_be32(ctx->nla[NFTA_TABLE_FLAGS]));
610         if (flags & ~NFT_TABLE_F_DORMANT)
611                 return -EINVAL;
612
613         if (flags == ctx->table->flags)
614                 return 0;
615
616         trans = nft_trans_alloc(ctx, NFT_MSG_NEWTABLE,
617                                 sizeof(struct nft_trans_table));
618         if (trans == NULL)
619                 return -ENOMEM;
620
621         if ((flags & NFT_TABLE_F_DORMANT) &&
622             !(ctx->table->flags & NFT_TABLE_F_DORMANT)) {
623                 nft_trans_table_enable(trans) = false;
624         } else if (!(flags & NFT_TABLE_F_DORMANT) &&
625                    ctx->table->flags & NFT_TABLE_F_DORMANT) {
626                 ret = nf_tables_table_enable(ctx->afi, ctx->table);
627                 if (ret >= 0) {
628                         ctx->table->flags &= ~NFT_TABLE_F_DORMANT;
629                         nft_trans_table_enable(trans) = true;
630                 }
631         }
632         if (ret < 0)
633                 goto err;
634
635         nft_trans_table_update(trans) = true;
636         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
637         return 0;
638 err:
639         nft_trans_destroy(trans);
640         return ret;
641 }
642
643 static int nf_tables_newtable(struct sock *nlsk, struct sk_buff *skb,
644                               const struct nlmsghdr *nlh,
645                               const struct nlattr * const nla[])
646 {
647         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
648         const struct nlattr *name;
649         struct nft_af_info *afi;
650         struct nft_table *table;
651         struct net *net = sock_net(skb->sk);
652         int family = nfmsg->nfgen_family;
653         u32 flags = 0;
654         struct nft_ctx ctx;
655         int err;
656
657         afi = nf_tables_afinfo_lookup(net, family, true);
658         if (IS_ERR(afi))
659                 return PTR_ERR(afi);
660
661         name = nla[NFTA_TABLE_NAME];
662         table = nf_tables_table_lookup(afi, name);
663         if (IS_ERR(table)) {
664                 if (PTR_ERR(table) != -ENOENT)
665                         return PTR_ERR(table);
666                 table = NULL;
667         }
668
669         if (table != NULL) {
670                 if (table->flags & NFT_TABLE_INACTIVE)
671                         return -ENOENT;
672                 if (nlh->nlmsg_flags & NLM_F_EXCL)
673                         return -EEXIST;
674                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
675                         return -EOPNOTSUPP;
676
677                 nft_ctx_init(&ctx, skb, nlh, afi, table, NULL, nla);
678                 return nf_tables_updtable(&ctx);
679         }
680
681         if (nla[NFTA_TABLE_FLAGS]) {
682                 flags = ntohl(nla_get_be32(nla[NFTA_TABLE_FLAGS]));
683                 if (flags & ~NFT_TABLE_F_DORMANT)
684                         return -EINVAL;
685         }
686
687         if (!try_module_get(afi->owner))
688                 return -EAFNOSUPPORT;
689
690         table = kzalloc(sizeof(*table), GFP_KERNEL);
691         if (table == NULL) {
692                 module_put(afi->owner);
693                 return -ENOMEM;
694         }
695
696         nla_strlcpy(table->name, name, NFT_TABLE_MAXNAMELEN);
697         INIT_LIST_HEAD(&table->chains);
698         INIT_LIST_HEAD(&table->sets);
699         table->flags = flags;
700
701         nft_ctx_init(&ctx, skb, nlh, afi, table, NULL, nla);
702         err = nft_trans_table_add(&ctx, NFT_MSG_NEWTABLE);
703         if (err < 0) {
704                 kfree(table);
705                 module_put(afi->owner);
706                 return err;
707         }
708         list_add_tail_rcu(&table->list, &afi->tables);
709         return 0;
710 }
711
712 static int nft_flush_table(struct nft_ctx *ctx)
713 {
714         int err;
715         struct nft_chain *chain, *nc;
716         struct nft_set *set, *ns;
717
718         list_for_each_entry(chain, &ctx->table->chains, list) {
719                 ctx->chain = chain;
720
721                 err = nft_delrule_by_chain(ctx);
722                 if (err < 0)
723                         goto out;
724         }
725
726         list_for_each_entry_safe(set, ns, &ctx->table->sets, list) {
727                 if (set->flags & NFT_SET_ANONYMOUS &&
728                     !list_empty(&set->bindings))
729                         continue;
730
731                 err = nft_delset(ctx, set);
732                 if (err < 0)
733                         goto out;
734         }
735
736         list_for_each_entry_safe(chain, nc, &ctx->table->chains, list) {
737                 ctx->chain = chain;
738
739                 err = nft_delchain(ctx);
740                 if (err < 0)
741                         goto out;
742         }
743
744         err = nft_deltable(ctx);
745 out:
746         return err;
747 }
748
749 static int nft_flush(struct nft_ctx *ctx, int family)
750 {
751         struct nft_af_info *afi;
752         struct nft_table *table, *nt;
753         const struct nlattr * const *nla = ctx->nla;
754         int err = 0;
755
756         list_for_each_entry(afi, &ctx->net->nft.af_info, list) {
757                 if (family != AF_UNSPEC && afi->family != family)
758                         continue;
759
760                 ctx->afi = afi;
761                 list_for_each_entry_safe(table, nt, &afi->tables, list) {
762                         if (nla[NFTA_TABLE_NAME] &&
763                             nla_strcmp(nla[NFTA_TABLE_NAME], table->name) != 0)
764                                 continue;
765
766                         ctx->table = table;
767
768                         err = nft_flush_table(ctx);
769                         if (err < 0)
770                                 goto out;
771                 }
772         }
773 out:
774         return err;
775 }
776
777 static int nf_tables_deltable(struct sock *nlsk, struct sk_buff *skb,
778                               const struct nlmsghdr *nlh,
779                               const struct nlattr * const nla[])
780 {
781         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
782         struct nft_af_info *afi;
783         struct nft_table *table;
784         struct net *net = sock_net(skb->sk);
785         int family = nfmsg->nfgen_family;
786         struct nft_ctx ctx;
787
788         nft_ctx_init(&ctx, skb, nlh, NULL, NULL, NULL, nla);
789         if (family == AF_UNSPEC || nla[NFTA_TABLE_NAME] == NULL)
790                 return nft_flush(&ctx, family);
791
792         afi = nf_tables_afinfo_lookup(net, family, false);
793         if (IS_ERR(afi))
794                 return PTR_ERR(afi);
795
796         table = nf_tables_table_lookup(afi, nla[NFTA_TABLE_NAME]);
797         if (IS_ERR(table))
798                 return PTR_ERR(table);
799         if (table->flags & NFT_TABLE_INACTIVE)
800                 return -ENOENT;
801
802         ctx.afi = afi;
803         ctx.table = table;
804
805         return nft_flush_table(&ctx);
806 }
807
808 static void nf_tables_table_destroy(struct nft_ctx *ctx)
809 {
810         BUG_ON(ctx->table->use > 0);
811
812         kfree(ctx->table);
813         module_put(ctx->afi->owner);
814 }
815
816 int nft_register_chain_type(const struct nf_chain_type *ctype)
817 {
818         int err = 0;
819
820         nfnl_lock(NFNL_SUBSYS_NFTABLES);
821         if (chain_type[ctype->family][ctype->type] != NULL) {
822                 err = -EBUSY;
823                 goto out;
824         }
825         chain_type[ctype->family][ctype->type] = ctype;
826 out:
827         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
828         return err;
829 }
830 EXPORT_SYMBOL_GPL(nft_register_chain_type);
831
832 void nft_unregister_chain_type(const struct nf_chain_type *ctype)
833 {
834         nfnl_lock(NFNL_SUBSYS_NFTABLES);
835         chain_type[ctype->family][ctype->type] = NULL;
836         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
837 }
838 EXPORT_SYMBOL_GPL(nft_unregister_chain_type);
839
840 /*
841  * Chains
842  */
843
844 static struct nft_chain *
845 nf_tables_chain_lookup_byhandle(const struct nft_table *table, u64 handle)
846 {
847         struct nft_chain *chain;
848
849         list_for_each_entry(chain, &table->chains, list) {
850                 if (chain->handle == handle)
851                         return chain;
852         }
853
854         return ERR_PTR(-ENOENT);
855 }
856
857 static struct nft_chain *nf_tables_chain_lookup(const struct nft_table *table,
858                                                 const struct nlattr *nla)
859 {
860         struct nft_chain *chain;
861
862         if (nla == NULL)
863                 return ERR_PTR(-EINVAL);
864
865         list_for_each_entry(chain, &table->chains, list) {
866                 if (!nla_strcmp(nla, chain->name))
867                         return chain;
868         }
869
870         return ERR_PTR(-ENOENT);
871 }
872
873 static const struct nla_policy nft_chain_policy[NFTA_CHAIN_MAX + 1] = {
874         [NFTA_CHAIN_TABLE]      = { .type = NLA_STRING },
875         [NFTA_CHAIN_HANDLE]     = { .type = NLA_U64 },
876         [NFTA_CHAIN_NAME]       = { .type = NLA_STRING,
877                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
878         [NFTA_CHAIN_HOOK]       = { .type = NLA_NESTED },
879         [NFTA_CHAIN_POLICY]     = { .type = NLA_U32 },
880         [NFTA_CHAIN_TYPE]       = { .type = NLA_STRING },
881         [NFTA_CHAIN_COUNTERS]   = { .type = NLA_NESTED },
882 };
883
884 static const struct nla_policy nft_hook_policy[NFTA_HOOK_MAX + 1] = {
885         [NFTA_HOOK_HOOKNUM]     = { .type = NLA_U32 },
886         [NFTA_HOOK_PRIORITY]    = { .type = NLA_U32 },
887 };
888
889 static int nft_dump_stats(struct sk_buff *skb, struct nft_stats __percpu *stats)
890 {
891         struct nft_stats *cpu_stats, total;
892         struct nlattr *nest;
893         unsigned int seq;
894         u64 pkts, bytes;
895         int cpu;
896
897         memset(&total, 0, sizeof(total));
898         for_each_possible_cpu(cpu) {
899                 cpu_stats = per_cpu_ptr(stats, cpu);
900                 do {
901                         seq = u64_stats_fetch_begin_irq(&cpu_stats->syncp);
902                         pkts = cpu_stats->pkts;
903                         bytes = cpu_stats->bytes;
904                 } while (u64_stats_fetch_retry_irq(&cpu_stats->syncp, seq));
905                 total.pkts += pkts;
906                 total.bytes += bytes;
907         }
908         nest = nla_nest_start(skb, NFTA_CHAIN_COUNTERS);
909         if (nest == NULL)
910                 goto nla_put_failure;
911
912         if (nla_put_be64(skb, NFTA_COUNTER_PACKETS, cpu_to_be64(total.pkts)) ||
913             nla_put_be64(skb, NFTA_COUNTER_BYTES, cpu_to_be64(total.bytes)))
914                 goto nla_put_failure;
915
916         nla_nest_end(skb, nest);
917         return 0;
918
919 nla_put_failure:
920         return -ENOSPC;
921 }
922
923 static int nf_tables_fill_chain_info(struct sk_buff *skb, struct net *net,
924                                      u32 portid, u32 seq, int event, u32 flags,
925                                      int family, const struct nft_table *table,
926                                      const struct nft_chain *chain)
927 {
928         struct nlmsghdr *nlh;
929         struct nfgenmsg *nfmsg;
930
931         event |= NFNL_SUBSYS_NFTABLES << 8;
932         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), flags);
933         if (nlh == NULL)
934                 goto nla_put_failure;
935
936         nfmsg = nlmsg_data(nlh);
937         nfmsg->nfgen_family     = family;
938         nfmsg->version          = NFNETLINK_V0;
939         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
940
941         if (nla_put_string(skb, NFTA_CHAIN_TABLE, table->name))
942                 goto nla_put_failure;
943         if (nla_put_be64(skb, NFTA_CHAIN_HANDLE, cpu_to_be64(chain->handle)))
944                 goto nla_put_failure;
945         if (nla_put_string(skb, NFTA_CHAIN_NAME, chain->name))
946                 goto nla_put_failure;
947
948         if (chain->flags & NFT_BASE_CHAIN) {
949                 const struct nft_base_chain *basechain = nft_base_chain(chain);
950                 const struct nf_hook_ops *ops = &basechain->ops[0];
951                 struct nlattr *nest;
952
953                 nest = nla_nest_start(skb, NFTA_CHAIN_HOOK);
954                 if (nest == NULL)
955                         goto nla_put_failure;
956                 if (nla_put_be32(skb, NFTA_HOOK_HOOKNUM, htonl(ops->hooknum)))
957                         goto nla_put_failure;
958                 if (nla_put_be32(skb, NFTA_HOOK_PRIORITY, htonl(ops->priority)))
959                         goto nla_put_failure;
960                 nla_nest_end(skb, nest);
961
962                 if (nla_put_be32(skb, NFTA_CHAIN_POLICY,
963                                  htonl(basechain->policy)))
964                         goto nla_put_failure;
965
966                 if (nla_put_string(skb, NFTA_CHAIN_TYPE, basechain->type->name))
967                         goto nla_put_failure;
968
969                 if (nft_dump_stats(skb, nft_base_chain(chain)->stats))
970                         goto nla_put_failure;
971         }
972
973         if (nla_put_be32(skb, NFTA_CHAIN_USE, htonl(chain->use)))
974                 goto nla_put_failure;
975
976         nlmsg_end(skb, nlh);
977         return 0;
978
979 nla_put_failure:
980         nlmsg_trim(skb, nlh);
981         return -1;
982 }
983
984 static int nf_tables_chain_notify(const struct nft_ctx *ctx, int event)
985 {
986         struct sk_buff *skb;
987         int err;
988
989         if (!ctx->report &&
990             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
991                 return 0;
992
993         err = -ENOBUFS;
994         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
995         if (skb == NULL)
996                 goto err;
997
998         err = nf_tables_fill_chain_info(skb, ctx->net, ctx->portid, ctx->seq,
999                                         event, 0, ctx->afi->family, ctx->table,
1000                                         ctx->chain);
1001         if (err < 0) {
1002                 kfree_skb(skb);
1003                 goto err;
1004         }
1005
1006         err = nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1007                              ctx->report, GFP_KERNEL);
1008 err:
1009         if (err < 0) {
1010                 nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1011                                   err);
1012         }
1013         return err;
1014 }
1015
1016 static int nf_tables_dump_chains(struct sk_buff *skb,
1017                                  struct netlink_callback *cb)
1018 {
1019         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1020         const struct nft_af_info *afi;
1021         const struct nft_table *table;
1022         const struct nft_chain *chain;
1023         unsigned int idx = 0, s_idx = cb->args[0];
1024         struct net *net = sock_net(skb->sk);
1025         int family = nfmsg->nfgen_family;
1026
1027         rcu_read_lock();
1028         cb->seq = net->nft.base_seq;
1029
1030         list_for_each_entry_rcu(afi, &net->nft.af_info, list) {
1031                 if (family != NFPROTO_UNSPEC && family != afi->family)
1032                         continue;
1033
1034                 list_for_each_entry_rcu(table, &afi->tables, list) {
1035                         list_for_each_entry_rcu(chain, &table->chains, list) {
1036                                 if (idx < s_idx)
1037                                         goto cont;
1038                                 if (idx > s_idx)
1039                                         memset(&cb->args[1], 0,
1040                                                sizeof(cb->args) - sizeof(cb->args[0]));
1041                                 if (nf_tables_fill_chain_info(skb, net,
1042                                                               NETLINK_CB(cb->skb).portid,
1043                                                               cb->nlh->nlmsg_seq,
1044                                                               NFT_MSG_NEWCHAIN,
1045                                                               NLM_F_MULTI,
1046                                                               afi->family, table, chain) < 0)
1047                                         goto done;
1048
1049                                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1050 cont:
1051                                 idx++;
1052                         }
1053                 }
1054         }
1055 done:
1056         rcu_read_unlock();
1057         cb->args[0] = idx;
1058         return skb->len;
1059 }
1060
1061 static int nf_tables_getchain(struct sock *nlsk, struct sk_buff *skb,
1062                               const struct nlmsghdr *nlh,
1063                               const struct nlattr * const nla[])
1064 {
1065         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1066         const struct nft_af_info *afi;
1067         const struct nft_table *table;
1068         const struct nft_chain *chain;
1069         struct sk_buff *skb2;
1070         struct net *net = sock_net(skb->sk);
1071         int family = nfmsg->nfgen_family;
1072         int err;
1073
1074         if (nlh->nlmsg_flags & NLM_F_DUMP) {
1075                 struct netlink_dump_control c = {
1076                         .dump = nf_tables_dump_chains,
1077                 };
1078                 return netlink_dump_start(nlsk, skb, nlh, &c);
1079         }
1080
1081         afi = nf_tables_afinfo_lookup(net, family, false);
1082         if (IS_ERR(afi))
1083                 return PTR_ERR(afi);
1084
1085         table = nf_tables_table_lookup(afi, nla[NFTA_CHAIN_TABLE]);
1086         if (IS_ERR(table))
1087                 return PTR_ERR(table);
1088         if (table->flags & NFT_TABLE_INACTIVE)
1089                 return -ENOENT;
1090
1091         chain = nf_tables_chain_lookup(table, nla[NFTA_CHAIN_NAME]);
1092         if (IS_ERR(chain))
1093                 return PTR_ERR(chain);
1094         if (chain->flags & NFT_CHAIN_INACTIVE)
1095                 return -ENOENT;
1096
1097         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
1098         if (!skb2)
1099                 return -ENOMEM;
1100
1101         err = nf_tables_fill_chain_info(skb2, net, NETLINK_CB(skb).portid,
1102                                         nlh->nlmsg_seq, NFT_MSG_NEWCHAIN, 0,
1103                                         family, table, chain);
1104         if (err < 0)
1105                 goto err;
1106
1107         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
1108
1109 err:
1110         kfree_skb(skb2);
1111         return err;
1112 }
1113
1114 static const struct nla_policy nft_counter_policy[NFTA_COUNTER_MAX + 1] = {
1115         [NFTA_COUNTER_PACKETS]  = { .type = NLA_U64 },
1116         [NFTA_COUNTER_BYTES]    = { .type = NLA_U64 },
1117 };
1118
1119 static struct nft_stats __percpu *nft_stats_alloc(const struct nlattr *attr)
1120 {
1121         struct nlattr *tb[NFTA_COUNTER_MAX+1];
1122         struct nft_stats __percpu *newstats;
1123         struct nft_stats *stats;
1124         int err;
1125
1126         err = nla_parse_nested(tb, NFTA_COUNTER_MAX, attr, nft_counter_policy);
1127         if (err < 0)
1128                 return ERR_PTR(err);
1129
1130         if (!tb[NFTA_COUNTER_BYTES] || !tb[NFTA_COUNTER_PACKETS])
1131                 return ERR_PTR(-EINVAL);
1132
1133         newstats = netdev_alloc_pcpu_stats(struct nft_stats);
1134         if (newstats == NULL)
1135                 return ERR_PTR(-ENOMEM);
1136
1137         /* Restore old counters on this cpu, no problem. Per-cpu statistics
1138          * are not exposed to userspace.
1139          */
1140         preempt_disable();
1141         stats = this_cpu_ptr(newstats);
1142         stats->bytes = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_BYTES]));
1143         stats->pkts = be64_to_cpu(nla_get_be64(tb[NFTA_COUNTER_PACKETS]));
1144         preempt_enable();
1145
1146         return newstats;
1147 }
1148
1149 static void nft_chain_stats_replace(struct nft_base_chain *chain,
1150                                     struct nft_stats __percpu *newstats)
1151 {
1152         if (newstats == NULL)
1153                 return;
1154
1155         if (chain->stats) {
1156                 struct nft_stats __percpu *oldstats =
1157                                 nft_dereference(chain->stats);
1158
1159                 rcu_assign_pointer(chain->stats, newstats);
1160                 synchronize_rcu();
1161                 free_percpu(oldstats);
1162         } else
1163                 rcu_assign_pointer(chain->stats, newstats);
1164 }
1165
1166 static void nf_tables_chain_destroy(struct nft_chain *chain)
1167 {
1168         BUG_ON(chain->use > 0);
1169
1170         if (chain->flags & NFT_BASE_CHAIN) {
1171                 module_put(nft_base_chain(chain)->type->owner);
1172                 free_percpu(nft_base_chain(chain)->stats);
1173                 kfree(nft_base_chain(chain));
1174         } else {
1175                 kfree(chain);
1176         }
1177 }
1178
1179 static int nf_tables_newchain(struct sock *nlsk, struct sk_buff *skb,
1180                               const struct nlmsghdr *nlh,
1181                               const struct nlattr * const nla[])
1182 {
1183         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1184         const struct nlattr * uninitialized_var(name);
1185         struct nft_af_info *afi;
1186         struct nft_table *table;
1187         struct nft_chain *chain;
1188         struct nft_base_chain *basechain = NULL;
1189         struct nlattr *ha[NFTA_HOOK_MAX + 1];
1190         struct net *net = sock_net(skb->sk);
1191         int family = nfmsg->nfgen_family;
1192         u8 policy = NF_ACCEPT;
1193         u64 handle = 0;
1194         unsigned int i;
1195         struct nft_stats __percpu *stats;
1196         int err;
1197         bool create;
1198         struct nft_ctx ctx;
1199
1200         create = nlh->nlmsg_flags & NLM_F_CREATE ? true : false;
1201
1202         afi = nf_tables_afinfo_lookup(net, family, true);
1203         if (IS_ERR(afi))
1204                 return PTR_ERR(afi);
1205
1206         table = nf_tables_table_lookup(afi, nla[NFTA_CHAIN_TABLE]);
1207         if (IS_ERR(table))
1208                 return PTR_ERR(table);
1209
1210         chain = NULL;
1211         name = nla[NFTA_CHAIN_NAME];
1212
1213         if (nla[NFTA_CHAIN_HANDLE]) {
1214                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_CHAIN_HANDLE]));
1215                 chain = nf_tables_chain_lookup_byhandle(table, handle);
1216                 if (IS_ERR(chain))
1217                         return PTR_ERR(chain);
1218         } else {
1219                 chain = nf_tables_chain_lookup(table, name);
1220                 if (IS_ERR(chain)) {
1221                         if (PTR_ERR(chain) != -ENOENT)
1222                                 return PTR_ERR(chain);
1223                         chain = NULL;
1224                 }
1225         }
1226
1227         if (nla[NFTA_CHAIN_POLICY]) {
1228                 if ((chain != NULL &&
1229                     !(chain->flags & NFT_BASE_CHAIN)) ||
1230                     nla[NFTA_CHAIN_HOOK] == NULL)
1231                         return -EOPNOTSUPP;
1232
1233                 policy = ntohl(nla_get_be32(nla[NFTA_CHAIN_POLICY]));
1234                 switch (policy) {
1235                 case NF_DROP:
1236                 case NF_ACCEPT:
1237                         break;
1238                 default:
1239                         return -EINVAL;
1240                 }
1241         }
1242
1243         if (chain != NULL) {
1244                 struct nft_stats *stats = NULL;
1245                 struct nft_trans *trans;
1246
1247                 if (chain->flags & NFT_CHAIN_INACTIVE)
1248                         return -ENOENT;
1249                 if (nlh->nlmsg_flags & NLM_F_EXCL)
1250                         return -EEXIST;
1251                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
1252                         return -EOPNOTSUPP;
1253
1254                 if (nla[NFTA_CHAIN_HANDLE] && name &&
1255                     !IS_ERR(nf_tables_chain_lookup(table, nla[NFTA_CHAIN_NAME])))
1256                         return -EEXIST;
1257
1258                 if (nla[NFTA_CHAIN_COUNTERS]) {
1259                         if (!(chain->flags & NFT_BASE_CHAIN))
1260                                 return -EOPNOTSUPP;
1261
1262                         stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1263                         if (IS_ERR(stats))
1264                                 return PTR_ERR(stats);
1265                 }
1266
1267                 nft_ctx_init(&ctx, skb, nlh, afi, table, chain, nla);
1268                 trans = nft_trans_alloc(&ctx, NFT_MSG_NEWCHAIN,
1269                                         sizeof(struct nft_trans_chain));
1270                 if (trans == NULL) {
1271                         free_percpu(stats);
1272                         return -ENOMEM;
1273                 }
1274
1275                 nft_trans_chain_stats(trans) = stats;
1276                 nft_trans_chain_update(trans) = true;
1277
1278                 if (nla[NFTA_CHAIN_POLICY])
1279                         nft_trans_chain_policy(trans) = policy;
1280                 else
1281                         nft_trans_chain_policy(trans) = -1;
1282
1283                 if (nla[NFTA_CHAIN_HANDLE] && name) {
1284                         nla_strlcpy(nft_trans_chain_name(trans), name,
1285                                     NFT_CHAIN_MAXNAMELEN);
1286                 }
1287                 list_add_tail(&trans->list, &net->nft.commit_list);
1288                 return 0;
1289         }
1290
1291         if (table->use == UINT_MAX)
1292                 return -EOVERFLOW;
1293
1294         if (nla[NFTA_CHAIN_HOOK]) {
1295                 const struct nf_chain_type *type;
1296                 struct nf_hook_ops *ops;
1297                 nf_hookfn *hookfn;
1298                 u32 hooknum, priority;
1299
1300                 type = chain_type[family][NFT_CHAIN_T_DEFAULT];
1301                 if (nla[NFTA_CHAIN_TYPE]) {
1302                         type = nf_tables_chain_type_lookup(afi,
1303                                                            nla[NFTA_CHAIN_TYPE],
1304                                                            create);
1305                         if (IS_ERR(type))
1306                                 return PTR_ERR(type);
1307                 }
1308
1309                 err = nla_parse_nested(ha, NFTA_HOOK_MAX, nla[NFTA_CHAIN_HOOK],
1310                                        nft_hook_policy);
1311                 if (err < 0)
1312                         return err;
1313                 if (ha[NFTA_HOOK_HOOKNUM] == NULL ||
1314                     ha[NFTA_HOOK_PRIORITY] == NULL)
1315                         return -EINVAL;
1316
1317                 hooknum = ntohl(nla_get_be32(ha[NFTA_HOOK_HOOKNUM]));
1318                 if (hooknum >= afi->nhooks)
1319                         return -EINVAL;
1320                 priority = ntohl(nla_get_be32(ha[NFTA_HOOK_PRIORITY]));
1321
1322                 if (!(type->hook_mask & (1 << hooknum)))
1323                         return -EOPNOTSUPP;
1324                 if (!try_module_get(type->owner))
1325                         return -ENOENT;
1326                 hookfn = type->hooks[hooknum];
1327
1328                 basechain = kzalloc(sizeof(*basechain), GFP_KERNEL);
1329                 if (basechain == NULL) {
1330                         module_put(type->owner);
1331                         return -ENOMEM;
1332                 }
1333
1334                 if (nla[NFTA_CHAIN_COUNTERS]) {
1335                         stats = nft_stats_alloc(nla[NFTA_CHAIN_COUNTERS]);
1336                         if (IS_ERR(stats)) {
1337                                 module_put(type->owner);
1338                                 kfree(basechain);
1339                                 return PTR_ERR(stats);
1340                         }
1341                         basechain->stats = stats;
1342                 } else {
1343                         stats = netdev_alloc_pcpu_stats(struct nft_stats);
1344                         if (stats == NULL) {
1345                                 module_put(type->owner);
1346                                 kfree(basechain);
1347                                 return -ENOMEM;
1348                         }
1349                         rcu_assign_pointer(basechain->stats, stats);
1350                 }
1351
1352                 basechain->type = type;
1353                 chain = &basechain->chain;
1354
1355                 for (i = 0; i < afi->nops; i++) {
1356                         ops = &basechain->ops[i];
1357                         ops->pf         = family;
1358                         ops->owner      = afi->owner;
1359                         ops->hooknum    = hooknum;
1360                         ops->priority   = priority;
1361                         ops->priv       = chain;
1362                         ops->hook       = afi->hooks[ops->hooknum];
1363                         if (hookfn)
1364                                 ops->hook = hookfn;
1365                         if (afi->hook_ops_init)
1366                                 afi->hook_ops_init(ops, i);
1367                 }
1368
1369                 chain->flags |= NFT_BASE_CHAIN;
1370                 basechain->policy = policy;
1371         } else {
1372                 chain = kzalloc(sizeof(*chain), GFP_KERNEL);
1373                 if (chain == NULL)
1374                         return -ENOMEM;
1375         }
1376
1377         INIT_LIST_HEAD(&chain->rules);
1378         chain->handle = nf_tables_alloc_handle(table);
1379         chain->net = net;
1380         chain->table = table;
1381         nla_strlcpy(chain->name, name, NFT_CHAIN_MAXNAMELEN);
1382
1383         if (!(table->flags & NFT_TABLE_F_DORMANT) &&
1384             chain->flags & NFT_BASE_CHAIN) {
1385                 err = nf_register_hooks(nft_base_chain(chain)->ops, afi->nops);
1386                 if (err < 0)
1387                         goto err1;
1388         }
1389
1390         nft_ctx_init(&ctx, skb, nlh, afi, table, chain, nla);
1391         err = nft_trans_chain_add(&ctx, NFT_MSG_NEWCHAIN);
1392         if (err < 0)
1393                 goto err2;
1394
1395         table->use++;
1396         list_add_tail_rcu(&chain->list, &table->chains);
1397         return 0;
1398 err2:
1399         nf_tables_unregister_hooks(table, chain, afi->nops);
1400 err1:
1401         nf_tables_chain_destroy(chain);
1402         return err;
1403 }
1404
1405 static int nf_tables_delchain(struct sock *nlsk, struct sk_buff *skb,
1406                               const struct nlmsghdr *nlh,
1407                               const struct nlattr * const nla[])
1408 {
1409         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1410         struct nft_af_info *afi;
1411         struct nft_table *table;
1412         struct nft_chain *chain;
1413         struct net *net = sock_net(skb->sk);
1414         int family = nfmsg->nfgen_family;
1415         struct nft_ctx ctx;
1416
1417         afi = nf_tables_afinfo_lookup(net, family, false);
1418         if (IS_ERR(afi))
1419                 return PTR_ERR(afi);
1420
1421         table = nf_tables_table_lookup(afi, nla[NFTA_CHAIN_TABLE]);
1422         if (IS_ERR(table))
1423                 return PTR_ERR(table);
1424         if (table->flags & NFT_TABLE_INACTIVE)
1425                 return -ENOENT;
1426
1427         chain = nf_tables_chain_lookup(table, nla[NFTA_CHAIN_NAME]);
1428         if (IS_ERR(chain))
1429                 return PTR_ERR(chain);
1430         if (chain->flags & NFT_CHAIN_INACTIVE)
1431                 return -ENOENT;
1432         if (chain->use > 0)
1433                 return -EBUSY;
1434
1435         nft_ctx_init(&ctx, skb, nlh, afi, table, chain, nla);
1436
1437         return nft_delchain(&ctx);
1438 }
1439
1440 /*
1441  * Expressions
1442  */
1443
1444 /**
1445  *      nft_register_expr - register nf_tables expr type
1446  *      @ops: expr type
1447  *
1448  *      Registers the expr type for use with nf_tables. Returns zero on
1449  *      success or a negative errno code otherwise.
1450  */
1451 int nft_register_expr(struct nft_expr_type *type)
1452 {
1453         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1454         if (type->family == NFPROTO_UNSPEC)
1455                 list_add_tail_rcu(&type->list, &nf_tables_expressions);
1456         else
1457                 list_add_rcu(&type->list, &nf_tables_expressions);
1458         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1459         return 0;
1460 }
1461 EXPORT_SYMBOL_GPL(nft_register_expr);
1462
1463 /**
1464  *      nft_unregister_expr - unregister nf_tables expr type
1465  *      @ops: expr type
1466  *
1467  *      Unregisters the expr typefor use with nf_tables.
1468  */
1469 void nft_unregister_expr(struct nft_expr_type *type)
1470 {
1471         nfnl_lock(NFNL_SUBSYS_NFTABLES);
1472         list_del_rcu(&type->list);
1473         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1474 }
1475 EXPORT_SYMBOL_GPL(nft_unregister_expr);
1476
1477 static const struct nft_expr_type *__nft_expr_type_get(u8 family,
1478                                                        struct nlattr *nla)
1479 {
1480         const struct nft_expr_type *type;
1481
1482         list_for_each_entry(type, &nf_tables_expressions, list) {
1483                 if (!nla_strcmp(nla, type->name) &&
1484                     (!type->family || type->family == family))
1485                         return type;
1486         }
1487         return NULL;
1488 }
1489
1490 static const struct nft_expr_type *nft_expr_type_get(u8 family,
1491                                                      struct nlattr *nla)
1492 {
1493         const struct nft_expr_type *type;
1494
1495         if (nla == NULL)
1496                 return ERR_PTR(-EINVAL);
1497
1498         type = __nft_expr_type_get(family, nla);
1499         if (type != NULL && try_module_get(type->owner))
1500                 return type;
1501
1502 #ifdef CONFIG_MODULES
1503         if (type == NULL) {
1504                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1505                 request_module("nft-expr-%u-%.*s", family,
1506                                nla_len(nla), (char *)nla_data(nla));
1507                 nfnl_lock(NFNL_SUBSYS_NFTABLES);
1508                 if (__nft_expr_type_get(family, nla))
1509                         return ERR_PTR(-EAGAIN);
1510
1511                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
1512                 request_module("nft-expr-%.*s",
1513                                nla_len(nla), (char *)nla_data(nla));
1514                 nfnl_lock(NFNL_SUBSYS_NFTABLES);
1515                 if (__nft_expr_type_get(family, nla))
1516                         return ERR_PTR(-EAGAIN);
1517         }
1518 #endif
1519         return ERR_PTR(-ENOENT);
1520 }
1521
1522 static const struct nla_policy nft_expr_policy[NFTA_EXPR_MAX + 1] = {
1523         [NFTA_EXPR_NAME]        = { .type = NLA_STRING },
1524         [NFTA_EXPR_DATA]        = { .type = NLA_NESTED },
1525 };
1526
1527 static int nf_tables_fill_expr_info(struct sk_buff *skb,
1528                                     const struct nft_expr *expr)
1529 {
1530         if (nla_put_string(skb, NFTA_EXPR_NAME, expr->ops->type->name))
1531                 goto nla_put_failure;
1532
1533         if (expr->ops->dump) {
1534                 struct nlattr *data = nla_nest_start(skb, NFTA_EXPR_DATA);
1535                 if (data == NULL)
1536                         goto nla_put_failure;
1537                 if (expr->ops->dump(skb, expr) < 0)
1538                         goto nla_put_failure;
1539                 nla_nest_end(skb, data);
1540         }
1541
1542         return skb->len;
1543
1544 nla_put_failure:
1545         return -1;
1546 };
1547
1548 struct nft_expr_info {
1549         const struct nft_expr_ops       *ops;
1550         struct nlattr                   *tb[NFT_EXPR_MAXATTR + 1];
1551 };
1552
1553 static int nf_tables_expr_parse(const struct nft_ctx *ctx,
1554                                 const struct nlattr *nla,
1555                                 struct nft_expr_info *info)
1556 {
1557         const struct nft_expr_type *type;
1558         const struct nft_expr_ops *ops;
1559         struct nlattr *tb[NFTA_EXPR_MAX + 1];
1560         int err;
1561
1562         err = nla_parse_nested(tb, NFTA_EXPR_MAX, nla, nft_expr_policy);
1563         if (err < 0)
1564                 return err;
1565
1566         type = nft_expr_type_get(ctx->afi->family, tb[NFTA_EXPR_NAME]);
1567         if (IS_ERR(type))
1568                 return PTR_ERR(type);
1569
1570         if (tb[NFTA_EXPR_DATA]) {
1571                 err = nla_parse_nested(info->tb, type->maxattr,
1572                                        tb[NFTA_EXPR_DATA], type->policy);
1573                 if (err < 0)
1574                         goto err1;
1575         } else
1576                 memset(info->tb, 0, sizeof(info->tb[0]) * (type->maxattr + 1));
1577
1578         if (type->select_ops != NULL) {
1579                 ops = type->select_ops(ctx,
1580                                        (const struct nlattr * const *)info->tb);
1581                 if (IS_ERR(ops)) {
1582                         err = PTR_ERR(ops);
1583                         goto err1;
1584                 }
1585         } else
1586                 ops = type->ops;
1587
1588         info->ops = ops;
1589         return 0;
1590
1591 err1:
1592         module_put(type->owner);
1593         return err;
1594 }
1595
1596 static int nf_tables_newexpr(const struct nft_ctx *ctx,
1597                              const struct nft_expr_info *info,
1598                              struct nft_expr *expr)
1599 {
1600         const struct nft_expr_ops *ops = info->ops;
1601         int err;
1602
1603         expr->ops = ops;
1604         if (ops->init) {
1605                 err = ops->init(ctx, expr, (const struct nlattr **)info->tb);
1606                 if (err < 0)
1607                         goto err1;
1608         }
1609
1610         return 0;
1611
1612 err1:
1613         expr->ops = NULL;
1614         return err;
1615 }
1616
1617 static void nf_tables_expr_destroy(const struct nft_ctx *ctx,
1618                                    struct nft_expr *expr)
1619 {
1620         if (expr->ops->destroy)
1621                 expr->ops->destroy(ctx, expr);
1622         module_put(expr->ops->type->owner);
1623 }
1624
1625 /*
1626  * Rules
1627  */
1628
1629 static struct nft_rule *__nf_tables_rule_lookup(const struct nft_chain *chain,
1630                                                 u64 handle)
1631 {
1632         struct nft_rule *rule;
1633
1634         // FIXME: this sucks
1635         list_for_each_entry(rule, &chain->rules, list) {
1636                 if (handle == rule->handle)
1637                         return rule;
1638         }
1639
1640         return ERR_PTR(-ENOENT);
1641 }
1642
1643 static struct nft_rule *nf_tables_rule_lookup(const struct nft_chain *chain,
1644                                               const struct nlattr *nla)
1645 {
1646         if (nla == NULL)
1647                 return ERR_PTR(-EINVAL);
1648
1649         return __nf_tables_rule_lookup(chain, be64_to_cpu(nla_get_be64(nla)));
1650 }
1651
1652 static const struct nla_policy nft_rule_policy[NFTA_RULE_MAX + 1] = {
1653         [NFTA_RULE_TABLE]       = { .type = NLA_STRING },
1654         [NFTA_RULE_CHAIN]       = { .type = NLA_STRING,
1655                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
1656         [NFTA_RULE_HANDLE]      = { .type = NLA_U64 },
1657         [NFTA_RULE_EXPRESSIONS] = { .type = NLA_NESTED },
1658         [NFTA_RULE_COMPAT]      = { .type = NLA_NESTED },
1659         [NFTA_RULE_POSITION]    = { .type = NLA_U64 },
1660         [NFTA_RULE_USERDATA]    = { .type = NLA_BINARY,
1661                                     .len = NFT_USERDATA_MAXLEN },
1662 };
1663
1664 static int nf_tables_fill_rule_info(struct sk_buff *skb, struct net *net,
1665                                     u32 portid, u32 seq, int event,
1666                                     u32 flags, int family,
1667                                     const struct nft_table *table,
1668                                     const struct nft_chain *chain,
1669                                     const struct nft_rule *rule)
1670 {
1671         struct nlmsghdr *nlh;
1672         struct nfgenmsg *nfmsg;
1673         const struct nft_expr *expr, *next;
1674         struct nlattr *list;
1675         const struct nft_rule *prule;
1676         int type = event | NFNL_SUBSYS_NFTABLES << 8;
1677
1678         nlh = nlmsg_put(skb, portid, seq, type, sizeof(struct nfgenmsg),
1679                         flags);
1680         if (nlh == NULL)
1681                 goto nla_put_failure;
1682
1683         nfmsg = nlmsg_data(nlh);
1684         nfmsg->nfgen_family     = family;
1685         nfmsg->version          = NFNETLINK_V0;
1686         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
1687
1688         if (nla_put_string(skb, NFTA_RULE_TABLE, table->name))
1689                 goto nla_put_failure;
1690         if (nla_put_string(skb, NFTA_RULE_CHAIN, chain->name))
1691                 goto nla_put_failure;
1692         if (nla_put_be64(skb, NFTA_RULE_HANDLE, cpu_to_be64(rule->handle)))
1693                 goto nla_put_failure;
1694
1695         if ((event != NFT_MSG_DELRULE) && (rule->list.prev != &chain->rules)) {
1696                 prule = list_entry(rule->list.prev, struct nft_rule, list);
1697                 if (nla_put_be64(skb, NFTA_RULE_POSITION,
1698                                  cpu_to_be64(prule->handle)))
1699                         goto nla_put_failure;
1700         }
1701
1702         list = nla_nest_start(skb, NFTA_RULE_EXPRESSIONS);
1703         if (list == NULL)
1704                 goto nla_put_failure;
1705         nft_rule_for_each_expr(expr, next, rule) {
1706                 struct nlattr *elem = nla_nest_start(skb, NFTA_LIST_ELEM);
1707                 if (elem == NULL)
1708                         goto nla_put_failure;
1709                 if (nf_tables_fill_expr_info(skb, expr) < 0)
1710                         goto nla_put_failure;
1711                 nla_nest_end(skb, elem);
1712         }
1713         nla_nest_end(skb, list);
1714
1715         if (rule->udata) {
1716                 struct nft_userdata *udata = nft_userdata(rule);
1717                 if (nla_put(skb, NFTA_RULE_USERDATA, udata->len + 1,
1718                             udata->data) < 0)
1719                         goto nla_put_failure;
1720         }
1721
1722         nlmsg_end(skb, nlh);
1723         return 0;
1724
1725 nla_put_failure:
1726         nlmsg_trim(skb, nlh);
1727         return -1;
1728 }
1729
1730 static int nf_tables_rule_notify(const struct nft_ctx *ctx,
1731                                  const struct nft_rule *rule,
1732                                  int event)
1733 {
1734         struct sk_buff *skb;
1735         int err;
1736
1737         if (!ctx->report &&
1738             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
1739                 return 0;
1740
1741         err = -ENOBUFS;
1742         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
1743         if (skb == NULL)
1744                 goto err;
1745
1746         err = nf_tables_fill_rule_info(skb, ctx->net, ctx->portid, ctx->seq,
1747                                        event, 0, ctx->afi->family, ctx->table,
1748                                        ctx->chain, rule);
1749         if (err < 0) {
1750                 kfree_skb(skb);
1751                 goto err;
1752         }
1753
1754         err = nfnetlink_send(skb, ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1755                              ctx->report, GFP_KERNEL);
1756 err:
1757         if (err < 0) {
1758                 nfnetlink_set_err(ctx->net, ctx->portid, NFNLGRP_NFTABLES,
1759                                   err);
1760         }
1761         return err;
1762 }
1763
1764 static int nf_tables_dump_rules(struct sk_buff *skb,
1765                                 struct netlink_callback *cb)
1766 {
1767         const struct nfgenmsg *nfmsg = nlmsg_data(cb->nlh);
1768         const struct nft_af_info *afi;
1769         const struct nft_table *table;
1770         const struct nft_chain *chain;
1771         const struct nft_rule *rule;
1772         unsigned int idx = 0, s_idx = cb->args[0];
1773         struct net *net = sock_net(skb->sk);
1774         int family = nfmsg->nfgen_family;
1775
1776         rcu_read_lock();
1777         cb->seq = net->nft.base_seq;
1778
1779         list_for_each_entry_rcu(afi, &net->nft.af_info, list) {
1780                 if (family != NFPROTO_UNSPEC && family != afi->family)
1781                         continue;
1782
1783                 list_for_each_entry_rcu(table, &afi->tables, list) {
1784                         list_for_each_entry_rcu(chain, &table->chains, list) {
1785                                 list_for_each_entry_rcu(rule, &chain->rules, list) {
1786                                         if (!nft_rule_is_active(net, rule))
1787                                                 goto cont;
1788                                         if (idx < s_idx)
1789                                                 goto cont;
1790                                         if (idx > s_idx)
1791                                                 memset(&cb->args[1], 0,
1792                                                        sizeof(cb->args) - sizeof(cb->args[0]));
1793                                         if (nf_tables_fill_rule_info(skb, net, NETLINK_CB(cb->skb).portid,
1794                                                                       cb->nlh->nlmsg_seq,
1795                                                                       NFT_MSG_NEWRULE,
1796                                                                       NLM_F_MULTI | NLM_F_APPEND,
1797                                                                       afi->family, table, chain, rule) < 0)
1798                                                 goto done;
1799
1800                                         nl_dump_check_consistent(cb, nlmsg_hdr(skb));
1801 cont:
1802                                         idx++;
1803                                 }
1804                         }
1805                 }
1806         }
1807 done:
1808         rcu_read_unlock();
1809
1810         cb->args[0] = idx;
1811         return skb->len;
1812 }
1813
1814 static int nf_tables_getrule(struct sock *nlsk, struct sk_buff *skb,
1815                              const struct nlmsghdr *nlh,
1816                              const struct nlattr * const nla[])
1817 {
1818         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1819         const struct nft_af_info *afi;
1820         const struct nft_table *table;
1821         const struct nft_chain *chain;
1822         const struct nft_rule *rule;
1823         struct sk_buff *skb2;
1824         struct net *net = sock_net(skb->sk);
1825         int family = nfmsg->nfgen_family;
1826         int err;
1827
1828         if (nlh->nlmsg_flags & NLM_F_DUMP) {
1829                 struct netlink_dump_control c = {
1830                         .dump = nf_tables_dump_rules,
1831                 };
1832                 return netlink_dump_start(nlsk, skb, nlh, &c);
1833         }
1834
1835         afi = nf_tables_afinfo_lookup(net, family, false);
1836         if (IS_ERR(afi))
1837                 return PTR_ERR(afi);
1838
1839         table = nf_tables_table_lookup(afi, nla[NFTA_RULE_TABLE]);
1840         if (IS_ERR(table))
1841                 return PTR_ERR(table);
1842         if (table->flags & NFT_TABLE_INACTIVE)
1843                 return -ENOENT;
1844
1845         chain = nf_tables_chain_lookup(table, nla[NFTA_RULE_CHAIN]);
1846         if (IS_ERR(chain))
1847                 return PTR_ERR(chain);
1848         if (chain->flags & NFT_CHAIN_INACTIVE)
1849                 return -ENOENT;
1850
1851         rule = nf_tables_rule_lookup(chain, nla[NFTA_RULE_HANDLE]);
1852         if (IS_ERR(rule))
1853                 return PTR_ERR(rule);
1854
1855         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
1856         if (!skb2)
1857                 return -ENOMEM;
1858
1859         err = nf_tables_fill_rule_info(skb2, net, NETLINK_CB(skb).portid,
1860                                        nlh->nlmsg_seq, NFT_MSG_NEWRULE, 0,
1861                                        family, table, chain, rule);
1862         if (err < 0)
1863                 goto err;
1864
1865         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
1866
1867 err:
1868         kfree_skb(skb2);
1869         return err;
1870 }
1871
1872 static void nf_tables_rule_destroy(const struct nft_ctx *ctx,
1873                                    struct nft_rule *rule)
1874 {
1875         struct nft_expr *expr;
1876
1877         /*
1878          * Careful: some expressions might not be initialized in case this
1879          * is called on error from nf_tables_newrule().
1880          */
1881         expr = nft_expr_first(rule);
1882         while (expr->ops && expr != nft_expr_last(rule)) {
1883                 nf_tables_expr_destroy(ctx, expr);
1884                 expr = nft_expr_next(expr);
1885         }
1886         kfree(rule);
1887 }
1888
1889 #define NFT_RULE_MAXEXPRS       128
1890
1891 static struct nft_expr_info *info;
1892
1893 static int nf_tables_newrule(struct sock *nlsk, struct sk_buff *skb,
1894                              const struct nlmsghdr *nlh,
1895                              const struct nlattr * const nla[])
1896 {
1897         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
1898         struct nft_af_info *afi;
1899         struct net *net = sock_net(skb->sk);
1900         struct nft_table *table;
1901         struct nft_chain *chain;
1902         struct nft_rule *rule, *old_rule = NULL;
1903         struct nft_userdata *udata;
1904         struct nft_trans *trans = NULL;
1905         struct nft_expr *expr;
1906         struct nft_ctx ctx;
1907         struct nlattr *tmp;
1908         unsigned int size, i, n, ulen = 0, usize = 0;
1909         int err, rem;
1910         bool create;
1911         u64 handle, pos_handle;
1912
1913         create = nlh->nlmsg_flags & NLM_F_CREATE ? true : false;
1914
1915         afi = nf_tables_afinfo_lookup(net, nfmsg->nfgen_family, create);
1916         if (IS_ERR(afi))
1917                 return PTR_ERR(afi);
1918
1919         table = nf_tables_table_lookup(afi, nla[NFTA_RULE_TABLE]);
1920         if (IS_ERR(table))
1921                 return PTR_ERR(table);
1922
1923         chain = nf_tables_chain_lookup(table, nla[NFTA_RULE_CHAIN]);
1924         if (IS_ERR(chain))
1925                 return PTR_ERR(chain);
1926
1927         if (nla[NFTA_RULE_HANDLE]) {
1928                 handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_HANDLE]));
1929                 rule = __nf_tables_rule_lookup(chain, handle);
1930                 if (IS_ERR(rule))
1931                         return PTR_ERR(rule);
1932
1933                 if (nlh->nlmsg_flags & NLM_F_EXCL)
1934                         return -EEXIST;
1935                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
1936                         old_rule = rule;
1937                 else
1938                         return -EOPNOTSUPP;
1939         } else {
1940                 if (!create || nlh->nlmsg_flags & NLM_F_REPLACE)
1941                         return -EINVAL;
1942                 handle = nf_tables_alloc_handle(table);
1943
1944                 if (chain->use == UINT_MAX)
1945                         return -EOVERFLOW;
1946         }
1947
1948         if (nla[NFTA_RULE_POSITION]) {
1949                 if (!(nlh->nlmsg_flags & NLM_F_CREATE))
1950                         return -EOPNOTSUPP;
1951
1952                 pos_handle = be64_to_cpu(nla_get_be64(nla[NFTA_RULE_POSITION]));
1953                 old_rule = __nf_tables_rule_lookup(chain, pos_handle);
1954                 if (IS_ERR(old_rule))
1955                         return PTR_ERR(old_rule);
1956         }
1957
1958         nft_ctx_init(&ctx, skb, nlh, afi, table, chain, nla);
1959
1960         n = 0;
1961         size = 0;
1962         if (nla[NFTA_RULE_EXPRESSIONS]) {
1963                 nla_for_each_nested(tmp, nla[NFTA_RULE_EXPRESSIONS], rem) {
1964                         err = -EINVAL;
1965                         if (nla_type(tmp) != NFTA_LIST_ELEM)
1966                                 goto err1;
1967                         if (n == NFT_RULE_MAXEXPRS)
1968                                 goto err1;
1969                         err = nf_tables_expr_parse(&ctx, tmp, &info[n]);
1970                         if (err < 0)
1971                                 goto err1;
1972                         size += info[n].ops->size;
1973                         n++;
1974                 }
1975         }
1976         /* Check for overflow of dlen field */
1977         err = -EFBIG;
1978         if (size >= 1 << 12)
1979                 goto err1;
1980
1981         if (nla[NFTA_RULE_USERDATA]) {
1982                 ulen = nla_len(nla[NFTA_RULE_USERDATA]);
1983                 if (ulen > 0)
1984                         usize = sizeof(struct nft_userdata) + ulen;
1985         }
1986
1987         err = -ENOMEM;
1988         rule = kzalloc(sizeof(*rule) + size + usize, GFP_KERNEL);
1989         if (rule == NULL)
1990                 goto err1;
1991
1992         nft_rule_activate_next(net, rule);
1993
1994         rule->handle = handle;
1995         rule->dlen   = size;
1996         rule->udata  = ulen ? 1 : 0;
1997
1998         if (ulen) {
1999                 udata = nft_userdata(rule);
2000                 udata->len = ulen - 1;
2001                 nla_memcpy(udata->data, nla[NFTA_RULE_USERDATA], ulen);
2002         }
2003
2004         expr = nft_expr_first(rule);
2005         for (i = 0; i < n; i++) {
2006                 err = nf_tables_newexpr(&ctx, &info[i], expr);
2007                 if (err < 0)
2008                         goto err2;
2009                 info[i].ops = NULL;
2010                 expr = nft_expr_next(expr);
2011         }
2012
2013         if (nlh->nlmsg_flags & NLM_F_REPLACE) {
2014                 if (nft_rule_is_active_next(net, old_rule)) {
2015                         trans = nft_trans_rule_add(&ctx, NFT_MSG_DELRULE,
2016                                                    old_rule);
2017                         if (trans == NULL) {
2018                                 err = -ENOMEM;
2019                                 goto err2;
2020                         }
2021                         nft_rule_deactivate_next(net, old_rule);
2022                         chain->use--;
2023                         list_add_tail_rcu(&rule->list, &old_rule->list);
2024                 } else {
2025                         err = -ENOENT;
2026                         goto err2;
2027                 }
2028         } else if (nlh->nlmsg_flags & NLM_F_APPEND)
2029                 if (old_rule)
2030                         list_add_rcu(&rule->list, &old_rule->list);
2031                 else
2032                         list_add_tail_rcu(&rule->list, &chain->rules);
2033         else {
2034                 if (old_rule)
2035                         list_add_tail_rcu(&rule->list, &old_rule->list);
2036                 else
2037                         list_add_rcu(&rule->list, &chain->rules);
2038         }
2039
2040         if (nft_trans_rule_add(&ctx, NFT_MSG_NEWRULE, rule) == NULL) {
2041                 err = -ENOMEM;
2042                 goto err3;
2043         }
2044         chain->use++;
2045         return 0;
2046
2047 err3:
2048         list_del_rcu(&rule->list);
2049 err2:
2050         nf_tables_rule_destroy(&ctx, rule);
2051 err1:
2052         for (i = 0; i < n; i++) {
2053                 if (info[i].ops != NULL)
2054                         module_put(info[i].ops->type->owner);
2055         }
2056         return err;
2057 }
2058
2059 static int nf_tables_delrule(struct sock *nlsk, struct sk_buff *skb,
2060                              const struct nlmsghdr *nlh,
2061                              const struct nlattr * const nla[])
2062 {
2063         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2064         struct nft_af_info *afi;
2065         struct net *net = sock_net(skb->sk);
2066         struct nft_table *table;
2067         struct nft_chain *chain = NULL;
2068         struct nft_rule *rule;
2069         int family = nfmsg->nfgen_family, err = 0;
2070         struct nft_ctx ctx;
2071
2072         afi = nf_tables_afinfo_lookup(net, family, false);
2073         if (IS_ERR(afi))
2074                 return PTR_ERR(afi);
2075
2076         table = nf_tables_table_lookup(afi, nla[NFTA_RULE_TABLE]);
2077         if (IS_ERR(table))
2078                 return PTR_ERR(table);
2079         if (table->flags & NFT_TABLE_INACTIVE)
2080                 return -ENOENT;
2081
2082         if (nla[NFTA_RULE_CHAIN]) {
2083                 chain = nf_tables_chain_lookup(table, nla[NFTA_RULE_CHAIN]);
2084                 if (IS_ERR(chain))
2085                         return PTR_ERR(chain);
2086         }
2087
2088         nft_ctx_init(&ctx, skb, nlh, afi, table, chain, nla);
2089
2090         if (chain) {
2091                 if (nla[NFTA_RULE_HANDLE]) {
2092                         rule = nf_tables_rule_lookup(chain,
2093                                                      nla[NFTA_RULE_HANDLE]);
2094                         if (IS_ERR(rule))
2095                                 return PTR_ERR(rule);
2096
2097                         err = nft_delrule(&ctx, rule);
2098                 } else {
2099                         err = nft_delrule_by_chain(&ctx);
2100                 }
2101         } else {
2102                 list_for_each_entry(chain, &table->chains, list) {
2103                         ctx.chain = chain;
2104                         err = nft_delrule_by_chain(&ctx);
2105                         if (err < 0)
2106                                 break;
2107                 }
2108         }
2109
2110         return err;
2111 }
2112
2113 /*
2114  * Sets
2115  */
2116
2117 static LIST_HEAD(nf_tables_set_ops);
2118
2119 int nft_register_set(struct nft_set_ops *ops)
2120 {
2121         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2122         list_add_tail_rcu(&ops->list, &nf_tables_set_ops);
2123         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2124         return 0;
2125 }
2126 EXPORT_SYMBOL_GPL(nft_register_set);
2127
2128 void nft_unregister_set(struct nft_set_ops *ops)
2129 {
2130         nfnl_lock(NFNL_SUBSYS_NFTABLES);
2131         list_del_rcu(&ops->list);
2132         nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2133 }
2134 EXPORT_SYMBOL_GPL(nft_unregister_set);
2135
2136 /*
2137  * Select a set implementation based on the data characteristics and the
2138  * given policy. The total memory use might not be known if no size is
2139  * given, in that case the amount of memory per element is used.
2140  */
2141 static const struct nft_set_ops *
2142 nft_select_set_ops(const struct nlattr * const nla[],
2143                    const struct nft_set_desc *desc,
2144                    enum nft_set_policies policy)
2145 {
2146         const struct nft_set_ops *ops, *bops;
2147         struct nft_set_estimate est, best;
2148         u32 features;
2149
2150 #ifdef CONFIG_MODULES
2151         if (list_empty(&nf_tables_set_ops)) {
2152                 nfnl_unlock(NFNL_SUBSYS_NFTABLES);
2153                 request_module("nft-set");
2154                 nfnl_lock(NFNL_SUBSYS_NFTABLES);
2155                 if (!list_empty(&nf_tables_set_ops))
2156                         return ERR_PTR(-EAGAIN);
2157         }
2158 #endif
2159         features = 0;
2160         if (nla[NFTA_SET_FLAGS] != NULL) {
2161                 features = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
2162                 features &= NFT_SET_INTERVAL | NFT_SET_MAP;
2163         }
2164
2165         bops       = NULL;
2166         best.size  = ~0;
2167         best.class = ~0;
2168
2169         list_for_each_entry(ops, &nf_tables_set_ops, list) {
2170                 if ((ops->features & features) != features)
2171                         continue;
2172                 if (!ops->estimate(desc, features, &est))
2173                         continue;
2174
2175                 switch (policy) {
2176                 case NFT_SET_POL_PERFORMANCE:
2177                         if (est.class < best.class)
2178                                 break;
2179                         if (est.class == best.class && est.size < best.size)
2180                                 break;
2181                         continue;
2182                 case NFT_SET_POL_MEMORY:
2183                         if (est.size < best.size)
2184                                 break;
2185                         if (est.size == best.size && est.class < best.class)
2186                                 break;
2187                         continue;
2188                 default:
2189                         break;
2190                 }
2191
2192                 if (!try_module_get(ops->owner))
2193                         continue;
2194                 if (bops != NULL)
2195                         module_put(bops->owner);
2196
2197                 bops = ops;
2198                 best = est;
2199         }
2200
2201         if (bops != NULL)
2202                 return bops;
2203
2204         return ERR_PTR(-EOPNOTSUPP);
2205 }
2206
2207 static const struct nla_policy nft_set_policy[NFTA_SET_MAX + 1] = {
2208         [NFTA_SET_TABLE]                = { .type = NLA_STRING },
2209         [NFTA_SET_NAME]                 = { .type = NLA_STRING,
2210                                             .len = IFNAMSIZ - 1 },
2211         [NFTA_SET_FLAGS]                = { .type = NLA_U32 },
2212         [NFTA_SET_KEY_TYPE]             = { .type = NLA_U32 },
2213         [NFTA_SET_KEY_LEN]              = { .type = NLA_U32 },
2214         [NFTA_SET_DATA_TYPE]            = { .type = NLA_U32 },
2215         [NFTA_SET_DATA_LEN]             = { .type = NLA_U32 },
2216         [NFTA_SET_POLICY]               = { .type = NLA_U32 },
2217         [NFTA_SET_DESC]                 = { .type = NLA_NESTED },
2218         [NFTA_SET_ID]                   = { .type = NLA_U32 },
2219 };
2220
2221 static const struct nla_policy nft_set_desc_policy[NFTA_SET_DESC_MAX + 1] = {
2222         [NFTA_SET_DESC_SIZE]            = { .type = NLA_U32 },
2223 };
2224
2225 static int nft_ctx_init_from_setattr(struct nft_ctx *ctx,
2226                                      const struct sk_buff *skb,
2227                                      const struct nlmsghdr *nlh,
2228                                      const struct nlattr * const nla[])
2229 {
2230         struct net *net = sock_net(skb->sk);
2231         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2232         struct nft_af_info *afi = NULL;
2233         struct nft_table *table = NULL;
2234
2235         if (nfmsg->nfgen_family != NFPROTO_UNSPEC) {
2236                 afi = nf_tables_afinfo_lookup(net, nfmsg->nfgen_family, false);
2237                 if (IS_ERR(afi))
2238                         return PTR_ERR(afi);
2239         }
2240
2241         if (nla[NFTA_SET_TABLE] != NULL) {
2242                 if (afi == NULL)
2243                         return -EAFNOSUPPORT;
2244
2245                 table = nf_tables_table_lookup(afi, nla[NFTA_SET_TABLE]);
2246                 if (IS_ERR(table))
2247                         return PTR_ERR(table);
2248                 if (table->flags & NFT_TABLE_INACTIVE)
2249                         return -ENOENT;
2250         }
2251
2252         nft_ctx_init(ctx, skb, nlh, afi, table, NULL, nla);
2253         return 0;
2254 }
2255
2256 struct nft_set *nf_tables_set_lookup(const struct nft_table *table,
2257                                      const struct nlattr *nla)
2258 {
2259         struct nft_set *set;
2260
2261         if (nla == NULL)
2262                 return ERR_PTR(-EINVAL);
2263
2264         list_for_each_entry(set, &table->sets, list) {
2265                 if (!nla_strcmp(nla, set->name))
2266                         return set;
2267         }
2268         return ERR_PTR(-ENOENT);
2269 }
2270
2271 struct nft_set *nf_tables_set_lookup_byid(const struct net *net,
2272                                           const struct nlattr *nla)
2273 {
2274         struct nft_trans *trans;
2275         u32 id = ntohl(nla_get_be32(nla));
2276
2277         list_for_each_entry(trans, &net->nft.commit_list, list) {
2278                 if (trans->msg_type == NFT_MSG_NEWSET &&
2279                     id == nft_trans_set_id(trans))
2280                         return nft_trans_set(trans);
2281         }
2282         return ERR_PTR(-ENOENT);
2283 }
2284
2285 static int nf_tables_set_alloc_name(struct nft_ctx *ctx, struct nft_set *set,
2286                                     const char *name)
2287 {
2288         const struct nft_set *i;
2289         const char *p;
2290         unsigned long *inuse;
2291         unsigned int n = 0, min = 0;
2292
2293         p = strnchr(name, IFNAMSIZ, '%');
2294         if (p != NULL) {
2295                 if (p[1] != 'd' || strchr(p + 2, '%'))
2296                         return -EINVAL;
2297
2298                 inuse = (unsigned long *)get_zeroed_page(GFP_KERNEL);
2299                 if (inuse == NULL)
2300                         return -ENOMEM;
2301 cont:
2302                 list_for_each_entry(i, &ctx->table->sets, list) {
2303                         int tmp;
2304
2305                         if (!sscanf(i->name, name, &tmp))
2306                                 continue;
2307                         if (tmp < min || tmp >= min + BITS_PER_BYTE * PAGE_SIZE)
2308                                 continue;
2309
2310                         set_bit(tmp - min, inuse);
2311                 }
2312
2313                 n = find_first_zero_bit(inuse, BITS_PER_BYTE * PAGE_SIZE);
2314                 if (n >= BITS_PER_BYTE * PAGE_SIZE) {
2315                         min += BITS_PER_BYTE * PAGE_SIZE;
2316                         memset(inuse, 0, PAGE_SIZE);
2317                         goto cont;
2318                 }
2319                 free_page((unsigned long)inuse);
2320         }
2321
2322         snprintf(set->name, sizeof(set->name), name, min + n);
2323         list_for_each_entry(i, &ctx->table->sets, list) {
2324                 if (!strcmp(set->name, i->name))
2325                         return -ENFILE;
2326         }
2327         return 0;
2328 }
2329
2330 static int nf_tables_fill_set(struct sk_buff *skb, const struct nft_ctx *ctx,
2331                               const struct nft_set *set, u16 event, u16 flags)
2332 {
2333         struct nfgenmsg *nfmsg;
2334         struct nlmsghdr *nlh;
2335         struct nlattr *desc;
2336         u32 portid = ctx->portid;
2337         u32 seq = ctx->seq;
2338
2339         event |= NFNL_SUBSYS_NFTABLES << 8;
2340         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
2341                         flags);
2342         if (nlh == NULL)
2343                 goto nla_put_failure;
2344
2345         nfmsg = nlmsg_data(nlh);
2346         nfmsg->nfgen_family     = ctx->afi->family;
2347         nfmsg->version          = NFNETLINK_V0;
2348         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
2349
2350         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
2351                 goto nla_put_failure;
2352         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
2353                 goto nla_put_failure;
2354         if (set->flags != 0)
2355                 if (nla_put_be32(skb, NFTA_SET_FLAGS, htonl(set->flags)))
2356                         goto nla_put_failure;
2357
2358         if (nla_put_be32(skb, NFTA_SET_KEY_TYPE, htonl(set->ktype)))
2359                 goto nla_put_failure;
2360         if (nla_put_be32(skb, NFTA_SET_KEY_LEN, htonl(set->klen)))
2361                 goto nla_put_failure;
2362         if (set->flags & NFT_SET_MAP) {
2363                 if (nla_put_be32(skb, NFTA_SET_DATA_TYPE, htonl(set->dtype)))
2364                         goto nla_put_failure;
2365                 if (nla_put_be32(skb, NFTA_SET_DATA_LEN, htonl(set->dlen)))
2366                         goto nla_put_failure;
2367         }
2368
2369         if (set->policy != NFT_SET_POL_PERFORMANCE) {
2370                 if (nla_put_be32(skb, NFTA_SET_POLICY, htonl(set->policy)))
2371                         goto nla_put_failure;
2372         }
2373
2374         desc = nla_nest_start(skb, NFTA_SET_DESC);
2375         if (desc == NULL)
2376                 goto nla_put_failure;
2377         if (set->size &&
2378             nla_put_be32(skb, NFTA_SET_DESC_SIZE, htonl(set->size)))
2379                 goto nla_put_failure;
2380         nla_nest_end(skb, desc);
2381
2382         nlmsg_end(skb, nlh);
2383         return 0;
2384
2385 nla_put_failure:
2386         nlmsg_trim(skb, nlh);
2387         return -1;
2388 }
2389
2390 static int nf_tables_set_notify(const struct nft_ctx *ctx,
2391                                 const struct nft_set *set,
2392                                 int event, gfp_t gfp_flags)
2393 {
2394         struct sk_buff *skb;
2395         u32 portid = ctx->portid;
2396         int err;
2397
2398         if (!ctx->report &&
2399             !nfnetlink_has_listeners(ctx->net, NFNLGRP_NFTABLES))
2400                 return 0;
2401
2402         err = -ENOBUFS;
2403         skb = nlmsg_new(NLMSG_GOODSIZE, gfp_flags);
2404         if (skb == NULL)
2405                 goto err;
2406
2407         err = nf_tables_fill_set(skb, ctx, set, event, 0);
2408         if (err < 0) {
2409                 kfree_skb(skb);
2410                 goto err;
2411         }
2412
2413         err = nfnetlink_send(skb, ctx->net, portid, NFNLGRP_NFTABLES,
2414                              ctx->report, gfp_flags);
2415 err:
2416         if (err < 0)
2417                 nfnetlink_set_err(ctx->net, portid, NFNLGRP_NFTABLES, err);
2418         return err;
2419 }
2420
2421 static int nf_tables_dump_sets(struct sk_buff *skb, struct netlink_callback *cb)
2422 {
2423         const struct nft_set *set;
2424         unsigned int idx, s_idx = cb->args[0];
2425         struct nft_af_info *afi;
2426         struct nft_table *table, *cur_table = (struct nft_table *)cb->args[2];
2427         struct net *net = sock_net(skb->sk);
2428         int cur_family = cb->args[3];
2429         struct nft_ctx *ctx = cb->data, ctx_set;
2430
2431         if (cb->args[1])
2432                 return skb->len;
2433
2434         rcu_read_lock();
2435         cb->seq = net->nft.base_seq;
2436
2437         list_for_each_entry_rcu(afi, &net->nft.af_info, list) {
2438                 if (ctx->afi && ctx->afi != afi)
2439                         continue;
2440
2441                 if (cur_family) {
2442                         if (afi->family != cur_family)
2443                                 continue;
2444
2445                         cur_family = 0;
2446                 }
2447                 list_for_each_entry_rcu(table, &afi->tables, list) {
2448                         if (ctx->table && ctx->table != table)
2449                                 continue;
2450
2451                         if (cur_table) {
2452                                 if (cur_table != table)
2453                                         continue;
2454
2455                                 cur_table = NULL;
2456                         }
2457                         idx = 0;
2458                         list_for_each_entry_rcu(set, &table->sets, list) {
2459                                 if (idx < s_idx)
2460                                         goto cont;
2461
2462                                 ctx_set = *ctx;
2463                                 ctx_set.table = table;
2464                                 ctx_set.afi = afi;
2465                                 if (nf_tables_fill_set(skb, &ctx_set, set,
2466                                                        NFT_MSG_NEWSET,
2467                                                        NLM_F_MULTI) < 0) {
2468                                         cb->args[0] = idx;
2469                                         cb->args[2] = (unsigned long) table;
2470                                         cb->args[3] = afi->family;
2471                                         goto done;
2472                                 }
2473                                 nl_dump_check_consistent(cb, nlmsg_hdr(skb));
2474 cont:
2475                                 idx++;
2476                         }
2477                         if (s_idx)
2478                                 s_idx = 0;
2479                 }
2480         }
2481         cb->args[1] = 1;
2482 done:
2483         rcu_read_unlock();
2484         return skb->len;
2485 }
2486
2487 static int nf_tables_dump_sets_done(struct netlink_callback *cb)
2488 {
2489         kfree(cb->data);
2490         return 0;
2491 }
2492
2493 static int nf_tables_getset(struct sock *nlsk, struct sk_buff *skb,
2494                             const struct nlmsghdr *nlh,
2495                             const struct nlattr * const nla[])
2496 {
2497         const struct nft_set *set;
2498         struct nft_ctx ctx;
2499         struct sk_buff *skb2;
2500         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2501         int err;
2502
2503         /* Verify existence before starting dump */
2504         err = nft_ctx_init_from_setattr(&ctx, skb, nlh, nla);
2505         if (err < 0)
2506                 return err;
2507
2508         if (nlh->nlmsg_flags & NLM_F_DUMP) {
2509                 struct netlink_dump_control c = {
2510                         .dump = nf_tables_dump_sets,
2511                         .done = nf_tables_dump_sets_done,
2512                 };
2513                 struct nft_ctx *ctx_dump;
2514
2515                 ctx_dump = kmalloc(sizeof(*ctx_dump), GFP_KERNEL);
2516                 if (ctx_dump == NULL)
2517                         return -ENOMEM;
2518
2519                 *ctx_dump = ctx;
2520                 c.data = ctx_dump;
2521
2522                 return netlink_dump_start(nlsk, skb, nlh, &c);
2523         }
2524
2525         /* Only accept unspec with dump */
2526         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
2527                 return -EAFNOSUPPORT;
2528
2529         set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_NAME]);
2530         if (IS_ERR(set))
2531                 return PTR_ERR(set);
2532         if (set->flags & NFT_SET_INACTIVE)
2533                 return -ENOENT;
2534
2535         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
2536         if (skb2 == NULL)
2537                 return -ENOMEM;
2538
2539         err = nf_tables_fill_set(skb2, &ctx, set, NFT_MSG_NEWSET, 0);
2540         if (err < 0)
2541                 goto err;
2542
2543         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
2544
2545 err:
2546         kfree_skb(skb2);
2547         return err;
2548 }
2549
2550 static int nf_tables_set_desc_parse(const struct nft_ctx *ctx,
2551                                     struct nft_set_desc *desc,
2552                                     const struct nlattr *nla)
2553 {
2554         struct nlattr *da[NFTA_SET_DESC_MAX + 1];
2555         int err;
2556
2557         err = nla_parse_nested(da, NFTA_SET_DESC_MAX, nla, nft_set_desc_policy);
2558         if (err < 0)
2559                 return err;
2560
2561         if (da[NFTA_SET_DESC_SIZE] != NULL)
2562                 desc->size = ntohl(nla_get_be32(da[NFTA_SET_DESC_SIZE]));
2563
2564         return 0;
2565 }
2566
2567 static int nf_tables_newset(struct sock *nlsk, struct sk_buff *skb,
2568                             const struct nlmsghdr *nlh,
2569                             const struct nlattr * const nla[])
2570 {
2571         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2572         const struct nft_set_ops *ops;
2573         struct nft_af_info *afi;
2574         struct net *net = sock_net(skb->sk);
2575         struct nft_table *table;
2576         struct nft_set *set;
2577         struct nft_ctx ctx;
2578         char name[IFNAMSIZ];
2579         unsigned int size;
2580         bool create;
2581         u32 ktype, dtype, flags, policy;
2582         struct nft_set_desc desc;
2583         int err;
2584
2585         if (nla[NFTA_SET_TABLE] == NULL ||
2586             nla[NFTA_SET_NAME] == NULL ||
2587             nla[NFTA_SET_KEY_LEN] == NULL ||
2588             nla[NFTA_SET_ID] == NULL)
2589                 return -EINVAL;
2590
2591         memset(&desc, 0, sizeof(desc));
2592
2593         ktype = NFT_DATA_VALUE;
2594         if (nla[NFTA_SET_KEY_TYPE] != NULL) {
2595                 ktype = ntohl(nla_get_be32(nla[NFTA_SET_KEY_TYPE]));
2596                 if ((ktype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK)
2597                         return -EINVAL;
2598         }
2599
2600         desc.klen = ntohl(nla_get_be32(nla[NFTA_SET_KEY_LEN]));
2601         if (desc.klen == 0 || desc.klen > FIELD_SIZEOF(struct nft_data, data))
2602                 return -EINVAL;
2603
2604         flags = 0;
2605         if (nla[NFTA_SET_FLAGS] != NULL) {
2606                 flags = ntohl(nla_get_be32(nla[NFTA_SET_FLAGS]));
2607                 if (flags & ~(NFT_SET_ANONYMOUS | NFT_SET_CONSTANT |
2608                               NFT_SET_INTERVAL | NFT_SET_MAP))
2609                         return -EINVAL;
2610         }
2611
2612         dtype = 0;
2613         if (nla[NFTA_SET_DATA_TYPE] != NULL) {
2614                 if (!(flags & NFT_SET_MAP))
2615                         return -EINVAL;
2616
2617                 dtype = ntohl(nla_get_be32(nla[NFTA_SET_DATA_TYPE]));
2618                 if ((dtype & NFT_DATA_RESERVED_MASK) == NFT_DATA_RESERVED_MASK &&
2619                     dtype != NFT_DATA_VERDICT)
2620                         return -EINVAL;
2621
2622                 if (dtype != NFT_DATA_VERDICT) {
2623                         if (nla[NFTA_SET_DATA_LEN] == NULL)
2624                                 return -EINVAL;
2625                         desc.dlen = ntohl(nla_get_be32(nla[NFTA_SET_DATA_LEN]));
2626                         if (desc.dlen == 0 ||
2627                             desc.dlen > FIELD_SIZEOF(struct nft_data, data))
2628                                 return -EINVAL;
2629                 } else
2630                         desc.dlen = sizeof(struct nft_data);
2631         } else if (flags & NFT_SET_MAP)
2632                 return -EINVAL;
2633
2634         policy = NFT_SET_POL_PERFORMANCE;
2635         if (nla[NFTA_SET_POLICY] != NULL)
2636                 policy = ntohl(nla_get_be32(nla[NFTA_SET_POLICY]));
2637
2638         if (nla[NFTA_SET_DESC] != NULL) {
2639                 err = nf_tables_set_desc_parse(&ctx, &desc, nla[NFTA_SET_DESC]);
2640                 if (err < 0)
2641                         return err;
2642         }
2643
2644         create = nlh->nlmsg_flags & NLM_F_CREATE ? true : false;
2645
2646         afi = nf_tables_afinfo_lookup(net, nfmsg->nfgen_family, create);
2647         if (IS_ERR(afi))
2648                 return PTR_ERR(afi);
2649
2650         table = nf_tables_table_lookup(afi, nla[NFTA_SET_TABLE]);
2651         if (IS_ERR(table))
2652                 return PTR_ERR(table);
2653
2654         nft_ctx_init(&ctx, skb, nlh, afi, table, NULL, nla);
2655
2656         set = nf_tables_set_lookup(table, nla[NFTA_SET_NAME]);
2657         if (IS_ERR(set)) {
2658                 if (PTR_ERR(set) != -ENOENT)
2659                         return PTR_ERR(set);
2660                 set = NULL;
2661         }
2662
2663         if (set != NULL) {
2664                 if (nlh->nlmsg_flags & NLM_F_EXCL)
2665                         return -EEXIST;
2666                 if (nlh->nlmsg_flags & NLM_F_REPLACE)
2667                         return -EOPNOTSUPP;
2668                 return 0;
2669         }
2670
2671         if (!(nlh->nlmsg_flags & NLM_F_CREATE))
2672                 return -ENOENT;
2673
2674         ops = nft_select_set_ops(nla, &desc, policy);
2675         if (IS_ERR(ops))
2676                 return PTR_ERR(ops);
2677
2678         size = 0;
2679         if (ops->privsize != NULL)
2680                 size = ops->privsize(nla);
2681
2682         err = -ENOMEM;
2683         set = kzalloc(sizeof(*set) + size, GFP_KERNEL);
2684         if (set == NULL)
2685                 goto err1;
2686
2687         nla_strlcpy(name, nla[NFTA_SET_NAME], sizeof(set->name));
2688         err = nf_tables_set_alloc_name(&ctx, set, name);
2689         if (err < 0)
2690                 goto err2;
2691
2692         INIT_LIST_HEAD(&set->bindings);
2693         set->ops   = ops;
2694         set->ktype = ktype;
2695         set->klen  = desc.klen;
2696         set->dtype = dtype;
2697         set->dlen  = desc.dlen;
2698         set->flags = flags;
2699         set->size  = desc.size;
2700         set->policy = policy;
2701
2702         err = ops->init(set, &desc, nla);
2703         if (err < 0)
2704                 goto err2;
2705
2706         err = nft_trans_set_add(&ctx, NFT_MSG_NEWSET, set);
2707         if (err < 0)
2708                 goto err2;
2709
2710         list_add_tail_rcu(&set->list, &table->sets);
2711         table->use++;
2712         return 0;
2713
2714 err2:
2715         kfree(set);
2716 err1:
2717         module_put(ops->owner);
2718         return err;
2719 }
2720
2721 static void nft_set_destroy(struct nft_set *set)
2722 {
2723         set->ops->destroy(set);
2724         module_put(set->ops->owner);
2725         kfree(set);
2726 }
2727
2728 static void nf_tables_set_destroy(const struct nft_ctx *ctx, struct nft_set *set)
2729 {
2730         list_del_rcu(&set->list);
2731         nf_tables_set_notify(ctx, set, NFT_MSG_DELSET, GFP_ATOMIC);
2732         nft_set_destroy(set);
2733 }
2734
2735 static int nf_tables_delset(struct sock *nlsk, struct sk_buff *skb,
2736                             const struct nlmsghdr *nlh,
2737                             const struct nlattr * const nla[])
2738 {
2739         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2740         struct nft_set *set;
2741         struct nft_ctx ctx;
2742         int err;
2743
2744         if (nfmsg->nfgen_family == NFPROTO_UNSPEC)
2745                 return -EAFNOSUPPORT;
2746         if (nla[NFTA_SET_TABLE] == NULL)
2747                 return -EINVAL;
2748
2749         err = nft_ctx_init_from_setattr(&ctx, skb, nlh, nla);
2750         if (err < 0)
2751                 return err;
2752
2753         set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_NAME]);
2754         if (IS_ERR(set))
2755                 return PTR_ERR(set);
2756         if (set->flags & NFT_SET_INACTIVE)
2757                 return -ENOENT;
2758         if (!list_empty(&set->bindings))
2759                 return -EBUSY;
2760
2761         return nft_delset(&ctx, set);
2762 }
2763
2764 static int nf_tables_bind_check_setelem(const struct nft_ctx *ctx,
2765                                         const struct nft_set *set,
2766                                         const struct nft_set_iter *iter,
2767                                         const struct nft_set_elem *elem)
2768 {
2769         enum nft_registers dreg;
2770
2771         dreg = nft_type_to_reg(set->dtype);
2772         return nft_validate_data_load(ctx, dreg, &elem->data,
2773                                       set->dtype == NFT_DATA_VERDICT ?
2774                                       NFT_DATA_VERDICT : NFT_DATA_VALUE);
2775 }
2776
2777 int nf_tables_bind_set(const struct nft_ctx *ctx, struct nft_set *set,
2778                        struct nft_set_binding *binding)
2779 {
2780         struct nft_set_binding *i;
2781         struct nft_set_iter iter;
2782
2783         if (!list_empty(&set->bindings) && set->flags & NFT_SET_ANONYMOUS)
2784                 return -EBUSY;
2785
2786         if (set->flags & NFT_SET_MAP) {
2787                 /* If the set is already bound to the same chain all
2788                  * jumps are already validated for that chain.
2789                  */
2790                 list_for_each_entry(i, &set->bindings, list) {
2791                         if (i->chain == binding->chain)
2792                                 goto bind;
2793                 }
2794
2795                 iter.skip       = 0;
2796                 iter.count      = 0;
2797                 iter.err        = 0;
2798                 iter.fn         = nf_tables_bind_check_setelem;
2799
2800                 set->ops->walk(ctx, set, &iter);
2801                 if (iter.err < 0) {
2802                         /* Destroy anonymous sets if binding fails */
2803                         if (set->flags & NFT_SET_ANONYMOUS)
2804                                 nf_tables_set_destroy(ctx, set);
2805
2806                         return iter.err;
2807                 }
2808         }
2809 bind:
2810         binding->chain = ctx->chain;
2811         list_add_tail_rcu(&binding->list, &set->bindings);
2812         return 0;
2813 }
2814
2815 void nf_tables_unbind_set(const struct nft_ctx *ctx, struct nft_set *set,
2816                           struct nft_set_binding *binding)
2817 {
2818         list_del_rcu(&binding->list);
2819
2820         if (list_empty(&set->bindings) && set->flags & NFT_SET_ANONYMOUS &&
2821             !(set->flags & NFT_SET_INACTIVE))
2822                 nf_tables_set_destroy(ctx, set);
2823 }
2824
2825 /*
2826  * Set elements
2827  */
2828
2829 static const struct nla_policy nft_set_elem_policy[NFTA_SET_ELEM_MAX + 1] = {
2830         [NFTA_SET_ELEM_KEY]             = { .type = NLA_NESTED },
2831         [NFTA_SET_ELEM_DATA]            = { .type = NLA_NESTED },
2832         [NFTA_SET_ELEM_FLAGS]           = { .type = NLA_U32 },
2833 };
2834
2835 static const struct nla_policy nft_set_elem_list_policy[NFTA_SET_ELEM_LIST_MAX + 1] = {
2836         [NFTA_SET_ELEM_LIST_TABLE]      = { .type = NLA_STRING },
2837         [NFTA_SET_ELEM_LIST_SET]        = { .type = NLA_STRING },
2838         [NFTA_SET_ELEM_LIST_ELEMENTS]   = { .type = NLA_NESTED },
2839         [NFTA_SET_ELEM_LIST_SET_ID]     = { .type = NLA_U32 },
2840 };
2841
2842 static int nft_ctx_init_from_elemattr(struct nft_ctx *ctx,
2843                                       const struct sk_buff *skb,
2844                                       const struct nlmsghdr *nlh,
2845                                       const struct nlattr * const nla[],
2846                                       bool trans)
2847 {
2848         const struct nfgenmsg *nfmsg = nlmsg_data(nlh);
2849         struct nft_af_info *afi;
2850         struct nft_table *table;
2851         struct net *net = sock_net(skb->sk);
2852
2853         afi = nf_tables_afinfo_lookup(net, nfmsg->nfgen_family, false);
2854         if (IS_ERR(afi))
2855                 return PTR_ERR(afi);
2856
2857         table = nf_tables_table_lookup(afi, nla[NFTA_SET_ELEM_LIST_TABLE]);
2858         if (IS_ERR(table))
2859                 return PTR_ERR(table);
2860         if (!trans && (table->flags & NFT_TABLE_INACTIVE))
2861                 return -ENOENT;
2862
2863         nft_ctx_init(ctx, skb, nlh, afi, table, NULL, nla);
2864         return 0;
2865 }
2866
2867 static int nf_tables_fill_setelem(struct sk_buff *skb,
2868                                   const struct nft_set *set,
2869                                   const struct nft_set_elem *elem)
2870 {
2871         unsigned char *b = skb_tail_pointer(skb);
2872         struct nlattr *nest;
2873
2874         nest = nla_nest_start(skb, NFTA_LIST_ELEM);
2875         if (nest == NULL)
2876                 goto nla_put_failure;
2877
2878         if (nft_data_dump(skb, NFTA_SET_ELEM_KEY, &elem->key, NFT_DATA_VALUE,
2879                           set->klen) < 0)
2880                 goto nla_put_failure;
2881
2882         if (set->flags & NFT_SET_MAP &&
2883             !(elem->flags & NFT_SET_ELEM_INTERVAL_END) &&
2884             nft_data_dump(skb, NFTA_SET_ELEM_DATA, &elem->data,
2885                           set->dtype == NFT_DATA_VERDICT ? NFT_DATA_VERDICT : NFT_DATA_VALUE,
2886                           set->dlen) < 0)
2887                 goto nla_put_failure;
2888
2889         if (elem->flags != 0)
2890                 if (nla_put_be32(skb, NFTA_SET_ELEM_FLAGS, htonl(elem->flags)))
2891                         goto nla_put_failure;
2892
2893         nla_nest_end(skb, nest);
2894         return 0;
2895
2896 nla_put_failure:
2897         nlmsg_trim(skb, b);
2898         return -EMSGSIZE;
2899 }
2900
2901 struct nft_set_dump_args {
2902         const struct netlink_callback   *cb;
2903         struct nft_set_iter             iter;
2904         struct sk_buff                  *skb;
2905 };
2906
2907 static int nf_tables_dump_setelem(const struct nft_ctx *ctx,
2908                                   const struct nft_set *set,
2909                                   const struct nft_set_iter *iter,
2910                                   const struct nft_set_elem *elem)
2911 {
2912         struct nft_set_dump_args *args;
2913
2914         args = container_of(iter, struct nft_set_dump_args, iter);
2915         return nf_tables_fill_setelem(args->skb, set, elem);
2916 }
2917
2918 static int nf_tables_dump_set(struct sk_buff *skb, struct netlink_callback *cb)
2919 {
2920         const struct nft_set *set;
2921         struct nft_set_dump_args args;
2922         struct nft_ctx ctx;
2923         struct nlattr *nla[NFTA_SET_ELEM_LIST_MAX + 1];
2924         struct nfgenmsg *nfmsg;
2925         struct nlmsghdr *nlh;
2926         struct nlattr *nest;
2927         u32 portid, seq;
2928         int event, err;
2929
2930         err = nlmsg_parse(cb->nlh, sizeof(struct nfgenmsg), nla,
2931                           NFTA_SET_ELEM_LIST_MAX, nft_set_elem_list_policy);
2932         if (err < 0)
2933                 return err;
2934
2935         err = nft_ctx_init_from_elemattr(&ctx, cb->skb, cb->nlh, (void *)nla,
2936                                          false);
2937         if (err < 0)
2938                 return err;
2939
2940         set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]);
2941         if (IS_ERR(set))
2942                 return PTR_ERR(set);
2943         if (set->flags & NFT_SET_INACTIVE)
2944                 return -ENOENT;
2945
2946         event  = NFT_MSG_NEWSETELEM;
2947         event |= NFNL_SUBSYS_NFTABLES << 8;
2948         portid = NETLINK_CB(cb->skb).portid;
2949         seq    = cb->nlh->nlmsg_seq;
2950
2951         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
2952                         NLM_F_MULTI);
2953         if (nlh == NULL)
2954                 goto nla_put_failure;
2955
2956         nfmsg = nlmsg_data(nlh);
2957         nfmsg->nfgen_family = ctx.afi->family;
2958         nfmsg->version      = NFNETLINK_V0;
2959         nfmsg->res_id       = htons(ctx.net->nft.base_seq & 0xffff);
2960
2961         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_TABLE, ctx.table->name))
2962                 goto nla_put_failure;
2963         if (nla_put_string(skb, NFTA_SET_ELEM_LIST_SET, set->name))
2964                 goto nla_put_failure;
2965
2966         nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
2967         if (nest == NULL)
2968                 goto nla_put_failure;
2969
2970         args.cb         = cb;
2971         args.skb        = skb;
2972         args.iter.skip  = cb->args[0];
2973         args.iter.count = 0;
2974         args.iter.err   = 0;
2975         args.iter.fn    = nf_tables_dump_setelem;
2976         set->ops->walk(&ctx, set, &args.iter);
2977
2978         nla_nest_end(skb, nest);
2979         nlmsg_end(skb, nlh);
2980
2981         if (args.iter.err && args.iter.err != -EMSGSIZE)
2982                 return args.iter.err;
2983         if (args.iter.count == cb->args[0])
2984                 return 0;
2985
2986         cb->args[0] = args.iter.count;
2987         return skb->len;
2988
2989 nla_put_failure:
2990         return -ENOSPC;
2991 }
2992
2993 static int nf_tables_getsetelem(struct sock *nlsk, struct sk_buff *skb,
2994                                 const struct nlmsghdr *nlh,
2995                                 const struct nlattr * const nla[])
2996 {
2997         const struct nft_set *set;
2998         struct nft_ctx ctx;
2999         int err;
3000
3001         err = nft_ctx_init_from_elemattr(&ctx, skb, nlh, nla, false);
3002         if (err < 0)
3003                 return err;
3004
3005         set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]);
3006         if (IS_ERR(set))
3007                 return PTR_ERR(set);
3008         if (set->flags & NFT_SET_INACTIVE)
3009                 return -ENOENT;
3010
3011         if (nlh->nlmsg_flags & NLM_F_DUMP) {
3012                 struct netlink_dump_control c = {
3013                         .dump = nf_tables_dump_set,
3014                 };
3015                 return netlink_dump_start(nlsk, skb, nlh, &c);
3016         }
3017         return -EOPNOTSUPP;
3018 }
3019
3020 static int nf_tables_fill_setelem_info(struct sk_buff *skb,
3021                                        const struct nft_ctx *ctx, u32 seq,
3022                                        u32 portid, int event, u16 flags,
3023                                        const struct nft_set *set,
3024                                        const struct nft_set_elem *elem)
3025 {
3026         struct nfgenmsg *nfmsg;
3027         struct nlmsghdr *nlh;
3028         struct nlattr *nest;
3029         int err;
3030
3031         event |= NFNL_SUBSYS_NFTABLES << 8;
3032         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg),
3033                         flags);
3034         if (nlh == NULL)
3035                 goto nla_put_failure;
3036
3037         nfmsg = nlmsg_data(nlh);
3038         nfmsg->nfgen_family     = ctx->afi->family;
3039         nfmsg->version          = NFNETLINK_V0;
3040         nfmsg->res_id           = htons(ctx->net->nft.base_seq & 0xffff);
3041
3042         if (nla_put_string(skb, NFTA_SET_TABLE, ctx->table->name))
3043                 goto nla_put_failure;
3044         if (nla_put_string(skb, NFTA_SET_NAME, set->name))
3045                 goto nla_put_failure;
3046
3047         nest = nla_nest_start(skb, NFTA_SET_ELEM_LIST_ELEMENTS);
3048         if (nest == NULL)
3049                 goto nla_put_failure;
3050
3051         err = nf_tables_fill_setelem(skb, set, elem);
3052         if (err < 0)
3053                 goto nla_put_failure;
3054
3055         nla_nest_end(skb, nest);
3056
3057         nlmsg_end(skb, nlh);
3058         return 0;
3059
3060 nla_put_failure:
3061         nlmsg_trim(skb, nlh);
3062         return -1;
3063 }
3064
3065 static int nf_tables_setelem_notify(const struct nft_ctx *ctx,
3066                                     const struct nft_set *set,
3067                                     const struct nft_set_elem *elem,
3068                                     int event, u16 flags)
3069 {
3070         struct net *net = ctx->net;
3071         u32 portid = ctx->portid;
3072         struct sk_buff *skb;
3073         int err;
3074
3075         if (!ctx->report && !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
3076                 return 0;
3077
3078         err = -ENOBUFS;
3079         skb = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
3080         if (skb == NULL)
3081                 goto err;
3082
3083         err = nf_tables_fill_setelem_info(skb, ctx, 0, portid, event, flags,
3084                                           set, elem);
3085         if (err < 0) {
3086                 kfree_skb(skb);
3087                 goto err;
3088         }
3089
3090         err = nfnetlink_send(skb, net, portid, NFNLGRP_NFTABLES, ctx->report,
3091                              GFP_KERNEL);
3092 err:
3093         if (err < 0)
3094                 nfnetlink_set_err(net, portid, NFNLGRP_NFTABLES, err);
3095         return err;
3096 }
3097
3098 static struct nft_trans *nft_trans_elem_alloc(struct nft_ctx *ctx,
3099                                               int msg_type,
3100                                               struct nft_set *set)
3101 {
3102         struct nft_trans *trans;
3103
3104         trans = nft_trans_alloc(ctx, msg_type, sizeof(struct nft_trans_elem));
3105         if (trans == NULL)
3106                 return NULL;
3107
3108         nft_trans_elem_set(trans) = set;
3109         return trans;
3110 }
3111
3112 static int nft_add_set_elem(struct nft_ctx *ctx, struct nft_set *set,
3113                             const struct nlattr *attr)
3114 {
3115         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
3116         struct nft_data_desc d1, d2;
3117         struct nft_set_elem elem;
3118         struct nft_set_binding *binding;
3119         enum nft_registers dreg;
3120         struct nft_trans *trans;
3121         int err;
3122
3123         if (set->size && set->nelems == set->size)
3124                 return -ENFILE;
3125
3126         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
3127                                nft_set_elem_policy);
3128         if (err < 0)
3129                 return err;
3130
3131         if (nla[NFTA_SET_ELEM_KEY] == NULL)
3132                 return -EINVAL;
3133
3134         elem.flags = 0;
3135         if (nla[NFTA_SET_ELEM_FLAGS] != NULL) {
3136                 elem.flags = ntohl(nla_get_be32(nla[NFTA_SET_ELEM_FLAGS]));
3137                 if (elem.flags & ~NFT_SET_ELEM_INTERVAL_END)
3138                         return -EINVAL;
3139         }
3140
3141         if (set->flags & NFT_SET_MAP) {
3142                 if (nla[NFTA_SET_ELEM_DATA] == NULL &&
3143                     !(elem.flags & NFT_SET_ELEM_INTERVAL_END))
3144                         return -EINVAL;
3145                 if (nla[NFTA_SET_ELEM_DATA] != NULL &&
3146                     elem.flags & NFT_SET_ELEM_INTERVAL_END)
3147                         return -EINVAL;
3148         } else {
3149                 if (nla[NFTA_SET_ELEM_DATA] != NULL)
3150                         return -EINVAL;
3151         }
3152
3153         err = nft_data_init(ctx, &elem.key, &d1, nla[NFTA_SET_ELEM_KEY]);
3154         if (err < 0)
3155                 goto err1;
3156         err = -EINVAL;
3157         if (d1.type != NFT_DATA_VALUE || d1.len != set->klen)
3158                 goto err2;
3159
3160         err = -EEXIST;
3161         if (set->ops->get(set, &elem) == 0)
3162                 goto err2;
3163
3164         if (nla[NFTA_SET_ELEM_DATA] != NULL) {
3165                 err = nft_data_init(ctx, &elem.data, &d2, nla[NFTA_SET_ELEM_DATA]);
3166                 if (err < 0)
3167                         goto err2;
3168
3169                 err = -EINVAL;
3170                 if (set->dtype != NFT_DATA_VERDICT && d2.len != set->dlen)
3171                         goto err3;
3172
3173                 dreg = nft_type_to_reg(set->dtype);
3174                 list_for_each_entry(binding, &set->bindings, list) {
3175                         struct nft_ctx bind_ctx = {
3176                                 .afi    = ctx->afi,
3177                                 .table  = ctx->table,
3178                                 .chain  = (struct nft_chain *)binding->chain,
3179                         };
3180
3181                         err = nft_validate_data_load(&bind_ctx, dreg,
3182                                                      &elem.data, d2.type);
3183                         if (err < 0)
3184                                 goto err3;
3185                 }
3186         }
3187
3188         trans = nft_trans_elem_alloc(ctx, NFT_MSG_NEWSETELEM, set);
3189         if (trans == NULL)
3190                 goto err3;
3191
3192         err = set->ops->insert(set, &elem);
3193         if (err < 0)
3194                 goto err4;
3195
3196         nft_trans_elem(trans) = elem;
3197         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
3198         return 0;
3199
3200 err4:
3201         kfree(trans);
3202 err3:
3203         if (nla[NFTA_SET_ELEM_DATA] != NULL)
3204                 nft_data_uninit(&elem.data, d2.type);
3205 err2:
3206         nft_data_uninit(&elem.key, d1.type);
3207 err1:
3208         return err;
3209 }
3210
3211 static int nf_tables_newsetelem(struct sock *nlsk, struct sk_buff *skb,
3212                                 const struct nlmsghdr *nlh,
3213                                 const struct nlattr * const nla[])
3214 {
3215         struct net *net = sock_net(skb->sk);
3216         const struct nlattr *attr;
3217         struct nft_set *set;
3218         struct nft_ctx ctx;
3219         int rem, err = 0;
3220
3221         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
3222                 return -EINVAL;
3223
3224         err = nft_ctx_init_from_elemattr(&ctx, skb, nlh, nla, true);
3225         if (err < 0)
3226                 return err;
3227
3228         set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]);
3229         if (IS_ERR(set)) {
3230                 if (nla[NFTA_SET_ELEM_LIST_SET_ID]) {
3231                         set = nf_tables_set_lookup_byid(net,
3232                                         nla[NFTA_SET_ELEM_LIST_SET_ID]);
3233                 }
3234                 if (IS_ERR(set))
3235                         return PTR_ERR(set);
3236         }
3237
3238         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
3239                 return -EBUSY;
3240
3241         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
3242                 err = nft_add_set_elem(&ctx, set, attr);
3243                 if (err < 0)
3244                         break;
3245
3246                 set->nelems++;
3247         }
3248         return err;
3249 }
3250
3251 static int nft_del_setelem(struct nft_ctx *ctx, struct nft_set *set,
3252                            const struct nlattr *attr)
3253 {
3254         struct nlattr *nla[NFTA_SET_ELEM_MAX + 1];
3255         struct nft_data_desc desc;
3256         struct nft_set_elem elem;
3257         struct nft_trans *trans;
3258         int err;
3259
3260         err = nla_parse_nested(nla, NFTA_SET_ELEM_MAX, attr,
3261                                nft_set_elem_policy);
3262         if (err < 0)
3263                 goto err1;
3264
3265         err = -EINVAL;
3266         if (nla[NFTA_SET_ELEM_KEY] == NULL)
3267                 goto err1;
3268
3269         err = nft_data_init(ctx, &elem.key, &desc, nla[NFTA_SET_ELEM_KEY]);
3270         if (err < 0)
3271                 goto err1;
3272
3273         err = -EINVAL;
3274         if (desc.type != NFT_DATA_VALUE || desc.len != set->klen)
3275                 goto err2;
3276
3277         err = set->ops->get(set, &elem);
3278         if (err < 0)
3279                 goto err2;
3280
3281         trans = nft_trans_elem_alloc(ctx, NFT_MSG_DELSETELEM, set);
3282         if (trans == NULL) {
3283                 err = -ENOMEM;
3284                 goto err2;
3285         }
3286
3287         nft_trans_elem(trans) = elem;
3288         list_add_tail(&trans->list, &ctx->net->nft.commit_list);
3289         return 0;
3290 err2:
3291         nft_data_uninit(&elem.key, desc.type);
3292 err1:
3293         return err;
3294 }
3295
3296 static int nf_tables_delsetelem(struct sock *nlsk, struct sk_buff *skb,
3297                                 const struct nlmsghdr *nlh,
3298                                 const struct nlattr * const nla[])
3299 {
3300         const struct nlattr *attr;
3301         struct nft_set *set;
3302         struct nft_ctx ctx;
3303         int rem, err = 0;
3304
3305         if (nla[NFTA_SET_ELEM_LIST_ELEMENTS] == NULL)
3306                 return -EINVAL;
3307
3308         err = nft_ctx_init_from_elemattr(&ctx, skb, nlh, nla, false);
3309         if (err < 0)
3310                 return err;
3311
3312         set = nf_tables_set_lookup(ctx.table, nla[NFTA_SET_ELEM_LIST_SET]);
3313         if (IS_ERR(set))
3314                 return PTR_ERR(set);
3315         if (!list_empty(&set->bindings) && set->flags & NFT_SET_CONSTANT)
3316                 return -EBUSY;
3317
3318         nla_for_each_nested(attr, nla[NFTA_SET_ELEM_LIST_ELEMENTS], rem) {
3319                 err = nft_del_setelem(&ctx, set, attr);
3320                 if (err < 0)
3321                         break;
3322
3323                 set->nelems--;
3324         }
3325         return err;
3326 }
3327
3328 static int nf_tables_fill_gen_info(struct sk_buff *skb, struct net *net,
3329                                    u32 portid, u32 seq)
3330 {
3331         struct nlmsghdr *nlh;
3332         struct nfgenmsg *nfmsg;
3333         int event = (NFNL_SUBSYS_NFTABLES << 8) | NFT_MSG_NEWGEN;
3334
3335         nlh = nlmsg_put(skb, portid, seq, event, sizeof(struct nfgenmsg), 0);
3336         if (nlh == NULL)
3337                 goto nla_put_failure;
3338
3339         nfmsg = nlmsg_data(nlh);
3340         nfmsg->nfgen_family     = AF_UNSPEC;
3341         nfmsg->version          = NFNETLINK_V0;
3342         nfmsg->res_id           = htons(net->nft.base_seq & 0xffff);
3343
3344         if (nla_put_be32(skb, NFTA_GEN_ID, htonl(net->nft.base_seq)))
3345                 goto nla_put_failure;
3346
3347         nlmsg_end(skb, nlh);
3348         return 0;
3349
3350 nla_put_failure:
3351         nlmsg_trim(skb, nlh);
3352         return -EMSGSIZE;
3353 }
3354
3355 static int nf_tables_gen_notify(struct net *net, struct sk_buff *skb, int event)
3356 {
3357         struct nlmsghdr *nlh = nlmsg_hdr(skb);
3358         struct sk_buff *skb2;
3359         int err;
3360
3361         if (nlmsg_report(nlh) &&
3362             !nfnetlink_has_listeners(net, NFNLGRP_NFTABLES))
3363                 return 0;
3364
3365         err = -ENOBUFS;
3366         skb2 = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL);
3367         if (skb2 == NULL)
3368                 goto err;
3369
3370         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
3371                                       nlh->nlmsg_seq);
3372         if (err < 0) {
3373                 kfree_skb(skb2);
3374                 goto err;
3375         }
3376
3377         err = nfnetlink_send(skb2, net, NETLINK_CB(skb).portid,
3378                              NFNLGRP_NFTABLES, nlmsg_report(nlh), GFP_KERNEL);
3379 err:
3380         if (err < 0) {
3381                 nfnetlink_set_err(net, NETLINK_CB(skb).portid, NFNLGRP_NFTABLES,
3382                                   err);
3383         }
3384         return err;
3385 }
3386
3387 static int nf_tables_getgen(struct sock *nlsk, struct sk_buff *skb,
3388                             const struct nlmsghdr *nlh,
3389                             const struct nlattr * const nla[])
3390 {
3391         struct net *net = sock_net(skb->sk);
3392         struct sk_buff *skb2;
3393         int err;
3394
3395         skb2 = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL);
3396         if (skb2 == NULL)
3397                 return -ENOMEM;
3398
3399         err = nf_tables_fill_gen_info(skb2, net, NETLINK_CB(skb).portid,
3400                                       nlh->nlmsg_seq);
3401         if (err < 0)
3402                 goto err;
3403
3404         return nlmsg_unicast(nlsk, skb2, NETLINK_CB(skb).portid);
3405 err:
3406         kfree_skb(skb2);
3407         return err;
3408 }
3409
3410 static const struct nfnl_callback nf_tables_cb[NFT_MSG_MAX] = {
3411         [NFT_MSG_NEWTABLE] = {
3412                 .call_batch     = nf_tables_newtable,
3413                 .attr_count     = NFTA_TABLE_MAX,
3414                 .policy         = nft_table_policy,
3415         },
3416         [NFT_MSG_GETTABLE] = {
3417                 .call           = nf_tables_gettable,
3418                 .attr_count     = NFTA_TABLE_MAX,
3419                 .policy         = nft_table_policy,
3420         },
3421         [NFT_MSG_DELTABLE] = {
3422                 .call_batch     = nf_tables_deltable,
3423                 .attr_count     = NFTA_TABLE_MAX,
3424                 .policy         = nft_table_policy,
3425         },
3426         [NFT_MSG_NEWCHAIN] = {
3427                 .call_batch     = nf_tables_newchain,
3428                 .attr_count     = NFTA_CHAIN_MAX,
3429                 .policy         = nft_chain_policy,
3430         },
3431         [NFT_MSG_GETCHAIN] = {
3432                 .call           = nf_tables_getchain,
3433                 .attr_count     = NFTA_CHAIN_MAX,
3434                 .policy         = nft_chain_policy,
3435         },
3436         [NFT_MSG_DELCHAIN] = {
3437                 .call_batch     = nf_tables_delchain,
3438                 .attr_count     = NFTA_CHAIN_MAX,
3439                 .policy         = nft_chain_policy,
3440         },
3441         [NFT_MSG_NEWRULE] = {
3442                 .call_batch     = nf_tables_newrule,
3443                 .attr_count     = NFTA_RULE_MAX,
3444                 .policy         = nft_rule_policy,
3445         },
3446         [NFT_MSG_GETRULE] = {
3447                 .call           = nf_tables_getrule,
3448                 .attr_count     = NFTA_RULE_MAX,
3449                 .policy         = nft_rule_policy,
3450         },
3451         [NFT_MSG_DELRULE] = {
3452                 .call_batch     = nf_tables_delrule,
3453                 .attr_count     = NFTA_RULE_MAX,
3454                 .policy         = nft_rule_policy,
3455         },
3456         [NFT_MSG_NEWSET] = {
3457                 .call_batch     = nf_tables_newset,
3458                 .attr_count     = NFTA_SET_MAX,
3459                 .policy         = nft_set_policy,
3460         },
3461         [NFT_MSG_GETSET] = {
3462                 .call           = nf_tables_getset,
3463                 .attr_count     = NFTA_SET_MAX,
3464                 .policy         = nft_set_policy,
3465         },
3466         [NFT_MSG_DELSET] = {
3467                 .call_batch     = nf_tables_delset,
3468                 .attr_count     = NFTA_SET_MAX,
3469                 .policy         = nft_set_policy,
3470         },
3471         [NFT_MSG_NEWSETELEM] = {
3472                 .call_batch     = nf_tables_newsetelem,
3473                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
3474                 .policy         = nft_set_elem_list_policy,
3475         },
3476         [NFT_MSG_GETSETELEM] = {
3477                 .call           = nf_tables_getsetelem,
3478                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
3479                 .policy         = nft_set_elem_list_policy,
3480         },
3481         [NFT_MSG_DELSETELEM] = {
3482                 .call_batch     = nf_tables_delsetelem,
3483                 .attr_count     = NFTA_SET_ELEM_LIST_MAX,
3484                 .policy         = nft_set_elem_list_policy,
3485         },
3486         [NFT_MSG_GETGEN] = {
3487                 .call           = nf_tables_getgen,
3488         },
3489 };
3490
3491 static void nft_chain_commit_update(struct nft_trans *trans)
3492 {
3493         struct nft_base_chain *basechain;
3494
3495         if (nft_trans_chain_name(trans)[0])
3496                 strcpy(trans->ctx.chain->name, nft_trans_chain_name(trans));
3497
3498         if (!(trans->ctx.chain->flags & NFT_BASE_CHAIN))
3499                 return;
3500
3501         basechain = nft_base_chain(trans->ctx.chain);
3502         nft_chain_stats_replace(basechain, nft_trans_chain_stats(trans));
3503
3504         switch (nft_trans_chain_policy(trans)) {
3505         case NF_DROP:
3506         case NF_ACCEPT:
3507                 basechain->policy = nft_trans_chain_policy(trans);
3508                 break;
3509         }
3510 }
3511
3512 static void nf_tables_commit_release(struct nft_trans *trans)
3513 {
3514         switch (trans->msg_type) {
3515         case NFT_MSG_DELTABLE:
3516                 nf_tables_table_destroy(&trans->ctx);
3517                 break;
3518         case NFT_MSG_DELCHAIN:
3519                 nf_tables_chain_destroy(trans->ctx.chain);
3520                 break;
3521         case NFT_MSG_DELRULE:
3522                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
3523                 break;
3524         case NFT_MSG_DELSET:
3525                 nft_set_destroy(nft_trans_set(trans));
3526                 break;
3527         }
3528         kfree(trans);
3529 }
3530
3531 static int nf_tables_commit(struct sk_buff *skb)
3532 {
3533         struct net *net = sock_net(skb->sk);
3534         struct nft_trans *trans, *next;
3535         struct nft_trans_elem *te;
3536
3537         /* Bump generation counter, invalidate any dump in progress */
3538         while (++net->nft.base_seq == 0);
3539
3540         /* A new generation has just started */
3541         net->nft.gencursor = gencursor_next(net);
3542
3543         /* Make sure all packets have left the previous generation before
3544          * purging old rules.
3545          */
3546         synchronize_rcu();
3547
3548         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
3549                 switch (trans->msg_type) {
3550                 case NFT_MSG_NEWTABLE:
3551                         if (nft_trans_table_update(trans)) {
3552                                 if (!nft_trans_table_enable(trans)) {
3553                                         nf_tables_table_disable(trans->ctx.afi,
3554                                                                 trans->ctx.table);
3555                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
3556                                 }
3557                         } else {
3558                                 trans->ctx.table->flags &= ~NFT_TABLE_INACTIVE;
3559                         }
3560                         nf_tables_table_notify(&trans->ctx, NFT_MSG_NEWTABLE);
3561                         nft_trans_destroy(trans);
3562                         break;
3563                 case NFT_MSG_DELTABLE:
3564                         nf_tables_table_notify(&trans->ctx, NFT_MSG_DELTABLE);
3565                         break;
3566                 case NFT_MSG_NEWCHAIN:
3567                         if (nft_trans_chain_update(trans))
3568                                 nft_chain_commit_update(trans);
3569                         else
3570                                 trans->ctx.chain->flags &= ~NFT_CHAIN_INACTIVE;
3571
3572                         nf_tables_chain_notify(&trans->ctx, NFT_MSG_NEWCHAIN);
3573                         nft_trans_destroy(trans);
3574                         break;
3575                 case NFT_MSG_DELCHAIN:
3576                         nf_tables_chain_notify(&trans->ctx, NFT_MSG_DELCHAIN);
3577                         nf_tables_unregister_hooks(trans->ctx.table,
3578                                                    trans->ctx.chain,
3579                                                    trans->ctx.afi->nops);
3580                         break;
3581                 case NFT_MSG_NEWRULE:
3582                         nft_rule_clear(trans->ctx.net, nft_trans_rule(trans));
3583                         nf_tables_rule_notify(&trans->ctx,
3584                                               nft_trans_rule(trans),
3585                                               NFT_MSG_NEWRULE);
3586                         nft_trans_destroy(trans);
3587                         break;
3588                 case NFT_MSG_DELRULE:
3589                         list_del_rcu(&nft_trans_rule(trans)->list);
3590                         nf_tables_rule_notify(&trans->ctx,
3591                                               nft_trans_rule(trans),
3592                                               NFT_MSG_DELRULE);
3593                         break;
3594                 case NFT_MSG_NEWSET:
3595                         nft_trans_set(trans)->flags &= ~NFT_SET_INACTIVE;
3596                         /* This avoids hitting -EBUSY when deleting the table
3597                          * from the transaction.
3598                          */
3599                         if (nft_trans_set(trans)->flags & NFT_SET_ANONYMOUS &&
3600                             !list_empty(&nft_trans_set(trans)->bindings))
3601                                 trans->ctx.table->use--;
3602
3603                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
3604                                              NFT_MSG_NEWSET, GFP_KERNEL);
3605                         nft_trans_destroy(trans);
3606                         break;
3607                 case NFT_MSG_DELSET:
3608                         nf_tables_set_notify(&trans->ctx, nft_trans_set(trans),
3609                                              NFT_MSG_DELSET, GFP_KERNEL);
3610                         break;
3611                 case NFT_MSG_NEWSETELEM:
3612                         nf_tables_setelem_notify(&trans->ctx,
3613                                                  nft_trans_elem_set(trans),
3614                                                  &nft_trans_elem(trans),
3615                                                  NFT_MSG_NEWSETELEM, 0);
3616                         nft_trans_destroy(trans);
3617                         break;
3618                 case NFT_MSG_DELSETELEM:
3619                         te = (struct nft_trans_elem *)trans->data;
3620                         nf_tables_setelem_notify(&trans->ctx, te->set,
3621                                                  &te->elem,
3622                                                  NFT_MSG_DELSETELEM, 0);
3623                         te->set->ops->get(te->set, &te->elem);
3624                         nft_data_uninit(&te->elem.key, NFT_DATA_VALUE);
3625                         if (te->set->flags & NFT_SET_MAP &&
3626                             !(te->elem.flags & NFT_SET_ELEM_INTERVAL_END))
3627                                 nft_data_uninit(&te->elem.data, te->set->dtype);
3628                         te->set->ops->remove(te->set, &te->elem);
3629                         nft_trans_destroy(trans);
3630                         break;
3631                 }
3632         }
3633
3634         synchronize_rcu();
3635
3636         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
3637                 list_del(&trans->list);
3638                 nf_tables_commit_release(trans);
3639         }
3640
3641         nf_tables_gen_notify(net, skb, NFT_MSG_NEWGEN);
3642
3643         return 0;
3644 }
3645
3646 static void nf_tables_abort_release(struct nft_trans *trans)
3647 {
3648         switch (trans->msg_type) {
3649         case NFT_MSG_NEWTABLE:
3650                 nf_tables_table_destroy(&trans->ctx);
3651                 break;
3652         case NFT_MSG_NEWCHAIN:
3653                 nf_tables_chain_destroy(trans->ctx.chain);
3654                 break;
3655         case NFT_MSG_NEWRULE:
3656                 nf_tables_rule_destroy(&trans->ctx, nft_trans_rule(trans));
3657                 break;
3658         case NFT_MSG_NEWSET:
3659                 nft_set_destroy(nft_trans_set(trans));
3660                 break;
3661         }
3662         kfree(trans);
3663 }
3664
3665 static int nf_tables_abort(struct sk_buff *skb)
3666 {
3667         struct net *net = sock_net(skb->sk);
3668         struct nft_trans *trans, *next;
3669         struct nft_trans_elem *te;
3670
3671         list_for_each_entry_safe(trans, next, &net->nft.commit_list, list) {
3672                 switch (trans->msg_type) {
3673                 case NFT_MSG_NEWTABLE:
3674                         if (nft_trans_table_update(trans)) {
3675                                 if (nft_trans_table_enable(trans)) {
3676                                         nf_tables_table_disable(trans->ctx.afi,
3677                                                                 trans->ctx.table);
3678                                         trans->ctx.table->flags |= NFT_TABLE_F_DORMANT;
3679                                 }
3680                                 nft_trans_destroy(trans);
3681                         } else {
3682                                 list_del_rcu(&trans->ctx.table->list);
3683                         }
3684                         break;
3685                 case NFT_MSG_DELTABLE:
3686                         list_add_tail_rcu(&trans->ctx.table->list,
3687                                           &trans->ctx.afi->tables);
3688                         nft_trans_destroy(trans);
3689                         break;
3690                 case NFT_MSG_NEWCHAIN:
3691                         if (nft_trans_chain_update(trans)) {
3692                                 free_percpu(nft_trans_chain_stats(trans));
3693
3694                                 nft_trans_destroy(trans);
3695                         } else {
3696                                 trans->ctx.table->use--;
3697                                 list_del_rcu(&trans->ctx.chain->list);
3698                                 nf_tables_unregister_hooks(trans->ctx.table,
3699                                                            trans->ctx.chain,
3700                                                            trans->ctx.afi->nops);
3701                         }
3702                         break;
3703                 case NFT_MSG_DELCHAIN:
3704                         trans->ctx.table->use++;
3705                         list_add_tail_rcu(&trans->ctx.chain->list,
3706                                           &trans->ctx.table->chains);
3707                         nft_trans_destroy(trans);
3708                         break;
3709                 case NFT_MSG_NEWRULE:
3710                         trans->ctx.chain->use--;
3711                         list_del_rcu(&nft_trans_rule(trans)->list);
3712                         break;
3713                 case NFT_MSG_DELRULE:
3714                         trans->ctx.chain->use++;
3715                         nft_rule_clear(trans->ctx.net, nft_trans_rule(trans));
3716                         nft_trans_destroy(trans);
3717                         break;
3718                 case NFT_MSG_NEWSET:
3719                         trans->ctx.table->use--;
3720                         list_del_rcu(&nft_trans_set(trans)->list);
3721                         break;
3722                 case NFT_MSG_DELSET:
3723                         trans->ctx.table->use++;
3724                         list_add_tail_rcu(&nft_trans_set(trans)->list,
3725                                           &trans->ctx.table->sets);
3726                         nft_trans_destroy(trans);
3727                         break;
3728                 case NFT_MSG_NEWSETELEM:
3729                         nft_trans_elem_set(trans)->nelems--;
3730                         te = (struct nft_trans_elem *)trans->data;
3731                         te->set->ops->get(te->set, &te->elem);
3732                         nft_data_uninit(&te->elem.key, NFT_DATA_VALUE);
3733                         if (te->set->flags & NFT_SET_MAP &&
3734                             !(te->elem.flags & NFT_SET_ELEM_INTERVAL_END))
3735                                 nft_data_uninit(&te->elem.data, te->set->dtype);
3736                         te->set->ops->remove(te->set, &te->elem);
3737                         nft_trans_destroy(trans);
3738                         break;
3739                 case NFT_MSG_DELSETELEM:
3740                         nft_trans_elem_set(trans)->nelems++;
3741                         nft_trans_destroy(trans);
3742                         break;
3743                 }
3744         }
3745
3746         synchronize_rcu();
3747
3748         list_for_each_entry_safe_reverse(trans, next,
3749                                          &net->nft.commit_list, list) {
3750                 list_del(&trans->list);
3751                 nf_tables_abort_release(trans);
3752         }
3753
3754         return 0;
3755 }
3756
3757 static const struct nfnetlink_subsystem nf_tables_subsys = {
3758         .name           = "nf_tables",
3759         .subsys_id      = NFNL_SUBSYS_NFTABLES,
3760         .cb_count       = NFT_MSG_MAX,
3761         .cb             = nf_tables_cb,
3762         .commit         = nf_tables_commit,
3763         .abort          = nf_tables_abort,
3764 };
3765
3766 int nft_chain_validate_dependency(const struct nft_chain *chain,
3767                                   enum nft_chain_type type)
3768 {
3769         const struct nft_base_chain *basechain;
3770
3771         if (chain->flags & NFT_BASE_CHAIN) {
3772                 basechain = nft_base_chain(chain);
3773                 if (basechain->type->type != type)
3774                         return -EOPNOTSUPP;
3775         }
3776         return 0;
3777 }
3778 EXPORT_SYMBOL_GPL(nft_chain_validate_dependency);
3779
3780 int nft_chain_validate_hooks(const struct nft_chain *chain,
3781                              unsigned int hook_flags)
3782 {
3783         struct nft_base_chain *basechain;
3784
3785         if (chain->flags & NFT_BASE_CHAIN) {
3786                 basechain = nft_base_chain(chain);
3787
3788                 if ((1 << basechain->ops[0].hooknum) & hook_flags)
3789                         return 0;
3790
3791                 return -EOPNOTSUPP;
3792         }
3793
3794         return 0;
3795 }
3796 EXPORT_SYMBOL_GPL(nft_chain_validate_hooks);
3797
3798 /*
3799  * Loop detection - walk through the ruleset beginning at the destination chain
3800  * of a new jump until either the source chain is reached (loop) or all
3801  * reachable chains have been traversed.
3802  *
3803  * The loop check is performed whenever a new jump verdict is added to an
3804  * expression or verdict map or a verdict map is bound to a new chain.
3805  */
3806
3807 static int nf_tables_check_loops(const struct nft_ctx *ctx,
3808                                  const struct nft_chain *chain);
3809
3810 static int nf_tables_loop_check_setelem(const struct nft_ctx *ctx,
3811                                         const struct nft_set *set,
3812                                         const struct nft_set_iter *iter,
3813                                         const struct nft_set_elem *elem)
3814 {
3815         if (elem->flags & NFT_SET_ELEM_INTERVAL_END)
3816                 return 0;
3817
3818         switch (elem->data.verdict) {
3819         case NFT_JUMP:
3820         case NFT_GOTO:
3821                 return nf_tables_check_loops(ctx, elem->data.chain);
3822         default:
3823                 return 0;
3824         }
3825 }
3826
3827 static int nf_tables_check_loops(const struct nft_ctx *ctx,
3828                                  const struct nft_chain *chain)
3829 {
3830         const struct nft_rule *rule;
3831         const struct nft_expr *expr, *last;
3832         const struct nft_set *set;
3833         struct nft_set_binding *binding;
3834         struct nft_set_iter iter;
3835
3836         if (ctx->chain == chain)
3837                 return -ELOOP;
3838
3839         list_for_each_entry(rule, &chain->rules, list) {
3840                 nft_rule_for_each_expr(expr, last, rule) {
3841                         const struct nft_data *data = NULL;
3842                         int err;
3843
3844                         if (!expr->ops->validate)
3845                                 continue;
3846
3847                         err = expr->ops->validate(ctx, expr, &data);
3848                         if (err < 0)
3849                                 return err;
3850
3851                         if (data == NULL)
3852                                 continue;
3853
3854                         switch (data->verdict) {
3855                         case NFT_JUMP:
3856                         case NFT_GOTO:
3857                                 err = nf_tables_check_loops(ctx, data->chain);
3858                                 if (err < 0)
3859                                         return err;
3860                         default:
3861                                 break;
3862                         }
3863                 }
3864         }
3865
3866         list_for_each_entry(set, &ctx->table->sets, list) {
3867                 if (!(set->flags & NFT_SET_MAP) ||
3868                     set->dtype != NFT_DATA_VERDICT)
3869                         continue;
3870
3871                 list_for_each_entry(binding, &set->bindings, list) {
3872                         if (binding->chain != chain)
3873                                 continue;
3874
3875                         iter.skip       = 0;
3876                         iter.count      = 0;
3877                         iter.err        = 0;
3878                         iter.fn         = nf_tables_loop_check_setelem;
3879
3880                         set->ops->walk(ctx, set, &iter);
3881                         if (iter.err < 0)
3882                                 return iter.err;
3883                 }
3884         }
3885
3886         return 0;
3887 }
3888
3889 /**
3890  *      nft_validate_input_register - validate an expressions' input register
3891  *
3892  *      @reg: the register number
3893  *
3894  *      Validate that the input register is one of the general purpose
3895  *      registers.
3896  */
3897 int nft_validate_input_register(enum nft_registers reg)
3898 {
3899         if (reg <= NFT_REG_VERDICT)
3900                 return -EINVAL;
3901         if (reg > NFT_REG_MAX)
3902                 return -ERANGE;
3903         return 0;
3904 }
3905 EXPORT_SYMBOL_GPL(nft_validate_input_register);
3906
3907 /**
3908  *      nft_validate_output_register - validate an expressions' output register
3909  *
3910  *      @reg: the register number
3911  *
3912  *      Validate that the output register is one of the general purpose
3913  *      registers or the verdict register.
3914  */
3915 int nft_validate_output_register(enum nft_registers reg)
3916 {
3917         if (reg < NFT_REG_VERDICT)
3918                 return -EINVAL;
3919         if (reg > NFT_REG_MAX)
3920                 return -ERANGE;
3921         return 0;
3922 }
3923 EXPORT_SYMBOL_GPL(nft_validate_output_register);
3924
3925 /**
3926  *      nft_validate_data_load - validate an expressions' data load
3927  *
3928  *      @ctx: context of the expression performing the load
3929  *      @reg: the destination register number
3930  *      @data: the data to load
3931  *      @type: the data type
3932  *
3933  *      Validate that a data load uses the appropriate data type for
3934  *      the destination register. A value of NULL for the data means
3935  *      that its runtime gathered data, which is always of type
3936  *      NFT_DATA_VALUE.
3937  */
3938 int nft_validate_data_load(const struct nft_ctx *ctx, enum nft_registers reg,
3939                            const struct nft_data *data,
3940                            enum nft_data_types type)
3941 {
3942         int err;
3943
3944         switch (reg) {
3945         case NFT_REG_VERDICT:
3946                 if (data == NULL || type != NFT_DATA_VERDICT)
3947                         return -EINVAL;
3948
3949                 if (data->verdict == NFT_GOTO || data->verdict == NFT_JUMP) {
3950                         err = nf_tables_check_loops(ctx, data->chain);
3951                         if (err < 0)
3952                                 return err;
3953
3954                         if (ctx->chain->level + 1 > data->chain->level) {
3955                                 if (ctx->chain->level + 1 == NFT_JUMP_STACK_SIZE)
3956                                         return -EMLINK;
3957                                 data->chain->level = ctx->chain->level + 1;
3958                         }
3959                 }
3960
3961                 return 0;
3962         default:
3963                 if (data != NULL && type != NFT_DATA_VALUE)
3964                         return -EINVAL;
3965                 return 0;
3966         }
3967 }
3968 EXPORT_SYMBOL_GPL(nft_validate_data_load);
3969
3970 static const struct nla_policy nft_verdict_policy[NFTA_VERDICT_MAX + 1] = {
3971         [NFTA_VERDICT_CODE]     = { .type = NLA_U32 },
3972         [NFTA_VERDICT_CHAIN]    = { .type = NLA_STRING,
3973                                     .len = NFT_CHAIN_MAXNAMELEN - 1 },
3974 };
3975
3976 static int nft_verdict_init(const struct nft_ctx *ctx, struct nft_data *data,
3977                             struct nft_data_desc *desc, const struct nlattr *nla)
3978 {
3979         struct nlattr *tb[NFTA_VERDICT_MAX + 1];
3980         struct nft_chain *chain;
3981         int err;
3982
3983         err = nla_parse_nested(tb, NFTA_VERDICT_MAX, nla, nft_verdict_policy);
3984         if (err < 0)
3985                 return err;
3986
3987         if (!tb[NFTA_VERDICT_CODE])
3988                 return -EINVAL;
3989         data->verdict = ntohl(nla_get_be32(tb[NFTA_VERDICT_CODE]));
3990
3991         switch (data->verdict) {
3992         default:
3993                 switch (data->verdict & NF_VERDICT_MASK) {
3994                 case NF_ACCEPT:
3995                 case NF_DROP:
3996                 case NF_QUEUE:
3997                         break;
3998                 default:
3999                         return -EINVAL;
4000                 }
4001                 /* fall through */
4002         case NFT_CONTINUE:
4003         case NFT_BREAK:
4004         case NFT_RETURN:
4005                 desc->len = sizeof(data->verdict);
4006                 break;
4007         case NFT_JUMP:
4008         case NFT_GOTO:
4009                 if (!tb[NFTA_VERDICT_CHAIN])
4010                         return -EINVAL;
4011                 chain = nf_tables_chain_lookup(ctx->table,
4012                                                tb[NFTA_VERDICT_CHAIN]);
4013                 if (IS_ERR(chain))
4014                         return PTR_ERR(chain);
4015                 if (chain->flags & NFT_BASE_CHAIN)
4016                         return -EOPNOTSUPP;
4017
4018                 chain->use++;
4019                 data->chain = chain;
4020                 desc->len = sizeof(data);
4021                 break;
4022         }
4023
4024         desc->type = NFT_DATA_VERDICT;
4025         return 0;
4026 }
4027
4028 static void nft_verdict_uninit(const struct nft_data *data)
4029 {
4030         switch (data->verdict) {
4031         case NFT_JUMP:
4032         case NFT_GOTO:
4033                 data->chain->use--;
4034                 break;
4035         }
4036 }
4037
4038 static int nft_verdict_dump(struct sk_buff *skb, const struct nft_data *data)
4039 {
4040         struct nlattr *nest;
4041
4042         nest = nla_nest_start(skb, NFTA_DATA_VERDICT);
4043         if (!nest)
4044                 goto nla_put_failure;
4045
4046         if (nla_put_be32(skb, NFTA_VERDICT_CODE, htonl(data->verdict)))
4047                 goto nla_put_failure;
4048
4049         switch (data->verdict) {
4050         case NFT_JUMP:
4051         case NFT_GOTO:
4052                 if (nla_put_string(skb, NFTA_VERDICT_CHAIN, data->chain->name))
4053                         goto nla_put_failure;
4054         }
4055         nla_nest_end(skb, nest);
4056         return 0;
4057
4058 nla_put_failure:
4059         return -1;
4060 }
4061
4062 static int nft_value_init(const struct nft_ctx *ctx, struct nft_data *data,
4063                           struct nft_data_desc *desc, const struct nlattr *nla)
4064 {
4065         unsigned int len;
4066
4067         len = nla_len(nla);
4068         if (len == 0)
4069                 return -EINVAL;
4070         if (len > sizeof(data->data))
4071                 return -EOVERFLOW;
4072
4073         nla_memcpy(data->data, nla, sizeof(data->data));
4074         desc->type = NFT_DATA_VALUE;
4075         desc->len  = len;
4076         return 0;
4077 }
4078
4079 static int nft_value_dump(struct sk_buff *skb, const struct nft_data *data,
4080                           unsigned int len)
4081 {
4082         return nla_put(skb, NFTA_DATA_VALUE, len, data->data);
4083 }
4084
4085 static const struct nla_policy nft_data_policy[NFTA_DATA_MAX + 1] = {
4086         [NFTA_DATA_VALUE]       = { .type = NLA_BINARY,
4087                                     .len  = FIELD_SIZEOF(struct nft_data, data) },
4088         [NFTA_DATA_VERDICT]     = { .type = NLA_NESTED },
4089 };
4090
4091 /**
4092  *      nft_data_init - parse nf_tables data netlink attributes
4093  *
4094  *      @ctx: context of the expression using the data
4095  *      @data: destination struct nft_data
4096  *      @desc: data description
4097  *      @nla: netlink attribute containing data
4098  *
4099  *      Parse the netlink data attributes and initialize a struct nft_data.
4100  *      The type and length of data are returned in the data description.
4101  *
4102  *      The caller can indicate that it only wants to accept data of type
4103  *      NFT_DATA_VALUE by passing NULL for the ctx argument.
4104  */
4105 int nft_data_init(const struct nft_ctx *ctx, struct nft_data *data,
4106                   struct nft_data_desc *desc, const struct nlattr *nla)
4107 {
4108         struct nlattr *tb[NFTA_DATA_MAX + 1];
4109         int err;
4110
4111         err = nla_parse_nested(tb, NFTA_DATA_MAX, nla, nft_data_policy);
4112         if (err < 0)
4113                 return err;
4114
4115         if (tb[NFTA_DATA_VALUE])
4116                 return nft_value_init(ctx, data, desc, tb[NFTA_DATA_VALUE]);
4117         if (tb[NFTA_DATA_VERDICT] && ctx != NULL)
4118                 return nft_verdict_init(ctx, data, desc, tb[NFTA_DATA_VERDICT]);
4119         return -EINVAL;
4120 }
4121 EXPORT_SYMBOL_GPL(nft_data_init);
4122
4123 /**
4124  *      nft_data_uninit - release a nft_data item
4125  *
4126  *      @data: struct nft_data to release
4127  *      @type: type of data
4128  *
4129  *      Release a nft_data item. NFT_DATA_VALUE types can be silently discarded,
4130  *      all others need to be released by calling this function.
4131  */
4132 void nft_data_uninit(const struct nft_data *data, enum nft_data_types type)
4133 {
4134         switch (type) {
4135         case NFT_DATA_VALUE:
4136                 return;
4137         case NFT_DATA_VERDICT:
4138                 return nft_verdict_uninit(data);
4139         default:
4140                 WARN_ON(1);
4141         }
4142 }
4143 EXPORT_SYMBOL_GPL(nft_data_uninit);
4144
4145 int nft_data_dump(struct sk_buff *skb, int attr, const struct nft_data *data,
4146                   enum nft_data_types type, unsigned int len)
4147 {
4148         struct nlattr *nest;
4149         int err;
4150
4151         nest = nla_nest_start(skb, attr);
4152         if (nest == NULL)
4153                 return -1;
4154
4155         switch (type) {
4156         case NFT_DATA_VALUE:
4157                 err = nft_value_dump(skb, data, len);
4158                 break;
4159         case NFT_DATA_VERDICT:
4160                 err = nft_verdict_dump(skb, data);
4161                 break;
4162         default:
4163                 err = -EINVAL;
4164                 WARN_ON(1);
4165         }
4166
4167         nla_nest_end(skb, nest);
4168         return err;
4169 }
4170 EXPORT_SYMBOL_GPL(nft_data_dump);
4171
4172 static int nf_tables_init_net(struct net *net)
4173 {
4174         INIT_LIST_HEAD(&net->nft.af_info);
4175         INIT_LIST_HEAD(&net->nft.commit_list);
4176         net->nft.base_seq = 1;
4177         return 0;
4178 }
4179
4180 static struct pernet_operations nf_tables_net_ops = {
4181         .init   = nf_tables_init_net,
4182 };
4183
4184 static int __init nf_tables_module_init(void)
4185 {
4186         int err;
4187
4188         info = kmalloc(sizeof(struct nft_expr_info) * NFT_RULE_MAXEXPRS,
4189                        GFP_KERNEL);
4190         if (info == NULL) {
4191                 err = -ENOMEM;
4192                 goto err1;
4193         }
4194
4195         err = nf_tables_core_module_init();
4196         if (err < 0)
4197                 goto err2;
4198
4199         err = nfnetlink_subsys_register(&nf_tables_subsys);
4200         if (err < 0)
4201                 goto err3;
4202
4203         pr_info("nf_tables: (c) 2007-2009 Patrick McHardy <kaber@trash.net>\n");
4204         return register_pernet_subsys(&nf_tables_net_ops);
4205 err3:
4206         nf_tables_core_module_exit();
4207 err2:
4208         kfree(info);
4209 err1:
4210         return err;
4211 }
4212
4213 static void __exit nf_tables_module_exit(void)
4214 {
4215         unregister_pernet_subsys(&nf_tables_net_ops);
4216         nfnetlink_subsys_unregister(&nf_tables_subsys);
4217         rcu_barrier();
4218         nf_tables_core_module_exit();
4219         kfree(info);
4220 }
4221
4222 module_init(nf_tables_module_init);
4223 module_exit(nf_tables_module_exit);
4224
4225 MODULE_LICENSE("GPL");
4226 MODULE_AUTHOR("Patrick McHardy <kaber@trash.net>");
4227 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_NFTABLES);