xref: /openbsd-src/sys/netinet/tcp_subr.c (revision 53555c846a0a6f917dbd0a191f826da995ab1c42)
1 /*	$OpenBSD: tcp_subr.c,v 1.204 2025/01/03 17:23:51 bluhm Exp $	*/
2 /*	$NetBSD: tcp_subr.c,v 1.22 1996/02/13 23:44:00 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  *	This product includes software developed by the University of
46  *	California, Berkeley and its contributors.
47  *	This product includes software developed at the Information
48  *	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/mutex.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/timeout.h>
78 #include <sys/protosw.h>
79 #include <sys/kernel.h>
80 #include <sys/pool.h>
81 
82 #include <net/route.h>
83 
84 #include <netinet/in.h>
85 #include <netinet/ip.h>
86 #include <netinet/in_pcb.h>
87 #include <netinet/ip_var.h>
88 #include <netinet6/ip6_var.h>
89 #include <netinet/ip_icmp.h>
90 #include <netinet/tcp.h>
91 #include <netinet/tcp_fsm.h>
92 #include <netinet/tcp_seq.h>
93 #include <netinet/tcp_timer.h>
94 #include <netinet/tcp_var.h>
95 
96 #ifdef INET6
97 #include <netinet6/ip6protosw.h>
98 #endif /* INET6 */
99 
100 #include <crypto/md5.h>
101 #include <crypto/sha2.h>
102 
103 /*
104  * Locks used to protect struct members in this file:
105  *	I	immutable after creation
106  *	T	tcp_timer_mtx		global tcp timer data structures
107  */
108 
109 struct mutex tcp_timer_mtx = MUTEX_INITIALIZER(IPL_SOFTNET);
110 
111 /* patchable/settable parameters for tcp */
112 int	tcp_mssdflt = TCP_MSS;
113 int	tcp_rttdflt = TCPTV_SRTTDFLT;
114 
115 /* values controllable via sysctl */
116 int	tcp_do_rfc1323 = 1;
117 int	tcp_do_sack = 1;	/* RFC 2018 selective ACKs */
118 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
119 #ifdef TCP_ECN
120 int	tcp_do_ecn = 0;		/* RFC3168 ECN enabled/disabled? */
121 #endif
122 int	tcp_do_rfc3390 = 2;	/* Increase TCP's Initial Window to 10*mss */
123 int	tcp_do_tso = 1;		/* TCP segmentation offload for output */
124 
125 #ifndef TCB_INITIAL_HASH_SIZE
126 #define	TCB_INITIAL_HASH_SIZE	128
127 #endif
128 
129 int tcp_reass_limit = NMBCLUSTERS / 8; /* hardlimit for tcpqe_pool */
130 int tcp_sackhole_limit = 32*1024; /* hardlimit for sackhl_pool */
131 
132 struct pool tcpcb_pool;
133 struct pool tcpqe_pool;
134 struct pool sackhl_pool;
135 
136 struct cpumem *tcpcounters;		/* tcp statistics */
137 
138 u_char		tcp_secret[16];	/* [I] */
139 SHA2_CTX	tcp_secret_ctx;	/* [I] */
140 tcp_seq		tcp_iss;	/* [T] updated by timer and connection */
141 uint64_t	tcp_starttime;	/* [I] random offset for tcp_now() */
142 
143 /*
144  * Tcp initialization
145  */
146 void
147 tcp_init(void)
148 {
149 	tcp_iss = 1;		/* wrong */
150 	/* 0 is treated special so add 1, 63 bits to count is enough */
151 	arc4random_buf(&tcp_starttime, sizeof(tcp_starttime));
152 	tcp_starttime = 1ULL + (tcp_starttime / 2);
153 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, IPL_SOFTNET, 0,
154 	    "tcpcb", NULL);
155 	pool_init(&tcpqe_pool, sizeof(struct tcpqent), 0, IPL_SOFTNET, 0,
156 	    "tcpqe", NULL);
157 	pool_sethardlimit(&tcpqe_pool, tcp_reass_limit, NULL, 0);
158 	pool_init(&sackhl_pool, sizeof(struct sackhole), 0, IPL_SOFTNET, 0,
159 	    "sackhl", NULL);
160 	pool_sethardlimit(&sackhl_pool, tcp_sackhole_limit, NULL, 0);
161 	in_pcbinit(&tcbtable, TCB_INITIAL_HASH_SIZE);
162 #ifdef INET6
163 	in_pcbinit(&tcb6table, TCB_INITIAL_HASH_SIZE);
164 #endif
165 	tcpcounters = counters_alloc(tcps_ncounters);
166 
167 	arc4random_buf(tcp_secret, sizeof(tcp_secret));
168 	SHA512Init(&tcp_secret_ctx);
169 	SHA512Update(&tcp_secret_ctx, tcp_secret, sizeof(tcp_secret));
170 
171 #ifdef INET6
172 	/*
173 	 * Since sizeof(struct ip6_hdr) > sizeof(struct ip), we
174 	 * do max length checks/computations only on the former.
175 	 */
176 	if (max_protohdr < (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)))
177 		max_protohdr = (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
178 	if ((max_linkhdr + sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) >
179 	    MHLEN)
180 		panic("tcp_init");
181 
182 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
183 #endif /* INET6 */
184 
185 	/* Initialize the compressed state engine. */
186 	syn_cache_init();
187 
188 	/* Initialize timer state. */
189 	tcp_timer_init();
190 }
191 
192 /*
193  * Create template to be used to send tcp packets on a connection.
194  * Call after host entry created, allocates an mbuf and fills
195  * in a skeletal tcp/ip header, minimizing the amount of work
196  * necessary when the connection is used.
197  *
198  * To support IPv6 in addition to IPv4 and considering that the sizes of
199  * the IPv4 and IPv6 headers are not the same, we now use a separate pointer
200  * for the TCP header.  Also, we made the former tcpiphdr header pointer
201  * into just an IP overlay pointer, with casting as appropriate for v6. rja
202  */
203 struct mbuf *
204 tcp_template(struct tcpcb *tp)
205 {
206 	struct inpcb *inp = tp->t_inpcb;
207 	struct mbuf *m;
208 	struct tcphdr *th;
209 
210 	CTASSERT(sizeof(struct ip) + sizeof(struct tcphdr) <= MHLEN);
211 	CTASSERT(sizeof(struct ip6_hdr) + sizeof(struct tcphdr) <= MHLEN);
212 
213 	if ((m = tp->t_template) == 0) {
214 		m = m_get(M_DONTWAIT, MT_HEADER);
215 		if (m == NULL)
216 			return (0);
217 
218 		switch (tp->pf) {
219 		case 0:	/*default to PF_INET*/
220 		case AF_INET:
221 			m->m_len = sizeof(struct ip);
222 			break;
223 #ifdef INET6
224 		case AF_INET6:
225 			m->m_len = sizeof(struct ip6_hdr);
226 			break;
227 #endif /* INET6 */
228 		}
229 		m->m_len += sizeof (struct tcphdr);
230 	}
231 
232 	switch(tp->pf) {
233 	case AF_INET:
234 		{
235 			struct ipovly *ipovly;
236 
237 			ipovly = mtod(m, struct ipovly *);
238 
239 			bzero(ipovly->ih_x1, sizeof ipovly->ih_x1);
240 			ipovly->ih_pr = IPPROTO_TCP;
241 			ipovly->ih_len = htons(sizeof (struct tcphdr));
242 			ipovly->ih_src = inp->inp_laddr;
243 			ipovly->ih_dst = inp->inp_faddr;
244 
245 			th = (struct tcphdr *)(mtod(m, caddr_t) +
246 				sizeof(struct ip));
247 		}
248 		break;
249 #ifdef INET6
250 	case AF_INET6:
251 		{
252 			struct ip6_hdr *ip6;
253 
254 			ip6 = mtod(m, struct ip6_hdr *);
255 
256 			ip6->ip6_src = inp->inp_laddr6;
257 			ip6->ip6_dst = inp->inp_faddr6;
258 			ip6->ip6_flow = htonl(0x60000000) |
259 			    (inp->inp_flowinfo & IPV6_FLOWLABEL_MASK);
260 
261 			ip6->ip6_nxt = IPPROTO_TCP;
262 			ip6->ip6_plen = htons(sizeof(struct tcphdr)); /*XXX*/
263 			ip6->ip6_hlim = in6_selecthlim(inp);	/*XXX*/
264 
265 			th = (struct tcphdr *)(mtod(m, caddr_t) +
266 				sizeof(struct ip6_hdr));
267 		}
268 		break;
269 #endif /* INET6 */
270 	}
271 
272 	th->th_sport = inp->inp_lport;
273 	th->th_dport = inp->inp_fport;
274 	th->th_seq = 0;
275 	th->th_ack = 0;
276 	th->th_x2  = 0;
277 	th->th_off = 5;
278 	th->th_flags = 0;
279 	th->th_win = 0;
280 	th->th_urp = 0;
281 	th->th_sum = 0;
282 	return (m);
283 }
284 
285 /*
286  * Send a single message to the TCP at address specified by
287  * the given TCP/IP header.  If m == 0, then we make a copy
288  * of the tcpiphdr at ti and send directly to the addressed host.
289  * This is used to force keep alive messages out using the TCP
290  * template for a connection tp->t_template.  If flags are given
291  * then we send a message back to the TCP which originated the
292  * segment ti, and discard the mbuf containing it and any other
293  * attached mbufs.
294  *
295  * In any case the ack and sequence number of the transmitted
296  * segment are as specified by the parameters.
297  */
298 void
299 tcp_respond(struct tcpcb *tp, caddr_t template, struct tcphdr *th0,
300     tcp_seq ack, tcp_seq seq, int flags, u_int rtableid, uint64_t now)
301 {
302 	int tlen;
303 	int win = 0;
304 	struct mbuf *m = NULL;
305 	struct tcphdr *th;
306 	struct ip *ip;
307 #ifdef INET6
308 	struct ip6_hdr *ip6;
309 #endif
310 	int af;		/* af on wire */
311 
312 	if (tp) {
313 		struct socket *so = tp->t_inpcb->inp_socket;
314 		win = sbspace(so, &so->so_rcv);
315 		/*
316 		 * If this is called with an unconnected
317 		 * socket/tp/pcb (tp->pf is 0), we lose.
318 		 */
319 		af = tp->pf;
320 	} else
321 		af = (((struct ip *)template)->ip_v == 6) ? AF_INET6 : AF_INET;
322 
323 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
324 	if (m == NULL)
325 		return;
326 	m->m_data += max_linkhdr;
327 	tlen = 0;
328 
329 #define xchg(a,b,type) do { type t; t=a; a=b; b=t; } while (0)
330 	switch (af) {
331 #ifdef INET6
332 	case AF_INET6:
333 		ip6 = mtod(m, struct ip6_hdr *);
334 		th = (struct tcphdr *)(ip6 + 1);
335 		tlen = sizeof(*ip6) + sizeof(*th);
336 		if (th0) {
337 			bcopy(template, ip6, sizeof(*ip6));
338 			bcopy(th0, th, sizeof(*th));
339 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
340 		} else {
341 			bcopy(template, ip6, tlen);
342 		}
343 		break;
344 #endif /* INET6 */
345 	case AF_INET:
346 		ip = mtod(m, struct ip *);
347 		th = (struct tcphdr *)(ip + 1);
348 		tlen = sizeof(*ip) + sizeof(*th);
349 		if (th0) {
350 			bcopy(template, ip, sizeof(*ip));
351 			bcopy(th0, th, sizeof(*th));
352 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, u_int32_t);
353 		} else {
354 			bcopy(template, ip, tlen);
355 		}
356 		break;
357 	}
358 	if (th0)
359 		xchg(th->th_dport, th->th_sport, u_int16_t);
360 	else
361 		flags = TH_ACK;
362 #undef xchg
363 
364 	th->th_seq = htonl(seq);
365 	th->th_ack = htonl(ack);
366 	th->th_x2 = 0;
367 	th->th_off = sizeof (struct tcphdr) >> 2;
368 	th->th_flags = flags;
369 	if (tp)
370 		win >>= tp->rcv_scale;
371 	if (win > TCP_MAXWIN)
372 		win = TCP_MAXWIN;
373 	th->th_win = htons((u_int16_t)win);
374 	th->th_urp = 0;
375 
376 	if (tp && (tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
377 	    (flags & TH_RST) == 0 && (tp->t_flags & TF_RCVD_TSTMP)) {
378 		u_int32_t *lp = (u_int32_t *)(th + 1);
379 		/* Form timestamp option as shown in appendix A of RFC 1323. */
380 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
381 		*lp++ = htonl(now + tp->ts_modulate);
382 		*lp   = htonl(tp->ts_recent);
383 		tlen += TCPOLEN_TSTAMP_APPA;
384 		th->th_off = (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_APPA) >> 2;
385 	}
386 
387 	m->m_len = tlen;
388 	m->m_pkthdr.len = tlen;
389 	m->m_pkthdr.ph_ifidx = 0;
390 	m->m_pkthdr.csum_flags |= M_TCP_CSUM_OUT;
391 
392 	/* force routing table */
393 	if (tp)
394 		m->m_pkthdr.ph_rtableid = tp->t_inpcb->inp_rtableid;
395 	else
396 		m->m_pkthdr.ph_rtableid = rtableid;
397 
398 	switch (af) {
399 #ifdef INET6
400 	case AF_INET6:
401 		ip6->ip6_flow = htonl(0x60000000);
402 		ip6->ip6_nxt  = IPPROTO_TCP;
403 		ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL); /*XXX*/
404 		ip6->ip6_plen = tlen - sizeof(struct ip6_hdr);
405 		ip6->ip6_plen = htons(ip6->ip6_plen);
406 		ip6_output(m, tp ? tp->t_inpcb->inp_outputopts6 : NULL,
407 		    tp ? &tp->t_inpcb->inp_route : NULL,
408 		    0, NULL,
409 		    tp ? &tp->t_inpcb->inp_seclevel : NULL);
410 		break;
411 #endif /* INET6 */
412 	case AF_INET:
413 		ip->ip_len = htons(tlen);
414 		ip->ip_ttl = ip_defttl;
415 		ip->ip_tos = 0;
416 		ip_output(m, NULL,
417 		    tp ? &tp->t_inpcb->inp_route : NULL,
418 		    ip_mtudisc ? IP_MTUDISC : 0, NULL,
419 		    tp ? &tp->t_inpcb->inp_seclevel : NULL, 0);
420 		break;
421 	}
422 }
423 
424 /*
425  * Create a new TCP control block, making an
426  * empty reassembly queue and hooking it to the argument
427  * protocol control block.
428  */
429 struct tcpcb *
430 tcp_newtcpcb(struct inpcb *inp, int wait)
431 {
432 	struct tcpcb *tp;
433 	int i;
434 
435 	tp = pool_get(&tcpcb_pool, (wait == M_WAIT ? PR_WAITOK : PR_NOWAIT) |
436 	    PR_ZERO);
437 	if (tp == NULL)
438 		return (NULL);
439 	TAILQ_INIT(&tp->t_segq);
440 	tp->t_maxseg = atomic_load_int(&tcp_mssdflt);
441 	tp->t_maxopd = 0;
442 
443 	tp->t_inpcb = inp;
444 	for (i = 0; i < TCPT_NTIMERS; i++)
445 		TCP_TIMER_INIT(tp, i);
446 	timeout_set_flags(&tp->t_timer_reaper, tcp_timer_reaper, tp,
447 	    KCLOCK_NONE, TIMEOUT_PROC | TIMEOUT_MPSAFE);
448 
449 	tp->sack_enable = atomic_load_int(&tcp_do_sack);
450 	tp->t_flags = atomic_load_int(&tcp_do_rfc1323) ?
451 	    (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
452 	/*
453 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
454 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
455 	 * reasonable initial retransmit time.
456 	 */
457 	tp->t_srtt = TCPTV_SRTTBASE;
458 	tp->t_rttvar = tcp_rttdflt <<
459 	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT - 1);
460 	tp->t_rttmin = TCPTV_MIN;
461 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
462 	    TCPTV_MIN, TCPTV_REXMTMAX);
463 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
464 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
465 
466 	tp->t_pmtud_mtu_sent = 0;
467 	tp->t_pmtud_mss_acked = 0;
468 
469 #ifdef INET6
470 	if (ISSET(inp->inp_flags, INP_IPV6)) {
471 		tp->pf = PF_INET6;
472 		inp->inp_ipv6.ip6_hlim = ip6_defhlim;
473 	} else
474 #endif
475 	{
476 		tp->pf = PF_INET;
477 		inp->inp_ip.ip_ttl = ip_defttl;
478 	}
479 
480 	inp->inp_ppcb = (caddr_t)tp;
481 	return (tp);
482 }
483 
484 /*
485  * Drop a TCP connection, reporting
486  * the specified error.  If connection is synchronized,
487  * then send a RST to peer.
488  */
489 struct tcpcb *
490 tcp_drop(struct tcpcb *tp, int errno)
491 {
492 	struct socket *so = tp->t_inpcb->inp_socket;
493 
494 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
495 		tp->t_state = TCPS_CLOSED;
496 		(void) tcp_output(tp);
497 		tcpstat_inc(tcps_drops);
498 	} else
499 		tcpstat_inc(tcps_conndrops);
500 	if (errno == ETIMEDOUT && tp->t_softerror)
501 		errno = tp->t_softerror;
502 	so->so_error = errno;
503 	return (tcp_close(tp));
504 }
505 
506 /*
507  * Close a TCP control block:
508  *	discard all space held by the tcp
509  *	discard internet protocol block
510  *	wake up any sleepers
511  */
512 struct tcpcb *
513 tcp_close(struct tcpcb *tp)
514 {
515 	struct inpcb *inp = tp->t_inpcb;
516 	struct socket *so = inp->inp_socket;
517 	struct sackhole *p, *q;
518 
519 	/* free the reassembly queue, if any */
520 	tcp_freeq(tp);
521 
522 	tcp_canceltimers(tp);
523 	syn_cache_cleanup(tp);
524 
525 	/* Free SACK holes. */
526 	q = p = tp->snd_holes;
527 	while (p != 0) {
528 		q = p->next;
529 		pool_put(&sackhl_pool, p);
530 		p = q;
531 	}
532 
533 	m_free(tp->t_template);
534 	/* Free tcpcb after all pending timers have been run. */
535 	timeout_add(&tp->t_timer_reaper, 0);
536 	inp->inp_ppcb = NULL;
537 	soisdisconnected(so);
538 	in_pcbdetach(inp);
539 	tcpstat_inc(tcps_closed);
540 	return (NULL);
541 }
542 
543 int
544 tcp_freeq(struct tcpcb *tp)
545 {
546 	struct tcpqent *qe;
547 	int rv = 0;
548 
549 	while ((qe = TAILQ_FIRST(&tp->t_segq)) != NULL) {
550 		TAILQ_REMOVE(&tp->t_segq, qe, tcpqe_q);
551 		m_freem(qe->tcpqe_m);
552 		pool_put(&tcpqe_pool, qe);
553 		rv = 1;
554 	}
555 	return (rv);
556 }
557 
558 /*
559  * Compute proper scaling value for receiver window from buffer space
560  */
561 
562 void
563 tcp_rscale(struct tcpcb *tp, u_long hiwat)
564 {
565 	tp->request_r_scale = 0;
566 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
567 	       TCP_MAXWIN << tp->request_r_scale < hiwat)
568 		tp->request_r_scale++;
569 }
570 
571 /*
572  * Notify a tcp user of an asynchronous error;
573  * store error as soft error, but wake up user
574  * (for now, won't do anything until can select for soft error).
575  */
576 void
577 tcp_notify(struct inpcb *inp, int error)
578 {
579 	struct tcpcb *tp = intotcpcb(inp);
580 	struct socket *so = inp->inp_socket;
581 
582 	/*
583 	 * Ignore some errors if we are hooked up.
584 	 * If connection hasn't completed, has retransmitted several times,
585 	 * and receives a second error, give up now.  This is better
586 	 * than waiting a long time to establish a connection that
587 	 * can never complete.
588 	 */
589 	if (tp->t_state == TCPS_ESTABLISHED &&
590 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
591 	      error == EHOSTDOWN)) {
592 		return;
593 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
594 	    tp->t_rxtshift > 3 && tp->t_softerror)
595 		so->so_error = error;
596 	else
597 		tp->t_softerror = error;
598 	wakeup((caddr_t) &so->so_timeo);
599 	sorwakeup(so);
600 	sowwakeup(so);
601 }
602 
603 #ifdef INET6
604 void
605 tcp6_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *d)
606 {
607 	struct tcphdr th;
608 	struct tcpcb *tp;
609 	void (*notify)(struct inpcb *, int) = tcp_notify;
610 	struct ip6_hdr *ip6;
611 	const struct sockaddr_in6 *sa6_src = NULL;
612 	struct sockaddr_in6 *sa6 = satosin6(sa);
613 	struct inpcb *inp;
614 	struct mbuf *m;
615 	tcp_seq seq;
616 	int off;
617 	struct {
618 		u_int16_t th_sport;
619 		u_int16_t th_dport;
620 		u_int32_t th_seq;
621 	} *thp;
622 
623 	CTASSERT(sizeof(*thp) <= sizeof(th));
624 	if (sa->sa_family != AF_INET6 ||
625 	    sa->sa_len != sizeof(struct sockaddr_in6) ||
626 	    IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
627 	    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
628 		return;
629 	if ((unsigned)cmd >= PRC_NCMDS)
630 		return;
631 	else if (cmd == PRC_QUENCH) {
632 		/*
633 		 * Don't honor ICMP Source Quench messages meant for
634 		 * TCP connections.
635 		 */
636 		/* XXX there's no PRC_QUENCH in IPv6 */
637 		return;
638 	} else if (PRC_IS_REDIRECT(cmd))
639 		notify = in_rtchange, d = NULL;
640 	else if (cmd == PRC_MSGSIZE)
641 		; /* special code is present, see below */
642 	else if (cmd == PRC_HOSTDEAD)
643 		d = NULL;
644 	else if (inet6ctlerrmap[cmd] == 0)
645 		return;
646 
647 	/* if the parameter is from icmp6, decode it. */
648 	if (d != NULL) {
649 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
650 		m = ip6cp->ip6c_m;
651 		ip6 = ip6cp->ip6c_ip6;
652 		off = ip6cp->ip6c_off;
653 		sa6_src = ip6cp->ip6c_src;
654 	} else {
655 		m = NULL;
656 		ip6 = NULL;
657 		sa6_src = &sa6_any;
658 	}
659 
660 	if (ip6) {
661 		/*
662 		 * XXX: We assume that when ip6 is non NULL,
663 		 * M and OFF are valid.
664 		 */
665 
666 		/* check if we can safely examine src and dst ports */
667 		if (m->m_pkthdr.len < off + sizeof(*thp))
668 			return;
669 
670 		bzero(&th, sizeof(th));
671 		m_copydata(m, off, sizeof(*thp), &th);
672 
673 		/*
674 		 * Check to see if we have a valid TCP connection
675 		 * corresponding to the address in the ICMPv6 message
676 		 * payload.
677 		 */
678 		inp = in6_pcblookup(&tcb6table, &sa6->sin6_addr,
679 		    th.th_dport, &sa6_src->sin6_addr, th.th_sport, rdomain);
680 		if (cmd == PRC_MSGSIZE) {
681 			/*
682 			 * Depending on the value of "valid" and routing table
683 			 * size (mtudisc_{hi,lo}wat), we will:
684 			 * - recalculate the new MTU and create the
685 			 *   corresponding routing entry, or
686 			 * - ignore the MTU change notification.
687 			 */
688 			icmp6_mtudisc_update((struct ip6ctlparam *)d,
689 			    inp != NULL);
690 			in_pcbunref(inp);
691 			return;
692 		}
693 		if (inp) {
694 			seq = ntohl(th.th_seq);
695 			if ((tp = intotcpcb(inp)) &&
696 			    SEQ_GEQ(seq, tp->snd_una) &&
697 			    SEQ_LT(seq, tp->snd_max))
698 				notify(inp, inet6ctlerrmap[cmd]);
699 		} else if (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
700 		    inet6ctlerrmap[cmd] == ENETUNREACH ||
701 		    inet6ctlerrmap[cmd] == EHOSTDOWN)
702 			syn_cache_unreach(sin6tosa_const(sa6_src), sa, &th,
703 			    rdomain);
704 		in_pcbunref(inp);
705 	} else {
706 		in6_pcbnotify(&tcb6table, sa6, 0,
707 		    sa6_src, 0, rdomain, cmd, NULL, notify);
708 	}
709 }
710 #endif
711 
712 void
713 tcp_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
714 {
715 	struct ip *ip = v;
716 	struct tcphdr *th;
717 	struct tcpcb *tp;
718 	struct inpcb *inp;
719 	struct in_addr faddr;
720 	tcp_seq seq;
721 	u_int mtu;
722 	void (*notify)(struct inpcb *, int) = tcp_notify;
723 	int errno;
724 
725 	if (sa->sa_family != AF_INET)
726 		return;
727 	faddr = satosin(sa)->sin_addr;
728 	if (faddr.s_addr == INADDR_ANY)
729 		return;
730 
731 	if ((unsigned)cmd >= PRC_NCMDS)
732 		return;
733 	errno = inetctlerrmap[cmd];
734 	if (cmd == PRC_QUENCH)
735 		/*
736 		 * Don't honor ICMP Source Quench messages meant for
737 		 * TCP connections.
738 		 */
739 		return;
740 	else if (PRC_IS_REDIRECT(cmd))
741 		notify = in_rtchange, ip = 0;
742 	else if (cmd == PRC_MSGSIZE && ip_mtudisc && ip) {
743 		/*
744 		 * Verify that the packet in the icmp payload refers
745 		 * to an existing TCP connection.
746 		 */
747 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
748 		seq = ntohl(th->th_seq);
749 		inp = in_pcblookup(&tcbtable,
750 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
751 		    rdomain);
752 		if (inp && (tp = intotcpcb(inp)) &&
753 		    SEQ_GEQ(seq, tp->snd_una) &&
754 		    SEQ_LT(seq, tp->snd_max)) {
755 			struct icmp *icp;
756 			icp = (struct icmp *)((caddr_t)ip -
757 					      offsetof(struct icmp, icmp_ip));
758 
759 			/*
760 			 * If the ICMP message advertises a Next-Hop MTU
761 			 * equal or larger than the maximum packet size we have
762 			 * ever sent, drop the message.
763 			 */
764 			mtu = (u_int)ntohs(icp->icmp_nextmtu);
765 			if (mtu >= tp->t_pmtud_mtu_sent) {
766 				in_pcbunref(inp);
767 				return;
768 			}
769 			if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
770 				/*
771 				 * Calculate new MTU, and create corresponding
772 				 * route (traditional PMTUD).
773 				 */
774 				tp->t_flags &= ~TF_PMTUD_PEND;
775 				icmp_mtudisc(icp, inp->inp_rtableid);
776 			} else {
777 				/*
778 				 * Record the information got in the ICMP
779 				 * message; act on it later.
780 				 * If we had already recorded an ICMP message,
781 				 * replace the old one only if the new message
782 				 * refers to an older TCP segment
783 				 */
784 				if (tp->t_flags & TF_PMTUD_PEND) {
785 					if (SEQ_LT(tp->t_pmtud_th_seq, seq)) {
786 						in_pcbunref(inp);
787 						return;
788 					}
789 				} else
790 					tp->t_flags |= TF_PMTUD_PEND;
791 				tp->t_pmtud_th_seq = seq;
792 				tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
793 				tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
794 				tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
795 				in_pcbunref(inp);
796 				return;
797 			}
798 		} else {
799 			/* ignore if we don't have a matching connection */
800 			in_pcbunref(inp);
801 			return;
802 		}
803 		in_pcbunref(inp);
804 		notify = tcp_mtudisc, ip = 0;
805 	} else if (cmd == PRC_MTUINC)
806 		notify = tcp_mtudisc_increase, ip = 0;
807 	else if (cmd == PRC_HOSTDEAD)
808 		ip = 0;
809 	else if (errno == 0)
810 		return;
811 
812 	if (ip) {
813 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
814 		inp = in_pcblookup(&tcbtable,
815 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
816 		    rdomain);
817 		if (inp) {
818 			seq = ntohl(th->th_seq);
819 			if ((tp = intotcpcb(inp)) &&
820 			    SEQ_GEQ(seq, tp->snd_una) &&
821 			    SEQ_LT(seq, tp->snd_max))
822 				notify(inp, errno);
823 		} else if (inetctlerrmap[cmd] == EHOSTUNREACH ||
824 		    inetctlerrmap[cmd] == ENETUNREACH ||
825 		    inetctlerrmap[cmd] == EHOSTDOWN) {
826 			struct sockaddr_in sin;
827 
828 			bzero(&sin, sizeof(sin));
829 			sin.sin_len = sizeof(sin);
830 			sin.sin_family = AF_INET;
831 			sin.sin_port = th->th_sport;
832 			sin.sin_addr = ip->ip_src;
833 			syn_cache_unreach(sintosa(&sin), sa, th, rdomain);
834 		}
835 		in_pcbunref(inp);
836 	} else
837 		in_pcbnotifyall(&tcbtable, satosin(sa), rdomain, errno, notify);
838 }
839 
840 
841 #ifdef INET6
842 /*
843  * Path MTU Discovery handlers.
844  */
845 void
846 tcp6_mtudisc_callback(struct sockaddr_in6 *sin6, u_int rdomain)
847 {
848 	in6_pcbnotify(&tcb6table, sin6, 0,
849 	    &sa6_any, 0, rdomain, PRC_MSGSIZE, NULL, tcp_mtudisc);
850 }
851 #endif /* INET6 */
852 
853 /*
854  * On receipt of path MTU corrections, flush old route and replace it
855  * with the new one.  Retransmit all unacknowledged packets, to ensure
856  * that all packets will be received.
857  */
858 void
859 tcp_mtudisc(struct inpcb *inp, int errno)
860 {
861 	struct tcpcb *tp = intotcpcb(inp);
862 	struct rtentry *rt;
863 	int orig_maxseg, change = 0;
864 
865 	if (tp == NULL)
866 		return;
867 	orig_maxseg = tp->t_maxseg;
868 
869 	rt = in_pcbrtentry(inp);
870 	if (rt != NULL) {
871 		unsigned int orig_mtulock = (rt->rt_locks & RTV_MTU);
872 
873 		/*
874 		 * If this was not a host route, remove and realloc.
875 		 */
876 		if ((rt->rt_flags & RTF_HOST) == 0) {
877 			in_rtchange(inp, errno);
878 			if ((rt = in_pcbrtentry(inp)) == NULL)
879 				return;
880 		}
881 		if (orig_mtulock < (rt->rt_locks & RTV_MTU))
882 			change = 1;
883 	}
884 	tcp_mss(tp, -1);
885 	if (orig_maxseg > tp->t_maxseg)
886 		change = 1;
887 
888 	/*
889 	 * Resend unacknowledged packets
890 	 */
891 	tp->snd_nxt = tp->snd_una;
892 	if (change || errno > 0)
893 		tcp_output(tp);
894 }
895 
896 void
897 tcp_mtudisc_increase(struct inpcb *inp, int errno)
898 {
899 	struct tcpcb *tp = intotcpcb(inp);
900 	struct rtentry *rt = in_pcbrtentry(inp);
901 
902 	if (tp != 0 && rt != 0) {
903 		/*
904 		 * If this was a host route, remove and realloc.
905 		 */
906 		if (rt->rt_flags & RTF_HOST)
907 			in_rtchange(inp, errno);
908 
909 		/* also takes care of congestion window */
910 		tcp_mss(tp, -1);
911 	}
912 }
913 
914 /*
915  * Generate new ISNs with a method based on RFC1948
916  */
917 #define TCP_ISS_CONN_INC 4096
918 
919 void
920 tcp_set_iss_tsm(struct tcpcb *tp)
921 {
922 	SHA2_CTX ctx;
923 	union {
924 		uint8_t bytes[SHA512_DIGEST_LENGTH];
925 		uint32_t words[2];
926 	} digest;
927 	u_int rdomain = rtable_l2(tp->t_inpcb->inp_rtableid);
928 	tcp_seq iss;
929 
930 	mtx_enter(&tcp_timer_mtx);
931 	tcp_iss += TCP_ISS_CONN_INC;
932 	iss = tcp_iss;
933 	mtx_leave(&tcp_timer_mtx);
934 
935 	ctx = tcp_secret_ctx;
936 	SHA512Update(&ctx, &rdomain, sizeof(rdomain));
937 	SHA512Update(&ctx, &tp->t_inpcb->inp_lport, sizeof(u_short));
938 	SHA512Update(&ctx, &tp->t_inpcb->inp_fport, sizeof(u_short));
939 	if (tp->pf == AF_INET6) {
940 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr6,
941 		    sizeof(struct in6_addr));
942 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr6,
943 		    sizeof(struct in6_addr));
944 	} else {
945 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr,
946 		    sizeof(struct in_addr));
947 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr,
948 		    sizeof(struct in_addr));
949 	}
950 	SHA512Final(digest.bytes, &ctx);
951 	tp->iss = digest.words[0] + iss;
952 	tp->ts_modulate = digest.words[1];
953 }
954 
955 #ifdef TCP_SIGNATURE
956 int
957 tcp_signature_tdb_attach(void)
958 {
959 	return (0);
960 }
961 
962 int
963 tcp_signature_tdb_init(struct tdb *tdbp, const struct xformsw *xsp,
964     struct ipsecinit *ii)
965 {
966 	if ((ii->ii_authkeylen < 1) || (ii->ii_authkeylen > 80))
967 		return (EINVAL);
968 
969 	tdbp->tdb_amxkey = malloc(ii->ii_authkeylen, M_XDATA, M_NOWAIT);
970 	if (tdbp->tdb_amxkey == NULL)
971 		return (ENOMEM);
972 	memcpy(tdbp->tdb_amxkey, ii->ii_authkey, ii->ii_authkeylen);
973 	tdbp->tdb_amxkeylen = ii->ii_authkeylen;
974 
975 	return (0);
976 }
977 
978 int
979 tcp_signature_tdb_zeroize(struct tdb *tdbp)
980 {
981 	if (tdbp->tdb_amxkey) {
982 		explicit_bzero(tdbp->tdb_amxkey, tdbp->tdb_amxkeylen);
983 		free(tdbp->tdb_amxkey, M_XDATA, tdbp->tdb_amxkeylen);
984 		tdbp->tdb_amxkey = NULL;
985 	}
986 
987 	return (0);
988 }
989 
990 int
991 tcp_signature_tdb_input(struct mbuf **mp, struct tdb *tdbp, int skip,
992     int protoff)
993 {
994 	m_freemp(mp);
995 	return (IPPROTO_DONE);
996 }
997 
998 int
999 tcp_signature_tdb_output(struct mbuf *m, struct tdb *tdbp, int skip,
1000     int protoff)
1001 {
1002 	m_freem(m);
1003 	return (EINVAL);
1004 }
1005 
1006 int
1007 tcp_signature_apply(caddr_t fstate, caddr_t data, unsigned int len)
1008 {
1009 	MD5Update((MD5_CTX *)fstate, (char *)data, len);
1010 	return 0;
1011 }
1012 
1013 int
1014 tcp_signature(struct tdb *tdb, int af, struct mbuf *m, struct tcphdr *th,
1015     int iphlen, int doswap, char *sig)
1016 {
1017 	MD5_CTX ctx;
1018 	int len;
1019 	struct tcphdr th0;
1020 
1021 	MD5Init(&ctx);
1022 
1023 	switch(af) {
1024 	case 0:
1025 	case AF_INET: {
1026 		struct ippseudo ippseudo;
1027 		struct ip *ip;
1028 
1029 		ip = mtod(m, struct ip *);
1030 
1031 		ippseudo.ippseudo_src = ip->ip_src;
1032 		ippseudo.ippseudo_dst = ip->ip_dst;
1033 		ippseudo.ippseudo_pad = 0;
1034 		ippseudo.ippseudo_p = IPPROTO_TCP;
1035 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - iphlen);
1036 
1037 		MD5Update(&ctx, (char *)&ippseudo,
1038 		    sizeof(struct ippseudo));
1039 		break;
1040 		}
1041 #ifdef INET6
1042 	case AF_INET6: {
1043 		struct ip6_hdr_pseudo ip6pseudo;
1044 		struct ip6_hdr *ip6;
1045 
1046 		ip6 = mtod(m, struct ip6_hdr *);
1047 		bzero(&ip6pseudo, sizeof(ip6pseudo));
1048 		ip6pseudo.ip6ph_src = ip6->ip6_src;
1049 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
1050 		in6_clearscope(&ip6pseudo.ip6ph_src);
1051 		in6_clearscope(&ip6pseudo.ip6ph_dst);
1052 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
1053 		ip6pseudo.ip6ph_len = htonl(m->m_pkthdr.len - iphlen);
1054 
1055 		MD5Update(&ctx, (char *)&ip6pseudo,
1056 		    sizeof(ip6pseudo));
1057 		break;
1058 		}
1059 #endif
1060 	}
1061 
1062 	th0 = *th;
1063 	th0.th_sum = 0;
1064 
1065 	if (doswap) {
1066 		th0.th_seq = htonl(th0.th_seq);
1067 		th0.th_ack = htonl(th0.th_ack);
1068 		th0.th_win = htons(th0.th_win);
1069 		th0.th_urp = htons(th0.th_urp);
1070 	}
1071 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
1072 
1073 	len = m->m_pkthdr.len - iphlen - th->th_off * sizeof(uint32_t);
1074 
1075 	if (len > 0 &&
1076 	    m_apply(m, iphlen + th->th_off * sizeof(uint32_t), len,
1077 	    tcp_signature_apply, (caddr_t)&ctx))
1078 		return (-1);
1079 
1080 	MD5Update(&ctx, tdb->tdb_amxkey, tdb->tdb_amxkeylen);
1081 	MD5Final(sig, &ctx);
1082 
1083 	return (0);
1084 }
1085 #endif /* TCP_SIGNATURE */
1086