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