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