inet_connection_sock.c 30.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
 * INET		An implementation of the TCP/IP protocol suite for the LINUX
 *		operating system.  INET is implemented using the  BSD Socket
 *		interface as the means of communication with the user level.
 *
 *		Support for INET connection oriented protocols.
 *
 * Authors:	See the TCP sources
 *
 *		This program is free software; you can redistribute it and/or
 *		modify it under the terms of the GNU General Public License
 *		as published by the Free Software Foundation; either version
 *		2 of the License, or(at your option) any later version.
 */

#include <linux/module.h>
#include <linux/jhash.h>

#include <net/inet_connection_sock.h>
#include <net/inet_hashtables.h>
#include <net/inet_timewait_sock.h>
#include <net/ip.h>
#include <net/route.h>
#include <net/tcp_states.h>
25
#include <net/xfrm.h>
26
#include <net/tcp.h>
27
#include <net/sock_reuseport.h>
28
#include <net/addrconf.h>
29 30 31 32 33 34

#ifdef INET_CSK_DEBUG
const char inet_csk_timer_bug_msg[] = "inet_csk BUG: unknown timer value\n";
EXPORT_SYMBOL(inet_csk_timer_bug_msg);
#endif

35 36 37 38 39 40 41
#if IS_ENABLED(CONFIG_IPV6)
/* match_wildcard == true:  IPV6_ADDR_ANY equals to any IPv6 addresses if IPv6
 *                          only, and any IPv4 addresses if not IPv6 only
 * match_wildcard == false: addresses must be exactly the same, i.e.
 *                          IPV6_ADDR_ANY only equals to IPV6_ADDR_ANY,
 *                          and 0.0.0.0 equals to 0.0.0.0 only
 */
42 43 44 45
static int 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,
46 47
				bool match_wildcard)
{
48
	int addr_type = ipv6_addr_type(sk1_rcv_saddr6);
49 50 51 52 53
	int addr_type2 = sk2_rcv_saddr6 ? ipv6_addr_type(sk2_rcv_saddr6) : IPV6_ADDR_MAPPED;

	/* if both are mapped, treat as IPv4 */
	if (addr_type == IPV6_ADDR_MAPPED && addr_type2 == IPV6_ADDR_MAPPED) {
		if (!sk2_ipv6only) {
54
			if (sk1_rcv_saddr == sk2_rcv_saddr)
55
				return 1;
56
			if (!sk1_rcv_saddr || !sk2_rcv_saddr)
57 58 59 60 61 62 63 64 65 66 67 68 69
				return match_wildcard;
		}
		return 0;
	}

	if (addr_type == IPV6_ADDR_ANY && addr_type2 == IPV6_ADDR_ANY)
		return 1;

	if (addr_type2 == IPV6_ADDR_ANY && match_wildcard &&
	    !(sk2_ipv6only && addr_type == IPV6_ADDR_MAPPED))
		return 1;

	if (addr_type == IPV6_ADDR_ANY && match_wildcard &&
70
	    !(sk1_ipv6only && addr_type2 == IPV6_ADDR_MAPPED))
71 72 73
		return 1;

	if (sk2_rcv_saddr6 &&
74
	    ipv6_addr_equal(sk1_rcv_saddr6, sk2_rcv_saddr6))
75 76 77 78 79 80 81 82 83 84
		return 1;

	return 0;
}
#endif

/* match_wildcard == true:  0.0.0.0 equals to any IPv4 addresses
 * match_wildcard == false: addresses must be exactly the same, i.e.
 *                          0.0.0.0 only equals to 0.0.0.0
 */
85 86
static int ipv4_rcv_saddr_equal(__be32 sk1_rcv_saddr, __be32 sk2_rcv_saddr,
				bool sk2_ipv6only, bool match_wildcard)
87
{
88 89
	if (!sk2_ipv6only) {
		if (sk1_rcv_saddr == sk2_rcv_saddr)
90
			return 1;
91
		if (!sk1_rcv_saddr || !sk2_rcv_saddr)
92 93 94 95 96 97 98 99 100 101
			return match_wildcard;
	}
	return 0;
}

int inet_rcv_saddr_equal(const struct sock *sk, const struct sock *sk2,
			 bool match_wildcard)
{
#if IS_ENABLED(CONFIG_IPV6)
	if (sk->sk_family == AF_INET6)
102
		return ipv6_rcv_saddr_equal(&sk->sk_v6_rcv_saddr,
103
					    inet6_rcv_saddr(sk2),
104 105 106 107 108
					    sk->sk_rcv_saddr,
					    sk2->sk_rcv_saddr,
					    ipv6_only_sock(sk),
					    ipv6_only_sock(sk2),
					    match_wildcard);
109
#endif
110 111
	return ipv4_rcv_saddr_equal(sk->sk_rcv_saddr, sk2->sk_rcv_saddr,
				    ipv6_only_sock(sk2), match_wildcard);
112 113 114
}
EXPORT_SYMBOL(inet_rcv_saddr_equal);

115
void inet_get_local_port_range(struct net *net, int *low, int *high)
116
{
117 118
	unsigned int seq;

119
	do {
120
		seq = read_seqbegin(&net->ipv4.ip_local_ports.lock);
121

122 123 124
		*low = net->ipv4.ip_local_ports.range[0];
		*high = net->ipv4.ip_local_ports.range[1];
	} while (read_seqretry(&net->ipv4.ip_local_ports.lock, seq));
125 126
}
EXPORT_SYMBOL(inet_get_local_port_range);
127

