GNU Linux-libre 4.14.266-gnu1
[releases.git] / net / ipv4 / netfilter / ipt_CLUSTERIP.c
1 /* Cluster IP hashmark target
2  * (C) 2003-2004 by Harald Welte <laforge@netfilter.org>
3  * based on ideas of Fabio Olive Leite <olive@unixforge.org>
4  *
5  * Development of this code funded by SuSE Linux AG, http://www.suse.com/
6  *
7  * This program is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License version 2 as
9  * published by the Free Software Foundation.
10  *
11  */
12 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
13 #include <linux/module.h>
14 #include <linux/proc_fs.h>
15 #include <linux/jhash.h>
16 #include <linux/bitops.h>
17 #include <linux/skbuff.h>
18 #include <linux/slab.h>
19 #include <linux/ip.h>
20 #include <linux/tcp.h>
21 #include <linux/udp.h>
22 #include <linux/icmp.h>
23 #include <linux/if_arp.h>
24 #include <linux/seq_file.h>
25 #include <linux/refcount.h>
26 #include <linux/netfilter_arp.h>
27 #include <linux/netfilter/x_tables.h>
28 #include <linux/netfilter_ipv4/ip_tables.h>
29 #include <linux/netfilter_ipv4/ipt_CLUSTERIP.h>
30 #include <net/netfilter/nf_conntrack.h>
31 #include <net/net_namespace.h>
32 #include <net/netns/generic.h>
33 #include <net/checksum.h>
34 #include <net/ip.h>
35
36 #define CLUSTERIP_VERSION "0.8"
37
38 MODULE_LICENSE("GPL");
39 MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>");
40 MODULE_DESCRIPTION("Xtables: CLUSTERIP target");
41
42 struct clusterip_config {
43         struct list_head list;                  /* list of all configs */
44         refcount_t refcount;                    /* reference count */
45         refcount_t entries;                     /* number of entries/rules
46                                                  * referencing us */
47
48         __be32 clusterip;                       /* the IP address */
49         u_int8_t clustermac[ETH_ALEN];          /* the MAC address */
50         int ifindex;                            /* device ifindex */
51         u_int16_t num_total_nodes;              /* total number of nodes */
52         unsigned long local_nodes;              /* node number array */
53
54 #ifdef CONFIG_PROC_FS
55         struct proc_dir_entry *pde;             /* proc dir entry */
56 #endif
57         enum clusterip_hashmode hash_mode;      /* which hashing mode */
58         u_int32_t hash_initval;                 /* hash initialization */
59         struct rcu_head rcu;
60
61         char ifname[IFNAMSIZ];                  /* device ifname */
62         struct notifier_block notifier;         /* refresh c->ifindex in it */
63 };
64
65 #ifdef CONFIG_PROC_FS
66 static const struct file_operations clusterip_proc_fops;
67 #endif
68
69 static unsigned int clusterip_net_id __read_mostly;
70
71 struct clusterip_net {
72         struct list_head configs;
73         /* lock protects the configs list */
74         spinlock_t lock;
75
76 #ifdef CONFIG_PROC_FS
77         struct proc_dir_entry *procdir;
78 #endif
79 };
80
81 static inline void
82 clusterip_config_get(struct clusterip_config *c)
83 {
84         refcount_inc(&c->refcount);
85 }
86
87
88 static void clusterip_config_rcu_free(struct rcu_head *head)
89 {
90         kfree(container_of(head, struct clusterip_config, rcu));
91 }
92
93 static inline void
94 clusterip_config_put(struct clusterip_config *c)
95 {
96         if (refcount_dec_and_test(&c->refcount))
97                 call_rcu_bh(&c->rcu, clusterip_config_rcu_free);
98 }
99
100 /* decrease the count of entries using/referencing this config.  If last
101  * entry(rule) is removed, remove the config from lists, but don't free it
102  * yet, since proc-files could still be holding references */
103 static inline void
104 clusterip_config_entry_put(struct net *net, struct clusterip_config *c)
105 {
106         struct clusterip_net *cn = net_generic(net, clusterip_net_id);
107
108         local_bh_disable();
109         if (refcount_dec_and_lock(&c->entries, &cn->lock)) {
110                 /* In case anyone still accesses the file, the open/close
111                  * functions are also incrementing the refcount on their own,
112                  * so it's safe to remove the entry even if it's in use. */
113 #ifdef CONFIG_PROC_FS
114                 if (cn->procdir)
115                         proc_remove(c->pde);
116 #endif
117                 list_del_rcu(&c->list);
118                 spin_unlock(&cn->lock);
119                 local_bh_enable();
120
121                 unregister_netdevice_notifier(&c->notifier);
122
123                 return;
124         }
125         local_bh_enable();
126 }
127
128 static struct clusterip_config *
129 __clusterip_config_find(struct net *net, __be32 clusterip)
130 {
131         struct clusterip_config *c;
132         struct clusterip_net *cn = net_generic(net, clusterip_net_id);
133
134         list_for_each_entry_rcu(c, &cn->configs, list) {
135                 if (c->clusterip == clusterip)
136                         return c;
137         }
138
139         return NULL;
140 }
141
142 static inline struct clusterip_config *
143 clusterip_config_find_get(struct net *net, __be32 clusterip, int entry)
144 {
145         struct clusterip_config *c;
146
147         rcu_read_lock_bh();
148         c = __clusterip_config_find(net, clusterip);
149         if (c) {
150 #ifdef CONFIG_PROC_FS
151                 if (!c->pde)
152                         c = NULL;
153                 else
154 #endif
155                 if (unlikely(!refcount_inc_not_zero(&c->refcount)))
156                         c = NULL;
157                 else if (entry)
158                         refcount_inc(&c->entries);
159         }
160         rcu_read_unlock_bh();
161
162         return c;
163 }
164
165 static void
166 clusterip_config_init_nodelist(struct clusterip_config *c,
167                                const struct ipt_clusterip_tgt_info *i)
168 {
169         int n;
170
171         for (n = 0; n < i->num_local_nodes; n++)
172                 set_bit(i->local_nodes[n] - 1, &c->local_nodes);
173 }
174
175 static int
176 clusterip_netdev_event(struct notifier_block *this, unsigned long event,
177                        void *ptr)
178 {
179         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
180         struct clusterip_config *c;
181
182         c = container_of(this, struct clusterip_config, notifier);
183         switch (event) {
184         case NETDEV_REGISTER:
185                 if (!strcmp(dev->name, c->ifname)) {
186                         c->ifindex = dev->ifindex;
187                         dev_mc_add(dev, c->clustermac);
188                 }
189                 break;
190         case NETDEV_UNREGISTER:
191                 if (dev->ifindex == c->ifindex) {
192                         dev_mc_del(dev, c->clustermac);
193                         c->ifindex = -1;
194                 }
195                 break;
196         case NETDEV_CHANGENAME:
197                 if (!strcmp(dev->name, c->ifname)) {
198                         c->ifindex = dev->ifindex;
199                         dev_mc_add(dev, c->clustermac);
200                 } else if (dev->ifindex == c->ifindex) {
201                         dev_mc_del(dev, c->clustermac);
202                         c->ifindex = -1;
203                 }
204                 break;
205         }
206
207         return NOTIFY_DONE;
208 }
209
210 static struct clusterip_config *
211 clusterip_config_init(struct net *net, const struct ipt_clusterip_tgt_info *i,
212                       __be32 ip, const char *iniface)
213 {
214         struct clusterip_net *cn = net_generic(net, clusterip_net_id);
215         struct clusterip_config *c;
216         int err;
217
218         c = kzalloc(sizeof(*c), GFP_ATOMIC);
219         if (!c)
220                 return ERR_PTR(-ENOMEM);
221
222         strcpy(c->ifname, iniface);
223         c->ifindex = -1;
224         c->clusterip = ip;
225         memcpy(&c->clustermac, &i->clustermac, ETH_ALEN);
226         c->num_total_nodes = i->num_total_nodes;
227         clusterip_config_init_nodelist(c, i);
228         c->hash_mode = i->hash_mode;
229         c->hash_initval = i->hash_initval;
230         refcount_set(&c->refcount, 1);
231
232         spin_lock_bh(&cn->lock);
233         if (__clusterip_config_find(net, ip)) {
234                 spin_unlock_bh(&cn->lock);
235                 kfree(c);
236
237                 return ERR_PTR(-EBUSY);
238         }
239
240         list_add_rcu(&c->list, &cn->configs);
241         spin_unlock_bh(&cn->lock);
242
243 #ifdef CONFIG_PROC_FS
244         {
245                 char buffer[16];
246
247                 /* create proc dir entry */
248                 sprintf(buffer, "%pI4", &ip);
249                 c->pde = proc_create_data(buffer, S_IWUSR|S_IRUSR,
250                                           cn->procdir,
251                                           &clusterip_proc_fops, c);
252                 if (!c->pde) {
253                         err = -ENOMEM;
254                         goto err;
255                 }
256         }
257 #endif
258
259         c->notifier.notifier_call = clusterip_netdev_event;
260         err = register_netdevice_notifier(&c->notifier);
261         if (!err) {
262                 refcount_set(&c->entries, 1);
263                 return c;
264         }
265
266 #ifdef CONFIG_PROC_FS
267         proc_remove(c->pde);
268 err:
269 #endif
270         spin_lock_bh(&cn->lock);
271         list_del_rcu(&c->list);
272         spin_unlock_bh(&cn->lock);
273         clusterip_config_put(c);
274
275         return ERR_PTR(err);
276 }
277
278 #ifdef CONFIG_PROC_FS
279 static int
280 clusterip_add_node(struct clusterip_config *c, u_int16_t nodenum)
281 {
282
283         if (nodenum == 0 ||
284             nodenum > c->num_total_nodes)
285                 return 1;
286
287         /* check if we already have this number in our bitfield */
288         if (test_and_set_bit(nodenum - 1, &c->local_nodes))
289                 return 1;
290
291         return 0;
292 }
293
294 static bool
295 clusterip_del_node(struct clusterip_config *c, u_int16_t nodenum)
296 {
297         if (nodenum == 0 ||
298             nodenum > c->num_total_nodes)
299                 return true;
300
301         if (test_and_clear_bit(nodenum - 1, &c->local_nodes))
302                 return false;
303
304         return true;
305 }
306 #endif
307
308 static inline u_int32_t
309 clusterip_hashfn(const struct sk_buff *skb,
310                  const struct clusterip_config *config)
311 {
312         const struct iphdr *iph = ip_hdr(skb);
313         unsigned long hashval;
314         u_int16_t sport = 0, dport = 0;
315         int poff;
316
317         poff = proto_ports_offset(iph->protocol);
318         if (poff >= 0) {
319                 const u_int16_t *ports;
320                 u16 _ports[2];
321
322                 ports = skb_header_pointer(skb, iph->ihl * 4 + poff, 4, _ports);
323                 if (ports) {
324                         sport = ports[0];
325                         dport = ports[1];
326                 }
327         } else {
328                 net_info_ratelimited("unknown protocol %u\n", iph->protocol);
329         }
330
331         switch (config->hash_mode) {
332         case CLUSTERIP_HASHMODE_SIP:
333                 hashval = jhash_1word(ntohl(iph->saddr),
334                                       config->hash_initval);
335                 break;
336         case CLUSTERIP_HASHMODE_SIP_SPT:
337                 hashval = jhash_2words(ntohl(iph->saddr), sport,
338                                        config->hash_initval);
339                 break;
340         case CLUSTERIP_HASHMODE_SIP_SPT_DPT:
341                 hashval = jhash_3words(ntohl(iph->saddr), sport, dport,
342                                        config->hash_initval);
343                 break;
344         default:
345                 /* to make gcc happy */
346                 hashval = 0;
347                 /* This cannot happen, unless the check function wasn't called
348                  * at rule load time */
349                 pr_info("unknown mode %u\n", config->hash_mode);
350                 BUG();
351                 break;
352         }
353
354         /* node numbers are 1..n, not 0..n */
355         return reciprocal_scale(hashval, config->num_total_nodes) + 1;
356 }
357
358 static inline int
359 clusterip_responsible(const struct clusterip_config *config, u_int32_t hash)
360 {
361         return test_bit(hash - 1, &config->local_nodes);
362 }
363
364 /***********************************************************************
365  * IPTABLES TARGET
366  ***********************************************************************/
367
368 static unsigned int
369 clusterip_tg(struct sk_buff *skb, const struct xt_action_param *par)
370 {
371         const struct ipt_clusterip_tgt_info *cipinfo = par->targinfo;
372         struct nf_conn *ct;
373         enum ip_conntrack_info ctinfo;
374         u_int32_t hash;
375
376         /* don't need to clusterip_config_get() here, since refcount
377          * is only decremented by destroy() - and ip_tables guarantees
378          * that the ->target() function isn't called after ->destroy() */
379
380         ct = nf_ct_get(skb, &ctinfo);
381         if (ct == NULL)
382                 return NF_DROP;
383
384         /* special case: ICMP error handling. conntrack distinguishes between
385          * error messages (RELATED) and information requests (see below) */
386         if (ip_hdr(skb)->protocol == IPPROTO_ICMP &&
387             (ctinfo == IP_CT_RELATED ||
388              ctinfo == IP_CT_RELATED_REPLY))
389                 return XT_CONTINUE;
390
391         /* ip_conntrack_icmp guarantees us that we only have ICMP_ECHO,
392          * TIMESTAMP, INFO_REQUEST or ADDRESS type icmp packets from here
393          * on, which all have an ID field [relevant for hashing]. */
394
395         hash = clusterip_hashfn(skb, cipinfo->config);
396
397         switch (ctinfo) {
398         case IP_CT_NEW:
399                 ct->mark = hash;
400                 break;
401         case IP_CT_RELATED:
402         case IP_CT_RELATED_REPLY:
403                 /* FIXME: we don't handle expectations at the moment.
404                  * They can arrive on a different node than
405                  * the master connection (e.g. FTP passive mode) */
406         case IP_CT_ESTABLISHED:
407         case IP_CT_ESTABLISHED_REPLY:
408                 break;
409         default:                        /* Prevent gcc warnings */
410                 break;
411         }
412
413 #ifdef DEBUG
414         nf_ct_dump_tuple_ip(&ct->tuplehash[IP_CT_DIR_ORIGINAL].tuple);
415 #endif
416         pr_debug("hash=%u ct_hash=%u ", hash, ct->mark);
417         if (!clusterip_responsible(cipinfo->config, hash)) {
418                 pr_debug("not responsible\n");
419                 return NF_DROP;
420         }
421         pr_debug("responsible\n");
422
423         /* despite being received via linklayer multicast, this is
424          * actually a unicast IP packet. TCP doesn't like PACKET_MULTICAST */
425         skb->pkt_type = PACKET_HOST;
426
427         return XT_CONTINUE;
428 }
429
430 static int clusterip_tg_check(const struct xt_tgchk_param *par)
431 {
432         struct ipt_clusterip_tgt_info *cipinfo = par->targinfo;
433         const struct ipt_entry *e = par->entryinfo;
434         struct clusterip_config *config;
435         int ret, i;
436
437         if (par->nft_compat) {
438                 pr_err("cannot use CLUSTERIP target from nftables compat\n");
439                 return -EOPNOTSUPP;
440         }
441
442         if (cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP &&
443             cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP_SPT &&
444             cipinfo->hash_mode != CLUSTERIP_HASHMODE_SIP_SPT_DPT) {
445                 pr_info("unknown mode %u\n", cipinfo->hash_mode);
446                 return -EINVAL;
447
448         }
449         if (e->ip.dmsk.s_addr != htonl(0xffffffff) ||
450             e->ip.dst.s_addr == 0) {
451                 pr_info("Please specify destination IP\n");
452                 return -EINVAL;
453         }
454         if (cipinfo->num_local_nodes > ARRAY_SIZE(cipinfo->local_nodes)) {
455                 pr_info("bad num_local_nodes %u\n", cipinfo->num_local_nodes);
456                 return -EINVAL;
457         }
458         for (i = 0; i < cipinfo->num_local_nodes; i++) {
459                 if (cipinfo->local_nodes[i] - 1 >=
460                     sizeof(config->local_nodes) * 8) {
461                         pr_info("bad local_nodes[%d] %u\n",
462                                 i, cipinfo->local_nodes[i]);
463                         return -EINVAL;
464                 }
465         }
466
467         config = clusterip_config_find_get(par->net, e->ip.dst.s_addr, 1);
468         if (!config) {
469                 if (!(cipinfo->flags & CLUSTERIP_FLAG_NEW)) {
470                         pr_info("no config found for %pI4, need 'new'\n",
471                                 &e->ip.dst.s_addr);
472                         return -EINVAL;
473                 } else {
474                         struct net_device *dev;
475
476                         if (e->ip.iniface[0] == '\0') {
477                                 pr_info("Please specify an interface name\n");
478                                 return -EINVAL;
479                         }
480
481                         dev = dev_get_by_name(par->net, e->ip.iniface);
482                         if (!dev) {
483                                 pr_info("no such interface %s\n",
484                                         e->ip.iniface);
485                                 return -ENOENT;
486                         }
487                         dev_put(dev);
488
489                         config = clusterip_config_init(par->net, cipinfo,
490                                                        e->ip.dst.s_addr,
491                                                        e->ip.iniface);
492                         if (IS_ERR(config))
493                                 return PTR_ERR(config);
494                 }
495         } else if (memcmp(&config->clustermac, &cipinfo->clustermac, ETH_ALEN))
496                 return -EINVAL;
497
498         ret = nf_ct_netns_get(par->net, par->family);
499         if (ret < 0) {
500                 pr_info("cannot load conntrack support for proto=%u\n",
501                         par->family);
502                 clusterip_config_entry_put(par->net, config);
503                 clusterip_config_put(config);
504                 return ret;
505         }
506
507         if (!par->net->xt.clusterip_deprecated_warning) {
508                 pr_info("ipt_CLUSTERIP is deprecated and it will removed soon, "
509                         "use xt_cluster instead\n");
510                 par->net->xt.clusterip_deprecated_warning = true;
511         }
512
513         cipinfo->config = config;
514         return ret;
515 }
516
517 /* drop reference count of cluster config when rule is deleted */
518 static void clusterip_tg_destroy(const struct xt_tgdtor_param *par)
519 {
520         const struct ipt_clusterip_tgt_info *cipinfo = par->targinfo;
521
522         /* if no more entries are referencing the config, remove it
523          * from the list and destroy the proc entry */
524         clusterip_config_entry_put(par->net, cipinfo->config);
525
526         clusterip_config_put(cipinfo->config);
527
528         nf_ct_netns_put(par->net, par->family);
529 }
530
531 #ifdef CONFIG_COMPAT
532 struct compat_ipt_clusterip_tgt_info
533 {
534         u_int32_t       flags;
535         u_int8_t        clustermac[6];
536         u_int16_t       num_total_nodes;
537         u_int16_t       num_local_nodes;
538         u_int16_t       local_nodes[CLUSTERIP_MAX_NODES];
539         u_int32_t       hash_mode;
540         u_int32_t       hash_initval;
541         compat_uptr_t   config;
542 };
543 #endif /* CONFIG_COMPAT */
544
545 static struct xt_target clusterip_tg_reg __read_mostly = {
546         .name           = "CLUSTERIP",
547         .family         = NFPROTO_IPV4,
548         .target         = clusterip_tg,
549         .checkentry     = clusterip_tg_check,
550         .destroy        = clusterip_tg_destroy,
551         .targetsize     = sizeof(struct ipt_clusterip_tgt_info),
552         .usersize       = offsetof(struct ipt_clusterip_tgt_info, config),
553 #ifdef CONFIG_COMPAT
554         .compatsize     = sizeof(struct compat_ipt_clusterip_tgt_info),
555 #endif /* CONFIG_COMPAT */
556         .me             = THIS_MODULE
557 };
558
559
560 /***********************************************************************
561  * ARP MANGLING CODE
562  ***********************************************************************/
563
564 /* hardcoded for 48bit ethernet and 32bit ipv4 addresses */
565 struct arp_payload {
566         u_int8_t src_hw[ETH_ALEN];
567         __be32 src_ip;
568         u_int8_t dst_hw[ETH_ALEN];
569         __be32 dst_ip;
570 } __packed;
571
572 #ifdef DEBUG
573 static void arp_print(struct arp_payload *payload)
574 {
575 #define HBUFFERLEN 30
576         char hbuffer[HBUFFERLEN];
577         int j, k;
578
579         for (k = 0, j = 0; k < HBUFFERLEN - 3 && j < ETH_ALEN; j++) {
580                 hbuffer[k++] = hex_asc_hi(payload->src_hw[j]);
581                 hbuffer[k++] = hex_asc_lo(payload->src_hw[j]);
582                 hbuffer[k++] = ':';
583         }
584         hbuffer[--k] = '\0';
585
586         pr_debug("src %pI4@%s, dst %pI4\n",
587                  &payload->src_ip, hbuffer, &payload->dst_ip);
588 }
589 #endif
590
591 static unsigned int
592 arp_mangle(void *priv,
593            struct sk_buff *skb,
594            const struct nf_hook_state *state)
595 {
596         struct arphdr *arp = arp_hdr(skb);
597         struct arp_payload *payload;
598         struct clusterip_config *c;
599         struct net *net = state->net;
600
601         /* we don't care about non-ethernet and non-ipv4 ARP */
602         if (arp->ar_hrd != htons(ARPHRD_ETHER) ||
603             arp->ar_pro != htons(ETH_P_IP) ||
604             arp->ar_pln != 4 || arp->ar_hln != ETH_ALEN)
605                 return NF_ACCEPT;
606
607         /* we only want to mangle arp requests and replies */
608         if (arp->ar_op != htons(ARPOP_REPLY) &&
609             arp->ar_op != htons(ARPOP_REQUEST))
610                 return NF_ACCEPT;
611
612         payload = (void *)(arp+1);
613
614         /* if there is no clusterip configuration for the arp reply's
615          * source ip, we don't want to mangle it */
616         c = clusterip_config_find_get(net, payload->src_ip, 0);
617         if (!c)
618                 return NF_ACCEPT;
619
620         /* normally the linux kernel always replies to arp queries of
621          * addresses on different interfacs.  However, in the CLUSTERIP case
622          * this wouldn't work, since we didn't subscribe the mcast group on
623          * other interfaces */
624         if (c->ifindex != state->out->ifindex) {
625                 pr_debug("not mangling arp reply on different interface: cip'%d'-skb'%d'\n",
626                          c->ifindex, state->out->ifindex);
627                 clusterip_config_put(c);
628                 return NF_ACCEPT;
629         }
630
631         /* mangle reply hardware address */
632         memcpy(payload->src_hw, c->clustermac, arp->ar_hln);
633
634 #ifdef DEBUG
635         pr_debug("mangled arp reply: ");
636         arp_print(payload);
637 #endif
638
639         clusterip_config_put(c);
640
641         return NF_ACCEPT;
642 }
643
644 static const struct nf_hook_ops cip_arp_ops = {
645         .hook = arp_mangle,
646         .pf = NFPROTO_ARP,
647         .hooknum = NF_ARP_OUT,
648         .priority = -1
649 };
650
651 /***********************************************************************
652  * PROC DIR HANDLING
653  ***********************************************************************/
654
655 #ifdef CONFIG_PROC_FS
656
657 struct clusterip_seq_position {
658         unsigned int pos;       /* position */
659         unsigned int weight;    /* number of bits set == size */
660         unsigned int bit;       /* current bit */
661         unsigned long val;      /* current value */
662 };
663
664 static void *clusterip_seq_start(struct seq_file *s, loff_t *pos)
665 {
666         struct clusterip_config *c = s->private;
667         unsigned int weight;
668         u_int32_t local_nodes;
669         struct clusterip_seq_position *idx;
670
671         /* FIXME: possible race */
672         local_nodes = c->local_nodes;
673         weight = hweight32(local_nodes);
674         if (*pos >= weight)
675                 return NULL;
676
677         idx = kmalloc(sizeof(struct clusterip_seq_position), GFP_KERNEL);
678         if (!idx)
679                 return ERR_PTR(-ENOMEM);
680
681         idx->pos = *pos;
682         idx->weight = weight;
683         idx->bit = ffs(local_nodes);
684         idx->val = local_nodes;
685         clear_bit(idx->bit - 1, &idx->val);
686
687         return idx;
688 }
689
690 static void *clusterip_seq_next(struct seq_file *s, void *v, loff_t *pos)
691 {
692         struct clusterip_seq_position *idx = v;
693
694         *pos = ++idx->pos;
695         if (*pos >= idx->weight) {
696                 kfree(v);
697                 return NULL;
698         }
699         idx->bit = ffs(idx->val);
700         clear_bit(idx->bit - 1, &idx->val);
701         return idx;
702 }
703
704 static void clusterip_seq_stop(struct seq_file *s, void *v)
705 {
706         if (!IS_ERR(v))
707                 kfree(v);
708 }
709
710 static int clusterip_seq_show(struct seq_file *s, void *v)
711 {
712         struct clusterip_seq_position *idx = v;
713
714         if (idx->pos != 0)
715                 seq_putc(s, ',');
716
717         seq_printf(s, "%u", idx->bit);
718
719         if (idx->pos == idx->weight - 1)
720                 seq_putc(s, '\n');
721
722         return 0;
723 }
724
725 static const struct seq_operations clusterip_seq_ops = {
726         .start  = clusterip_seq_start,
727         .next   = clusterip_seq_next,
728         .stop   = clusterip_seq_stop,
729         .show   = clusterip_seq_show,
730 };
731
732 static int clusterip_proc_open(struct inode *inode, struct file *file)
733 {
734         int ret = seq_open(file, &clusterip_seq_ops);
735
736         if (!ret) {
737                 struct seq_file *sf = file->private_data;
738                 struct clusterip_config *c = PDE_DATA(inode);
739
740                 sf->private = c;
741
742                 clusterip_config_get(c);
743         }
744
745         return ret;
746 }
747
748 static int clusterip_proc_release(struct inode *inode, struct file *file)
749 {
750         struct clusterip_config *c = PDE_DATA(inode);
751         int ret;
752
753         ret = seq_release(inode, file);
754
755         if (!ret)
756                 clusterip_config_put(c);
757
758         return ret;
759 }
760
761 static ssize_t clusterip_proc_write(struct file *file, const char __user *input,
762                                 size_t size, loff_t *ofs)
763 {
764         struct clusterip_config *c = PDE_DATA(file_inode(file));
765 #define PROC_WRITELEN   10
766         char buffer[PROC_WRITELEN+1];
767         unsigned long nodenum;
768         int rc;
769
770         if (size > PROC_WRITELEN)
771                 return -EIO;
772         if (copy_from_user(buffer, input, size))
773                 return -EFAULT;
774         buffer[size] = 0;
775
776         if (*buffer == '+') {
777                 rc = kstrtoul(buffer+1, 10, &nodenum);
778                 if (rc)
779                         return rc;
780                 if (clusterip_add_node(c, nodenum))
781                         return -ENOMEM;
782         } else if (*buffer == '-') {
783                 rc = kstrtoul(buffer+1, 10, &nodenum);
784                 if (rc)
785                         return rc;
786                 if (clusterip_del_node(c, nodenum))
787                         return -ENOENT;
788         } else
789                 return -EIO;
790
791         return size;
792 }
793
794 static const struct file_operations clusterip_proc_fops = {
795         .owner   = THIS_MODULE,
796         .open    = clusterip_proc_open,
797         .read    = seq_read,
798         .write   = clusterip_proc_write,
799         .llseek  = seq_lseek,
800         .release = clusterip_proc_release,
801 };
802
803 #endif /* CONFIG_PROC_FS */
804
805 static int clusterip_net_init(struct net *net)
806 {
807         struct clusterip_net *cn = net_generic(net, clusterip_net_id);
808         int ret;
809
810         INIT_LIST_HEAD(&cn->configs);
811
812         spin_lock_init(&cn->lock);
813
814         ret = nf_register_net_hook(net, &cip_arp_ops);
815         if (ret < 0)
816                 return ret;
817
818 #ifdef CONFIG_PROC_FS
819         cn->procdir = proc_mkdir("ipt_CLUSTERIP", net->proc_net);
820         if (!cn->procdir) {
821                 nf_unregister_net_hook(net, &cip_arp_ops);
822                 pr_err("Unable to proc dir entry\n");
823                 return -ENOMEM;
824         }
825 #endif /* CONFIG_PROC_FS */
826
827         return 0;
828 }
829
830 static void clusterip_net_exit(struct net *net)
831 {
832 #ifdef CONFIG_PROC_FS
833         struct clusterip_net *cn = net_generic(net, clusterip_net_id);
834         proc_remove(cn->procdir);
835         cn->procdir = NULL;
836 #endif
837         nf_unregister_net_hook(net, &cip_arp_ops);
838 }
839
840 static struct pernet_operations clusterip_net_ops = {
841         .init = clusterip_net_init,
842         .exit = clusterip_net_exit,
843         .id   = &clusterip_net_id,
844         .size = sizeof(struct clusterip_net),
845 };
846
847 static int __init clusterip_tg_init(void)
848 {
849         int ret;
850
851         ret = register_pernet_subsys(&clusterip_net_ops);
852         if (ret < 0)
853                 return ret;
854
855         ret = xt_register_target(&clusterip_tg_reg);
856         if (ret < 0)
857                 goto cleanup_subsys;
858
859         pr_info("ClusterIP Version %s loaded successfully\n",
860                 CLUSTERIP_VERSION);
861
862         return 0;
863
864 cleanup_subsys:
865         unregister_pernet_subsys(&clusterip_net_ops);
866         return ret;
867 }
868
869 static void __exit clusterip_tg_exit(void)
870 {
871         pr_info("ClusterIP Version %s unloading\n", CLUSTERIP_VERSION);
872
873         xt_unregister_target(&clusterip_tg_reg);
874         unregister_pernet_subsys(&clusterip_net_ops);
875
876         /* Wait for completion of call_rcu_bh()'s (clusterip_config_rcu_free) */
877         rcu_barrier_bh();
878 }
879
880 module_init(clusterip_tg_init);
881 module_exit(clusterip_tg_exit);