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