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