J
Josef Bacik 已提交
128 129 130
static int inet_csk_bind_conflict(const struct sock *sk,
				  const struct inet_bind_bucket *tb,
				  bool relax, bool reuseport_ok)
131 132
{
	struct sock *sk2;
133 134
	bool reuse = sk->sk_reuse;
	bool reuseport = !!sk->sk_reuseport && reuseport_ok;
135
	kuid_t uid = sock_i_uid((struct sock *)sk);
136

137 138 139 140 141 142 143
	/*
	 * Unlike other sk lookup places we do not check
	 * for sk_net here, since _all_ the socks listed
	 * in tb->owners list belong to the same net - the
	 * one this bucket belongs to.
	 */

144
	sk_for_each_bound(sk2, &tb->owners) {
145 146 147 148
		if (sk != sk2 &&
		    (!sk->sk_bound_dev_if ||
		     !sk2->sk_bound_dev_if ||
		     sk->sk_bound_dev_if == sk2->sk_bound_dev_if)) {
149 150 151
			if ((!reuse || !sk2->sk_reuse ||
			    sk2->sk_state == TCP_LISTEN) &&
			    (!reuseport || !sk2->sk_reuseport ||
152 153
			     rcu_access_pointer(sk->sk_reuseport_cb) ||
			     (sk2->sk_state != TCP_TIME_WAIT &&
154
			     !uid_eq(uid, sock_i_uid(sk2))))) {
J
Josef Bacik 已提交
155
				if (inet_rcv_saddr_equal(sk, sk2, true))
156
					break;
157
			}
158 159
			if (!relax && reuse && sk2->sk_reuse &&
			    sk2->sk_state != TCP_LISTEN) {
J
Josef Bacik 已提交
160
				if (inet_rcv_saddr_equal(sk, sk2, true))
161 162
					break;
			}
163 164
		}
	}
165
	return sk2 != NULL;
166
}
167

168 169 170
/*
 * Find an open port number for the socket.  Returns with the
 * inet_bind_hashbucket lock held.
171
 */
172 173
static struct inet_bind_hashbucket *
inet_csk_find_open_port(struct sock *sk, struct inet_bind_bucket **tb_ret, int *port_ret)
174
{
175
	struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
176
	int port = 0;
177
	struct inet_bind_hashbucket *head;
178
	struct net *net = sock_net(sk);
179 180 181
	int i, low, high, attempt_half;
	struct inet_bind_bucket *tb;
	u32 remaining, offset;
182

183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
	attempt_half = (sk->sk_reuse == SK_CAN_REUSE) ? 1 : 0;
other_half_scan:
	inet_get_local_port_range(net, &low, &high);
	high++; /* [32768, 60999] -> [32768, 61000[ */
	if (high - low < 4)
		attempt_half = 0;
	if (attempt_half) {
		int half = low + (((high - low) >> 2) << 1);

		if (attempt_half == 1)
			high = half;
		else
			low = half;
	}
	remaining = high - low;
	if (likely(remaining > 1))
		remaining &= ~1U;
200

201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218
	offset = prandom_u32() % remaining;
	/* __inet_hash_connect() favors ports having @low parity
	 * We do the opposite to not pollute connect() users.
	 */
	offset |= 1U;

other_parity_scan:
	port = low + offset;
	for (i = 0; i < remaining; i += 2, port += 2) {
		if (unlikely(port >= high))
			port -= remaining;
		if (inet_is_local_reserved_port(net, port))
			continue;
		head = &hinfo->bhash[inet_bhashfn(net, port,
						  hinfo->bhash_size)];
		spin_lock_bh(&head->lock);
		inet_bind_bucket_for_each(tb, &head->chain)
			if (net_eq(ib_net(tb), net) && tb->port == port) {
219
				if (!inet_csk_bind_conflict(sk, tb, false, false))
220
					goto success;
221
				goto next_port;
222
			}
223 224
		tb = NULL;
		goto success;
225 226 227 228 229 230 231 232 233 234 235 236 237 238
next_port:
		spin_unlock_bh(&head->lock);
		cond_resched();
	}

	offset--;
	if (!(offset & 1))
		goto other_parity_scan;

	if (attempt_half == 1) {
		/* OK we now try the upper half of the range */
		attempt_half = 2;
		goto other_half_scan;
	}
239 240 241 242 243 244
	return NULL;
success:
	*port_ret = port;
	*tb_ret = tb;
	return head;
}
245

246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
				     struct sock *sk)
{
	kuid_t uid = sock_i_uid(sk);

