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