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