	if (tb->fastreuseport <= 0)
		return 0;
	if (!sk->sk_reuseport)
		return 0;
	if (rcu_access_pointer(sk->sk_reuseport_cb))
		return 0;
	if (!uid_eq(tb->fastuid, uid))
		return 0;
	/* We only need to check the rcv_saddr if this tb was once marked
	 * without fastreuseport and then was reset, as we can only know that
	 * the fast_*rcv_saddr doesn't have any conflicts with the socks on the
	 * owners list.
	 */
	if (tb->fastreuseport == FASTREUSEPORT_ANY)
		return 1;
#if IS_ENABLED(CONFIG_IPV6)
	if (tb->fast_sk_family == AF_INET6)
		return ipv6_rcv_saddr_equal(&tb->fast_v6_rcv_saddr,
					    &sk->sk_v6_rcv_saddr,
					    tb->fast_rcv_saddr,
					    sk->sk_rcv_saddr,
					    tb->fast_ipv6_only,
					    ipv6_only_sock(sk), true);
#endif
	return ipv4_rcv_saddr_equal(tb->fast_rcv_saddr, sk->sk_rcv_saddr,
				    ipv6_only_sock(sk), true);
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
/* Obtain a reference to a local port for the given sock,
 * if snum is zero it means select any available local port.
 * We try to allocate an odd port (and leave even ports for connect())
 */
int inet_csk_get_port(struct sock *sk, unsigned short snum)
{
	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
	struct inet_hashinfo *hinfo = sk->sk_prot->h.hashinfo;
	int ret = 1, port = snum;
	struct inet_bind_hashbucket *head;
	struct net *net = sock_net(sk);
	struct inet_bind_bucket *tb = NULL;
	kuid_t uid = sock_i_uid(sk);

	if (!port) {
		head = inet_csk_find_open_port(sk, &tb, &port);
		if (!head)
			return ret;
		if (!tb)
			goto tb_not_found;
		goto success;
	}
	head = &hinfo->bhash[inet_bhashfn(net, port,
					  hinfo->bhash_size)];
	spin_lock_bh(&head->lock);
	inet_bind_bucket_for_each(tb, &head->chain)
		if (net_eq(ib_net(tb), net) && tb->port == port)
			goto tb_found;
307 308 309 310 311
tb_not_found:
	tb = inet_bind_bucket_create(hinfo->bind_bucket_cachep,
				     net, head, port);
	if (!tb)
		goto fail_unlock;
312 313
tb_found:
	if (!hlist_empty(&tb->owners)) {
314 315 316
		if (sk->sk_reuse == SK_FORCE_REUSE)
			goto success;

317
		if ((tb->fastreuse > 0 && reuse) ||
318
		    sk_reuseport_match(tb, sk))
319
			goto success;
320
		if (inet_csk_bind_conflict(sk, tb, true, true))
321
			goto fail_unlock;
322 323 324
	}
success:
	if (!hlist_empty(&tb->owners)) {
325
		tb->fastreuse = reuse;
326
		if (sk->sk_reuseport) {
327
			tb->fastreuseport = FASTREUSEPORT_ANY;
328
			tb->fastuid = uid;
329 330
			tb->fast_rcv_saddr = sk->sk_rcv_saddr;
			tb->fast_ipv6_only = ipv6_only_sock(sk);
J
Josef Bacik 已提交
331
			tb->fast_sk_family = sk->sk_family;
332 333 334
#if IS_ENABLED(CONFIG_IPV6)
			tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
#endif
335
		} else {
336
			tb->fastreuseport = 0;
337
		}
338 339 340
	} else {
		if (!reuse)
			tb->fastreuse = 0;
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
		if (sk->sk_reuseport) {
			/* We didn't match or we don't have fastreuseport set on
			 * the tb, but we have sk_reuseport set on this socket
			 * and we know that there are no bind conflicts with
			 * this socket in this tb, so reset our tb's reuseport
			 * settings so that any subsequent sockets that match
			 * our current socket will be put on the fast path.
			 *
			 * If we reset we need to set FASTREUSEPORT_STRICT so we
			 * do extra checking for all subsequent sk_reuseport
			 * socks.
			 */
			if (!sk_reuseport_match(tb, sk)) {
				tb->fastreuseport = FASTREUSEPORT_STRICT;
				tb->fastuid = uid;
				tb->fast_rcv_saddr = sk->sk_rcv_saddr;
				tb->fast_ipv6_only = ipv6_only_sock(sk);
J
Josef Bacik 已提交
358
				tb->fast_sk_family = sk->sk_family;
359 360 361 362 363
#if IS_ENABLED(CONFIG_IPV6)
				tb->fast_v6_rcv_saddr = sk->sk_v6_rcv_saddr;
#endif
			}
		} else {
364
			tb->fastreuseport = 0;
365
		}
366
	}
367
	if (!inet_csk(sk)->icsk_bind_hash)
368
		inet_bind_hash(sk, tb, port);
369
	WARN_ON(inet_csk(sk)->icsk_bind_hash != tb);
370
	ret = 0;
371 372

fail_unlock:
373
	spin_unlock_bh(&head->lock);
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
	return ret;
}
EXPORT_SYMBOL_GPL(inet_csk_get_port);

/*
 * Wait for an incoming connection, avoid race conditions. This must be called
 * with the socket locked.
 */
static int inet_csk_wait_for_connect(struct sock *sk, long timeo)
{
	struct inet_connection_sock *icsk = inet_csk(sk);
	DEFINE_WAIT(wait);
	int err;

	/*
	 * True wake-one mechanism for incoming connections: only
	 * one process gets woken up, not the 'whole herd'.
	 * Since we do not 'race & poll' for established sockets
	 * anymore, the common case will execute the loop only once.
	 *
	 * Subtle issue: "add_wait_queue_exclusive()" will be added
	 * after any current non-exclusive waiters, and we know that
	 * it will always _stay_ after any new non-exclusive waiters
	 * because all non-exclusive waiters are added at the
	 * beginning of the wait-queue. As such, it's ok to "drop"
	 * our exclusiveness temporarily when we get woken up without
	 * having to remove and re-insert us on the wait queue.
	 */
	for (;;) {
E
Eric Dumazet 已提交
403
		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
404 405 406 407
					  TASK_INTERRUPTIBLE);
		release_sock(sk);
		if (reqsk_queue_empty(&icsk->icsk_accept_queue))
			timeo = schedule_timeout(timeo);
408
		sched_annotate_sleep();
409 410 411 412 413 414 415 416 417 418 419 420 421 422
		lock_sock(sk);
		err = 0;
		if (!reqsk_queue_empty(&icsk->icsk_accept_queue))
			break;
		err = -EINVAL;
		if (sk->sk_state != TCP_LISTEN)
			break;
		err = sock_intr_errno(timeo);
		if (signal_pending(current))
			break;
		err = -EAGAIN;
		if (!timeo)
			break;
	}
E
Eric Dumazet 已提交
423
	finish_wait(sk_sleep(sk), &wait);
424 425 426 427 428 429
	return err;
}

