netfilter: ipset: Use SET_WITH_*() helpers to test set extensions
[firefly-linux-kernel-4.4.55.git] / net / netfilter / ipset / ip_set_core.c
1 /* Copyright (C) 2000-2002 Joakim Axelsson <gozem@linux.nu>
2  *                         Patrick Schaaf <bof@bof.de>
3  * Copyright (C) 2003-2013 Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License version 2 as
7  * published by the Free Software Foundation.
8  */
9
10 /* Kernel module for IP set management */
11
12 #include <linux/init.h>
13 #include <linux/module.h>
14 #include <linux/moduleparam.h>
15 #include <linux/ip.h>
16 #include <linux/skbuff.h>
17 #include <linux/spinlock.h>
18 #include <linux/rculist.h>
19 #include <net/netlink.h>
20 #include <net/net_namespace.h>
21 #include <net/netns/generic.h>
22
23 #include <linux/netfilter.h>
24 #include <linux/netfilter/x_tables.h>
25 #include <linux/netfilter/nfnetlink.h>
26 #include <linux/netfilter/ipset/ip_set.h>
27
28 static LIST_HEAD(ip_set_type_list);             /* all registered set types */
29 static DEFINE_MUTEX(ip_set_type_mutex);         /* protects ip_set_type_list */
30 static DEFINE_RWLOCK(ip_set_ref_lock);          /* protects the set refs */
31
32 struct ip_set_net {
33         struct ip_set * __rcu *ip_set_list;     /* all individual sets */
34         ip_set_id_t     ip_set_max;     /* max number of sets */
35         int             is_deleted;     /* deleted by ip_set_net_exit */
36 };
37 static int ip_set_net_id __read_mostly;
38
39 static inline struct ip_set_net *ip_set_pernet(struct net *net)
40 {
41         return net_generic(net, ip_set_net_id);
42 }
43
44 #define IP_SET_INC      64
45 #define STRNCMP(a, b)   (strncmp(a, b, IPSET_MAXNAMELEN) == 0)
46
47 static unsigned int max_sets;
48
49 module_param(max_sets, int, 0600);
50 MODULE_PARM_DESC(max_sets, "maximal number of sets");
51 MODULE_LICENSE("GPL");
52 MODULE_AUTHOR("Jozsef Kadlecsik <kadlec@blackhole.kfki.hu>");
53 MODULE_DESCRIPTION("core IP set support");
54 MODULE_ALIAS_NFNL_SUBSYS(NFNL_SUBSYS_IPSET);
55
56 /* When the nfnl mutex is held: */
57 #define ip_set_dereference(p)           \
58         rcu_dereference_protected(p, 1)
59 #define ip_set(inst, id)                \
60         ip_set_dereference((inst)->ip_set_list)[id]
61
62 /*
63  * The set types are implemented in modules and registered set types
64  * can be found in ip_set_type_list. Adding/deleting types is
65  * serialized by ip_set_type_mutex.
66  */
67
68 static inline void
69 ip_set_type_lock(void)
70 {
71         mutex_lock(&ip_set_type_mutex);
72 }
73
74 static inline void
75 ip_set_type_unlock(void)
76 {
77         mutex_unlock(&ip_set_type_mutex);
78 }
79
80 /* Register and deregister settype */
81
82 static struct ip_set_type *
83 find_set_type(const char *name, u8 family, u8 revision)
84 {
85         struct ip_set_type *type;
86
87         list_for_each_entry_rcu(type, &ip_set_type_list, list)
88                 if (STRNCMP(type->name, name) &&
89                     (type->family == family ||
90                      type->family == NFPROTO_UNSPEC) &&
91                     revision >= type->revision_min &&
92                     revision <= type->revision_max)
93                         return type;
94         return NULL;
95 }
96
97 /* Unlock, try to load a set type module and lock again */
98 static bool
99 load_settype(const char *name)
100 {
101         nfnl_unlock(NFNL_SUBSYS_IPSET);
102         pr_debug("try to load ip_set_%s\n", name);
103         if (request_module("ip_set_%s", name) < 0) {
104                 pr_warn("Can't find ip_set type %s\n", name);
105                 nfnl_lock(NFNL_SUBSYS_IPSET);
106                 return false;
107         }
108         nfnl_lock(NFNL_SUBSYS_IPSET);
109         return true;
110 }
111
112 /* Find a set type and reference it */
113 #define find_set_type_get(name, family, revision, found)        \
114         __find_set_type_get(name, family, revision, found, false)
115
116 static int
117 __find_set_type_get(const char *name, u8 family, u8 revision,
118                     struct ip_set_type **found, bool retry)
119 {
120         struct ip_set_type *type;
121         int err;
122
123         if (retry && !load_settype(name))
124                 return -IPSET_ERR_FIND_TYPE;
125
126         rcu_read_lock();
127         *found = find_set_type(name, family, revision);
128         if (*found) {
129                 err = !try_module_get((*found)->me) ? -EFAULT : 0;
130                 goto unlock;
131         }
132         /* Make sure the type is already loaded
133          * but we don't support the revision */
134         list_for_each_entry_rcu(type, &ip_set_type_list, list)
135                 if (STRNCMP(type->name, name)) {
136                         err = -IPSET_ERR_FIND_TYPE;
137                         goto unlock;
138                 }
139         rcu_read_unlock();
140
141         return retry ? -IPSET_ERR_FIND_TYPE :
142                 __find_set_type_get(name, family, revision, found, true);
143
144 unlock:
145         rcu_read_unlock();
146         return err;
147 }
148
149 /* Find a given set type by name and family.
150  * If we succeeded, the supported minimal and maximum revisions are
151  * filled out.
152  */
153 #define find_set_type_minmax(name, family, min, max) \
154         __find_set_type_minmax(name, family, min, max, false)
155
156 static int
157 __find_set_type_minmax(const char *name, u8 family, u8 *min, u8 *max,
158                        bool retry)
159 {
160         struct ip_set_type *type;
161         bool found = false;
162
163         if (retry && !load_settype(name))
164                 return -IPSET_ERR_FIND_TYPE;
165
166         *min = 255; *max = 0;
167         rcu_read_lock();
168         list_for_each_entry_rcu(type, &ip_set_type_list, list)
169                 if (STRNCMP(type->name, name) &&
170                     (type->family == family ||
171                      type->family == NFPROTO_UNSPEC)) {
172                         found = true;
173                         if (type->revision_min < *min)
174                                 *min = type->revision_min;
175                         if (type->revision_max > *max)
176                                 *max = type->revision_max;
177                 }
178         rcu_read_unlock();
179         if (found)
180                 return 0;
181
182         return retry ? -IPSET_ERR_FIND_TYPE :
183                 __find_set_type_minmax(name, family, min, max, true);
184 }
185
186 #define family_name(f)  ((f) == NFPROTO_IPV4 ? "inet" : \
187                          (f) == NFPROTO_IPV6 ? "inet6" : "any")
188
189 /* Register a set type structure. The type is identified by
190  * the unique triple of name, family and revision.
191  */
192 int
193 ip_set_type_register(struct ip_set_type *type)
194 {
195         int ret = 0;
196
197         if (type->protocol != IPSET_PROTOCOL) {
198                 pr_warn("ip_set type %s, family %s, revision %u:%u uses wrong protocol version %u (want %u)\n",
199                         type->name, family_name(type->family),
200                         type->revision_min, type->revision_max,
201                         type->protocol, IPSET_PROTOCOL);
202                 return -EINVAL;
203         }
204
205         ip_set_type_lock();
206         if (find_set_type(type->name, type->family, type->revision_min)) {
207                 /* Duplicate! */
208                 pr_warn("ip_set type %s, family %s with revision min %u already registered!\n",
209                         type->name, family_name(type->family),
210                         type->revision_min);
211                 ret = -EINVAL;
212                 goto unlock;
213         }
214         list_add_rcu(&type->list, &ip_set_type_list);
215         pr_debug("type %s, family %s, revision %u:%u registered.\n",
216                  type->name, family_name(type->family),
217                  type->revision_min, type->revision_max);
218 unlock:
219         ip_set_type_unlock();
220         return ret;
221 }
222 EXPORT_SYMBOL_GPL(ip_set_type_register);
223
224 /* Unregister a set type. There's a small race with ip_set_create */
225 void
226 ip_set_type_unregister(struct ip_set_type *type)
227 {
228         ip_set_type_lock();
229         if (!find_set_type(type->name, type->family, type->revision_min)) {
230                 pr_warn("ip_set type %s, family %s with revision min %u not registered\n",
231                         type->name, family_name(type->family),
232                         type->revision_min);
233                 goto unlock;
234         }
235         list_del_rcu(&type->list);
236         pr_debug("type %s, family %s with revision min %u unregistered.\n",
237                  type->name, family_name(type->family), type->revision_min);
238 unlock:
239         ip_set_type_unlock();
240
241         synchronize_rcu();
242 }
243 EXPORT_SYMBOL_GPL(ip_set_type_unregister);
244
245 /* Utility functions */
246 void *
247 ip_set_alloc(size_t size)
248 {
249         void *members = NULL;
250
251         if (size < KMALLOC_MAX_SIZE)
252                 members = kzalloc(size, GFP_KERNEL | __GFP_NOWARN);
253
254         if (members) {
255                 pr_debug("%p: allocated with kmalloc\n", members);
256                 return members;
257         }
258
259         members = vzalloc(size);
260         if (!members)
261                 return NULL;
262         pr_debug("%p: allocated with vmalloc\n", members);
263
264         return members;
265 }
266 EXPORT_SYMBOL_GPL(ip_set_alloc);
267
268 void
269 ip_set_free(void *members)
270 {
271         pr_debug("%p: free with %s\n", members,
272                  is_vmalloc_addr(members) ? "vfree" : "kfree");
273         kvfree(members);
274 }
275 EXPORT_SYMBOL_GPL(ip_set_free);
276
277 static inline bool
278 flag_nested(const struct nlattr *nla)
279 {
280         return nla->nla_type & NLA_F_NESTED;
281 }
282
283 static const struct nla_policy ipaddr_policy[IPSET_ATTR_IPADDR_MAX + 1] = {
284         [IPSET_ATTR_IPADDR_IPV4]        = { .type = NLA_U32 },
285         [IPSET_ATTR_IPADDR_IPV6]        = { .type = NLA_BINARY,
286                                             .len = sizeof(struct in6_addr) },
287 };
288
289 int
290 ip_set_get_ipaddr4(struct nlattr *nla,  __be32 *ipaddr)
291 {
292         struct nlattr *tb[IPSET_ATTR_IPADDR_MAX+1];
293
294         if (unlikely(!flag_nested(nla)))
295                 return -IPSET_ERR_PROTOCOL;
296         if (nla_parse_nested(tb, IPSET_ATTR_IPADDR_MAX, nla, ipaddr_policy))
297                 return -IPSET_ERR_PROTOCOL;
298         if (unlikely(!ip_set_attr_netorder(tb, IPSET_ATTR_IPADDR_IPV4)))
299                 return -IPSET_ERR_PROTOCOL;
300
301         *ipaddr = nla_get_be32(tb[IPSET_ATTR_IPADDR_IPV4]);
302         return 0;
303 }
304 EXPORT_SYMBOL_GPL(ip_set_get_ipaddr4);
305
306 int
307 ip_set_get_ipaddr6(struct nlattr *nla, union nf_inet_addr *ipaddr)
308 {
309         struct nlattr *tb[IPSET_ATTR_IPADDR_MAX+1];
310
311         if (unlikely(!flag_nested(nla)))
312                 return -IPSET_ERR_PROTOCOL;
313
314         if (nla_parse_nested(tb, IPSET_ATTR_IPADDR_MAX, nla, ipaddr_policy))
315                 return -IPSET_ERR_PROTOCOL;
316         if (unlikely(!ip_set_attr_netorder(tb, IPSET_ATTR_IPADDR_IPV6)))
317                 return -IPSET_ERR_PROTOCOL;
318
319         memcpy(ipaddr, nla_data(tb[IPSET_ATTR_IPADDR_IPV6]),
320                 sizeof(struct in6_addr));
321         return 0;
322 }
323 EXPORT_SYMBOL_GPL(ip_set_get_ipaddr6);
324
325 typedef void (*destroyer)(void *);
326 /* ipset data extension types, in size order */
327
328 const struct ip_set_ext_type ip_set_extensions[] = {
329         [IPSET_EXT_ID_COUNTER] = {
330                 .type   = IPSET_EXT_COUNTER,
331                 .flag   = IPSET_FLAG_WITH_COUNTERS,
332                 .len    = sizeof(struct ip_set_counter),
333                 .align  = __alignof__(struct ip_set_counter),
334         },
335         [IPSET_EXT_ID_TIMEOUT] = {
336                 .type   = IPSET_EXT_TIMEOUT,
337                 .len    = sizeof(unsigned long),
338                 .align  = __alignof__(unsigned long),
339         },
340         [IPSET_EXT_ID_SKBINFO] = {
341                 .type   = IPSET_EXT_SKBINFO,
342                 .flag   = IPSET_FLAG_WITH_SKBINFO,
343                 .len    = sizeof(struct ip_set_skbinfo),
344                 .align  = __alignof__(struct ip_set_skbinfo),
345         },
346         [IPSET_EXT_ID_COMMENT] = {
347                 .type    = IPSET_EXT_COMMENT | IPSET_EXT_DESTROY,
348                 .flag    = IPSET_FLAG_WITH_COMMENT,
349                 .len     = sizeof(struct ip_set_comment),
350                 .align   = __alignof__(struct ip_set_comment),
351                 .destroy = (destroyer) ip_set_comment_free,
352         },
353 };
354 EXPORT_SYMBOL_GPL(ip_set_extensions);
355
356 static inline bool
357 add_extension(enum ip_set_ext_id id, u32 flags, struct nlattr *tb[])
358 {
359         return ip_set_extensions[id].flag ?
360                 (flags & ip_set_extensions[id].flag) :
361                 !!tb[IPSET_ATTR_TIMEOUT];
362 }
363
364 size_t
365 ip_set_elem_len(struct ip_set *set, struct nlattr *tb[], size_t len)
366 {
367         enum ip_set_ext_id id;
368         size_t offset = len;
369         u32 cadt_flags = 0;
370
371         if (tb[IPSET_ATTR_CADT_FLAGS])
372                 cadt_flags = ip_set_get_h32(tb[IPSET_ATTR_CADT_FLAGS]);
373         if (cadt_flags & IPSET_FLAG_WITH_FORCEADD)
374                 set->flags |= IPSET_CREATE_FLAG_FORCEADD;
375         for (id = 0; id < IPSET_EXT_ID_MAX; id++) {
376                 if (!add_extension(id, cadt_flags, tb))
377                         continue;
378                 offset = ALIGN(offset, ip_set_extensions[id].align);
379                 set->offset[id] = offset;
380                 set->extensions |= ip_set_extensions[id].type;
381                 offset += ip_set_extensions[id].len;
382         }
383         return offset;
384 }
385 EXPORT_SYMBOL_GPL(ip_set_elem_len);
386
387 int
388 ip_set_get_extensions(struct ip_set *set, struct nlattr *tb[],
389                       struct ip_set_ext *ext)
390 {
391         u64 fullmark;
392         if (tb[IPSET_ATTR_TIMEOUT]) {
393                 if (!SET_WITH_TIMEOUT(set))
394                         return -IPSET_ERR_TIMEOUT;
395                 ext->timeout = ip_set_timeout_uget(tb[IPSET_ATTR_TIMEOUT]);
396         }
397         if (tb[IPSET_ATTR_BYTES] || tb[IPSET_ATTR_PACKETS]) {
398                 if (!SET_WITH_COUNTER(set))
399                         return -IPSET_ERR_COUNTER;
400                 if (tb[IPSET_ATTR_BYTES])
401                         ext->bytes = be64_to_cpu(nla_get_be64(
402                                                  tb[IPSET_ATTR_BYTES]));
403                 if (tb[IPSET_ATTR_PACKETS])
404                         ext->packets = be64_to_cpu(nla_get_be64(
405                                                    tb[IPSET_ATTR_PACKETS]));
406         }
407         if (tb[IPSET_ATTR_COMMENT]) {
408                 if (!SET_WITH_COMMENT(set))
409                         return -IPSET_ERR_COMMENT;
410                 ext->comment = ip_set_comment_uget(tb[IPSET_ATTR_COMMENT]);
411         }
412         if (tb[IPSET_ATTR_SKBMARK]) {
413                 if (!SET_WITH_SKBINFO(set))
414                         return -IPSET_ERR_SKBINFO;
415                 fullmark = be64_to_cpu(nla_get_be64(tb[IPSET_ATTR_SKBMARK]));
416                 ext->skbmark = fullmark >> 32;
417                 ext->skbmarkmask = fullmark & 0xffffffff;
418         }
419         if (tb[IPSET_ATTR_SKBPRIO]) {
420                 if (!SET_WITH_SKBINFO(set))
421                         return -IPSET_ERR_SKBINFO;
422                 ext->skbprio = be32_to_cpu(nla_get_be32(
423                                             tb[IPSET_ATTR_SKBPRIO]));
424         }
425         if (tb[IPSET_ATTR_SKBQUEUE]) {
426                 if (!SET_WITH_SKBINFO(set))
427                         return -IPSET_ERR_SKBINFO;
428                 ext->skbqueue = be16_to_cpu(nla_get_be16(
429                                             tb[IPSET_ATTR_SKBQUEUE]));
430         }
431         return 0;
432 }
433 EXPORT_SYMBOL_GPL(ip_set_get_extensions);
434
435 int
436 ip_set_put_extensions(struct sk_buff *skb, const struct ip_set *set,
437                       const void *e, bool active)
438 {
439         if (SET_WITH_TIMEOUT(set)) {
440                 unsigned long *timeout = ext_timeout(e, set);
441
442                 if (nla_put_net32(skb, IPSET_ATTR_TIMEOUT,
443                         htonl(active ? ip_set_timeout_get(timeout)
444                                 : *timeout)))
445                         return -EMSGSIZE;
446         }
447         if (SET_WITH_COUNTER(set) &&
448             ip_set_put_counter(skb, ext_counter(e, set)))
449                 return -EMSGSIZE;
450         if (SET_WITH_COMMENT(set) &&
451             ip_set_put_comment(skb, ext_comment(e, set)))
452                 return -EMSGSIZE;
453         if (SET_WITH_SKBINFO(set) &&
454             ip_set_put_skbinfo(skb, ext_skbinfo(e, set)))
455                 return -EMSGSIZE;
456         return 0;
457 }
458 EXPORT_SYMBOL_GPL(ip_set_put_extensions);
459
460 /*
461  * Creating/destroying/renaming/swapping affect the existence and
462  * the properties of a set. All of these can be executed from userspace
463  * only and serialized by the nfnl mutex indirectly from nfnetlink.
464  *
465  * Sets are identified by their index in ip_set_list and the index
466  * is used by the external references (set/SET netfilter modules).
467  *
468  * The set behind an index may change by swapping only, from userspace.
469  */
470
471 static inline void
472 __ip_set_get(struct ip_set *set)
473 {
474         write_lock_bh(&ip_set_ref_lock);
475         set->ref++;
476         write_unlock_bh(&ip_set_ref_lock);
477 }
478
479 static inline void
480 __ip_set_put(struct ip_set *set)
481 {
482         write_lock_bh(&ip_set_ref_lock);
483         BUG_ON(set->ref == 0);
484         set->ref--;
485         write_unlock_bh(&ip_set_ref_lock);
486 }
487
488 /*
489  * Add, del and test set entries from kernel.
490  *
491  * The set behind the index must exist and must be referenced
492  * so it can't be destroyed (or changed) under our foot.
493  */
494
495 static inline struct ip_set *
496 ip_set_rcu_get(struct net *net, ip_set_id_t index)
497 {
498         struct ip_set *set;
499         struct ip_set_net *inst = ip_set_pernet(net);
500
501         rcu_read_lock();
502         /* ip_set_list itself needs to be protected */
503         set = rcu_dereference(inst->ip_set_list)[index];
504         rcu_read_unlock();
505
506         return set;
507 }
508
509 int
510 ip_set_test(ip_set_id_t index, const struct sk_buff *skb,
511             const struct xt_action_param *par, struct ip_set_adt_opt *opt)
512 {
513         struct ip_set *set = ip_set_rcu_get(
514                         dev_net(par->in ? par->in : par->out), index);
515         int ret = 0;
516
517         BUG_ON(set == NULL);
518         pr_debug("set %s, index %u\n", set->name, index);
519
520         if (opt->dim < set->type->dimension ||
521             !(opt->family == set->family || set->family == NFPROTO_UNSPEC))
522                 return 0;
523
524         read_lock_bh(&set->lock);
525         ret = set->variant->kadt(set, skb, par, IPSET_TEST, opt);
526         read_unlock_bh(&set->lock);
527
528         if (ret == -EAGAIN) {
529                 /* Type requests element to be completed */
530                 pr_debug("element must be completed, ADD is triggered\n");
531                 write_lock_bh(&set->lock);
532                 set->variant->kadt(set, skb, par, IPSET_ADD, opt);
533                 write_unlock_bh(&set->lock);
534                 ret = 1;
535         } else {
536                 /* --return-nomatch: invert matched element */
537                 if ((opt->cmdflags & IPSET_FLAG_RETURN_NOMATCH) &&
538                     (set->type->features & IPSET_TYPE_NOMATCH) &&
539                     (ret > 0 || ret == -ENOTEMPTY))
540                         ret = -ret;
541         }
542
543         /* Convert error codes to nomatch */
544         return (ret < 0 ? 0 : ret);
545 }
546 EXPORT_SYMBOL_GPL(ip_set_test);
547
548 int
549 ip_set_add(ip_set_id_t index, const struct sk_buff *skb,
550            const struct xt_action_param *par, struct ip_set_adt_opt *opt)
551 {
552         struct ip_set *set = ip_set_rcu_get(
553                         dev_net(par->in ? par->in : par->out), index);
554         int ret;
555
556         BUG_ON(set == NULL);
557         pr_debug("set %s, index %u\n", set->name, index);
558
559         if (opt->dim < set->type->dimension ||
560             !(opt->family == set->family || set->family == NFPROTO_UNSPEC))
561                 return -IPSET_ERR_TYPE_MISMATCH;
562
563         write_lock_bh(&set->lock);
564         ret = set->variant->kadt(set, skb, par, IPSET_ADD, opt);
565         write_unlock_bh(&set->lock);
566
567         return ret;
568 }
569 EXPORT_SYMBOL_GPL(ip_set_add);
570
571 int
572 ip_set_del(ip_set_id_t index, const struct sk_buff *skb,
573            const struct xt_action_param *par, struct ip_set_adt_opt *opt)
574 {
575         struct ip_set *set = ip_set_rcu_get(
576                         dev_net(par->in ? par->in : par->out), index);
577         int ret = 0;
578
579         BUG_ON(set == NULL);
580         pr_debug("set %s, index %u\n", set->name, index);
581
582         if (opt->dim < set->type->dimension ||
583             !(opt->family == set->family || set->family == NFPROTO_UNSPEC))
584                 return -IPSET_ERR_TYPE_MISMATCH;
585
586         write_lock_bh(&set->lock);
587         ret = set->variant->kadt(set, skb, par, IPSET_DEL, opt);
588         write_unlock_bh(&set->lock);
589
590         return ret;
591 }
592 EXPORT_SYMBOL_GPL(ip_set_del);
593
594 /*
595  * Find set by name, reference it once. The reference makes sure the
596  * thing pointed to, does not go away under our feet.
597  *
598  */
599 ip_set_id_t
600 ip_set_get_byname(struct net *net, const char *name, struct ip_set **set)
601 {
602         ip_set_id_t i, index = IPSET_INVALID_ID;
603         struct ip_set *s;
604         struct ip_set_net *inst = ip_set_pernet(net);
605
606         rcu_read_lock();
607         for (i = 0; i < inst->ip_set_max; i++) {
608                 s = rcu_dereference(inst->ip_set_list)[i];
609                 if (s != NULL && STRNCMP(s->name, name)) {
610                         __ip_set_get(s);
611                         index = i;
612                         *set = s;
613                         break;
614                 }
615         }
616         rcu_read_unlock();
617
618         return index;
619 }
620 EXPORT_SYMBOL_GPL(ip_set_get_byname);
621
622 /*
623  * If the given set pointer points to a valid set, decrement
624  * reference count by 1. The caller shall not assume the index
625  * to be valid, after calling this function.
626  *
627  */
628
629 static inline void
630 __ip_set_put_byindex(struct ip_set_net *inst, ip_set_id_t index)
631 {
632         struct ip_set *set;
633
634         rcu_read_lock();
635         set = rcu_dereference(inst->ip_set_list)[index];
636         if (set != NULL)
637                 __ip_set_put(set);
638         rcu_read_unlock();
639 }
640
641 void
642 ip_set_put_byindex(struct net *net, ip_set_id_t index)
643 {
644         struct ip_set_net *inst = ip_set_pernet(net);
645
646         __ip_set_put_byindex(inst, index);
647 }
648 EXPORT_SYMBOL_GPL(ip_set_put_byindex);
649
650 /*
651  * Get the name of a set behind a set index.
652  * We assume the set is referenced, so it does exist and
653  * can't be destroyed. The set cannot be renamed due to
654  * the referencing either.
655  *
656  */
657 const char *
658 ip_set_name_byindex(struct net *net, ip_set_id_t index)
659 {
660         const struct ip_set *set = ip_set_rcu_get(net, index);
661
662         BUG_ON(set == NULL);
663         BUG_ON(set->ref == 0);
664
665         /* Referenced, so it's safe */
666         return set->name;
667 }
668 EXPORT_SYMBOL_GPL(ip_set_name_byindex);
669
670 /*
671  * Routines to call by external subsystems, which do not
672  * call nfnl_lock for us.
673  */
674
675 /*
676  * Find set by index, reference it once. The reference makes sure the
677  * thing pointed to, does not go away under our feet.
678  *
679  * The nfnl mutex is used in the function.
680  */
681 ip_set_id_t
682 ip_set_nfnl_get_byindex(struct net *net, ip_set_id_t index)
683 {
684         struct ip_set *set;
685         struct ip_set_net *inst = ip_set_pernet(net);
686
687         if (index >= inst->ip_set_max)
688                 return IPSET_INVALID_ID;
689
690         nfnl_lock(NFNL_SUBSYS_IPSET);
691         set = ip_set(inst, index);
692         if (set)
693                 __ip_set_get(set);
694         else
695                 index = IPSET_INVALID_ID;
696         nfnl_unlock(NFNL_SUBSYS_IPSET);
697
698         return index;
699 }
700 EXPORT_SYMBOL_GPL(ip_set_nfnl_get_byindex);
701
702 /*
703  * If the given set pointer points to a valid set, decrement
704  * reference count by 1. The caller shall not assume the index
705  * to be valid, after calling this function.
706  *
707  * The nfnl mutex is used in the function.
708  */
709 void
710 ip_set_nfnl_put(struct net *net, ip_set_id_t index)
711 {
712         struct ip_set *set;
713         struct ip_set_net *inst = ip_set_pernet(net);
714
715         nfnl_lock(NFNL_SUBSYS_IPSET);
716         if (!inst->is_deleted) { /* already deleted from ip_set_net_exit() */
717                 set = ip_set(inst, index);
718                 if (set != NULL)
719                         __ip_set_put(set);
720         }
721         nfnl_unlock(NFNL_SUBSYS_IPSET);
722 }
723 EXPORT_SYMBOL_GPL(ip_set_nfnl_put);
724
725 /*
726  * Communication protocol with userspace over netlink.
727  *
728  * The commands are serialized by the nfnl mutex.
729  */
730
731 static inline bool
732 protocol_failed(const struct nlattr * const tb[])
733 {
734         return !tb[IPSET_ATTR_PROTOCOL] ||
735                nla_get_u8(tb[IPSET_ATTR_PROTOCOL]) != IPSET_PROTOCOL;
736 }
737
738 static inline u32
739 flag_exist(const struct nlmsghdr *nlh)
740 {
741         return nlh->nlmsg_flags & NLM_F_EXCL ? 0 : IPSET_FLAG_EXIST;
742 }
743
744 static struct nlmsghdr *
745 start_msg(struct sk_buff *skb, u32 portid, u32 seq, unsigned int flags,
746           enum ipset_cmd cmd)
747 {
748         struct nlmsghdr *nlh;
749         struct nfgenmsg *nfmsg;
750
751         nlh = nlmsg_put(skb, portid, seq, cmd | (NFNL_SUBSYS_IPSET << 8),
752                         sizeof(*nfmsg), flags);
753         if (nlh == NULL)
754                 return NULL;
755
756         nfmsg = nlmsg_data(nlh);
757         nfmsg->nfgen_family = NFPROTO_IPV4;
758         nfmsg->version = NFNETLINK_V0;
759         nfmsg->res_id = 0;
760
761         return nlh;
762 }
763
764 /* Create a set */
765
766 static const struct nla_policy ip_set_create_policy[IPSET_ATTR_CMD_MAX + 1] = {
767         [IPSET_ATTR_PROTOCOL]   = { .type = NLA_U8 },
768         [IPSET_ATTR_SETNAME]    = { .type = NLA_NUL_STRING,
769                                     .len = IPSET_MAXNAMELEN - 1 },
770         [IPSET_ATTR_TYPENAME]   = { .type = NLA_NUL_STRING,
771                                     .len = IPSET_MAXNAMELEN - 1},
772         [IPSET_ATTR_REVISION]   = { .type = NLA_U8 },
773         [IPSET_ATTR_FAMILY]     = { .type = NLA_U8 },
774         [IPSET_ATTR_DATA]       = { .type = NLA_NESTED },
775 };
776
777 static struct ip_set *
778 find_set_and_id(struct ip_set_net *inst, const char *name, ip_set_id_t *id)
779 {
780         struct ip_set *set = NULL;
781         ip_set_id_t i;
782
783         *id = IPSET_INVALID_ID;
784         for (i = 0; i < inst->ip_set_max; i++) {
785                 set = ip_set(inst, i);
786                 if (set != NULL && STRNCMP(set->name, name)) {
787                         *id = i;
788                         break;
789                 }
790         }
791         return (*id == IPSET_INVALID_ID ? NULL : set);
792 }
793
794 static inline struct ip_set *
795 find_set(struct ip_set_net *inst, const char *name)
796 {
797         ip_set_id_t id;
798
799         return find_set_and_id(inst, name, &id);
800 }
801
802 static int
803 find_free_id(struct ip_set_net *inst, const char *name, ip_set_id_t *index,
804              struct ip_set **set)
805 {
806         struct ip_set *s;
807         ip_set_id_t i;
808
809         *index = IPSET_INVALID_ID;
810         for (i = 0;  i < inst->ip_set_max; i++) {
811                 s = ip_set(inst, i);
812                 if (s == NULL) {
813                         if (*index == IPSET_INVALID_ID)
814                                 *index = i;
815                 } else if (STRNCMP(name, s->name)) {
816                         /* Name clash */
817                         *set = s;
818                         return -EEXIST;
819                 }
820         }
821         if (*index == IPSET_INVALID_ID)
822                 /* No free slot remained */
823                 return -IPSET_ERR_MAX_SETS;
824         return 0;
825 }
826
827 static int
828 ip_set_none(struct sock *ctnl, struct sk_buff *skb,
829             const struct nlmsghdr *nlh,
830             const struct nlattr * const attr[])
831 {
832         return -EOPNOTSUPP;
833 }
834
835 static int
836 ip_set_create(struct sock *ctnl, struct sk_buff *skb,
837               const struct nlmsghdr *nlh,
838               const struct nlattr * const attr[])
839 {
840         struct net *net = sock_net(ctnl);
841         struct ip_set_net *inst = ip_set_pernet(net);
842         struct ip_set *set, *clash = NULL;
843         ip_set_id_t index = IPSET_INVALID_ID;
844         struct nlattr *tb[IPSET_ATTR_CREATE_MAX+1] = {};
845         const char *name, *typename;
846         u8 family, revision;
847         u32 flags = flag_exist(nlh);
848         int ret = 0;
849
850         if (unlikely(protocol_failed(attr) ||
851                      attr[IPSET_ATTR_SETNAME] == NULL ||
852                      attr[IPSET_ATTR_TYPENAME] == NULL ||
853                      attr[IPSET_ATTR_REVISION] == NULL ||
854                      attr[IPSET_ATTR_FAMILY] == NULL ||
855                      (attr[IPSET_ATTR_DATA] != NULL &&
856                       !flag_nested(attr[IPSET_ATTR_DATA]))))
857                 return -IPSET_ERR_PROTOCOL;
858
859         name = nla_data(attr[IPSET_ATTR_SETNAME]);
860         typename = nla_data(attr[IPSET_ATTR_TYPENAME]);
861         family = nla_get_u8(attr[IPSET_ATTR_FAMILY]);
862         revision = nla_get_u8(attr[IPSET_ATTR_REVISION]);
863         pr_debug("setname: %s, typename: %s, family: %s, revision: %u\n",
864                  name, typename, family_name(family), revision);
865
866         /*
867          * First, and without any locks, allocate and initialize
868          * a normal base set structure.
869          */
870         set = kzalloc(sizeof(struct ip_set), GFP_KERNEL);
871         if (!set)
872                 return -ENOMEM;
873         rwlock_init(&set->lock);
874         strlcpy(set->name, name, IPSET_MAXNAMELEN);
875         set->family = family;
876         set->revision = revision;
877
878         /*
879          * Next, check that we know the type, and take
880          * a reference on the type, to make sure it stays available
881          * while constructing our new set.
882          *
883          * After referencing the type, we try to create the type
884          * specific part of the set without holding any locks.
885          */
886         ret = find_set_type_get(typename, family, revision, &(set->type));
887         if (ret)
888                 goto out;
889
890         /*
891          * Without holding any locks, create private part.
892          */
893         if (attr[IPSET_ATTR_DATA] &&
894             nla_parse_nested(tb, IPSET_ATTR_CREATE_MAX, attr[IPSET_ATTR_DATA],
895                              set->type->create_policy)) {
896                 ret = -IPSET_ERR_PROTOCOL;
897                 goto put_out;
898         }
899
900         ret = set->type->create(net, set, tb, flags);
901         if (ret != 0)
902                 goto put_out;
903
904         /* BTW, ret==0 here. */
905
906         /*
907          * Here, we have a valid, constructed set and we are protected
908          * by the nfnl mutex. Find the first free index in ip_set_list
909          * and check clashing.
910          */
911         ret = find_free_id(inst, set->name, &index, &clash);
912         if (ret == -EEXIST) {
913                 /* If this is the same set and requested, ignore error */
914                 if ((flags & IPSET_FLAG_EXIST) &&
915                     STRNCMP(set->type->name, clash->type->name) &&
916                     set->type->family == clash->type->family &&
917                     set->type->revision_min == clash->type->revision_min &&
918                     set->type->revision_max == clash->type->revision_max &&
919                     set->variant->same_set(set, clash))
920                         ret = 0;
921                 goto cleanup;
922         } else if (ret == -IPSET_ERR_MAX_SETS) {
923                 struct ip_set **list, **tmp;
924                 ip_set_id_t i = inst->ip_set_max + IP_SET_INC;
925
926                 if (i < inst->ip_set_max || i == IPSET_INVALID_ID)
927                         /* Wraparound */
928                         goto cleanup;
929
930                 list = kzalloc(sizeof(struct ip_set *) * i, GFP_KERNEL);
931                 if (!list)
932                         goto cleanup;
933                 /* nfnl mutex is held, both lists are valid */
934                 tmp = ip_set_dereference(inst->ip_set_list);
935                 memcpy(list, tmp, sizeof(struct ip_set *) * inst->ip_set_max);
936                 rcu_assign_pointer(inst->ip_set_list, list);
937                 /* Make sure all current packets have passed through */
938                 synchronize_net();
939                 /* Use new list */
940                 index = inst->ip_set_max;
941                 inst->ip_set_max = i;
942                 kfree(tmp);
943                 ret = 0;
944         } else if (ret)
945                 goto cleanup;
946
947         /*
948          * Finally! Add our shiny new set to the list, and be done.
949          */
950         pr_debug("create: '%s' created with index %u!\n", set->name, index);
951         ip_set(inst, index) = set;
952
953         return ret;
954
955 cleanup:
956         set->variant->destroy(set);
957 put_out:
958         module_put(set->type->me);
959 out:
960         kfree(set);
961         return ret;
962 }
963
964 /* Destroy sets */
965
966 static const struct nla_policy
967 ip_set_setname_policy[IPSET_ATTR_CMD_MAX + 1] = {
968         [IPSET_ATTR_PROTOCOL]   = { .type = NLA_U8 },
969         [IPSET_ATTR_SETNAME]    = { .type = NLA_NUL_STRING,
970                                     .len = IPSET_MAXNAMELEN - 1 },
971 };
972
973 static void
974 ip_set_destroy_set(struct ip_set_net *inst, ip_set_id_t index)
975 {
976         struct ip_set *set = ip_set(inst, index);
977
978         pr_debug("set: %s\n",  set->name);
979         ip_set(inst, index) = NULL;
980
981         /* Must call it without holding any lock */
982         set->variant->destroy(set);
983         module_put(set->type->me);
984         kfree(set);
985 }
986
987 static int
988 ip_set_destroy(struct sock *ctnl, struct sk_buff *skb,
989                const struct nlmsghdr *nlh,
990                const struct nlattr * const attr[])
991 {
992         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
993         struct ip_set *s;
994         ip_set_id_t i;
995         int ret = 0;
996
997         if (unlikely(protocol_failed(attr)))
998                 return -IPSET_ERR_PROTOCOL;
999
1000         /* Commands are serialized and references are
1001          * protected by the ip_set_ref_lock.
1002          * External systems (i.e. xt_set) must call
1003          * ip_set_put|get_nfnl_* functions, that way we
1004          * can safely check references here.
1005          *
1006          * list:set timer can only decrement the reference
1007          * counter, so if it's already zero, we can proceed
1008          * without holding the lock.
1009          */
1010         read_lock_bh(&ip_set_ref_lock);
1011         if (!attr[IPSET_ATTR_SETNAME]) {
1012                 for (i = 0; i < inst->ip_set_max; i++) {
1013                         s = ip_set(inst, i);
1014                         if (s != NULL && s->ref) {
1015                                 ret = -IPSET_ERR_BUSY;
1016                                 goto out;
1017                         }
1018                 }
1019                 read_unlock_bh(&ip_set_ref_lock);
1020                 for (i = 0; i < inst->ip_set_max; i++) {
1021                         s = ip_set(inst, i);
1022                         if (s != NULL)
1023                                 ip_set_destroy_set(inst, i);
1024                 }
1025         } else {
1026                 s = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME]),
1027                                     &i);
1028                 if (s == NULL) {
1029                         ret = -ENOENT;
1030                         goto out;
1031                 } else if (s->ref) {
1032                         ret = -IPSET_ERR_BUSY;
1033                         goto out;
1034                 }
1035                 read_unlock_bh(&ip_set_ref_lock);
1036
1037                 ip_set_destroy_set(inst, i);
1038         }
1039         return 0;
1040 out:
1041         read_unlock_bh(&ip_set_ref_lock);
1042         return ret;
1043 }
1044
1045 /* Flush sets */
1046
1047 static void
1048 ip_set_flush_set(struct ip_set *set)
1049 {
1050         pr_debug("set: %s\n",  set->name);
1051
1052         write_lock_bh(&set->lock);
1053         set->variant->flush(set);
1054         write_unlock_bh(&set->lock);
1055 }
1056
1057 static int
1058 ip_set_flush(struct sock *ctnl, struct sk_buff *skb,
1059              const struct nlmsghdr *nlh,
1060              const struct nlattr * const attr[])
1061 {
1062         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1063         struct ip_set *s;
1064         ip_set_id_t i;
1065
1066         if (unlikely(protocol_failed(attr)))
1067                 return -IPSET_ERR_PROTOCOL;
1068
1069         if (!attr[IPSET_ATTR_SETNAME]) {
1070                 for (i = 0; i < inst->ip_set_max; i++) {
1071                         s = ip_set(inst, i);
1072                         if (s != NULL)
1073                                 ip_set_flush_set(s);
1074                 }
1075         } else {
1076                 s = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1077                 if (s == NULL)
1078                         return -ENOENT;
1079
1080                 ip_set_flush_set(s);
1081         }
1082
1083         return 0;
1084 }
1085
1086 /* Rename a set */
1087
1088 static const struct nla_policy
1089 ip_set_setname2_policy[IPSET_ATTR_CMD_MAX + 1] = {
1090         [IPSET_ATTR_PROTOCOL]   = { .type = NLA_U8 },
1091         [IPSET_ATTR_SETNAME]    = { .type = NLA_NUL_STRING,
1092                                     .len = IPSET_MAXNAMELEN - 1 },
1093         [IPSET_ATTR_SETNAME2]   = { .type = NLA_NUL_STRING,
1094                                     .len = IPSET_MAXNAMELEN - 1 },
1095 };
1096
1097 static int
1098 ip_set_rename(struct sock *ctnl, struct sk_buff *skb,
1099               const struct nlmsghdr *nlh,
1100               const struct nlattr * const attr[])
1101 {
1102         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1103         struct ip_set *set, *s;
1104         const char *name2;
1105         ip_set_id_t i;
1106         int ret = 0;
1107
1108         if (unlikely(protocol_failed(attr) ||
1109                      attr[IPSET_ATTR_SETNAME] == NULL ||
1110                      attr[IPSET_ATTR_SETNAME2] == NULL))
1111                 return -IPSET_ERR_PROTOCOL;
1112
1113         set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1114         if (set == NULL)
1115                 return -ENOENT;
1116
1117         read_lock_bh(&ip_set_ref_lock);
1118         if (set->ref != 0) {
1119                 ret = -IPSET_ERR_REFERENCED;
1120                 goto out;
1121         }
1122
1123         name2 = nla_data(attr[IPSET_ATTR_SETNAME2]);
1124         for (i = 0; i < inst->ip_set_max; i++) {
1125                 s = ip_set(inst, i);
1126                 if (s != NULL && STRNCMP(s->name, name2)) {
1127                         ret = -IPSET_ERR_EXIST_SETNAME2;
1128                         goto out;
1129                 }
1130         }
1131         strncpy(set->name, name2, IPSET_MAXNAMELEN);
1132
1133 out:
1134         read_unlock_bh(&ip_set_ref_lock);
1135         return ret;
1136 }
1137
1138 /* Swap two sets so that name/index points to the other.
1139  * References and set names are also swapped.
1140  *
1141  * The commands are serialized by the nfnl mutex and references are
1142  * protected by the ip_set_ref_lock. The kernel interfaces
1143  * do not hold the mutex but the pointer settings are atomic
1144  * so the ip_set_list always contains valid pointers to the sets.
1145  */
1146
1147 static int
1148 ip_set_swap(struct sock *ctnl, struct sk_buff *skb,
1149             const struct nlmsghdr *nlh,
1150             const struct nlattr * const attr[])
1151 {
1152         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1153         struct ip_set *from, *to;
1154         ip_set_id_t from_id, to_id;
1155         char from_name[IPSET_MAXNAMELEN];
1156
1157         if (unlikely(protocol_failed(attr) ||
1158                      attr[IPSET_ATTR_SETNAME] == NULL ||
1159                      attr[IPSET_ATTR_SETNAME2] == NULL))
1160                 return -IPSET_ERR_PROTOCOL;
1161
1162         from = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME]),
1163                                &from_id);
1164         if (from == NULL)
1165                 return -ENOENT;
1166
1167         to = find_set_and_id(inst, nla_data(attr[IPSET_ATTR_SETNAME2]),
1168                              &to_id);
1169         if (to == NULL)
1170                 return -IPSET_ERR_EXIST_SETNAME2;
1171
1172         /* Features must not change.
1173          * Not an artificial restriction anymore, as we must prevent
1174          * possible loops created by swapping in setlist type of sets. */
1175         if (!(from->type->features == to->type->features &&
1176               from->family == to->family))
1177                 return -IPSET_ERR_TYPE_MISMATCH;
1178
1179         strncpy(from_name, from->name, IPSET_MAXNAMELEN);
1180         strncpy(from->name, to->name, IPSET_MAXNAMELEN);
1181         strncpy(to->name, from_name, IPSET_MAXNAMELEN);
1182
1183         write_lock_bh(&ip_set_ref_lock);
1184         swap(from->ref, to->ref);
1185         ip_set(inst, from_id) = to;
1186         ip_set(inst, to_id) = from;
1187         write_unlock_bh(&ip_set_ref_lock);
1188
1189         return 0;
1190 }
1191
1192 /* List/save set data */
1193
1194 #define DUMP_INIT       0
1195 #define DUMP_ALL        1
1196 #define DUMP_ONE        2
1197 #define DUMP_LAST       3
1198
1199 #define DUMP_TYPE(arg)          (((u32)(arg)) & 0x0000FFFF)
1200 #define DUMP_FLAGS(arg)         (((u32)(arg)) >> 16)
1201
1202 static int
1203 ip_set_dump_done(struct netlink_callback *cb)
1204 {
1205         struct ip_set_net *inst = (struct ip_set_net *)cb->args[IPSET_CB_NET];
1206         if (cb->args[IPSET_CB_ARG0]) {
1207                 pr_debug("release set %s\n",
1208                          ip_set(inst, cb->args[IPSET_CB_INDEX])->name);
1209                 __ip_set_put_byindex(inst,
1210                         (ip_set_id_t) cb->args[IPSET_CB_INDEX]);
1211         }
1212         return 0;
1213 }
1214
1215 static inline void
1216 dump_attrs(struct nlmsghdr *nlh)
1217 {
1218         const struct nlattr *attr;
1219         int rem;
1220
1221         pr_debug("dump nlmsg\n");
1222         nlmsg_for_each_attr(attr, nlh, sizeof(struct nfgenmsg), rem) {
1223                 pr_debug("type: %u, len %u\n", nla_type(attr), attr->nla_len);
1224         }
1225 }
1226
1227 static int
1228 dump_init(struct netlink_callback *cb, struct ip_set_net *inst)
1229 {
1230         struct nlmsghdr *nlh = nlmsg_hdr(cb->skb);
1231         int min_len = nlmsg_total_size(sizeof(struct nfgenmsg));
1232         struct nlattr *cda[IPSET_ATTR_CMD_MAX+1];
1233         struct nlattr *attr = (void *)nlh + min_len;
1234         u32 dump_type;
1235         ip_set_id_t index;
1236
1237         /* Second pass, so parser can't fail */
1238         nla_parse(cda, IPSET_ATTR_CMD_MAX,
1239                   attr, nlh->nlmsg_len - min_len, ip_set_setname_policy);
1240
1241         /* cb->args[IPSET_CB_NET]:      net namespace
1242          *         [IPSET_CB_DUMP]:     dump single set/all sets
1243          *         [IPSET_CB_INDEX]:    set index
1244          *         [IPSET_CB_ARG0]:     type specific
1245          */
1246
1247         if (cda[IPSET_ATTR_SETNAME]) {
1248                 struct ip_set *set;
1249
1250                 set = find_set_and_id(inst, nla_data(cda[IPSET_ATTR_SETNAME]),
1251                                       &index);
1252                 if (set == NULL)
1253                         return -ENOENT;
1254
1255                 dump_type = DUMP_ONE;
1256                 cb->args[IPSET_CB_INDEX] = index;
1257         } else
1258                 dump_type = DUMP_ALL;
1259
1260         if (cda[IPSET_ATTR_FLAGS]) {
1261                 u32 f = ip_set_get_h32(cda[IPSET_ATTR_FLAGS]);
1262                 dump_type |= (f << 16);
1263         }
1264         cb->args[IPSET_CB_NET] = (unsigned long)inst;
1265         cb->args[IPSET_CB_DUMP] = dump_type;
1266
1267         return 0;
1268 }
1269
1270 static int
1271 ip_set_dump_start(struct sk_buff *skb, struct netlink_callback *cb)
1272 {
1273         ip_set_id_t index = IPSET_INVALID_ID, max;
1274         struct ip_set *set = NULL;
1275         struct nlmsghdr *nlh = NULL;
1276         unsigned int flags = NETLINK_CB(cb->skb).portid ? NLM_F_MULTI : 0;
1277         struct ip_set_net *inst = ip_set_pernet(sock_net(skb->sk));
1278         u32 dump_type, dump_flags;
1279         int ret = 0;
1280
1281         if (!cb->args[IPSET_CB_DUMP]) {
1282                 ret = dump_init(cb, inst);
1283                 if (ret < 0) {
1284                         nlh = nlmsg_hdr(cb->skb);
1285                         /* We have to create and send the error message
1286                          * manually :-( */
1287                         if (nlh->nlmsg_flags & NLM_F_ACK)
1288                                 netlink_ack(cb->skb, nlh, ret);
1289                         return ret;
1290                 }
1291         }
1292
1293         if (cb->args[IPSET_CB_INDEX] >= inst->ip_set_max)
1294                 goto out;
1295
1296         dump_type = DUMP_TYPE(cb->args[IPSET_CB_DUMP]);
1297         dump_flags = DUMP_FLAGS(cb->args[IPSET_CB_DUMP]);
1298         max = dump_type == DUMP_ONE ? cb->args[IPSET_CB_INDEX] + 1
1299                                     : inst->ip_set_max;
1300 dump_last:
1301         pr_debug("dump type, flag: %u %u index: %ld\n",
1302                  dump_type, dump_flags, cb->args[IPSET_CB_INDEX]);
1303         for (; cb->args[IPSET_CB_INDEX] < max; cb->args[IPSET_CB_INDEX]++) {
1304                 index = (ip_set_id_t) cb->args[IPSET_CB_INDEX];
1305                 set = ip_set(inst, index);
1306                 if (set == NULL) {
1307                         if (dump_type == DUMP_ONE) {
1308                                 ret = -ENOENT;
1309                                 goto out;
1310                         }
1311                         continue;
1312                 }
1313                 /* When dumping all sets, we must dump "sorted"
1314                  * so that lists (unions of sets) are dumped last.
1315                  */
1316                 if (dump_type != DUMP_ONE &&
1317                     ((dump_type == DUMP_ALL) ==
1318                      !!(set->type->features & IPSET_DUMP_LAST)))
1319                         continue;
1320                 pr_debug("List set: %s\n", set->name);
1321                 if (!cb->args[IPSET_CB_ARG0]) {
1322                         /* Start listing: make sure set won't be destroyed */
1323                         pr_debug("reference set\n");
1324                         __ip_set_get(set);
1325                 }
1326                 nlh = start_msg(skb, NETLINK_CB(cb->skb).portid,
1327                                 cb->nlh->nlmsg_seq, flags,
1328                                 IPSET_CMD_LIST);
1329                 if (!nlh) {
1330                         ret = -EMSGSIZE;
1331                         goto release_refcount;
1332                 }
1333                 if (nla_put_u8(skb, IPSET_ATTR_PROTOCOL, IPSET_PROTOCOL) ||
1334                     nla_put_string(skb, IPSET_ATTR_SETNAME, set->name))
1335                         goto nla_put_failure;
1336                 if (dump_flags & IPSET_FLAG_LIST_SETNAME)
1337                         goto next_set;
1338                 switch (cb->args[IPSET_CB_ARG0]) {
1339                 case 0:
1340                         /* Core header data */
1341                         if (nla_put_string(skb, IPSET_ATTR_TYPENAME,
1342                                            set->type->name) ||
1343                             nla_put_u8(skb, IPSET_ATTR_FAMILY,
1344                                        set->family) ||
1345                             nla_put_u8(skb, IPSET_ATTR_REVISION,
1346                                        set->revision))
1347                                 goto nla_put_failure;
1348                         ret = set->variant->head(set, skb);
1349                         if (ret < 0)
1350                                 goto release_refcount;
1351                         if (dump_flags & IPSET_FLAG_LIST_HEADER)
1352                                 goto next_set;
1353                         /* Fall through and add elements */
1354                 default:
1355                         read_lock_bh(&set->lock);
1356                         ret = set->variant->list(set, skb, cb);
1357                         read_unlock_bh(&set->lock);
1358                         if (!cb->args[IPSET_CB_ARG0])
1359                                 /* Set is done, proceed with next one */
1360                                 goto next_set;
1361                         goto release_refcount;
1362                 }
1363         }
1364         /* If we dump all sets, continue with dumping last ones */
1365         if (dump_type == DUMP_ALL) {
1366                 dump_type = DUMP_LAST;
1367                 cb->args[IPSET_CB_DUMP] = dump_type | (dump_flags << 16);
1368                 cb->args[IPSET_CB_INDEX] = 0;
1369                 goto dump_last;
1370         }
1371         goto out;
1372
1373 nla_put_failure:
1374         ret = -EFAULT;
1375 next_set:
1376         if (dump_type == DUMP_ONE)
1377                 cb->args[IPSET_CB_INDEX] = IPSET_INVALID_ID;
1378         else
1379                 cb->args[IPSET_CB_INDEX]++;
1380 release_refcount:
1381         /* If there was an error or set is done, release set */
1382         if (ret || !cb->args[IPSET_CB_ARG0]) {
1383                 pr_debug("release set %s\n", ip_set(inst, index)->name);
1384                 __ip_set_put_byindex(inst, index);
1385                 cb->args[IPSET_CB_ARG0] = 0;
1386         }
1387 out:
1388         if (nlh) {
1389                 nlmsg_end(skb, nlh);
1390                 pr_debug("nlmsg_len: %u\n", nlh->nlmsg_len);
1391                 dump_attrs(nlh);
1392         }
1393
1394         return ret < 0 ? ret : skb->len;
1395 }
1396
1397 static int
1398 ip_set_dump(struct sock *ctnl, struct sk_buff *skb,
1399             const struct nlmsghdr *nlh,
1400             const struct nlattr * const attr[])
1401 {
1402         if (unlikely(protocol_failed(attr)))
1403                 return -IPSET_ERR_PROTOCOL;
1404
1405         {
1406                 struct netlink_dump_control c = {
1407                         .dump = ip_set_dump_start,
1408                         .done = ip_set_dump_done,
1409                 };
1410                 return netlink_dump_start(ctnl, skb, nlh, &c);
1411         }
1412 }
1413
1414 /* Add, del and test */
1415
1416 static const struct nla_policy ip_set_adt_policy[IPSET_ATTR_CMD_MAX + 1] = {
1417         [IPSET_ATTR_PROTOCOL]   = { .type = NLA_U8 },
1418         [IPSET_ATTR_SETNAME]    = { .type = NLA_NUL_STRING,
1419                                     .len = IPSET_MAXNAMELEN - 1 },
1420         [IPSET_ATTR_LINENO]     = { .type = NLA_U32 },
1421         [IPSET_ATTR_DATA]       = { .type = NLA_NESTED },
1422         [IPSET_ATTR_ADT]        = { .type = NLA_NESTED },
1423 };
1424
1425 static int
1426 call_ad(struct sock *ctnl, struct sk_buff *skb, struct ip_set *set,
1427         struct nlattr *tb[], enum ipset_adt adt,
1428         u32 flags, bool use_lineno)
1429 {
1430         int ret;
1431         u32 lineno = 0;
1432         bool eexist = flags & IPSET_FLAG_EXIST, retried = false;
1433
1434         do {
1435                 write_lock_bh(&set->lock);
1436                 ret = set->variant->uadt(set, tb, adt, &lineno, flags, retried);
1437                 write_unlock_bh(&set->lock);
1438                 retried = true;
1439         } while (ret == -EAGAIN &&
1440                  set->variant->resize &&
1441                  (ret = set->variant->resize(set, retried)) == 0);
1442
1443         if (!ret || (ret == -IPSET_ERR_EXIST && eexist))
1444                 return 0;
1445         if (lineno && use_lineno) {
1446                 /* Error in restore/batch mode: send back lineno */
1447                 struct nlmsghdr *rep, *nlh = nlmsg_hdr(skb);
1448                 struct sk_buff *skb2;
1449                 struct nlmsgerr *errmsg;
1450                 size_t payload = min(SIZE_MAX,
1451                                      sizeof(*errmsg) + nlmsg_len(nlh));
1452                 int min_len = nlmsg_total_size(sizeof(struct nfgenmsg));
1453                 struct nlattr *cda[IPSET_ATTR_CMD_MAX+1];
1454                 struct nlattr *cmdattr;
1455                 u32 *errline;
1456
1457                 skb2 = nlmsg_new(payload, GFP_KERNEL);
1458                 if (skb2 == NULL)
1459                         return -ENOMEM;
1460                 rep = __nlmsg_put(skb2, NETLINK_CB(skb).portid,
1461                                   nlh->nlmsg_seq, NLMSG_ERROR, payload, 0);
1462                 errmsg = nlmsg_data(rep);
1463                 errmsg->error = ret;
1464                 memcpy(&errmsg->msg, nlh, nlh->nlmsg_len);
1465                 cmdattr = (void *)&errmsg->msg + min_len;
1466
1467                 nla_parse(cda, IPSET_ATTR_CMD_MAX,
1468                           cmdattr, nlh->nlmsg_len - min_len,
1469                           ip_set_adt_policy);
1470
1471                 errline = nla_data(cda[IPSET_ATTR_LINENO]);
1472
1473                 *errline = lineno;
1474
1475                 netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
1476                 /* Signal netlink not to send its ACK/errmsg.  */
1477                 return -EINTR;
1478         }
1479
1480         return ret;
1481 }
1482
1483 static int
1484 ip_set_uadd(struct sock *ctnl, struct sk_buff *skb,
1485             const struct nlmsghdr *nlh,
1486             const struct nlattr * const attr[])
1487 {
1488         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1489         struct ip_set *set;
1490         struct nlattr *tb[IPSET_ATTR_ADT_MAX+1] = {};
1491         const struct nlattr *nla;
1492         u32 flags = flag_exist(nlh);
1493         bool use_lineno;
1494         int ret = 0;
1495
1496         if (unlikely(protocol_failed(attr) ||
1497                      attr[IPSET_ATTR_SETNAME] == NULL ||
1498                      !((attr[IPSET_ATTR_DATA] != NULL) ^
1499                        (attr[IPSET_ATTR_ADT] != NULL)) ||
1500                      (attr[IPSET_ATTR_DATA] != NULL &&
1501                       !flag_nested(attr[IPSET_ATTR_DATA])) ||
1502                      (attr[IPSET_ATTR_ADT] != NULL &&
1503                       (!flag_nested(attr[IPSET_ATTR_ADT]) ||
1504                        attr[IPSET_ATTR_LINENO] == NULL))))
1505                 return -IPSET_ERR_PROTOCOL;
1506
1507         set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1508         if (set == NULL)
1509                 return -ENOENT;
1510
1511         use_lineno = !!attr[IPSET_ATTR_LINENO];
1512         if (attr[IPSET_ATTR_DATA]) {
1513                 if (nla_parse_nested(tb, IPSET_ATTR_ADT_MAX,
1514                                      attr[IPSET_ATTR_DATA],
1515                                      set->type->adt_policy))
1516                         return -IPSET_ERR_PROTOCOL;
1517                 ret = call_ad(ctnl, skb, set, tb, IPSET_ADD, flags,
1518                               use_lineno);
1519         } else {
1520                 int nla_rem;
1521
1522                 nla_for_each_nested(nla, attr[IPSET_ATTR_ADT], nla_rem) {
1523                         memset(tb, 0, sizeof(tb));
1524                         if (nla_type(nla) != IPSET_ATTR_DATA ||
1525                             !flag_nested(nla) ||
1526                             nla_parse_nested(tb, IPSET_ATTR_ADT_MAX, nla,
1527                                              set->type->adt_policy))
1528                                 return -IPSET_ERR_PROTOCOL;
1529                         ret = call_ad(ctnl, skb, set, tb, IPSET_ADD,
1530                                       flags, use_lineno);
1531                         if (ret < 0)
1532                                 return ret;
1533                 }
1534         }
1535         return ret;
1536 }
1537
1538 static int
1539 ip_set_udel(struct sock *ctnl, struct sk_buff *skb,
1540             const struct nlmsghdr *nlh,
1541             const struct nlattr * const attr[])
1542 {
1543         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1544         struct ip_set *set;
1545         struct nlattr *tb[IPSET_ATTR_ADT_MAX+1] = {};
1546         const struct nlattr *nla;
1547         u32 flags = flag_exist(nlh);
1548         bool use_lineno;
1549         int ret = 0;
1550
1551         if (unlikely(protocol_failed(attr) ||
1552                      attr[IPSET_ATTR_SETNAME] == NULL ||
1553                      !((attr[IPSET_ATTR_DATA] != NULL) ^
1554                        (attr[IPSET_ATTR_ADT] != NULL)) ||
1555                      (attr[IPSET_ATTR_DATA] != NULL &&
1556                       !flag_nested(attr[IPSET_ATTR_DATA])) ||
1557                      (attr[IPSET_ATTR_ADT] != NULL &&
1558                       (!flag_nested(attr[IPSET_ATTR_ADT]) ||
1559                        attr[IPSET_ATTR_LINENO] == NULL))))
1560                 return -IPSET_ERR_PROTOCOL;
1561
1562         set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1563         if (set == NULL)
1564                 return -ENOENT;
1565
1566         use_lineno = !!attr[IPSET_ATTR_LINENO];
1567         if (attr[IPSET_ATTR_DATA]) {
1568                 if (nla_parse_nested(tb, IPSET_ATTR_ADT_MAX,
1569                                      attr[IPSET_ATTR_DATA],
1570                                      set->type->adt_policy))
1571                         return -IPSET_ERR_PROTOCOL;
1572                 ret = call_ad(ctnl, skb, set, tb, IPSET_DEL, flags,
1573                               use_lineno);
1574         } else {
1575                 int nla_rem;
1576
1577                 nla_for_each_nested(nla, attr[IPSET_ATTR_ADT], nla_rem) {
1578                         memset(tb, 0, sizeof(*tb));
1579                         if (nla_type(nla) != IPSET_ATTR_DATA ||
1580                             !flag_nested(nla) ||
1581                             nla_parse_nested(tb, IPSET_ATTR_ADT_MAX, nla,
1582                                              set->type->adt_policy))
1583                                 return -IPSET_ERR_PROTOCOL;
1584                         ret = call_ad(ctnl, skb, set, tb, IPSET_DEL,
1585                                       flags, use_lineno);
1586                         if (ret < 0)
1587                                 return ret;
1588                 }
1589         }
1590         return ret;
1591 }
1592
1593 static int
1594 ip_set_utest(struct sock *ctnl, struct sk_buff *skb,
1595              const struct nlmsghdr *nlh,
1596              const struct nlattr * const attr[])
1597 {
1598         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1599         struct ip_set *set;
1600         struct nlattr *tb[IPSET_ATTR_ADT_MAX+1] = {};
1601         int ret = 0;
1602
1603         if (unlikely(protocol_failed(attr) ||
1604                      attr[IPSET_ATTR_SETNAME] == NULL ||
1605                      attr[IPSET_ATTR_DATA] == NULL ||
1606                      !flag_nested(attr[IPSET_ATTR_DATA])))
1607                 return -IPSET_ERR_PROTOCOL;
1608
1609         set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1610         if (set == NULL)
1611                 return -ENOENT;
1612
1613         if (nla_parse_nested(tb, IPSET_ATTR_ADT_MAX, attr[IPSET_ATTR_DATA],
1614                              set->type->adt_policy))
1615                 return -IPSET_ERR_PROTOCOL;
1616
1617         read_lock_bh(&set->lock);
1618         ret = set->variant->uadt(set, tb, IPSET_TEST, NULL, 0, 0);
1619         read_unlock_bh(&set->lock);
1620         /* Userspace can't trigger element to be re-added */
1621         if (ret == -EAGAIN)
1622                 ret = 1;
1623
1624         return ret > 0 ? 0 : -IPSET_ERR_EXIST;
1625 }
1626
1627 /* Get headed data of a set */
1628
1629 static int
1630 ip_set_header(struct sock *ctnl, struct sk_buff *skb,
1631               const struct nlmsghdr *nlh,
1632               const struct nlattr * const attr[])
1633 {
1634         struct ip_set_net *inst = ip_set_pernet(sock_net(ctnl));
1635         const struct ip_set *set;
1636         struct sk_buff *skb2;
1637         struct nlmsghdr *nlh2;
1638         int ret = 0;
1639
1640         if (unlikely(protocol_failed(attr) ||
1641                      attr[IPSET_ATTR_SETNAME] == NULL))
1642                 return -IPSET_ERR_PROTOCOL;
1643
1644         set = find_set(inst, nla_data(attr[IPSET_ATTR_SETNAME]));
1645         if (set == NULL)
1646                 return -ENOENT;
1647
1648         skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1649         if (skb2 == NULL)
1650                 return -ENOMEM;
1651
1652         nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, nlh->nlmsg_seq, 0,
1653                          IPSET_CMD_HEADER);
1654         if (!nlh2)
1655                 goto nlmsg_failure;
1656         if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, IPSET_PROTOCOL) ||
1657             nla_put_string(skb2, IPSET_ATTR_SETNAME, set->name) ||
1658             nla_put_string(skb2, IPSET_ATTR_TYPENAME, set->type->name) ||
1659             nla_put_u8(skb2, IPSET_ATTR_FAMILY, set->family) ||
1660             nla_put_u8(skb2, IPSET_ATTR_REVISION, set->revision))
1661                 goto nla_put_failure;
1662         nlmsg_end(skb2, nlh2);
1663
1664         ret = netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
1665         if (ret < 0)
1666                 return ret;
1667
1668         return 0;
1669
1670 nla_put_failure:
1671         nlmsg_cancel(skb2, nlh2);
1672 nlmsg_failure:
1673         kfree_skb(skb2);
1674         return -EMSGSIZE;
1675 }
1676
1677 /* Get type data */
1678
1679 static const struct nla_policy ip_set_type_policy[IPSET_ATTR_CMD_MAX + 1] = {
1680         [IPSET_ATTR_PROTOCOL]   = { .type = NLA_U8 },
1681         [IPSET_ATTR_TYPENAME]   = { .type = NLA_NUL_STRING,
1682                                     .len = IPSET_MAXNAMELEN - 1 },
1683         [IPSET_ATTR_FAMILY]     = { .type = NLA_U8 },
1684 };
1685
1686 static int
1687 ip_set_type(struct sock *ctnl, struct sk_buff *skb,
1688             const struct nlmsghdr *nlh,
1689             const struct nlattr * const attr[])
1690 {
1691         struct sk_buff *skb2;
1692         struct nlmsghdr *nlh2;
1693         u8 family, min, max;
1694         const char *typename;
1695         int ret = 0;
1696
1697         if (unlikely(protocol_failed(attr) ||
1698                      attr[IPSET_ATTR_TYPENAME] == NULL ||
1699                      attr[IPSET_ATTR_FAMILY] == NULL))
1700                 return -IPSET_ERR_PROTOCOL;
1701
1702         family = nla_get_u8(attr[IPSET_ATTR_FAMILY]);
1703         typename = nla_data(attr[IPSET_ATTR_TYPENAME]);
1704         ret = find_set_type_minmax(typename, family, &min, &max);
1705         if (ret)
1706                 return ret;
1707
1708         skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1709         if (skb2 == NULL)
1710                 return -ENOMEM;
1711
1712         nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, nlh->nlmsg_seq, 0,
1713                          IPSET_CMD_TYPE);
1714         if (!nlh2)
1715                 goto nlmsg_failure;
1716         if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, IPSET_PROTOCOL) ||
1717             nla_put_string(skb2, IPSET_ATTR_TYPENAME, typename) ||
1718             nla_put_u8(skb2, IPSET_ATTR_FAMILY, family) ||
1719             nla_put_u8(skb2, IPSET_ATTR_REVISION, max) ||
1720             nla_put_u8(skb2, IPSET_ATTR_REVISION_MIN, min))
1721                 goto nla_put_failure;
1722         nlmsg_end(skb2, nlh2);
1723
1724         pr_debug("Send TYPE, nlmsg_len: %u\n", nlh2->nlmsg_len);
1725         ret = netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
1726         if (ret < 0)
1727                 return ret;
1728
1729         return 0;
1730
1731 nla_put_failure:
1732         nlmsg_cancel(skb2, nlh2);
1733 nlmsg_failure:
1734         kfree_skb(skb2);
1735         return -EMSGSIZE;
1736 }
1737
1738 /* Get protocol version */
1739
1740 static const struct nla_policy
1741 ip_set_protocol_policy[IPSET_ATTR_CMD_MAX + 1] = {
1742         [IPSET_ATTR_PROTOCOL]   = { .type = NLA_U8 },
1743 };
1744
1745 static int
1746 ip_set_protocol(struct sock *ctnl, struct sk_buff *skb,
1747                 const struct nlmsghdr *nlh,
1748                 const struct nlattr * const attr[])
1749 {
1750         struct sk_buff *skb2;
1751         struct nlmsghdr *nlh2;
1752         int ret = 0;
1753
1754         if (unlikely(attr[IPSET_ATTR_PROTOCOL] == NULL))
1755                 return -IPSET_ERR_PROTOCOL;
1756
1757         skb2 = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
1758         if (skb2 == NULL)
1759                 return -ENOMEM;
1760
1761         nlh2 = start_msg(skb2, NETLINK_CB(skb).portid, nlh->nlmsg_seq, 0,
1762                          IPSET_CMD_PROTOCOL);
1763         if (!nlh2)
1764                 goto nlmsg_failure;
1765         if (nla_put_u8(skb2, IPSET_ATTR_PROTOCOL, IPSET_PROTOCOL))
1766                 goto nla_put_failure;
1767         nlmsg_end(skb2, nlh2);
1768
1769         ret = netlink_unicast(ctnl, skb2, NETLINK_CB(skb).portid, MSG_DONTWAIT);
1770         if (ret < 0)
1771                 return ret;
1772
1773         return 0;
1774
1775 nla_put_failure:
1776         nlmsg_cancel(skb2, nlh2);
1777 nlmsg_failure:
1778         kfree_skb(skb2);
1779         return -EMSGSIZE;
1780 }
1781
1782 static const struct nfnl_callback ip_set_netlink_subsys_cb[IPSET_MSG_MAX] = {
1783         [IPSET_CMD_NONE]        = {
1784                 .call           = ip_set_none,
1785                 .attr_count     = IPSET_ATTR_CMD_MAX,
1786         },
1787         [IPSET_CMD_CREATE]      = {
1788                 .call           = ip_set_create,
1789                 .attr_count     = IPSET_ATTR_CMD_MAX,
1790                 .policy         = ip_set_create_policy,
1791         },
1792         [IPSET_CMD_DESTROY]     = {
1793                 .call           = ip_set_destroy,
1794                 .attr_count     = IPSET_ATTR_CMD_MAX,
1795                 .policy         = ip_set_setname_policy,
1796         },
1797         [IPSET_CMD_FLUSH]       = {
1798                 .call           = ip_set_flush,
1799                 .attr_count     = IPSET_ATTR_CMD_MAX,
1800                 .policy         = ip_set_setname_policy,
1801         },
1802         [IPSET_CMD_RENAME]      = {
1803                 .call           = ip_set_rename,
1804                 .attr_count     = IPSET_ATTR_CMD_MAX,
1805                 .policy         = ip_set_setname2_policy,
1806         },
1807         [IPSET_CMD_SWAP]        = {
1808                 .call           = ip_set_swap,
1809                 .attr_count     = IPSET_ATTR_CMD_MAX,
1810                 .policy         = ip_set_setname2_policy,
1811         },
1812         [IPSET_CMD_LIST]        = {
1813                 .call           = ip_set_dump,
1814                 .attr_count     = IPSET_ATTR_CMD_MAX,
1815                 .policy         = ip_set_setname_policy,
1816         },
1817         [IPSET_CMD_SAVE]        = {
1818                 .call           = ip_set_dump,
1819                 .attr_count     = IPSET_ATTR_CMD_MAX,
1820                 .policy         = ip_set_setname_policy,
1821         },
1822         [IPSET_CMD_ADD] = {
1823                 .call           = ip_set_uadd,
1824                 .attr_count     = IPSET_ATTR_CMD_MAX,
1825                 .policy         = ip_set_adt_policy,
1826         },
1827         [IPSET_CMD_DEL] = {
1828                 .call           = ip_set_udel,
1829                 .attr_count     = IPSET_ATTR_CMD_MAX,
1830                 .policy         = ip_set_adt_policy,
1831         },
1832         [IPSET_CMD_TEST]        = {
1833                 .call           = ip_set_utest,
1834                 .attr_count     = IPSET_ATTR_CMD_MAX,
1835                 .policy         = ip_set_adt_policy,
1836         },
1837         [IPSET_CMD_HEADER]      = {
1838                 .call           = ip_set_header,
1839                 .attr_count     = IPSET_ATTR_CMD_MAX,
1840                 .policy         = ip_set_setname_policy,
1841         },
1842         [IPSET_CMD_TYPE]        = {
1843                 .call           = ip_set_type,
1844                 .attr_count     = IPSET_ATTR_CMD_MAX,
1845                 .policy         = ip_set_type_policy,
1846         },
1847         [IPSET_CMD_PROTOCOL]    = {
1848                 .call           = ip_set_protocol,
1849                 .attr_count     = IPSET_ATTR_CMD_MAX,
1850                 .policy         = ip_set_protocol_policy,
1851         },
1852 };
1853
1854 static struct nfnetlink_subsystem ip_set_netlink_subsys __read_mostly = {
1855         .name           = "ip_set",
1856         .subsys_id      = NFNL_SUBSYS_IPSET,
1857         .cb_count       = IPSET_MSG_MAX,
1858         .cb             = ip_set_netlink_subsys_cb,
1859 };
1860
1861 /* Interface to iptables/ip6tables */
1862
1863 static int
1864 ip_set_sockfn_get(struct sock *sk, int optval, void __user *user, int *len)
1865 {
1866         unsigned int *op;
1867         void *data;
1868         int copylen = *len, ret = 0;
1869         struct net *net = sock_net(sk);
1870         struct ip_set_net *inst = ip_set_pernet(net);
1871
1872         if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1873                 return -EPERM;
1874         if (optval != SO_IP_SET)
1875                 return -EBADF;
1876         if (*len < sizeof(unsigned int))
1877                 return -EINVAL;
1878
1879         data = vmalloc(*len);
1880         if (!data)
1881                 return -ENOMEM;
1882         if (copy_from_user(data, user, *len) != 0) {
1883                 ret = -EFAULT;
1884                 goto done;
1885         }
1886         op = (unsigned int *) data;
1887
1888         if (*op < IP_SET_OP_VERSION) {
1889                 /* Check the version at the beginning of operations */
1890                 struct ip_set_req_version *req_version = data;
1891
1892                 if (*len < sizeof(struct ip_set_req_version)) {
1893                         ret = -EINVAL;
1894                         goto done;
1895                 }
1896
1897                 if (req_version->version != IPSET_PROTOCOL) {
1898                         ret = -EPROTO;
1899                         goto done;
1900                 }
1901         }
1902
1903         switch (*op) {
1904         case IP_SET_OP_VERSION: {
1905                 struct ip_set_req_version *req_version = data;
1906
1907                 if (*len != sizeof(struct ip_set_req_version)) {
1908                         ret = -EINVAL;
1909                         goto done;
1910                 }
1911
1912                 req_version->version = IPSET_PROTOCOL;
1913                 ret = copy_to_user(user, req_version,
1914                                    sizeof(struct ip_set_req_version));
1915                 goto done;
1916         }
1917         case IP_SET_OP_GET_BYNAME: {
1918                 struct ip_set_req_get_set *req_get = data;
1919                 ip_set_id_t id;
1920
1921                 if (*len != sizeof(struct ip_set_req_get_set)) {
1922                         ret = -EINVAL;
1923                         goto done;
1924                 }
1925                 req_get->set.name[IPSET_MAXNAMELEN - 1] = '\0';
1926                 nfnl_lock(NFNL_SUBSYS_IPSET);
1927                 find_set_and_id(inst, req_get->set.name, &id);
1928                 req_get->set.index = id;
1929                 nfnl_unlock(NFNL_SUBSYS_IPSET);
1930                 goto copy;
1931         }
1932         case IP_SET_OP_GET_FNAME: {
1933                 struct ip_set_req_get_set_family *req_get = data;
1934                 ip_set_id_t id;
1935
1936                 if (*len != sizeof(struct ip_set_req_get_set_family)) {
1937                         ret = -EINVAL;
1938                         goto done;
1939                 }
1940                 req_get->set.name[IPSET_MAXNAMELEN - 1] = '\0';
1941                 nfnl_lock(NFNL_SUBSYS_IPSET);
1942                 find_set_and_id(inst, req_get->set.name, &id);
1943                 req_get->set.index = id;
1944                 if (id != IPSET_INVALID_ID)
1945                         req_get->family = ip_set(inst, id)->family;
1946                 nfnl_unlock(NFNL_SUBSYS_IPSET);
1947                 goto copy;
1948         }
1949         case IP_SET_OP_GET_BYINDEX: {
1950                 struct ip_set_req_get_set *req_get = data;
1951                 struct ip_set *set;
1952
1953                 if (*len != sizeof(struct ip_set_req_get_set) ||
1954                     req_get->set.index >= inst->ip_set_max) {
1955                         ret = -EINVAL;
1956                         goto done;
1957                 }
1958                 nfnl_lock(NFNL_SUBSYS_IPSET);
1959                 set = ip_set(inst, req_get->set.index);
1960                 strncpy(req_get->set.name, set ? set->name : "",
1961                         IPSET_MAXNAMELEN);
1962                 nfnl_unlock(NFNL_SUBSYS_IPSET);
1963                 goto copy;
1964         }
1965         default:
1966                 ret = -EBADMSG;
1967                 goto done;
1968         }       /* end of switch(op) */
1969
1970 copy:
1971         ret = copy_to_user(user, data, copylen);
1972
1973 done:
1974         vfree(data);
1975         if (ret > 0)
1976                 ret = 0;
1977         return ret;
1978 }
1979
1980 static struct nf_sockopt_ops so_set __read_mostly = {
1981         .pf             = PF_INET,
1982         .get_optmin     = SO_IP_SET,
1983         .get_optmax     = SO_IP_SET + 1,
1984         .get            = &ip_set_sockfn_get,
1985         .owner          = THIS_MODULE,
1986 };
1987
1988 static int __net_init
1989 ip_set_net_init(struct net *net)
1990 {
1991         struct ip_set_net *inst = ip_set_pernet(net);
1992         struct ip_set **list;
1993
1994         inst->ip_set_max = max_sets ? max_sets : CONFIG_IP_SET_MAX;
1995         if (inst->ip_set_max >= IPSET_INVALID_ID)
1996                 inst->ip_set_max = IPSET_INVALID_ID - 1;
1997
1998         list = kzalloc(sizeof(struct ip_set *) * inst->ip_set_max, GFP_KERNEL);
1999         if (!list)
2000                 return -ENOMEM;
2001         inst->is_deleted = 0;
2002         rcu_assign_pointer(inst->ip_set_list, list);
2003         return 0;
2004 }
2005
2006 static void __net_exit
2007 ip_set_net_exit(struct net *net)
2008 {
2009         struct ip_set_net *inst = ip_set_pernet(net);
2010
2011         struct ip_set *set = NULL;
2012         ip_set_id_t i;
2013
2014         inst->is_deleted = 1; /* flag for ip_set_nfnl_put */
2015
2016         for (i = 0; i < inst->ip_set_max; i++) {
2017                 set = ip_set(inst, i);
2018                 if (set != NULL)
2019                         ip_set_destroy_set(inst, i);
2020         }
2021         kfree(rcu_dereference_protected(inst->ip_set_list, 1));
2022 }
2023
2024 static struct pernet_operations ip_set_net_ops = {
2025         .init   = ip_set_net_init,
2026         .exit   = ip_set_net_exit,
2027         .id     = &ip_set_net_id,
2028         .size   = sizeof(struct ip_set_net)
2029 };
2030
2031
2032 static int __init
2033 ip_set_init(void)
2034 {
2035         int ret = nfnetlink_subsys_register(&ip_set_netlink_subsys);
2036         if (ret != 0) {
2037                 pr_err("ip_set: cannot register with nfnetlink.\n");
2038                 return ret;
2039         }
2040         ret = nf_register_sockopt(&so_set);
2041         if (ret != 0) {
2042                 pr_err("SO_SET registry failed: %d\n", ret);
2043                 nfnetlink_subsys_unregister(&ip_set_netlink_subsys);
2044                 return ret;
2045         }
2046         ret = register_pernet_subsys(&ip_set_net_ops);
2047         if (ret) {
2048                 pr_err("ip_set: cannot register pernet_subsys.\n");
2049                 nf_unregister_sockopt(&so_set);
2050                 nfnetlink_subsys_unregister(&ip_set_netlink_subsys);
2051                 return ret;
2052         }
2053         pr_info("ip_set: protocol %u\n", IPSET_PROTOCOL);
2054         return 0;
2055 }
2056
2057 static void __exit
2058 ip_set_fini(void)
2059 {
2060         unregister_pernet_subsys(&ip_set_net_ops);
2061         nf_unregister_sockopt(&so_set);
2062         nfnetlink_subsys_unregister(&ip_set_netlink_subsys);
2063         pr_debug("these are the famous last words\n");
2064 }
2065
2066 module_init(ip_set_init);
2067 module_exit(ip_set_fini);