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