/*
 * This will accept the next outstanding connection.
 */
430
struct sock *inet_csk_accept(struct sock *sk, int flags, int *err, bool kern)
431 432
{
	struct inet_connection_sock *icsk = inet_csk(sk);
433 434
	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
	struct request_sock *req;
435
	struct sock *newsk;
436 437 438 439 440 441 442 443 444 445 446 447
	int error;

	lock_sock(sk);

	/* We need to make sure that this socket is listening,
	 * and that it has something pending.
	 */
	error = -EINVAL;
	if (sk->sk_state != TCP_LISTEN)
		goto out_err;

	/* Find already established connection */
448
	if (reqsk_queue_empty(queue)) {
449 450 451 452 453 454 455 456 457 458 459
		long timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);

		/* If this is a non blocking socket don't sleep */
		error = -EAGAIN;
		if (!timeo)
			goto out_err;

		error = inet_csk_wait_for_connect(sk, timeo);
		if (error)
			goto out_err;
	}
460
	req = reqsk_queue_remove(queue, sk);
461 462
	newsk = req->sk;

463
	if (sk->sk_protocol == IPPROTO_TCP &&
464 465
	    tcp_rsk(req)->tfo_listener) {
		spin_lock_bh(&queue->fastopenq.lock);
466
		if (tcp_rsk(req)->tfo_listener) {
467 468 469 470 471 472 473 474 475
			/* We are still waiting for the final ACK from 3WHS
			 * so can't free req now. Instead, we set req->sk to
			 * NULL to signify that the child socket is taken
			 * so reqsk_fastopen_remove() will free the req
			 * when 3WHS finishes (or is aborted).
			 */
			req->sk = NULL;
			req = NULL;
		}
476
		spin_unlock_bh(&queue->fastopenq.lock);
477
	}
478 479
out:
	release_sock(sk);
480
	if (req)
481
		reqsk_put(req);
482 483 484
	return newsk;
out_err:
	newsk = NULL;
485
	req = NULL;
486 487 488 489 490 491 492
	*err = error;
	goto out;
}
EXPORT_SYMBOL(inet_csk_accept);

/*
 * Using different timers for retransmit, delayed acks and probes
493
 * We may wish use just one timer maintaining a list of expire jiffies
494 495 496 497 498 499 500 501 502
 * to optimize.
 */
void inet_csk_init_xmit_timers(struct sock *sk,
			       void (*retransmit_handler)(unsigned long),
			       void (*delack_handler)(unsigned long),
			       void (*keepalive_handler)(unsigned long))
{
	struct inet_connection_sock *icsk = inet_csk(sk);

503 504 505 506 507
	setup_timer(&icsk->icsk_retransmit_timer, retransmit_handler,
			(unsigned long)sk);
	setup_timer(&icsk->icsk_delack_timer, delack_handler,
			(unsigned long)sk);
	setup_timer(&sk->sk_timer, keepalive_handler, (unsigned long)sk);
508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
	icsk->icsk_pending = icsk->icsk_ack.pending = 0;
}
EXPORT_SYMBOL(inet_csk_init_xmit_timers);

void inet_csk_clear_xmit_timers(struct sock *sk)
{
	struct inet_connection_sock *icsk = inet_csk(sk);

	icsk->icsk_pending = icsk->icsk_ack.pending = icsk->icsk_ack.blocked = 0;

	sk_stop_timer(sk, &icsk->icsk_retransmit_timer);
	sk_stop_timer(sk, &icsk->icsk_delack_timer);
	sk_stop_timer(sk, &sk->sk_timer);
}
EXPORT_SYMBOL(inet_csk_clear_xmit_timers);

void inet_csk_delete_keepalive_timer(struct sock *sk)
{
	sk_stop_timer(sk, &sk->sk_timer);
}
EXPORT_SYMBOL(inet_csk_delete_keepalive_timer);

void inet_csk_reset_keepalive_timer(struct sock *sk, unsigned long len)
{
	sk_reset_timer(sk, &sk->sk_timer, jiffies + len);
}
EXPORT_SYMBOL(inet_csk_reset_keepalive_timer);

536
struct dst_entry *inet_csk_route_req(const struct sock *sk,
537
				     struct flowi4 *fl4,
538
				     const struct request_sock *req)
539 540
{
	const struct inet_request_sock *ireq = inet_rsk(req);
541 542 543
	struct net *net = read_pnet(&ireq->ireq_net);
	struct ip_options_rcu *opt = ireq->opt;
	struct rtable *rt;
544

545
	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
546
			   RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
547
			   sk->sk_protocol, inet_sk_flowi_flags(sk),
548
			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
549
			   ireq->ir_loc_addr, ireq->ir_rmt_port,
550
			   htons(ireq->ir_num), sk->sk_uid);
551 552
	security_req_classify_flow(req, flowi4_to_flowi(fl4));
	rt = ip_route_output_flow(net, fl4, sk);
553
	if (IS_ERR(rt))
I
Ilpo Järvinen 已提交
554
		goto no_route;
J
Julian Anastasov 已提交
555
	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
I
Ilpo Järvinen 已提交
556
		goto route_err;
557
	return &rt->dst;
I
Ilpo Järvinen 已提交
558 559 560 561

route_err:
	ip_rt_put(rt);
