OSDN Git Service

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