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