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 
26 #if IS_ENABLED(CONFIG_IPV6)
27 /* match_sk*_wildcard == true:  IPV6_ADDR_ANY equals to any IPv6 addresses
28  *				if IPv6 only, and any IPv4 addresses
29  *				if not IPv6 only
30  * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
31  *				IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
32  *				and 0.0.0.0 equals to 0.0.0.0 only
33  */
34 static bool ipv6_rcv_saddr_equal(const struct in6_addr *sk1_rcv_saddr6,
35 				 const struct in6_addr *sk2_rcv_saddr6,
36 				 __be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
37 				 bool sk1_ipv6only, bool sk2_ipv6only,
38 				 bool match_sk1_wildcard,
39 				 bool match_sk2_wildcard)
40 {
41 	int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
42 	int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;
43 
44 	/* if both are mapped, treat as IPv4 */
45 	if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
46 		if (!sk2_ipv6only) {
47 			if (sk1_rcv_saddr == sk2_rcv_saddr)
48 				return true;
49 			return (match_sk1_wildcard && !sk1_rcv_saddr) ||
50 				(match_sk2_wildcard && !sk2_rcv_saddr);
51 		}
52 		return false;
53 	}
54 
55 	if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
56 		return true;
57 
58 	if (addr_type2 == IPV6_ADDR_ANY && match_sk2_wildcard &&
59 	    !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
60 		return true;
61 
62 	if (addr_type == IPV6_ADDR_ANY && match_sk1_wildcard &&
63 	    !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
64 		return true;
65 
66 	if (sk2_rcv_saddr6 &&
67 	    ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
68 		return true;
69 
70 	return false;
71 }
72 #endif
73 
74 /* match_sk*_wildcard == true:  0.0.0.0 equals to any IPv4 addresses
75  * match_sk*_wildcard == false: addresses must be exactly the same, i.e.
76  *				0.0.0.0 only equals to 0.0.0.0
77  */
78 static bool ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
79 				 bool sk2_ipv6only, bool match_sk1_wildcard,
80 				 bool match_sk2_wildcard)
81 {
82 	if (!sk2_ipv6only) {
83 		if (sk1_rcv_saddr == sk2_rcv_saddr)
84 			return true;
85 		return (match_sk1_wildcard && !sk1_rcv_saddr) ||
86 			(match_sk2_wildcard && !sk2_rcv_saddr);
87 	}
88 	return false;
89 }
90 
91 bool inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
92 			  bool match_wildcard)
93 {
94 #if IS_ENABLED(CONFIG_IPV6)
95 	if (sk->sk_family == AF_INET6)
96 		return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
97 					    inet6_rcv_saddr(sk2),
98 					    sk->sk_rcv_saddr,
99 					    sk2->sk_rcv_saddr,
100 					    ipv6_only_sock(sk),
101 					    ipv6_only_sock(sk2),
102 					    match_wildcard,
103 					    match_wildcard);
104 #endif
105 	return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
106 				    ipv6_only_sock(sk2), match_wildcard,
107 				    match_wildcard);
108 }
109 EXPORT_SYMBOL(inet_rcv_saddr_equal);
110 
111 bool inet_rcv_saddr_any(const struct sock *sk)
112 {
113 #if IS_ENABLED(CONFIG_IPV6)
114 	if (sk->sk_family == AF_INET6)
115 		return ipv6_addr_any(&sk->sk_v6_rcv_saddr);
116 #endif
117 	return !sk->sk_rcv_saddr;
118 }
119 
120 void inet_get_local_port_range(struct net *net, int *low, int *high)
121 {
122 	unsigned int seq;
123 
124 	do {
125 		seq = read_seqbegin(&net->ipv4.ip_local_ports.lock);
126 
127 		*low = net->ipv4.ip_local_ports.range[0];
128 		*high = net->ipv4.ip_local_ports.range[1];
129 	} while (read_seqretry(&net->ipv4.ip_local_ports.lock, seq));
130 }
131 EXPORT_SYMBOL(inet_get_local_port_range);
132 
133 static int inet_csk_bind_conflict(const struct sock *sk,
134 				  const struct inet_bind_bucket *tb,
135 				  bool relax, bool reuseport_ok)
136 {
137 	struct sock *sk2;
138 	bool reuse = sk->sk_reuse;
139 	bool reuseport = !!sk->sk_reuseport;
140 	kuid_t uid = sock_i_uid((struct sock *)sk);
141 
142 	/*
143 	 * Unlike other sk lookup places we do not check
144 	 * for sk_net here, since _all_ the socks listed
145 	 * in tb->owners list belong to the same net - the
146 	 * one this bucket belongs to.
147 	 */
148 
149 	sk_for_each_bound(sk2, &tb->owners) {
150 		if (sk != sk2 &&
151 		    (!sk->sk_bound_dev_if ||
152 		     !sk2->sk_bound_dev_if ||
153 		     sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) {
154 			if (reuse && sk2->sk_reuse &&
155 			    sk2->sk_state != TCP_LISTEN) {
156 				if ((!relax ||
157 				     (!reuseport_ok &&
158 				      reuseport && sk2->sk_reuseport &&
159 				      !rcu_access_pointer(sk->sk_reuseport_cb) &&
160 				      (sk2->sk_state == TCP_TIME_WAIT ||
161 				       uid_eq(uid, sock_i_uid(sk2))))) &&
162 				    inet_rcv_saddr_equal(sk, sk2, true))
163 					break;
164 			} else if (!reuseport_ok ||
165 				   !reuseport || !sk2->sk_reuseport ||
166 				   rcu_access_pointer(sk->sk_reuseport_cb) ||
167 				   (sk2->sk_state != TCP_TIME_WAIT &&
168 				    !uid_eq(uid, sock_i_uid(sk2)))) {
169 				if (inet_rcv_saddr_equal(sk, sk2, true))
170 					break;
171 			}
172 		}
173 	}
174 	return sk2 != NULL;
175 }
176 
177 /*
178  * Find an open port number for the socket.  Returns with the
179  * inet_bind_hashbucket lock held.
180  */
181 static struct inet_bind_hashbucket *
182 inet_csk_find_open_port(struct sock *sk, struct inet_bind_bucket **tb_ret, int *port_ret)
183 {
184 	struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
185 	int port = 0;
186 	struct inet_bind_hashbucket *head;
187 	struct net *net = sock_net(sk);
188 	bool relax = false;
189 	int i, low, high, attempt_half;
190 	struct inet_bind_bucket *tb;
191 	u32 remaining, offset;
192 	int l3mdev;
193 
194 	l3mdev = inet_sk_bound_l3mdev(sk);
195 ports_exhausted:
196 	attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
197 other_half_scan:
198 	inet_get_local_port_range(net, &low, &high);
199 	high++; /* [32768, 60999] -> [32768, 61000[ */
200 	if (high - low < 4)
201 		attempt_half = 0;
202 	if (attempt_half) {
203 		int half = low + (((high - low) >> 2) << 1);
204 
205 		if (attempt_half == 1)
206 			high = half;
207 		else
208 			low = half;
209 	}
210 	remaining = high - low;
211 	if (likely(remaining > 1))
212 		remaining &= ~1U;
213 
214 	offset = prandom_u32() % remaining;
215 	/* __inet_hash_connect() favors ports having @low parity
216 	 * We do the opposite to not pollute connect() users.
217 	 */
218 	offset |= 1U;
219 
220 other_parity_scan:
221 	port = low + offset;
222 	for (i = 0; i < remaining; i += 2, port += 2) {
223 		if (unlikely(port >= high))
224 			port -= remaining;
225 		if (inet_is_local_reserved_port(net, port))
226 			continue;
227 		head = &hinfo->bhash[inet_bhashfn(net, port,
228 						  hinfo->bhash_size)];
229 		spin_lock_bh(&head->lock);
230 		inet_bind_bucket_for_each(tb, &head->chain)
231 			if (net_eq(ib_net(tb), net) && tb->l3mdev == l3mdev &&
232 			    tb->port == port) {
233 				if (!inet_csk_bind_conflict(sk, tb, relax, false))
234 					goto success;
235 				goto next_port;
236 			}
237 		tb = NULL;
238 		goto success;
239 next_port:
240 		spin_unlock_bh(&head->lock);
241 		cond_resched();
242 	}
243 
244 	offset--;
245 	if (!(offset & 1))
246 		goto other_parity_scan;
247 
248 	if (attempt_half == 1) {
249 		/* OK we now try the upper half of the range */
250 		attempt_half = 2;
251 		goto other_half_scan;
252 	}
253 
254 	if (net->ipv4.sysctl_ip_autobind_reuse && !relax) {
255 		/* We still have a chance to connect to different destinations */
256 		relax = true;
257 		goto ports_exhausted;
258 	}
259 	return NULL;
260 success:
261 	*port_ret = port;
262 	*tb_ret = tb;
263 	return head;
264 }
265 
266 static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
267 				     struct sock *sk)
268 {
269 	kuid_t uid = sock_i_uid(sk);
270 
271 	if (tb->fastreuseport <= 0)
272 		return 0;
273 	if (!sk->sk_reuseport)
274 		return 0;
275 	if (rcu_access_pointer(sk->sk_reuseport_cb))
276 		return 0;
277 	if (!uid_eq(tb->fastuid, uid))
278 		return 0;
279 	/* We only need to check the rcv_saddr if this tb was once marked
280 	 * without fastreuseport and then was reset, as we can only know that
281 	 * the fast_*rcv_saddr doesn't have any conflicts with the socks on the
282 	 * owners list.
283 	 */
284 	if (tb->fastreuseport == FASTREUSEPORT_ANY)
285 		return 1;
286 #if IS_ENABLED(CONFIG_IPV6)
287 	if (tb->fast_sk_family == AF_INET6)
288 		return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
289 					    inet6_rcv_saddr(sk),
290 					    tb->fast_rcv_saddr,
291 					    sk->sk_rcv_saddr,
292 					    tb->fast_ipv6_only,
293 					    ipv6_only_sock(sk), true, false);
294 #endif
295 	return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
296 				    ipv6_only_sock(sk), true, false);
297 }
298 
299 void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
300 			       struct sock *sk)
301 {
302 	kuid_t uid = sock_i_uid(sk);
303 	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
304 
305 	if (hlist_empty(&tb->owners)) {
306 		tb->fastreuse = reuse;
307 		if (sk->sk_reuseport) {
308 			tb->fastreuseport = FASTREUSEPORT_ANY;
309 			tb->fastuid = uid;
310 			tb->fast_rcv_saddr = sk->sk_rcv_saddr;
311 			tb->fast_ipv6_only = ipv6_only_sock(sk);
312 			tb->fast_sk_family = sk->sk_family;
313 #if IS_ENABLED(CONFIG_IPV6)
314 			tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
315 #endif
316 		} else {
317 			tb->fastreuseport = 0;
318 		}
319 	} else {
320 		if (!reuse)
321 			tb->fastreuse = 0;
322 		if (sk->sk_reuseport) {
323 			/* We didn't match or we don't have fastreuseport set on
324 			 * the tb, but we have sk_reuseport set on this socket
325 			 * and we know that there are no bind conflicts with
326 			 * this socket in this tb, so reset our tb's reuseport
327 			 * settings so that any subsequent sockets that match
328 			 * our current socket will be put on the fast path.
329 			 *
330 			 * If we reset we need to set FASTREUSEPORT_STRICT so we
331 			 * do extra checking for all subsequent sk_reuseport
332 			 * socks.
333 			 */
334 			if (!sk_reuseport_match(tb, sk)) {
335 				tb->fastreuseport = FASTREUSEPORT_STRICT;
336 				tb->fastuid = uid;
337 				tb->fast_rcv_saddr = sk->sk_rcv_saddr;
338 				tb->fast_ipv6_only = ipv6_only_sock(sk);
339 				tb->fast_sk_family = sk->sk_family;
340 #if IS_ENABLED(CONFIG_IPV6)
341 				tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
342 #endif
343 			}
344 		} else {
345 			tb->fastreuseport = 0;
346 		}
347 	}
348 }
349 
350 /* Obtain a reference to a local port for the given sock,
351  * if snum is zero it means select any available local port.
352  * We try to allocate an odd port (and leave even ports for connect())
353  */
354 int inet_csk_get_port(struct sock *sk, unsigned short snum)
355 {
356 	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
357 	struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
358 	int ret = 1, port = snum;
359 	struct inet_bind_hashbucket *head;
360 	struct net *net = sock_net(sk);
361 	struct inet_bind_bucket *tb = NULL;
362 	int l3mdev;
363 
364 	l3mdev = inet_sk_bound_l3mdev(sk);
365 
366 	if (!port) {
367 		head = inet_csk_find_open_port(sk, &tb, &port);
368 		if (!head)
369 			return ret;
370 		if (!tb)
371 			goto tb_not_found;
372 		goto success;
373 	}
374 	head = &hinfo->bhash[inet_bhashfn(net, port,
375 					  hinfo->bhash_size)];
376 	spin_lock_bh(&head->lock);
377 	inet_bind_bucket_for_each(tb, &head->chain)
378 		if (net_eq(ib_net(tb), net) && tb->l3mdev == l3mdev &&
379 		    tb->port == port)
380 			goto tb_found;
381 tb_not_found:
382 	tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
383 				     net, head, port, l3mdev);
384 	if (!tb)
385 		goto fail_unlock;
386 tb_found:
387 	if (!hlist_empty(&tb->owners)) {
388 		if (sk->sk_reuse == SK_FORCE_REUSE)
389 			goto success;
390 
391 		if ((tb->fastreuse > 0 && reuse) ||
392 		    sk_reuseport_match(tb, sk))
393 			goto success;
394 		if (inet_csk_bind_conflict(sk, tb, true, true))
395 			goto fail_unlock;
396 	}
397 success:
398 	inet_csk_update_fastreuse(tb, sk);
399 
400 	if (!inet_csk(sk)->icsk_bind_hash)
401 		inet_bind_hash(sk, tb, port);
402 	WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
403 	ret = 0;
404 
405 fail_unlock:
406 	spin_unlock_bh(&head->lock);
407 	return ret;
408 }
409 EXPORT_SYMBOL_GPL(inet_csk_get_port);
410 
411 /*
412  * Wait for an incoming connection, avoid race conditions. This must be called
413  * with the socket locked.
414  */
415 static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
416 {
417 	struct inet_connection_sock *icsk = inet_csk(sk);
418 	DEFINE_WAIT(wait);
419 	int err;
420 
421 	/*
422 	 * True wake-one mechanism for incoming connections: only
423 	 * one process gets woken up, not the 'whole herd'.
424 	 * Since we do not 'race & poll' for established sockets
425 	 * anymore, the common case will execute the loop only once.
426 	 *
427 	 * Subtle issue: "add_wait_queue_exclusive()" will be added
428 	 * after any current non-exclusive waiters, and we know that
429 	 * it will always _stay_ after any new non-exclusive waiters
430 	 * because all non-exclusive waiters are added at the
431 	 * beginning of the wait-queue. As such, it's ok to "drop"
432 	 * our exclusiveness temporarily when we get woken up without
433 	 * having to remove and re-insert us on the wait queue.
434 	 */
435 	for (;;) {
436 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
437 					  TASK_INTERRUPTIBLE);
438 		release_sock(sk);
439 		if (reqsk_queue_empty(&icsk->icsk_accept_queue))
440 			timeo = schedule_timeout(timeo);
441 		sched_annotate_sleep();
442 		lock_sock(sk);
443 		err = 0;
444 		if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
445 			break;
446 		err = -EINVAL;
447 		if (sk->sk_state != TCP_LISTEN)
448 			break;
449 		err = sock_intr_errno(timeo);
450 		if (signal_pending(current))
451 			break;
452 		err = -EAGAIN;
453 		if (!timeo)
454 			break;
455 	}
456 	finish_wait(sk_sleep(sk), &wait);
457 	return err;
458 }
459 
460 /*
461  * This will accept the next outstanding connection.
462  */
463 struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)
464 {
465 	struct inet_connection_sock *icsk = inet_csk(sk);
466 	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
467 	struct request_sock *req;
468 	struct sock *newsk;
469 	int error;
470 
471 	lock_sock(sk);
472 
473 	/* We need to make sure that this socket is listening,
474 	 * and that it has something pending.
475 	 */
476 	error = -EINVAL;
477 	if (sk->sk_state != TCP_LISTEN)
478 		goto out_err;
479 
480 	/* Find already established connection */
481 	if (reqsk_queue_empty(queue)) {
482 		long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
483 
484 		/* If this is a non blocking socket don't sleep */
485 		error = -EAGAIN;
486 		if (!timeo)
487 			goto out_err;
488 
489 		error = inet_csk_wait_for_connect(sk, timeo);
490 		if (error)
491 			goto out_err;
492 	}
493 	req = reqsk_queue_remove(queue, sk);
494 	newsk = req->sk;
495 
496 	if (sk->sk_protocol == IPPROTO_TCP &&
497 	    tcp_rsk(req)->tfo_listener) {
498 		spin_lock_bh(&queue->fastopenq.lock);
499 		if (tcp_rsk(req)->tfo_listener) {
500 			/* We are still waiting for the final ACK from 3WHS
501 			 * so can't free req now. Instead, we set req->sk to
502 			 * NULL to signify that the child socket is taken
503 			 * so reqsk_fastopen_remove() will free the req
504 			 * when 3WHS finishes (or is aborted).
505 			 */
506 			req->sk = NULL;
507 			req = NULL;
508 		}
509 		spin_unlock_bh(&queue->fastopenq.lock);
510 	}
511 
512 out:
513 	release_sock(sk);
514 	if (newsk && mem_cgroup_sockets_enabled) {
515 		int amt;
516 
517 		/* atomically get the memory usage, set and charge the
518 		 * newsk->sk_memcg.
519 		 */
520 		lock_sock(newsk);
521 
522 		/* The socket has not been accepted yet, no need to look at
523 		 * newsk->sk_wmem_queued.
524 		 */
525 		amt = sk_mem_pages(newsk->sk_forward_alloc +
526 				   atomic_read(&newsk->sk_rmem_alloc));
527 		mem_cgroup_sk_alloc(newsk);
528 		if (newsk->sk_memcg && amt)
529 			mem_cgroup_charge_skmem(newsk->sk_memcg, amt);
530 
531 		release_sock(newsk);
532 	}
533 	if (req)
534 		reqsk_put(req);
535 	return newsk;
536 out_err:
537 	newsk = NULL;
538 	req = NULL;
539 	*err = error;
540 	goto out;
541 }
542 EXPORT_SYMBOL(inet_csk_accept);
543 
544 /*
545  * Using different timers for retransmit, delayed acks and probes
546  * We may wish use just one timer maintaining a list of expire jiffies
547  * to optimize.
548  */
549 void inet_csk_init_xmit_timers(struct sock *sk,
550 			       void (*retransmit_handler)(struct timer_list *t),
551 			       void (*delack_handler)(struct timer_list *t),
552 			       void (*keepalive_handler)(struct timer_list *t))
553 {
554 	struct inet_connection_sock *icsk = inet_csk(sk);
555 
556 	timer_setup(&icsk->icsk_retransmit_timer, retransmit_handler, 0);
557 	timer_setup(&icsk->icsk_delack_timer, delack_handler, 0);
558 	timer_setup(&sk->sk_timer, keepalive_handler, 0);
559 	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
560 }
561 EXPORT_SYMBOL(inet_csk_init_xmit_timers);
562 
563 void inet_csk_clear_xmit_timers(struct sock *sk)
564 {
565 	struct inet_connection_sock *icsk = inet_csk(sk);
566 
567 	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
568 
569 	sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
570 	sk_stop_timer(sk, &icsk->icsk_delack_timer);
571 	sk_stop_timer(sk, &sk->sk_timer);
572 }
573 EXPORT_SYMBOL(inet_csk_clear_xmit_timers);
574 
575 void inet_csk_delete_keepalive_timer(struct sock *sk)
576 {
577 	sk_stop_timer(sk, &sk->sk_timer);
578 }
579 EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);
580 
581 void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
582 {
583 	sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
584 }
585 EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);
586 
587 struct dst_entry *inet_csk_route_req(const struct sock *sk,
588 				     struct flowi4 *fl4,
589 				     const struct request_sock *req)
590 {
591 	const struct inet_request_sock *ireq = inet_rsk(req);
592 	struct net *net = read_pnet(&ireq->ireq_net);
593 	struct ip_options_rcu *opt;
594 	struct rtable *rt;
595 
596 	rcu_read_lock();
597 	opt = rcu_dereference(ireq->ireq_opt);
598 
599 	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
600 			   RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
601 			   sk->sk_protocol, inet_sk_flowi_flags(sk),
602 			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
603 			   ireq->ir_loc_addr, ireq->ir_rmt_port,
604 			   htons(ireq->ir_num), sk->sk_uid);
605 	security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
606 	rt = ip_route_output_flow(net, fl4, sk);
607 	if (IS_ERR(rt))
608 		goto no_route;
609 	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
610 		goto route_err;
611 	rcu_read_unlock();
612 	return &rt->dst;
613 
614 route_err:
615 	ip_rt_put(rt);
616 no_route:
617 	rcu_read_unlock();
618 	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
619 	return NULL;
620 }
621 EXPORT_SYMBOL_GPL(inet_csk_route_req);
622 
623 struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
624 					    struct sock *newsk,
625 					    const struct request_sock *req)
626 {
627 	const struct inet_request_sock *ireq = inet_rsk(req);
628 	struct net *net = read_pnet(&ireq->ireq_net);
629 	struct inet_sock *newinet = inet_sk(newsk);
630 	struct ip_options_rcu *opt;
631 	struct flowi4 *fl4;
632 	struct rtable *rt;
633 
634 	opt = rcu_dereference(ireq->ireq_opt);
635 	fl4 = &newinet->cork.fl.u.ip4;
636 
637 	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
638 			   RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
639 			   sk->sk_protocol, inet_sk_flowi_flags(sk),
640 			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
641 			   ireq->ir_loc_addr, ireq->ir_rmt_port,
642 			   htons(ireq->ir_num), sk->sk_uid);
643 	security_req_classify_flow(req, flowi4_to_flowi_common(fl4));
644 	rt = ip_route_output_flow(net, fl4, sk);
645 	if (IS_ERR(rt))
646 		goto no_route;
647 	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
648 		goto route_err;
649 	return &rt->dst;
650 
651 route_err:
652 	ip_rt_put(rt);
653 no_route:
654 	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
655 	return NULL;
656 }
657 EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);
658 
659 /* Decide when to expire the request and when to resend SYN-ACK */
660 static void syn_ack_recalc(struct request_sock *req,
661 			   const int max_syn_ack_retries,
662 			   const u8 rskq_defer_accept,
663 			   int *expire, int *resend)
664 {
665 	if (!rskq_defer_accept) {
666 		*expire = req->num_timeout >= max_syn_ack_retries;
667 		*resend = 1;
668 		return;
669 	}
670 	*expire = req->num_timeout >= max_syn_ack_retries &&
671 		  (!inet_rsk(req)->acked || req->num_timeout >= rskq_defer_accept);
672 	/* Do not resend while waiting for data after ACK,
673 	 * start to resend on end of deferring period to give
674 	 * last chance for data or ACK to create established socket.
675 	 */
676 	*resend = !inet_rsk(req)->acked ||
677 		  req->num_timeout >= rskq_defer_accept - 1;
678 }
679 
680 int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
681 {
682 	int err = req->rsk_ops->rtx_syn_ack(parent, req);
683 
684 	if (!err)
685 		req->num_retrans++;
686 	return err;
687 }
688 EXPORT_SYMBOL(inet_rtx_syn_ack);
689 
690 /* return true if req was found in the ehash table */
691 static bool reqsk_queue_unlink(struct request_sock *req)
692 {
693 	struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
694 	bool found = false;
695 
696 	if (sk_hashed(req_to_sk(req))) {
697 		spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
698 
699 		spin_lock(lock);
700 		found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
701 		spin_unlock(lock);
702 	}
703 	if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
704 		reqsk_put(req);
705 	return found;
706 }
707 
708 bool inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
709 {
710 	bool unlinked = reqsk_queue_unlink(req);
711 
712 	if (unlinked) {
713 		reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
714 		reqsk_put(req);
715 	}
716 	return unlinked;
717 }
718 EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);
719 
720 void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
721 {
722 	inet_csk_reqsk_queue_drop(sk, req);
723 	reqsk_put(req);
724 }
725 EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);
726 
727 static void reqsk_timer_handler(struct timer_list *t)
728 {
729 	struct request_sock *req = from_timer(req, t, rsk_timer);
730 	struct sock *sk_listener = req->rsk_listener;
731 	struct net *net = sock_net(sk_listener);
732 	struct inet_connection_sock *icsk = inet_csk(sk_listener);
733 	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
734 	int max_syn_ack_retries, qlen, expire = 0, resend = 0;
735 
736 	if (inet_sk_state_load(sk_listener) != TCP_LISTEN)
737 		goto drop;
738 
739 	max_syn_ack_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries;
740 	/* Normally all the openreqs are young and become mature
741 	 * (i.e. converted to established socket) for first timeout.
742 	 * If synack was not acknowledged for 1 second, it means
743 	 * one of the following things: synack was lost, ack was lost,
744 	 * rtt is high or nobody planned to ack (i.e. synflood).
745 	 * When server is a bit loaded, queue is populated with old
746 	 * open requests, reducing effective size of queue.
747 	 * When server is well loaded, queue size reduces to zero
748 	 * after several minutes of work. It is not synflood,
749 	 * it is normal operation. The solution is pruning
750 	 * too old entries overriding normal timeout, when
751 	 * situation becomes dangerous.
752 	 *
753 	 * Essentially, we reserve half of room for young
754 	 * embrions; and abort old ones without pity, if old
755 	 * ones are about to clog our table.
756 	 */
757 	qlen = reqsk_queue_len(queue);
758 	if ((qlen << 1) > max(8U, READ_ONCE(sk_listener->sk_max_ack_backlog))) {
759 		int young = reqsk_queue_len_young(queue) << 1;
760 
761 		while (max_syn_ack_retries > 2) {
762 			if (qlen < young)
763 				break;
764 			max_syn_ack_retries--;
765 			young <<= 1;
766 		}
767 	}
768 	syn_ack_recalc(req, max_syn_ack_retries, READ_ONCE(queue->rskq_defer_accept),
769 		       &expire, &resend);
770 	req->rsk_ops->syn_ack_timeout(req);
771 	if (!expire &&
772 	    (!resend ||
773 	     !inet_rtx_syn_ack(sk_listener, req) ||
774 	     inet_rsk(req)->acked)) {
775 		unsigned long timeo;
776 
777 		if (req->num_timeout++ == 0)
778 			atomic_dec(&queue->young);
779 		timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
780 		mod_timer(&req->rsk_timer, jiffies + timeo);
781 		return;
782 	}
783 drop:
784 	inet_csk_reqsk_queue_drop_and_put(sk_listener, req);
785 }
786 
787 static void reqsk_queue_hash_req(struct request_sock *req,
788 				 unsigned long timeout)
789 {
790 	timer_setup(&req->rsk_timer, reqsk_timer_handler, TIMER_PINNED);
791 	mod_timer(&req->rsk_timer, jiffies + timeout);
792 
793 	inet_ehash_insert(req_to_sk(req), NULL, NULL);
794 	/* before letting lookups find us, make sure all req fields
795 	 * are committed to memory and refcnt initialized.
796 	 */
797 	smp_wmb();
798 	refcount_set(&req->rsk_refcnt, 2 + 1);
799 }
800 
801 void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
802 				   unsigned long timeout)
803 {
804 	reqsk_queue_hash_req(req, timeout);
805 	inet_csk_reqsk_queue_added(sk);
806 }
807 EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
808 
809 static void inet_clone_ulp(const struct request_sock *req, struct sock *newsk,
810 			   const gfp_t priority)
811 {
812 	struct inet_connection_sock *icsk = inet_csk(newsk);
813 
814 	if (!icsk->icsk_ulp_ops)
815 		return;
816 
817 	if (icsk->icsk_ulp_ops->clone)
818 		icsk->icsk_ulp_ops->clone(req, newsk, priority);
819 }
820 
821 /**
822  *	inet_csk_clone_lock - clone an inet socket, and lock its clone
823  *	@sk: the socket to clone
824  *	@req: request_sock
825  *	@priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
826  *
827  *	Caller must unlock socket even in error path (bh_unlock_sock(newsk))
828  */
829 struct sock *inet_csk_clone_lock(const struct sock *sk,
830 				 const struct request_sock *req,
831 				 const gfp_t priority)
832 {
833 	struct sock *newsk = sk_clone_lock(sk, priority);
834 
835 	if (newsk) {
836 		struct inet_connection_sock *newicsk = inet_csk(newsk);
837 
838 		inet_sk_set_state(newsk, TCP_SYN_RECV);
839 		newicsk->icsk_bind_hash = NULL;
840 
841 		inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
842 		inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
843 		inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
844 
845 		/* listeners have SOCK_RCU_FREE, not the children */
846 		sock_reset_flag(newsk, SOCK_RCU_FREE);
847 
848 		inet_sk(newsk)->mc_list = NULL;
849 
850 		newsk->sk_mark = inet_rsk(req)->ir_mark;
851 		atomic64_set(&newsk->sk_cookie,
852 			     atomic64_read(&inet_rsk(req)->ir_cookie));
853 
854 		newicsk->icsk_retransmits = 0;
855 		newicsk->icsk_backoff	  = 0;
856 		newicsk->icsk_probes_out  = 0;
857 		newicsk->icsk_probes_tstamp = 0;
858 
859 		/* Deinitialize accept_queue to trap illegal accesses. */
860 		memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
861 
862 		inet_clone_ulp(req, newsk, priority);
863 
864 		security_inet_csk_clone(newsk, req);
865 	}
866 	return newsk;
867 }
868 EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
869 
870 /*
871  * At this point, there should be no process reference to this
872  * socket, and thus no user references at all.  Therefore we
873  * can assume the socket waitqueue is inactive and nobody will
874  * try to jump onto it.
875  */
876 void inet_csk_destroy_sock(struct sock *sk)
877 {
878 	WARN_ON(sk->sk_state != TCP_CLOSE);
879 	WARN_ON(!sock_flag(sk, SOCK_DEAD));
880 
881 	/* It cannot be in hash table! */
882 	WARN_ON(!sk_unhashed(sk));
883 
884 	/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
885 	WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
886 
887 	sk->sk_prot->destroy(sk);
888 
889 	sk_stream_kill_queues(sk);
890 
891 	xfrm_sk_free_policy(sk);
892 
893 	sk_refcnt_debug_release(sk);
894 
895 	percpu_counter_dec(sk->sk_prot->orphan_count);
896 
897 	sock_put(sk);
898 }
899 EXPORT_SYMBOL(inet_csk_destroy_sock);
900 
901 /* This function allows to force a closure of a socket after the call to
902  * tcp/dccp_create_openreq_child().
903  */
904 void inet_csk_prepare_forced_close(struct sock *sk)
905 	__releases(&sk->sk_lock.slock)
906 {
907 	/* sk_clone_lock locked the socket and set refcnt to 2 */
908 	bh_unlock_sock(sk);
909 	sock_put(sk);
910 	inet_csk_prepare_for_destroy_sock(sk);
911 	inet_sk(sk)->inet_num = 0;
912 }
913 EXPORT_SYMBOL(inet_csk_prepare_forced_close);
914 
915 int inet_csk_listen_start(struct sock *sk, int backlog)
916 {
917 	struct inet_connection_sock *icsk = inet_csk(sk);
918 	struct inet_sock *inet = inet_sk(sk);
919 	int err = -EADDRINUSE;
920 
921 	reqsk_queue_alloc(&icsk->icsk_accept_queue);
922 
923 	sk->sk_ack_backlog = 0;
924 	inet_csk_delack_init(sk);
925 
926 	/* There is race window here: we announce ourselves listening,
927 	 * but this transition is still not validated by get_port().
928 	 * It is OK, because this socket enters to hash table only
929 	 * after validation is complete.
930 	 */
931 	inet_sk_state_store(sk, TCP_LISTEN);
932 	if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
933 		inet->inet_sport = htons(inet->inet_num);
934 
935 		sk_dst_reset(sk);
936 		err = sk->sk_prot->hash(sk);
937 
938 		if (likely(!err))
939 			return 0;
940 	}
941 
942 	inet_sk_set_state(sk, TCP_CLOSE);
943 	return err;
944 }
945 EXPORT_SYMBOL_GPL(inet_csk_listen_start);
946 
947 static void inet_child_forget(struct sock *sk, struct request_sock *req,
948 			      struct sock *child)
949 {
950 	sk->sk_prot->disconnect(child, O_NONBLOCK);
951 
952 	sock_orphan(child);
953 
954 	percpu_counter_inc(sk->sk_prot->orphan_count);
955 
956 	if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
957 		BUG_ON(rcu_access_pointer(tcp_sk(child)->fastopen_rsk) != req);
958 		BUG_ON(sk != req->rsk_listener);
959 
960 		/* Paranoid, to prevent race condition if
961 		 * an inbound pkt destined for child is
962 		 * blocked by sock lock in tcp_v4_rcv().
963 		 * Also to satisfy an assertion in
964 		 * tcp_v4_destroy_sock().
965 		 */
966 		RCU_INIT_POINTER(tcp_sk(child)->fastopen_rsk, NULL);
967 	}
968 	inet_csk_destroy_sock(child);
969 }
970 
971 struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
972 				      struct request_sock *req,
973 				      struct sock *child)
974 {
975 	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;
976 
977 	spin_lock(&queue->rskq_lock);
978 	if (unlikely(sk->sk_state != TCP_LISTEN)) {
979 		inet_child_forget(sk, req, child);
980 		child = NULL;
981 	} else {
982 		req->sk = child;
983 		req->dl_next = NULL;
984 		if (queue->rskq_accept_head == NULL)
985 			WRITE_ONCE(queue->rskq_accept_head, req);
986 		else
987 			queue->rskq_accept_tail->dl_next = req;
988 		queue->rskq_accept_tail = req;
989 		sk_acceptq_added(sk);
990 	}
991 	spin_unlock(&queue->rskq_lock);
992 	return child;
993 }
994 EXPORT_SYMBOL(inet_csk_reqsk_queue_add);
995 
996 struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
997 					 struct request_sock *req, bool own_req)
998 {
999 	if (own_req) {
1000 		inet_csk_reqsk_queue_drop(sk, req);
1001 		reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
1002 		if (inet_csk_reqsk_queue_add(sk, req, child))
1003 			return child;
1004 	}
1005 	/* Too bad, another child took ownership of the request, undo. */
1006 	bh_unlock_sock(child);
1007 	sock_put(child);
1008 	return NULL;
1009 }
1010 EXPORT_SYMBOL(inet_csk_complete_hashdance);
1011 
1012 /*
1013  *	This routine closes sockets which have been at least partially
1014  *	opened, but not yet accepted.
1015  */
1016 void inet_csk_listen_stop(struct sock *sk)
1017 {
1018 	struct inet_connection_sock *icsk = inet_csk(sk);
1019 	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
1020 	struct request_sock *next, *req;
1021 
1022 	/* Following specs, it would be better either to send FIN
1023 	 * (and enter FIN-WAIT-1, it is normal close)
1024 	 * or to send active reset (abort).
1025 	 * Certainly, it is pretty dangerous while synflood, but it is
1026 	 * bad justification for our negligence 8)
1027 	 * To be honest, we are not able to make either
1028 	 * of the variants now.			--ANK
1029 	 */
1030 	while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
1031 		struct sock *child = req->sk;
1032 
1033 		local_bh_disable();
1034 		bh_lock_sock(child);
1035 		WARN_ON(sock_owned_by_user(child));
1036 		sock_hold(child);
1037 
1038 		inet_child_forget(sk, req, child);
1039 		reqsk_put(req);
1040 		bh_unlock_sock(child);
1041 		local_bh_enable();
1042 		sock_put(child);
1043 
1044 		cond_resched();
1045 	}
1046 	if (queue->fastopenq.rskq_rst_head) {
1047 		/* Free all the reqs queued in rskq_rst_head. */
1048 		spin_lock_bh(&queue->fastopenq.lock);
1049 		req = queue->fastopenq.rskq_rst_head;
1050 		queue->fastopenq.rskq_rst_head = NULL;
1051 		spin_unlock_bh(&queue->fastopenq.lock);
1052 		while (req != NULL) {
1053 			next = req->dl_next;
1054 			reqsk_put(req);
1055 			req = next;
1056 		}
1057 	}
1058 	WARN_ON_ONCE(sk->sk_ack_backlog);
1059 }
1060 EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
1061 
1062 void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
1063 {
1064 	struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
1065 	const struct inet_sock *inet = inet_sk(sk);
1066 
1067 	sin->sin_family		= AF_INET;
1068 	sin->sin_addr.s_addr	= inet->inet_daddr;
1069 	sin->sin_port		= inet->inet_dport;
1070 }
1071 EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
1072 
1073 static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
1074 {
1075 	const struct inet_sock *inet = inet_sk(sk);
1076 	const struct ip_options_rcu *inet_opt;
1077 	__be32 daddr = inet->inet_daddr;
1078 	struct flowi4 *fl4;
1079 	struct rtable *rt;
1080 
1081 	rcu_read_lock();
1082 	inet_opt = rcu_dereference(inet->inet_opt);
1083 	if (inet_opt && inet_opt->opt.srr)
1084 		daddr = inet_opt->opt.faddr;
1085 	fl4 = &fl->u.ip4;
1086 	rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
1087 				   inet->inet_saddr, inet->inet_dport,
1088 				   inet->inet_sport, sk->sk_protocol,
1089 				   RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
1090 	if (IS_ERR(rt))
1091 		rt = NULL;
1092 	if (rt)
1093 		sk_setup_caps(sk, &rt->dst);
1094 	rcu_read_unlock();
1095 
1096 	return &rt->dst;
1097 }
1098 
1099 struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
1100 {
1101 	struct dst_entry *dst = __sk_dst_check(sk, 0);
1102 	struct inet_sock *inet = inet_sk(sk);
1103 
1104 	if (!dst) {
1105 		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1106 		if (!dst)
1107 			goto out;
1108 	}
1109 	dst->ops->update_pmtu(dst, sk, NULL, mtu, true);
1110 
1111 	dst = __sk_dst_check(sk, 0);
1112 	if (!dst)
1113 		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
1114 out:
1115 	return dst;
1116 }
1117 EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);
1118