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