1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		Support for INET connection oriented protocols.
8  *
9  * Authors:	See the TCP sources
10  */
11 
12 #include <linux/module.h>
13 #include <linux/jhash.h>
14 
15 #include <net/inet_connection_sock.h>
16 #include <net/inet_hashtables.h>
17 #include <net/inet_timewait_sock.h>
18 #include <net/ip.h>
19 #include <net/route.h>
20 #include <net/tcp_states.h>
21 #include <net/xfrm.h>
22 #include <net/tcp.h>
23 #include <net/sock_reuseport.h>
24 #include <net/addrconf.h>
25 #include <trace/hooks/net.h>
26 
27 #if IS_ENABLED(CONFIG_IPV6)
28 /* match_sk*_wildcard == true:  IPV6_ADDR_ANY equals to any IPv6 addresses
29  *				if IPv6 only, and any IPv4 addresses
30  *				if not IPv6 only
31  * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
32  *				IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
33  *				and 0.0.0.0 equals to 0.0.0.0 only
34  */
ipv6_rcv_saddr_equal(const struct in6_addr * sk1_rcv_saddr6,const struct in6_addr * sk2_rcv_saddr6,__be32 sk1_rcv_saddr,__be32 sk2_rcv_saddr,bool sk1_ipv6only,bool sk2_ipv6only,bool match_sk1_wildcard,bool match_sk2_wildcard)35 static bool ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6,
36 				 const struct in6_addr *sk2_rcv_saddr6,
37 				 __be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
38 				 bool sk1_ipv6only, bool sk2_ipv6only,
39 				 bool match_sk1_wildcard,
40 				 bool match_sk2_wildcard)
41 {
42 	int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
43 	int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;
44 
45 	/* if both are mapped, treat as IPv4 */
46 	if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
47 		if (!sk2_ipv6only) {
48 			if (sk1_rcv_saddr == sk2_rcv_saddr)
49 				return true;
50 			return (match_sk1_wildcard && !sk1_rcv_saddr) ||
51 				(match_sk2_wildcard && !sk2_rcv_saddr);
52 		}
53 		return false;
54 	}
55 
56 	if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
57 		return true;
58 
59 	if (addr_type2 == IPV6_ADDR_ANY && match_sk2_wildcard &&
60 	    !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
61 		return true;
62 
63 	if (addr_type == IPV6_ADDR_ANY && match_sk1_wildcard &&
64 	    !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
65 		return true;
66 
67 	if (sk2_rcv_saddr6 &&
68 	    ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
69 		return true;
70 
71 	return false;
72 }
73 #endif
74 
75 /* match_sk*_wildcard == true:  0.0.0.0 equals to any IPv4 addresses
76  * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
77  *				0.0.0.0 only equals to 0.0.0.0
78  */
ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr,__be32 sk2_rcv_saddr,bool sk2_ipv6only,bool match_sk1_wildcard,bool match_sk2_wildcard)79 static bool ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
80 				 bool sk2_ipv6only, bool match_sk1_wildcard,
81 				 bool match_sk2_wildcard)
82 {
83 	if (!sk2_ipv6only) {
84 		if (sk1_rcv_saddr == sk2_rcv_saddr)
85 			return true;
86 		return (match_sk1_wildcard && !sk1_rcv_saddr) ||
87 			(match_sk2_wildcard && !sk2_rcv_saddr);
88 	}
89 	return false;
90 }
91 
inet_rcv_saddr_equal(const struct sock * sk,const struct sock * sk2,bool match_wildcard)92 bool inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
93 			  bool match_wildcard)
94 {
95 #if IS_ENABLED(CONFIG_IPV6)
96 	if (sk->sk_family == AF_INET6)
97 		return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
98 					    inet6_rcv_saddr(sk2),
99 					    sk->sk_rcv_saddr,
100 					    sk2->sk_rcv_saddr,
101 					    ipv6_only_sock(sk),
102 					    ipv6_only_sock(sk2),
103 					    match_wildcard,
104 					    match_wildcard);
105 #endif
106 	return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
107 				    ipv6_only_sock(sk2), match_wildcard,
108 				    match_wildcard);
109 }
110 EXPORT_SYMBOL(inet_rcv_saddr_equal);
111 
inet_rcv_saddr_any(const struct sock * sk)112 bool inet_rcv_saddr_any(const struct sock *sk)
113 {
114 #if IS_ENABLED(CONFIG_IPV6)
115 	if (sk->sk_family == AF_INET6)
116 		return ipv6_addr_any(&sk->sk_v6_rcv_saddr);
117 #endif
118 	return !sk->sk_rcv_saddr;
119 }
120 
121 /**
122  *	inet_sk_get_local_port_range - fetch ephemeral ports range
123  *	@sk: socket
124  *	@low: pointer to low port
125  *	@high: pointer to high port
126  *
127  *	Fetch netns port range (/proc/sys/net/ipv4/ip_local_port_range)
128  *	Range can be overridden if socket got IP_LOCAL_PORT_RANGE option.
129  *	Returns true if IP_LOCAL_PORT_RANGE was set on this socket.
130  */
inet_sk_get_local_port_range(const struct sock * sk,int * low,int * high)131 bool inet_sk_get_local_port_range(const struct sock *sk, int *low, int *high)
132 {
133 	int lo, hi, sk_lo, sk_hi;
134 	bool local_range = false;
135 	u32 sk_range;
136 
137 	inet_get_local_port_range(sock_net(sk), &lo, &hi);
138 
139 	sk_range = READ_ONCE(inet_sk(sk)->local_port_range);
140 	if (unlikely(sk_range)) {
141 		sk_lo = sk_range & 0xffff;
142 		sk_hi = sk_range >> 16;
143 
144 		if (lo <= sk_lo && sk_lo <= hi)
145 			lo = sk_lo;
146 		if (lo <= sk_hi && sk_hi <= hi)
147 			hi = sk_hi;
148 		local_range = true;
149 	}
150 
151 	*low = lo;
152 	*high = hi;
153 	return local_range;
154 }
155 EXPORT_SYMBOL(inet_sk_get_local_port_range);
156 
inet_use_bhash2_on_bind(const struct sock * sk)157 static bool inet_use_bhash2_on_bind(const struct sock *sk)
158 {
159 #if IS_ENABLED(CONFIG_IPV6)
160 	if (sk->sk_family == AF_INET6) {
161 		int addr_type = ipv6_addr_type(&sk->sk_v6_rcv_saddr);
162 
163 		if (addr_type == IPV6_ADDR_ANY)
164 			return false;
165 
166 		if (addr_type != IPV6_ADDR_MAPPED)
167 			return true;
168 	}
169 #endif
170 	return sk->sk_rcv_saddr != htonl(INADDR_ANY);
171 }
172 
inet_bind_conflict(const struct sock * sk,struct sock * sk2,kuid_t sk_uid,bool relax,bool reuseport_cb_ok,bool reuseport_ok)173 static bool inet_bind_conflict(const struct sock *sk, struct sock *sk2,
174 			       kuid_t sk_uid, bool relax,
175 			       bool reuseport_cb_ok, bool reuseport_ok)
176 {
177 	int bound_dev_if2;
178 
179 	if (sk == sk2)
180 		return false;
181 
182 	bound_dev_if2 = READ_ONCE(sk2->sk_bound_dev_if);
183 
184 	if (!sk->sk_bound_dev_if || !bound_dev_if2 ||
185 	    sk->sk_bound_dev_if == bound_dev_if2) {
186 		if (sk->sk_reuse && sk2->sk_reuse &&
187 		    sk2->sk_state != TCP_LISTEN) {
188 			if (!relax || (!reuseport_ok && sk->sk_reuseport &&
189 				       sk2->sk_reuseport && reuseport_cb_ok &&
190 				       (sk2->sk_state == TCP_TIME_WAIT ||
191 					uid_eq(sk_uid, sock_i_uid(sk2)))))
192 				return true;
193 		} else if (!reuseport_ok || !sk->sk_reuseport ||
194 			   !sk2->sk_reuseport || !reuseport_cb_ok ||
195 			   (sk2->sk_state != TCP_TIME_WAIT &&
196 			    !uid_eq(sk_uid, sock_i_uid(sk2)))) {
197 			return true;
198 		}
199 	}
200 	return false;
201 }
202 
__inet_bhash2_conflict(const struct sock * sk,struct sock * sk2,kuid_t sk_uid,bool relax,bool reuseport_cb_ok,bool reuseport_ok)203 static bool __inet_bhash2_conflict(const struct sock *sk, struct sock *sk2,
204 				   kuid_t sk_uid, bool relax,
205 				   bool reuseport_cb_ok, bool reuseport_ok)
206 {
207 	if (ipv6_only_sock(sk2)) {
208 		if (sk->sk_family == AF_INET)
209 			return false;
210 
211 #if IS_ENABLED(CONFIG_IPV6)
212 		if (ipv6_addr_v4mapped(&sk->sk_v6_rcv_saddr))
213 			return false;
214 #endif
215 	}
216 
217 	return inet_bind_conflict(sk, sk2, sk_uid, relax,
218 				  reuseport_cb_ok, reuseport_ok);
219 }
220 
inet_bhash2_conflict(const struct sock * sk,const struct inet_bind2_bucket * tb2,kuid_t sk_uid,bool relax,bool reuseport_cb_ok,bool reuseport_ok)221 static bool inet_bhash2_conflict(const struct sock *sk,
222 				 const struct inet_bind2_bucket *tb2,
223 				 kuid_t sk_uid,
224 				 bool relax, bool reuseport_cb_ok,
225 				 bool reuseport_ok)
226 {
227 	struct sock *sk2;
228 
229 	sk_for_each_bound(sk2, &tb2->owners) {
230 		if (__inet_bhash2_conflict(sk, sk2, sk_uid, relax,
231 					   reuseport_cb_ok, reuseport_ok))
232 			return true;
233 	}
234 
235 	return false;
236 }
237 
238 #define sk_for_each_bound_bhash(__sk, __tb2, __tb)			\
239 	hlist_for_each_entry(__tb2, &(__tb)->bhash2, bhash_node)	\
240 		sk_for_each_bound((__sk), &(__tb2)->owners)
241 
242 /* This should be called only when the tb and tb2 hashbuckets' locks are held */
inet_csk_bind_conflict(const struct sock * sk,const struct inet_bind_bucket * tb,const struct inet_bind2_bucket * tb2,bool relax,bool reuseport_ok)243 static int inet_csk_bind_conflict(const struct sock *sk,
244 				  const struct inet_bind_bucket *tb,
245 				  const struct inet_bind2_bucket *tb2, /* may be null */
246 				  bool relax, bool reuseport_ok)
247 {
248 	kuid_t uid = sock_i_uid((struct sock *)sk);
249 	struct sock_reuseport *reuseport_cb;
250 	bool reuseport_cb_ok;
251 	struct sock *sk2;
252 
253 	rcu_read_lock();
254 	reuseport_cb = rcu_dereference(sk->sk_reuseport_cb);
255 	/* paired with WRITE_ONCE() in __reuseport_(add|detach)_closed_sock */
256 	reuseport_cb_ok = !reuseport_cb || READ_ONCE(reuseport_cb->num_closed_socks);
257 	rcu_read_unlock();
258 
259 	/* Conflicts with an existing IPV6_ADDR_ANY (if ipv6) or INADDR_ANY (if
260 	 * ipv4) should have been checked already. We need to do these two
261 	 * checks separately because their spinlocks have to be acquired/released
262 	 * independently of each other, to prevent possible deadlocks
263 	 */
264 	if (inet_use_bhash2_on_bind(sk))
265 		return tb2 && inet_bhash2_conflict(sk, tb2, uid, relax,
266 						   reuseport_cb_ok, reuseport_ok);
267 
268 	/* Unlike other sk lookup places we do not check
269 	 * for sk_net here, since _all_ the socks listed
270 	 * in tb->owners and tb2->owners list belong
271 	 * to the same net - the one this bucket belongs to.
272 	 */
273 	sk_for_each_bound_bhash(sk2, tb2, tb) {
274 		if (!inet_bind_conflict(sk, sk2, uid, relax, reuseport_cb_ok, reuseport_ok))
275 			continue;
276 
277 		if (inet_rcv_saddr_equal(sk, sk2, true))
278 			return true;
279 	}
280 
281 	return false;
282 }
283 
284 /* Determine if there is a bind conflict with an existing IPV6_ADDR_ANY (if ipv6) or
285  * INADDR_ANY (if ipv4) socket.
286  *
287  * Caller must hold bhash hashbucket lock with local bh disabled, to protect
288  * against concurrent binds on the port for addr any
289  */
inet_bhash2_addr_any_conflict(const struct sock * sk,int port,int l3mdev,bool relax,bool reuseport_ok)290 static bool inet_bhash2_addr_any_conflict(const struct sock *sk, int port, int l3mdev,
291 					  bool relax, bool reuseport_ok)
292 {
293 	kuid_t uid = sock_i_uid((struct sock *)sk);
294 	const struct net *net = sock_net(sk);
295 	struct sock_reuseport *reuseport_cb;
296 	struct inet_bind_hashbucket *head2;
297 	struct inet_bind2_bucket *tb2;
298 	bool conflict = false;
299 	bool reuseport_cb_ok;
300 
301 	rcu_read_lock();
302 	reuseport_cb = rcu_dereference(sk->sk_reuseport_cb);
303 	/* paired with WRITE_ONCE() in __reuseport_(add|detach)_closed_sock */
304 	reuseport_cb_ok = !reuseport_cb || READ_ONCE(reuseport_cb->num_closed_socks);
305 	rcu_read_unlock();
306 
307 	head2 = inet_bhash2_addr_any_hashbucket(sk, net, port);
308 
309 	spin_lock(&head2->lock);
310 
311 	inet_bind_bucket_for_each(tb2, &head2->chain) {
312 		if (!inet_bind2_bucket_match_addr_any(tb2, net, port, l3mdev, sk))
313 			continue;
314 
315 		if (!inet_bhash2_conflict(sk, tb2, uid, relax, reuseport_cb_ok,	reuseport_ok))
316 			continue;
317 
318 		conflict = true;
319 		break;
320 	}
321 
322 	spin_unlock(&head2->lock);
323 
324 	return conflict;
325 }
326 
327 /*
328  * Find an open port number for the socket.  Returns with the
329  * inet_bind_hashbucket locks held if successful.
330  */
331 static struct inet_bind_hashbucket *
inet_csk_find_open_port(const struct sock * sk,struct inet_bind_bucket ** tb_ret,struct inet_bind2_bucket ** tb2_ret,struct inet_bind_hashbucket ** head2_ret,int * port_ret)332 inet_csk_find_open_port(const struct sock *sk, struct inet_bind_bucket **tb_ret,
333 			struct inet_bind2_bucket **tb2_ret,
334 			struct inet_bind_hashbucket **head2_ret, int *port_ret)
335 {
336 	struct inet_hashinfo *hinfo = tcp_or_dccp_get_hashinfo(sk);
337 	int i, low, high, attempt_half, port, l3mdev;
338 	struct inet_bind_hashbucket *head, *head2;
339 	struct net *net = sock_net(sk);
340 	struct inet_bind2_bucket *tb2;
341 	struct inet_bind_bucket *tb;
342 	u32 remaining, offset;
343 	bool relax = false;
344 
345 	l3mdev = inet_sk_bound_l3mdev(sk);
346 ports_exhausted:
347 	attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
348 other_half_scan:
349 	inet_sk_get_local_port_range(sk, &low, &high);
350 	high++; /* [32768, 60999] -> [32768, 61000[ */
351 	if (high - low < 4)
352 		attempt_half = 0;
353 	if (attempt_half) {
354 		int half = low + (((high - low) >> 2) << 1);
355 
356 		if (attempt_half == 1)
357 			high = half;
358 		else
359 			low = half;
360 	}
361 	remaining = high - low;
362 	if (likely(remaining > 1))
363 		remaining &= ~1U;
364 
365 	offset = get_random_u32_below(remaining);
366 	/* __inet_hash_connect() favors ports having @low parity
367 	 * We do the opposite to not pollute connect() users.
368 	 */
369 	offset |= 1U;
370 
371 other_parity_scan:
372 	port = low + offset;
373 	for (i = 0; i < remaining; i += 2, port += 2) {
374 		if (unlikely(port >= high))
375 			port -= remaining;
376 		if (inet_is_local_reserved_port(net, port))
377 			continue;
378 		head = &hinfo->bhash[inet_bhashfn(net, port,
379 						  hinfo->bhash_size)];
380 		spin_lock_bh(&head->lock);
381 		if (inet_use_bhash2_on_bind(sk)) {
382 			if (inet_bhash2_addr_any_conflict(sk, port, l3mdev, relax, false))
383 				goto next_port;
384 		}
385 
386 		head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
387 		spin_lock(&head2->lock);
388 		tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
389 		inet_bind_bucket_for_each(tb, &head->chain)
390 			if (inet_bind_bucket_match(tb, net, port, l3mdev)) {
391 				if (!inet_csk_bind_conflict(sk, tb, tb2,
392 							    relax, false))
393 					goto success;
394 				spin_unlock(&head2->lock);
395 				goto next_port;
396 			}
397 		tb = NULL;
398 		goto success;
399 next_port:
400 		spin_unlock_bh(&head->lock);
401 		cond_resched();
402 	}
403 
404 	offset--;
405 	if (!(offset & 1))
406 		goto other_parity_scan;
407 
408 	if (attempt_half == 1) {
409 		/* OK we now try the upper half of the range */
410 		attempt_half = 2;
411 		goto other_half_scan;
412 	}
413 
414 	if (READ_ONCE(net->ipv4.sysctl_ip_autobind_reuse) && !relax) {
415 		/* We still have a chance to connect to different destinations */
416 		relax = true;
417 		goto ports_exhausted;
418 	}
419 	return NULL;
420 success:
421 	*port_ret = port;
422 	*tb_ret = tb;
423 	*tb2_ret = tb2;
424 	*head2_ret = head2;
425 	return head;
426 }
427 
sk_reuseport_match(struct inet_bind_bucket * tb,struct sock * sk)428 static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
429 				     struct sock *sk)
430 {
431 	kuid_t uid = sock_i_uid(sk);
432 
433 	if (tb->fastreuseport <= 0)
434 		return 0;
435 	if (!sk->sk_reuseport)
436 		return 0;
437 	if (rcu_access_pointer(sk->sk_reuseport_cb))
438 		return 0;
439 	if (!uid_eq(tb->fastuid, uid))
440 		return 0;
441 	/* We only need to check the rcv_saddr if this tb was once marked
442 	 * without fastreuseport and then was reset, as we can only know that
443 	 * the fast_*rcv_saddr doesn't have any conflicts with the socks on the
444 	 * owners list.
445 	 */
446 	if (tb->fastreuseport == FASTREUSEPORT_ANY)
447 		return 1;
448 #if IS_ENABLED(CONFIG_IPV6)
449 	if (tb->fast_sk_family == AF_INET6)
450 		return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
451 					    inet6_rcv_saddr(sk),
452 					    tb->fast_rcv_saddr,
453 					    sk->sk_rcv_saddr,
454 					    tb->fast_ipv6_only,
455 					    ipv6_only_sock(sk), true, false);
456 #endif
457 	return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
458 				    ipv6_only_sock(sk), true, false);
459 }
460 
inet_csk_update_fastreuse(struct inet_bind_bucket * tb,struct sock * sk)461 void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
462 			       struct sock *sk)
463 {
464 	kuid_t uid = sock_i_uid(sk);
465 	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
466 
467 	if (hlist_empty(&tb->bhash2)) {
468 		tb->fastreuse = reuse;
469 		if (sk->sk_reuseport) {
470 			tb->fastreuseport = FASTREUSEPORT_ANY;
471 			tb->fastuid = uid;
472 			tb->fast_rcv_saddr = sk->sk_rcv_saddr;
473 			tb->fast_ipv6_only = ipv6_only_sock(sk);
474 			tb->fast_sk_family = sk->sk_family;
475 #if IS_ENABLED(CONFIG_IPV6)
476 			tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
477 #endif
478 		} else {
479 			tb->fastreuseport = 0;
480 		}
481 	} else {
482 		if (!reuse)
483 			tb->fastreuse = 0;
484 		if (sk->sk_reuseport) {
485 			/* We didn't match or we don't have fastreuseport set on
486 			 * the tb, but we have sk_reuseport set on this socket
487 			 * and we know that there are no bind conflicts with
488 			 * this socket in this tb, so reset our tb's reuseport
489 			 * settings so that any subsequent sockets that match
490 			 * our current socket will be put on the fast path.
491 			 *
492 			 * If we reset we need to set FASTREUSEPORT_STRICT so we
493 			 * do extra checking for all subsequent sk_reuseport
494 			 * socks.
495 			 */
496 			if (!sk_reuseport_match(tb, sk)) {
497 				tb->fastreuseport = FASTREUSEPORT_STRICT;
498 				tb->fastuid = uid;
499 				tb->fast_rcv_saddr = sk->sk_rcv_saddr;
500 				tb->fast_ipv6_only = ipv6_only_sock(sk);
501 				tb->fast_sk_family = sk->sk_family;
502 #if IS_ENABLED(CONFIG_IPV6)
503 				tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
504 #endif
505 			}
506 		} else {
507 			tb->fastreuseport = 0;
508 		}
509 	}
510 }
511 
512 /* Obtain a reference to a local port for the given sock,
513  * if snum is zero it means select any available local port.
514  * We try to allocate an odd port (and leave even ports for connect())
515  */
inet_csk_get_port(struct sock * sk,unsigned short snum)516 int inet_csk_get_port(struct sock *sk, unsigned short snum)
517 {
518 	struct inet_hashinfo *hinfo = tcp_or_dccp_get_hashinfo(sk);
519 	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
520 	bool found_port = false, check_bind_conflict = true;
521 	bool bhash_created = false, bhash2_created = false;
522 	int ret = -EADDRINUSE, port = snum, l3mdev;
523 	struct inet_bind_hashbucket *head, *head2;
524 	struct inet_bind2_bucket *tb2 = NULL;
525 	struct inet_bind_bucket *tb = NULL;
526 	bool head2_lock_acquired = false;
527 	struct net *net = sock_net(sk);
528 
529 	l3mdev = inet_sk_bound_l3mdev(sk);
530 
531 	if (!port) {
532 		head = inet_csk_find_open_port(sk, &tb, &tb2, &head2, &port);
533 		if (!head)
534 			return ret;
535 
536 		head2_lock_acquired = true;
537 
538 		if (tb && tb2)
539 			goto success;
540 		found_port = true;
541 	} else {
542 		head = &hinfo->bhash[inet_bhashfn(net, port,
543 						  hinfo->bhash_size)];
544 		spin_lock_bh(&head->lock);
545 		inet_bind_bucket_for_each(tb, &head->chain)
546 			if (inet_bind_bucket_match(tb, net, port, l3mdev))
547 				break;
548 	}
549 
550 	if (!tb) {
551 		tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep, net,
552 					     head, port, l3mdev);
553 		if (!tb)
554 			goto fail_unlock;
555 		bhash_created = true;
556 	}
557 
558 	if (!found_port) {
559 		if (!hlist_empty(&tb->bhash2)) {
560 			if (sk->sk_reuse == SK_FORCE_REUSE ||
561 			    (tb->fastreuse > 0 && reuse) ||
562 			    sk_reuseport_match(tb, sk))
563 				check_bind_conflict = false;
564 		}
565 
566 		if (check_bind_conflict && inet_use_bhash2_on_bind(sk)) {
567 			if (inet_bhash2_addr_any_conflict(sk, port, l3mdev, true, true))
568 				goto fail_unlock;
569 		}
570 
571 		head2 = inet_bhashfn_portaddr(hinfo, sk, net, port);
572 		spin_lock(&head2->lock);
573 		head2_lock_acquired = true;
574 		tb2 = inet_bind2_bucket_find(head2, net, port, l3mdev, sk);
575 	}
576 
577 	if (!tb2) {
578 		tb2 = inet_bind2_bucket_create(hinfo->bind2_bucket_cachep,
579 					       net, head2, tb, sk);
580 		if (!tb2)
581 			goto fail_unlock;
582 		bhash2_created = true;
583 	}
584 
585 	if (!found_port && check_bind_conflict) {
586 		if (inet_csk_bind_conflict(sk, tb, tb2, true, true))
587 			goto fail_unlock;
588 	}
589 
590 success:
591 	inet_csk_update_fastreuse(tb, sk);
592 
593 	if (!inet_csk(sk)->icsk_bind_hash)
594 		inet_bind_hash(sk, tb, tb2, port);
595 	WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
596 	WARN_ON(inet_csk(sk)->icsk_bind2_hash != tb2);
597 	ret = 0;
598 
599 fail_unlock:
600 	if (ret) {
601 		if (bhash2_created)
602 			inet_bind2_bucket_destroy(hinfo->bind2_bucket_cachep, tb2);
603 		if (bhash_created)
604 			inet_bind_bucket_destroy(hinfo->bind_bucket_cachep, tb);
605 	}
606 	if (head2_lock_acquired)
607 		spin_unlock(&head2->lock);
608 	spin_unlock_bh(&head->lock);
609 	return ret;
610 }
611 EXPORT_SYMBOL_GPL(inet_csk_get_port);
612 
613 /*
614  * Wait for an incoming connection, avoid race conditions. This must be called
615  * with the socket locked.
616  */
inet_csk_wait_for_connect(struct sock * sk,long timeo)617 static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
618 {
619 	struct inet_connection_sock *icsk = inet_csk(sk);
620 	DEFINE_WAIT(wait);
621 	int err;
622 
623 	/*
624 	 * True wake-one mechanism for incoming connections: only
625 	 * one process gets woken up, not the 'whole herd'.
626 	 * Since we do not 'race & poll' for established sockets
627 	 * anymore, the common case will execute the loop only once.
628 	 *
629 	 * Subtle issue: "add_wait_queue_exclusive()" will be added
630 	 * after any current non-exclusive waiters, and we know that
631 	 * it will always _stay_ after any new non-exclusive waiters
632 	 * because all non-exclusive waiters are added at the
633 	 * beginning of the wait-queue. As such, it's ok to "drop"
634 	 * our exclusiveness temporarily when we get woken up without
635 	 * having to remove and re-insert us on the wait queue.
636 	 */
637 	for (;;) {
638 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
639 					  TASK_INTERRUPTIBLE);
640 		release_sock(sk);
641 		if (reqsk_queue_empty(&icsk->icsk_accept_queue))
642 			timeo = schedule_timeout(timeo);
643 		sched_annotate_sleep();
644 		lock_sock(sk);
645 		err = 0;
646 		if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
647 			break;
648 		err = -EINVAL;
649 		if (sk->sk_state != TCP_LISTEN)
650 			break;
651 		err = sock_intr_errno(timeo);
652 		if (signal_pending(current))
653 			break;
654 		err = -EAGAIN;
655 		if (!timeo)
656 			break;
657 	}
658 	finish_wait(sk_sleep(sk), &wait);
659 	return err;
660 }
661 
662 /*
663  * This will accept the next outstanding connection.
664  */
inet_csk_accept(struct sock * sk,struct proto_accept_arg * arg)665 struct sock *inet_csk_accept(struct sock *sk, struct proto_accept_arg *arg)
666 {
667 	struct inet_connection_sock *icsk = inet_csk(sk);
668 	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
669 	struct request_sock *req;
670 	struct sock *newsk;
671 	int error;
672 
673 	lock_sock(sk);
674 
675 	/* We need to make sure that this socket is listening,
676 	 * and that it has something pending.
677 	 */
678 	error = -EINVAL;
679 	if (sk->sk_state != TCP_LISTEN)
680 		goto out_err;
681 
682 	/* Find already established connection */
683 	if (reqsk_queue_empty(queue)) {
684 		long timeo = sock_rcvtimeo(sk, arg->flags & O_NONBLOCK);
685 
686 		/* If this is a non blocking socket don't sleep */
687 		error = -EAGAIN;
688 		if (!timeo)
689 			goto out_err;
690 
691 		error = inet_csk_wait_for_connect(sk, timeo);
692 		if (error)
693 			goto out_err;
694 	}
695 	req = reqsk_queue_remove(queue, sk);
696 	arg->is_empty = reqsk_queue_empty(queue);
697 	newsk = req->sk;
698 
699 	if (sk->sk_protocol == IPPROTO_TCP &&
700 	    tcp_rsk(req)->tfo_listener) {
701 		spin_lock_bh(&queue->fastopenq.lock);
702 		if (tcp_rsk(req)->tfo_listener) {
703 			/* We are still waiting for the final ACK from 3WHS
704 			 * so can't free req now. Instead, we set req->sk to
705 			 * NULL to signify that the child socket is taken
706 			 * so reqsk_fastopen_remove() will free the req
707 			 * when 3WHS finishes (or is aborted).
708 			 */
709 			req->sk = NULL;
710 			req = NULL;
711 		}
712 		spin_unlock_bh(&queue->fastopenq.lock);
713 	}
714 
715 out:
716 	release_sock(sk);
717 	if (newsk && mem_cgroup_sockets_enabled) {
718 		gfp_t gfp = GFP_KERNEL | __GFP_NOFAIL;
719 		int amt = 0;
720 
721 		/* atomically get the memory usage, set and charge the
722 		 * newsk->sk_memcg.
723 		 */
724 		lock_sock(newsk);
725 
726 		mem_cgroup_sk_alloc(newsk);
727 		if (newsk->sk_memcg) {
728 			/* The socket has not been accepted yet, no need
729 			 * to look at newsk->sk_wmem_queued.
730 			 */
731 			amt = sk_mem_pages(newsk->sk_forward_alloc +
732 					   atomic_read(&newsk->sk_rmem_alloc));
733 		}
734 
735 		if (amt)
736 			mem_cgroup_charge_skmem(newsk->sk_memcg, amt, gfp);
737 		kmem_cache_charge(newsk, gfp);
738 
739 		release_sock(newsk);
740 	}
741 	if (req)
742 		reqsk_put(req);
743 
744 	if (newsk)
745 		inet_init_csk_locks(newsk);
746 
747 	return newsk;
748 out_err:
749 	newsk = NULL;
750 	req = NULL;
751 	arg->err = error;
752 	goto out;
753 }
754 EXPORT_SYMBOL(inet_csk_accept);
755 
756 /*
757  * Using different timers for retransmit, delayed acks and probes
758  * We may wish use just one timer maintaining a list of expire jiffies
759  * to optimize.
760  */
inet_csk_init_xmit_timers(struct sock * sk,void (* retransmit_handler)(struct timer_list * t),void (* delack_handler)(struct timer_list * t),void (* keepalive_handler)(struct timer_list * t))761 void inet_csk_init_xmit_timers(struct sock *sk,
762 			       void (*retransmit_handler)(struct timer_list *t),
763 			       void (*delack_handler)(struct timer_list *t),
764 			       void (*keepalive_handler)(struct timer_list *t))
765 {
766 	struct inet_connection_sock *icsk = inet_csk(sk);
767 
768 	timer_setup(&icsk->icsk_retransmit_timer, retransmit_handler, 0);
769 	timer_setup(&icsk->icsk_delack_timer, delack_handler, 0);
770 	timer_setup(&sk->sk_timer, keepalive_handler, 0);
771 	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
772 }
773 EXPORT_SYMBOL(inet_csk_init_xmit_timers);
774 
inet_csk_clear_xmit_timers(struct sock * sk)775 void inet_csk_clear_xmit_timers(struct sock *sk)
776 {
777 	struct inet_connection_sock *icsk = inet_csk(sk);
778 
779 	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
780 
781 	sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
782 	sk_stop_timer(sk, &icsk->icsk_delack_timer);
783 	sk_stop_timer(sk, &sk->sk_timer);
784 }
785 EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
786 
inet_csk_clear_xmit_timers_sync(struct sock * sk)787 void inet_csk_clear_xmit_timers_sync(struct sock *sk)
788 {
789 	struct inet_connection_sock *icsk = inet_csk(sk);
790 
791 	/* ongoing timer handlers need to acquire socket lock. */
792 	sock_not_owned_by_me(sk);
793 
794 	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
795 
796 	sk_stop_timer_sync(sk, &icsk->icsk_retransmit_timer);
797 	sk_stop_timer_sync(sk, &icsk->icsk_delack_timer);
798 	sk_stop_timer_sync(sk, &sk->sk_timer);
799 }
800 
inet_csk_delete_keepalive_timer(struct sock * sk)801 void inet_csk_delete_keepalive_timer(struct sock *sk)
802 {
803 	sk_stop_timer(sk, &sk->sk_timer);
804 }
805 EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
806 
inet_csk_reset_keepalive_timer(struct sock * sk,unsigned long len)807 void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
808 {
809 	sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
810 }
811 EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
812 
inet_csk_route_req(const struct sock * sk,struct flowi4 * fl4,const struct request_sock * req)813 struct dst_entry *inet_csk_route_req(const struct sock *sk,
814 				     struct flowi4 *fl4,
815 				     const struct request_sock *req)
816 {
817 	const struct inet_request_sock *ireq = inet_rsk(req);
818 	struct net *net = read_pnet(&ireq->ireq_net);
819 	struct ip_options_rcu *opt;
820 	struct rtable *rt;
821 
822 	rcu_read_lock();
823 	opt = rcu_dereference(ireq->ireq_opt);
824 
825 	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
826 			   ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
827 			   sk->sk_protocol, inet_sk_flowi_flags(sk),
828 			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
829 			   ireq->ir_loc_addr, ireq->ir_rmt_port,
830 			   htons(ireq->ir_num), sk->sk_uid);
831 	security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
832 	rt = ip_route_output_flow(net, fl4, sk);
833 	if (IS_ERR(rt))
834 		goto no_route;
835 	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
836 		goto route_err;
837 	rcu_read_unlock();
838 	return &rt->dst;
839 
840 route_err:
841 	ip_rt_put(rt);
842 no_route:
843 	rcu_read_unlock();
844 	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
845 	return NULL;
846 }
847 EXPORT_SYMBOL_GPL(inet_csk_route_req);
848 
inet_csk_route_child_sock(const struct sock * sk,struct sock * newsk,const struct request_sock * req)849 struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
850 					    struct sock *newsk,
851 					    const struct request_sock *req)
852 {
853 	const struct inet_request_sock *ireq = inet_rsk(req);
854 	struct net *net = read_pnet(&ireq->ireq_net);
855 	struct inet_sock *newinet = inet_sk(newsk);
856 	struct ip_options_rcu *opt;
857 	struct flowi4 *fl4;
858 	struct rtable *rt;
859 
860 	opt = rcu_dereference(ireq->ireq_opt);
861 	fl4 = &newinet->cork.fl.u.ip4;
862 
863 	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
864 			   ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
865 			   sk->sk_protocol, inet_sk_flowi_flags(sk),
866 			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
867 			   ireq->ir_loc_addr, ireq->ir_rmt_port,
868 			   htons(ireq->ir_num), sk->sk_uid);
869 	security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
870 	rt = ip_route_output_flow(net, fl4, sk);
871 	if (IS_ERR(rt))
872 		goto no_route;
873 	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
874 		goto route_err;
875 	return &rt->dst;
876 
877 route_err:
878 	ip_rt_put(rt);
879 no_route:
880 	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
881 	return NULL;
882 }
883 EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
884 
885 /* Decide when to expire the request and when to resend SYN-ACK */
syn_ack_recalc(struct request_sock * req,const int max_syn_ack_retries,const u8 rskq_defer_accept,int * expire,int * resend)886 static void syn_ack_recalc(struct request_sock *req,
887 			   const int max_syn_ack_retries,
888 			   const u8 rskq_defer_accept,
889 			   int *expire, int *resend)
890 {
891 	if (!rskq_defer_accept) {
892 		*expire = req->num_timeout >= max_syn_ack_retries;
893 		*resend = 1;
894 		return;
895 	}
896 	*expire = req->num_timeout >= max_syn_ack_retries &&
897 		  (!inet_rsk(req)->acked || req->num_timeout >= rskq_defer_accept);
898 	/* Do not resend while waiting for data after ACK,
899 	 * start to resend on end of deferring period to give
900 	 * last chance for data or ACK to create established socket.
901 	 */
902 	*resend = !inet_rsk(req)->acked ||
903 		  req->num_timeout >= rskq_defer_accept - 1;
904 }
905 
inet_rtx_syn_ack(const struct sock * parent,struct request_sock * req)906 int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
907 {
908 	int err = req->rsk_ops->rtx_syn_ack(parent, req);
909 
910 	if (!err)
911 		req->num_retrans++;
912 	return err;
913 }
914 EXPORT_SYMBOL(inet_rtx_syn_ack);
915 
916 static struct request_sock *
reqsk_alloc_noprof(const struct request_sock_ops * ops,struct sock * sk_listener,bool attach_listener)917 reqsk_alloc_noprof(const struct request_sock_ops *ops, struct sock *sk_listener,
918 		   bool attach_listener)
919 {
920 	struct request_sock *req;
921 
922 	req = kmem_cache_alloc_noprof(ops->slab, GFP_ATOMIC | __GFP_NOWARN);
923 	if (!req)
924 		return NULL;
925 	req->rsk_listener = NULL;
926 	if (attach_listener) {
927 		if (unlikely(!refcount_inc_not_zero(&sk_listener->sk_refcnt))) {
928 			kmem_cache_free(ops->slab, req);
929 			return NULL;
930 		}
931 		req->rsk_listener = sk_listener;
932 	}
933 	req->rsk_ops = ops;
934 	req_to_sk(req)->sk_prot = sk_listener->sk_prot;
935 	sk_node_init(&req_to_sk(req)->sk_node);
936 	sk_tx_queue_clear(req_to_sk(req));
937 	req->saved_syn = NULL;
938 	req->syncookie = 0;
939 	req->timeout = 0;
940 	req->num_timeout = 0;
941 	req->num_retrans = 0;
942 	req->sk = NULL;
943 	refcount_set(&req->rsk_refcnt, 0);
944 
945 	return req;
946 }
947 #define reqsk_alloc(...)	alloc_hooks(reqsk_alloc_noprof(__VA_ARGS__))
948 
inet_reqsk_alloc(const struct request_sock_ops * ops,struct sock * sk_listener,bool attach_listener)949 struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops,
950 				      struct sock *sk_listener,
951 				      bool attach_listener)
952 {
953 	struct request_sock *req = reqsk_alloc(ops, sk_listener,
954 					       attach_listener);
955 
956 	if (req) {
957 		struct inet_request_sock *ireq = inet_rsk(req);
958 
959 		ireq->ireq_opt = NULL;
960 #if IS_ENABLED(CONFIG_IPV6)
961 		ireq->pktopts = NULL;
962 #endif
963 		atomic64_set(&ireq->ir_cookie, 0);
964 		ireq->ireq_state = TCP_NEW_SYN_RECV;
965 		write_pnet(&ireq->ireq_net, sock_net(sk_listener));
966 		ireq->ireq_family = sk_listener->sk_family;
967 		req->timeout = TCP_TIMEOUT_INIT;
968 	}
969 
970 	return req;
971 }
972 EXPORT_SYMBOL(inet_reqsk_alloc);
973 
inet_reqsk_clone(struct request_sock * req,struct sock * sk)974 static struct request_sock *inet_reqsk_clone(struct request_sock *req,
975 					     struct sock *sk)
976 {
977 	struct sock *req_sk, *nreq_sk;
978 	struct request_sock *nreq;
979 
980 	nreq = kmem_cache_alloc(req->rsk_ops->slab, GFP_ATOMIC | __GFP_NOWARN);
981 	if (!nreq) {
982 		__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
983 
984 		/* paired with refcount_inc_not_zero() in reuseport_migrate_sock() */
985 		sock_put(sk);
986 		return NULL;
987 	}
988 
989 	req_sk = req_to_sk(req);
990 	nreq_sk = req_to_sk(nreq);
991 
992 	memcpy(nreq_sk, req_sk,
993 	       offsetof(struct sock, sk_dontcopy_begin));
994 	unsafe_memcpy(&nreq_sk->sk_dontcopy_end, &req_sk->sk_dontcopy_end,
995 		      req->rsk_ops->obj_size - offsetof(struct sock, sk_dontcopy_end),
996 		      /* alloc is larger than struct, see above */);
997 
998 	sk_node_init(&nreq_sk->sk_node);
999 	nreq_sk->sk_tx_queue_mapping = req_sk->sk_tx_queue_mapping;
1000 #ifdef CONFIG_SOCK_RX_QUEUE_MAPPING
1001 	nreq_sk->sk_rx_queue_mapping = req_sk->sk_rx_queue_mapping;
1002 #endif
1003 	nreq_sk->sk_incoming_cpu = req_sk->sk_incoming_cpu;
1004 
1005 	nreq->rsk_listener = sk;
1006 
1007 	/* We need not acquire fastopenq->lock
1008 	 * because the child socket is locked in inet_csk_listen_stop().
1009 	 */
1010 	if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(nreq)->tfo_listener)
1011 		rcu_assign_pointer(tcp_sk(nreq->sk)->fastopen_rsk, nreq);
1012 
1013 	return nreq;
1014 }
1015 
reqsk_queue_migrated(struct request_sock_queue * queue,const struct request_sock * req)1016 static void reqsk_queue_migrated(struct request_sock_queue *queue,
1017 				 const struct request_sock *req)
1018 {
1019 	if (req->num_timeout == 0)
1020 		atomic_inc(&queue->young);
1021 	atomic_inc(&queue->qlen);
1022 }
1023 
reqsk_migrate_reset(struct request_sock * req)1024 static void reqsk_migrate_reset(struct request_sock *req)
1025 {
1026 	req->saved_syn = NULL;
1027 #if IS_ENABLED(CONFIG_IPV6)
1028 	inet_rsk(req)->ipv6_opt = NULL;
1029 	inet_rsk(req)->pktopts = NULL;
1030 #else
1031 	inet_rsk(req)->ireq_opt = NULL;
1032 #endif
1033 }
1034 
1035 /* return true if req was found in the ehash table */
reqsk_queue_unlink(struct request_sock * req)1036 static bool reqsk_queue_unlink(struct request_sock *req)
1037 {
1038 	struct sock *sk = req_to_sk(req);
1039 	bool found = false;
1040 
1041 	if (sk_hashed(sk)) {
1042 		struct inet_hashinfo *hashinfo = tcp_or_dccp_get_hashinfo(sk);
1043 		spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
1044 
1045 		spin_lock(lock);
1046 		found = __sk_nulls_del_node_init_rcu(sk);
1047 		spin_unlock(lock);
1048 	}
1049 
1050 	return found;
1051 }
1052 
__inet_csk_reqsk_queue_drop(struct sock * sk,struct request_sock * req,bool from_timer)1053 static bool __inet_csk_reqsk_queue_drop(struct sock *sk,
1054 					struct request_sock *req,
1055 					bool from_timer)
1056 {
1057 	bool unlinked = reqsk_queue_unlink(req);
1058 
1059 	if (!from_timer && timer_delete_sync(&req->rsk_timer))
1060 		reqsk_put(req);
1061 
1062 	if (unlinked) {
1063 		reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
1064 		reqsk_put(req);
1065 	}
1066 
1067 	return unlinked;
1068 }
1069 
inet_csk_reqsk_queue_drop(struct sock * sk,struct request_sock * req)1070 bool inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
1071 {
1072 	return __inet_csk_reqsk_queue_drop(sk, req, false);
1073 }
1074 EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
1075 
inet_csk_reqsk_queue_drop_and_put(struct sock * sk,struct request_sock * req)1076 void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
1077 {
1078 	inet_csk_reqsk_queue_drop(sk, req);
1079 	reqsk_put(req);
1080 }
1081 EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
1082 
reqsk_timer_handler(struct timer_list * t)1083 static void reqsk_timer_handler(struct timer_list *t)
1084 {
1085 	struct request_sock *req = from_timer(req, t, rsk_timer);
1086 	struct request_sock *nreq = NULL, *oreq = req;
1087 	struct sock *sk_listener = req->rsk_listener;
1088 	struct inet_connection_sock *icsk;
1089 	struct request_sock_queue *queue;
1090 	struct net *net;
1091 	int max_syn_ack_retries, qlen, expire = 0, resend = 0;
1092 
1093 	if (inet_sk_state_load(sk_listener) != TCP_LISTEN) {
1094 		struct sock *nsk;
1095 
1096 		nsk = reuseport_migrate_sock(sk_listener, req_to_sk(req), NULL);
1097 		if (!nsk)
1098 			goto drop;
1099 
1100 		nreq = inet_reqsk_clone(req, nsk);
1101 		if (!nreq)
1102 			goto drop;
1103 
1104 		/* The new timer for the cloned req can decrease the 2
1105 		 * by calling inet_csk_reqsk_queue_drop_and_put(), so
1106 		 * hold another count to prevent use-after-free and
1107 		 * call reqsk_put() just before return.
1108 		 */
1109 		refcount_set(&nreq->rsk_refcnt, 2 + 1);
1110 		timer_setup(&nreq->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
1111 		reqsk_queue_migrated(&inet_csk(nsk)->icsk_accept_queue, req);
1112 
1113 		req = nreq;
1114 		sk_listener = nsk;
1115 	}
1116 
1117 	icsk = inet_csk(sk_listener);
1118 	net = sock_net(sk_listener);
1119 	max_syn_ack_retries = READ_ONCE(icsk->icsk_syn_retries) ? :
1120 		READ_ONCE(net->ipv4.sysctl_tcp_synack_retries);
1121 	/* Normally all the openreqs are young and become mature
1122 	 * (i.e. converted to established socket) for first timeout.
1123 	 * If synack was not acknowledged for 1 second, it means
1124 	 * one of the following things: synack was lost, ack was lost,
1125 	 * rtt is high or nobody planned to ack (i.e. synflood).
1126 	 * When server is a bit loaded, queue is populated with old
1127 	 * open requests, reducing effective size of queue.
1128 	 * When server is well loaded, queue size reduces to zero
1129 	 * after several minutes of work. It is not synflood,
1130 	 * it is normal operation. The solution is pruning
1131 	 * too old entries overriding normal timeout, when
1132 	 * situation becomes dangerous.
1133 	 *
1134 	 * Essentially, we reserve half of room for young
1135 	 * embrions; and abort old ones without pity, if old
1136 	 * ones are about to clog our table.
1137 	 */
1138 	queue = &icsk->icsk_accept_queue;
1139 	qlen = reqsk_queue_len(queue);
1140 	if ((qlen << 1) > max(8U, READ_ONCE(sk_listener->sk_max_ack_backlog))) {
1141 		int young = reqsk_queue_len_young(queue) << 1;
1142 
1143 		while (max_syn_ack_retries > 2) {
1144 			if (qlen < young)
1145 				break;
1146 			max_syn_ack_retries--;
1147 			young <<= 1;
1148 		}
1149 	}
1150 	syn_ack_recalc(req, max_syn_ack_retries, READ_ONCE(queue->rskq_defer_accept),
1151 		       &expire, &resend);
1152 	req->rsk_ops->syn_ack_timeout(req);
1153 	if (!expire &&
1154 	    (!resend ||
1155 	     !inet_rtx_syn_ack(sk_listener, req) ||
1156 	     inet_rsk(req)->acked)) {
1157 		if (req->num_timeout++ == 0)
1158 			atomic_dec(&queue->young);
1159 		mod_timer(&req->rsk_timer, jiffies + reqsk_timeout(req, TCP_RTO_MAX));
1160 
1161 		if (!nreq)
1162 			return;
1163 
1164 		if (!inet_ehash_insert(req_to_sk(nreq), req_to_sk(oreq), NULL)) {
1165 			/* delete timer */
1166 			__inet_csk_reqsk_queue_drop(sk_listener, nreq, true);
1167 			goto no_ownership;
1168 		}
1169 
1170 		__NET_INC_STATS(net, LINUX_MIB_TCPMIGRATEREQSUCCESS);
1171 		reqsk_migrate_reset(oreq);
1172 		reqsk_queue_removed(&inet_csk(oreq->rsk_listener)->icsk_accept_queue, oreq);
1173 		reqsk_put(oreq);
1174 
1175 		reqsk_put(nreq);
1176 		return;
1177 	}
1178 
1179 	/* Even if we can clone the req, we may need not retransmit any more
1180 	 * SYN+ACKs (nreq->num_timeout > max_syn_ack_retries, etc), or another
1181 	 * CPU may win the "own_req" race so that inet_ehash_insert() fails.
1182 	 */
1183 	if (nreq) {
1184 		__NET_INC_STATS(net, LINUX_MIB_TCPMIGRATEREQFAILURE);
1185 no_ownership:
1186 		reqsk_migrate_reset(nreq);
1187 		reqsk_queue_removed(queue, nreq);
1188 		__reqsk_free(nreq);
1189 	}
1190 
1191 drop:
1192 	__inet_csk_reqsk_queue_drop(sk_listener, oreq, true);
1193 	reqsk_put(oreq);
1194 }
1195 
reqsk_queue_hash_req(struct request_sock * req,unsigned long timeout)1196 static bool reqsk_queue_hash_req(struct request_sock *req,
1197 				 unsigned long timeout)
1198 {
1199 	bool found_dup_sk = false;
1200 
1201 	if (!inet_ehash_insert(req_to_sk(req), NULL, &found_dup_sk))
1202 		return false;
1203 
1204 	/* The timer needs to be setup after a successful insertion. */
1205 	timer_setup(&req->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
1206 	mod_timer(&req->rsk_timer, jiffies + timeout);
1207 
1208 	/* before letting lookups find us, make sure all req fields
1209 	 * are committed to memory and refcnt initialized.
1210 	 */
1211 	smp_wmb();
1212 	refcount_set(&req->rsk_refcnt, 2 + 1);
1213 	return true;
1214 }
1215 
inet_csk_reqsk_queue_hash_add(struct sock * sk,struct request_sock * req,unsigned long timeout)1216 bool inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
1217 				   unsigned long timeout)
1218 {
1219 	if (!reqsk_queue_hash_req(req, timeout))
1220 		return false;
1221 
1222 	inet_csk_reqsk_queue_added(sk);
1223 	return true;
1224 }
1225 EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
1226 
inet_clone_ulp(const struct request_sock * req,struct sock * newsk,const gfp_t priority)1227 static void inet_clone_ulp(const struct request_sock *req, struct sock *newsk,
1228 			   const gfp_t priority)
1229 {
1230 	struct inet_connection_sock *icsk = inet_csk(newsk);
1231 
1232 	if (!icsk->icsk_ulp_ops)
1233 		return;
1234 
1235 	icsk->icsk_ulp_ops->clone(req, newsk, priority);
1236 }
1237 
1238 /**
1239  *	inet_csk_clone_lock - clone an inet socket, and lock its clone
1240  *	@sk: the socket to clone
1241  *	@req: request_sock
1242  *	@priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
1243  *
1244  *	Caller must unlock socket even in error path (bh_unlock_sock(newsk))
1245  */
inet_csk_clone_lock(const struct sock * sk,const struct request_sock * req,const gfp_t priority)1246 struct sock *inet_csk_clone_lock(const struct sock *sk,
1247 				 const struct request_sock *req,
1248 				 const gfp_t priority)
1249 {
1250 	struct sock *newsk = sk_clone_lock(sk, priority);
1251 
1252 	if (newsk) {
1253 		struct inet_connection_sock *newicsk = inet_csk(newsk);
1254 
1255 		inet_sk_set_state(newsk, TCP_SYN_RECV);
1256 		newicsk->icsk_bind_hash = NULL;
1257 		newicsk->icsk_bind2_hash = NULL;
1258 
1259 		inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
1260 		inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
1261 		inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
1262 
1263 		/* listeners have SOCK_RCU_FREE, not the children */
1264 		sock_reset_flag(newsk, SOCK_RCU_FREE);
1265 
1266 		inet_sk(newsk)->mc_list = NULL;
1267 
1268 		newsk->sk_mark = inet_rsk(req)->ir_mark;
1269 		atomic64_set(&newsk->sk_cookie,
1270 			     atomic64_read(&inet_rsk(req)->ir_cookie));
1271 
1272 		newicsk->icsk_retransmits = 0;
1273 		newicsk->icsk_backoff	  = 0;
1274 		newicsk->icsk_probes_out  = 0;
1275 		newicsk->icsk_probes_tstamp = 0;
1276 
1277 		/* Deinitialize accept_queue to trap illegal accesses. */
1278 		memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
1279 
1280 		inet_clone_ulp(req, newsk, priority);
1281 
1282 		security_inet_csk_clone(newsk, req);
1283 
1284 		trace_android_vh_inet_csk_clone_lock(newsk, req);
1285 	}
1286 	return newsk;
1287 }
1288 EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
1289 
1290 /*
1291  * At this point, there should be no process reference to this
1292  * socket, and thus no user references at all.  Therefore we
1293  * can assume the socket waitqueue is inactive and nobody will
1294  * try to jump onto it.
1295  */
inet_csk_destroy_sock(struct sock * sk)1296 void inet_csk_destroy_sock(struct sock *sk)
1297 {
1298 	WARN_ON(sk->sk_state != TCP_CLOSE);
1299 	WARN_ON(!sock_flag(sk, SOCK_DEAD));
1300 
1301 	/* It cannot be in hash table! */
1302 	WARN_ON(!sk_unhashed(sk));
1303 
1304 	/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
1305 	WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
1306 
1307 	sk->sk_prot->destroy(sk);
1308 
1309 	sk_stream_kill_queues(sk);
1310 
1311 	xfrm_sk_free_policy(sk);
1312 
1313 	this_cpu_dec(*sk->sk_prot->orphan_count);
1314 
1315 	sock_put(sk);
1316 }
1317 EXPORT_SYMBOL(inet_csk_destroy_sock);
1318 
1319 /* This function allows to force a closure of a socket after the call to
1320  * tcp/dccp_create_openreq_child().
1321  */
inet_csk_prepare_forced_close(struct sock * sk)1322 void inet_csk_prepare_forced_close(struct sock *sk)
1323 	__releases(&sk->sk_lock.slock)
1324 {
1325 	/* sk_clone_lock locked the socket and set refcnt to 2 */
1326 	bh_unlock_sock(sk);
1327 	sock_put(sk);
1328 	inet_csk_prepare_for_destroy_sock(sk);
1329 	inet_sk(sk)->inet_num = 0;
1330 }
1331 EXPORT_SYMBOL(inet_csk_prepare_forced_close);
1332 
inet_ulp_can_listen(const struct sock * sk)1333 static int inet_ulp_can_listen(const struct sock *sk)
1334 {
1335 	const struct inet_connection_sock *icsk = inet_csk(sk);
1336 
1337 	if (icsk->icsk_ulp_ops && !icsk->icsk_ulp_ops->clone)
1338 		return -EINVAL;
1339 
1340 	return 0;
1341 }
1342 
inet_csk_listen_start(struct sock * sk)1343 int inet_csk_listen_start(struct sock *sk)
1344 {
1345 	struct inet_connection_sock *icsk = inet_csk(sk);
1346 	struct inet_sock *inet = inet_sk(sk);
1347 	int err;
1348 
1349 	err = inet_ulp_can_listen(sk);
1350 	if (unlikely(err))
1351 		return err;
1352 
1353 	reqsk_queue_alloc(&icsk->icsk_accept_queue);
1354 
1355 	sk->sk_ack_backlog = 0;
1356 	inet_csk_delack_init(sk);
1357 
1358 	/* There is race window here: we announce ourselves listening,
1359 	 * but this transition is still not validated by get_port().
1360 	 * It is OK, because this socket enters to hash table only
1361 	 * after validation is complete.
1362 	 */
1363 	inet_sk_state_store(sk, TCP_LISTEN);
1364 	err = sk->sk_prot->get_port(sk, inet->inet_num);
1365 	if (!err) {
1366 		inet->inet_sport = htons(inet->inet_num);
1367 
1368 		sk_dst_reset(sk);
1369 		err = sk->sk_prot->hash(sk);
1370 
1371 		if (likely(!err))
1372 			return 0;
1373 	}
1374 
1375 	inet_sk_set_state(sk, TCP_CLOSE);
1376 	return err;
1377 }
1378 EXPORT_SYMBOL_GPL(inet_csk_listen_start);
1379 
inet_child_forget(struct sock * sk,struct request_sock * req,struct sock * child)1380 static void inet_child_forget(struct sock *sk, struct request_sock *req,
1381 			      struct sock *child)
1382 {
1383 	sk->sk_prot->disconnect(child, O_NONBLOCK);
1384 
1385 	sock_orphan(child);
1386 
1387 	this_cpu_inc(*sk->sk_prot->orphan_count);
1388 
1389 	if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
1390 		BUG_ON(rcu_access_pointer(tcp_sk(child)->fastopen_rsk) != req);
1391 		BUG_ON(sk != req->rsk_listener);
1392 
1393 		/* Paranoid, to prevent race condition if
1394 		 * an inbound pkt destined for child is
1395 		 * blocked by sock lock in tcp_v4_rcv().
1396 		 * Also to satisfy an assertion in
1397 		 * tcp_v4_destroy_sock().
1398 		 */
1399 		RCU_INIT_POINTER(tcp_sk(child)->fastopen_rsk, NULL);
1400 	}
1401 	inet_csk_destroy_sock(child);
1402 }
1403 
inet_csk_reqsk_queue_add(struct sock * sk,struct request_sock * req,struct sock * child)1404 struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
1405 				      struct request_sock *req,
1406 				      struct sock *child)
1407 {
1408 	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
1409 
1410 	spin_lock(&queue->rskq_lock);
1411 	if (unlikely(sk->sk_state != TCP_LISTEN)) {
1412 		inet_child_forget(sk, req, child);
1413 		child = NULL;
1414 	} else {
1415 		req->sk = child;
1416 		req->dl_next = NULL;
1417 		if (queue->rskq_accept_head == NULL)
1418 			WRITE_ONCE(queue->rskq_accept_head, req);
1419 		else
1420 			queue->rskq_accept_tail->dl_next = req;
1421 		queue->rskq_accept_tail = req;
1422 		sk_acceptq_added(sk);
1423 	}
1424 	spin_unlock(&queue->rskq_lock);
1425 	return child;
1426 }
1427 EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
1428 
inet_csk_complete_hashdance(struct sock * sk,struct sock * child,struct request_sock * req,bool own_req)1429 struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
1430 					 struct request_sock *req, bool own_req)
1431 {
1432 	if (own_req) {
1433 		inet_csk_reqsk_queue_drop(req->rsk_listener, req);
1434 		reqsk_queue_removed(&inet_csk(req->rsk_listener)->icsk_accept_queue, req);
1435 
1436 		if (sk != req->rsk_listener) {
1437 			/* another listening sk has been selected,
1438 			 * migrate the req to it.
1439 			 */
1440 			struct request_sock *nreq;
1441 
1442 			/* hold a refcnt for the nreq->rsk_listener
1443 			 * which is assigned in inet_reqsk_clone()
1444 			 */
1445 			sock_hold(sk);
1446 			nreq = inet_reqsk_clone(req, sk);
1447 			if (!nreq) {
1448 				inet_child_forget(sk, req, child);
1449 				goto child_put;
1450 			}
1451 
1452 			refcount_set(&nreq->rsk_refcnt, 1);
1453 			if (inet_csk_reqsk_queue_add(sk, nreq, child)) {
1454 				__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQSUCCESS);
1455 				reqsk_migrate_reset(req);
1456 				reqsk_put(req);
1457 				return child;
1458 			}
1459 
1460 			__NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMIGRATEREQFAILURE);
1461 			reqsk_migrate_reset(nreq);
1462 			__reqsk_free(nreq);
1463 		} else if (inet_csk_reqsk_queue_add(sk, req, child)) {
1464 			return child;
1465 		}
1466 	}
1467 	/* Too bad, another child took ownership of the request, undo. */
1468 child_put:
1469 	bh_unlock_sock(child);
1470 	sock_put(child);
1471 	return NULL;
1472 }
1473 EXPORT_SYMBOL(inet_csk_complete_hashdance);
1474 
1475 /*
1476  *	This routine closes sockets which have been at least partially
1477  *	opened, but not yet accepted.
1478  */
inet_csk_listen_stop(struct sock * sk)1479 void inet_csk_listen_stop(struct sock *sk)
1480 {
1481 	struct inet_connection_sock *icsk = inet_csk(sk);
1482 	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
1483 	struct request_sock *next, *req;
1484 
1485 	/* Following specs, it would be better either to send FIN
1486 	 * (and enter FIN-WAIT-1, it is normal close)
1487 	 * or to send active reset (abort).
1488 	 * Certainly, it is pretty dangerous while synflood, but it is
1489 	 * bad justification for our negligence 8)
1490 	 * To be honest, we are not able to make either
1491 	 * of the variants now.			--ANK
1492 	 */
1493 	while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
1494 		struct sock *child = req->sk, *nsk;
1495 		struct request_sock *nreq;
1496 
1497 		local_bh_disable();
1498 		bh_lock_sock(child);
1499 		WARN_ON(sock_owned_by_user(child));
1500 		sock_hold(child);
1501 
1502 		nsk = reuseport_migrate_sock(sk, child, NULL);
1503 		if (nsk) {
1504 			nreq = inet_reqsk_clone(req, nsk);
1505 			if (nreq) {
1506 				refcount_set(&nreq->rsk_refcnt, 1);
1507 
1508 				if (inet_csk_reqsk_queue_add(nsk, nreq, child)) {
1509 					__NET_INC_STATS(sock_net(nsk),
1510 							LINUX_MIB_TCPMIGRATEREQSUCCESS);
1511 					reqsk_migrate_reset(req);
1512 				} else {
1513 					__NET_INC_STATS(sock_net(nsk),
1514 							LINUX_MIB_TCPMIGRATEREQFAILURE);
1515 					reqsk_migrate_reset(nreq);
1516 					__reqsk_free(nreq);
1517 				}
1518 
1519 				/* inet_csk_reqsk_queue_add() has already
1520 				 * called inet_child_forget() on failure case.
1521 				 */
1522 				goto skip_child_forget;
1523 			}
1524 		}
1525 
1526 		inet_child_forget(sk, req, child);
1527 skip_child_forget:
1528 		reqsk_put(req);
1529 		bh_unlock_sock(child);
1530 		local_bh_enable();
1531 		sock_put(child);
1532 
1533 		cond_resched();
1534 	}
1535 	if (queue->fastopenq.rskq_rst_head) {
1536 		/* Free all the reqs queued in rskq_rst_head. */
1537 		spin_lock_bh(&queue->fastopenq.lock);
1538 		req = queue->fastopenq.rskq_rst_head;
1539 		queue->fastopenq.rskq_rst_head = NULL;
1540 		spin_unlock_bh(&queue->fastopenq.lock);
1541 		while (req != NULL) {
1542 			next = req->dl_next;
1543 			reqsk_put(req);
1544 			req = next;
1545 		}
1546 	}
1547 	WARN_ON_ONCE(sk->sk_ack_backlog);
1548 }
1549 EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
1550 
inet_csk_addr2sockaddr(struct sock * sk,struct sockaddr * uaddr)1551 void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
1552 {
1553 	struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
1554 	const struct inet_sock *inet = inet_sk(sk);
1555 
1556 	sin->sin_family		= AF_INET;
1557 	sin->sin_addr.s_addr	= inet->inet_daddr;
1558 	sin->sin_port		= inet->inet_dport;
1559 }
1560 EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
1561 
inet_csk_rebuild_route(struct sock * sk,struct flowi * fl)1562 static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
1563 {
1564 	const struct inet_sock *inet = inet_sk(sk);
1565 	const struct ip_options_rcu *inet_opt;
1566 	__be32 daddr = inet->inet_daddr;
1567 	struct flowi4 *fl4;
1568 	struct rtable *rt;
1569 
1570 	rcu_read_lock();
1571 	inet_opt = rcu_dereference(inet->inet_opt);
1572 	if (inet_opt && inet_opt->opt.srr)
1573 		daddr = inet_opt->opt.faddr;
1574 	fl4 = &fl->u.ip4;
1575 	rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
1576 				   inet->inet_saddr, inet->inet_dport,
1577 				   inet->inet_sport, sk->sk_protocol,
1578 				   ip_sock_rt_tos(sk), sk->sk_bound_dev_if);
1579 	if (IS_ERR(rt))
1580 		rt = NULL;
1581 	if (rt)
1582 		sk_setup_caps(sk, &rt->dst);
1583 	rcu_read_unlock();
1584 
1585 	return &rt->dst;
1586 }
1587 
inet_csk_update_pmtu(struct sock * sk,u32 mtu)1588 struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
1589 {
1590 	struct dst_entry *dst = __sk_dst_check(sk, 0);
1591 	struct inet_sock *inet = inet_sk(sk);
1592 
1593 	if (!dst) {
1594 		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1595 		if (!dst)
1596 			goto out;
1597 	}
1598 	dst->ops->update_pmtu(dst, sk, NULL, mtu, true);
1599 
1600 	dst = __sk_dst_check(sk, 0);
1601 	if (!dst)
1602 		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1603 out:
1604 	return dst;
1605 }
1606 EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);
1607