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