• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * IPVS         An implementation of the IP virtual server support for the
4  *              LINUX operating system.  IPVS is now implemented as a module
5  *              over the NetFilter framework. IPVS can be used to build a
6  *              high-performance and highly available server based on a
7  *              cluster of servers.
8  *
9  * Authors:     Wensong Zhang <wensong@linuxvirtualserver.org>
10  *              Peter Kese <peter.kese@ijs.si>
11  *              Julian Anastasov <ja@ssi.bg>
12  *
13  * Changes:
14  */
15 
16 #define KMSG_COMPONENT "IPVS"
17 #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt
18 
19 #include <linux/module.h>
20 #include <linux/init.h>
21 #include <linux/types.h>
22 #include <linux/capability.h>
23 #include <linux/fs.h>
24 #include <linux/sysctl.h>
25 #include <linux/proc_fs.h>
26 #include <linux/workqueue.h>
27 #include <linux/swap.h>
28 #include <linux/seq_file.h>
29 #include <linux/slab.h>
30 
31 #include <linux/netfilter.h>
32 #include <linux/netfilter_ipv4.h>
33 #include <linux/mutex.h>
34 
35 #include <net/net_namespace.h>
36 #include <linux/nsproxy.h>
37 #include <net/ip.h>
38 #ifdef CONFIG_IP_VS_IPV6
39 #include <net/ipv6.h>
40 #include <net/ip6_route.h>
41 #include <net/netfilter/ipv6/nf_defrag_ipv6.h>
42 #endif
43 #include <net/route.h>
44 #include <net/sock.h>
45 #include <net/genetlink.h>
46 
47 #include <linux/uaccess.h>
48 
49 #include <net/ip_vs.h>
50 
51 /* semaphore for IPVS sockopts. And, [gs]etsockopt may sleep. */
52 static DEFINE_MUTEX(__ip_vs_mutex);
53 
54 /* sysctl variables */
55 
56 #ifdef CONFIG_IP_VS_DEBUG
57 static int sysctl_ip_vs_debug_level = 0;
58 
ip_vs_get_debug_level(void)59 int ip_vs_get_debug_level(void)
60 {
61 	return sysctl_ip_vs_debug_level;
62 }
63 #endif
64 
65 
66 /*  Protos */
67 static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup);
68 
69 
70 #ifdef CONFIG_IP_VS_IPV6
71 /* Taken from rt6_fill_node() in net/ipv6/route.c, is there a better way? */
__ip_vs_addr_is_local_v6(struct net * net,const struct in6_addr * addr)72 static bool __ip_vs_addr_is_local_v6(struct net *net,
73 				     const struct in6_addr *addr)
74 {
75 	struct flowi6 fl6 = {
76 		.daddr = *addr,
77 	};
78 	struct dst_entry *dst = ip6_route_output(net, NULL, &fl6);
79 	bool is_local;
80 
81 	is_local = !dst->error && dst->dev && (dst->dev->flags & IFF_LOOPBACK);
82 
83 	dst_release(dst);
84 	return is_local;
85 }
86 #endif
87 
88 #ifdef CONFIG_SYSCTL
89 /*
90  *	update_defense_level is called from keventd and from sysctl,
91  *	so it needs to protect itself from softirqs
92  */
update_defense_level(struct netns_ipvs * ipvs)93 static void update_defense_level(struct netns_ipvs *ipvs)
94 {
95 	struct sysinfo i;
96 	int availmem;
97 	int nomem;
98 	int to_change = -1;
99 
100 	/* we only count free and buffered memory (in pages) */
101 	si_meminfo(&i);
102 	availmem = i.freeram + i.bufferram;
103 	/* however in linux 2.5 the i.bufferram is total page cache size,
104 	   we need adjust it */
105 	/* si_swapinfo(&i); */
106 	/* availmem = availmem - (i.totalswap - i.freeswap); */
107 
108 	nomem = (availmem < ipvs->sysctl_amemthresh);
109 
110 	local_bh_disable();
111 
112 	/* drop_entry */
113 	spin_lock(&ipvs->dropentry_lock);
114 	switch (ipvs->sysctl_drop_entry) {
115 	case 0:
116 		atomic_set(&ipvs->dropentry, 0);
117 		break;
118 	case 1:
119 		if (nomem) {
120 			atomic_set(&ipvs->dropentry, 1);
121 			ipvs->sysctl_drop_entry = 2;
122 		} else {
123 			atomic_set(&ipvs->dropentry, 0);
124 		}
125 		break;
126 	case 2:
127 		if (nomem) {
128 			atomic_set(&ipvs->dropentry, 1);
129 		} else {
130 			atomic_set(&ipvs->dropentry, 0);
131 			ipvs->sysctl_drop_entry = 1;
132 		}
133 		break;
134 	case 3:
135 		atomic_set(&ipvs->dropentry, 1);
136 		break;
137 	}
138 	spin_unlock(&ipvs->dropentry_lock);
139 
140 	/* drop_packet */
141 	spin_lock(&ipvs->droppacket_lock);
142 	switch (ipvs->sysctl_drop_packet) {
143 	case 0:
144 		ipvs->drop_rate = 0;
145 		break;
146 	case 1:
147 		if (nomem) {
148 			ipvs->drop_rate = ipvs->drop_counter
149 				= ipvs->sysctl_amemthresh /
150 				(ipvs->sysctl_amemthresh-availmem);
151 			ipvs->sysctl_drop_packet = 2;
152 		} else {
153 			ipvs->drop_rate = 0;
154 		}
155 		break;
156 	case 2:
157 		if (nomem) {
158 			ipvs->drop_rate = ipvs->drop_counter
159 				= ipvs->sysctl_amemthresh /
160 				(ipvs->sysctl_amemthresh-availmem);
161 		} else {
162 			ipvs->drop_rate = 0;
163 			ipvs->sysctl_drop_packet = 1;
164 		}
165 		break;
166 	case 3:
167 		ipvs->drop_rate = ipvs->sysctl_am_droprate;
168 		break;
169 	}
170 	spin_unlock(&ipvs->droppacket_lock);
171 
172 	/* secure_tcp */
173 	spin_lock(&ipvs->securetcp_lock);
174 	switch (ipvs->sysctl_secure_tcp) {
175 	case 0:
176 		if (ipvs->old_secure_tcp >= 2)
177 			to_change = 0;
178 		break;
179 	case 1:
180 		if (nomem) {
181 			if (ipvs->old_secure_tcp < 2)
182 				to_change = 1;
183 			ipvs->sysctl_secure_tcp = 2;
184 		} else {
185 			if (ipvs->old_secure_tcp >= 2)
186 				to_change = 0;
187 		}
188 		break;
189 	case 2:
190 		if (nomem) {
191 			if (ipvs->old_secure_tcp < 2)
192 				to_change = 1;
193 		} else {
194 			if (ipvs->old_secure_tcp >= 2)
195 				to_change = 0;
196 			ipvs->sysctl_secure_tcp = 1;
197 		}
198 		break;
199 	case 3:
200 		if (ipvs->old_secure_tcp < 2)
201 			to_change = 1;
202 		break;
203 	}
204 	ipvs->old_secure_tcp = ipvs->sysctl_secure_tcp;
205 	if (to_change >= 0)
206 		ip_vs_protocol_timeout_change(ipvs,
207 					      ipvs->sysctl_secure_tcp > 1);
208 	spin_unlock(&ipvs->securetcp_lock);
209 
210 	local_bh_enable();
211 }
212 
213 /* Handler for delayed work for expiring no
214  * destination connections
215  */
expire_nodest_conn_handler(struct work_struct * work)216 static void expire_nodest_conn_handler(struct work_struct *work)
217 {
218 	struct netns_ipvs *ipvs;
219 
220 	ipvs = container_of(work, struct netns_ipvs,
221 			    expire_nodest_conn_work.work);
222 	ip_vs_expire_nodest_conn_flush(ipvs);
223 }
224 
225 /*
226  *	Timer for checking the defense
227  */
228 #define DEFENSE_TIMER_PERIOD	1*HZ
229 
defense_work_handler(struct work_struct * work)230 static void defense_work_handler(struct work_struct *work)
231 {
232 	struct netns_ipvs *ipvs =
233 		container_of(work, struct netns_ipvs, defense_work.work);
234 
235 	update_defense_level(ipvs);
236 	if (atomic_read(&ipvs->dropentry))
237 		ip_vs_random_dropentry(ipvs);
238 	queue_delayed_work(system_long_wq, &ipvs->defense_work,
239 			   DEFENSE_TIMER_PERIOD);
240 }
241 #endif
242 
243 int
ip_vs_use_count_inc(void)244 ip_vs_use_count_inc(void)
245 {
246 	return try_module_get(THIS_MODULE);
247 }
248 
249 void
ip_vs_use_count_dec(void)250 ip_vs_use_count_dec(void)
251 {
252 	module_put(THIS_MODULE);
253 }
254 
255 
256 /*
257  *	Hash table: for virtual service lookups
258  */
259 #define IP_VS_SVC_TAB_BITS 8
260 #define IP_VS_SVC_TAB_SIZE (1 << IP_VS_SVC_TAB_BITS)
261 #define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1)
262 
263 /* the service table hashed by <protocol, addr, port> */
264 static struct hlist_head ip_vs_svc_table[IP_VS_SVC_TAB_SIZE];
265 /* the service table hashed by fwmark */
266 static struct hlist_head ip_vs_svc_fwm_table[IP_VS_SVC_TAB_SIZE];
267 
268 
269 /*
270  *	Returns hash value for virtual service
271  */
272 static inline unsigned int
ip_vs_svc_hashkey(struct netns_ipvs * ipvs,int af,unsigned int proto,const union nf_inet_addr * addr,__be16 port)273 ip_vs_svc_hashkey(struct netns_ipvs *ipvs, int af, unsigned int proto,
274 		  const union nf_inet_addr *addr, __be16 port)
275 {
276 	unsigned int porth = ntohs(port);
277 	__be32 addr_fold = addr->ip;
278 	__u32 ahash;
279 
280 #ifdef CONFIG_IP_VS_IPV6
281 	if (af == AF_INET6)
282 		addr_fold = addr->ip6[0]^addr->ip6[1]^
283 			    addr->ip6[2]^addr->ip6[3];
284 #endif
285 	ahash = ntohl(addr_fold);
286 	ahash ^= ((size_t) ipvs >> 8);
287 
288 	return (proto ^ ahash ^ (porth >> IP_VS_SVC_TAB_BITS) ^ porth) &
289 	       IP_VS_SVC_TAB_MASK;
290 }
291 
292 /*
293  *	Returns hash value of fwmark for virtual service lookup
294  */
ip_vs_svc_fwm_hashkey(struct netns_ipvs * ipvs,__u32 fwmark)295 static inline unsigned int ip_vs_svc_fwm_hashkey(struct netns_ipvs *ipvs, __u32 fwmark)
296 {
297 	return (((size_t)ipvs>>8) ^ fwmark) & IP_VS_SVC_TAB_MASK;
298 }
299 
300 /*
301  *	Hashes a service in the ip_vs_svc_table by <netns,proto,addr,port>
302  *	or in the ip_vs_svc_fwm_table by fwmark.
303  *	Should be called with locked tables.
304  */
ip_vs_svc_hash(struct ip_vs_service * svc)305 static int ip_vs_svc_hash(struct ip_vs_service *svc)
306 {
307 	unsigned int hash;
308 
309 	if (svc->flags & IP_VS_SVC_F_HASHED) {
310 		pr_err("%s(): request for already hashed, called from %pS\n",
311 		       __func__, __builtin_return_address(0));
312 		return 0;
313 	}
314 
315 	if (svc->fwmark == 0) {
316 		/*
317 		 *  Hash it by <netns,protocol,addr,port> in ip_vs_svc_table
318 		 */
319 		hash = ip_vs_svc_hashkey(svc->ipvs, svc->af, svc->protocol,
320 					 &svc->addr, svc->port);
321 		hlist_add_head_rcu(&svc->s_list, &ip_vs_svc_table[hash]);
322 	} else {
323 		/*
324 		 *  Hash it by fwmark in svc_fwm_table
325 		 */
326 		hash = ip_vs_svc_fwm_hashkey(svc->ipvs, svc->fwmark);
327 		hlist_add_head_rcu(&svc->f_list, &ip_vs_svc_fwm_table[hash]);
328 	}
329 
330 	svc->flags |= IP_VS_SVC_F_HASHED;
331 	/* increase its refcnt because it is referenced by the svc table */
332 	atomic_inc(&svc->refcnt);
333 	return 1;
334 }
335 
336 
337 /*
338  *	Unhashes a service from svc_table / svc_fwm_table.
339  *	Should be called with locked tables.
340  */
ip_vs_svc_unhash(struct ip_vs_service * svc)341 static int ip_vs_svc_unhash(struct ip_vs_service *svc)
342 {
343 	if (!(svc->flags & IP_VS_SVC_F_HASHED)) {
344 		pr_err("%s(): request for unhash flagged, called from %pS\n",
345 		       __func__, __builtin_return_address(0));
346 		return 0;
347 	}
348 
349 	if (svc->fwmark == 0) {
350 		/* Remove it from the svc_table table */
351 		hlist_del_rcu(&svc->s_list);
352 	} else {
353 		/* Remove it from the svc_fwm_table table */
354 		hlist_del_rcu(&svc->f_list);
355 	}
356 
357 	svc->flags &= ~IP_VS_SVC_F_HASHED;
358 	atomic_dec(&svc->refcnt);
359 	return 1;
360 }
361 
362 
363 /*
364  *	Get service by {netns, proto,addr,port} in the service table.
365  */
366 static inline struct ip_vs_service *
__ip_vs_service_find(struct netns_ipvs * ipvs,int af,__u16 protocol,const union nf_inet_addr * vaddr,__be16 vport)367 __ip_vs_service_find(struct netns_ipvs *ipvs, int af, __u16 protocol,
368 		     const union nf_inet_addr *vaddr, __be16 vport)
369 {
370 	unsigned int hash;
371 	struct ip_vs_service *svc;
372 
373 	/* Check for "full" addressed entries */
374 	hash = ip_vs_svc_hashkey(ipvs, af, protocol, vaddr, vport);
375 
376 	hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[hash], s_list) {
377 		if ((svc->af == af)
378 		    && ip_vs_addr_equal(af, &svc->addr, vaddr)
379 		    && (svc->port == vport)
380 		    && (svc->protocol == protocol)
381 		    && (svc->ipvs == ipvs)) {
382 			/* HIT */
383 			return svc;
384 		}
385 	}
386 
387 	return NULL;
388 }
389 
390 
391 /*
392  *	Get service by {fwmark} in the service table.
393  */
394 static inline struct ip_vs_service *
__ip_vs_svc_fwm_find(struct netns_ipvs * ipvs,int af,__u32 fwmark)395 __ip_vs_svc_fwm_find(struct netns_ipvs *ipvs, int af, __u32 fwmark)
396 {
397 	unsigned int hash;
398 	struct ip_vs_service *svc;
399 
400 	/* Check for fwmark addressed entries */
401 	hash = ip_vs_svc_fwm_hashkey(ipvs, fwmark);
402 
403 	hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[hash], f_list) {
404 		if (svc->fwmark == fwmark && svc->af == af
405 		    && (svc->ipvs == ipvs)) {
406 			/* HIT */
407 			return svc;
408 		}
409 	}
410 
411 	return NULL;
412 }
413 
414 /* Find service, called under RCU lock */
415 struct ip_vs_service *
ip_vs_service_find(struct netns_ipvs * ipvs,int af,__u32 fwmark,__u16 protocol,const union nf_inet_addr * vaddr,__be16 vport)416 ip_vs_service_find(struct netns_ipvs *ipvs, int af, __u32 fwmark, __u16 protocol,
417 		   const union nf_inet_addr *vaddr, __be16 vport)
418 {
419 	struct ip_vs_service *svc;
420 
421 	/*
422 	 *	Check the table hashed by fwmark first
423 	 */
424 	if (fwmark) {
425 		svc = __ip_vs_svc_fwm_find(ipvs, af, fwmark);
426 		if (svc)
427 			goto out;
428 	}
429 
430 	/*
431 	 *	Check the table hashed by <protocol,addr,port>
432 	 *	for "full" addressed entries
433 	 */
434 	svc = __ip_vs_service_find(ipvs, af, protocol, vaddr, vport);
435 
436 	if (!svc && protocol == IPPROTO_TCP &&
437 	    atomic_read(&ipvs->ftpsvc_counter) &&
438 	    (vport == FTPDATA || !inet_port_requires_bind_service(ipvs->net, ntohs(vport)))) {
439 		/*
440 		 * Check if ftp service entry exists, the packet
441 		 * might belong to FTP data connections.
442 		 */
443 		svc = __ip_vs_service_find(ipvs, af, protocol, vaddr, FTPPORT);
444 	}
445 
446 	if (svc == NULL
447 	    && atomic_read(&ipvs->nullsvc_counter)) {
448 		/*
449 		 * Check if the catch-all port (port zero) exists
450 		 */
451 		svc = __ip_vs_service_find(ipvs, af, protocol, vaddr, 0);
452 	}
453 
454   out:
455 	IP_VS_DBG_BUF(9, "lookup service: fwm %u %s %s:%u %s\n",
456 		      fwmark, ip_vs_proto_name(protocol),
457 		      IP_VS_DBG_ADDR(af, vaddr), ntohs(vport),
458 		      svc ? "hit" : "not hit");
459 
460 	return svc;
461 }
462 
463 
464 static inline void
__ip_vs_bind_svc(struct ip_vs_dest * dest,struct ip_vs_service * svc)465 __ip_vs_bind_svc(struct ip_vs_dest *dest, struct ip_vs_service *svc)
466 {
467 	atomic_inc(&svc->refcnt);
468 	rcu_assign_pointer(dest->svc, svc);
469 }
470 
ip_vs_service_free(struct ip_vs_service * svc)471 static void ip_vs_service_free(struct ip_vs_service *svc)
472 {
473 	free_percpu(svc->stats.cpustats);
474 	kfree(svc);
475 }
476 
ip_vs_service_rcu_free(struct rcu_head * head)477 static void ip_vs_service_rcu_free(struct rcu_head *head)
478 {
479 	struct ip_vs_service *svc;
480 
481 	svc = container_of(head, struct ip_vs_service, rcu_head);
482 	ip_vs_service_free(svc);
483 }
484 
__ip_vs_svc_put(struct ip_vs_service * svc,bool do_delay)485 static void __ip_vs_svc_put(struct ip_vs_service *svc, bool do_delay)
486 {
487 	if (atomic_dec_and_test(&svc->refcnt)) {
488 		IP_VS_DBG_BUF(3, "Removing service %u/%s:%u\n",
489 			      svc->fwmark,
490 			      IP_VS_DBG_ADDR(svc->af, &svc->addr),
491 			      ntohs(svc->port));
492 		if (do_delay)
493 			call_rcu(&svc->rcu_head, ip_vs_service_rcu_free);
494 		else
495 			ip_vs_service_free(svc);
496 	}
497 }
498 
499 
500 /*
501  *	Returns hash value for real service
502  */
ip_vs_rs_hashkey(int af,const union nf_inet_addr * addr,__be16 port)503 static inline unsigned int ip_vs_rs_hashkey(int af,
504 					    const union nf_inet_addr *addr,
505 					    __be16 port)
506 {
507 	unsigned int porth = ntohs(port);
508 	__be32 addr_fold = addr->ip;
509 
510 #ifdef CONFIG_IP_VS_IPV6
511 	if (af == AF_INET6)
512 		addr_fold = addr->ip6[0]^addr->ip6[1]^
513 			    addr->ip6[2]^addr->ip6[3];
514 #endif
515 
516 	return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth)
517 		& IP_VS_RTAB_MASK;
518 }
519 
520 /* Hash ip_vs_dest in rs_table by <proto,addr,port>. */
ip_vs_rs_hash(struct netns_ipvs * ipvs,struct ip_vs_dest * dest)521 static void ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest)
522 {
523 	unsigned int hash;
524 	__be16 port;
525 
526 	if (dest->in_rs_table)
527 		return;
528 
529 	switch (IP_VS_DFWD_METHOD(dest)) {
530 	case IP_VS_CONN_F_MASQ:
531 		port = dest->port;
532 		break;
533 	case IP_VS_CONN_F_TUNNEL:
534 		switch (dest->tun_type) {
535 		case IP_VS_CONN_F_TUNNEL_TYPE_GUE:
536 			port = dest->tun_port;
537 			break;
538 		case IP_VS_CONN_F_TUNNEL_TYPE_IPIP:
539 		case IP_VS_CONN_F_TUNNEL_TYPE_GRE:
540 			port = 0;
541 			break;
542 		default:
543 			return;
544 		}
545 		break;
546 	default:
547 		return;
548 	}
549 
550 	/*
551 	 *	Hash by proto,addr,port,
552 	 *	which are the parameters of the real service.
553 	 */
554 	hash = ip_vs_rs_hashkey(dest->af, &dest->addr, port);
555 
556 	hlist_add_head_rcu(&dest->d_list, &ipvs->rs_table[hash]);
557 	dest->in_rs_table = 1;
558 }
559 
560 /* Unhash ip_vs_dest from rs_table. */
ip_vs_rs_unhash(struct ip_vs_dest * dest)561 static void ip_vs_rs_unhash(struct ip_vs_dest *dest)
562 {
563 	/*
564 	 * Remove it from the rs_table table.
565 	 */
566 	if (dest->in_rs_table) {
567 		hlist_del_rcu(&dest->d_list);
568 		dest->in_rs_table = 0;
569 	}
570 }
571 
572 /* Check if real service by <proto,addr,port> is present */
ip_vs_has_real_service(struct netns_ipvs * ipvs,int af,__u16 protocol,const union nf_inet_addr * daddr,__be16 dport)573 bool ip_vs_has_real_service(struct netns_ipvs *ipvs, int af, __u16 protocol,
574 			    const union nf_inet_addr *daddr, __be16 dport)
575 {
576 	unsigned int hash;
577 	struct ip_vs_dest *dest;
578 
579 	/* Check for "full" addressed entries */
580 	hash = ip_vs_rs_hashkey(af, daddr, dport);
581 
582 	hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
583 		if (dest->port == dport &&
584 		    dest->af == af &&
585 		    ip_vs_addr_equal(af, &dest->addr, daddr) &&
586 		    (dest->protocol == protocol || dest->vfwmark) &&
587 		    IP_VS_DFWD_METHOD(dest) == IP_VS_CONN_F_MASQ) {
588 			/* HIT */
589 			return true;
590 		}
591 	}
592 
593 	return false;
594 }
595 
596 /* Find real service record by <proto,addr,port>.
597  * In case of multiple records with the same <proto,addr,port>, only
598  * the first found record is returned.
599  *
600  * To be called under RCU lock.
601  */
ip_vs_find_real_service(struct netns_ipvs * ipvs,int af,__u16 protocol,const union nf_inet_addr * daddr,__be16 dport)602 struct ip_vs_dest *ip_vs_find_real_service(struct netns_ipvs *ipvs, int af,
603 					   __u16 protocol,
604 					   const union nf_inet_addr *daddr,
605 					   __be16 dport)
606 {
607 	unsigned int hash;
608 	struct ip_vs_dest *dest;
609 
610 	/* Check for "full" addressed entries */
611 	hash = ip_vs_rs_hashkey(af, daddr, dport);
612 
613 	hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
614 		if (dest->port == dport &&
615 		    dest->af == af &&
616 		    ip_vs_addr_equal(af, &dest->addr, daddr) &&
617 		    (dest->protocol == protocol || dest->vfwmark) &&
618 		    IP_VS_DFWD_METHOD(dest) == IP_VS_CONN_F_MASQ) {
619 			/* HIT */
620 			return dest;
621 		}
622 	}
623 
624 	return NULL;
625 }
626 
627 /* Find real service record by <af,addr,tun_port>.
628  * In case of multiple records with the same <af,addr,tun_port>, only
629  * the first found record is returned.
630  *
631  * To be called under RCU lock.
632  */
ip_vs_find_tunnel(struct netns_ipvs * ipvs,int af,const union nf_inet_addr * daddr,__be16 tun_port)633 struct ip_vs_dest *ip_vs_find_tunnel(struct netns_ipvs *ipvs, int af,
634 				     const union nf_inet_addr *daddr,
635 				     __be16 tun_port)
636 {
637 	struct ip_vs_dest *dest;
638 	unsigned int hash;
639 
640 	/* Check for "full" addressed entries */
641 	hash = ip_vs_rs_hashkey(af, daddr, tun_port);
642 
643 	hlist_for_each_entry_rcu(dest, &ipvs->rs_table[hash], d_list) {
644 		if (dest->tun_port == tun_port &&
645 		    dest->af == af &&
646 		    ip_vs_addr_equal(af, &dest->addr, daddr) &&
647 		    IP_VS_DFWD_METHOD(dest) == IP_VS_CONN_F_TUNNEL) {
648 			/* HIT */
649 			return dest;
650 		}
651 	}
652 
653 	return NULL;
654 }
655 
656 /* Lookup destination by {addr,port} in the given service
657  * Called under RCU lock.
658  */
659 static struct ip_vs_dest *
ip_vs_lookup_dest(struct ip_vs_service * svc,int dest_af,const union nf_inet_addr * daddr,__be16 dport)660 ip_vs_lookup_dest(struct ip_vs_service *svc, int dest_af,
661 		  const union nf_inet_addr *daddr, __be16 dport)
662 {
663 	struct ip_vs_dest *dest;
664 
665 	/*
666 	 * Find the destination for the given service
667 	 */
668 	list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
669 		if ((dest->af == dest_af) &&
670 		    ip_vs_addr_equal(dest_af, &dest->addr, daddr) &&
671 		    (dest->port == dport)) {
672 			/* HIT */
673 			return dest;
674 		}
675 	}
676 
677 	return NULL;
678 }
679 
680 /*
681  * Find destination by {daddr,dport,vaddr,protocol}
682  * Created to be used in ip_vs_process_message() in
683  * the backup synchronization daemon. It finds the
684  * destination to be bound to the received connection
685  * on the backup.
686  * Called under RCU lock, no refcnt is returned.
687  */
ip_vs_find_dest(struct netns_ipvs * ipvs,int svc_af,int dest_af,const union nf_inet_addr * daddr,__be16 dport,const union nf_inet_addr * vaddr,__be16 vport,__u16 protocol,__u32 fwmark,__u32 flags)688 struct ip_vs_dest *ip_vs_find_dest(struct netns_ipvs *ipvs, int svc_af, int dest_af,
689 				   const union nf_inet_addr *daddr,
690 				   __be16 dport,
691 				   const union nf_inet_addr *vaddr,
692 				   __be16 vport, __u16 protocol, __u32 fwmark,
693 				   __u32 flags)
694 {
695 	struct ip_vs_dest *dest;
696 	struct ip_vs_service *svc;
697 	__be16 port = dport;
698 
699 	svc = ip_vs_service_find(ipvs, svc_af, fwmark, protocol, vaddr, vport);
700 	if (!svc)
701 		return NULL;
702 	if (fwmark && (flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ)
703 		port = 0;
704 	dest = ip_vs_lookup_dest(svc, dest_af, daddr, port);
705 	if (!dest)
706 		dest = ip_vs_lookup_dest(svc, dest_af, daddr, port ^ dport);
707 	return dest;
708 }
709 
ip_vs_dest_dst_rcu_free(struct rcu_head * head)710 void ip_vs_dest_dst_rcu_free(struct rcu_head *head)
711 {
712 	struct ip_vs_dest_dst *dest_dst = container_of(head,
713 						       struct ip_vs_dest_dst,
714 						       rcu_head);
715 
716 	dst_release(dest_dst->dst_cache);
717 	kfree(dest_dst);
718 }
719 
720 /* Release dest_dst and dst_cache for dest in user context */
__ip_vs_dst_cache_reset(struct ip_vs_dest * dest)721 static void __ip_vs_dst_cache_reset(struct ip_vs_dest *dest)
722 {
723 	struct ip_vs_dest_dst *old;
724 
725 	old = rcu_dereference_protected(dest->dest_dst, 1);
726 	if (old) {
727 		RCU_INIT_POINTER(dest->dest_dst, NULL);
728 		call_rcu(&old->rcu_head, ip_vs_dest_dst_rcu_free);
729 	}
730 }
731 
732 /*
733  *  Lookup dest by {svc,addr,port} in the destination trash.
734  *  The destination trash is used to hold the destinations that are removed
735  *  from the service table but are still referenced by some conn entries.
736  *  The reason to add the destination trash is when the dest is temporary
737  *  down (either by administrator or by monitor program), the dest can be
738  *  picked back from the trash, the remaining connections to the dest can
739  *  continue, and the counting information of the dest is also useful for
740  *  scheduling.
741  */
742 static struct ip_vs_dest *
ip_vs_trash_get_dest(struct ip_vs_service * svc,int dest_af,const union nf_inet_addr * daddr,__be16 dport)743 ip_vs_trash_get_dest(struct ip_vs_service *svc, int dest_af,
744 		     const union nf_inet_addr *daddr, __be16 dport)
745 {
746 	struct ip_vs_dest *dest;
747 	struct netns_ipvs *ipvs = svc->ipvs;
748 
749 	/*
750 	 * Find the destination in trash
751 	 */
752 	spin_lock_bh(&ipvs->dest_trash_lock);
753 	list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
754 		IP_VS_DBG_BUF(3, "Destination %u/%s:%u still in trash, "
755 			      "dest->refcnt=%d\n",
756 			      dest->vfwmark,
757 			      IP_VS_DBG_ADDR(dest->af, &dest->addr),
758 			      ntohs(dest->port),
759 			      refcount_read(&dest->refcnt));
760 		if (dest->af == dest_af &&
761 		    ip_vs_addr_equal(dest_af, &dest->addr, daddr) &&
762 		    dest->port == dport &&
763 		    dest->vfwmark == svc->fwmark &&
764 		    dest->protocol == svc->protocol &&
765 		    (svc->fwmark ||
766 		     (ip_vs_addr_equal(svc->af, &dest->vaddr, &svc->addr) &&
767 		      dest->vport == svc->port))) {
768 			/* HIT */
769 			list_del(&dest->t_list);
770 			goto out;
771 		}
772 	}
773 
774 	dest = NULL;
775 
776 out:
777 	spin_unlock_bh(&ipvs->dest_trash_lock);
778 
779 	return dest;
780 }
781 
ip_vs_dest_free(struct ip_vs_dest * dest)782 static void ip_vs_dest_free(struct ip_vs_dest *dest)
783 {
784 	struct ip_vs_service *svc = rcu_dereference_protected(dest->svc, 1);
785 
786 	__ip_vs_dst_cache_reset(dest);
787 	__ip_vs_svc_put(svc, false);
788 	free_percpu(dest->stats.cpustats);
789 	ip_vs_dest_put_and_free(dest);
790 }
791 
792 /*
793  *  Clean up all the destinations in the trash
794  *  Called by the ip_vs_control_cleanup()
795  *
796  *  When the ip_vs_control_clearup is activated by ipvs module exit,
797  *  the service tables must have been flushed and all the connections
798  *  are expired, and the refcnt of each destination in the trash must
799  *  be 1, so we simply release them here.
800  */
ip_vs_trash_cleanup(struct netns_ipvs * ipvs)801 static void ip_vs_trash_cleanup(struct netns_ipvs *ipvs)
802 {
803 	struct ip_vs_dest *dest, *nxt;
804 
805 	del_timer_sync(&ipvs->dest_trash_timer);
806 	/* No need to use dest_trash_lock */
807 	list_for_each_entry_safe(dest, nxt, &ipvs->dest_trash, t_list) {
808 		list_del(&dest->t_list);
809 		ip_vs_dest_free(dest);
810 	}
811 }
812 
813 static void
ip_vs_copy_stats(struct ip_vs_kstats * dst,struct ip_vs_stats * src)814 ip_vs_copy_stats(struct ip_vs_kstats *dst, struct ip_vs_stats *src)
815 {
816 #define IP_VS_SHOW_STATS_COUNTER(c) dst->c = src->kstats.c - src->kstats0.c
817 
818 	spin_lock_bh(&src->lock);
819 
820 	IP_VS_SHOW_STATS_COUNTER(conns);
821 	IP_VS_SHOW_STATS_COUNTER(inpkts);
822 	IP_VS_SHOW_STATS_COUNTER(outpkts);
823 	IP_VS_SHOW_STATS_COUNTER(inbytes);
824 	IP_VS_SHOW_STATS_COUNTER(outbytes);
825 
826 	ip_vs_read_estimator(dst, src);
827 
828 	spin_unlock_bh(&src->lock);
829 }
830 
831 static void
ip_vs_export_stats_user(struct ip_vs_stats_user * dst,struct ip_vs_kstats * src)832 ip_vs_export_stats_user(struct ip_vs_stats_user *dst, struct ip_vs_kstats *src)
833 {
834 	dst->conns = (u32)src->conns;
835 	dst->inpkts = (u32)src->inpkts;
836 	dst->outpkts = (u32)src->outpkts;
837 	dst->inbytes = src->inbytes;
838 	dst->outbytes = src->outbytes;
839 	dst->cps = (u32)src->cps;
840 	dst->inpps = (u32)src->inpps;
841 	dst->outpps = (u32)src->outpps;
842 	dst->inbps = (u32)src->inbps;
843 	dst->outbps = (u32)src->outbps;
844 }
845 
846 static void
ip_vs_zero_stats(struct ip_vs_stats * stats)847 ip_vs_zero_stats(struct ip_vs_stats *stats)
848 {
849 	spin_lock_bh(&stats->lock);
850 
851 	/* get current counters as zero point, rates are zeroed */
852 
853 #define IP_VS_ZERO_STATS_COUNTER(c) stats->kstats0.c = stats->kstats.c
854 
855 	IP_VS_ZERO_STATS_COUNTER(conns);
856 	IP_VS_ZERO_STATS_COUNTER(inpkts);
857 	IP_VS_ZERO_STATS_COUNTER(outpkts);
858 	IP_VS_ZERO_STATS_COUNTER(inbytes);
859 	IP_VS_ZERO_STATS_COUNTER(outbytes);
860 
861 	ip_vs_zero_estimator(stats);
862 
863 	spin_unlock_bh(&stats->lock);
864 }
865 
866 /*
867  *	Update a destination in the given service
868  */
869 static void
__ip_vs_update_dest(struct ip_vs_service * svc,struct ip_vs_dest * dest,struct ip_vs_dest_user_kern * udest,int add)870 __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest,
871 		    struct ip_vs_dest_user_kern *udest, int add)
872 {
873 	struct netns_ipvs *ipvs = svc->ipvs;
874 	struct ip_vs_service *old_svc;
875 	struct ip_vs_scheduler *sched;
876 	int conn_flags;
877 
878 	/* We cannot modify an address and change the address family */
879 	BUG_ON(!add && udest->af != dest->af);
880 
881 	if (add && udest->af != svc->af)
882 		ipvs->mixed_address_family_dests++;
883 
884 	/* keep the last_weight with latest non-0 weight */
885 	if (add || udest->weight != 0)
886 		atomic_set(&dest->last_weight, udest->weight);
887 
888 	/* set the weight and the flags */
889 	atomic_set(&dest->weight, udest->weight);
890 	conn_flags = udest->conn_flags & IP_VS_CONN_F_DEST_MASK;
891 	conn_flags |= IP_VS_CONN_F_INACTIVE;
892 
893 	/* Need to rehash? */
894 	if ((udest->conn_flags & IP_VS_CONN_F_FWD_MASK) !=
895 	    IP_VS_DFWD_METHOD(dest) ||
896 	    udest->tun_type != dest->tun_type ||
897 	    udest->tun_port != dest->tun_port)
898 		ip_vs_rs_unhash(dest);
899 
900 	/* set the tunnel info */
901 	dest->tun_type = udest->tun_type;
902 	dest->tun_port = udest->tun_port;
903 	dest->tun_flags = udest->tun_flags;
904 
905 	/* set the IP_VS_CONN_F_NOOUTPUT flag if not masquerading/NAT */
906 	if ((conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ) {
907 		conn_flags |= IP_VS_CONN_F_NOOUTPUT;
908 	} else {
909 		/* FTP-NAT requires conntrack for mangling */
910 		if (svc->port == FTPPORT)
911 			ip_vs_register_conntrack(svc);
912 	}
913 	atomic_set(&dest->conn_flags, conn_flags);
914 	/* Put the real service in rs_table if not present. */
915 	ip_vs_rs_hash(ipvs, dest);
916 
917 	/* bind the service */
918 	old_svc = rcu_dereference_protected(dest->svc, 1);
919 	if (!old_svc) {
920 		__ip_vs_bind_svc(dest, svc);
921 	} else {
922 		if (old_svc != svc) {
923 			ip_vs_zero_stats(&dest->stats);
924 			__ip_vs_bind_svc(dest, svc);
925 			__ip_vs_svc_put(old_svc, true);
926 		}
927 	}
928 
929 	/* set the dest status flags */
930 	dest->flags |= IP_VS_DEST_F_AVAILABLE;
931 
932 	if (udest->u_threshold == 0 || udest->u_threshold > dest->u_threshold)
933 		dest->flags &= ~IP_VS_DEST_F_OVERLOAD;
934 	dest->u_threshold = udest->u_threshold;
935 	dest->l_threshold = udest->l_threshold;
936 
937 	dest->af = udest->af;
938 
939 	spin_lock_bh(&dest->dst_lock);
940 	__ip_vs_dst_cache_reset(dest);
941 	spin_unlock_bh(&dest->dst_lock);
942 
943 	if (add) {
944 		ip_vs_start_estimator(svc->ipvs, &dest->stats);
945 		list_add_rcu(&dest->n_list, &svc->destinations);
946 		svc->num_dests++;
947 		sched = rcu_dereference_protected(svc->scheduler, 1);
948 		if (sched && sched->add_dest)
949 			sched->add_dest(svc, dest);
950 	} else {
951 		sched = rcu_dereference_protected(svc->scheduler, 1);
952 		if (sched && sched->upd_dest)
953 			sched->upd_dest(svc, dest);
954 	}
955 }
956 
957 
958 /*
959  *	Create a destination for the given service
960  */
961 static int
ip_vs_new_dest(struct ip_vs_service * svc,struct ip_vs_dest_user_kern * udest,struct ip_vs_dest ** dest_p)962 ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest,
963 	       struct ip_vs_dest **dest_p)
964 {
965 	struct ip_vs_dest *dest;
966 	unsigned int atype, i;
967 
968 	EnterFunction(2);
969 
970 #ifdef CONFIG_IP_VS_IPV6
971 	if (udest->af == AF_INET6) {
972 		int ret;
973 
974 		atype = ipv6_addr_type(&udest->addr.in6);
975 		if ((!(atype & IPV6_ADDR_UNICAST) ||
976 			atype & IPV6_ADDR_LINKLOCAL) &&
977 			!__ip_vs_addr_is_local_v6(svc->ipvs->net, &udest->addr.in6))
978 			return -EINVAL;
979 
980 		ret = nf_defrag_ipv6_enable(svc->ipvs->net);
981 		if (ret)
982 			return ret;
983 	} else
984 #endif
985 	{
986 		atype = inet_addr_type(svc->ipvs->net, udest->addr.ip);
987 		if (atype != RTN_LOCAL && atype != RTN_UNICAST)
988 			return -EINVAL;
989 	}
990 
991 	dest = kzalloc(sizeof(struct ip_vs_dest), GFP_KERNEL);
992 	if (dest == NULL)
993 		return -ENOMEM;
994 
995 	dest->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
996 	if (!dest->stats.cpustats)
997 		goto err_alloc;
998 
999 	for_each_possible_cpu(i) {
1000 		struct ip_vs_cpu_stats *ip_vs_dest_stats;
1001 		ip_vs_dest_stats = per_cpu_ptr(dest->stats.cpustats, i);
1002 		u64_stats_init(&ip_vs_dest_stats->syncp);
1003 	}
1004 
1005 	dest->af = udest->af;
1006 	dest->protocol = svc->protocol;
1007 	dest->vaddr = svc->addr;
1008 	dest->vport = svc->port;
1009 	dest->vfwmark = svc->fwmark;
1010 	ip_vs_addr_copy(udest->af, &dest->addr, &udest->addr);
1011 	dest->port = udest->port;
1012 
1013 	atomic_set(&dest->activeconns, 0);
1014 	atomic_set(&dest->inactconns, 0);
1015 	atomic_set(&dest->persistconns, 0);
1016 	refcount_set(&dest->refcnt, 1);
1017 
1018 	INIT_HLIST_NODE(&dest->d_list);
1019 	spin_lock_init(&dest->dst_lock);
1020 	spin_lock_init(&dest->stats.lock);
1021 	__ip_vs_update_dest(svc, dest, udest, 1);
1022 
1023 	*dest_p = dest;
1024 
1025 	LeaveFunction(2);
1026 	return 0;
1027 
1028 err_alloc:
1029 	kfree(dest);
1030 	return -ENOMEM;
1031 }
1032 
1033 
1034 /*
1035  *	Add a destination into an existing service
1036  */
1037 static int
ip_vs_add_dest(struct ip_vs_service * svc,struct ip_vs_dest_user_kern * udest)1038 ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1039 {
1040 	struct ip_vs_dest *dest;
1041 	union nf_inet_addr daddr;
1042 	__be16 dport = udest->port;
1043 	int ret;
1044 
1045 	EnterFunction(2);
1046 
1047 	if (udest->weight < 0) {
1048 		pr_err("%s(): server weight less than zero\n", __func__);
1049 		return -ERANGE;
1050 	}
1051 
1052 	if (udest->l_threshold > udest->u_threshold) {
1053 		pr_err("%s(): lower threshold is higher than upper threshold\n",
1054 			__func__);
1055 		return -ERANGE;
1056 	}
1057 
1058 	if (udest->tun_type == IP_VS_CONN_F_TUNNEL_TYPE_GUE) {
1059 		if (udest->tun_port == 0) {
1060 			pr_err("%s(): tunnel port is zero\n", __func__);
1061 			return -EINVAL;
1062 		}
1063 	}
1064 
1065 	ip_vs_addr_copy(udest->af, &daddr, &udest->addr);
1066 
1067 	/* We use function that requires RCU lock */
1068 	rcu_read_lock();
1069 	dest = ip_vs_lookup_dest(svc, udest->af, &daddr, dport);
1070 	rcu_read_unlock();
1071 
1072 	if (dest != NULL) {
1073 		IP_VS_DBG(1, "%s(): dest already exists\n", __func__);
1074 		return -EEXIST;
1075 	}
1076 
1077 	/*
1078 	 * Check if the dest already exists in the trash and
1079 	 * is from the same service
1080 	 */
1081 	dest = ip_vs_trash_get_dest(svc, udest->af, &daddr, dport);
1082 
1083 	if (dest != NULL) {
1084 		IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, "
1085 			      "dest->refcnt=%d, service %u/%s:%u\n",
1086 			      IP_VS_DBG_ADDR(udest->af, &daddr), ntohs(dport),
1087 			      refcount_read(&dest->refcnt),
1088 			      dest->vfwmark,
1089 			      IP_VS_DBG_ADDR(svc->af, &dest->vaddr),
1090 			      ntohs(dest->vport));
1091 
1092 		__ip_vs_update_dest(svc, dest, udest, 1);
1093 		ret = 0;
1094 	} else {
1095 		/*
1096 		 * Allocate and initialize the dest structure
1097 		 */
1098 		ret = ip_vs_new_dest(svc, udest, &dest);
1099 	}
1100 	LeaveFunction(2);
1101 
1102 	return ret;
1103 }
1104 
1105 
1106 /*
1107  *	Edit a destination in the given service
1108  */
1109 static int
ip_vs_edit_dest(struct ip_vs_service * svc,struct ip_vs_dest_user_kern * udest)1110 ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1111 {
1112 	struct ip_vs_dest *dest;
1113 	union nf_inet_addr daddr;
1114 	__be16 dport = udest->port;
1115 
1116 	EnterFunction(2);
1117 
1118 	if (udest->weight < 0) {
1119 		pr_err("%s(): server weight less than zero\n", __func__);
1120 		return -ERANGE;
1121 	}
1122 
1123 	if (udest->l_threshold > udest->u_threshold) {
1124 		pr_err("%s(): lower threshold is higher than upper threshold\n",
1125 			__func__);
1126 		return -ERANGE;
1127 	}
1128 
1129 	if (udest->tun_type == IP_VS_CONN_F_TUNNEL_TYPE_GUE) {
1130 		if (udest->tun_port == 0) {
1131 			pr_err("%s(): tunnel port is zero\n", __func__);
1132 			return -EINVAL;
1133 		}
1134 	}
1135 
1136 	ip_vs_addr_copy(udest->af, &daddr, &udest->addr);
1137 
1138 	/* We use function that requires RCU lock */
1139 	rcu_read_lock();
1140 	dest = ip_vs_lookup_dest(svc, udest->af, &daddr, dport);
1141 	rcu_read_unlock();
1142 
1143 	if (dest == NULL) {
1144 		IP_VS_DBG(1, "%s(): dest doesn't exist\n", __func__);
1145 		return -ENOENT;
1146 	}
1147 
1148 	__ip_vs_update_dest(svc, dest, udest, 0);
1149 	LeaveFunction(2);
1150 
1151 	return 0;
1152 }
1153 
1154 /*
1155  *	Delete a destination (must be already unlinked from the service)
1156  */
__ip_vs_del_dest(struct netns_ipvs * ipvs,struct ip_vs_dest * dest,bool cleanup)1157 static void __ip_vs_del_dest(struct netns_ipvs *ipvs, struct ip_vs_dest *dest,
1158 			     bool cleanup)
1159 {
1160 	ip_vs_stop_estimator(ipvs, &dest->stats);
1161 
1162 	/*
1163 	 *  Remove it from the d-linked list with the real services.
1164 	 */
1165 	ip_vs_rs_unhash(dest);
1166 
1167 	spin_lock_bh(&ipvs->dest_trash_lock);
1168 	IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, dest->refcnt=%d\n",
1169 		      IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port),
1170 		      refcount_read(&dest->refcnt));
1171 	if (list_empty(&ipvs->dest_trash) && !cleanup)
1172 		mod_timer(&ipvs->dest_trash_timer,
1173 			  jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1));
1174 	/* dest lives in trash with reference */
1175 	list_add(&dest->t_list, &ipvs->dest_trash);
1176 	dest->idle_start = 0;
1177 	spin_unlock_bh(&ipvs->dest_trash_lock);
1178 
1179 	/* Queue up delayed work to expire all no destination connections.
1180 	 * No-op when CONFIG_SYSCTL is disabled.
1181 	 */
1182 	if (!cleanup)
1183 		ip_vs_enqueue_expire_nodest_conns(ipvs);
1184 }
1185 
1186 
1187 /*
1188  *	Unlink a destination from the given service
1189  */
__ip_vs_unlink_dest(struct ip_vs_service * svc,struct ip_vs_dest * dest,int svcupd)1190 static void __ip_vs_unlink_dest(struct ip_vs_service *svc,
1191 				struct ip_vs_dest *dest,
1192 				int svcupd)
1193 {
1194 	dest->flags &= ~IP_VS_DEST_F_AVAILABLE;
1195 
1196 	/*
1197 	 *  Remove it from the d-linked destination list.
1198 	 */
1199 	list_del_rcu(&dest->n_list);
1200 	svc->num_dests--;
1201 
1202 	if (dest->af != svc->af)
1203 		svc->ipvs->mixed_address_family_dests--;
1204 
1205 	if (svcupd) {
1206 		struct ip_vs_scheduler *sched;
1207 
1208 		sched = rcu_dereference_protected(svc->scheduler, 1);
1209 		if (sched && sched->del_dest)
1210 			sched->del_dest(svc, dest);
1211 	}
1212 }
1213 
1214 
1215 /*
1216  *	Delete a destination server in the given service
1217  */
1218 static int
ip_vs_del_dest(struct ip_vs_service * svc,struct ip_vs_dest_user_kern * udest)1219 ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest)
1220 {
1221 	struct ip_vs_dest *dest;
1222 	__be16 dport = udest->port;
1223 
1224 	EnterFunction(2);
1225 
1226 	/* We use function that requires RCU lock */
1227 	rcu_read_lock();
1228 	dest = ip_vs_lookup_dest(svc, udest->af, &udest->addr, dport);
1229 	rcu_read_unlock();
1230 
1231 	if (dest == NULL) {
1232 		IP_VS_DBG(1, "%s(): destination not found!\n", __func__);
1233 		return -ENOENT;
1234 	}
1235 
1236 	/*
1237 	 *	Unlink dest from the service
1238 	 */
1239 	__ip_vs_unlink_dest(svc, dest, 1);
1240 
1241 	/*
1242 	 *	Delete the destination
1243 	 */
1244 	__ip_vs_del_dest(svc->ipvs, dest, false);
1245 
1246 	LeaveFunction(2);
1247 
1248 	return 0;
1249 }
1250 
ip_vs_dest_trash_expire(struct timer_list * t)1251 static void ip_vs_dest_trash_expire(struct timer_list *t)
1252 {
1253 	struct netns_ipvs *ipvs = from_timer(ipvs, t, dest_trash_timer);
1254 	struct ip_vs_dest *dest, *next;
1255 	unsigned long now = jiffies;
1256 
1257 	spin_lock(&ipvs->dest_trash_lock);
1258 	list_for_each_entry_safe(dest, next, &ipvs->dest_trash, t_list) {
1259 		if (refcount_read(&dest->refcnt) > 1)
1260 			continue;
1261 		if (dest->idle_start) {
1262 			if (time_before(now, dest->idle_start +
1263 					     IP_VS_DEST_TRASH_PERIOD))
1264 				continue;
1265 		} else {
1266 			dest->idle_start = max(1UL, now);
1267 			continue;
1268 		}
1269 		IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u from trash\n",
1270 			      dest->vfwmark,
1271 			      IP_VS_DBG_ADDR(dest->af, &dest->addr),
1272 			      ntohs(dest->port));
1273 		list_del(&dest->t_list);
1274 		ip_vs_dest_free(dest);
1275 	}
1276 	if (!list_empty(&ipvs->dest_trash))
1277 		mod_timer(&ipvs->dest_trash_timer,
1278 			  jiffies + (IP_VS_DEST_TRASH_PERIOD >> 1));
1279 	spin_unlock(&ipvs->dest_trash_lock);
1280 }
1281 
1282 /*
1283  *	Add a service into the service hash table
1284  */
1285 static int
ip_vs_add_service(struct netns_ipvs * ipvs,struct ip_vs_service_user_kern * u,struct ip_vs_service ** svc_p)1286 ip_vs_add_service(struct netns_ipvs *ipvs, struct ip_vs_service_user_kern *u,
1287 		  struct ip_vs_service **svc_p)
1288 {
1289 	int ret = 0, i;
1290 	struct ip_vs_scheduler *sched = NULL;
1291 	struct ip_vs_pe *pe = NULL;
1292 	struct ip_vs_service *svc = NULL;
1293 	int ret_hooks = -1;
1294 
1295 	/* increase the module use count */
1296 	if (!ip_vs_use_count_inc())
1297 		return -ENOPROTOOPT;
1298 
1299 	/* Lookup the scheduler by 'u->sched_name' */
1300 	if (strcmp(u->sched_name, "none")) {
1301 		sched = ip_vs_scheduler_get(u->sched_name);
1302 		if (!sched) {
1303 			pr_info("Scheduler module ip_vs_%s not found\n",
1304 				u->sched_name);
1305 			ret = -ENOENT;
1306 			goto out_err;
1307 		}
1308 	}
1309 
1310 	if (u->pe_name && *u->pe_name) {
1311 		pe = ip_vs_pe_getbyname(u->pe_name);
1312 		if (pe == NULL) {
1313 			pr_info("persistence engine module ip_vs_pe_%s "
1314 				"not found\n", u->pe_name);
1315 			ret = -ENOENT;
1316 			goto out_err;
1317 		}
1318 	}
1319 
1320 #ifdef CONFIG_IP_VS_IPV6
1321 	if (u->af == AF_INET6) {
1322 		__u32 plen = (__force __u32) u->netmask;
1323 
1324 		if (plen < 1 || plen > 128) {
1325 			ret = -EINVAL;
1326 			goto out_err;
1327 		}
1328 
1329 		ret = nf_defrag_ipv6_enable(ipvs->net);
1330 		if (ret)
1331 			goto out_err;
1332 	}
1333 #endif
1334 
1335 	if ((u->af == AF_INET && !ipvs->num_services) ||
1336 	    (u->af == AF_INET6 && !ipvs->num_services6)) {
1337 		ret = ip_vs_register_hooks(ipvs, u->af);
1338 		if (ret < 0)
1339 			goto out_err;
1340 		ret_hooks = ret;
1341 	}
1342 
1343 	svc = kzalloc(sizeof(struct ip_vs_service), GFP_KERNEL);
1344 	if (svc == NULL) {
1345 		IP_VS_DBG(1, "%s(): no memory\n", __func__);
1346 		ret = -ENOMEM;
1347 		goto out_err;
1348 	}
1349 	svc->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
1350 	if (!svc->stats.cpustats) {
1351 		ret = -ENOMEM;
1352 		goto out_err;
1353 	}
1354 
1355 	for_each_possible_cpu(i) {
1356 		struct ip_vs_cpu_stats *ip_vs_stats;
1357 		ip_vs_stats = per_cpu_ptr(svc->stats.cpustats, i);
1358 		u64_stats_init(&ip_vs_stats->syncp);
1359 	}
1360 
1361 
1362 	/* I'm the first user of the service */
1363 	atomic_set(&svc->refcnt, 0);
1364 
1365 	svc->af = u->af;
1366 	svc->protocol = u->protocol;
1367 	ip_vs_addr_copy(svc->af, &svc->addr, &u->addr);
1368 	svc->port = u->port;
1369 	svc->fwmark = u->fwmark;
1370 	svc->flags = u->flags & ~IP_VS_SVC_F_HASHED;
1371 	svc->timeout = u->timeout * HZ;
1372 	svc->netmask = u->netmask;
1373 	svc->ipvs = ipvs;
1374 
1375 	INIT_LIST_HEAD(&svc->destinations);
1376 	spin_lock_init(&svc->sched_lock);
1377 	spin_lock_init(&svc->stats.lock);
1378 
1379 	/* Bind the scheduler */
1380 	if (sched) {
1381 		ret = ip_vs_bind_scheduler(svc, sched);
1382 		if (ret)
1383 			goto out_err;
1384 		sched = NULL;
1385 	}
1386 
1387 	/* Bind the ct retriever */
1388 	RCU_INIT_POINTER(svc->pe, pe);
1389 	pe = NULL;
1390 
1391 	/* Update the virtual service counters */
1392 	if (svc->port == FTPPORT)
1393 		atomic_inc(&ipvs->ftpsvc_counter);
1394 	else if (svc->port == 0)
1395 		atomic_inc(&ipvs->nullsvc_counter);
1396 	if (svc->pe && svc->pe->conn_out)
1397 		atomic_inc(&ipvs->conn_out_counter);
1398 
1399 	ip_vs_start_estimator(ipvs, &svc->stats);
1400 
1401 	/* Count only IPv4 services for old get/setsockopt interface */
1402 	if (svc->af == AF_INET)
1403 		ipvs->num_services++;
1404 	else if (svc->af == AF_INET6)
1405 		ipvs->num_services6++;
1406 
1407 	/* Hash the service into the service table */
1408 	ip_vs_svc_hash(svc);
1409 
1410 	*svc_p = svc;
1411 	/* Now there is a service - full throttle */
1412 	ipvs->enable = 1;
1413 	return 0;
1414 
1415 
1416  out_err:
1417 	if (ret_hooks >= 0)
1418 		ip_vs_unregister_hooks(ipvs, u->af);
1419 	if (svc != NULL) {
1420 		ip_vs_unbind_scheduler(svc, sched);
1421 		ip_vs_service_free(svc);
1422 	}
1423 	ip_vs_scheduler_put(sched);
1424 	ip_vs_pe_put(pe);
1425 
1426 	/* decrease the module use count */
1427 	ip_vs_use_count_dec();
1428 
1429 	return ret;
1430 }
1431 
1432 
1433 /*
1434  *	Edit a service and bind it with a new scheduler
1435  */
1436 static int
ip_vs_edit_service(struct ip_vs_service * svc,struct ip_vs_service_user_kern * u)1437 ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u)
1438 {
1439 	struct ip_vs_scheduler *sched = NULL, *old_sched;
1440 	struct ip_vs_pe *pe = NULL, *old_pe = NULL;
1441 	int ret = 0;
1442 	bool new_pe_conn_out, old_pe_conn_out;
1443 
1444 	/*
1445 	 * Lookup the scheduler, by 'u->sched_name'
1446 	 */
1447 	if (strcmp(u->sched_name, "none")) {
1448 		sched = ip_vs_scheduler_get(u->sched_name);
1449 		if (!sched) {
1450 			pr_info("Scheduler module ip_vs_%s not found\n",
1451 				u->sched_name);
1452 			return -ENOENT;
1453 		}
1454 	}
1455 	old_sched = sched;
1456 
1457 	if (u->pe_name && *u->pe_name) {
1458 		pe = ip_vs_pe_getbyname(u->pe_name);
1459 		if (pe == NULL) {
1460 			pr_info("persistence engine module ip_vs_pe_%s "
1461 				"not found\n", u->pe_name);
1462 			ret = -ENOENT;
1463 			goto out;
1464 		}
1465 		old_pe = pe;
1466 	}
1467 
1468 #ifdef CONFIG_IP_VS_IPV6
1469 	if (u->af == AF_INET6) {
1470 		__u32 plen = (__force __u32) u->netmask;
1471 
1472 		if (plen < 1 || plen > 128) {
1473 			ret = -EINVAL;
1474 			goto out;
1475 		}
1476 	}
1477 #endif
1478 
1479 	old_sched = rcu_dereference_protected(svc->scheduler, 1);
1480 	if (sched != old_sched) {
1481 		if (old_sched) {
1482 			ip_vs_unbind_scheduler(svc, old_sched);
1483 			RCU_INIT_POINTER(svc->scheduler, NULL);
1484 			/* Wait all svc->sched_data users */
1485 			synchronize_rcu();
1486 		}
1487 		/* Bind the new scheduler */
1488 		if (sched) {
1489 			ret = ip_vs_bind_scheduler(svc, sched);
1490 			if (ret) {
1491 				ip_vs_scheduler_put(sched);
1492 				goto out;
1493 			}
1494 		}
1495 	}
1496 
1497 	/*
1498 	 * Set the flags and timeout value
1499 	 */
1500 	svc->flags = u->flags | IP_VS_SVC_F_HASHED;
1501 	svc->timeout = u->timeout * HZ;
1502 	svc->netmask = u->netmask;
1503 
1504 	old_pe = rcu_dereference_protected(svc->pe, 1);
1505 	if (pe != old_pe) {
1506 		rcu_assign_pointer(svc->pe, pe);
1507 		/* check for optional methods in new pe */
1508 		new_pe_conn_out = (pe && pe->conn_out) ? true : false;
1509 		old_pe_conn_out = (old_pe && old_pe->conn_out) ? true : false;
1510 		if (new_pe_conn_out && !old_pe_conn_out)
1511 			atomic_inc(&svc->ipvs->conn_out_counter);
1512 		if (old_pe_conn_out && !new_pe_conn_out)
1513 			atomic_dec(&svc->ipvs->conn_out_counter);
1514 	}
1515 
1516 out:
1517 	ip_vs_scheduler_put(old_sched);
1518 	ip_vs_pe_put(old_pe);
1519 	return ret;
1520 }
1521 
1522 /*
1523  *	Delete a service from the service list
1524  *	- The service must be unlinked, unlocked and not referenced!
1525  *	- We are called under _bh lock
1526  */
__ip_vs_del_service(struct ip_vs_service * svc,bool cleanup)1527 static void __ip_vs_del_service(struct ip_vs_service *svc, bool cleanup)
1528 {
1529 	struct ip_vs_dest *dest, *nxt;
1530 	struct ip_vs_scheduler *old_sched;
1531 	struct ip_vs_pe *old_pe;
1532 	struct netns_ipvs *ipvs = svc->ipvs;
1533 
1534 	if (svc->af == AF_INET) {
1535 		ipvs->num_services--;
1536 		if (!ipvs->num_services)
1537 			ip_vs_unregister_hooks(ipvs, svc->af);
1538 	} else if (svc->af == AF_INET6) {
1539 		ipvs->num_services6--;
1540 		if (!ipvs->num_services6)
1541 			ip_vs_unregister_hooks(ipvs, svc->af);
1542 	}
1543 
1544 	ip_vs_stop_estimator(svc->ipvs, &svc->stats);
1545 
1546 	/* Unbind scheduler */
1547 	old_sched = rcu_dereference_protected(svc->scheduler, 1);
1548 	ip_vs_unbind_scheduler(svc, old_sched);
1549 	ip_vs_scheduler_put(old_sched);
1550 
1551 	/* Unbind persistence engine, keep svc->pe */
1552 	old_pe = rcu_dereference_protected(svc->pe, 1);
1553 	if (old_pe && old_pe->conn_out)
1554 		atomic_dec(&ipvs->conn_out_counter);
1555 	ip_vs_pe_put(old_pe);
1556 
1557 	/*
1558 	 *    Unlink the whole destination list
1559 	 */
1560 	list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) {
1561 		__ip_vs_unlink_dest(svc, dest, 0);
1562 		__ip_vs_del_dest(svc->ipvs, dest, cleanup);
1563 	}
1564 
1565 	/*
1566 	 *    Update the virtual service counters
1567 	 */
1568 	if (svc->port == FTPPORT)
1569 		atomic_dec(&ipvs->ftpsvc_counter);
1570 	else if (svc->port == 0)
1571 		atomic_dec(&ipvs->nullsvc_counter);
1572 
1573 	/*
1574 	 *    Free the service if nobody refers to it
1575 	 */
1576 	__ip_vs_svc_put(svc, true);
1577 
1578 	/* decrease the module use count */
1579 	ip_vs_use_count_dec();
1580 }
1581 
1582 /*
1583  * Unlink a service from list and try to delete it if its refcnt reached 0
1584  */
ip_vs_unlink_service(struct ip_vs_service * svc,bool cleanup)1585 static void ip_vs_unlink_service(struct ip_vs_service *svc, bool cleanup)
1586 {
1587 	ip_vs_unregister_conntrack(svc);
1588 	/* Hold svc to avoid double release from dest_trash */
1589 	atomic_inc(&svc->refcnt);
1590 	/*
1591 	 * Unhash it from the service table
1592 	 */
1593 	ip_vs_svc_unhash(svc);
1594 
1595 	__ip_vs_del_service(svc, cleanup);
1596 }
1597 
1598 /*
1599  *	Delete a service from the service list
1600  */
ip_vs_del_service(struct ip_vs_service * svc)1601 static int ip_vs_del_service(struct ip_vs_service *svc)
1602 {
1603 	if (svc == NULL)
1604 		return -EEXIST;
1605 	ip_vs_unlink_service(svc, false);
1606 
1607 	return 0;
1608 }
1609 
1610 
1611 /*
1612  *	Flush all the virtual services
1613  */
ip_vs_flush(struct netns_ipvs * ipvs,bool cleanup)1614 static int ip_vs_flush(struct netns_ipvs *ipvs, bool cleanup)
1615 {
1616 	int idx;
1617 	struct ip_vs_service *svc;
1618 	struct hlist_node *n;
1619 
1620 	/*
1621 	 * Flush the service table hashed by <netns,protocol,addr,port>
1622 	 */
1623 	for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1624 		hlist_for_each_entry_safe(svc, n, &ip_vs_svc_table[idx],
1625 					  s_list) {
1626 			if (svc->ipvs == ipvs)
1627 				ip_vs_unlink_service(svc, cleanup);
1628 		}
1629 	}
1630 
1631 	/*
1632 	 * Flush the service table hashed by fwmark
1633 	 */
1634 	for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1635 		hlist_for_each_entry_safe(svc, n, &ip_vs_svc_fwm_table[idx],
1636 					  f_list) {
1637 			if (svc->ipvs == ipvs)
1638 				ip_vs_unlink_service(svc, cleanup);
1639 		}
1640 	}
1641 
1642 	return 0;
1643 }
1644 
1645 /*
1646  *	Delete service by {netns} in the service table.
1647  *	Called by __ip_vs_batch_cleanup()
1648  */
ip_vs_service_nets_cleanup(struct list_head * net_list)1649 void ip_vs_service_nets_cleanup(struct list_head *net_list)
1650 {
1651 	struct netns_ipvs *ipvs;
1652 	struct net *net;
1653 
1654 	EnterFunction(2);
1655 	/* Check for "full" addressed entries */
1656 	mutex_lock(&__ip_vs_mutex);
1657 	list_for_each_entry(net, net_list, exit_list) {
1658 		ipvs = net_ipvs(net);
1659 		ip_vs_flush(ipvs, true);
1660 	}
1661 	mutex_unlock(&__ip_vs_mutex);
1662 	LeaveFunction(2);
1663 }
1664 
1665 /* Put all references for device (dst_cache) */
1666 static inline void
ip_vs_forget_dev(struct ip_vs_dest * dest,struct net_device * dev)1667 ip_vs_forget_dev(struct ip_vs_dest *dest, struct net_device *dev)
1668 {
1669 	struct ip_vs_dest_dst *dest_dst;
1670 
1671 	spin_lock_bh(&dest->dst_lock);
1672 	dest_dst = rcu_dereference_protected(dest->dest_dst, 1);
1673 	if (dest_dst && dest_dst->dst_cache->dev == dev) {
1674 		IP_VS_DBG_BUF(3, "Reset dev:%s dest %s:%u ,dest->refcnt=%d\n",
1675 			      dev->name,
1676 			      IP_VS_DBG_ADDR(dest->af, &dest->addr),
1677 			      ntohs(dest->port),
1678 			      refcount_read(&dest->refcnt));
1679 		__ip_vs_dst_cache_reset(dest);
1680 	}
1681 	spin_unlock_bh(&dest->dst_lock);
1682 
1683 }
1684 /* Netdev event receiver
1685  * Currently only NETDEV_DOWN is handled to release refs to cached dsts
1686  */
ip_vs_dst_event(struct notifier_block * this,unsigned long event,void * ptr)1687 static int ip_vs_dst_event(struct notifier_block *this, unsigned long event,
1688 			   void *ptr)
1689 {
1690 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
1691 	struct net *net = dev_net(dev);
1692 	struct netns_ipvs *ipvs = net_ipvs(net);
1693 	struct ip_vs_service *svc;
1694 	struct ip_vs_dest *dest;
1695 	unsigned int idx;
1696 
1697 	if (event != NETDEV_DOWN || !ipvs)
1698 		return NOTIFY_DONE;
1699 	IP_VS_DBG(3, "%s() dev=%s\n", __func__, dev->name);
1700 	EnterFunction(2);
1701 	mutex_lock(&__ip_vs_mutex);
1702 	for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1703 		hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1704 			if (svc->ipvs == ipvs) {
1705 				list_for_each_entry(dest, &svc->destinations,
1706 						    n_list) {
1707 					ip_vs_forget_dev(dest, dev);
1708 				}
1709 			}
1710 		}
1711 
1712 		hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1713 			if (svc->ipvs == ipvs) {
1714 				list_for_each_entry(dest, &svc->destinations,
1715 						    n_list) {
1716 					ip_vs_forget_dev(dest, dev);
1717 				}
1718 			}
1719 
1720 		}
1721 	}
1722 
1723 	spin_lock_bh(&ipvs->dest_trash_lock);
1724 	list_for_each_entry(dest, &ipvs->dest_trash, t_list) {
1725 		ip_vs_forget_dev(dest, dev);
1726 	}
1727 	spin_unlock_bh(&ipvs->dest_trash_lock);
1728 	mutex_unlock(&__ip_vs_mutex);
1729 	LeaveFunction(2);
1730 	return NOTIFY_DONE;
1731 }
1732 
1733 /*
1734  *	Zero counters in a service or all services
1735  */
ip_vs_zero_service(struct ip_vs_service * svc)1736 static int ip_vs_zero_service(struct ip_vs_service *svc)
1737 {
1738 	struct ip_vs_dest *dest;
1739 
1740 	list_for_each_entry(dest, &svc->destinations, n_list) {
1741 		ip_vs_zero_stats(&dest->stats);
1742 	}
1743 	ip_vs_zero_stats(&svc->stats);
1744 	return 0;
1745 }
1746 
ip_vs_zero_all(struct netns_ipvs * ipvs)1747 static int ip_vs_zero_all(struct netns_ipvs *ipvs)
1748 {
1749 	int idx;
1750 	struct ip_vs_service *svc;
1751 
1752 	for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1753 		hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
1754 			if (svc->ipvs == ipvs)
1755 				ip_vs_zero_service(svc);
1756 		}
1757 	}
1758 
1759 	for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
1760 		hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
1761 			if (svc->ipvs == ipvs)
1762 				ip_vs_zero_service(svc);
1763 		}
1764 	}
1765 
1766 	ip_vs_zero_stats(&ipvs->tot_stats);
1767 	return 0;
1768 }
1769 
1770 #ifdef CONFIG_SYSCTL
1771 
1772 static int three = 3;
1773 
1774 static int
proc_do_defense_mode(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)1775 proc_do_defense_mode(struct ctl_table *table, int write,
1776 		     void *buffer, size_t *lenp, loff_t *ppos)
1777 {
1778 	struct netns_ipvs *ipvs = table->extra2;
1779 	int *valp = table->data;
1780 	int val = *valp;
1781 	int rc;
1782 
1783 	struct ctl_table tmp = {
1784 		.data = &val,
1785 		.maxlen = sizeof(int),
1786 		.mode = table->mode,
1787 	};
1788 
1789 	rc = proc_dointvec(&tmp, write, buffer, lenp, ppos);
1790 	if (write && (*valp != val)) {
1791 		if (val < 0 || val > 3) {
1792 			rc = -EINVAL;
1793 		} else {
1794 			*valp = val;
1795 			update_defense_level(ipvs);
1796 		}
1797 	}
1798 	return rc;
1799 }
1800 
1801 static int
proc_do_sync_threshold(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)1802 proc_do_sync_threshold(struct ctl_table *table, int write,
1803 		       void *buffer, size_t *lenp, loff_t *ppos)
1804 {
1805 	struct netns_ipvs *ipvs = table->extra2;
1806 	int *valp = table->data;
1807 	int val[2];
1808 	int rc;
1809 	struct ctl_table tmp = {
1810 		.data = &val,
1811 		.maxlen = table->maxlen,
1812 		.mode = table->mode,
1813 	};
1814 
1815 	mutex_lock(&ipvs->sync_mutex);
1816 	memcpy(val, valp, sizeof(val));
1817 	rc = proc_dointvec(&tmp, write, buffer, lenp, ppos);
1818 	if (write) {
1819 		if (val[0] < 0 || val[1] < 0 ||
1820 		    (val[0] >= val[1] && val[1]))
1821 			rc = -EINVAL;
1822 		else
1823 			memcpy(valp, val, sizeof(val));
1824 	}
1825 	mutex_unlock(&ipvs->sync_mutex);
1826 	return rc;
1827 }
1828 
1829 static int
proc_do_sync_ports(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)1830 proc_do_sync_ports(struct ctl_table *table, int write,
1831 		   void *buffer, size_t *lenp, loff_t *ppos)
1832 {
1833 	int *valp = table->data;
1834 	int val = *valp;
1835 	int rc;
1836 
1837 	struct ctl_table tmp = {
1838 		.data = &val,
1839 		.maxlen = sizeof(int),
1840 		.mode = table->mode,
1841 	};
1842 
1843 	rc = proc_dointvec(&tmp, write, buffer, lenp, ppos);
1844 	if (write && (*valp != val)) {
1845 		if (val < 1 || !is_power_of_2(val))
1846 			rc = -EINVAL;
1847 		else
1848 			*valp = val;
1849 	}
1850 	return rc;
1851 }
1852 
1853 /*
1854  *	IPVS sysctl table (under the /proc/sys/net/ipv4/vs/)
1855  *	Do not change order or insert new entries without
1856  *	align with netns init in ip_vs_control_net_init()
1857  */
1858 
1859 static struct ctl_table vs_vars[] = {
1860 	{
1861 		.procname	= "amemthresh",
1862 		.maxlen		= sizeof(int),
1863 		.mode		= 0644,
1864 		.proc_handler	= proc_dointvec,
1865 	},
1866 	{
1867 		.procname	= "am_droprate",
1868 		.maxlen		= sizeof(int),
1869 		.mode		= 0644,
1870 		.proc_handler	= proc_dointvec,
1871 	},
1872 	{
1873 		.procname	= "drop_entry",
1874 		.maxlen		= sizeof(int),
1875 		.mode		= 0644,
1876 		.proc_handler	= proc_do_defense_mode,
1877 	},
1878 	{
1879 		.procname	= "drop_packet",
1880 		.maxlen		= sizeof(int),
1881 		.mode		= 0644,
1882 		.proc_handler	= proc_do_defense_mode,
1883 	},
1884 #ifdef CONFIG_IP_VS_NFCT
1885 	{
1886 		.procname	= "conntrack",
1887 		.maxlen		= sizeof(int),
1888 		.mode		= 0644,
1889 		.proc_handler	= &proc_dointvec,
1890 	},
1891 #endif
1892 	{
1893 		.procname	= "secure_tcp",
1894 		.maxlen		= sizeof(int),
1895 		.mode		= 0644,
1896 		.proc_handler	= proc_do_defense_mode,
1897 	},
1898 	{
1899 		.procname	= "snat_reroute",
1900 		.maxlen		= sizeof(int),
1901 		.mode		= 0644,
1902 		.proc_handler	= &proc_dointvec,
1903 	},
1904 	{
1905 		.procname	= "sync_version",
1906 		.maxlen		= sizeof(int),
1907 		.mode		= 0644,
1908 		.proc_handler	= proc_dointvec_minmax,
1909 		.extra1		= SYSCTL_ZERO,
1910 		.extra2		= SYSCTL_ONE,
1911 	},
1912 	{
1913 		.procname	= "sync_ports",
1914 		.maxlen		= sizeof(int),
1915 		.mode		= 0644,
1916 		.proc_handler	= proc_do_sync_ports,
1917 	},
1918 	{
1919 		.procname	= "sync_persist_mode",
1920 		.maxlen		= sizeof(int),
1921 		.mode		= 0644,
1922 		.proc_handler	= proc_dointvec,
1923 	},
1924 	{
1925 		.procname	= "sync_qlen_max",
1926 		.maxlen		= sizeof(unsigned long),
1927 		.mode		= 0644,
1928 		.proc_handler	= proc_doulongvec_minmax,
1929 	},
1930 	{
1931 		.procname	= "sync_sock_size",
1932 		.maxlen		= sizeof(int),
1933 		.mode		= 0644,
1934 		.proc_handler	= proc_dointvec,
1935 	},
1936 	{
1937 		.procname	= "cache_bypass",
1938 		.maxlen		= sizeof(int),
1939 		.mode		= 0644,
1940 		.proc_handler	= proc_dointvec,
1941 	},
1942 	{
1943 		.procname	= "expire_nodest_conn",
1944 		.maxlen		= sizeof(int),
1945 		.mode		= 0644,
1946 		.proc_handler	= proc_dointvec,
1947 	},
1948 	{
1949 		.procname	= "sloppy_tcp",
1950 		.maxlen		= sizeof(int),
1951 		.mode		= 0644,
1952 		.proc_handler	= proc_dointvec,
1953 	},
1954 	{
1955 		.procname	= "sloppy_sctp",
1956 		.maxlen		= sizeof(int),
1957 		.mode		= 0644,
1958 		.proc_handler	= proc_dointvec,
1959 	},
1960 	{
1961 		.procname	= "expire_quiescent_template",
1962 		.maxlen		= sizeof(int),
1963 		.mode		= 0644,
1964 		.proc_handler	= proc_dointvec,
1965 	},
1966 	{
1967 		.procname	= "sync_threshold",
1968 		.maxlen		=
1969 			sizeof(((struct netns_ipvs *)0)->sysctl_sync_threshold),
1970 		.mode		= 0644,
1971 		.proc_handler	= proc_do_sync_threshold,
1972 	},
1973 	{
1974 		.procname	= "sync_refresh_period",
1975 		.maxlen		= sizeof(int),
1976 		.mode		= 0644,
1977 		.proc_handler	= proc_dointvec_jiffies,
1978 	},
1979 	{
1980 		.procname	= "sync_retries",
1981 		.maxlen		= sizeof(int),
1982 		.mode		= 0644,
1983 		.proc_handler	= proc_dointvec_minmax,
1984 		.extra1		= SYSCTL_ZERO,
1985 		.extra2		= &three,
1986 	},
1987 	{
1988 		.procname	= "nat_icmp_send",
1989 		.maxlen		= sizeof(int),
1990 		.mode		= 0644,
1991 		.proc_handler	= proc_dointvec,
1992 	},
1993 	{
1994 		.procname	= "pmtu_disc",
1995 		.maxlen		= sizeof(int),
1996 		.mode		= 0644,
1997 		.proc_handler	= proc_dointvec,
1998 	},
1999 	{
2000 		.procname	= "backup_only",
2001 		.maxlen		= sizeof(int),
2002 		.mode		= 0644,
2003 		.proc_handler	= proc_dointvec,
2004 	},
2005 	{
2006 		.procname	= "conn_reuse_mode",
2007 		.maxlen		= sizeof(int),
2008 		.mode		= 0644,
2009 		.proc_handler	= proc_dointvec,
2010 	},
2011 	{
2012 		.procname	= "schedule_icmp",
2013 		.maxlen		= sizeof(int),
2014 		.mode		= 0644,
2015 		.proc_handler	= proc_dointvec,
2016 	},
2017 	{
2018 		.procname	= "ignore_tunneled",
2019 		.maxlen		= sizeof(int),
2020 		.mode		= 0644,
2021 		.proc_handler	= proc_dointvec,
2022 	},
2023 #ifdef CONFIG_IP_VS_DEBUG
2024 	{
2025 		.procname	= "debug_level",
2026 		.data		= &sysctl_ip_vs_debug_level,
2027 		.maxlen		= sizeof(int),
2028 		.mode		= 0644,
2029 		.proc_handler	= proc_dointvec,
2030 	},
2031 #endif
2032 	{ }
2033 };
2034 
2035 #endif
2036 
2037 #ifdef CONFIG_PROC_FS
2038 
2039 struct ip_vs_iter {
2040 	struct seq_net_private p;  /* Do not move this, netns depends upon it*/
2041 	struct hlist_head *table;
2042 	int bucket;
2043 };
2044 
2045 /*
2046  *	Write the contents of the VS rule table to a PROCfs file.
2047  *	(It is kept just for backward compatibility)
2048  */
ip_vs_fwd_name(unsigned int flags)2049 static inline const char *ip_vs_fwd_name(unsigned int flags)
2050 {
2051 	switch (flags & IP_VS_CONN_F_FWD_MASK) {
2052 	case IP_VS_CONN_F_LOCALNODE:
2053 		return "Local";
2054 	case IP_VS_CONN_F_TUNNEL:
2055 		return "Tunnel";
2056 	case IP_VS_CONN_F_DROUTE:
2057 		return "Route";
2058 	default:
2059 		return "Masq";
2060 	}
2061 }
2062 
2063 
2064 /* Get the Nth entry in the two lists */
ip_vs_info_array(struct seq_file * seq,loff_t pos)2065 static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos)
2066 {
2067 	struct net *net = seq_file_net(seq);
2068 	struct netns_ipvs *ipvs = net_ipvs(net);
2069 	struct ip_vs_iter *iter = seq->private;
2070 	int idx;
2071 	struct ip_vs_service *svc;
2072 
2073 	/* look in hash by protocol */
2074 	for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2075 		hlist_for_each_entry_rcu(svc, &ip_vs_svc_table[idx], s_list) {
2076 			if ((svc->ipvs == ipvs) && pos-- == 0) {
2077 				iter->table = ip_vs_svc_table;
2078 				iter->bucket = idx;
2079 				return svc;
2080 			}
2081 		}
2082 	}
2083 
2084 	/* keep looking in fwmark */
2085 	for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2086 		hlist_for_each_entry_rcu(svc, &ip_vs_svc_fwm_table[idx],
2087 					 f_list) {
2088 			if ((svc->ipvs == ipvs) && pos-- == 0) {
2089 				iter->table = ip_vs_svc_fwm_table;
2090 				iter->bucket = idx;
2091 				return svc;
2092 			}
2093 		}
2094 	}
2095 
2096 	return NULL;
2097 }
2098 
ip_vs_info_seq_start(struct seq_file * seq,loff_t * pos)2099 static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos)
2100 	__acquires(RCU)
2101 {
2102 	rcu_read_lock();
2103 	return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN;
2104 }
2105 
2106 
ip_vs_info_seq_next(struct seq_file * seq,void * v,loff_t * pos)2107 static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2108 {
2109 	struct hlist_node *e;
2110 	struct ip_vs_iter *iter;
2111 	struct ip_vs_service *svc;
2112 
2113 	++*pos;
2114 	if (v == SEQ_START_TOKEN)
2115 		return ip_vs_info_array(seq,0);
2116 
2117 	svc = v;
2118 	iter = seq->private;
2119 
2120 	if (iter->table == ip_vs_svc_table) {
2121 		/* next service in table hashed by protocol */
2122 		e = rcu_dereference(hlist_next_rcu(&svc->s_list));
2123 		if (e)
2124 			return hlist_entry(e, struct ip_vs_service, s_list);
2125 
2126 		while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
2127 			hlist_for_each_entry_rcu(svc,
2128 						 &ip_vs_svc_table[iter->bucket],
2129 						 s_list) {
2130 				return svc;
2131 			}
2132 		}
2133 
2134 		iter->table = ip_vs_svc_fwm_table;
2135 		iter->bucket = -1;
2136 		goto scan_fwmark;
2137 	}
2138 
2139 	/* next service in hashed by fwmark */
2140 	e = rcu_dereference(hlist_next_rcu(&svc->f_list));
2141 	if (e)
2142 		return hlist_entry(e, struct ip_vs_service, f_list);
2143 
2144  scan_fwmark:
2145 	while (++iter->bucket < IP_VS_SVC_TAB_SIZE) {
2146 		hlist_for_each_entry_rcu(svc,
2147 					 &ip_vs_svc_fwm_table[iter->bucket],
2148 					 f_list)
2149 			return svc;
2150 	}
2151 
2152 	return NULL;
2153 }
2154 
ip_vs_info_seq_stop(struct seq_file * seq,void * v)2155 static void ip_vs_info_seq_stop(struct seq_file *seq, void *v)
2156 	__releases(RCU)
2157 {
2158 	rcu_read_unlock();
2159 }
2160 
2161 
ip_vs_info_seq_show(struct seq_file * seq,void * v)2162 static int ip_vs_info_seq_show(struct seq_file *seq, void *v)
2163 {
2164 	if (v == SEQ_START_TOKEN) {
2165 		seq_printf(seq,
2166 			"IP Virtual Server version %d.%d.%d (size=%d)\n",
2167 			NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2168 		seq_puts(seq,
2169 			 "Prot LocalAddress:Port Scheduler Flags\n");
2170 		seq_puts(seq,
2171 			 "  -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n");
2172 	} else {
2173 		struct net *net = seq_file_net(seq);
2174 		struct netns_ipvs *ipvs = net_ipvs(net);
2175 		const struct ip_vs_service *svc = v;
2176 		const struct ip_vs_iter *iter = seq->private;
2177 		const struct ip_vs_dest *dest;
2178 		struct ip_vs_scheduler *sched = rcu_dereference(svc->scheduler);
2179 		char *sched_name = sched ? sched->name : "none";
2180 
2181 		if (svc->ipvs != ipvs)
2182 			return 0;
2183 		if (iter->table == ip_vs_svc_table) {
2184 #ifdef CONFIG_IP_VS_IPV6
2185 			if (svc->af == AF_INET6)
2186 				seq_printf(seq, "%s  [%pI6]:%04X %s ",
2187 					   ip_vs_proto_name(svc->protocol),
2188 					   &svc->addr.in6,
2189 					   ntohs(svc->port),
2190 					   sched_name);
2191 			else
2192 #endif
2193 				seq_printf(seq, "%s  %08X:%04X %s %s ",
2194 					   ip_vs_proto_name(svc->protocol),
2195 					   ntohl(svc->addr.ip),
2196 					   ntohs(svc->port),
2197 					   sched_name,
2198 					   (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2199 		} else {
2200 			seq_printf(seq, "FWM  %08X %s %s",
2201 				   svc->fwmark, sched_name,
2202 				   (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":"");
2203 		}
2204 
2205 		if (svc->flags & IP_VS_SVC_F_PERSISTENT)
2206 			seq_printf(seq, "persistent %d %08X\n",
2207 				svc->timeout,
2208 				ntohl(svc->netmask));
2209 		else
2210 			seq_putc(seq, '\n');
2211 
2212 		list_for_each_entry_rcu(dest, &svc->destinations, n_list) {
2213 #ifdef CONFIG_IP_VS_IPV6
2214 			if (dest->af == AF_INET6)
2215 				seq_printf(seq,
2216 					   "  -> [%pI6]:%04X"
2217 					   "      %-7s %-6d %-10d %-10d\n",
2218 					   &dest->addr.in6,
2219 					   ntohs(dest->port),
2220 					   ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2221 					   atomic_read(&dest->weight),
2222 					   atomic_read(&dest->activeconns),
2223 					   atomic_read(&dest->inactconns));
2224 			else
2225 #endif
2226 				seq_printf(seq,
2227 					   "  -> %08X:%04X      "
2228 					   "%-7s %-6d %-10d %-10d\n",
2229 					   ntohl(dest->addr.ip),
2230 					   ntohs(dest->port),
2231 					   ip_vs_fwd_name(atomic_read(&dest->conn_flags)),
2232 					   atomic_read(&dest->weight),
2233 					   atomic_read(&dest->activeconns),
2234 					   atomic_read(&dest->inactconns));
2235 
2236 		}
2237 	}
2238 	return 0;
2239 }
2240 
2241 static const struct seq_operations ip_vs_info_seq_ops = {
2242 	.start = ip_vs_info_seq_start,
2243 	.next  = ip_vs_info_seq_next,
2244 	.stop  = ip_vs_info_seq_stop,
2245 	.show  = ip_vs_info_seq_show,
2246 };
2247 
ip_vs_stats_show(struct seq_file * seq,void * v)2248 static int ip_vs_stats_show(struct seq_file *seq, void *v)
2249 {
2250 	struct net *net = seq_file_single_net(seq);
2251 	struct ip_vs_kstats show;
2252 
2253 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2254 	seq_puts(seq,
2255 		 "   Total Incoming Outgoing         Incoming         Outgoing\n");
2256 	seq_puts(seq,
2257 		 "   Conns  Packets  Packets            Bytes            Bytes\n");
2258 
2259 	ip_vs_copy_stats(&show, &net_ipvs(net)->tot_stats);
2260 	seq_printf(seq, "%8LX %8LX %8LX %16LX %16LX\n\n",
2261 		   (unsigned long long)show.conns,
2262 		   (unsigned long long)show.inpkts,
2263 		   (unsigned long long)show.outpkts,
2264 		   (unsigned long long)show.inbytes,
2265 		   (unsigned long long)show.outbytes);
2266 
2267 /*                01234567 01234567 01234567 0123456701234567 0123456701234567*/
2268 	seq_puts(seq,
2269 		 " Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2270 	seq_printf(seq, "%8LX %8LX %8LX %16LX %16LX\n",
2271 		   (unsigned long long)show.cps,
2272 		   (unsigned long long)show.inpps,
2273 		   (unsigned long long)show.outpps,
2274 		   (unsigned long long)show.inbps,
2275 		   (unsigned long long)show.outbps);
2276 
2277 	return 0;
2278 }
2279 
ip_vs_stats_percpu_show(struct seq_file * seq,void * v)2280 static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v)
2281 {
2282 	struct net *net = seq_file_single_net(seq);
2283 	struct ip_vs_stats *tot_stats = &net_ipvs(net)->tot_stats;
2284 	struct ip_vs_cpu_stats __percpu *cpustats = tot_stats->cpustats;
2285 	struct ip_vs_kstats kstats;
2286 	int i;
2287 
2288 /*               01234567 01234567 01234567 0123456701234567 0123456701234567 */
2289 	seq_puts(seq,
2290 		 "       Total Incoming Outgoing         Incoming         Outgoing\n");
2291 	seq_puts(seq,
2292 		 "CPU    Conns  Packets  Packets            Bytes            Bytes\n");
2293 
2294 	for_each_possible_cpu(i) {
2295 		struct ip_vs_cpu_stats *u = per_cpu_ptr(cpustats, i);
2296 		unsigned int start;
2297 		u64 conns, inpkts, outpkts, inbytes, outbytes;
2298 
2299 		do {
2300 			start = u64_stats_fetch_begin_irq(&u->syncp);
2301 			conns = u->cnt.conns;
2302 			inpkts = u->cnt.inpkts;
2303 			outpkts = u->cnt.outpkts;
2304 			inbytes = u->cnt.inbytes;
2305 			outbytes = u->cnt.outbytes;
2306 		} while (u64_stats_fetch_retry_irq(&u->syncp, start));
2307 
2308 		seq_printf(seq, "%3X %8LX %8LX %8LX %16LX %16LX\n",
2309 			   i, (u64)conns, (u64)inpkts,
2310 			   (u64)outpkts, (u64)inbytes,
2311 			   (u64)outbytes);
2312 	}
2313 
2314 	ip_vs_copy_stats(&kstats, tot_stats);
2315 
2316 	seq_printf(seq, "  ~ %8LX %8LX %8LX %16LX %16LX\n\n",
2317 		   (unsigned long long)kstats.conns,
2318 		   (unsigned long long)kstats.inpkts,
2319 		   (unsigned long long)kstats.outpkts,
2320 		   (unsigned long long)kstats.inbytes,
2321 		   (unsigned long long)kstats.outbytes);
2322 
2323 /*                ... 01234567 01234567 01234567 0123456701234567 0123456701234567 */
2324 	seq_puts(seq,
2325 		 "     Conns/s   Pkts/s   Pkts/s          Bytes/s          Bytes/s\n");
2326 	seq_printf(seq, "    %8LX %8LX %8LX %16LX %16LX\n",
2327 		   kstats.cps,
2328 		   kstats.inpps,
2329 		   kstats.outpps,
2330 		   kstats.inbps,
2331 		   kstats.outbps);
2332 
2333 	return 0;
2334 }
2335 #endif
2336 
2337 /*
2338  *	Set timeout values for tcp tcpfin udp in the timeout_table.
2339  */
ip_vs_set_timeout(struct netns_ipvs * ipvs,struct ip_vs_timeout_user * u)2340 static int ip_vs_set_timeout(struct netns_ipvs *ipvs, struct ip_vs_timeout_user *u)
2341 {
2342 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2343 	struct ip_vs_proto_data *pd;
2344 #endif
2345 
2346 	IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n",
2347 		  u->tcp_timeout,
2348 		  u->tcp_fin_timeout,
2349 		  u->udp_timeout);
2350 
2351 #ifdef CONFIG_IP_VS_PROTO_TCP
2352 	if (u->tcp_timeout < 0 || u->tcp_timeout > (INT_MAX / HZ) ||
2353 	    u->tcp_fin_timeout < 0 || u->tcp_fin_timeout > (INT_MAX / HZ)) {
2354 		return -EINVAL;
2355 	}
2356 #endif
2357 
2358 #ifdef CONFIG_IP_VS_PROTO_UDP
2359 	if (u->udp_timeout < 0 || u->udp_timeout > (INT_MAX / HZ))
2360 		return -EINVAL;
2361 #endif
2362 
2363 #ifdef CONFIG_IP_VS_PROTO_TCP
2364 	if (u->tcp_timeout) {
2365 		pd = ip_vs_proto_data_get(ipvs, IPPROTO_TCP);
2366 		pd->timeout_table[IP_VS_TCP_S_ESTABLISHED]
2367 			= u->tcp_timeout * HZ;
2368 	}
2369 
2370 	if (u->tcp_fin_timeout) {
2371 		pd = ip_vs_proto_data_get(ipvs, IPPROTO_TCP);
2372 		pd->timeout_table[IP_VS_TCP_S_FIN_WAIT]
2373 			= u->tcp_fin_timeout * HZ;
2374 	}
2375 #endif
2376 
2377 #ifdef CONFIG_IP_VS_PROTO_UDP
2378 	if (u->udp_timeout) {
2379 		pd = ip_vs_proto_data_get(ipvs, IPPROTO_UDP);
2380 		pd->timeout_table[IP_VS_UDP_S_NORMAL]
2381 			= u->udp_timeout * HZ;
2382 	}
2383 #endif
2384 	return 0;
2385 }
2386 
2387 #define CMDID(cmd)		(cmd - IP_VS_BASE_CTL)
2388 
2389 struct ip_vs_svcdest_user {
2390 	struct ip_vs_service_user	s;
2391 	struct ip_vs_dest_user		d;
2392 };
2393 
2394 static const unsigned char set_arglen[CMDID(IP_VS_SO_SET_MAX) + 1] = {
2395 	[CMDID(IP_VS_SO_SET_ADD)]         = sizeof(struct ip_vs_service_user),
2396 	[CMDID(IP_VS_SO_SET_EDIT)]        = sizeof(struct ip_vs_service_user),
2397 	[CMDID(IP_VS_SO_SET_DEL)]         = sizeof(struct ip_vs_service_user),
2398 	[CMDID(IP_VS_SO_SET_ADDDEST)]     = sizeof(struct ip_vs_svcdest_user),
2399 	[CMDID(IP_VS_SO_SET_DELDEST)]     = sizeof(struct ip_vs_svcdest_user),
2400 	[CMDID(IP_VS_SO_SET_EDITDEST)]    = sizeof(struct ip_vs_svcdest_user),
2401 	[CMDID(IP_VS_SO_SET_TIMEOUT)]     = sizeof(struct ip_vs_timeout_user),
2402 	[CMDID(IP_VS_SO_SET_STARTDAEMON)] = sizeof(struct ip_vs_daemon_user),
2403 	[CMDID(IP_VS_SO_SET_STOPDAEMON)]  = sizeof(struct ip_vs_daemon_user),
2404 	[CMDID(IP_VS_SO_SET_ZERO)]        = sizeof(struct ip_vs_service_user),
2405 };
2406 
2407 union ip_vs_set_arglen {
2408 	struct ip_vs_service_user	field_IP_VS_SO_SET_ADD;
2409 	struct ip_vs_service_user	field_IP_VS_SO_SET_EDIT;
2410 	struct ip_vs_service_user	field_IP_VS_SO_SET_DEL;
2411 	struct ip_vs_svcdest_user	field_IP_VS_SO_SET_ADDDEST;
2412 	struct ip_vs_svcdest_user	field_IP_VS_SO_SET_DELDEST;
2413 	struct ip_vs_svcdest_user	field_IP_VS_SO_SET_EDITDEST;
2414 	struct ip_vs_timeout_user	field_IP_VS_SO_SET_TIMEOUT;
2415 	struct ip_vs_daemon_user	field_IP_VS_SO_SET_STARTDAEMON;
2416 	struct ip_vs_daemon_user	field_IP_VS_SO_SET_STOPDAEMON;
2417 	struct ip_vs_service_user	field_IP_VS_SO_SET_ZERO;
2418 };
2419 
2420 #define MAX_SET_ARGLEN	sizeof(union ip_vs_set_arglen)
2421 
ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern * usvc,struct ip_vs_service_user * usvc_compat)2422 static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc,
2423 				  struct ip_vs_service_user *usvc_compat)
2424 {
2425 	memset(usvc, 0, sizeof(*usvc));
2426 
2427 	usvc->af		= AF_INET;
2428 	usvc->protocol		= usvc_compat->protocol;
2429 	usvc->addr.ip		= usvc_compat->addr;
2430 	usvc->port		= usvc_compat->port;
2431 	usvc->fwmark		= usvc_compat->fwmark;
2432 
2433 	/* Deep copy of sched_name is not needed here */
2434 	usvc->sched_name	= usvc_compat->sched_name;
2435 
2436 	usvc->flags		= usvc_compat->flags;
2437 	usvc->timeout		= usvc_compat->timeout;
2438 	usvc->netmask		= usvc_compat->netmask;
2439 }
2440 
ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern * udest,struct ip_vs_dest_user * udest_compat)2441 static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest,
2442 				   struct ip_vs_dest_user *udest_compat)
2443 {
2444 	memset(udest, 0, sizeof(*udest));
2445 
2446 	udest->addr.ip		= udest_compat->addr;
2447 	udest->port		= udest_compat->port;
2448 	udest->conn_flags	= udest_compat->conn_flags;
2449 	udest->weight		= udest_compat->weight;
2450 	udest->u_threshold	= udest_compat->u_threshold;
2451 	udest->l_threshold	= udest_compat->l_threshold;
2452 	udest->af		= AF_INET;
2453 	udest->tun_type		= IP_VS_CONN_F_TUNNEL_TYPE_IPIP;
2454 }
2455 
2456 static int
do_ip_vs_set_ctl(struct sock * sk,int cmd,sockptr_t ptr,unsigned int len)2457 do_ip_vs_set_ctl(struct sock *sk, int cmd, sockptr_t ptr, unsigned int len)
2458 {
2459 	struct net *net = sock_net(sk);
2460 	int ret;
2461 	unsigned char arg[MAX_SET_ARGLEN];
2462 	struct ip_vs_service_user *usvc_compat;
2463 	struct ip_vs_service_user_kern usvc;
2464 	struct ip_vs_service *svc;
2465 	struct ip_vs_dest_user *udest_compat;
2466 	struct ip_vs_dest_user_kern udest;
2467 	struct netns_ipvs *ipvs = net_ipvs(net);
2468 
2469 	BUILD_BUG_ON(sizeof(arg) > 255);
2470 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2471 		return -EPERM;
2472 
2473 	if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX)
2474 		return -EINVAL;
2475 	if (len != set_arglen[CMDID(cmd)]) {
2476 		IP_VS_DBG(1, "set_ctl: len %u != %u\n",
2477 			  len, set_arglen[CMDID(cmd)]);
2478 		return -EINVAL;
2479 	}
2480 
2481 	if (copy_from_sockptr(arg, ptr, len) != 0)
2482 		return -EFAULT;
2483 
2484 	/* Handle daemons since they have another lock */
2485 	if (cmd == IP_VS_SO_SET_STARTDAEMON ||
2486 	    cmd == IP_VS_SO_SET_STOPDAEMON) {
2487 		struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg;
2488 
2489 		if (cmd == IP_VS_SO_SET_STARTDAEMON) {
2490 			struct ipvs_sync_daemon_cfg cfg;
2491 
2492 			memset(&cfg, 0, sizeof(cfg));
2493 			ret = -EINVAL;
2494 			if (strscpy(cfg.mcast_ifn, dm->mcast_ifn,
2495 				    sizeof(cfg.mcast_ifn)) <= 0)
2496 				return ret;
2497 			cfg.syncid = dm->syncid;
2498 			ret = start_sync_thread(ipvs, &cfg, dm->state);
2499 		} else {
2500 			ret = stop_sync_thread(ipvs, dm->state);
2501 		}
2502 		return ret;
2503 	}
2504 
2505 	mutex_lock(&__ip_vs_mutex);
2506 	if (cmd == IP_VS_SO_SET_FLUSH) {
2507 		/* Flush the virtual service */
2508 		ret = ip_vs_flush(ipvs, false);
2509 		goto out_unlock;
2510 	} else if (cmd == IP_VS_SO_SET_TIMEOUT) {
2511 		/* Set timeout values for (tcp tcpfin udp) */
2512 		ret = ip_vs_set_timeout(ipvs, (struct ip_vs_timeout_user *)arg);
2513 		goto out_unlock;
2514 	} else if (!len) {
2515 		/* No more commands with len == 0 below */
2516 		ret = -EINVAL;
2517 		goto out_unlock;
2518 	}
2519 
2520 	usvc_compat = (struct ip_vs_service_user *)arg;
2521 	udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1);
2522 
2523 	/* We only use the new structs internally, so copy userspace compat
2524 	 * structs to extended internal versions */
2525 	ip_vs_copy_usvc_compat(&usvc, usvc_compat);
2526 	ip_vs_copy_udest_compat(&udest, udest_compat);
2527 
2528 	if (cmd == IP_VS_SO_SET_ZERO) {
2529 		/* if no service address is set, zero counters in all */
2530 		if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) {
2531 			ret = ip_vs_zero_all(ipvs);
2532 			goto out_unlock;
2533 		}
2534 	}
2535 
2536 	if ((cmd == IP_VS_SO_SET_ADD || cmd == IP_VS_SO_SET_EDIT) &&
2537 	    strnlen(usvc.sched_name, IP_VS_SCHEDNAME_MAXLEN) ==
2538 	    IP_VS_SCHEDNAME_MAXLEN) {
2539 		ret = -EINVAL;
2540 		goto out_unlock;
2541 	}
2542 
2543 	/* Check for valid protocol: TCP or UDP or SCTP, even for fwmark!=0 */
2544 	if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP &&
2545 	    usvc.protocol != IPPROTO_SCTP) {
2546 		pr_err("set_ctl: invalid protocol: %d %pI4:%d\n",
2547 		       usvc.protocol, &usvc.addr.ip,
2548 		       ntohs(usvc.port));
2549 		ret = -EFAULT;
2550 		goto out_unlock;
2551 	}
2552 
2553 	/* Lookup the exact service by <protocol, addr, port> or fwmark */
2554 	rcu_read_lock();
2555 	if (usvc.fwmark == 0)
2556 		svc = __ip_vs_service_find(ipvs, usvc.af, usvc.protocol,
2557 					   &usvc.addr, usvc.port);
2558 	else
2559 		svc = __ip_vs_svc_fwm_find(ipvs, usvc.af, usvc.fwmark);
2560 	rcu_read_unlock();
2561 
2562 	if (cmd != IP_VS_SO_SET_ADD
2563 	    && (svc == NULL || svc->protocol != usvc.protocol)) {
2564 		ret = -ESRCH;
2565 		goto out_unlock;
2566 	}
2567 
2568 	switch (cmd) {
2569 	case IP_VS_SO_SET_ADD:
2570 		if (svc != NULL)
2571 			ret = -EEXIST;
2572 		else
2573 			ret = ip_vs_add_service(ipvs, &usvc, &svc);
2574 		break;
2575 	case IP_VS_SO_SET_EDIT:
2576 		ret = ip_vs_edit_service(svc, &usvc);
2577 		break;
2578 	case IP_VS_SO_SET_DEL:
2579 		ret = ip_vs_del_service(svc);
2580 		if (!ret)
2581 			goto out_unlock;
2582 		break;
2583 	case IP_VS_SO_SET_ZERO:
2584 		ret = ip_vs_zero_service(svc);
2585 		break;
2586 	case IP_VS_SO_SET_ADDDEST:
2587 		ret = ip_vs_add_dest(svc, &udest);
2588 		break;
2589 	case IP_VS_SO_SET_EDITDEST:
2590 		ret = ip_vs_edit_dest(svc, &udest);
2591 		break;
2592 	case IP_VS_SO_SET_DELDEST:
2593 		ret = ip_vs_del_dest(svc, &udest);
2594 	}
2595 
2596   out_unlock:
2597 	mutex_unlock(&__ip_vs_mutex);
2598 	return ret;
2599 }
2600 
2601 
2602 static void
ip_vs_copy_service(struct ip_vs_service_entry * dst,struct ip_vs_service * src)2603 ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src)
2604 {
2605 	struct ip_vs_scheduler *sched;
2606 	struct ip_vs_kstats kstats;
2607 	char *sched_name;
2608 
2609 	sched = rcu_dereference_protected(src->scheduler, 1);
2610 	sched_name = sched ? sched->name : "none";
2611 	dst->protocol = src->protocol;
2612 	dst->addr = src->addr.ip;
2613 	dst->port = src->port;
2614 	dst->fwmark = src->fwmark;
2615 	strlcpy(dst->sched_name, sched_name, sizeof(dst->sched_name));
2616 	dst->flags = src->flags;
2617 	dst->timeout = src->timeout / HZ;
2618 	dst->netmask = src->netmask;
2619 	dst->num_dests = src->num_dests;
2620 	ip_vs_copy_stats(&kstats, &src->stats);
2621 	ip_vs_export_stats_user(&dst->stats, &kstats);
2622 }
2623 
2624 static inline int
__ip_vs_get_service_entries(struct netns_ipvs * ipvs,const struct ip_vs_get_services * get,struct ip_vs_get_services __user * uptr)2625 __ip_vs_get_service_entries(struct netns_ipvs *ipvs,
2626 			    const struct ip_vs_get_services *get,
2627 			    struct ip_vs_get_services __user *uptr)
2628 {
2629 	int idx, count=0;
2630 	struct ip_vs_service *svc;
2631 	struct ip_vs_service_entry entry;
2632 	int ret = 0;
2633 
2634 	for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2635 		hlist_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) {
2636 			/* Only expose IPv4 entries to old interface */
2637 			if (svc->af != AF_INET || (svc->ipvs != ipvs))
2638 				continue;
2639 
2640 			if (count >= get->num_services)
2641 				goto out;
2642 			memset(&entry, 0, sizeof(entry));
2643 			ip_vs_copy_service(&entry, svc);
2644 			if (copy_to_user(&uptr->entrytable[count],
2645 					 &entry, sizeof(entry))) {
2646 				ret = -EFAULT;
2647 				goto out;
2648 			}
2649 			count++;
2650 		}
2651 	}
2652 
2653 	for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
2654 		hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) {
2655 			/* Only expose IPv4 entries to old interface */
2656 			if (svc->af != AF_INET || (svc->ipvs != ipvs))
2657 				continue;
2658 
2659 			if (count >= get->num_services)
2660 				goto out;
2661 			memset(&entry, 0, sizeof(entry));
2662 			ip_vs_copy_service(&entry, svc);
2663 			if (copy_to_user(&uptr->entrytable[count],
2664 					 &entry, sizeof(entry))) {
2665 				ret = -EFAULT;
2666 				goto out;
2667 			}
2668 			count++;
2669 		}
2670 	}
2671 out:
2672 	return ret;
2673 }
2674 
2675 static inline int
__ip_vs_get_dest_entries(struct netns_ipvs * ipvs,const struct ip_vs_get_dests * get,struct ip_vs_get_dests __user * uptr)2676 __ip_vs_get_dest_entries(struct netns_ipvs *ipvs, const struct ip_vs_get_dests *get,
2677 			 struct ip_vs_get_dests __user *uptr)
2678 {
2679 	struct ip_vs_service *svc;
2680 	union nf_inet_addr addr = { .ip = get->addr };
2681 	int ret = 0;
2682 
2683 	rcu_read_lock();
2684 	if (get->fwmark)
2685 		svc = __ip_vs_svc_fwm_find(ipvs, AF_INET, get->fwmark);
2686 	else
2687 		svc = __ip_vs_service_find(ipvs, AF_INET, get->protocol, &addr,
2688 					   get->port);
2689 	rcu_read_unlock();
2690 
2691 	if (svc) {
2692 		int count = 0;
2693 		struct ip_vs_dest *dest;
2694 		struct ip_vs_dest_entry entry;
2695 		struct ip_vs_kstats kstats;
2696 
2697 		memset(&entry, 0, sizeof(entry));
2698 		list_for_each_entry(dest, &svc->destinations, n_list) {
2699 			if (count >= get->num_dests)
2700 				break;
2701 
2702 			/* Cannot expose heterogeneous members via sockopt
2703 			 * interface
2704 			 */
2705 			if (dest->af != svc->af)
2706 				continue;
2707 
2708 			entry.addr = dest->addr.ip;
2709 			entry.port = dest->port;
2710 			entry.conn_flags = atomic_read(&dest->conn_flags);
2711 			entry.weight = atomic_read(&dest->weight);
2712 			entry.u_threshold = dest->u_threshold;
2713 			entry.l_threshold = dest->l_threshold;
2714 			entry.activeconns = atomic_read(&dest->activeconns);
2715 			entry.inactconns = atomic_read(&dest->inactconns);
2716 			entry.persistconns = atomic_read(&dest->persistconns);
2717 			ip_vs_copy_stats(&kstats, &dest->stats);
2718 			ip_vs_export_stats_user(&entry.stats, &kstats);
2719 			if (copy_to_user(&uptr->entrytable[count],
2720 					 &entry, sizeof(entry))) {
2721 				ret = -EFAULT;
2722 				break;
2723 			}
2724 			count++;
2725 		}
2726 	} else
2727 		ret = -ESRCH;
2728 	return ret;
2729 }
2730 
2731 static inline void
__ip_vs_get_timeouts(struct netns_ipvs * ipvs,struct ip_vs_timeout_user * u)2732 __ip_vs_get_timeouts(struct netns_ipvs *ipvs, struct ip_vs_timeout_user *u)
2733 {
2734 #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP)
2735 	struct ip_vs_proto_data *pd;
2736 #endif
2737 
2738 	memset(u, 0, sizeof (*u));
2739 
2740 #ifdef CONFIG_IP_VS_PROTO_TCP
2741 	pd = ip_vs_proto_data_get(ipvs, IPPROTO_TCP);
2742 	u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ;
2743 	u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ;
2744 #endif
2745 #ifdef CONFIG_IP_VS_PROTO_UDP
2746 	pd = ip_vs_proto_data_get(ipvs, IPPROTO_UDP);
2747 	u->udp_timeout =
2748 			pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ;
2749 #endif
2750 }
2751 
2752 static const unsigned char get_arglen[CMDID(IP_VS_SO_GET_MAX) + 1] = {
2753 	[CMDID(IP_VS_SO_GET_VERSION)]  = 64,
2754 	[CMDID(IP_VS_SO_GET_INFO)]     = sizeof(struct ip_vs_getinfo),
2755 	[CMDID(IP_VS_SO_GET_SERVICES)] = sizeof(struct ip_vs_get_services),
2756 	[CMDID(IP_VS_SO_GET_SERVICE)]  = sizeof(struct ip_vs_service_entry),
2757 	[CMDID(IP_VS_SO_GET_DESTS)]    = sizeof(struct ip_vs_get_dests),
2758 	[CMDID(IP_VS_SO_GET_TIMEOUT)]  = sizeof(struct ip_vs_timeout_user),
2759 	[CMDID(IP_VS_SO_GET_DAEMON)]   = 2 * sizeof(struct ip_vs_daemon_user),
2760 };
2761 
2762 union ip_vs_get_arglen {
2763 	char				field_IP_VS_SO_GET_VERSION[64];
2764 	struct ip_vs_getinfo		field_IP_VS_SO_GET_INFO;
2765 	struct ip_vs_get_services	field_IP_VS_SO_GET_SERVICES;
2766 	struct ip_vs_service_entry	field_IP_VS_SO_GET_SERVICE;
2767 	struct ip_vs_get_dests		field_IP_VS_SO_GET_DESTS;
2768 	struct ip_vs_timeout_user	field_IP_VS_SO_GET_TIMEOUT;
2769 	struct ip_vs_daemon_user	field_IP_VS_SO_GET_DAEMON[2];
2770 };
2771 
2772 #define MAX_GET_ARGLEN	sizeof(union ip_vs_get_arglen)
2773 
2774 static int
do_ip_vs_get_ctl(struct sock * sk,int cmd,void __user * user,int * len)2775 do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len)
2776 {
2777 	unsigned char arg[MAX_GET_ARGLEN];
2778 	int ret = 0;
2779 	unsigned int copylen;
2780 	struct net *net = sock_net(sk);
2781 	struct netns_ipvs *ipvs = net_ipvs(net);
2782 
2783 	BUG_ON(!net);
2784 	BUILD_BUG_ON(sizeof(arg) > 255);
2785 	if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2786 		return -EPERM;
2787 
2788 	if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX)
2789 		return -EINVAL;
2790 
2791 	copylen = get_arglen[CMDID(cmd)];
2792 	if (*len < (int) copylen) {
2793 		IP_VS_DBG(1, "get_ctl: len %d < %u\n", *len, copylen);
2794 		return -EINVAL;
2795 	}
2796 
2797 	if (copy_from_user(arg, user, copylen) != 0)
2798 		return -EFAULT;
2799 	/*
2800 	 * Handle daemons first since it has its own locking
2801 	 */
2802 	if (cmd == IP_VS_SO_GET_DAEMON) {
2803 		struct ip_vs_daemon_user d[2];
2804 
2805 		memset(&d, 0, sizeof(d));
2806 		mutex_lock(&ipvs->sync_mutex);
2807 		if (ipvs->sync_state & IP_VS_STATE_MASTER) {
2808 			d[0].state = IP_VS_STATE_MASTER;
2809 			strlcpy(d[0].mcast_ifn, ipvs->mcfg.mcast_ifn,
2810 				sizeof(d[0].mcast_ifn));
2811 			d[0].syncid = ipvs->mcfg.syncid;
2812 		}
2813 		if (ipvs->sync_state & IP_VS_STATE_BACKUP) {
2814 			d[1].state = IP_VS_STATE_BACKUP;
2815 			strlcpy(d[1].mcast_ifn, ipvs->bcfg.mcast_ifn,
2816 				sizeof(d[1].mcast_ifn));
2817 			d[1].syncid = ipvs->bcfg.syncid;
2818 		}
2819 		if (copy_to_user(user, &d, sizeof(d)) != 0)
2820 			ret = -EFAULT;
2821 		mutex_unlock(&ipvs->sync_mutex);
2822 		return ret;
2823 	}
2824 
2825 	mutex_lock(&__ip_vs_mutex);
2826 	switch (cmd) {
2827 	case IP_VS_SO_GET_VERSION:
2828 	{
2829 		char buf[64];
2830 
2831 		sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)",
2832 			NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size);
2833 		if (copy_to_user(user, buf, strlen(buf)+1) != 0) {
2834 			ret = -EFAULT;
2835 			goto out;
2836 		}
2837 		*len = strlen(buf)+1;
2838 	}
2839 	break;
2840 
2841 	case IP_VS_SO_GET_INFO:
2842 	{
2843 		struct ip_vs_getinfo info;
2844 		info.version = IP_VS_VERSION_CODE;
2845 		info.size = ip_vs_conn_tab_size;
2846 		info.num_services = ipvs->num_services;
2847 		if (copy_to_user(user, &info, sizeof(info)) != 0)
2848 			ret = -EFAULT;
2849 	}
2850 	break;
2851 
2852 	case IP_VS_SO_GET_SERVICES:
2853 	{
2854 		struct ip_vs_get_services *get;
2855 		int size;
2856 
2857 		get = (struct ip_vs_get_services *)arg;
2858 		size = struct_size(get, entrytable, get->num_services);
2859 		if (*len != size) {
2860 			pr_err("length: %u != %u\n", *len, size);
2861 			ret = -EINVAL;
2862 			goto out;
2863 		}
2864 		ret = __ip_vs_get_service_entries(ipvs, get, user);
2865 	}
2866 	break;
2867 
2868 	case IP_VS_SO_GET_SERVICE:
2869 	{
2870 		struct ip_vs_service_entry *entry;
2871 		struct ip_vs_service *svc;
2872 		union nf_inet_addr addr;
2873 
2874 		entry = (struct ip_vs_service_entry *)arg;
2875 		addr.ip = entry->addr;
2876 		rcu_read_lock();
2877 		if (entry->fwmark)
2878 			svc = __ip_vs_svc_fwm_find(ipvs, AF_INET, entry->fwmark);
2879 		else
2880 			svc = __ip_vs_service_find(ipvs, AF_INET,
2881 						   entry->protocol, &addr,
2882 						   entry->port);
2883 		rcu_read_unlock();
2884 		if (svc) {
2885 			ip_vs_copy_service(entry, svc);
2886 			if (copy_to_user(user, entry, sizeof(*entry)) != 0)
2887 				ret = -EFAULT;
2888 		} else
2889 			ret = -ESRCH;
2890 	}
2891 	break;
2892 
2893 	case IP_VS_SO_GET_DESTS:
2894 	{
2895 		struct ip_vs_get_dests *get;
2896 		int size;
2897 
2898 		get = (struct ip_vs_get_dests *)arg;
2899 		size = struct_size(get, entrytable, get->num_dests);
2900 		if (*len != size) {
2901 			pr_err("length: %u != %u\n", *len, size);
2902 			ret = -EINVAL;
2903 			goto out;
2904 		}
2905 		ret = __ip_vs_get_dest_entries(ipvs, get, user);
2906 	}
2907 	break;
2908 
2909 	case IP_VS_SO_GET_TIMEOUT:
2910 	{
2911 		struct ip_vs_timeout_user t;
2912 
2913 		__ip_vs_get_timeouts(ipvs, &t);
2914 		if (copy_to_user(user, &t, sizeof(t)) != 0)
2915 			ret = -EFAULT;
2916 	}
2917 	break;
2918 
2919 	default:
2920 		ret = -EINVAL;
2921 	}
2922 
2923 out:
2924 	mutex_unlock(&__ip_vs_mutex);
2925 	return ret;
2926 }
2927 
2928 
2929 static struct nf_sockopt_ops ip_vs_sockopts = {
2930 	.pf		= PF_INET,
2931 	.set_optmin	= IP_VS_BASE_CTL,
2932 	.set_optmax	= IP_VS_SO_SET_MAX+1,
2933 	.set		= do_ip_vs_set_ctl,
2934 	.get_optmin	= IP_VS_BASE_CTL,
2935 	.get_optmax	= IP_VS_SO_GET_MAX+1,
2936 	.get		= do_ip_vs_get_ctl,
2937 	.owner		= THIS_MODULE,
2938 };
2939 
2940 /*
2941  * Generic Netlink interface
2942  */
2943 
2944 /* IPVS genetlink family */
2945 static struct genl_family ip_vs_genl_family;
2946 
2947 /* Policy used for first-level command attributes */
2948 static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = {
2949 	[IPVS_CMD_ATTR_SERVICE]		= { .type = NLA_NESTED },
2950 	[IPVS_CMD_ATTR_DEST]		= { .type = NLA_NESTED },
2951 	[IPVS_CMD_ATTR_DAEMON]		= { .type = NLA_NESTED },
2952 	[IPVS_CMD_ATTR_TIMEOUT_TCP]	= { .type = NLA_U32 },
2953 	[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]	= { .type = NLA_U32 },
2954 	[IPVS_CMD_ATTR_TIMEOUT_UDP]	= { .type = NLA_U32 },
2955 };
2956 
2957 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */
2958 static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = {
2959 	[IPVS_DAEMON_ATTR_STATE]	= { .type = NLA_U32 },
2960 	[IPVS_DAEMON_ATTR_MCAST_IFN]	= { .type = NLA_NUL_STRING,
2961 					    .len = IP_VS_IFNAME_MAXLEN - 1 },
2962 	[IPVS_DAEMON_ATTR_SYNC_ID]	= { .type = NLA_U32 },
2963 	[IPVS_DAEMON_ATTR_SYNC_MAXLEN]	= { .type = NLA_U16 },
2964 	[IPVS_DAEMON_ATTR_MCAST_GROUP]	= { .type = NLA_U32 },
2965 	[IPVS_DAEMON_ATTR_MCAST_GROUP6]	= { .len = sizeof(struct in6_addr) },
2966 	[IPVS_DAEMON_ATTR_MCAST_PORT]	= { .type = NLA_U16 },
2967 	[IPVS_DAEMON_ATTR_MCAST_TTL]	= { .type = NLA_U8 },
2968 };
2969 
2970 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */
2971 static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = {
2972 	[IPVS_SVC_ATTR_AF]		= { .type = NLA_U16 },
2973 	[IPVS_SVC_ATTR_PROTOCOL]	= { .type = NLA_U16 },
2974 	[IPVS_SVC_ATTR_ADDR]		= { .type = NLA_BINARY,
2975 					    .len = sizeof(union nf_inet_addr) },
2976 	[IPVS_SVC_ATTR_PORT]		= { .type = NLA_U16 },
2977 	[IPVS_SVC_ATTR_FWMARK]		= { .type = NLA_U32 },
2978 	[IPVS_SVC_ATTR_SCHED_NAME]	= { .type = NLA_NUL_STRING,
2979 					    .len = IP_VS_SCHEDNAME_MAXLEN - 1 },
2980 	[IPVS_SVC_ATTR_PE_NAME]		= { .type = NLA_NUL_STRING,
2981 					    .len = IP_VS_PENAME_MAXLEN },
2982 	[IPVS_SVC_ATTR_FLAGS]		= { .type = NLA_BINARY,
2983 					    .len = sizeof(struct ip_vs_flags) },
2984 	[IPVS_SVC_ATTR_TIMEOUT]		= { .type = NLA_U32 },
2985 	[IPVS_SVC_ATTR_NETMASK]		= { .type = NLA_U32 },
2986 	[IPVS_SVC_ATTR_STATS]		= { .type = NLA_NESTED },
2987 };
2988 
2989 /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */
2990 static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = {
2991 	[IPVS_DEST_ATTR_ADDR]		= { .type = NLA_BINARY,
2992 					    .len = sizeof(union nf_inet_addr) },
2993 	[IPVS_DEST_ATTR_PORT]		= { .type = NLA_U16 },
2994 	[IPVS_DEST_ATTR_FWD_METHOD]	= { .type = NLA_U32 },
2995 	[IPVS_DEST_ATTR_WEIGHT]		= { .type = NLA_U32 },
2996 	[IPVS_DEST_ATTR_U_THRESH]	= { .type = NLA_U32 },
2997 	[IPVS_DEST_ATTR_L_THRESH]	= { .type = NLA_U32 },
2998 	[IPVS_DEST_ATTR_ACTIVE_CONNS]	= { .type = NLA_U32 },
2999 	[IPVS_DEST_ATTR_INACT_CONNS]	= { .type = NLA_U32 },
3000 	[IPVS_DEST_ATTR_PERSIST_CONNS]	= { .type = NLA_U32 },
3001 	[IPVS_DEST_ATTR_STATS]		= { .type = NLA_NESTED },
3002 	[IPVS_DEST_ATTR_ADDR_FAMILY]	= { .type = NLA_U16 },
3003 	[IPVS_DEST_ATTR_TUN_TYPE]	= { .type = NLA_U8 },
3004 	[IPVS_DEST_ATTR_TUN_PORT]	= { .type = NLA_U16 },
3005 	[IPVS_DEST_ATTR_TUN_FLAGS]	= { .type = NLA_U16 },
3006 };
3007 
ip_vs_genl_fill_stats(struct sk_buff * skb,int container_type,struct ip_vs_kstats * kstats)3008 static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type,
3009 				 struct ip_vs_kstats *kstats)
3010 {
3011 	struct nlattr *nl_stats = nla_nest_start_noflag(skb, container_type);
3012 
3013 	if (!nl_stats)
3014 		return -EMSGSIZE;
3015 
3016 	if (nla_put_u32(skb, IPVS_STATS_ATTR_CONNS, (u32)kstats->conns) ||
3017 	    nla_put_u32(skb, IPVS_STATS_ATTR_INPKTS, (u32)kstats->inpkts) ||
3018 	    nla_put_u32(skb, IPVS_STATS_ATTR_OUTPKTS, (u32)kstats->outpkts) ||
3019 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INBYTES, kstats->inbytes,
3020 			      IPVS_STATS_ATTR_PAD) ||
3021 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTBYTES, kstats->outbytes,
3022 			      IPVS_STATS_ATTR_PAD) ||
3023 	    nla_put_u32(skb, IPVS_STATS_ATTR_CPS, (u32)kstats->cps) ||
3024 	    nla_put_u32(skb, IPVS_STATS_ATTR_INPPS, (u32)kstats->inpps) ||
3025 	    nla_put_u32(skb, IPVS_STATS_ATTR_OUTPPS, (u32)kstats->outpps) ||
3026 	    nla_put_u32(skb, IPVS_STATS_ATTR_INBPS, (u32)kstats->inbps) ||
3027 	    nla_put_u32(skb, IPVS_STATS_ATTR_OUTBPS, (u32)kstats->outbps))
3028 		goto nla_put_failure;
3029 	nla_nest_end(skb, nl_stats);
3030 
3031 	return 0;
3032 
3033 nla_put_failure:
3034 	nla_nest_cancel(skb, nl_stats);
3035 	return -EMSGSIZE;
3036 }
3037 
ip_vs_genl_fill_stats64(struct sk_buff * skb,int container_type,struct ip_vs_kstats * kstats)3038 static int ip_vs_genl_fill_stats64(struct sk_buff *skb, int container_type,
3039 				   struct ip_vs_kstats *kstats)
3040 {
3041 	struct nlattr *nl_stats = nla_nest_start_noflag(skb, container_type);
3042 
3043 	if (!nl_stats)
3044 		return -EMSGSIZE;
3045 
3046 	if (nla_put_u64_64bit(skb, IPVS_STATS_ATTR_CONNS, kstats->conns,
3047 			      IPVS_STATS_ATTR_PAD) ||
3048 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INPKTS, kstats->inpkts,
3049 			      IPVS_STATS_ATTR_PAD) ||
3050 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTPKTS, kstats->outpkts,
3051 			      IPVS_STATS_ATTR_PAD) ||
3052 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INBYTES, kstats->inbytes,
3053 			      IPVS_STATS_ATTR_PAD) ||
3054 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTBYTES, kstats->outbytes,
3055 			      IPVS_STATS_ATTR_PAD) ||
3056 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_CPS, kstats->cps,
3057 			      IPVS_STATS_ATTR_PAD) ||
3058 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INPPS, kstats->inpps,
3059 			      IPVS_STATS_ATTR_PAD) ||
3060 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTPPS, kstats->outpps,
3061 			      IPVS_STATS_ATTR_PAD) ||
3062 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_INBPS, kstats->inbps,
3063 			      IPVS_STATS_ATTR_PAD) ||
3064 	    nla_put_u64_64bit(skb, IPVS_STATS_ATTR_OUTBPS, kstats->outbps,
3065 			      IPVS_STATS_ATTR_PAD))
3066 		goto nla_put_failure;
3067 	nla_nest_end(skb, nl_stats);
3068 
3069 	return 0;
3070 
3071 nla_put_failure:
3072 	nla_nest_cancel(skb, nl_stats);
3073 	return -EMSGSIZE;
3074 }
3075 
ip_vs_genl_fill_service(struct sk_buff * skb,struct ip_vs_service * svc)3076 static int ip_vs_genl_fill_service(struct sk_buff *skb,
3077 				   struct ip_vs_service *svc)
3078 {
3079 	struct ip_vs_scheduler *sched;
3080 	struct ip_vs_pe *pe;
3081 	struct nlattr *nl_service;
3082 	struct ip_vs_flags flags = { .flags = svc->flags,
3083 				     .mask = ~0 };
3084 	struct ip_vs_kstats kstats;
3085 	char *sched_name;
3086 
3087 	nl_service = nla_nest_start_noflag(skb, IPVS_CMD_ATTR_SERVICE);
3088 	if (!nl_service)
3089 		return -EMSGSIZE;
3090 
3091 	if (nla_put_u16(skb, IPVS_SVC_ATTR_AF, svc->af))
3092 		goto nla_put_failure;
3093 	if (svc->fwmark) {
3094 		if (nla_put_u32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark))
3095 			goto nla_put_failure;
3096 	} else {
3097 		if (nla_put_u16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol) ||
3098 		    nla_put(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr) ||
3099 		    nla_put_be16(skb, IPVS_SVC_ATTR_PORT, svc->port))
3100 			goto nla_put_failure;
3101 	}
3102 
3103 	sched = rcu_dereference_protected(svc->scheduler, 1);
3104 	sched_name = sched ? sched->name : "none";
3105 	pe = rcu_dereference_protected(svc->pe, 1);
3106 	if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, sched_name) ||
3107 	    (pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, pe->name)) ||
3108 	    nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) ||
3109 	    nla_put_u32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ) ||
3110 	    nla_put_be32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask))
3111 		goto nla_put_failure;
3112 	ip_vs_copy_stats(&kstats, &svc->stats);
3113 	if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &kstats))
3114 		goto nla_put_failure;
3115 	if (ip_vs_genl_fill_stats64(skb, IPVS_SVC_ATTR_STATS64, &kstats))
3116 		goto nla_put_failure;
3117 
3118 	nla_nest_end(skb, nl_service);
3119 
3120 	return 0;
3121 
3122 nla_put_failure:
3123 	nla_nest_cancel(skb, nl_service);
3124 	return -EMSGSIZE;
3125 }
3126 
ip_vs_genl_dump_service(struct sk_buff * skb,struct ip_vs_service * svc,struct netlink_callback * cb)3127 static int ip_vs_genl_dump_service(struct sk_buff *skb,
3128 				   struct ip_vs_service *svc,
3129 				   struct netlink_callback *cb)
3130 {
3131 	void *hdr;
3132 
3133 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3134 			  &ip_vs_genl_family, NLM_F_MULTI,
3135 			  IPVS_CMD_NEW_SERVICE);
3136 	if (!hdr)
3137 		return -EMSGSIZE;
3138 
3139 	if (ip_vs_genl_fill_service(skb, svc) < 0)
3140 		goto nla_put_failure;
3141 
3142 	genlmsg_end(skb, hdr);
3143 	return 0;
3144 
3145 nla_put_failure:
3146 	genlmsg_cancel(skb, hdr);
3147 	return -EMSGSIZE;
3148 }
3149 
ip_vs_genl_dump_services(struct sk_buff * skb,struct netlink_callback * cb)3150 static int ip_vs_genl_dump_services(struct sk_buff *skb,
3151 				    struct netlink_callback *cb)
3152 {
3153 	int idx = 0, i;
3154 	int start = cb->args[0];
3155 	struct ip_vs_service *svc;
3156 	struct net *net = sock_net(skb->sk);
3157 	struct netns_ipvs *ipvs = net_ipvs(net);
3158 
3159 	mutex_lock(&__ip_vs_mutex);
3160 	for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
3161 		hlist_for_each_entry(svc, &ip_vs_svc_table[i], s_list) {
3162 			if (++idx <= start || (svc->ipvs != ipvs))
3163 				continue;
3164 			if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
3165 				idx--;
3166 				goto nla_put_failure;
3167 			}
3168 		}
3169 	}
3170 
3171 	for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) {
3172 		hlist_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) {
3173 			if (++idx <= start || (svc->ipvs != ipvs))
3174 				continue;
3175 			if (ip_vs_genl_dump_service(skb, svc, cb) < 0) {
3176 				idx--;
3177 				goto nla_put_failure;
3178 			}
3179 		}
3180 	}
3181 
3182 nla_put_failure:
3183 	mutex_unlock(&__ip_vs_mutex);
3184 	cb->args[0] = idx;
3185 
3186 	return skb->len;
3187 }
3188 
ip_vs_is_af_valid(int af)3189 static bool ip_vs_is_af_valid(int af)
3190 {
3191 	if (af == AF_INET)
3192 		return true;
3193 #ifdef CONFIG_IP_VS_IPV6
3194 	if (af == AF_INET6 && ipv6_mod_enabled())
3195 		return true;
3196 #endif
3197 	return false;
3198 }
3199 
ip_vs_genl_parse_service(struct netns_ipvs * ipvs,struct ip_vs_service_user_kern * usvc,struct nlattr * nla,bool full_entry,struct ip_vs_service ** ret_svc)3200 static int ip_vs_genl_parse_service(struct netns_ipvs *ipvs,
3201 				    struct ip_vs_service_user_kern *usvc,
3202 				    struct nlattr *nla, bool full_entry,
3203 				    struct ip_vs_service **ret_svc)
3204 {
3205 	struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1];
3206 	struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr;
3207 	struct ip_vs_service *svc;
3208 
3209 	/* Parse mandatory identifying service fields first */
3210 	if (nla == NULL ||
3211 	    nla_parse_nested_deprecated(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy, NULL))
3212 		return -EINVAL;
3213 
3214 	nla_af		= attrs[IPVS_SVC_ATTR_AF];
3215 	nla_protocol	= attrs[IPVS_SVC_ATTR_PROTOCOL];
3216 	nla_addr	= attrs[IPVS_SVC_ATTR_ADDR];
3217 	nla_port	= attrs[IPVS_SVC_ATTR_PORT];
3218 	nla_fwmark	= attrs[IPVS_SVC_ATTR_FWMARK];
3219 
3220 	if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr))))
3221 		return -EINVAL;
3222 
3223 	memset(usvc, 0, sizeof(*usvc));
3224 
3225 	usvc->af = nla_get_u16(nla_af);
3226 	if (!ip_vs_is_af_valid(usvc->af))
3227 		return -EAFNOSUPPORT;
3228 
3229 	if (nla_fwmark) {
3230 		usvc->protocol = IPPROTO_TCP;
3231 		usvc->fwmark = nla_get_u32(nla_fwmark);
3232 	} else {
3233 		usvc->protocol = nla_get_u16(nla_protocol);
3234 		nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr));
3235 		usvc->port = nla_get_be16(nla_port);
3236 		usvc->fwmark = 0;
3237 	}
3238 
3239 	rcu_read_lock();
3240 	if (usvc->fwmark)
3241 		svc = __ip_vs_svc_fwm_find(ipvs, usvc->af, usvc->fwmark);
3242 	else
3243 		svc = __ip_vs_service_find(ipvs, usvc->af, usvc->protocol,
3244 					   &usvc->addr, usvc->port);
3245 	rcu_read_unlock();
3246 	*ret_svc = svc;
3247 
3248 	/* If a full entry was requested, check for the additional fields */
3249 	if (full_entry) {
3250 		struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout,
3251 			      *nla_netmask;
3252 		struct ip_vs_flags flags;
3253 
3254 		nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME];
3255 		nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME];
3256 		nla_flags = attrs[IPVS_SVC_ATTR_FLAGS];
3257 		nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT];
3258 		nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK];
3259 
3260 		if (!(nla_sched && nla_flags && nla_timeout && nla_netmask))
3261 			return -EINVAL;
3262 
3263 		nla_memcpy(&flags, nla_flags, sizeof(flags));
3264 
3265 		/* prefill flags from service if it already exists */
3266 		if (svc)
3267 			usvc->flags = svc->flags;
3268 
3269 		/* set new flags from userland */
3270 		usvc->flags = (usvc->flags & ~flags.mask) |
3271 			      (flags.flags & flags.mask);
3272 		usvc->sched_name = nla_data(nla_sched);
3273 		usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL;
3274 		usvc->timeout = nla_get_u32(nla_timeout);
3275 		usvc->netmask = nla_get_be32(nla_netmask);
3276 	}
3277 
3278 	return 0;
3279 }
3280 
ip_vs_genl_find_service(struct netns_ipvs * ipvs,struct nlattr * nla)3281 static struct ip_vs_service *ip_vs_genl_find_service(struct netns_ipvs *ipvs,
3282 						     struct nlattr *nla)
3283 {
3284 	struct ip_vs_service_user_kern usvc;
3285 	struct ip_vs_service *svc;
3286 	int ret;
3287 
3288 	ret = ip_vs_genl_parse_service(ipvs, &usvc, nla, false, &svc);
3289 	return ret ? ERR_PTR(ret) : svc;
3290 }
3291 
ip_vs_genl_fill_dest(struct sk_buff * skb,struct ip_vs_dest * dest)3292 static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest)
3293 {
3294 	struct nlattr *nl_dest;
3295 	struct ip_vs_kstats kstats;
3296 
3297 	nl_dest = nla_nest_start_noflag(skb, IPVS_CMD_ATTR_DEST);
3298 	if (!nl_dest)
3299 		return -EMSGSIZE;
3300 
3301 	if (nla_put(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr) ||
3302 	    nla_put_be16(skb, IPVS_DEST_ATTR_PORT, dest->port) ||
3303 	    nla_put_u32(skb, IPVS_DEST_ATTR_FWD_METHOD,
3304 			(atomic_read(&dest->conn_flags) &
3305 			 IP_VS_CONN_F_FWD_MASK)) ||
3306 	    nla_put_u32(skb, IPVS_DEST_ATTR_WEIGHT,
3307 			atomic_read(&dest->weight)) ||
3308 	    nla_put_u8(skb, IPVS_DEST_ATTR_TUN_TYPE,
3309 		       dest->tun_type) ||
3310 	    nla_put_be16(skb, IPVS_DEST_ATTR_TUN_PORT,
3311 			 dest->tun_port) ||
3312 	    nla_put_u16(skb, IPVS_DEST_ATTR_TUN_FLAGS,
3313 			dest->tun_flags) ||
3314 	    nla_put_u32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold) ||
3315 	    nla_put_u32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold) ||
3316 	    nla_put_u32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS,
3317 			atomic_read(&dest->activeconns)) ||
3318 	    nla_put_u32(skb, IPVS_DEST_ATTR_INACT_CONNS,
3319 			atomic_read(&dest->inactconns)) ||
3320 	    nla_put_u32(skb, IPVS_DEST_ATTR_PERSIST_CONNS,
3321 			atomic_read(&dest->persistconns)) ||
3322 	    nla_put_u16(skb, IPVS_DEST_ATTR_ADDR_FAMILY, dest->af))
3323 		goto nla_put_failure;
3324 	ip_vs_copy_stats(&kstats, &dest->stats);
3325 	if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &kstats))
3326 		goto nla_put_failure;
3327 	if (ip_vs_genl_fill_stats64(skb, IPVS_DEST_ATTR_STATS64, &kstats))
3328 		goto nla_put_failure;
3329 
3330 	nla_nest_end(skb, nl_dest);
3331 
3332 	return 0;
3333 
3334 nla_put_failure:
3335 	nla_nest_cancel(skb, nl_dest);
3336 	return -EMSGSIZE;
3337 }
3338 
ip_vs_genl_dump_dest(struct sk_buff * skb,struct ip_vs_dest * dest,struct netlink_callback * cb)3339 static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest,
3340 				struct netlink_callback *cb)
3341 {
3342 	void *hdr;
3343 
3344 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3345 			  &ip_vs_genl_family, NLM_F_MULTI,
3346 			  IPVS_CMD_NEW_DEST);
3347 	if (!hdr)
3348 		return -EMSGSIZE;
3349 
3350 	if (ip_vs_genl_fill_dest(skb, dest) < 0)
3351 		goto nla_put_failure;
3352 
3353 	genlmsg_end(skb, hdr);
3354 	return 0;
3355 
3356 nla_put_failure:
3357 	genlmsg_cancel(skb, hdr);
3358 	return -EMSGSIZE;
3359 }
3360 
ip_vs_genl_dump_dests(struct sk_buff * skb,struct netlink_callback * cb)3361 static int ip_vs_genl_dump_dests(struct sk_buff *skb,
3362 				 struct netlink_callback *cb)
3363 {
3364 	int idx = 0;
3365 	int start = cb->args[0];
3366 	struct ip_vs_service *svc;
3367 	struct ip_vs_dest *dest;
3368 	struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1];
3369 	struct net *net = sock_net(skb->sk);
3370 	struct netns_ipvs *ipvs = net_ipvs(net);
3371 
3372 	mutex_lock(&__ip_vs_mutex);
3373 
3374 	/* Try to find the service for which to dump destinations */
3375 	if (nlmsg_parse_deprecated(cb->nlh, GENL_HDRLEN, attrs, IPVS_CMD_ATTR_MAX, ip_vs_cmd_policy, cb->extack))
3376 		goto out_err;
3377 
3378 
3379 	svc = ip_vs_genl_find_service(ipvs, attrs[IPVS_CMD_ATTR_SERVICE]);
3380 	if (IS_ERR_OR_NULL(svc))
3381 		goto out_err;
3382 
3383 	/* Dump the destinations */
3384 	list_for_each_entry(dest, &svc->destinations, n_list) {
3385 		if (++idx <= start)
3386 			continue;
3387 		if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) {
3388 			idx--;
3389 			goto nla_put_failure;
3390 		}
3391 	}
3392 
3393 nla_put_failure:
3394 	cb->args[0] = idx;
3395 
3396 out_err:
3397 	mutex_unlock(&__ip_vs_mutex);
3398 
3399 	return skb->len;
3400 }
3401 
ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern * udest,struct nlattr * nla,bool full_entry)3402 static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest,
3403 				 struct nlattr *nla, bool full_entry)
3404 {
3405 	struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1];
3406 	struct nlattr *nla_addr, *nla_port;
3407 	struct nlattr *nla_addr_family;
3408 
3409 	/* Parse mandatory identifying destination fields first */
3410 	if (nla == NULL ||
3411 	    nla_parse_nested_deprecated(attrs, IPVS_DEST_ATTR_MAX, nla, ip_vs_dest_policy, NULL))
3412 		return -EINVAL;
3413 
3414 	nla_addr	= attrs[IPVS_DEST_ATTR_ADDR];
3415 	nla_port	= attrs[IPVS_DEST_ATTR_PORT];
3416 	nla_addr_family	= attrs[IPVS_DEST_ATTR_ADDR_FAMILY];
3417 
3418 	if (!(nla_addr && nla_port))
3419 		return -EINVAL;
3420 
3421 	memset(udest, 0, sizeof(*udest));
3422 
3423 	nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr));
3424 	udest->port = nla_get_be16(nla_port);
3425 
3426 	if (nla_addr_family)
3427 		udest->af = nla_get_u16(nla_addr_family);
3428 	else
3429 		udest->af = 0;
3430 
3431 	/* If a full entry was requested, check for the additional fields */
3432 	if (full_entry) {
3433 		struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh,
3434 			      *nla_l_thresh, *nla_tun_type, *nla_tun_port,
3435 			      *nla_tun_flags;
3436 
3437 		nla_fwd		= attrs[IPVS_DEST_ATTR_FWD_METHOD];
3438 		nla_weight	= attrs[IPVS_DEST_ATTR_WEIGHT];
3439 		nla_u_thresh	= attrs[IPVS_DEST_ATTR_U_THRESH];
3440 		nla_l_thresh	= attrs[IPVS_DEST_ATTR_L_THRESH];
3441 		nla_tun_type	= attrs[IPVS_DEST_ATTR_TUN_TYPE];
3442 		nla_tun_port	= attrs[IPVS_DEST_ATTR_TUN_PORT];
3443 		nla_tun_flags	= attrs[IPVS_DEST_ATTR_TUN_FLAGS];
3444 
3445 		if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh))
3446 			return -EINVAL;
3447 
3448 		udest->conn_flags = nla_get_u32(nla_fwd)
3449 				    & IP_VS_CONN_F_FWD_MASK;
3450 		udest->weight = nla_get_u32(nla_weight);
3451 		udest->u_threshold = nla_get_u32(nla_u_thresh);
3452 		udest->l_threshold = nla_get_u32(nla_l_thresh);
3453 
3454 		if (nla_tun_type)
3455 			udest->tun_type = nla_get_u8(nla_tun_type);
3456 
3457 		if (nla_tun_port)
3458 			udest->tun_port = nla_get_be16(nla_tun_port);
3459 
3460 		if (nla_tun_flags)
3461 			udest->tun_flags = nla_get_u16(nla_tun_flags);
3462 	}
3463 
3464 	return 0;
3465 }
3466 
ip_vs_genl_fill_daemon(struct sk_buff * skb,__u32 state,struct ipvs_sync_daemon_cfg * c)3467 static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __u32 state,
3468 				  struct ipvs_sync_daemon_cfg *c)
3469 {
3470 	struct nlattr *nl_daemon;
3471 
3472 	nl_daemon = nla_nest_start_noflag(skb, IPVS_CMD_ATTR_DAEMON);
3473 	if (!nl_daemon)
3474 		return -EMSGSIZE;
3475 
3476 	if (nla_put_u32(skb, IPVS_DAEMON_ATTR_STATE, state) ||
3477 	    nla_put_string(skb, IPVS_DAEMON_ATTR_MCAST_IFN, c->mcast_ifn) ||
3478 	    nla_put_u32(skb, IPVS_DAEMON_ATTR_SYNC_ID, c->syncid) ||
3479 	    nla_put_u16(skb, IPVS_DAEMON_ATTR_SYNC_MAXLEN, c->sync_maxlen) ||
3480 	    nla_put_u16(skb, IPVS_DAEMON_ATTR_MCAST_PORT, c->mcast_port) ||
3481 	    nla_put_u8(skb, IPVS_DAEMON_ATTR_MCAST_TTL, c->mcast_ttl))
3482 		goto nla_put_failure;
3483 #ifdef CONFIG_IP_VS_IPV6
3484 	if (c->mcast_af == AF_INET6) {
3485 		if (nla_put_in6_addr(skb, IPVS_DAEMON_ATTR_MCAST_GROUP6,
3486 				     &c->mcast_group.in6))
3487 			goto nla_put_failure;
3488 	} else
3489 #endif
3490 		if (c->mcast_af == AF_INET &&
3491 		    nla_put_in_addr(skb, IPVS_DAEMON_ATTR_MCAST_GROUP,
3492 				    c->mcast_group.ip))
3493 			goto nla_put_failure;
3494 	nla_nest_end(skb, nl_daemon);
3495 
3496 	return 0;
3497 
3498 nla_put_failure:
3499 	nla_nest_cancel(skb, nl_daemon);
3500 	return -EMSGSIZE;
3501 }
3502 
ip_vs_genl_dump_daemon(struct sk_buff * skb,__u32 state,struct ipvs_sync_daemon_cfg * c,struct netlink_callback * cb)3503 static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __u32 state,
3504 				  struct ipvs_sync_daemon_cfg *c,
3505 				  struct netlink_callback *cb)
3506 {
3507 	void *hdr;
3508 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3509 			  &ip_vs_genl_family, NLM_F_MULTI,
3510 			  IPVS_CMD_NEW_DAEMON);
3511 	if (!hdr)
3512 		return -EMSGSIZE;
3513 
3514 	if (ip_vs_genl_fill_daemon(skb, state, c))
3515 		goto nla_put_failure;
3516 
3517 	genlmsg_end(skb, hdr);
3518 	return 0;
3519 
3520 nla_put_failure:
3521 	genlmsg_cancel(skb, hdr);
3522 	return -EMSGSIZE;
3523 }
3524 
ip_vs_genl_dump_daemons(struct sk_buff * skb,struct netlink_callback * cb)3525 static int ip_vs_genl_dump_daemons(struct sk_buff *skb,
3526 				   struct netlink_callback *cb)
3527 {
3528 	struct net *net = sock_net(skb->sk);
3529 	struct netns_ipvs *ipvs = net_ipvs(net);
3530 
3531 	mutex_lock(&ipvs->sync_mutex);
3532 	if ((ipvs->sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) {
3533 		if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER,
3534 					   &ipvs->mcfg, cb) < 0)
3535 			goto nla_put_failure;
3536 
3537 		cb->args[0] = 1;
3538 	}
3539 
3540 	if ((ipvs->sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) {
3541 		if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP,
3542 					   &ipvs->bcfg, cb) < 0)
3543 			goto nla_put_failure;
3544 
3545 		cb->args[1] = 1;
3546 	}
3547 
3548 nla_put_failure:
3549 	mutex_unlock(&ipvs->sync_mutex);
3550 
3551 	return skb->len;
3552 }
3553 
ip_vs_genl_new_daemon(struct netns_ipvs * ipvs,struct nlattr ** attrs)3554 static int ip_vs_genl_new_daemon(struct netns_ipvs *ipvs, struct nlattr **attrs)
3555 {
3556 	struct ipvs_sync_daemon_cfg c;
3557 	struct nlattr *a;
3558 	int ret;
3559 
3560 	memset(&c, 0, sizeof(c));
3561 	if (!(attrs[IPVS_DAEMON_ATTR_STATE] &&
3562 	      attrs[IPVS_DAEMON_ATTR_MCAST_IFN] &&
3563 	      attrs[IPVS_DAEMON_ATTR_SYNC_ID]))
3564 		return -EINVAL;
3565 	strlcpy(c.mcast_ifn, nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]),
3566 		sizeof(c.mcast_ifn));
3567 	c.syncid = nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID]);
3568 
3569 	a = attrs[IPVS_DAEMON_ATTR_SYNC_MAXLEN];
3570 	if (a)
3571 		c.sync_maxlen = nla_get_u16(a);
3572 
3573 	a = attrs[IPVS_DAEMON_ATTR_MCAST_GROUP];
3574 	if (a) {
3575 		c.mcast_af = AF_INET;
3576 		c.mcast_group.ip = nla_get_in_addr(a);
3577 		if (!ipv4_is_multicast(c.mcast_group.ip))
3578 			return -EINVAL;
3579 	} else {
3580 		a = attrs[IPVS_DAEMON_ATTR_MCAST_GROUP6];
3581 		if (a) {
3582 #ifdef CONFIG_IP_VS_IPV6
3583 			int addr_type;
3584 
3585 			c.mcast_af = AF_INET6;
3586 			c.mcast_group.in6 = nla_get_in6_addr(a);
3587 			addr_type = ipv6_addr_type(&c.mcast_group.in6);
3588 			if (!(addr_type & IPV6_ADDR_MULTICAST))
3589 				return -EINVAL;
3590 #else
3591 			return -EAFNOSUPPORT;
3592 #endif
3593 		}
3594 	}
3595 
3596 	a = attrs[IPVS_DAEMON_ATTR_MCAST_PORT];
3597 	if (a)
3598 		c.mcast_port = nla_get_u16(a);
3599 
3600 	a = attrs[IPVS_DAEMON_ATTR_MCAST_TTL];
3601 	if (a)
3602 		c.mcast_ttl = nla_get_u8(a);
3603 
3604 	/* The synchronization protocol is incompatible with mixed family
3605 	 * services
3606 	 */
3607 	if (ipvs->mixed_address_family_dests > 0)
3608 		return -EINVAL;
3609 
3610 	ret = start_sync_thread(ipvs, &c,
3611 				nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3612 	return ret;
3613 }
3614 
ip_vs_genl_del_daemon(struct netns_ipvs * ipvs,struct nlattr ** attrs)3615 static int ip_vs_genl_del_daemon(struct netns_ipvs *ipvs, struct nlattr **attrs)
3616 {
3617 	int ret;
3618 
3619 	if (!attrs[IPVS_DAEMON_ATTR_STATE])
3620 		return -EINVAL;
3621 
3622 	ret = stop_sync_thread(ipvs,
3623 			       nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]));
3624 	return ret;
3625 }
3626 
ip_vs_genl_set_config(struct netns_ipvs * ipvs,struct nlattr ** attrs)3627 static int ip_vs_genl_set_config(struct netns_ipvs *ipvs, struct nlattr **attrs)
3628 {
3629 	struct ip_vs_timeout_user t;
3630 
3631 	__ip_vs_get_timeouts(ipvs, &t);
3632 
3633 	if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP])
3634 		t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]);
3635 
3636 	if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN])
3637 		t.tcp_fin_timeout =
3638 			nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]);
3639 
3640 	if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP])
3641 		t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]);
3642 
3643 	return ip_vs_set_timeout(ipvs, &t);
3644 }
3645 
ip_vs_genl_set_daemon(struct sk_buff * skb,struct genl_info * info)3646 static int ip_vs_genl_set_daemon(struct sk_buff *skb, struct genl_info *info)
3647 {
3648 	int ret = -EINVAL, cmd;
3649 	struct net *net = sock_net(skb->sk);
3650 	struct netns_ipvs *ipvs = net_ipvs(net);
3651 
3652 	cmd = info->genlhdr->cmd;
3653 
3654 	if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) {
3655 		struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1];
3656 
3657 		if (!info->attrs[IPVS_CMD_ATTR_DAEMON] ||
3658 		    nla_parse_nested_deprecated(daemon_attrs, IPVS_DAEMON_ATTR_MAX, info->attrs[IPVS_CMD_ATTR_DAEMON], ip_vs_daemon_policy, info->extack))
3659 			goto out;
3660 
3661 		if (cmd == IPVS_CMD_NEW_DAEMON)
3662 			ret = ip_vs_genl_new_daemon(ipvs, daemon_attrs);
3663 		else
3664 			ret = ip_vs_genl_del_daemon(ipvs, daemon_attrs);
3665 	}
3666 
3667 out:
3668 	return ret;
3669 }
3670 
ip_vs_genl_set_cmd(struct sk_buff * skb,struct genl_info * info)3671 static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info)
3672 {
3673 	bool need_full_svc = false, need_full_dest = false;
3674 	struct ip_vs_service *svc = NULL;
3675 	struct ip_vs_service_user_kern usvc;
3676 	struct ip_vs_dest_user_kern udest;
3677 	int ret = 0, cmd;
3678 	struct net *net = sock_net(skb->sk);
3679 	struct netns_ipvs *ipvs = net_ipvs(net);
3680 
3681 	cmd = info->genlhdr->cmd;
3682 
3683 	mutex_lock(&__ip_vs_mutex);
3684 
3685 	if (cmd == IPVS_CMD_FLUSH) {
3686 		ret = ip_vs_flush(ipvs, false);
3687 		goto out;
3688 	} else if (cmd == IPVS_CMD_SET_CONFIG) {
3689 		ret = ip_vs_genl_set_config(ipvs, info->attrs);
3690 		goto out;
3691 	} else if (cmd == IPVS_CMD_ZERO &&
3692 		   !info->attrs[IPVS_CMD_ATTR_SERVICE]) {
3693 		ret = ip_vs_zero_all(ipvs);
3694 		goto out;
3695 	}
3696 
3697 	/* All following commands require a service argument, so check if we
3698 	 * received a valid one. We need a full service specification when
3699 	 * adding / editing a service. Only identifying members otherwise. */
3700 	if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE)
3701 		need_full_svc = true;
3702 
3703 	ret = ip_vs_genl_parse_service(ipvs, &usvc,
3704 				       info->attrs[IPVS_CMD_ATTR_SERVICE],
3705 				       need_full_svc, &svc);
3706 	if (ret)
3707 		goto out;
3708 
3709 	/* Unless we're adding a new service, the service must already exist */
3710 	if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) {
3711 		ret = -ESRCH;
3712 		goto out;
3713 	}
3714 
3715 	/* Destination commands require a valid destination argument. For
3716 	 * adding / editing a destination, we need a full destination
3717 	 * specification. */
3718 	if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST ||
3719 	    cmd == IPVS_CMD_DEL_DEST) {
3720 		if (cmd != IPVS_CMD_DEL_DEST)
3721 			need_full_dest = true;
3722 
3723 		ret = ip_vs_genl_parse_dest(&udest,
3724 					    info->attrs[IPVS_CMD_ATTR_DEST],
3725 					    need_full_dest);
3726 		if (ret)
3727 			goto out;
3728 
3729 		/* Old protocols did not allow the user to specify address
3730 		 * family, so we set it to zero instead.  We also didn't
3731 		 * allow heterogeneous pools in the old code, so it's safe
3732 		 * to assume that this will have the same address family as
3733 		 * the service.
3734 		 */
3735 		if (udest.af == 0)
3736 			udest.af = svc->af;
3737 
3738 		if (!ip_vs_is_af_valid(udest.af)) {
3739 			ret = -EAFNOSUPPORT;
3740 			goto out;
3741 		}
3742 
3743 		if (udest.af != svc->af && cmd != IPVS_CMD_DEL_DEST) {
3744 			/* The synchronization protocol is incompatible
3745 			 * with mixed family services
3746 			 */
3747 			if (ipvs->sync_state) {
3748 				ret = -EINVAL;
3749 				goto out;
3750 			}
3751 
3752 			/* Which connection types do we support? */
3753 			switch (udest.conn_flags) {
3754 			case IP_VS_CONN_F_TUNNEL:
3755 				/* We are able to forward this */
3756 				break;
3757 			default:
3758 				ret = -EINVAL;
3759 				goto out;
3760 			}
3761 		}
3762 	}
3763 
3764 	switch (cmd) {
3765 	case IPVS_CMD_NEW_SERVICE:
3766 		if (svc == NULL)
3767 			ret = ip_vs_add_service(ipvs, &usvc, &svc);
3768 		else
3769 			ret = -EEXIST;
3770 		break;
3771 	case IPVS_CMD_SET_SERVICE:
3772 		ret = ip_vs_edit_service(svc, &usvc);
3773 		break;
3774 	case IPVS_CMD_DEL_SERVICE:
3775 		ret = ip_vs_del_service(svc);
3776 		/* do not use svc, it can be freed */
3777 		break;
3778 	case IPVS_CMD_NEW_DEST:
3779 		ret = ip_vs_add_dest(svc, &udest);
3780 		break;
3781 	case IPVS_CMD_SET_DEST:
3782 		ret = ip_vs_edit_dest(svc, &udest);
3783 		break;
3784 	case IPVS_CMD_DEL_DEST:
3785 		ret = ip_vs_del_dest(svc, &udest);
3786 		break;
3787 	case IPVS_CMD_ZERO:
3788 		ret = ip_vs_zero_service(svc);
3789 		break;
3790 	default:
3791 		ret = -EINVAL;
3792 	}
3793 
3794 out:
3795 	mutex_unlock(&__ip_vs_mutex);
3796 
3797 	return ret;
3798 }
3799 
ip_vs_genl_get_cmd(struct sk_buff * skb,struct genl_info * info)3800 static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info)
3801 {
3802 	struct sk_buff *msg;
3803 	void *reply;
3804 	int ret, cmd, reply_cmd;
3805 	struct net *net = sock_net(skb->sk);
3806 	struct netns_ipvs *ipvs = net_ipvs(net);
3807 
3808 	cmd = info->genlhdr->cmd;
3809 
3810 	if (cmd == IPVS_CMD_GET_SERVICE)
3811 		reply_cmd = IPVS_CMD_NEW_SERVICE;
3812 	else if (cmd == IPVS_CMD_GET_INFO)
3813 		reply_cmd = IPVS_CMD_SET_INFO;
3814 	else if (cmd == IPVS_CMD_GET_CONFIG)
3815 		reply_cmd = IPVS_CMD_SET_CONFIG;
3816 	else {
3817 		pr_err("unknown Generic Netlink command\n");
3818 		return -EINVAL;
3819 	}
3820 
3821 	msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL);
3822 	if (!msg)
3823 		return -ENOMEM;
3824 
3825 	mutex_lock(&__ip_vs_mutex);
3826 
3827 	reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd);
3828 	if (reply == NULL)
3829 		goto nla_put_failure;
3830 
3831 	switch (cmd) {
3832 	case IPVS_CMD_GET_SERVICE:
3833 	{
3834 		struct ip_vs_service *svc;
3835 
3836 		svc = ip_vs_genl_find_service(ipvs,
3837 					      info->attrs[IPVS_CMD_ATTR_SERVICE]);
3838 		if (IS_ERR(svc)) {
3839 			ret = PTR_ERR(svc);
3840 			goto out_err;
3841 		} else if (svc) {
3842 			ret = ip_vs_genl_fill_service(msg, svc);
3843 			if (ret)
3844 				goto nla_put_failure;
3845 		} else {
3846 			ret = -ESRCH;
3847 			goto out_err;
3848 		}
3849 
3850 		break;
3851 	}
3852 
3853 	case IPVS_CMD_GET_CONFIG:
3854 	{
3855 		struct ip_vs_timeout_user t;
3856 
3857 		__ip_vs_get_timeouts(ipvs, &t);
3858 #ifdef CONFIG_IP_VS_PROTO_TCP
3859 		if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP,
3860 				t.tcp_timeout) ||
3861 		    nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN,
3862 				t.tcp_fin_timeout))
3863 			goto nla_put_failure;
3864 #endif
3865 #ifdef CONFIG_IP_VS_PROTO_UDP
3866 		if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout))
3867 			goto nla_put_failure;
3868 #endif
3869 
3870 		break;
3871 	}
3872 
3873 	case IPVS_CMD_GET_INFO:
3874 		if (nla_put_u32(msg, IPVS_INFO_ATTR_VERSION,
3875 				IP_VS_VERSION_CODE) ||
3876 		    nla_put_u32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE,
3877 				ip_vs_conn_tab_size))
3878 			goto nla_put_failure;
3879 		break;
3880 	}
3881 
3882 	genlmsg_end(msg, reply);
3883 	ret = genlmsg_reply(msg, info);
3884 	goto out;
3885 
3886 nla_put_failure:
3887 	pr_err("not enough space in Netlink message\n");
3888 	ret = -EMSGSIZE;
3889 
3890 out_err:
3891 	nlmsg_free(msg);
3892 out:
3893 	mutex_unlock(&__ip_vs_mutex);
3894 
3895 	return ret;
3896 }
3897 
3898 
3899 static const struct genl_small_ops ip_vs_genl_ops[] = {
3900 	{
3901 		.cmd	= IPVS_CMD_NEW_SERVICE,
3902 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3903 		.flags	= GENL_ADMIN_PERM,
3904 		.doit	= ip_vs_genl_set_cmd,
3905 	},
3906 	{
3907 		.cmd	= IPVS_CMD_SET_SERVICE,
3908 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3909 		.flags	= GENL_ADMIN_PERM,
3910 		.doit	= ip_vs_genl_set_cmd,
3911 	},
3912 	{
3913 		.cmd	= IPVS_CMD_DEL_SERVICE,
3914 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3915 		.flags	= GENL_ADMIN_PERM,
3916 		.doit	= ip_vs_genl_set_cmd,
3917 	},
3918 	{
3919 		.cmd	= IPVS_CMD_GET_SERVICE,
3920 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3921 		.flags	= GENL_ADMIN_PERM,
3922 		.doit	= ip_vs_genl_get_cmd,
3923 		.dumpit	= ip_vs_genl_dump_services,
3924 	},
3925 	{
3926 		.cmd	= IPVS_CMD_NEW_DEST,
3927 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3928 		.flags	= GENL_ADMIN_PERM,
3929 		.doit	= ip_vs_genl_set_cmd,
3930 	},
3931 	{
3932 		.cmd	= IPVS_CMD_SET_DEST,
3933 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3934 		.flags	= GENL_ADMIN_PERM,
3935 		.doit	= ip_vs_genl_set_cmd,
3936 	},
3937 	{
3938 		.cmd	= IPVS_CMD_DEL_DEST,
3939 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3940 		.flags	= GENL_ADMIN_PERM,
3941 		.doit	= ip_vs_genl_set_cmd,
3942 	},
3943 	{
3944 		.cmd	= IPVS_CMD_GET_DEST,
3945 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3946 		.flags	= GENL_ADMIN_PERM,
3947 		.dumpit	= ip_vs_genl_dump_dests,
3948 	},
3949 	{
3950 		.cmd	= IPVS_CMD_NEW_DAEMON,
3951 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3952 		.flags	= GENL_ADMIN_PERM,
3953 		.doit	= ip_vs_genl_set_daemon,
3954 	},
3955 	{
3956 		.cmd	= IPVS_CMD_DEL_DAEMON,
3957 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3958 		.flags	= GENL_ADMIN_PERM,
3959 		.doit	= ip_vs_genl_set_daemon,
3960 	},
3961 	{
3962 		.cmd	= IPVS_CMD_GET_DAEMON,
3963 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3964 		.flags	= GENL_ADMIN_PERM,
3965 		.dumpit	= ip_vs_genl_dump_daemons,
3966 	},
3967 	{
3968 		.cmd	= IPVS_CMD_SET_CONFIG,
3969 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3970 		.flags	= GENL_ADMIN_PERM,
3971 		.doit	= ip_vs_genl_set_cmd,
3972 	},
3973 	{
3974 		.cmd	= IPVS_CMD_GET_CONFIG,
3975 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3976 		.flags	= GENL_ADMIN_PERM,
3977 		.doit	= ip_vs_genl_get_cmd,
3978 	},
3979 	{
3980 		.cmd	= IPVS_CMD_GET_INFO,
3981 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3982 		.flags	= GENL_ADMIN_PERM,
3983 		.doit	= ip_vs_genl_get_cmd,
3984 	},
3985 	{
3986 		.cmd	= IPVS_CMD_ZERO,
3987 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3988 		.flags	= GENL_ADMIN_PERM,
3989 		.doit	= ip_vs_genl_set_cmd,
3990 	},
3991 	{
3992 		.cmd	= IPVS_CMD_FLUSH,
3993 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
3994 		.flags	= GENL_ADMIN_PERM,
3995 		.doit	= ip_vs_genl_set_cmd,
3996 	},
3997 };
3998 
3999 static struct genl_family ip_vs_genl_family __ro_after_init = {
4000 	.hdrsize	= 0,
4001 	.name		= IPVS_GENL_NAME,
4002 	.version	= IPVS_GENL_VERSION,
4003 	.maxattr	= IPVS_CMD_ATTR_MAX,
4004 	.policy = ip_vs_cmd_policy,
4005 	.netnsok        = true,         /* Make ipvsadm to work on netns */
4006 	.module		= THIS_MODULE,
4007 	.small_ops	= ip_vs_genl_ops,
4008 	.n_small_ops	= ARRAY_SIZE(ip_vs_genl_ops),
4009 };
4010 
ip_vs_genl_register(void)4011 static int __init ip_vs_genl_register(void)
4012 {
4013 	return genl_register_family(&ip_vs_genl_family);
4014 }
4015 
ip_vs_genl_unregister(void)4016 static void ip_vs_genl_unregister(void)
4017 {
4018 	genl_unregister_family(&ip_vs_genl_family);
4019 }
4020 
4021 /* End of Generic Netlink interface definitions */
4022 
4023 /*
4024  * per netns intit/exit func.
4025  */
4026 #ifdef CONFIG_SYSCTL
ip_vs_control_net_init_sysctl(struct netns_ipvs * ipvs)4027 static int __net_init ip_vs_control_net_init_sysctl(struct netns_ipvs *ipvs)
4028 {
4029 	struct net *net = ipvs->net;
4030 	int idx;
4031 	struct ctl_table *tbl;
4032 
4033 	atomic_set(&ipvs->dropentry, 0);
4034 	spin_lock_init(&ipvs->dropentry_lock);
4035 	spin_lock_init(&ipvs->droppacket_lock);
4036 	spin_lock_init(&ipvs->securetcp_lock);
4037 
4038 	if (!net_eq(net, &init_net)) {
4039 		tbl = kmemdup(vs_vars, sizeof(vs_vars), GFP_KERNEL);
4040 		if (tbl == NULL)
4041 			return -ENOMEM;
4042 
4043 		/* Don't export sysctls to unprivileged users */
4044 		if (net->user_ns != &init_user_ns)
4045 			tbl[0].procname = NULL;
4046 	} else
4047 		tbl = vs_vars;
4048 	/* Initialize sysctl defaults */
4049 	for (idx = 0; idx < ARRAY_SIZE(vs_vars); idx++) {
4050 		if (tbl[idx].proc_handler == proc_do_defense_mode)
4051 			tbl[idx].extra2 = ipvs;
4052 	}
4053 	idx = 0;
4054 	ipvs->sysctl_amemthresh = 1024;
4055 	tbl[idx++].data = &ipvs->sysctl_amemthresh;
4056 	ipvs->sysctl_am_droprate = 10;
4057 	tbl[idx++].data = &ipvs->sysctl_am_droprate;
4058 	tbl[idx++].data = &ipvs->sysctl_drop_entry;
4059 	tbl[idx++].data = &ipvs->sysctl_drop_packet;
4060 #ifdef CONFIG_IP_VS_NFCT
4061 	tbl[idx++].data = &ipvs->sysctl_conntrack;
4062 #endif
4063 	tbl[idx++].data = &ipvs->sysctl_secure_tcp;
4064 	ipvs->sysctl_snat_reroute = 1;
4065 	tbl[idx++].data = &ipvs->sysctl_snat_reroute;
4066 	ipvs->sysctl_sync_ver = 1;
4067 	tbl[idx++].data = &ipvs->sysctl_sync_ver;
4068 	ipvs->sysctl_sync_ports = 1;
4069 	tbl[idx++].data = &ipvs->sysctl_sync_ports;
4070 	tbl[idx++].data = &ipvs->sysctl_sync_persist_mode;
4071 	ipvs->sysctl_sync_qlen_max = nr_free_buffer_pages() / 32;
4072 	tbl[idx++].data = &ipvs->sysctl_sync_qlen_max;
4073 	ipvs->sysctl_sync_sock_size = 0;
4074 	tbl[idx++].data = &ipvs->sysctl_sync_sock_size;
4075 	tbl[idx++].data = &ipvs->sysctl_cache_bypass;
4076 	tbl[idx++].data = &ipvs->sysctl_expire_nodest_conn;
4077 	tbl[idx++].data = &ipvs->sysctl_sloppy_tcp;
4078 	tbl[idx++].data = &ipvs->sysctl_sloppy_sctp;
4079 	tbl[idx++].data = &ipvs->sysctl_expire_quiescent_template;
4080 	ipvs->sysctl_sync_threshold[0] = DEFAULT_SYNC_THRESHOLD;
4081 	ipvs->sysctl_sync_threshold[1] = DEFAULT_SYNC_PERIOD;
4082 	tbl[idx].data = &ipvs->sysctl_sync_threshold;
4083 	tbl[idx].extra2 = ipvs;
4084 	tbl[idx++].maxlen = sizeof(ipvs->sysctl_sync_threshold);
4085 	ipvs->sysctl_sync_refresh_period = DEFAULT_SYNC_REFRESH_PERIOD;
4086 	tbl[idx++].data = &ipvs->sysctl_sync_refresh_period;
4087 	ipvs->sysctl_sync_retries = clamp_t(int, DEFAULT_SYNC_RETRIES, 0, 3);
4088 	tbl[idx++].data = &ipvs->sysctl_sync_retries;
4089 	tbl[idx++].data = &ipvs->sysctl_nat_icmp_send;
4090 	ipvs->sysctl_pmtu_disc = 1;
4091 	tbl[idx++].data = &ipvs->sysctl_pmtu_disc;
4092 	tbl[idx++].data = &ipvs->sysctl_backup_only;
4093 	ipvs->sysctl_conn_reuse_mode = 1;
4094 	tbl[idx++].data = &ipvs->sysctl_conn_reuse_mode;
4095 	tbl[idx++].data = &ipvs->sysctl_schedule_icmp;
4096 	tbl[idx++].data = &ipvs->sysctl_ignore_tunneled;
4097 #ifdef CONFIG_IP_VS_DEBUG
4098 	/* Global sysctls must be ro in non-init netns */
4099 	if (!net_eq(net, &init_net))
4100 		tbl[idx++].mode = 0444;
4101 #endif
4102 
4103 	ipvs->sysctl_hdr = register_net_sysctl(net, "net/ipv4/vs", tbl);
4104 	if (ipvs->sysctl_hdr == NULL) {
4105 		if (!net_eq(net, &init_net))
4106 			kfree(tbl);
4107 		return -ENOMEM;
4108 	}
4109 	ip_vs_start_estimator(ipvs, &ipvs->tot_stats);
4110 	ipvs->sysctl_tbl = tbl;
4111 	/* Schedule defense work */
4112 	INIT_DELAYED_WORK(&ipvs->defense_work, defense_work_handler);
4113 	queue_delayed_work(system_long_wq, &ipvs->defense_work,
4114 			   DEFENSE_TIMER_PERIOD);
4115 
4116 	/* Init delayed work for expiring no dest conn */
4117 	INIT_DELAYED_WORK(&ipvs->expire_nodest_conn_work,
4118 			  expire_nodest_conn_handler);
4119 
4120 	return 0;
4121 }
4122 
ip_vs_control_net_cleanup_sysctl(struct netns_ipvs * ipvs)4123 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct netns_ipvs *ipvs)
4124 {
4125 	struct net *net = ipvs->net;
4126 
4127 	cancel_delayed_work_sync(&ipvs->expire_nodest_conn_work);
4128 	cancel_delayed_work_sync(&ipvs->defense_work);
4129 	cancel_work_sync(&ipvs->defense_work.work);
4130 	unregister_net_sysctl_table(ipvs->sysctl_hdr);
4131 	ip_vs_stop_estimator(ipvs, &ipvs->tot_stats);
4132 
4133 	if (!net_eq(net, &init_net))
4134 		kfree(ipvs->sysctl_tbl);
4135 }
4136 
4137 #else
4138 
ip_vs_control_net_init_sysctl(struct netns_ipvs * ipvs)4139 static int __net_init ip_vs_control_net_init_sysctl(struct netns_ipvs *ipvs) { return 0; }
ip_vs_control_net_cleanup_sysctl(struct netns_ipvs * ipvs)4140 static void __net_exit ip_vs_control_net_cleanup_sysctl(struct netns_ipvs *ipvs) { }
4141 
4142 #endif
4143 
4144 static struct notifier_block ip_vs_dst_notifier = {
4145 	.notifier_call = ip_vs_dst_event,
4146 #ifdef CONFIG_IP_VS_IPV6
4147 	.priority = ADDRCONF_NOTIFY_PRIORITY + 5,
4148 #endif
4149 };
4150 
ip_vs_control_net_init(struct netns_ipvs * ipvs)4151 int __net_init ip_vs_control_net_init(struct netns_ipvs *ipvs)
4152 {
4153 	int i, idx;
4154 
4155 	/* Initialize rs_table */
4156 	for (idx = 0; idx < IP_VS_RTAB_SIZE; idx++)
4157 		INIT_HLIST_HEAD(&ipvs->rs_table[idx]);
4158 
4159 	INIT_LIST_HEAD(&ipvs->dest_trash);
4160 	spin_lock_init(&ipvs->dest_trash_lock);
4161 	timer_setup(&ipvs->dest_trash_timer, ip_vs_dest_trash_expire, 0);
4162 	atomic_set(&ipvs->ftpsvc_counter, 0);
4163 	atomic_set(&ipvs->nullsvc_counter, 0);
4164 	atomic_set(&ipvs->conn_out_counter, 0);
4165 
4166 	/* procfs stats */
4167 	ipvs->tot_stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats);
4168 	if (!ipvs->tot_stats.cpustats)
4169 		return -ENOMEM;
4170 
4171 	for_each_possible_cpu(i) {
4172 		struct ip_vs_cpu_stats *ipvs_tot_stats;
4173 		ipvs_tot_stats = per_cpu_ptr(ipvs->tot_stats.cpustats, i);
4174 		u64_stats_init(&ipvs_tot_stats->syncp);
4175 	}
4176 
4177 	spin_lock_init(&ipvs->tot_stats.lock);
4178 
4179 #ifdef CONFIG_PROC_FS
4180 	if (!proc_create_net("ip_vs", 0, ipvs->net->proc_net,
4181 			     &ip_vs_info_seq_ops, sizeof(struct ip_vs_iter)))
4182 		goto err_vs;
4183 	if (!proc_create_net_single("ip_vs_stats", 0, ipvs->net->proc_net,
4184 				    ip_vs_stats_show, NULL))
4185 		goto err_stats;
4186 	if (!proc_create_net_single("ip_vs_stats_percpu", 0,
4187 				    ipvs->net->proc_net,
4188 				    ip_vs_stats_percpu_show, NULL))
4189 		goto err_percpu;
4190 #endif
4191 
4192 	if (ip_vs_control_net_init_sysctl(ipvs))
4193 		goto err;
4194 
4195 	return 0;
4196 
4197 err:
4198 #ifdef CONFIG_PROC_FS
4199 	remove_proc_entry("ip_vs_stats_percpu", ipvs->net->proc_net);
4200 
4201 err_percpu:
4202 	remove_proc_entry("ip_vs_stats", ipvs->net->proc_net);
4203 
4204 err_stats:
4205 	remove_proc_entry("ip_vs", ipvs->net->proc_net);
4206 
4207 err_vs:
4208 #endif
4209 	free_percpu(ipvs->tot_stats.cpustats);
4210 	return -ENOMEM;
4211 }
4212 
ip_vs_control_net_cleanup(struct netns_ipvs * ipvs)4213 void __net_exit ip_vs_control_net_cleanup(struct netns_ipvs *ipvs)
4214 {
4215 	ip_vs_trash_cleanup(ipvs);
4216 	ip_vs_control_net_cleanup_sysctl(ipvs);
4217 #ifdef CONFIG_PROC_FS
4218 	remove_proc_entry("ip_vs_stats_percpu", ipvs->net->proc_net);
4219 	remove_proc_entry("ip_vs_stats", ipvs->net->proc_net);
4220 	remove_proc_entry("ip_vs", ipvs->net->proc_net);
4221 #endif
4222 	free_percpu(ipvs->tot_stats.cpustats);
4223 }
4224 
ip_vs_register_nl_ioctl(void)4225 int __init ip_vs_register_nl_ioctl(void)
4226 {
4227 	int ret;
4228 
4229 	ret = nf_register_sockopt(&ip_vs_sockopts);
4230 	if (ret) {
4231 		pr_err("cannot register sockopt.\n");
4232 		goto err_sock;
4233 	}
4234 
4235 	ret = ip_vs_genl_register();
4236 	if (ret) {
4237 		pr_err("cannot register Generic Netlink interface.\n");
4238 		goto err_genl;
4239 	}
4240 	return 0;
4241 
4242 err_genl:
4243 	nf_unregister_sockopt(&ip_vs_sockopts);
4244 err_sock:
4245 	return ret;
4246 }
4247 
ip_vs_unregister_nl_ioctl(void)4248 void ip_vs_unregister_nl_ioctl(void)
4249 {
4250 	ip_vs_genl_unregister();
4251 	nf_unregister_sockopt(&ip_vs_sockopts);
4252 }
4253 
ip_vs_control_init(void)4254 int __init ip_vs_control_init(void)
4255 {
4256 	int idx;
4257 	int ret;
4258 
4259 	EnterFunction(2);
4260 
4261 	/* Initialize svc_table, ip_vs_svc_fwm_table */
4262 	for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) {
4263 		INIT_HLIST_HEAD(&ip_vs_svc_table[idx]);
4264 		INIT_HLIST_HEAD(&ip_vs_svc_fwm_table[idx]);
4265 	}
4266 
4267 	smp_wmb();	/* Do we really need it now ? */
4268 
4269 	ret = register_netdevice_notifier(&ip_vs_dst_notifier);
4270 	if (ret < 0)
4271 		return ret;
4272 
4273 	LeaveFunction(2);
4274 	return 0;
4275 }
4276 
4277 
ip_vs_control_cleanup(void)4278 void ip_vs_control_cleanup(void)
4279 {
4280 	EnterFunction(2);
4281 	unregister_netdevice_notifier(&ip_vs_dst_notifier);
4282 	LeaveFunction(2);
4283 }
4284