no_route:
E
Eric Dumazet 已提交
562
	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
I
Ilpo Järvinen 已提交
563
	return NULL;
564 565 566
}
EXPORT_SYMBOL_GPL(inet_csk_route_req);

567
struct dst_entry *inet_csk_route_child_sock(const struct sock *sk,
568 569 570 571
					    struct sock *newsk,
					    const struct request_sock *req)
{
	const struct inet_request_sock *ireq = inet_rsk(req);
572
	struct net *net = read_pnet(&ireq->ireq_net);
573
	struct inet_sock *newinet = inet_sk(newsk);
574
	struct ip_options_rcu *opt;
575 576 577 578
	struct flowi4 *fl4;
	struct rtable *rt;

	fl4 = &newinet->cork.fl.u.ip4;
579 580 581

	rcu_read_lock();
	opt = rcu_dereference(newinet->inet_opt);
582
	flowi4_init_output(fl4, ireq->ir_iif, ireq->ir_mark,
583 584
			   RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE,
			   sk->sk_protocol, inet_sk_flowi_flags(sk),
585
			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
586
			   ireq->ir_loc_addr, ireq->ir_rmt_port,
587
			   htons(ireq->ir_num), sk->sk_uid);
588 589 590 591
	security_req_classify_flow(req, flowi4_to_flowi(fl4));
	rt = ip_route_output_flow(net, fl4, sk);
	if (IS_ERR(rt))
		goto no_route;
J
Julian Anastasov 已提交
592
	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway)
593
		goto route_err;
594
	rcu_read_unlock();
595 596 597 598 599
	return &rt->dst;

route_err:
	ip_rt_put(rt);
no_route:
600
	rcu_read_unlock();
E
Eric Dumazet 已提交
601
	__IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
602 603 604 605
	return NULL;
}
EXPORT_SYMBOL_GPL(inet_csk_route_child_sock);

E
Eric Dumazet 已提交
606
#if IS_ENABLED(CONFIG_IPV6)
607 608
#define AF_INET_FAMILY(fam) ((fam) == AF_INET)
#else
609
#define AF_INET_FAMILY(fam) true
610 611
#endif

612 613 614 615 616 617 618
/* Decide when to expire the request and when to resend SYN-ACK */
static inline void syn_ack_recalc(struct request_sock *req, const int thresh,
				  const int max_retries,
				  const u8 rskq_defer_accept,
				  int *expire, int *resend)
{
	if (!rskq_defer_accept) {
619
		*expire = req->num_timeout >= thresh;
620 621 622
		*resend = 1;
		return;
	}
623 624
	*expire = req->num_timeout >= thresh &&
		  (!inet_rsk(req)->acked || req->num_timeout >= max_retries);
625 626 627 628 629 630
	/*
	 * Do not resend while waiting for data after ACK,
	 * start to resend on end of deferring period to give
	 * last chance for data or ACK to create established socket.
	 */
	*resend = !inet_rsk(req)->acked ||
631
		  req->num_timeout >= rskq_defer_accept - 1;
632 633
}

634
int inet_rtx_syn_ack(const struct sock *parent, struct request_sock *req)
635
{
C
Christoph Paasch 已提交
636
	int err = req->rsk_ops->rtx_syn_ack(parent, req);
637 638 639 640 641 642 643

	if (!err)
		req->num_retrans++;
	return err;
}
EXPORT_SYMBOL(inet_rtx_syn_ack);

644
/* return true if req was found in the ehash table */
645 646 647
static bool reqsk_queue_unlink(struct request_sock_queue *queue,
			       struct request_sock *req)
{
648
	struct inet_hashinfo *hashinfo = req_to_sk(req)->sk_prot->h.hashinfo;
649
	bool found = false;
650

651 652
	if (sk_hashed(req_to_sk(req))) {
		spinlock_t *lock = inet_ehash_lockp(hashinfo, req->rsk_hash);
653

654 655 656 657
		spin_lock(lock);
		found = __sk_nulls_del_node_init_rcu(req_to_sk(req));
		spin_unlock(lock);
	}
658
	if (timer_pending(&req->rsk_timer) && del_timer_sync(&req->rsk_timer))
659 660 661 662 663 664 665 666 667 668 669 670 671
		reqsk_put(req);
	return found;
}

void inet_csk_reqsk_queue_drop(struct sock *sk, struct request_sock *req)
{
	if (reqsk_queue_unlink(&inet_csk(sk)->icsk_accept_queue, req)) {
		reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
		reqsk_put(req);
	}
}
EXPORT_SYMBOL(inet_csk_reqsk_queue_drop);

672 673 674 675 676 677 678
void inet_csk_reqsk_queue_drop_and_put(struct sock *sk, struct request_sock *req)
{
	inet_csk_reqsk_queue_drop(sk, req);
	reqsk_put(req);
}
EXPORT_SYMBOL(inet_csk_reqsk_queue_drop_and_put);

