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