1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.
6  * Copyright (c) 2006-2007 Robert N. M. Watson
7  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8  * All rights reserved.
9  *
10  * Portions of this software were developed by Robert N. M. Watson under
11  * contract to Juniper Networks, Inc.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	From: @(#)tcp_usrreq.c	8.2 (Berkeley) 1/3/94
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD: stable/12/sys/netinet/tcp_usrreq.c 372961 2023-03-03 21:30:21Z git2svn $");
42 
43 #include "opt_ddb.h"
44 #include "opt_inet.h"
45 #include "opt_inet6.h"
46 #include "opt_ipsec.h"
47 #include "opt_tcpdebug.h"
48 
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/limits.h>
52 #include <sys/malloc.h>
53 #include <sys/refcount.h>
54 #include <sys/kernel.h>
55 #include <sys/sysctl.h>
56 #include <sys/mbuf.h>
57 #ifdef INET6
58 #include <sys/domain.h>
59 #endif /* INET6 */
60 #include <sys/socket.h>
61 #include <sys/socketvar.h>
62 #include <sys/protosw.h>
63 #include <sys/proc.h>
64 #include <sys/jail.h>
65 #include <sys/syslog.h>
66 
67 #ifdef DDB
68 #include <ddb/ddb.h>
69 #endif
70 
71 #include <net/if.h>
72 #include <net/if_var.h>
73 #include <net/route.h>
74 #include <net/vnet.h>
75 
76 #include <netinet/in.h>
77 #include <netinet/in_kdtrace.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/in_systm.h>
80 #include <netinet/in_var.h>
81 #include <netinet/ip_var.h>
82 #ifdef INET6
83 #include <netinet/ip6.h>
84 #include <netinet6/in6_pcb.h>
85 #include <netinet6/ip6_var.h>
86 #include <netinet6/scope6_var.h>
87 #endif
88 #include <netinet/tcp.h>
89 #include <netinet/tcp_fsm.h>
90 #include <netinet/tcp_seq.h>
91 #include <netinet/tcp_timer.h>
92 #include <netinet/tcp_var.h>
93 #include <netinet/tcp_log_buf.h>
94 #include <netinet/tcpip.h>
95 #include <netinet/cc/cc.h>
96 #include <netinet/tcp_fastopen.h>
97 #include <netinet/tcp_hpts.h>
98 #ifdef TCPPCAP
99 #include <netinet/tcp_pcap.h>
100 #endif
101 #ifdef TCPDEBUG
102 #include <netinet/tcp_debug.h>
103 #endif
104 #ifdef TCP_OFFLOAD
105 #include <netinet/tcp_offload.h>
106 #endif
107 #include <netipsec/ipsec_support.h>
108 
109 /*
110  * TCP protocol interface to socket abstraction.
111  */
112 static int	tcp_attach(struct socket *);
113 #ifdef INET
114 static int	tcp_connect(struct tcpcb *, struct sockaddr *,
115 		    struct thread *td);
116 #endif /* INET */
117 #ifdef INET6
118 static int	tcp6_connect(struct tcpcb *, struct sockaddr *,
119 		    struct thread *td);
120 #endif /* INET6 */
121 static void	tcp_disconnect(struct tcpcb *);
122 static void	tcp_usrclosed(struct tcpcb *);
123 static void	tcp_fill_info(struct tcpcb *, struct tcp_info *);
124 
125 #ifdef TCPDEBUG
126 #define	TCPDEBUG0	int ostate = 0
127 #define	TCPDEBUG1()	ostate = tp ? tp->t_state : 0
128 #define	TCPDEBUG2(req)	if (tp && (so->so_options & SO_DEBUG)) \
129 				tcp_trace(TA_USER, ostate, tp, 0, 0, req)
130 #else
131 #define	TCPDEBUG0
132 #define	TCPDEBUG1()
133 #define	TCPDEBUG2(req)
134 #endif
135 
136 /*
137  * tcp_require_unique port requires a globally-unique source port for each
138  * outgoing connection.  The default is to require the 4-tuple to be unique.
139  */
140 VNET_DEFINE(int, tcp_require_unique_port) = 0;
141 SYSCTL_INT(_net_inet_tcp, OID_AUTO, require_unique_port,
142     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(tcp_require_unique_port), 0,
143     "Require globally-unique ephemeral port for outgoing connections");
144 #define	V_tcp_require_unique_port	VNET(tcp_require_unique_port)
145 
146 /*
147  * TCP attaches to socket via pru_attach(), reserving space,
148  * and an internet control block.
149  */
150 static int
tcp_usr_attach(struct socket * so,int proto,struct thread * td)151 tcp_usr_attach(struct socket *so, int proto, struct thread *td)
152 {
153 	struct inpcb *inp;
154 	struct tcpcb *tp = NULL;
155 	int error;
156 	TCPDEBUG0;
157 
158 	inp = sotoinpcb(so);
159 	KASSERT(inp == NULL, ("tcp_usr_attach: inp != NULL"));
160 	TCPDEBUG1();
161 
162 	error = tcp_attach(so);
163 	if (error)
164 		goto out;
165 
166 	inp = sotoinpcb(so);
167 	tp = intotcpcb(inp);
168 out:
169 	TCPDEBUG2(PRU_ATTACH);
170 	TCP_PROBE2(debug__user, tp, PRU_ATTACH);
171 	return error;
172 }
173 
174 /*
175  * tcp_detach is called when the socket layer loses its final reference
176  * to the socket, be it a file descriptor reference, a reference from TCP,
177  * etc.  At this point, there is only one case in which we will keep around
178  * inpcb state: time wait.
179  *
180  * This function can probably be re-absorbed back into tcp_usr_detach() now
181  * that there is a single detach path.
182  */
183 static void
tcp_detach(struct socket * so,struct inpcb * inp)184 tcp_detach(struct socket *so, struct inpcb *inp)
185 {
186 	struct tcpcb *tp;
187 
188 	INP_INFO_LOCK_ASSERT(&V_tcbinfo);
189 	INP_WLOCK_ASSERT(inp);
190 
191 	KASSERT(so->so_pcb == inp, ("tcp_detach: so_pcb != inp"));
192 	KASSERT(inp->inp_socket == so, ("tcp_detach: inp_socket != so"));
193 
194 	tp = intotcpcb(inp);
195 
196 	if (inp->inp_flags & INP_TIMEWAIT) {
197 		/*
198 		 * There are two cases to handle: one in which the time wait
199 		 * state is being discarded (INP_DROPPED), and one in which
200 		 * this connection will remain in timewait.  In the former,
201 		 * it is time to discard all state (except tcptw, which has
202 		 * already been discarded by the timewait close code, which
203 		 * should be further up the call stack somewhere).  In the
204 		 * latter case, we detach from the socket, but leave the pcb
205 		 * present until timewait ends.
206 		 *
207 		 * XXXRW: Would it be cleaner to free the tcptw here?
208 		 *
209 		 * Astute question indeed, from twtcp perspective there are
210 		 * four cases to consider:
211 		 *
212 		 * #1 tcp_detach is called at tcptw creation time by
213 		 *  tcp_twstart, then do not discard the newly created tcptw
214 		 *  and leave inpcb present until timewait ends
215 		 * #2 tcp_detach is called at tcptw creation time by
216 		 *  tcp_twstart, but connection is local and tw will be
217 		 *  discarded immediately
218 		 * #3 tcp_detach is called at timewait end (or reuse) by
219 		 *  tcp_twclose, then the tcptw has already been discarded
220 		 *  (or reused) and inpcb is freed here
221 		 * #4 tcp_detach is called() after timewait ends (or reuse)
222 		 *  (e.g. by soclose), then tcptw has already been discarded
223 		 *  (or reused) and inpcb is freed here
224 		 *
225 		 *  In all three cases the tcptw should not be freed here.
226 		 */
227 		if (inp->inp_flags & INP_DROPPED) {
228 			in_pcbdetach(inp);
229 			if (__predict_true(tp == NULL)) {
230 				in_pcbfree(inp);
231 			} else {
232 				/*
233 				 * This case should not happen as in TIMEWAIT
234 				 * state the inp should not be destroyed before
235 				 * its tcptw.  If INVARIANTS is defined, panic.
236 				 */
237 #ifdef INVARIANTS
238 				panic("%s: Panic before an inp double-free: "
239 				    "INP_TIMEWAIT && INP_DROPPED && tp != NULL"
240 				    , __func__);
241 #else
242 				log(LOG_ERR, "%s: Avoid an inp double-free: "
243 				    "INP_TIMEWAIT && INP_DROPPED && tp != NULL"
244 				    , __func__);
245 #endif
246 				INP_WUNLOCK(inp);
247 			}
248 		} else {
249 			in_pcbdetach(inp);
250 			INP_WUNLOCK(inp);
251 		}
252 	} else {
253 		/*
254 		 * If the connection is not in timewait, we consider two
255 		 * two conditions: one in which no further processing is
256 		 * necessary (dropped || embryonic), and one in which TCP is
257 		 * not yet done, but no longer requires the socket, so the
258 		 * pcb will persist for the time being.
259 		 *
260 		 * XXXRW: Does the second case still occur?
261 		 */
262 		if (inp->inp_flags & INP_DROPPED ||
263 		    tp->t_state < TCPS_SYN_SENT) {
264 			tcp_discardcb(tp);
265 			in_pcbdetach(inp);
266 			in_pcbfree(inp);
267 		} else {
268 			in_pcbdetach(inp);
269 			INP_WUNLOCK(inp);
270 		}
271 	}
272 }
273 
274 /*
275  * pru_detach() detaches the TCP protocol from the socket.
276  * If the protocol state is non-embryonic, then can't
277  * do this directly: have to initiate a pru_disconnect(),
278  * which may finish later; embryonic TCB's can just
279  * be discarded here.
280  */
281 static void
tcp_usr_detach(struct socket * so)282 tcp_usr_detach(struct socket *so)
283 {
284 	struct inpcb *inp;
285 	int rlock = 0;
286 	struct epoch_tracker et;
287 
288 	inp = sotoinpcb(so);
289 	KASSERT(inp != NULL, ("tcp_usr_detach: inp == NULL"));
290 	if (!INP_INFO_WLOCKED(&V_tcbinfo)) {
291 		INP_INFO_RLOCK_ET(&V_tcbinfo, et);
292 		rlock = 1;
293 	}
294 	INP_WLOCK(inp);
295 	KASSERT(inp->inp_socket != NULL,
296 	    ("tcp_usr_detach: inp_socket == NULL"));
297 	tcp_detach(so, inp);
298 	if (rlock)
299 		INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
300 }
301 
302 #ifdef INET
303 /*
304  * Give the socket an address.
305  */
306 static int
tcp_usr_bind(struct socket * so,struct sockaddr * nam,struct thread * td)307 tcp_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
308 {
309 	int error = 0;
310 	struct inpcb *inp;
311 	struct tcpcb *tp = NULL;
312 	struct sockaddr_in *sinp;
313 
314 	sinp = (struct sockaddr_in *)nam;
315 	if (nam->sa_len != sizeof (*sinp))
316 		return (EINVAL);
317 	/*
318 	 * Must check for multicast addresses and disallow binding
319 	 * to them.
320 	 */
321 	if (sinp->sin_family == AF_INET &&
322 	    IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
323 		return (EAFNOSUPPORT);
324 
325 	TCPDEBUG0;
326 	inp = sotoinpcb(so);
327 	KASSERT(inp != NULL, ("tcp_usr_bind: inp == NULL"));
328 	INP_WLOCK(inp);
329 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
330 		error = EINVAL;
331 		goto out;
332 	}
333 	tp = intotcpcb(inp);
334 	TCPDEBUG1();
335 	INP_HASH_WLOCK(&V_tcbinfo);
336 	error = in_pcbbind(inp, nam, td->td_ucred);
337 	INP_HASH_WUNLOCK(&V_tcbinfo);
338 out:
339 	TCPDEBUG2(PRU_BIND);
340 	TCP_PROBE2(debug__user, tp, PRU_BIND);
341 	INP_WUNLOCK(inp);
342 
343 	return (error);
344 }
345 #endif /* INET */
346 
347 #ifdef INET6
348 static int
tcp6_usr_bind(struct socket * so,struct sockaddr * nam,struct thread * td)349 tcp6_usr_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
350 {
351 	int error = 0;
352 	struct inpcb *inp;
353 	struct tcpcb *tp = NULL;
354 	struct sockaddr_in6 *sin6;
355 	u_char vflagsav;
356 
357 	sin6 = (struct sockaddr_in6 *)nam;
358 	if (nam->sa_len != sizeof (*sin6))
359 		return (EINVAL);
360 	/*
361 	 * Must check for multicast addresses and disallow binding
362 	 * to them.
363 	 */
364 	if (sin6->sin6_family == AF_INET6 &&
365 	    IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
366 		return (EAFNOSUPPORT);
367 
368 	TCPDEBUG0;
369 	inp = sotoinpcb(so);
370 	KASSERT(inp != NULL, ("tcp6_usr_bind: inp == NULL"));
371 	INP_WLOCK(inp);
372 	vflagsav = inp->inp_vflag;
373 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
374 		error = EINVAL;
375 		goto out;
376 	}
377 	tp = intotcpcb(inp);
378 	TCPDEBUG1();
379 	INP_HASH_WLOCK(&V_tcbinfo);
380 	inp->inp_vflag &= ~INP_IPV4;
381 	inp->inp_vflag |= INP_IPV6;
382 #ifdef INET
383 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
384 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
385 			inp->inp_vflag |= INP_IPV4;
386 		else if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
387 			struct sockaddr_in sin;
388 
389 			in6_sin6_2_sin(&sin, sin6);
390 			if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
391 				error = EAFNOSUPPORT;
392 				INP_HASH_WUNLOCK(&V_tcbinfo);
393 				goto out;
394 			}
395 			inp->inp_vflag |= INP_IPV4;
396 			inp->inp_vflag &= ~INP_IPV6;
397 			error = in_pcbbind(inp, (struct sockaddr *)&sin,
398 			    td->td_ucred);
399 			INP_HASH_WUNLOCK(&V_tcbinfo);
400 			goto out;
401 		}
402 	}
403 #endif
404 	error = in6_pcbbind(inp, nam, td->td_ucred);
405 	INP_HASH_WUNLOCK(&V_tcbinfo);
406 out:
407 	if (error != 0)
408 		inp->inp_vflag = vflagsav;
409 	TCPDEBUG2(PRU_BIND);
410 	TCP_PROBE2(debug__user, tp, PRU_BIND);
411 	INP_WUNLOCK(inp);
412 	return (error);
413 }
414 #endif /* INET6 */
415 
416 #ifdef INET
417 /*
418  * Prepare to accept connections.
419  */
420 static int
tcp_usr_listen(struct socket * so,int backlog,struct thread * td)421 tcp_usr_listen(struct socket *so, int backlog, struct thread *td)
422 {
423 	int error = 0;
424 	struct inpcb *inp;
425 	struct tcpcb *tp = NULL;
426 
427 	TCPDEBUG0;
428 	inp = sotoinpcb(so);
429 	KASSERT(inp != NULL, ("tcp_usr_listen: inp == NULL"));
430 	INP_WLOCK(inp);
431 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
432 		error = EINVAL;
433 		goto out;
434 	}
435 	tp = intotcpcb(inp);
436 	TCPDEBUG1();
437 	SOCK_LOCK(so);
438 	error = solisten_proto_check(so);
439 	INP_HASH_WLOCK(&V_tcbinfo);
440 	if (error == 0 && inp->inp_lport == 0)
441 		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
442 	INP_HASH_WUNLOCK(&V_tcbinfo);
443 	if (error == 0) {
444 		tcp_state_change(tp, TCPS_LISTEN);
445 		solisten_proto(so, backlog);
446 #ifdef TCP_OFFLOAD
447 		if ((so->so_options & SO_NO_OFFLOAD) == 0)
448 			tcp_offload_listen_start(tp);
449 #endif
450 	}
451 	SOCK_UNLOCK(so);
452 
453 	if (IS_FASTOPEN(tp->t_flags))
454 		tp->t_tfo_pending = tcp_fastopen_alloc_counter();
455 
456 out:
457 	TCPDEBUG2(PRU_LISTEN);
458 	TCP_PROBE2(debug__user, tp, PRU_LISTEN);
459 	INP_WUNLOCK(inp);
460 	return (error);
461 }
462 #endif /* INET */
463 
464 #ifdef INET6
465 static int
tcp6_usr_listen(struct socket * so,int backlog,struct thread * td)466 tcp6_usr_listen(struct socket *so, int backlog, struct thread *td)
467 {
468 	int error = 0;
469 	struct inpcb *inp;
470 	struct tcpcb *tp = NULL;
471 	u_char vflagsav;
472 
473 	TCPDEBUG0;
474 	inp = sotoinpcb(so);
475 	KASSERT(inp != NULL, ("tcp6_usr_listen: inp == NULL"));
476 	INP_WLOCK(inp);
477 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
478 		error = EINVAL;
479 		goto out;
480 	}
481 	vflagsav = inp->inp_vflag;
482 	tp = intotcpcb(inp);
483 	TCPDEBUG1();
484 	SOCK_LOCK(so);
485 	error = solisten_proto_check(so);
486 	INP_HASH_WLOCK(&V_tcbinfo);
487 	if (error == 0 && inp->inp_lport == 0) {
488 		inp->inp_vflag &= ~INP_IPV4;
489 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
490 			inp->inp_vflag |= INP_IPV4;
491 		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
492 	}
493 	INP_HASH_WUNLOCK(&V_tcbinfo);
494 	if (error == 0) {
495 		tcp_state_change(tp, TCPS_LISTEN);
496 		solisten_proto(so, backlog);
497 #ifdef TCP_OFFLOAD
498 		if ((so->so_options & SO_NO_OFFLOAD) == 0)
499 			tcp_offload_listen_start(tp);
500 #endif
501 	}
502 	SOCK_UNLOCK(so);
503 
504 	if (IS_FASTOPEN(tp->t_flags))
505 		tp->t_tfo_pending = tcp_fastopen_alloc_counter();
506 
507 	if (error != 0)
508 		inp->inp_vflag = vflagsav;
509 
510 out:
511 	TCPDEBUG2(PRU_LISTEN);
512 	TCP_PROBE2(debug__user, tp, PRU_LISTEN);
513 	INP_WUNLOCK(inp);
514 	return (error);
515 }
516 #endif /* INET6 */
517 
518 #ifdef INET
519 /*
520  * Initiate connection to peer.
521  * Create a template for use in transmissions on this connection.
522  * Enter SYN_SENT state, and mark socket as connecting.
523  * Start keep-alive timer, and seed output sequence space.
524  * Send initial segment on connection.
525  */
526 static int
tcp_usr_connect(struct socket * so,struct sockaddr * nam,struct thread * td)527 tcp_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
528 {
529 	int error = 0;
530 	struct inpcb *inp;
531 	struct tcpcb *tp = NULL;
532 	struct sockaddr_in *sinp;
533 
534 	sinp = (struct sockaddr_in *)nam;
535 	if (nam->sa_len != sizeof (*sinp))
536 		return (EINVAL);
537 	/*
538 	 * Must disallow TCP ``connections'' to multicast addresses.
539 	 */
540 	if (sinp->sin_family == AF_INET
541 	    && IN_MULTICAST(ntohl(sinp->sin_addr.s_addr)))
542 		return (EAFNOSUPPORT);
543 	if ((sinp->sin_family == AF_INET) &&
544 	    (ntohl(sinp->sin_addr.s_addr) == INADDR_BROADCAST))
545 		return (EACCES);
546 	if ((error = prison_remote_ip4(td->td_ucred, &sinp->sin_addr)) != 0)
547 		return (error);
548 
549 	TCPDEBUG0;
550 	inp = sotoinpcb(so);
551 	KASSERT(inp != NULL, ("tcp_usr_connect: inp == NULL"));
552 	INP_WLOCK(inp);
553 	if (inp->inp_flags & INP_TIMEWAIT) {
554 		error = EADDRINUSE;
555 		goto out;
556 	}
557 	if (inp->inp_flags & INP_DROPPED) {
558 		error = ECONNREFUSED;
559 		goto out;
560 	}
561 	tp = intotcpcb(inp);
562 	TCPDEBUG1();
563 	if ((error = tcp_connect(tp, nam, td)) != 0)
564 		goto out;
565 #ifdef TCP_OFFLOAD
566 	if (registered_toedevs > 0 &&
567 	    (so->so_options & SO_NO_OFFLOAD) == 0 &&
568 	    (error = tcp_offload_connect(so, nam)) == 0)
569 		goto out;
570 #endif
571 	tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
572 	error = tp->t_fb->tfb_tcp_output(tp);
573 out:
574 	TCPDEBUG2(PRU_CONNECT);
575 	TCP_PROBE2(debug__user, tp, PRU_CONNECT);
576 	INP_WUNLOCK(inp);
577 	return (error);
578 }
579 #endif /* INET */
580 
581 #ifdef INET6
582 static int
tcp6_usr_connect(struct socket * so,struct sockaddr * nam,struct thread * td)583 tcp6_usr_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
584 {
585 	int error = 0;
586 	struct inpcb *inp;
587 	struct tcpcb *tp = NULL;
588 	struct sockaddr_in6 *sin6;
589 	u_int8_t incflagsav;
590 	u_char vflagsav;
591 
592 	TCPDEBUG0;
593 
594 	sin6 = (struct sockaddr_in6 *)nam;
595 	if (nam->sa_len != sizeof (*sin6))
596 		return (EINVAL);
597 	/*
598 	 * Must disallow TCP ``connections'' to multicast addresses.
599 	 */
600 	if (sin6->sin6_family == AF_INET6
601 	    && IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr))
602 		return (EAFNOSUPPORT);
603 
604 	inp = sotoinpcb(so);
605 	KASSERT(inp != NULL, ("tcp6_usr_connect: inp == NULL"));
606 	INP_WLOCK(inp);
607 	vflagsav = inp->inp_vflag;
608 	incflagsav = inp->inp_inc.inc_flags;
609 	if (inp->inp_flags & INP_TIMEWAIT) {
610 		error = EADDRINUSE;
611 		goto out;
612 	}
613 	if (inp->inp_flags & INP_DROPPED) {
614 		error = ECONNREFUSED;
615 		goto out;
616 	}
617 	tp = intotcpcb(inp);
618 	TCPDEBUG1();
619 #ifdef INET
620 	/*
621 	 * XXXRW: Some confusion: V4/V6 flags relate to binding, and
622 	 * therefore probably require the hash lock, which isn't held here.
623 	 * Is this a significant problem?
624 	 */
625 	if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
626 		struct sockaddr_in sin;
627 
628 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
629 			error = EINVAL;
630 			goto out;
631 		}
632 		if ((inp->inp_vflag & INP_IPV4) == 0) {
633 			error = EAFNOSUPPORT;
634 			goto out;
635 		}
636 
637 		in6_sin6_2_sin(&sin, sin6);
638 		if (IN_MULTICAST(ntohl(sin.sin_addr.s_addr))) {
639 			error = EAFNOSUPPORT;
640 			goto out;
641 		}
642 		if (ntohl(sin.sin_addr.s_addr) == INADDR_BROADCAST) {
643 			error = EACCES;
644 			goto out;
645 		}
646 		if ((error = prison_remote_ip4(td->td_ucred,
647 		    &sin.sin_addr)) != 0)
648 			goto out;
649 		inp->inp_vflag |= INP_IPV4;
650 		inp->inp_vflag &= ~INP_IPV6;
651 		if ((error = tcp_connect(tp, (struct sockaddr *)&sin, td)) != 0)
652 			goto out;
653 #ifdef TCP_OFFLOAD
654 		if (registered_toedevs > 0 &&
655 		    (so->so_options & SO_NO_OFFLOAD) == 0 &&
656 		    (error = tcp_offload_connect(so, nam)) == 0)
657 			goto out;
658 #endif
659 		error = tp->t_fb->tfb_tcp_output(tp);
660 		goto out;
661 	} else {
662 		if ((inp->inp_vflag & INP_IPV6) == 0) {
663 			error = EAFNOSUPPORT;
664 			goto out;
665 		}
666 	}
667 #endif
668 	if ((error = prison_remote_ip6(td->td_ucred, &sin6->sin6_addr)) != 0)
669 		goto out;
670 	inp->inp_vflag &= ~INP_IPV4;
671 	inp->inp_vflag |= INP_IPV6;
672 	inp->inp_inc.inc_flags |= INC_ISIPV6;
673 	if ((error = tcp6_connect(tp, nam, td)) != 0)
674 		goto out;
675 #ifdef TCP_OFFLOAD
676 	if (registered_toedevs > 0 &&
677 	    (so->so_options & SO_NO_OFFLOAD) == 0 &&
678 	    (error = tcp_offload_connect(so, nam)) == 0)
679 		goto out;
680 #endif
681 	tcp_timer_activate(tp, TT_KEEP, TP_KEEPINIT(tp));
682 	error = tp->t_fb->tfb_tcp_output(tp);
683 
684 out:
685 	/*
686 	 * If the implicit bind in the connect call fails, restore
687 	 * the flags we modified.
688 	 */
689 	if (error != 0 && inp->inp_lport == 0) {
690 		inp->inp_vflag = vflagsav;
691 		inp->inp_inc.inc_flags = incflagsav;
692 	}
693 
694 	TCPDEBUG2(PRU_CONNECT);
695 	TCP_PROBE2(debug__user, tp, PRU_CONNECT);
696 	INP_WUNLOCK(inp);
697 	return (error);
698 }
699 #endif /* INET6 */
700 
701 /*
702  * Initiate disconnect from peer.
703  * If connection never passed embryonic stage, just drop;
704  * else if don't need to let data drain, then can just drop anyways,
705  * else have to begin TCP shutdown process: mark socket disconnecting,
706  * drain unread data, state switch to reflect user close, and
707  * send segment (e.g. FIN) to peer.  Socket will be really disconnected
708  * when peer sends FIN and acks ours.
709  *
710  * SHOULD IMPLEMENT LATER PRU_CONNECT VIA REALLOC TCPCB.
711  */
712 static int
tcp_usr_disconnect(struct socket * so)713 tcp_usr_disconnect(struct socket *so)
714 {
715 	struct inpcb *inp;
716 	struct tcpcb *tp = NULL;
717 	struct epoch_tracker et;
718 	int error = 0;
719 
720 	TCPDEBUG0;
721 	INP_INFO_RLOCK_ET(&V_tcbinfo, et);
722 	inp = sotoinpcb(so);
723 	KASSERT(inp != NULL, ("tcp_usr_disconnect: inp == NULL"));
724 	INP_WLOCK(inp);
725 	if (inp->inp_flags & INP_TIMEWAIT)
726 		goto out;
727 	if (inp->inp_flags & INP_DROPPED) {
728 		error = ECONNRESET;
729 		goto out;
730 	}
731 	tp = intotcpcb(inp);
732 	TCPDEBUG1();
733 	tcp_disconnect(tp);
734 out:
735 	TCPDEBUG2(PRU_DISCONNECT);
736 	TCP_PROBE2(debug__user, tp, PRU_DISCONNECT);
737 	INP_WUNLOCK(inp);
738 	INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
739 	return (error);
740 }
741 
742 #ifdef INET
743 /*
744  * Accept a connection.  Essentially all the work is done at higher levels;
745  * just return the address of the peer, storing through addr.
746  */
747 static int
tcp_usr_accept(struct socket * so,struct sockaddr ** nam)748 tcp_usr_accept(struct socket *so, struct sockaddr **nam)
749 {
750 	int error = 0;
751 	struct inpcb *inp = NULL;
752 	struct tcpcb *tp = NULL;
753 	struct in_addr addr;
754 	in_port_t port = 0;
755 	TCPDEBUG0;
756 
757 	if (so->so_state & SS_ISDISCONNECTED)
758 		return (ECONNABORTED);
759 
760 	inp = sotoinpcb(so);
761 	KASSERT(inp != NULL, ("tcp_usr_accept: inp == NULL"));
762 	INP_WLOCK(inp);
763 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
764 		error = ECONNABORTED;
765 		goto out;
766 	}
767 	tp = intotcpcb(inp);
768 	TCPDEBUG1();
769 
770 	/*
771 	 * We inline in_getpeeraddr and COMMON_END here, so that we can
772 	 * copy the data of interest and defer the malloc until after we
773 	 * release the lock.
774 	 */
775 	port = inp->inp_fport;
776 	addr = inp->inp_faddr;
777 
778 out:
779 	TCPDEBUG2(PRU_ACCEPT);
780 	TCP_PROBE2(debug__user, tp, PRU_ACCEPT);
781 	INP_WUNLOCK(inp);
782 	if (error == 0)
783 		*nam = in_sockaddr(port, &addr);
784 	return error;
785 }
786 #endif /* INET */
787 
788 #ifdef INET6
789 static int
tcp6_usr_accept(struct socket * so,struct sockaddr ** nam)790 tcp6_usr_accept(struct socket *so, struct sockaddr **nam)
791 {
792 	struct inpcb *inp = NULL;
793 	int error = 0;
794 	struct tcpcb *tp = NULL;
795 	struct in_addr addr;
796 	struct in6_addr addr6;
797 	struct epoch_tracker et;
798 	in_port_t port = 0;
799 	int v4 = 0;
800 	TCPDEBUG0;
801 
802 	if (so->so_state & SS_ISDISCONNECTED)
803 		return (ECONNABORTED);
804 
805 	inp = sotoinpcb(so);
806 	KASSERT(inp != NULL, ("tcp6_usr_accept: inp == NULL"));
807 	INP_INFO_RLOCK_ET(&V_tcbinfo, et);
808 	INP_WLOCK(inp);
809 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
810 		error = ECONNABORTED;
811 		goto out;
812 	}
813 	tp = intotcpcb(inp);
814 	TCPDEBUG1();
815 
816 	/*
817 	 * We inline in6_mapped_peeraddr and COMMON_END here, so that we can
818 	 * copy the data of interest and defer the malloc until after we
819 	 * release the lock.
820 	 */
821 	if (inp->inp_vflag & INP_IPV4) {
822 		v4 = 1;
823 		port = inp->inp_fport;
824 		addr = inp->inp_faddr;
825 	} else {
826 		port = inp->inp_fport;
827 		addr6 = inp->in6p_faddr;
828 	}
829 
830 out:
831 	TCPDEBUG2(PRU_ACCEPT);
832 	TCP_PROBE2(debug__user, tp, PRU_ACCEPT);
833 	INP_WUNLOCK(inp);
834 	INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
835 	if (error == 0) {
836 		if (v4)
837 			*nam = in6_v4mapsin6_sockaddr(port, &addr);
838 		else
839 			*nam = in6_sockaddr(port, &addr6);
840 	}
841 	return error;
842 }
843 #endif /* INET6 */
844 
845 /*
846  * Mark the connection as being incapable of further output.
847  */
848 static int
tcp_usr_shutdown(struct socket * so)849 tcp_usr_shutdown(struct socket *so)
850 {
851 	int error = 0;
852 	struct inpcb *inp;
853 	struct tcpcb *tp = NULL;
854 	struct epoch_tracker et;
855 
856 	TCPDEBUG0;
857 	INP_INFO_RLOCK_ET(&V_tcbinfo, et);
858 	inp = sotoinpcb(so);
859 	KASSERT(inp != NULL, ("inp == NULL"));
860 	INP_WLOCK(inp);
861 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
862 		error = ECONNRESET;
863 		goto out;
864 	}
865 	tp = intotcpcb(inp);
866 	TCPDEBUG1();
867 	socantsendmore(so);
868 	tcp_usrclosed(tp);
869 	if (!(inp->inp_flags & INP_DROPPED))
870 		error = tp->t_fb->tfb_tcp_output(tp);
871 
872 out:
873 	TCPDEBUG2(PRU_SHUTDOWN);
874 	TCP_PROBE2(debug__user, tp, PRU_SHUTDOWN);
875 	INP_WUNLOCK(inp);
876 	INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
877 
878 	return (error);
879 }
880 
881 /*
882  * After a receive, possibly send window update to peer.
883  */
884 static int
tcp_usr_rcvd(struct socket * so,int flags)885 tcp_usr_rcvd(struct socket *so, int flags)
886 {
887 	struct inpcb *inp;
888 	struct tcpcb *tp = NULL;
889 	int error = 0;
890 
891 	TCPDEBUG0;
892 	inp = sotoinpcb(so);
893 	KASSERT(inp != NULL, ("tcp_usr_rcvd: inp == NULL"));
894 	INP_WLOCK(inp);
895 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
896 		error = ECONNRESET;
897 		goto out;
898 	}
899 	tp = intotcpcb(inp);
900 	TCPDEBUG1();
901 	/*
902 	 * For passively-created TFO connections, don't attempt a window
903 	 * update while still in SYN_RECEIVED as this may trigger an early
904 	 * SYN|ACK.  It is preferable to have the SYN|ACK be sent along with
905 	 * application response data, or failing that, when the DELACK timer
906 	 * expires.
907 	 */
908 	if (IS_FASTOPEN(tp->t_flags) &&
909 	    (tp->t_state == TCPS_SYN_RECEIVED))
910 		goto out;
911 #ifdef TCP_OFFLOAD
912 	if (tp->t_flags & TF_TOE)
913 		tcp_offload_rcvd(tp);
914 	else
915 #endif
916 	tp->t_fb->tfb_tcp_output(tp);
917 
918 out:
919 	TCPDEBUG2(PRU_RCVD);
920 	TCP_PROBE2(debug__user, tp, PRU_RCVD);
921 	INP_WUNLOCK(inp);
922 	return (error);
923 }
924 
925 /*
926  * Do a send by putting data in output queue and updating urgent
927  * marker if URG set.  Possibly send more data.  Unlike the other
928  * pru_*() routines, the mbuf chains are our responsibility.  We
929  * must either enqueue them or free them.  The other pru_* routines
930  * generally are caller-frees.
931  */
932 static int
tcp_usr_send(struct socket * so,int flags,struct mbuf * m,struct sockaddr * nam,struct mbuf * control,struct thread * td)933 tcp_usr_send(struct socket *so, int flags, struct mbuf *m,
934     struct sockaddr *nam, struct mbuf *control, struct thread *td)
935 {
936 	int error = 0;
937 	struct inpcb *inp;
938 	struct tcpcb *tp = NULL;
939 	struct epoch_tracker net_et;
940 #ifdef INET
941 #ifdef INET6
942 	struct sockaddr_in sin;
943 #endif
944 	struct sockaddr_in *sinp;
945 #endif
946 #ifdef INET6
947 	int isipv6;
948 #endif
949 	u_int8_t incflagsav;
950 	u_char vflagsav;
951 	bool restoreflags;
952 	TCPDEBUG0;
953 
954 	/*
955 	 * We require the pcbinfo lock if we will close the socket as part of
956 	 * this call.
957 	 */
958 	if (flags & PRUS_EOF)
959 		INP_INFO_RLOCK_ET(&V_tcbinfo, net_et);
960 	inp = sotoinpcb(so);
961 	KASSERT(inp != NULL, ("tcp_usr_send: inp == NULL"));
962 	INP_WLOCK(inp);
963 	vflagsav = inp->inp_vflag;
964 	incflagsav = inp->inp_inc.inc_flags;
965 	restoreflags = false;
966 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
967 		if (control)
968 			m_freem(control);
969 		/*
970 		 * In case of PRUS_NOTREADY, tcp_usr_ready() is responsible
971 		 * for freeing memory.
972 		 */
973 		if (m && (flags & PRUS_NOTREADY) == 0)
974 			m_freem(m);
975 		error = ECONNRESET;
976 		goto out;
977 	}
978 	tp = intotcpcb(inp);
979 	TCPDEBUG1();
980 	if (nam != NULL && tp->t_state < TCPS_SYN_SENT) {
981 		switch (nam->sa_family) {
982 #ifdef INET
983 		case AF_INET:
984 			sinp = (struct sockaddr_in *)nam;
985 			if (sinp->sin_len != sizeof(struct sockaddr_in)) {
986 				if (m)
987 					m_freem(m);
988 				error = EINVAL;
989 				goto out;
990 			}
991 			if ((inp->inp_vflag & INP_IPV6) != 0) {
992 				if (m)
993 					m_freem(m);
994 				error = EAFNOSUPPORT;
995 				goto out;
996 			}
997 			if (IN_MULTICAST(ntohl(sinp->sin_addr.s_addr))) {
998 				if (m)
999 					m_freem(m);
1000 				error = EAFNOSUPPORT;
1001 				goto out;
1002 			}
1003 			if (ntohl(sinp->sin_addr.s_addr) == INADDR_BROADCAST) {
1004 				if (m)
1005 					m_freem(m);
1006 				error = EACCES;
1007 				goto out;
1008 			}
1009 			if ((error = prison_remote_ip4(td->td_ucred,
1010 			    &sinp->sin_addr))) {
1011 				if (m)
1012 					m_freem(m);
1013 				goto out;
1014 			}
1015 #ifdef INET6
1016 			isipv6 = 0;
1017 #endif
1018 			break;
1019 #endif /* INET */
1020 #ifdef INET6
1021 		case AF_INET6:
1022 		{
1023 			struct sockaddr_in6 *sin6;
1024 
1025 			sin6 = (struct sockaddr_in6 *)nam;
1026 			if (sin6->sin6_len != sizeof(*sin6)) {
1027 				if (m)
1028 					m_freem(m);
1029 				error = EINVAL;
1030 				goto out;
1031 			}
1032 			if ((inp->inp_vflag & INP_IPV6PROTO) == 0) {
1033 				if (m != NULL)
1034 					m_freem(m);
1035 				error = EAFNOSUPPORT;
1036 				goto out;
1037 			}
1038 			if (IN6_IS_ADDR_MULTICAST(&sin6->sin6_addr)) {
1039 				if (m)
1040 					m_freem(m);
1041 				error = EAFNOSUPPORT;
1042 				goto out;
1043 			}
1044 			if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1045 #ifdef INET
1046 				if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
1047 					error = EINVAL;
1048 					if (m)
1049 						m_freem(m);
1050 					goto out;
1051 				}
1052 				if ((inp->inp_vflag & INP_IPV4) == 0) {
1053 					error = EAFNOSUPPORT;
1054 					if (m)
1055 						m_freem(m);
1056 					goto out;
1057 				}
1058 				restoreflags = true;
1059 				inp->inp_vflag &= ~INP_IPV6;
1060 				sinp = &sin;
1061 				in6_sin6_2_sin(sinp, sin6);
1062 				if (IN_MULTICAST(
1063 				    ntohl(sinp->sin_addr.s_addr))) {
1064 					error = EAFNOSUPPORT;
1065 					if (m)
1066 						m_freem(m);
1067 					goto out;
1068 				}
1069 				if ((error = prison_remote_ip4(td->td_ucred,
1070 				    &sinp->sin_addr))) {
1071 					if (m)
1072 						m_freem(m);
1073 					goto out;
1074 				}
1075 				isipv6 = 0;
1076 #else /* !INET */
1077 				error = EAFNOSUPPORT;
1078 				if (m)
1079 					m_freem(m);
1080 				goto out;
1081 #endif /* INET */
1082 			} else {
1083 				if ((inp->inp_vflag & INP_IPV6) == 0) {
1084 					if (m)
1085 						m_freem(m);
1086 					error = EAFNOSUPPORT;
1087 					goto out;
1088 				}
1089 				restoreflags = true;
1090 				inp->inp_vflag &= ~INP_IPV4;
1091 				inp->inp_inc.inc_flags |= INC_ISIPV6;
1092 				if ((error = prison_remote_ip6(td->td_ucred,
1093 				    &sin6->sin6_addr))) {
1094 					if (m)
1095 						m_freem(m);
1096 					goto out;
1097 				}
1098 				isipv6 = 1;
1099 			}
1100 			break;
1101 		}
1102 #endif /* INET6 */
1103 		default:
1104 			if (m)
1105 				m_freem(m);
1106 			error = EAFNOSUPPORT;
1107 			goto out;
1108 		}
1109 	}
1110 	if (control) {
1111 		/* TCP doesn't do control messages (rights, creds, etc) */
1112 		if (control->m_len) {
1113 			m_freem(control);
1114 			if (m)
1115 				m_freem(m);
1116 			error = EINVAL;
1117 			goto out;
1118 		}
1119 		m_freem(control);	/* empty control, just free it */
1120 	}
1121 	if (!(flags & PRUS_OOB)) {
1122 		sbappendstream(&so->so_snd, m, flags);
1123 		if (nam && tp->t_state < TCPS_SYN_SENT) {
1124 			/*
1125 			 * Do implied connect if not yet connected,
1126 			 * initialize window to default value, and
1127 			 * initialize maxseg using peer's cached MSS.
1128 			 */
1129 #ifdef INET6
1130 			if (isipv6)
1131 				error = tcp6_connect(tp, nam, td);
1132 #endif /* INET6 */
1133 #if defined(INET6) && defined(INET)
1134 			else
1135 #endif
1136 #ifdef INET
1137 				error = tcp_connect(tp,
1138 				    (struct sockaddr *)sinp, td);
1139 #endif
1140 			/*
1141 			 * The bind operation in tcp_connect succeeded. We
1142 			 * no longer want to restore the flags if later
1143 			 * operations fail.
1144 			 */
1145 			if (error == 0 || inp->inp_lport != 0)
1146 				restoreflags = false;
1147 
1148 			if (error)
1149 				goto out;
1150 			if (IS_FASTOPEN(tp->t_flags))
1151 				tcp_fastopen_connect(tp);
1152 			else {
1153 				tp->snd_wnd = TTCP_CLIENT_SND_WND;
1154 				tcp_mss(tp, -1);
1155 			}
1156 		}
1157 		if (flags & PRUS_EOF) {
1158 			/*
1159 			 * Close the send side of the connection after
1160 			 * the data is sent.
1161 			 */
1162 			INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1163 			socantsendmore(so);
1164 			tcp_usrclosed(tp);
1165 		}
1166 		if (!(inp->inp_flags & INP_DROPPED) &&
1167 		    !(flags & PRUS_NOTREADY)) {
1168 			if (flags & PRUS_MORETOCOME)
1169 				tp->t_flags |= TF_MORETOCOME;
1170 			error = tp->t_fb->tfb_tcp_output(tp);
1171 			if (flags & PRUS_MORETOCOME)
1172 				tp->t_flags &= ~TF_MORETOCOME;
1173 		}
1174 	} else {
1175 		/*
1176 		 * XXXRW: PRUS_EOF not implemented with PRUS_OOB?
1177 		 */
1178 		SOCKBUF_LOCK(&so->so_snd);
1179 		if (sbspace(&so->so_snd) < -512) {
1180 			SOCKBUF_UNLOCK(&so->so_snd);
1181 			m_freem(m);
1182 			error = ENOBUFS;
1183 			goto out;
1184 		}
1185 		/*
1186 		 * According to RFC961 (Assigned Protocols),
1187 		 * the urgent pointer points to the last octet
1188 		 * of urgent data.  We continue, however,
1189 		 * to consider it to indicate the first octet
1190 		 * of data past the urgent section.
1191 		 * Otherwise, snd_up should be one lower.
1192 		 */
1193 		sbappendstream_locked(&so->so_snd, m, flags);
1194 		SOCKBUF_UNLOCK(&so->so_snd);
1195 		if (nam && tp->t_state < TCPS_SYN_SENT) {
1196 			/*
1197 			 * Do implied connect if not yet connected,
1198 			 * initialize window to default value, and
1199 			 * initialize maxseg using peer's cached MSS.
1200 			 */
1201 
1202 			/*
1203 			 * Not going to contemplate SYN|URG
1204 			 */
1205 			if (IS_FASTOPEN(tp->t_flags))
1206 				tp->t_flags &= ~TF_FASTOPEN;
1207 #ifdef INET6
1208 			if (isipv6)
1209 				error = tcp6_connect(tp, nam, td);
1210 #endif /* INET6 */
1211 #if defined(INET6) && defined(INET)
1212 			else
1213 #endif
1214 #ifdef INET
1215 				error = tcp_connect(tp,
1216 				    (struct sockaddr *)sinp, td);
1217 #endif
1218 			/*
1219 			 * The bind operation in tcp_connect succeeded. We
1220 			 * no longer want to restore the flags if later
1221 			 * operations fail.
1222 			 */
1223 			if (error == 0 || inp->inp_lport != 0)
1224 				restoreflags = false;
1225 
1226 			if (error)
1227 				goto out;
1228 			tp->snd_wnd = TTCP_CLIENT_SND_WND;
1229 			tcp_mss(tp, -1);
1230 		}
1231 		tp->snd_up = tp->snd_una + sbavail(&so->so_snd);
1232 		if (!(flags & PRUS_NOTREADY)) {
1233 			tp->t_flags |= TF_FORCEDATA;
1234 			error = tp->t_fb->tfb_tcp_output(tp);
1235 			tp->t_flags &= ~TF_FORCEDATA;
1236 		}
1237 	}
1238 	TCP_LOG_EVENT(tp, NULL,
1239 	    &inp->inp_socket->so_rcv,
1240 	    &inp->inp_socket->so_snd,
1241 	    TCP_LOG_USERSEND, error,
1242 	    0, NULL, false);
1243 out:
1244 	/*
1245 	 * If the request was unsuccessful and we changed flags,
1246 	 * restore the original flags.
1247 	 */
1248 	if (error != 0 && restoreflags) {
1249 		inp->inp_vflag = vflagsav;
1250 		inp->inp_inc.inc_flags = incflagsav;
1251 	}
1252 	TCPDEBUG2((flags & PRUS_OOB) ? PRU_SENDOOB :
1253 		  ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1254 	TCP_PROBE2(debug__user, tp, (flags & PRUS_OOB) ? PRU_SENDOOB :
1255 		   ((flags & PRUS_EOF) ? PRU_SEND_EOF : PRU_SEND));
1256 	INP_WUNLOCK(inp);
1257 	if (flags & PRUS_EOF)
1258 		INP_INFO_RUNLOCK_ET(&V_tcbinfo, net_et);
1259 	return (error);
1260 }
1261 
1262 static int
tcp_usr_ready(struct socket * so,struct mbuf * m,int count)1263 tcp_usr_ready(struct socket *so, struct mbuf *m, int count)
1264 {
1265 	struct inpcb *inp;
1266 	struct tcpcb *tp;
1267 	int error;
1268 
1269 	inp = sotoinpcb(so);
1270 	INP_WLOCK(inp);
1271 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1272 		INP_WUNLOCK(inp);
1273 		for (int i = 0; i < count; i++)
1274 			m = m_free(m);
1275 		return (ECONNRESET);
1276 	}
1277 	tp = intotcpcb(inp);
1278 
1279 	SOCKBUF_LOCK(&so->so_snd);
1280 	error = sbready(&so->so_snd, m, count);
1281 	SOCKBUF_UNLOCK(&so->so_snd);
1282 	if (error == 0)
1283 		error = tp->t_fb->tfb_tcp_output(tp);
1284 	INP_WUNLOCK(inp);
1285 
1286 	return (error);
1287 }
1288 
1289 /*
1290  * Abort the TCP.  Drop the connection abruptly.
1291  */
1292 static void
tcp_usr_abort(struct socket * so)1293 tcp_usr_abort(struct socket *so)
1294 {
1295 	struct inpcb *inp;
1296 	struct tcpcb *tp = NULL;
1297 	struct epoch_tracker et;
1298 	TCPDEBUG0;
1299 
1300 	inp = sotoinpcb(so);
1301 	KASSERT(inp != NULL, ("tcp_usr_abort: inp == NULL"));
1302 
1303 	INP_INFO_RLOCK_ET(&V_tcbinfo, et);
1304 	INP_WLOCK(inp);
1305 	KASSERT(inp->inp_socket != NULL,
1306 	    ("tcp_usr_abort: inp_socket == NULL"));
1307 
1308 	/*
1309 	 * If we still have full TCP state, and we're not dropped, drop.
1310 	 */
1311 	if (!(inp->inp_flags & INP_TIMEWAIT) &&
1312 	    !(inp->inp_flags & INP_DROPPED)) {
1313 		tp = intotcpcb(inp);
1314 		TCPDEBUG1();
1315 		tp = tcp_drop(tp, ECONNABORTED);
1316 		if (tp == NULL)
1317 			goto dropped;
1318 		TCPDEBUG2(PRU_ABORT);
1319 		TCP_PROBE2(debug__user, tp, PRU_ABORT);
1320 	}
1321 	if (!(inp->inp_flags & INP_DROPPED)) {
1322 		SOCK_LOCK(so);
1323 		so->so_state |= SS_PROTOREF;
1324 		SOCK_UNLOCK(so);
1325 		inp->inp_flags |= INP_SOCKREF;
1326 	}
1327 	INP_WUNLOCK(inp);
1328 dropped:
1329 	INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1330 }
1331 
1332 /*
1333  * TCP socket is closed.  Start friendly disconnect.
1334  */
1335 static void
tcp_usr_close(struct socket * so)1336 tcp_usr_close(struct socket *so)
1337 {
1338 	struct inpcb *inp;
1339 	struct tcpcb *tp = NULL;
1340 	struct epoch_tracker et;
1341 	TCPDEBUG0;
1342 
1343 	inp = sotoinpcb(so);
1344 	KASSERT(inp != NULL, ("tcp_usr_close: inp == NULL"));
1345 
1346 	INP_INFO_RLOCK_ET(&V_tcbinfo, et);
1347 	INP_WLOCK(inp);
1348 	KASSERT(inp->inp_socket != NULL,
1349 	    ("tcp_usr_close: inp_socket == NULL"));
1350 
1351 	/*
1352 	 * If we still have full TCP state, and we're not dropped, initiate
1353 	 * a disconnect.
1354 	 */
1355 	if (!(inp->inp_flags & INP_TIMEWAIT) &&
1356 	    !(inp->inp_flags & INP_DROPPED)) {
1357 		tp = intotcpcb(inp);
1358 		TCPDEBUG1();
1359 		tcp_disconnect(tp);
1360 		TCPDEBUG2(PRU_CLOSE);
1361 		TCP_PROBE2(debug__user, tp, PRU_CLOSE);
1362 	}
1363 	if (!(inp->inp_flags & INP_DROPPED)) {
1364 		SOCK_LOCK(so);
1365 		so->so_state |= SS_PROTOREF;
1366 		SOCK_UNLOCK(so);
1367 		inp->inp_flags |= INP_SOCKREF;
1368 	}
1369 	INP_WUNLOCK(inp);
1370 	INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
1371 }
1372 
1373 /*
1374  * Receive out-of-band data.
1375  */
1376 static int
tcp_usr_rcvoob(struct socket * so,struct mbuf * m,int flags)1377 tcp_usr_rcvoob(struct socket *so, struct mbuf *m, int flags)
1378 {
1379 	int error = 0;
1380 	struct inpcb *inp;
1381 	struct tcpcb *tp = NULL;
1382 
1383 	TCPDEBUG0;
1384 	inp = sotoinpcb(so);
1385 	KASSERT(inp != NULL, ("tcp_usr_rcvoob: inp == NULL"));
1386 	INP_WLOCK(inp);
1387 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1388 		error = ECONNRESET;
1389 		goto out;
1390 	}
1391 	tp = intotcpcb(inp);
1392 	TCPDEBUG1();
1393 	if ((so->so_oobmark == 0 &&
1394 	     (so->so_rcv.sb_state & SBS_RCVATMARK) == 0) ||
1395 	    so->so_options & SO_OOBINLINE ||
1396 	    tp->t_oobflags & TCPOOB_HADDATA) {
1397 		error = EINVAL;
1398 		goto out;
1399 	}
1400 	if ((tp->t_oobflags & TCPOOB_HAVEDATA) == 0) {
1401 		error = EWOULDBLOCK;
1402 		goto out;
1403 	}
1404 	m->m_len = 1;
1405 	*mtod(m, caddr_t) = tp->t_iobc;
1406 	if ((flags & MSG_PEEK) == 0)
1407 		tp->t_oobflags ^= (TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1408 
1409 out:
1410 	TCPDEBUG2(PRU_RCVOOB);
1411 	TCP_PROBE2(debug__user, tp, PRU_RCVOOB);
1412 	INP_WUNLOCK(inp);
1413 	return (error);
1414 }
1415 
1416 #ifdef INET
1417 struct pr_usrreqs tcp_usrreqs = {
1418 	.pru_abort =		tcp_usr_abort,
1419 	.pru_accept =		tcp_usr_accept,
1420 	.pru_attach =		tcp_usr_attach,
1421 	.pru_bind =		tcp_usr_bind,
1422 	.pru_connect =		tcp_usr_connect,
1423 	.pru_control =		in_control,
1424 	.pru_detach =		tcp_usr_detach,
1425 	.pru_disconnect =	tcp_usr_disconnect,
1426 	.pru_listen =		tcp_usr_listen,
1427 	.pru_peeraddr =		in_getpeeraddr,
1428 	.pru_rcvd =		tcp_usr_rcvd,
1429 	.pru_rcvoob =		tcp_usr_rcvoob,
1430 	.pru_send =		tcp_usr_send,
1431 	.pru_ready =		tcp_usr_ready,
1432 	.pru_shutdown =		tcp_usr_shutdown,
1433 	.pru_sockaddr =		in_getsockaddr,
1434 	.pru_sosetlabel =	in_pcbsosetlabel,
1435 	.pru_close =		tcp_usr_close,
1436 };
1437 #endif /* INET */
1438 
1439 #ifdef INET6
1440 struct pr_usrreqs tcp6_usrreqs = {
1441 	.pru_abort =		tcp_usr_abort,
1442 	.pru_accept =		tcp6_usr_accept,
1443 	.pru_attach =		tcp_usr_attach,
1444 	.pru_bind =		tcp6_usr_bind,
1445 	.pru_connect =		tcp6_usr_connect,
1446 	.pru_control =		in6_control,
1447 	.pru_detach =		tcp_usr_detach,
1448 	.pru_disconnect =	tcp_usr_disconnect,
1449 	.pru_listen =		tcp6_usr_listen,
1450 	.pru_peeraddr =		in6_mapped_peeraddr,
1451 	.pru_rcvd =		tcp_usr_rcvd,
1452 	.pru_rcvoob =		tcp_usr_rcvoob,
1453 	.pru_send =		tcp_usr_send,
1454 	.pru_ready =		tcp_usr_ready,
1455 	.pru_shutdown =		tcp_usr_shutdown,
1456 	.pru_sockaddr =		in6_mapped_sockaddr,
1457 	.pru_sosetlabel =	in_pcbsosetlabel,
1458 	.pru_close =		tcp_usr_close,
1459 };
1460 #endif /* INET6 */
1461 
1462 #ifdef INET
1463 /*
1464  * Common subroutine to open a TCP connection to remote host specified
1465  * by struct sockaddr_in in mbuf *nam.  Call in_pcbbind to assign a local
1466  * port number if needed.  Call in_pcbconnect_setup to do the routing and
1467  * to choose a local host address (interface).  If there is an existing
1468  * incarnation of the same connection in TIME-WAIT state and if the remote
1469  * host was sending CC options and if the connection duration was < MSL, then
1470  * truncate the previous TIME-WAIT state and proceed.
1471  * Initialize connection parameters and enter SYN-SENT state.
1472  */
1473 static int
tcp_connect(struct tcpcb * tp,struct sockaddr * nam,struct thread * td)1474 tcp_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1475 {
1476 	struct inpcb *inp = tp->t_inpcb, *oinp;
1477 	struct socket *so = inp->inp_socket;
1478 	struct in_addr laddr;
1479 	u_short lport;
1480 	int error;
1481 
1482 	INP_WLOCK_ASSERT(inp);
1483 	INP_HASH_WLOCK(&V_tcbinfo);
1484 
1485 	if (V_tcp_require_unique_port && inp->inp_lport == 0) {
1486 		error = in_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1487 		if (error)
1488 			goto out;
1489 	}
1490 
1491 	/*
1492 	 * Cannot simply call in_pcbconnect, because there might be an
1493 	 * earlier incarnation of this same connection still in
1494 	 * TIME_WAIT state, creating an ADDRINUSE error.
1495 	 */
1496 	laddr = inp->inp_laddr;
1497 	lport = inp->inp_lport;
1498 	error = in_pcbconnect_setup(inp, nam, &laddr.s_addr, &lport,
1499 	    &inp->inp_faddr.s_addr, &inp->inp_fport, &oinp, td->td_ucred);
1500 	if (error && oinp == NULL)
1501 		goto out;
1502 	if (oinp) {
1503 		error = EADDRINUSE;
1504 		goto out;
1505 	}
1506 	/* Handle initial bind if it hadn't been done in advance. */
1507 	if (inp->inp_lport == 0) {
1508 		inp->inp_lport = lport;
1509 		if (in_pcbinshash(inp) != 0) {
1510 			inp->inp_lport = 0;
1511 			error = EAGAIN;
1512 			goto out;
1513 		}
1514 	}
1515 	inp->inp_laddr = laddr;
1516 	in_pcbrehash(inp);
1517 	INP_HASH_WUNLOCK(&V_tcbinfo);
1518 
1519 	/*
1520 	 * Compute window scaling to request:
1521 	 * Scale to fit into sweet spot.  See tcp_syncache.c.
1522 	 * XXX: This should move to tcp_output().
1523 	 */
1524 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1525 	    (TCP_MAXWIN << tp->request_r_scale) < sb_max)
1526 		tp->request_r_scale++;
1527 
1528 	soisconnecting(so);
1529 	TCPSTAT_INC(tcps_connattempt);
1530 	tcp_state_change(tp, TCPS_SYN_SENT);
1531 	tp->iss = tcp_new_isn(&inp->inp_inc);
1532 	if (tp->t_flags & TF_REQ_TSTMP)
1533 		tp->ts_offset = tcp_new_ts_offset(&inp->inp_inc);
1534 	tcp_sendseqinit(tp);
1535 
1536 	return 0;
1537 
1538 out:
1539 	INP_HASH_WUNLOCK(&V_tcbinfo);
1540 	return (error);
1541 }
1542 #endif /* INET */
1543 
1544 #ifdef INET6
1545 static int
tcp6_connect(struct tcpcb * tp,struct sockaddr * nam,struct thread * td)1546 tcp6_connect(struct tcpcb *tp, struct sockaddr *nam, struct thread *td)
1547 {
1548 	struct inpcb *inp = tp->t_inpcb;
1549 	int error;
1550 
1551 	INP_WLOCK_ASSERT(inp);
1552 	INP_HASH_WLOCK(&V_tcbinfo);
1553 
1554 	if (V_tcp_require_unique_port && inp->inp_lport == 0) {
1555 		error = in6_pcbbind(inp, (struct sockaddr *)0, td->td_ucred);
1556 		if (error)
1557 			goto out;
1558 	}
1559 	error = in6_pcbconnect(inp, nam, td->td_ucred);
1560 	if (error != 0)
1561 		goto out;
1562 	INP_HASH_WUNLOCK(&V_tcbinfo);
1563 
1564 	/* Compute window scaling to request.  */
1565 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1566 	    (TCP_MAXWIN << tp->request_r_scale) < sb_max)
1567 		tp->request_r_scale++;
1568 
1569 	soisconnecting(inp->inp_socket);
1570 	TCPSTAT_INC(tcps_connattempt);
1571 	tcp_state_change(tp, TCPS_SYN_SENT);
1572 	tp->iss = tcp_new_isn(&inp->inp_inc);
1573 	if (tp->t_flags & TF_REQ_TSTMP)
1574 		tp->ts_offset = tcp_new_ts_offset(&inp->inp_inc);
1575 	tcp_sendseqinit(tp);
1576 
1577 	return 0;
1578 
1579 out:
1580 	INP_HASH_WUNLOCK(&V_tcbinfo);
1581 	return error;
1582 }
1583 #endif /* INET6 */
1584 
1585 /*
1586  * Export TCP internal state information via a struct tcp_info, based on the
1587  * Linux 2.6 API.  Not ABI compatible as our constants are mapped differently
1588  * (TCP state machine, etc).  We export all information using FreeBSD-native
1589  * constants -- for example, the numeric values for tcpi_state will differ
1590  * from Linux.
1591  */
1592 static void
tcp_fill_info(struct tcpcb * tp,struct tcp_info * ti)1593 tcp_fill_info(struct tcpcb *tp, struct tcp_info *ti)
1594 {
1595 
1596 	INP_WLOCK_ASSERT(tp->t_inpcb);
1597 	bzero(ti, sizeof(*ti));
1598 
1599 	ti->tcpi_state = tp->t_state;
1600 	if ((tp->t_flags & TF_REQ_TSTMP) && (tp->t_flags & TF_RCVD_TSTMP))
1601 		ti->tcpi_options |= TCPI_OPT_TIMESTAMPS;
1602 	if (tp->t_flags & TF_SACK_PERMIT)
1603 		ti->tcpi_options |= TCPI_OPT_SACK;
1604 	if ((tp->t_flags & TF_REQ_SCALE) && (tp->t_flags & TF_RCVD_SCALE)) {
1605 		ti->tcpi_options |= TCPI_OPT_WSCALE;
1606 		ti->tcpi_snd_wscale = tp->snd_scale;
1607 		ti->tcpi_rcv_wscale = tp->rcv_scale;
1608 	}
1609 	if (tp->t_flags & TF_ECN_PERMIT)
1610 		ti->tcpi_options |= TCPI_OPT_ECN;
1611 
1612 	ti->tcpi_rto = tp->t_rxtcur * tick;
1613 	ti->tcpi_last_data_recv = ((uint32_t)ticks - tp->t_rcvtime) * tick;
1614 	ti->tcpi_rtt = ((u_int64_t)tp->t_srtt * tick) >> TCP_RTT_SHIFT;
1615 	ti->tcpi_rttvar = ((u_int64_t)tp->t_rttvar * tick) >> TCP_RTTVAR_SHIFT;
1616 
1617 	ti->tcpi_snd_ssthresh = tp->snd_ssthresh;
1618 	ti->tcpi_snd_cwnd = tp->snd_cwnd;
1619 
1620 	/*
1621 	 * FreeBSD-specific extension fields for tcp_info.
1622 	 */
1623 	ti->tcpi_rcv_space = tp->rcv_wnd;
1624 	ti->tcpi_rcv_nxt = tp->rcv_nxt;
1625 	ti->tcpi_snd_wnd = tp->snd_wnd;
1626 	ti->tcpi_snd_bwnd = 0;		/* Unused, kept for compat. */
1627 	ti->tcpi_snd_nxt = tp->snd_nxt;
1628 	ti->tcpi_snd_mss = tp->t_maxseg;
1629 	ti->tcpi_rcv_mss = tp->t_maxseg;
1630 	ti->tcpi_snd_rexmitpack = tp->t_sndrexmitpack;
1631 	ti->tcpi_rcv_ooopack = tp->t_rcvoopack;
1632 	ti->tcpi_snd_zerowin = tp->t_sndzerowin;
1633 #ifdef TCP_OFFLOAD
1634 	if (tp->t_flags & TF_TOE) {
1635 		ti->tcpi_options |= TCPI_OPT_TOE;
1636 		tcp_offload_tcp_info(tp, ti);
1637 	}
1638 #endif
1639 }
1640 
1641 /*
1642  * tcp_ctloutput() must drop the inpcb lock before performing copyin on
1643  * socket option arguments.  When it re-acquires the lock after the copy, it
1644  * has to revalidate that the connection is still valid for the socket
1645  * option.
1646  */
1647 #define INP_WLOCK_RECHECK_CLEANUP(inp, cleanup) do {			\
1648 	INP_WLOCK(inp);							\
1649 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {		\
1650 		INP_WUNLOCK(inp);					\
1651 		cleanup;						\
1652 		return (ECONNRESET);					\
1653 	}								\
1654 	tp = intotcpcb(inp);						\
1655 } while(0)
1656 #define INP_WLOCK_RECHECK(inp) INP_WLOCK_RECHECK_CLEANUP((inp), /* noop */)
1657 
1658 int
tcp_ctloutput(struct socket * so,struct sockopt * sopt)1659 tcp_ctloutput(struct socket *so, struct sockopt *sopt)
1660 {
1661 	int	error;
1662 	struct	inpcb *inp;
1663 	struct	tcpcb *tp;
1664 	struct tcp_function_block *blk;
1665 	struct tcp_function_set fsn;
1666 
1667 	error = 0;
1668 	inp = sotoinpcb(so);
1669 	KASSERT(inp != NULL, ("tcp_ctloutput: inp == NULL"));
1670 	if (sopt->sopt_level != IPPROTO_TCP) {
1671 #ifdef INET6
1672 		if (inp->inp_vflag & INP_IPV6PROTO) {
1673 			error = ip6_ctloutput(so, sopt);
1674 			/*
1675 			 * In case of the IPV6_USE_MIN_MTU socket option,
1676 			 * the INC_IPV6MINMTU flag to announce a corresponding
1677 			 * MSS during the initial handshake.
1678 			 * If the TCP connection is not in the front states,
1679 			 * just reduce the MSS being used.
1680 			 * This avoids the sending of TCP segments which will
1681 			 * be fragmented at the IPv6 layer.
1682 			 */
1683 			if ((error == 0) &&
1684 			    (sopt->sopt_dir == SOPT_SET) &&
1685 			    (sopt->sopt_level == IPPROTO_IPV6) &&
1686 			    (sopt->sopt_name == IPV6_USE_MIN_MTU)) {
1687 				INP_WLOCK(inp);
1688 				if ((inp->inp_flags &
1689 				    (INP_TIMEWAIT | INP_DROPPED))) {
1690 					INP_WUNLOCK(inp);
1691 					return (ECONNRESET);
1692 				}
1693 				inp->inp_inc.inc_flags |= INC_IPV6MINMTU;
1694 				tp = intotcpcb(inp);
1695 				if ((tp->t_state >= TCPS_SYN_SENT) &&
1696 				    (inp->inp_inc.inc_flags & INC_ISIPV6)) {
1697 					struct ip6_pktopts *opt;
1698 
1699 					opt = inp->in6p_outputopts;
1700 					if ((opt != NULL) &&
1701 					    (opt->ip6po_minmtu ==
1702 					    IP6PO_MINMTU_ALL)) {
1703 						if (tp->t_maxseg > TCP6_MSS) {
1704 							tp->t_maxseg = TCP6_MSS;
1705 						}
1706 					}
1707 				}
1708 				INP_WUNLOCK(inp);
1709 			}
1710 		}
1711 #endif /* INET6 */
1712 #if defined(INET6) && defined(INET)
1713 		else
1714 #endif
1715 #ifdef INET
1716 		{
1717 			error = ip_ctloutput(so, sopt);
1718 		}
1719 #endif
1720 		return (error);
1721 	}
1722 	INP_WLOCK(inp);
1723 	if (inp->inp_flags & (INP_TIMEWAIT | INP_DROPPED)) {
1724 		INP_WUNLOCK(inp);
1725 		return (ECONNRESET);
1726 	}
1727 	tp = intotcpcb(inp);
1728 	/*
1729 	 * Protect the TCP option TCP_FUNCTION_BLK so
1730 	 * that a sub-function can *never* overwrite this.
1731 	 */
1732 	if ((sopt->sopt_dir == SOPT_SET) &&
1733 	    (sopt->sopt_name == TCP_FUNCTION_BLK)) {
1734 		INP_WUNLOCK(inp);
1735 		error = sooptcopyin(sopt, &fsn, sizeof fsn,
1736 		    sizeof fsn);
1737 		if (error)
1738 			return (error);
1739 		INP_WLOCK_RECHECK(inp);
1740 		blk = find_and_ref_tcp_functions(&fsn);
1741 		if (blk == NULL) {
1742 			INP_WUNLOCK(inp);
1743 			return (ENOENT);
1744 		}
1745 		if (tp->t_fb == blk) {
1746 			/* You already have this */
1747 			refcount_release(&blk->tfb_refcnt);
1748 			INP_WUNLOCK(inp);
1749 			return (0);
1750 		}
1751 		if (tp->t_state != TCPS_CLOSED) {
1752 			/*
1753 			 * The user has advanced the state
1754 			 * past the initial point, we may not
1755 			 * be able to switch.
1756 			 */
1757 			if (blk->tfb_tcp_handoff_ok != NULL) {
1758 				/*
1759 				 * Does the stack provide a
1760 				 * query mechanism, if so it may
1761 				 * still be possible?
1762 				 */
1763 				error = (*blk->tfb_tcp_handoff_ok)(tp);
1764 			} else
1765 				error = EINVAL;
1766 			if (error) {
1767 				refcount_release(&blk->tfb_refcnt);
1768 				INP_WUNLOCK(inp);
1769 				return(error);
1770 			}
1771 		}
1772 		if (blk->tfb_flags & TCP_FUNC_BEING_REMOVED) {
1773 			refcount_release(&blk->tfb_refcnt);
1774 			INP_WUNLOCK(inp);
1775 			return (ENOENT);
1776 		}
1777 		/*
1778 		 * Release the old refcnt, the
1779 		 * lookup acquired a ref on the
1780 		 * new one already.
1781 		 */
1782 		if (tp->t_fb->tfb_tcp_fb_fini) {
1783 			/*
1784 			 * Tell the stack to cleanup with 0 i.e.
1785 			 * the tcb is not going away.
1786 			 */
1787 			(*tp->t_fb->tfb_tcp_fb_fini)(tp, 0);
1788 		}
1789 #ifdef TCPHPTS
1790 		/* Assure that we are not on any hpts */
1791 		tcp_hpts_remove(tp->t_inpcb, HPTS_REMOVE_ALL);
1792 #endif
1793 		if (blk->tfb_tcp_fb_init) {
1794 			error = (*blk->tfb_tcp_fb_init)(tp);
1795 			if (error) {
1796 				refcount_release(&blk->tfb_refcnt);
1797 				if (tp->t_fb->tfb_tcp_fb_init) {
1798 					if((*tp->t_fb->tfb_tcp_fb_init)(tp) != 0)  {
1799 						/* Fall back failed, drop the connection */
1800 						INP_WUNLOCK(inp);
1801 						soabort(so);
1802 						return(error);
1803 					}
1804 				}
1805 				goto err_out;
1806 			}
1807 		}
1808 		refcount_release(&tp->t_fb->tfb_refcnt);
1809 		tp->t_fb = blk;
1810 #ifdef TCP_OFFLOAD
1811 		if (tp->t_flags & TF_TOE) {
1812 			tcp_offload_ctloutput(tp, sopt->sopt_dir,
1813 			     sopt->sopt_name);
1814 		}
1815 #endif
1816 err_out:
1817 		INP_WUNLOCK(inp);
1818 		return (error);
1819 	} else if ((sopt->sopt_dir == SOPT_GET) &&
1820 	    (sopt->sopt_name == TCP_FUNCTION_BLK)) {
1821 		strncpy(fsn.function_set_name, tp->t_fb->tfb_tcp_block_name,
1822 		    TCP_FUNCTION_NAME_LEN_MAX);
1823 		fsn.function_set_name[TCP_FUNCTION_NAME_LEN_MAX - 1] = '\0';
1824 		fsn.pcbcnt = tp->t_fb->tfb_refcnt;
1825 		INP_WUNLOCK(inp);
1826 		error = sooptcopyout(sopt, &fsn, sizeof fsn);
1827 		return (error);
1828 	}
1829 	/* Pass in the INP locked, called must unlock it */
1830 	return (tp->t_fb->tfb_tcp_ctloutput(so, sopt, inp, tp));
1831 }
1832 
1833 /*
1834  * If this assert becomes untrue, we need to change the size of the buf
1835  * variable in tcp_default_ctloutput().
1836  */
1837 #ifdef CTASSERT
1838 CTASSERT(TCP_CA_NAME_MAX <= TCP_LOG_ID_LEN);
1839 CTASSERT(TCP_LOG_REASON_LEN <= TCP_LOG_ID_LEN);
1840 #endif
1841 
1842 int
tcp_default_ctloutput(struct socket * so,struct sockopt * sopt,struct inpcb * inp,struct tcpcb * tp)1843 tcp_default_ctloutput(struct socket *so, struct sockopt *sopt, struct inpcb *inp, struct tcpcb *tp)
1844 {
1845 	int	error, opt, optval;
1846 	u_int	ui;
1847 	struct	tcp_info ti;
1848 	struct cc_algo *algo;
1849 	char	*pbuf, buf[TCP_LOG_ID_LEN];
1850 	size_t	len;
1851 
1852 	/*
1853 	 * For TCP_CCALGOOPT forward the control to CC module, for both
1854 	 * SOPT_SET and SOPT_GET.
1855 	 */
1856 	switch (sopt->sopt_name) {
1857 	case TCP_CCALGOOPT:
1858 		INP_WUNLOCK(inp);
1859 		if (sopt->sopt_valsize > CC_ALGOOPT_LIMIT)
1860 			return (EINVAL);
1861 		pbuf = malloc(sopt->sopt_valsize, M_TEMP, M_WAITOK | M_ZERO);
1862 		error = sooptcopyin(sopt, pbuf, sopt->sopt_valsize,
1863 		    sopt->sopt_valsize);
1864 		if (error) {
1865 			free(pbuf, M_TEMP);
1866 			return (error);
1867 		}
1868 		INP_WLOCK_RECHECK_CLEANUP(inp, free(pbuf, M_TEMP));
1869 		if (CC_ALGO(tp)->ctl_output != NULL)
1870 			error = CC_ALGO(tp)->ctl_output(tp->ccv, sopt, pbuf);
1871 		else
1872 			error = ENOENT;
1873 		INP_WUNLOCK(inp);
1874 		if (error == 0 && sopt->sopt_dir == SOPT_GET)
1875 			error = sooptcopyout(sopt, pbuf, sopt->sopt_valsize);
1876 		free(pbuf, M_TEMP);
1877 		return (error);
1878 	}
1879 
1880 	switch (sopt->sopt_dir) {
1881 	case SOPT_SET:
1882 		switch (sopt->sopt_name) {
1883 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
1884 		case TCP_MD5SIG:
1885 			if (!TCPMD5_ENABLED()) {
1886 				INP_WUNLOCK(inp);
1887 				return (ENOPROTOOPT);
1888 			}
1889 			error = TCPMD5_PCBCTL(inp, sopt);
1890 			if (error)
1891 				return (error);
1892 			goto unlock_and_done;
1893 #endif /* IPSEC */
1894 
1895 		case TCP_NODELAY:
1896 		case TCP_NOOPT:
1897 			INP_WUNLOCK(inp);
1898 			error = sooptcopyin(sopt, &optval, sizeof optval,
1899 			    sizeof optval);
1900 			if (error)
1901 				return (error);
1902 
1903 			INP_WLOCK_RECHECK(inp);
1904 			switch (sopt->sopt_name) {
1905 			case TCP_NODELAY:
1906 				opt = TF_NODELAY;
1907 				break;
1908 			case TCP_NOOPT:
1909 				opt = TF_NOOPT;
1910 				break;
1911 			default:
1912 				opt = 0; /* dead code to fool gcc */
1913 				break;
1914 			}
1915 
1916 			if (optval)
1917 				tp->t_flags |= opt;
1918 			else
1919 				tp->t_flags &= ~opt;
1920 unlock_and_done:
1921 #ifdef TCP_OFFLOAD
1922 			if (tp->t_flags & TF_TOE) {
1923 				tcp_offload_ctloutput(tp, sopt->sopt_dir,
1924 				    sopt->sopt_name);
1925 			}
1926 #endif
1927 			INP_WUNLOCK(inp);
1928 			break;
1929 
1930 		case TCP_NOPUSH:
1931 			INP_WUNLOCK(inp);
1932 			error = sooptcopyin(sopt, &optval, sizeof optval,
1933 			    sizeof optval);
1934 			if (error)
1935 				return (error);
1936 
1937 			INP_WLOCK_RECHECK(inp);
1938 			if (optval)
1939 				tp->t_flags |= TF_NOPUSH;
1940 			else if (tp->t_flags & TF_NOPUSH) {
1941 				tp->t_flags &= ~TF_NOPUSH;
1942 				if (TCPS_HAVEESTABLISHED(tp->t_state))
1943 					error = tp->t_fb->tfb_tcp_output(tp);
1944 			}
1945 			goto unlock_and_done;
1946 
1947 		case TCP_MAXSEG:
1948 			INP_WUNLOCK(inp);
1949 			error = sooptcopyin(sopt, &optval, sizeof optval,
1950 			    sizeof optval);
1951 			if (error)
1952 				return (error);
1953 
1954 			INP_WLOCK_RECHECK(inp);
1955 			if (optval > 0 && optval <= tp->t_maxseg &&
1956 			    optval + 40 >= V_tcp_minmss)
1957 				tp->t_maxseg = optval;
1958 			else
1959 				error = EINVAL;
1960 			goto unlock_and_done;
1961 
1962 		case TCP_INFO:
1963 			INP_WUNLOCK(inp);
1964 			error = EINVAL;
1965 			break;
1966 
1967 		case TCP_CONGESTION:
1968 			INP_WUNLOCK(inp);
1969 			error = sooptcopyin(sopt, buf, TCP_CA_NAME_MAX - 1, 1);
1970 			if (error)
1971 				break;
1972 			buf[sopt->sopt_valsize] = '\0';
1973 			INP_WLOCK_RECHECK(inp);
1974 			CC_LIST_RLOCK();
1975 			STAILQ_FOREACH(algo, &cc_list, entries)
1976 				if (strncmp(buf, algo->name,
1977 				    TCP_CA_NAME_MAX) == 0)
1978 					break;
1979 			CC_LIST_RUNLOCK();
1980 			if (algo == NULL) {
1981 				INP_WUNLOCK(inp);
1982 				error = EINVAL;
1983 				break;
1984 			}
1985 			/*
1986 			 * We hold a write lock over the tcb so it's safe to
1987 			 * do these things without ordering concerns.
1988 			 */
1989 			if (CC_ALGO(tp)->cb_destroy != NULL)
1990 				CC_ALGO(tp)->cb_destroy(tp->ccv);
1991 			CC_DATA(tp) = NULL;
1992 			CC_ALGO(tp) = algo;
1993 			/*
1994 			 * If something goes pear shaped initialising the new
1995 			 * algo, fall back to newreno (which does not
1996 			 * require initialisation).
1997 			 */
1998 			if (algo->cb_init != NULL &&
1999 			    algo->cb_init(tp->ccv) != 0) {
2000 				CC_ALGO(tp) = &newreno_cc_algo;
2001 				/*
2002 				 * The only reason init should fail is
2003 				 * because of malloc.
2004 				 */
2005 				error = ENOMEM;
2006 			}
2007 			INP_WUNLOCK(inp);
2008 			break;
2009 
2010 		case TCP_KEEPIDLE:
2011 		case TCP_KEEPINTVL:
2012 		case TCP_KEEPINIT:
2013 			INP_WUNLOCK(inp);
2014 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2015 			if (error)
2016 				return (error);
2017 
2018 			if (ui > (UINT_MAX / hz)) {
2019 				error = EINVAL;
2020 				break;
2021 			}
2022 			ui *= hz;
2023 
2024 			INP_WLOCK_RECHECK(inp);
2025 			switch (sopt->sopt_name) {
2026 			case TCP_KEEPIDLE:
2027 				tp->t_keepidle = ui;
2028 				/*
2029 				 * XXX: better check current remaining
2030 				 * timeout and "merge" it with new value.
2031 				 */
2032 				if ((tp->t_state > TCPS_LISTEN) &&
2033 				    (tp->t_state <= TCPS_CLOSING))
2034 					tcp_timer_activate(tp, TT_KEEP,
2035 					    TP_KEEPIDLE(tp));
2036 				break;
2037 			case TCP_KEEPINTVL:
2038 				tp->t_keepintvl = ui;
2039 				if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2040 				    (TP_MAXIDLE(tp) > 0))
2041 					tcp_timer_activate(tp, TT_2MSL,
2042 					    TP_MAXIDLE(tp));
2043 				break;
2044 			case TCP_KEEPINIT:
2045 				tp->t_keepinit = ui;
2046 				if (tp->t_state == TCPS_SYN_RECEIVED ||
2047 				    tp->t_state == TCPS_SYN_SENT)
2048 					tcp_timer_activate(tp, TT_KEEP,
2049 					    TP_KEEPINIT(tp));
2050 				break;
2051 			}
2052 			goto unlock_and_done;
2053 
2054 		case TCP_KEEPCNT:
2055 			INP_WUNLOCK(inp);
2056 			error = sooptcopyin(sopt, &ui, sizeof(ui), sizeof(ui));
2057 			if (error)
2058 				return (error);
2059 
2060 			INP_WLOCK_RECHECK(inp);
2061 			tp->t_keepcnt = ui;
2062 			if ((tp->t_state == TCPS_FIN_WAIT_2) &&
2063 			    (TP_MAXIDLE(tp) > 0))
2064 				tcp_timer_activate(tp, TT_2MSL,
2065 				    TP_MAXIDLE(tp));
2066 			goto unlock_and_done;
2067 
2068 #ifdef TCPPCAP
2069 		case TCP_PCAP_OUT:
2070 		case TCP_PCAP_IN:
2071 			INP_WUNLOCK(inp);
2072 			error = sooptcopyin(sopt, &optval, sizeof optval,
2073 			    sizeof optval);
2074 			if (error)
2075 				return (error);
2076 
2077 			INP_WLOCK_RECHECK(inp);
2078 			if (optval >= 0)
2079 				tcp_pcap_set_sock_max(
2080 					(sopt->sopt_name == TCP_PCAP_OUT) ?
2081 					&(tp->t_outpkts) : &(tp->t_inpkts),
2082 					optval);
2083 			else
2084 				error = EINVAL;
2085 			goto unlock_and_done;
2086 #endif
2087 
2088 		case TCP_FASTOPEN: {
2089 			struct tcp_fastopen tfo_optval;
2090 
2091 			INP_WUNLOCK(inp);
2092 			if (!V_tcp_fastopen_client_enable &&
2093 			    !V_tcp_fastopen_server_enable)
2094 				return (EPERM);
2095 
2096 			error = sooptcopyin(sopt, &tfo_optval,
2097 				    sizeof(tfo_optval), sizeof(int));
2098 			if (error)
2099 				return (error);
2100 
2101 			INP_WLOCK_RECHECK(inp);
2102 			if ((tp->t_state != TCPS_CLOSED) &&
2103 			    (tp->t_state != TCPS_LISTEN)) {
2104 				error = EINVAL;
2105 				goto unlock_and_done;
2106 			}
2107 			if (tfo_optval.enable) {
2108 				if (tp->t_state == TCPS_LISTEN) {
2109 					if (!V_tcp_fastopen_server_enable) {
2110 						error = EPERM;
2111 						goto unlock_and_done;
2112 					}
2113 
2114 					if (tp->t_tfo_pending == NULL)
2115 						tp->t_tfo_pending =
2116 						    tcp_fastopen_alloc_counter();
2117 				} else {
2118 					/*
2119 					 * If a pre-shared key was provided,
2120 					 * stash it in the client cookie
2121 					 * field of the tcpcb for use during
2122 					 * connect.
2123 					 */
2124 					if (sopt->sopt_valsize ==
2125 					    sizeof(tfo_optval)) {
2126 						memcpy(tp->t_tfo_cookie.client,
2127 						       tfo_optval.psk,
2128 						       TCP_FASTOPEN_PSK_LEN);
2129 						tp->t_tfo_client_cookie_len =
2130 						    TCP_FASTOPEN_PSK_LEN;
2131 					}
2132 				}
2133 				tp->t_flags |= TF_FASTOPEN;
2134 			} else
2135 				tp->t_flags &= ~TF_FASTOPEN;
2136 			goto unlock_and_done;
2137 		}
2138 
2139 #ifdef TCP_BLACKBOX
2140 		case TCP_LOG:
2141 			INP_WUNLOCK(inp);
2142 			error = sooptcopyin(sopt, &optval, sizeof optval,
2143 			    sizeof optval);
2144 			if (error)
2145 				return (error);
2146 
2147 			INP_WLOCK_RECHECK(inp);
2148 			error = tcp_log_state_change(tp, optval);
2149 			goto unlock_and_done;
2150 
2151 		case TCP_LOGBUF:
2152 			INP_WUNLOCK(inp);
2153 			error = EINVAL;
2154 			break;
2155 
2156 		case TCP_LOGID:
2157 			INP_WUNLOCK(inp);
2158 			error = sooptcopyin(sopt, buf, TCP_LOG_ID_LEN - 1, 0);
2159 			if (error)
2160 				break;
2161 			buf[sopt->sopt_valsize] = '\0';
2162 			INP_WLOCK_RECHECK(inp);
2163 			error = tcp_log_set_id(tp, buf);
2164 			/* tcp_log_set_id() unlocks the INP. */
2165 			break;
2166 
2167 		case TCP_LOGDUMP:
2168 		case TCP_LOGDUMPID:
2169 			INP_WUNLOCK(inp);
2170 			error =
2171 			    sooptcopyin(sopt, buf, TCP_LOG_REASON_LEN - 1, 0);
2172 			if (error)
2173 				break;
2174 			buf[sopt->sopt_valsize] = '\0';
2175 			INP_WLOCK_RECHECK(inp);
2176 			if (sopt->sopt_name == TCP_LOGDUMP) {
2177 				error = tcp_log_dump_tp_logbuf(tp, buf,
2178 				    M_WAITOK, true);
2179 				INP_WUNLOCK(inp);
2180 			} else {
2181 				tcp_log_dump_tp_bucket_logbufs(tp, buf);
2182 				/*
2183 				 * tcp_log_dump_tp_bucket_logbufs() drops the
2184 				 * INP lock.
2185 				 */
2186 			}
2187 			break;
2188 #endif
2189 
2190 		default:
2191 			INP_WUNLOCK(inp);
2192 			error = ENOPROTOOPT;
2193 			break;
2194 		}
2195 		break;
2196 
2197 	case SOPT_GET:
2198 		tp = intotcpcb(inp);
2199 		switch (sopt->sopt_name) {
2200 #if defined(IPSEC_SUPPORT) || defined(TCP_SIGNATURE)
2201 		case TCP_MD5SIG:
2202 			if (!TCPMD5_ENABLED()) {
2203 				INP_WUNLOCK(inp);
2204 				return (ENOPROTOOPT);
2205 			}
2206 			error = TCPMD5_PCBCTL(inp, sopt);
2207 			break;
2208 #endif
2209 
2210 		case TCP_NODELAY:
2211 			optval = tp->t_flags & TF_NODELAY;
2212 			INP_WUNLOCK(inp);
2213 			error = sooptcopyout(sopt, &optval, sizeof optval);
2214 			break;
2215 		case TCP_MAXSEG:
2216 			optval = tp->t_maxseg;
2217 			INP_WUNLOCK(inp);
2218 			error = sooptcopyout(sopt, &optval, sizeof optval);
2219 			break;
2220 		case TCP_NOOPT:
2221 			optval = tp->t_flags & TF_NOOPT;
2222 			INP_WUNLOCK(inp);
2223 			error = sooptcopyout(sopt, &optval, sizeof optval);
2224 			break;
2225 		case TCP_NOPUSH:
2226 			optval = tp->t_flags & TF_NOPUSH;
2227 			INP_WUNLOCK(inp);
2228 			error = sooptcopyout(sopt, &optval, sizeof optval);
2229 			break;
2230 		case TCP_INFO:
2231 			tcp_fill_info(tp, &ti);
2232 			INP_WUNLOCK(inp);
2233 			error = sooptcopyout(sopt, &ti, sizeof ti);
2234 			break;
2235 		case TCP_CONGESTION:
2236 			len = strlcpy(buf, CC_ALGO(tp)->name, TCP_CA_NAME_MAX);
2237 			INP_WUNLOCK(inp);
2238 			error = sooptcopyout(sopt, buf, len + 1);
2239 			break;
2240 		case TCP_KEEPIDLE:
2241 		case TCP_KEEPINTVL:
2242 		case TCP_KEEPINIT:
2243 		case TCP_KEEPCNT:
2244 			switch (sopt->sopt_name) {
2245 			case TCP_KEEPIDLE:
2246 				ui = TP_KEEPIDLE(tp) / hz;
2247 				break;
2248 			case TCP_KEEPINTVL:
2249 				ui = TP_KEEPINTVL(tp) / hz;
2250 				break;
2251 			case TCP_KEEPINIT:
2252 				ui = TP_KEEPINIT(tp) / hz;
2253 				break;
2254 			case TCP_KEEPCNT:
2255 				ui = TP_KEEPCNT(tp);
2256 				break;
2257 			}
2258 			INP_WUNLOCK(inp);
2259 			error = sooptcopyout(sopt, &ui, sizeof(ui));
2260 			break;
2261 #ifdef TCPPCAP
2262 		case TCP_PCAP_OUT:
2263 		case TCP_PCAP_IN:
2264 			optval = tcp_pcap_get_sock_max(
2265 					(sopt->sopt_name == TCP_PCAP_OUT) ?
2266 					&(tp->t_outpkts) : &(tp->t_inpkts));
2267 			INP_WUNLOCK(inp);
2268 			error = sooptcopyout(sopt, &optval, sizeof optval);
2269 			break;
2270 #endif
2271 		case TCP_FASTOPEN:
2272 			optval = tp->t_flags & TF_FASTOPEN;
2273 			INP_WUNLOCK(inp);
2274 			error = sooptcopyout(sopt, &optval, sizeof optval);
2275 			break;
2276 #ifdef TCP_BLACKBOX
2277 		case TCP_LOG:
2278 			optval = tp->t_logstate;
2279 			INP_WUNLOCK(inp);
2280 			error = sooptcopyout(sopt, &optval, sizeof(optval));
2281 			break;
2282 		case TCP_LOGBUF:
2283 			/* tcp_log_getlogbuf() does INP_WUNLOCK(inp) */
2284 			error = tcp_log_getlogbuf(sopt, tp);
2285 			break;
2286 		case TCP_LOGID:
2287 			len = tcp_log_get_id(tp, buf);
2288 			INP_WUNLOCK(inp);
2289 			error = sooptcopyout(sopt, buf, len + 1);
2290 			break;
2291 		case TCP_LOGDUMP:
2292 		case TCP_LOGDUMPID:
2293 			INP_WUNLOCK(inp);
2294 			error = EINVAL;
2295 			break;
2296 #endif
2297 		default:
2298 			INP_WUNLOCK(inp);
2299 			error = ENOPROTOOPT;
2300 			break;
2301 		}
2302 		break;
2303 	}
2304 	return (error);
2305 }
2306 #undef INP_WLOCK_RECHECK
2307 #undef INP_WLOCK_RECHECK_CLEANUP
2308 
2309 /*
2310  * Attach TCP protocol to socket, allocating
2311  * internet protocol control block, tcp control block,
2312  * bufer space, and entering LISTEN state if to accept connections.
2313  */
2314 static int
tcp_attach(struct socket * so)2315 tcp_attach(struct socket *so)
2316 {
2317 	struct tcpcb *tp;
2318 	struct inpcb *inp;
2319 	struct epoch_tracker et;
2320 	int error;
2321 
2322 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
2323 		error = soreserve(so, V_tcp_sendspace, V_tcp_recvspace);
2324 		if (error)
2325 			return (error);
2326 	}
2327 	so->so_rcv.sb_flags |= SB_AUTOSIZE;
2328 	so->so_snd.sb_flags |= SB_AUTOSIZE;
2329 	INP_INFO_RLOCK_ET(&V_tcbinfo, et);
2330 	error = in_pcballoc(so, &V_tcbinfo);
2331 	if (error) {
2332 		INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
2333 		return (error);
2334 	}
2335 	inp = sotoinpcb(so);
2336 #ifdef INET6
2337 	if (inp->inp_vflag & INP_IPV6PROTO) {
2338 		inp->inp_vflag |= INP_IPV6;
2339 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
2340 			inp->inp_vflag |= INP_IPV4;
2341 		inp->in6p_hops = -1;	/* use kernel default */
2342 	}
2343 	else
2344 #endif
2345 	inp->inp_vflag |= INP_IPV4;
2346 	tp = tcp_newtcpcb(inp);
2347 	if (tp == NULL) {
2348 		in_pcbdetach(inp);
2349 		in_pcbfree(inp);
2350 		INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
2351 		return (ENOBUFS);
2352 	}
2353 	tp->t_state = TCPS_CLOSED;
2354 	INP_WUNLOCK(inp);
2355 	INP_INFO_RUNLOCK_ET(&V_tcbinfo, et);
2356 	TCPSTATES_INC(TCPS_CLOSED);
2357 	return (0);
2358 }
2359 
2360 /*
2361  * Initiate (or continue) disconnect.
2362  * If embryonic state, just send reset (once).
2363  * If in ``let data drain'' option and linger null, just drop.
2364  * Otherwise (hard), mark socket disconnecting and drop
2365  * current input data; switch states based on user close, and
2366  * send segment to peer (with FIN).
2367  */
2368 static void
tcp_disconnect(struct tcpcb * tp)2369 tcp_disconnect(struct tcpcb *tp)
2370 {
2371 	struct inpcb *inp = tp->t_inpcb;
2372 	struct socket *so = inp->inp_socket;
2373 
2374 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2375 	INP_WLOCK_ASSERT(inp);
2376 
2377 	/*
2378 	 * Neither tcp_close() nor tcp_drop() should return NULL, as the
2379 	 * socket is still open.
2380 	 */
2381 	if (tp->t_state < TCPS_ESTABLISHED &&
2382 	    !(tp->t_state > TCPS_LISTEN && IS_FASTOPEN(tp->t_flags))) {
2383 		tp = tcp_close(tp);
2384 		KASSERT(tp != NULL,
2385 		    ("tcp_disconnect: tcp_close() returned NULL"));
2386 	} else if ((so->so_options & SO_LINGER) && so->so_linger == 0) {
2387 		tp = tcp_drop(tp, 0);
2388 		KASSERT(tp != NULL,
2389 		    ("tcp_disconnect: tcp_drop() returned NULL"));
2390 	} else {
2391 		soisdisconnecting(so);
2392 		sbflush(&so->so_rcv);
2393 		tcp_usrclosed(tp);
2394 		if (!(inp->inp_flags & INP_DROPPED))
2395 			tp->t_fb->tfb_tcp_output(tp);
2396 	}
2397 }
2398 
2399 /*
2400  * User issued close, and wish to trail through shutdown states:
2401  * if never received SYN, just forget it.  If got a SYN from peer,
2402  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
2403  * If already got a FIN from peer, then almost done; go to LAST_ACK
2404  * state.  In all other cases, have already sent FIN to peer (e.g.
2405  * after PRU_SHUTDOWN), and just have to play tedious game waiting
2406  * for peer to send FIN or not respond to keep-alives, etc.
2407  * We can let the user exit from the close as soon as the FIN is acked.
2408  */
2409 static void
tcp_usrclosed(struct tcpcb * tp)2410 tcp_usrclosed(struct tcpcb *tp)
2411 {
2412 
2413 	INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
2414 	INP_WLOCK_ASSERT(tp->t_inpcb);
2415 
2416 	switch (tp->t_state) {
2417 	case TCPS_LISTEN:
2418 #ifdef TCP_OFFLOAD
2419 		tcp_offload_listen_stop(tp);
2420 #endif
2421 		tcp_state_change(tp, TCPS_CLOSED);
2422 		/* FALLTHROUGH */
2423 	case TCPS_CLOSED:
2424 		tp = tcp_close(tp);
2425 		/*
2426 		 * tcp_close() should never return NULL here as the socket is
2427 		 * still open.
2428 		 */
2429 		KASSERT(tp != NULL,
2430 		    ("tcp_usrclosed: tcp_close() returned NULL"));
2431 		break;
2432 
2433 	case TCPS_SYN_SENT:
2434 	case TCPS_SYN_RECEIVED:
2435 		tp->t_flags |= TF_NEEDFIN;
2436 		break;
2437 
2438 	case TCPS_ESTABLISHED:
2439 		tcp_state_change(tp, TCPS_FIN_WAIT_1);
2440 		break;
2441 
2442 	case TCPS_CLOSE_WAIT:
2443 		tcp_state_change(tp, TCPS_LAST_ACK);
2444 		break;
2445 	}
2446 	if (tp->t_state >= TCPS_FIN_WAIT_2) {
2447 		soisdisconnected(tp->t_inpcb->inp_socket);
2448 		/* Prevent the connection hanging in FIN_WAIT_2 forever. */
2449 		if (tp->t_state == TCPS_FIN_WAIT_2) {
2450 			int timeout;
2451 
2452 			timeout = (tcp_fast_finwait2_recycle) ?
2453 			    tcp_finwait2_timeout : TP_MAXIDLE(tp);
2454 			tcp_timer_activate(tp, TT_2MSL, timeout);
2455 		}
2456 	}
2457 }
2458 
2459 #ifdef DDB
2460 static void
db_print_indent(int indent)2461 db_print_indent(int indent)
2462 {
2463 	int i;
2464 
2465 	for (i = 0; i < indent; i++)
2466 		db_printf(" ");
2467 }
2468 
2469 static void
db_print_tstate(int t_state)2470 db_print_tstate(int t_state)
2471 {
2472 
2473 	switch (t_state) {
2474 	case TCPS_CLOSED:
2475 		db_printf("TCPS_CLOSED");
2476 		return;
2477 
2478 	case TCPS_LISTEN:
2479 		db_printf("TCPS_LISTEN");
2480 		return;
2481 
2482 	case TCPS_SYN_SENT:
2483 		db_printf("TCPS_SYN_SENT");
2484 		return;
2485 
2486 	case TCPS_SYN_RECEIVED:
2487 		db_printf("TCPS_SYN_RECEIVED");
2488 		return;
2489 
2490 	case TCPS_ESTABLISHED:
2491 		db_printf("TCPS_ESTABLISHED");
2492 		return;
2493 
2494 	case TCPS_CLOSE_WAIT:
2495 		db_printf("TCPS_CLOSE_WAIT");
2496 		return;
2497 
2498 	case TCPS_FIN_WAIT_1:
2499 		db_printf("TCPS_FIN_WAIT_1");
2500 		return;
2501 
2502 	case TCPS_CLOSING:
2503 		db_printf("TCPS_CLOSING");
2504 		return;
2505 
2506 	case TCPS_LAST_ACK:
2507 		db_printf("TCPS_LAST_ACK");
2508 		return;
2509 
2510 	case TCPS_FIN_WAIT_2:
2511 		db_printf("TCPS_FIN_WAIT_2");
2512 		return;
2513 
2514 	case TCPS_TIME_WAIT:
2515 		db_printf("TCPS_TIME_WAIT");
2516 		return;
2517 
2518 	default:
2519 		db_printf("unknown");
2520 		return;
2521 	}
2522 }
2523 
2524 static void
db_print_tflags(u_int t_flags)2525 db_print_tflags(u_int t_flags)
2526 {
2527 	int comma;
2528 
2529 	comma = 0;
2530 	if (t_flags & TF_ACKNOW) {
2531 		db_printf("%sTF_ACKNOW", comma ? ", " : "");
2532 		comma = 1;
2533 	}
2534 	if (t_flags & TF_DELACK) {
2535 		db_printf("%sTF_DELACK", comma ? ", " : "");
2536 		comma = 1;
2537 	}
2538 	if (t_flags & TF_NODELAY) {
2539 		db_printf("%sTF_NODELAY", comma ? ", " : "");
2540 		comma = 1;
2541 	}
2542 	if (t_flags & TF_NOOPT) {
2543 		db_printf("%sTF_NOOPT", comma ? ", " : "");
2544 		comma = 1;
2545 	}
2546 	if (t_flags & TF_SENTFIN) {
2547 		db_printf("%sTF_SENTFIN", comma ? ", " : "");
2548 		comma = 1;
2549 	}
2550 	if (t_flags & TF_REQ_SCALE) {
2551 		db_printf("%sTF_REQ_SCALE", comma ? ", " : "");
2552 		comma = 1;
2553 	}
2554 	if (t_flags & TF_RCVD_SCALE) {
2555 		db_printf("%sTF_RECVD_SCALE", comma ? ", " : "");
2556 		comma = 1;
2557 	}
2558 	if (t_flags & TF_REQ_TSTMP) {
2559 		db_printf("%sTF_REQ_TSTMP", comma ? ", " : "");
2560 		comma = 1;
2561 	}
2562 	if (t_flags & TF_RCVD_TSTMP) {
2563 		db_printf("%sTF_RCVD_TSTMP", comma ? ", " : "");
2564 		comma = 1;
2565 	}
2566 	if (t_flags & TF_SACK_PERMIT) {
2567 		db_printf("%sTF_SACK_PERMIT", comma ? ", " : "");
2568 		comma = 1;
2569 	}
2570 	if (t_flags & TF_NEEDSYN) {
2571 		db_printf("%sTF_NEEDSYN", comma ? ", " : "");
2572 		comma = 1;
2573 	}
2574 	if (t_flags & TF_NEEDFIN) {
2575 		db_printf("%sTF_NEEDFIN", comma ? ", " : "");
2576 		comma = 1;
2577 	}
2578 	if (t_flags & TF_NOPUSH) {
2579 		db_printf("%sTF_NOPUSH", comma ? ", " : "");
2580 		comma = 1;
2581 	}
2582 	if (t_flags & TF_MORETOCOME) {
2583 		db_printf("%sTF_MORETOCOME", comma ? ", " : "");
2584 		comma = 1;
2585 	}
2586 	if (t_flags & TF_LQ_OVERFLOW) {
2587 		db_printf("%sTF_LQ_OVERFLOW", comma ? ", " : "");
2588 		comma = 1;
2589 	}
2590 	if (t_flags & TF_LASTIDLE) {
2591 		db_printf("%sTF_LASTIDLE", comma ? ", " : "");
2592 		comma = 1;
2593 	}
2594 	if (t_flags & TF_RXWIN0SENT) {
2595 		db_printf("%sTF_RXWIN0SENT", comma ? ", " : "");
2596 		comma = 1;
2597 	}
2598 	if (t_flags & TF_FASTRECOVERY) {
2599 		db_printf("%sTF_FASTRECOVERY", comma ? ", " : "");
2600 		comma = 1;
2601 	}
2602 	if (t_flags & TF_CONGRECOVERY) {
2603 		db_printf("%sTF_CONGRECOVERY", comma ? ", " : "");
2604 		comma = 1;
2605 	}
2606 	if (t_flags & TF_WASFRECOVERY) {
2607 		db_printf("%sTF_WASFRECOVERY", comma ? ", " : "");
2608 		comma = 1;
2609 	}
2610 	if (t_flags & TF_SIGNATURE) {
2611 		db_printf("%sTF_SIGNATURE", comma ? ", " : "");
2612 		comma = 1;
2613 	}
2614 	if (t_flags & TF_FORCEDATA) {
2615 		db_printf("%sTF_FORCEDATA", comma ? ", " : "");
2616 		comma = 1;
2617 	}
2618 	if (t_flags & TF_TSO) {
2619 		db_printf("%sTF_TSO", comma ? ", " : "");
2620 		comma = 1;
2621 	}
2622 	if (t_flags & TF_ECN_PERMIT) {
2623 		db_printf("%sTF_ECN_PERMIT", comma ? ", " : "");
2624 		comma = 1;
2625 	}
2626 	if (t_flags & TF_FASTOPEN) {
2627 		db_printf("%sTF_FASTOPEN", comma ? ", " : "");
2628 		comma = 1;
2629 	}
2630 }
2631 
2632 static void
db_print_toobflags(char t_oobflags)2633 db_print_toobflags(char t_oobflags)
2634 {
2635 	int comma;
2636 
2637 	comma = 0;
2638 	if (t_oobflags & TCPOOB_HAVEDATA) {
2639 		db_printf("%sTCPOOB_HAVEDATA", comma ? ", " : "");
2640 		comma = 1;
2641 	}
2642 	if (t_oobflags & TCPOOB_HADDATA) {
2643 		db_printf("%sTCPOOB_HADDATA", comma ? ", " : "");
2644 		comma = 1;
2645 	}
2646 }
2647 
2648 static void
db_print_tcpcb(struct tcpcb * tp,const char * name,int indent)2649 db_print_tcpcb(struct tcpcb *tp, const char *name, int indent)
2650 {
2651 
2652 	db_print_indent(indent);
2653 	db_printf("%s at %p\n", name, tp);
2654 
2655 	indent += 2;
2656 
2657 	db_print_indent(indent);
2658 	db_printf("t_segq first: %p   t_segqlen: %d   t_dupacks: %d\n",
2659 	   TAILQ_FIRST(&tp->t_segq), tp->t_segqlen, tp->t_dupacks);
2660 
2661 	db_print_indent(indent);
2662 	db_printf("tt_rexmt: %p   tt_persist: %p   tt_keep: %p\n",
2663 	    &tp->t_timers->tt_rexmt, &tp->t_timers->tt_persist, &tp->t_timers->tt_keep);
2664 
2665 	db_print_indent(indent);
2666 	db_printf("tt_2msl: %p   tt_delack: %p   t_inpcb: %p\n", &tp->t_timers->tt_2msl,
2667 	    &tp->t_timers->tt_delack, tp->t_inpcb);
2668 
2669 	db_print_indent(indent);
2670 	db_printf("t_state: %d (", tp->t_state);
2671 	db_print_tstate(tp->t_state);
2672 	db_printf(")\n");
2673 
2674 	db_print_indent(indent);
2675 	db_printf("t_flags: 0x%x (", tp->t_flags);
2676 	db_print_tflags(tp->t_flags);
2677 	db_printf(")\n");
2678 
2679 	db_print_indent(indent);
2680 	db_printf("snd_una: 0x%08x   snd_max: 0x%08x   snd_nxt: x0%08x\n",
2681 	    tp->snd_una, tp->snd_max, tp->snd_nxt);
2682 
2683 	db_print_indent(indent);
2684 	db_printf("snd_up: 0x%08x   snd_wl1: 0x%08x   snd_wl2: 0x%08x\n",
2685 	   tp->snd_up, tp->snd_wl1, tp->snd_wl2);
2686 
2687 	db_print_indent(indent);
2688 	db_printf("iss: 0x%08x   irs: 0x%08x   rcv_nxt: 0x%08x\n",
2689 	    tp->iss, tp->irs, tp->rcv_nxt);
2690 
2691 	db_print_indent(indent);
2692 	db_printf("rcv_adv: 0x%08x   rcv_wnd: %u   rcv_up: 0x%08x\n",
2693 	    tp->rcv_adv, tp->rcv_wnd, tp->rcv_up);
2694 
2695 	db_print_indent(indent);
2696 	db_printf("snd_wnd: %u   snd_cwnd: %u\n",
2697 	   tp->snd_wnd, tp->snd_cwnd);
2698 
2699 	db_print_indent(indent);
2700 	db_printf("snd_ssthresh: %u   snd_recover: "
2701 	    "0x%08x\n", tp->snd_ssthresh, tp->snd_recover);
2702 
2703 	db_print_indent(indent);
2704 	db_printf("t_rcvtime: %u   t_startime: %u\n",
2705 	    tp->t_rcvtime, tp->t_starttime);
2706 
2707 	db_print_indent(indent);
2708 	db_printf("t_rttime: %u   t_rtsq: 0x%08x\n",
2709 	    tp->t_rtttime, tp->t_rtseq);
2710 
2711 	db_print_indent(indent);
2712 	db_printf("t_rxtcur: %d   t_maxseg: %u   t_srtt: %d\n",
2713 	    tp->t_rxtcur, tp->t_maxseg, tp->t_srtt);
2714 
2715 	db_print_indent(indent);
2716 	db_printf("t_rttvar: %d   t_rxtshift: %d   t_rttmin: %u   "
2717 	    "t_rttbest: %u\n", tp->t_rttvar, tp->t_rxtshift, tp->t_rttmin,
2718 	    tp->t_rttbest);
2719 
2720 	db_print_indent(indent);
2721 	db_printf("t_rttupdated: %lu   max_sndwnd: %u   t_softerror: %d\n",
2722 	    tp->t_rttupdated, tp->max_sndwnd, tp->t_softerror);
2723 
2724 	db_print_indent(indent);
2725 	db_printf("t_oobflags: 0x%x (", tp->t_oobflags);
2726 	db_print_toobflags(tp->t_oobflags);
2727 	db_printf(")   t_iobc: 0x%02x\n", tp->t_iobc);
2728 
2729 	db_print_indent(indent);
2730 	db_printf("snd_scale: %u   rcv_scale: %u   request_r_scale: %u\n",
2731 	    tp->snd_scale, tp->rcv_scale, tp->request_r_scale);
2732 
2733 	db_print_indent(indent);
2734 	db_printf("ts_recent: %u   ts_recent_age: %u\n",
2735 	    tp->ts_recent, tp->ts_recent_age);
2736 
2737 	db_print_indent(indent);
2738 	db_printf("ts_offset: %u   last_ack_sent: 0x%08x   snd_cwnd_prev: "
2739 	    "%u\n", tp->ts_offset, tp->last_ack_sent, tp->snd_cwnd_prev);
2740 
2741 	db_print_indent(indent);
2742 	db_printf("snd_ssthresh_prev: %u   snd_recover_prev: 0x%08x   "
2743 	    "t_badrxtwin: %u\n", tp->snd_ssthresh_prev,
2744 	    tp->snd_recover_prev, tp->t_badrxtwin);
2745 
2746 	db_print_indent(indent);
2747 	db_printf("snd_numholes: %d  snd_holes first: %p\n",
2748 	    tp->snd_numholes, TAILQ_FIRST(&tp->snd_holes));
2749 
2750 	db_print_indent(indent);
2751 	db_printf("snd_fack: 0x%08x   rcv_numsacks: %d   sack_newdata: "
2752 	    "0x%08x\n", tp->snd_fack, tp->rcv_numsacks, tp->sack_newdata);
2753 
2754 	/* Skip sackblks, sackhint. */
2755 
2756 	db_print_indent(indent);
2757 	db_printf("t_rttlow: %d   rfbuf_ts: %u   rfbuf_cnt: %d\n",
2758 	    tp->t_rttlow, tp->rfbuf_ts, tp->rfbuf_cnt);
2759 }
2760 
DB_SHOW_COMMAND(tcpcb,db_show_tcpcb)2761 DB_SHOW_COMMAND(tcpcb, db_show_tcpcb)
2762 {
2763 	struct tcpcb *tp;
2764 
2765 	if (!have_addr) {
2766 		db_printf("usage: show tcpcb <addr>\n");
2767 		return;
2768 	}
2769 	tp = (struct tcpcb *)addr;
2770 
2771 	db_print_tcpcb(tp, "tcpcb", 0);
2772 }
2773 #endif
2774