679
static void reqsk_timer_handler(unsigned long data)
680
{
681 682
	struct request_sock *req = (struct request_sock *)data;
	struct sock *sk_listener = req->rsk_listener;
683
	struct net *net = sock_net(sk_listener);
684
	struct inet_connection_sock *icsk = inet_csk(sk_listener);
685
	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
686
	int qlen, expire = 0, resend = 0;
687
	int max_retries, thresh;
688
	u8 defer_accept;
689

690
	if (sk_state_load(sk_listener) != TCP_LISTEN)
691
		goto drop;
692

693
	max_retries = icsk->icsk_syn_retries ? : net->ipv4.sysctl_tcp_synack_retries;
694
	thresh = max_retries;
695 696
	/* Normally all the openreqs are young and become mature
	 * (i.e. converted to established socket) for first timeout.
697
	 * If synack was not acknowledged for 1 second, it means
698 699 700 701 702 703 704 705 706 707 708 709 710 711
	 * one of the following things: synack was lost, ack was lost,
	 * rtt is high or nobody planned to ack (i.e. synflood).
	 * When server is a bit loaded, queue is populated with old
	 * open requests, reducing effective size of queue.
	 * When server is well loaded, queue size reduces to zero
	 * after several minutes of work. It is not synflood,
	 * it is normal operation. The solution is pruning
	 * too old entries overriding normal timeout, when
	 * situation becomes dangerous.
	 *
	 * Essentially, we reserve half of room for young
	 * embrions; and abort old ones without pity, if old
	 * ones are about to clog our table.
	 */
712
	qlen = reqsk_queue_len(queue);
713
	if ((qlen << 1) > max(8U, sk_listener->sk_max_ack_backlog)) {
714
		int young = reqsk_queue_len_young(queue) << 1;
715 716

		while (thresh > 2) {
717
			if (qlen < young)
718 719 720 721 722
				break;
			thresh--;
			young <<= 1;
		}
	}
723 724 725 726
	defer_accept = READ_ONCE(queue->rskq_defer_accept);
	if (defer_accept)
		max_retries = defer_accept;
	syn_ack_recalc(req, thresh, max_retries, defer_accept,
727
		       &expire, &resend);
728
	req->rsk_ops->syn_ack_timeout(req);
729 730 731 732 733 734 735
	if (!expire &&
	    (!resend ||
	     !inet_rtx_syn_ack(sk_listener, req) ||
	     inet_rsk(req)->acked)) {
		unsigned long timeo;

		if (req->num_timeout++ == 0)
736
			atomic_dec(&queue->young);
737
		timeo = min(TCP_TIMEOUT_INIT << req->num_timeout, TCP_RTO_MAX);
738
		mod_timer(&req->rsk_timer, jiffies + timeo);
739 740
		return;
	}
741
drop:
742
	inet_csk_reqsk_queue_drop_and_put(sk_listener, req);
743
}
744

745 746
static void reqsk_queue_hash_req(struct request_sock *req,
				 unsigned long timeout)
747 748 749 750
{
	req->num_retrans = 0;
	req->num_timeout = 0;
	req->sk = NULL;
751

752 753 754
	setup_pinned_timer(&req->rsk_timer, reqsk_timer_handler,
			    (unsigned long)req);
	mod_timer(&req->rsk_timer, jiffies + timeout);
755

756
	inet_ehash_insert(req_to_sk(req), NULL);
757 758 759 760
	/* before letting lookups find us, make sure all req fields
	 * are committed to memory and refcnt initialized.
	 */
	smp_wmb();
761
	refcount_set(&req->rsk_refcnt, 2 + 1);
762
}
763

764 765 766 767 768
void inet_csk_reqsk_queue_hash_add(struct sock *sk, struct request_sock *req,
				   unsigned long timeout)
{
	reqsk_queue_hash_req(req, timeout);
	inet_csk_reqsk_queue_added(sk);
769
}
770
EXPORT_SYMBOL_GPL(inet_csk_reqsk_queue_hash_add);
771

772 773 774 775 776 777 778 779 780 781 782
/**
 *	inet_csk_clone_lock - clone an inet socket, and lock its clone
 *	@sk: the socket to clone
 *	@req: request_sock
 *	@priority: for allocation (%GFP_KERNEL, %GFP_ATOMIC, etc)
 *
 *	Caller must unlock socket even in error path (bh_unlock_sock(newsk))
 */
struct sock *inet_csk_clone_lock(const struct sock *sk,
				 const struct request_sock *req,
				 const gfp_t priority)
783
{
784
	struct sock *newsk = sk_clone_lock(sk, priority);
785

786
	if (newsk) {
787 788 789 790 791
		struct inet_connection_sock *newicsk = inet_csk(newsk);

		newsk->sk_state = TCP_SYN_RECV;
		newicsk->icsk_bind_hash = NULL;

792
		inet_sk(newsk)->inet_dport = inet_rsk(req)->ir_rmt_port;
E
Eric Dumazet 已提交
793 794
		inet_sk(newsk)->inet_num = inet_rsk(req)->ir_num;
		inet_sk(newsk)->inet_sport = htons(inet_rsk(req)->ir_num);
795

796 797 798
		/* listeners have SOCK_RCU_FREE, not the children */
		sock_reset_flag(newsk, SOCK_RCU_FREE);

799 800
		inet_sk(newsk)->mc_list = NULL;

801
		newsk->sk_mark = inet_rsk(req)->ir_mark;
E
Eric Dumazet 已提交
802 803
		atomic64_set(&newsk->sk_cookie,
			     atomic64_read(&inet_rsk(req)->ir_cookie));
804

805
		newicsk->icsk_retransmits = 0;
806 807
		newicsk->icsk_backoff	  = 0;
		newicsk->icsk_probes_out  = 0;
808 809 810

		/* Deinitialize accept_queue to trap illegal accesses. */
		memset(&newicsk->icsk_accept_queue, 0, sizeof(newicsk->icsk_accept_queue));
811 812

		security_inet_csk_clone(newsk, req);
813 814 815
	}
	return newsk;
}
816
EXPORT_SYMBOL_GPL(inet_csk_clone_lock);
817 818 819 820 821 822 823 824 825

/*
 * At this point, there should be no process reference to this
 * socket, and thus no user references at all.  Therefore we
 * can assume the socket waitqueue is inactive and nobody will
 * try to jump onto it.
 */
void inet_csk_destroy_sock(struct sock *sk)
{
826 827
	WARN_ON(sk->sk_state != TCP_CLOSE);
	WARN_ON(!sock_flag(sk, SOCK_DEAD));
828 829

	/* It cannot be in hash table! */
830
	WARN_ON(!sk_unhashed(sk));
831

E
Eric Dumazet 已提交
832 833
	/* If it has not 0 inet_sk(sk)->inet_num, it must be bound */
	WARN_ON(inet_sk(sk)->inet_num && !inet_csk(sk)->icsk_bind_hash);
834 835 836 837 838 839 840 841 842

	sk->sk_prot->destroy(sk);

	sk_stream_kill_queues(sk);

	xfrm_sk_free_policy(sk);

	sk_refcnt_debug_release(sk);

843
	percpu_counter_dec(sk->sk_prot->orphan_count);
844

845 846 847 848
	sock_put(sk);
}
EXPORT_SYMBOL(inet_csk_destroy_sock);

849 850 851 852
/* This function allows to force a closure of a socket after the call to
 * tcp/dccp_create_openreq_child().
 */
void inet_csk_prepare_forced_close(struct sock *sk)
853
	__releases(&sk->sk_lock.slock)
854 855 856 857 858 859 860 861 862 863 864 865
{
	/* sk_clone_lock locked the socket and set refcnt to 2 */
	bh_unlock_sock(sk);
	sock_put(sk);

	/* The below has to be done to allow calling inet_csk_destroy_sock */
	sock_set_flag(sk, SOCK_DEAD);
	percpu_counter_inc(sk->sk_prot->orphan_count);
	inet_sk(sk)->inet_num = 0;
}
EXPORT_SYMBOL(inet_csk_prepare_forced_close);

866
int inet_csk_listen_start(struct sock *sk, int backlog)
867 868
{
	struct inet_connection_sock *icsk = inet_csk(sk);
E
Eric Dumazet 已提交
869
	struct inet_sock *inet = inet_sk(sk);
870
	int err = -EADDRINUSE;
871

E
Eric Dumazet 已提交
872
	reqsk_queue_alloc(&icsk->icsk_accept_queue);
873

874
	sk->sk_max_ack_backlog = backlog;
875 876 877 878 879 880 881 882
	sk->sk_ack_backlog = 0;
	inet_csk_delack_init(sk);

	/* There is race window here: we announce ourselves listening,
	 * but this transition is still not validated by get_port().
	 * It is OK, because this socket enters to hash table only
	 * after validation is complete.
	 */
883
	sk_state_store(sk, TCP_LISTEN);
E
Eric Dumazet 已提交
884 885
	if (!sk->sk_prot->get_port(sk, inet->inet_num)) {
		inet->inet_sport = htons(inet->inet_num);
886 887

		sk_dst_reset(sk);
888
		err = sk->sk_prot->hash(sk);
889

890 891
		if (likely(!err))
			return 0;
892 893 894
	}

	sk->sk_state = TCP_CLOSE;
895
	return err;
896 897 898
}
EXPORT_SYMBOL_GPL(inet_csk_listen_start);

899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922
static void inet_child_forget(struct sock *sk, struct request_sock *req,
			      struct sock *child)
{
	sk->sk_prot->disconnect(child, O_NONBLOCK);

	sock_orphan(child);

	percpu_counter_inc(sk->sk_prot->orphan_count);

	if (sk->sk_protocol == IPPROTO_TCP && tcp_rsk(req)->tfo_listener) {
		BUG_ON(tcp_sk(child)->fastopen_rsk != req);
		BUG_ON(sk != req->rsk_listener);

		/* Paranoid, to prevent race condition if
		 * an inbound pkt destined for child is
		 * blocked by sock lock in tcp_v4_rcv().
		 * Also to satisfy an assertion in
		 * tcp_v4_destroy_sock().
		 */
		tcp_sk(child)->fastopen_rsk = NULL;
	}
	inet_csk_destroy_sock(child);
}

923 924 925
struct sock *inet_csk_reqsk_queue_add(struct sock *sk,
				      struct request_sock *req,
				      struct sock *child)
926 927 928 929 930 931
{
	struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue;

	spin_lock(&queue->rskq_lock);
	if (unlikely(sk->sk_state != TCP_LISTEN)) {
		inet_child_forget(sk, req, child);
932
		child = NULL;
933 934 935 936 937 938 939 940 941 942 943
	} else {
		req->sk = child;
		req->dl_next = NULL;
		if (queue->rskq_accept_head == NULL)
			queue->rskq_accept_head = req;
		else
			queue->rskq_accept_tail->dl_next = req;
		queue->rskq_accept_tail = req;
		sk_acceptq_added(sk);
	}
	spin_unlock(&queue->rskq_lock);
944
	return child;
945 946 947
}
EXPORT_SYMBOL(inet_csk_reqsk_queue_add);

948 949 950 951 952 953
struct sock *inet_csk_complete_hashdance(struct sock *sk, struct sock *child,
					 struct request_sock *req, bool own_req)
{
	if (own_req) {
		inet_csk_reqsk_queue_drop(sk, req);
		reqsk_queue_removed(&inet_csk(sk)->icsk_accept_queue, req);
954 955
		if (inet_csk_reqsk_queue_add(sk, req, child))
			return child;
956 957 958 959 960 961 962 963
	}
	/* Too bad, another child took ownership of the request, undo. */
	bh_unlock_sock(child);
	sock_put(child);
	return NULL;
}
EXPORT_SYMBOL(inet_csk_complete_hashdance);

964 965 966 967 968 969 970
/*
 *	This routine closes sockets which have been at least partially
 *	opened, but not yet accepted.
 */
void inet_csk_listen_stop(struct sock *sk)
{
	struct inet_connection_sock *icsk = inet_csk(sk);
971
	struct request_sock_queue *queue = &icsk->icsk_accept_queue;
972
	struct request_sock *next, *req;
973 974 975 976 977 978 979 980 981

	/* Following specs, it would be better either to send FIN
	 * (and enter FIN-WAIT-1, it is normal close)
	 * or to send active reset (abort).
	 * Certainly, it is pretty dangerous while synflood, but it is
	 * bad justification for our negligence 8)
	 * To be honest, we are not able to make either
	 * of the variants now.			--ANK
	 */
982
	while ((req = reqsk_queue_remove(queue, sk)) != NULL) {
983 984 985 986
		struct sock *child = req->sk;

		local_bh_disable();
		bh_lock_sock(child);
987
		WARN_ON(sock_owned_by_user(child));
988 989
		sock_hold(child);

990
		inet_child_forget(sk, req, child);
991
		reqsk_put(req);
992 993 994 995
		bh_unlock_sock(child);
		local_bh_enable();
		sock_put(child);

996
		cond_resched();
997
	}
998
	if (queue->fastopenq.rskq_rst_head) {
999
		/* Free all the reqs queued in rskq_rst_head. */
1000
		spin_lock_bh(&queue->fastopenq.lock);
1001
		req = queue->fastopenq.rskq_rst_head;
1002 1003
		queue->fastopenq.rskq_rst_head = NULL;
		spin_unlock_bh(&queue->fastopenq.lock);
1004 1005
		while (req != NULL) {
			next = req->dl_next;
1006
			reqsk_put(req);
1007
			req = next;
1008 1009
		}
	}
1010
	WARN_ON_ONCE(sk->sk_ack_backlog);
1011 1012
}
EXPORT_SYMBOL_GPL(inet_csk_listen_stop);
1013 1014 1015 1016 1017 1018 1019

void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr)
{
	struct sockaddr_in *sin = (struct sockaddr_in *)uaddr;
	const struct inet_sock *inet = inet_sk(sk);

	sin->sin_family		= AF_INET;
E
Eric Dumazet 已提交
1020 1021
	sin->sin_addr.s_addr	= inet->inet_daddr;
	sin->sin_port		= inet->inet_dport;
1022 1023
}
EXPORT_SYMBOL_GPL(inet_csk_addr2sockaddr);
1024

1025 1026 1027 1028
#ifdef CONFIG_COMPAT
int inet_csk_compat_getsockopt(struct sock *sk, int level, int optname,
			       char __user *optval, int __user *optlen)
{
1029
	const struct inet_connection_sock *icsk = inet_csk(sk);
1030

1031
	if (icsk->icsk_af_ops->compat_getsockopt)
1032 1033 1034 1035 1036 1037 1038 1039
		return icsk->icsk_af_ops->compat_getsockopt(sk, level, optname,
							    optval, optlen);
	return icsk->icsk_af_ops->getsockopt(sk, level, optname,
					     optval, optlen);
}
EXPORT_SYMBOL_GPL(inet_csk_compat_getsockopt);

int inet_csk_compat_setsockopt(struct sock *sk, int level, int optname,
1040
			       char __user *optval, unsigned int optlen)
1041
{
1042
	const struct inet_connection_sock *icsk = inet_csk(sk);
1043

1044
	if (icsk->icsk_af_ops->compat_setsockopt)
1045 1046 1047 1048 1049 1050 1051
		return icsk->icsk_af_ops->compat_setsockopt(sk, level, optname,
							    optval, optlen);
	return icsk->icsk_af_ops->setsockopt(sk, level, optname,
					     optval, optlen);
}
EXPORT_SYMBOL_GPL(inet_csk_compat_setsockopt);
#endif
1052 1053 1054

static struct dst_entry *inet_csk_rebuild_route(struct sock *sk, struct flowi *fl)
{
E
Eric Dumazet 已提交
1055 1056
	const struct inet_sock *inet = inet_sk(sk);
	const struct ip_options_rcu *inet_opt;
1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
	__be32 daddr = inet->inet_daddr;
	struct flowi4 *fl4;
	struct rtable *rt;

	rcu_read_lock();
	inet_opt = rcu_dereference(inet->inet_opt);
	if (inet_opt && inet_opt->opt.srr)
		daddr = inet_opt->opt.faddr;
	fl4 = &fl->u.ip4;
	rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr,
				   inet->inet_saddr, inet->inet_dport,
				   inet->inet_sport, sk->sk_protocol,
				   RT_CONN_FLAGS(sk), sk->sk_bound_dev_if);
	if (IS_ERR(rt))
		rt = NULL;
	if (rt)
		sk_setup_caps(sk, &rt->dst);
	rcu_read_unlock();

	return &rt->dst;
}

struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu)
{
	struct dst_entry *dst = __sk_dst_check(sk, 0);
	struct inet_sock *inet = inet_sk(sk);

	if (!dst) {
		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
		if (!dst)
			goto out;
	}
1089
	dst->ops->update_pmtu(dst, sk, NULL, mtu);
1090 1091 1092 1093 1094 1095 1096 1097

	dst = __sk_dst_check(sk, 0);
	if (!dst)
		dst = inet_csk_rebuild_route(sk, &inet->cork.fl);
out:
	return dst;
}
EXPORT_SYMBOL_GPL(inet_csk_update_pmtu);