1/*	$OpenBSD: tcp_subr.c,v 1.201 2024/04/17 20:48: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
109struct mutex tcp_timer_mtx = MUTEX_INITIALIZER(IPL_SOFTNET);
110
111/* patchable/settable parameters for tcp */
112int	tcp_mssdflt = TCP_MSS;
113int	tcp_rttdflt = TCPTV_SRTTDFLT;
114
115/* values controllable via sysctl */
116int	tcp_do_rfc1323 = 1;
117int	tcp_do_sack = 1;	/* RFC 2018 selective ACKs */
118int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
119#ifdef TCP_ECN
120int	tcp_do_ecn = 0;		/* RFC3168 ECN enabled/disabled? */
121#endif
122int	tcp_do_rfc3390 = 2;	/* Increase TCP's Initial Window to 10*mss */
123int	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
129int tcp_reass_limit = NMBCLUSTERS / 8; /* hardlimit for tcpqe_pool */
130int tcp_sackhole_limit = 32*1024; /* hardlimit for sackhl_pool */
131
132struct pool tcpcb_pool;
133struct pool tcpqe_pool;
134struct pool sackhl_pool;
135
136struct cpumem *tcpcounters;		/* tcp statistics */
137
138u_char		tcp_secret[16];	/* [I] */
139SHA2_CTX	tcp_secret_ctx;	/* [I] */
140tcp_seq		tcp_iss;	/* [T] updated by timer and connection */
141uint64_t	tcp_starttime;	/* [I] random offset for tcp_now() */
142
143/*
144 * Tcp initialization
145 */
146void
147tcp_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 */
203struct mbuf *
204tcp_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 */
298void
299tcp_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 */
429struct tcpcb *
430tcp_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 = tcp_mssdflt;
441	tp->t_maxopd = 0;
442
443	for (i = 0; i < TCPT_NTIMERS; i++)
444		TCP_TIMER_INIT(tp, i);
445
446	tp->sack_enable = tcp_do_sack;
447	tp->t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
448	tp->t_inpcb = inp;
449	/*
450	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
451	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
452	 * reasonable initial retransmit time.
453	 */
454	tp->t_srtt = TCPTV_SRTTBASE;
455	tp->t_rttvar = tcp_rttdflt <<
456	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT - 1);
457	tp->t_rttmin = TCPTV_MIN;
458	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
459	    TCPTV_MIN, TCPTV_REXMTMAX);
460	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
461	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
462
463	tp->t_pmtud_mtu_sent = 0;
464	tp->t_pmtud_mss_acked = 0;
465
466#ifdef INET6
467	if (ISSET(inp->inp_flags, INP_IPV6)) {
468		tp->pf = PF_INET6;
469		inp->inp_ipv6.ip6_hlim = ip6_defhlim;
470	} else
471#endif
472	{
473		tp->pf = PF_INET;
474		inp->inp_ip.ip_ttl = ip_defttl;
475	}
476
477	inp->inp_ppcb = (caddr_t)tp;
478	return (tp);
479}
480
481/*
482 * Drop a TCP connection, reporting
483 * the specified error.  If connection is synchronized,
484 * then send a RST to peer.
485 */
486struct tcpcb *
487tcp_drop(struct tcpcb *tp, int errno)
488{
489	struct socket *so = tp->t_inpcb->inp_socket;
490
491	if (TCPS_HAVERCVDSYN(tp->t_state)) {
492		tp->t_state = TCPS_CLOSED;
493		(void) tcp_output(tp);
494		tcpstat_inc(tcps_drops);
495	} else
496		tcpstat_inc(tcps_conndrops);
497	if (errno == ETIMEDOUT && tp->t_softerror)
498		errno = tp->t_softerror;
499	so->so_error = errno;
500	return (tcp_close(tp));
501}
502
503/*
504 * Close a TCP control block:
505 *	discard all space held by the tcp
506 *	discard internet protocol block
507 *	wake up any sleepers
508 */
509struct tcpcb *
510tcp_close(struct tcpcb *tp)
511{
512	struct inpcb *inp = tp->t_inpcb;
513	struct socket *so = inp->inp_socket;
514	struct sackhole *p, *q;
515
516	/* free the reassembly queue, if any */
517	tcp_freeq(tp);
518
519	tcp_canceltimers(tp);
520	syn_cache_cleanup(tp);
521
522	/* Free SACK holes. */
523	q = p = tp->snd_holes;
524	while (p != 0) {
525		q = p->next;
526		pool_put(&sackhl_pool, p);
527		p = q;
528	}
529
530	m_free(tp->t_template);
531	/* Free tcpcb after all pending timers have been run. */
532	TCP_TIMER_ARM(tp, TCPT_REAPER, 1);
533
534	inp->inp_ppcb = NULL;
535	soisdisconnected(so);
536	in_pcbdetach(inp);
537	return (NULL);
538}
539
540int
541tcp_freeq(struct tcpcb *tp)
542{
543	struct tcpqent *qe;
544	int rv = 0;
545
546	while ((qe = TAILQ_FIRST(&tp->t_segq)) != NULL) {
547		TAILQ_REMOVE(&tp->t_segq, qe, tcpqe_q);
548		m_freem(qe->tcpqe_m);
549		pool_put(&tcpqe_pool, qe);
550		rv = 1;
551	}
552	return (rv);
553}
554
555/*
556 * Compute proper scaling value for receiver window from buffer space
557 */
558
559void
560tcp_rscale(struct tcpcb *tp, u_long hiwat)
561{
562	tp->request_r_scale = 0;
563	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
564	       TCP_MAXWIN << tp->request_r_scale < hiwat)
565		tp->request_r_scale++;
566}
567
568/*
569 * Notify a tcp user of an asynchronous error;
570 * store error as soft error, but wake up user
571 * (for now, won't do anything until can select for soft error).
572 */
573void
574tcp_notify(struct inpcb *inp, int error)
575{
576	struct tcpcb *tp = intotcpcb(inp);
577	struct socket *so = inp->inp_socket;
578
579	/*
580	 * Ignore some errors if we are hooked up.
581	 * If connection hasn't completed, has retransmitted several times,
582	 * and receives a second error, give up now.  This is better
583	 * than waiting a long time to establish a connection that
584	 * can never complete.
585	 */
586	if (tp->t_state == TCPS_ESTABLISHED &&
587	     (error == EHOSTUNREACH || error == ENETUNREACH ||
588	      error == EHOSTDOWN)) {
589		return;
590	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
591	    tp->t_rxtshift > 3 && tp->t_softerror)
592		so->so_error = error;
593	else
594		tp->t_softerror = error;
595	wakeup((caddr_t) &so->so_timeo);
596	sorwakeup(so);
597	sowwakeup(so);
598}
599
600#ifdef INET6
601void
602tcp6_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *d)
603{
604	struct tcphdr th;
605	struct tcpcb *tp;
606	void (*notify)(struct inpcb *, int) = tcp_notify;
607	struct ip6_hdr *ip6;
608	const struct sockaddr_in6 *sa6_src = NULL;
609	struct sockaddr_in6 *sa6 = satosin6(sa);
610	struct inpcb *inp;
611	struct mbuf *m;
612	tcp_seq seq;
613	int off;
614	struct {
615		u_int16_t th_sport;
616		u_int16_t th_dport;
617		u_int32_t th_seq;
618	} *thp;
619
620	CTASSERT(sizeof(*thp) <= sizeof(th));
621	if (sa->sa_family != AF_INET6 ||
622	    sa->sa_len != sizeof(struct sockaddr_in6) ||
623	    IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
624	    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
625		return;
626	if ((unsigned)cmd >= PRC_NCMDS)
627		return;
628	else if (cmd == PRC_QUENCH) {
629		/*
630		 * Don't honor ICMP Source Quench messages meant for
631		 * TCP connections.
632		 */
633		/* XXX there's no PRC_QUENCH in IPv6 */
634		return;
635	} else if (PRC_IS_REDIRECT(cmd))
636		notify = in_rtchange, d = NULL;
637	else if (cmd == PRC_MSGSIZE)
638		; /* special code is present, see below */
639	else if (cmd == PRC_HOSTDEAD)
640		d = NULL;
641	else if (inet6ctlerrmap[cmd] == 0)
642		return;
643
644	/* if the parameter is from icmp6, decode it. */
645	if (d != NULL) {
646		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
647		m = ip6cp->ip6c_m;
648		ip6 = ip6cp->ip6c_ip6;
649		off = ip6cp->ip6c_off;
650		sa6_src = ip6cp->ip6c_src;
651	} else {
652		m = NULL;
653		ip6 = NULL;
654		sa6_src = &sa6_any;
655	}
656
657	if (ip6) {
658		/*
659		 * XXX: We assume that when ip6 is non NULL,
660		 * M and OFF are valid.
661		 */
662
663		/* check if we can safely examine src and dst ports */
664		if (m->m_pkthdr.len < off + sizeof(*thp))
665			return;
666
667		bzero(&th, sizeof(th));
668		m_copydata(m, off, sizeof(*thp), &th);
669
670		/*
671		 * Check to see if we have a valid TCP connection
672		 * corresponding to the address in the ICMPv6 message
673		 * payload.
674		 */
675		inp = in6_pcblookup(&tcb6table, &sa6->sin6_addr,
676		    th.th_dport, &sa6_src->sin6_addr, th.th_sport, rdomain);
677		if (cmd == PRC_MSGSIZE) {
678			/*
679			 * Depending on the value of "valid" and routing table
680			 * size (mtudisc_{hi,lo}wat), we will:
681			 * - recalculate the new MTU and create the
682			 *   corresponding routing entry, or
683			 * - ignore the MTU change notification.
684			 */
685			icmp6_mtudisc_update((struct ip6ctlparam *)d,
686			    inp != NULL);
687			in_pcbunref(inp);
688			return;
689		}
690		if (inp) {
691			seq = ntohl(th.th_seq);
692			if ((tp = intotcpcb(inp)) &&
693			    SEQ_GEQ(seq, tp->snd_una) &&
694			    SEQ_LT(seq, tp->snd_max))
695				notify(inp, inet6ctlerrmap[cmd]);
696		} else if (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
697		    inet6ctlerrmap[cmd] == ENETUNREACH ||
698		    inet6ctlerrmap[cmd] == EHOSTDOWN)
699			syn_cache_unreach(sin6tosa_const(sa6_src), sa, &th,
700			    rdomain);
701		in_pcbunref(inp);
702	} else {
703		in6_pcbnotify(&tcb6table, sa6, 0,
704		    sa6_src, 0, rdomain, cmd, NULL, notify);
705	}
706}
707#endif
708
709void
710tcp_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
711{
712	struct ip *ip = v;
713	struct tcphdr *th;
714	struct tcpcb *tp;
715	struct inpcb *inp;
716	struct in_addr faddr;
717	tcp_seq seq;
718	u_int mtu;
719	void (*notify)(struct inpcb *, int) = tcp_notify;
720	int errno;
721
722	if (sa->sa_family != AF_INET)
723		return;
724	faddr = satosin(sa)->sin_addr;
725	if (faddr.s_addr == INADDR_ANY)
726		return;
727
728	if ((unsigned)cmd >= PRC_NCMDS)
729		return;
730	errno = inetctlerrmap[cmd];
731	if (cmd == PRC_QUENCH)
732		/*
733		 * Don't honor ICMP Source Quench messages meant for
734		 * TCP connections.
735		 */
736		return;
737	else if (PRC_IS_REDIRECT(cmd))
738		notify = in_rtchange, ip = 0;
739	else if (cmd == PRC_MSGSIZE && ip_mtudisc && ip) {
740		/*
741		 * Verify that the packet in the icmp payload refers
742		 * to an existing TCP connection.
743		 */
744		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
745		seq = ntohl(th->th_seq);
746		inp = in_pcblookup(&tcbtable,
747		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
748		    rdomain);
749		if (inp && (tp = intotcpcb(inp)) &&
750		    SEQ_GEQ(seq, tp->snd_una) &&
751		    SEQ_LT(seq, tp->snd_max)) {
752			struct icmp *icp;
753			icp = (struct icmp *)((caddr_t)ip -
754					      offsetof(struct icmp, icmp_ip));
755
756			/*
757			 * If the ICMP message advertises a Next-Hop MTU
758			 * equal or larger than the maximum packet size we have
759			 * ever sent, drop the message.
760			 */
761			mtu = (u_int)ntohs(icp->icmp_nextmtu);
762			if (mtu >= tp->t_pmtud_mtu_sent) {
763				in_pcbunref(inp);
764				return;
765			}
766			if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
767				/*
768				 * Calculate new MTU, and create corresponding
769				 * route (traditional PMTUD).
770				 */
771				tp->t_flags &= ~TF_PMTUD_PEND;
772				icmp_mtudisc(icp, inp->inp_rtableid);
773			} else {
774				/*
775				 * Record the information got in the ICMP
776				 * message; act on it later.
777				 * If we had already recorded an ICMP message,
778				 * replace the old one only if the new message
779				 * refers to an older TCP segment
780				 */
781				if (tp->t_flags & TF_PMTUD_PEND) {
782					if (SEQ_LT(tp->t_pmtud_th_seq, seq)) {
783						in_pcbunref(inp);
784						return;
785					}
786				} else
787					tp->t_flags |= TF_PMTUD_PEND;
788				tp->t_pmtud_th_seq = seq;
789				tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
790				tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
791				tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
792				in_pcbunref(inp);
793				return;
794			}
795		} else {
796			/* ignore if we don't have a matching connection */
797			in_pcbunref(inp);
798			return;
799		}
800		in_pcbunref(inp);
801		notify = tcp_mtudisc, ip = 0;
802	} else if (cmd == PRC_MTUINC)
803		notify = tcp_mtudisc_increase, ip = 0;
804	else if (cmd == PRC_HOSTDEAD)
805		ip = 0;
806	else if (errno == 0)
807		return;
808
809	if (ip) {
810		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
811		inp = in_pcblookup(&tcbtable,
812		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
813		    rdomain);
814		if (inp) {
815			seq = ntohl(th->th_seq);
816			if ((tp = intotcpcb(inp)) &&
817			    SEQ_GEQ(seq, tp->snd_una) &&
818			    SEQ_LT(seq, tp->snd_max))
819				notify(inp, errno);
820		} else if (inetctlerrmap[cmd] == EHOSTUNREACH ||
821		    inetctlerrmap[cmd] == ENETUNREACH ||
822		    inetctlerrmap[cmd] == EHOSTDOWN) {
823			struct sockaddr_in sin;
824
825			bzero(&sin, sizeof(sin));
826			sin.sin_len = sizeof(sin);
827			sin.sin_family = AF_INET;
828			sin.sin_port = th->th_sport;
829			sin.sin_addr = ip->ip_src;
830			syn_cache_unreach(sintosa(&sin), sa, th, rdomain);
831		}
832		in_pcbunref(inp);
833	} else
834		in_pcbnotifyall(&tcbtable, satosin(sa), rdomain, errno, notify);
835}
836
837
838#ifdef INET6
839/*
840 * Path MTU Discovery handlers.
841 */
842void
843tcp6_mtudisc_callback(struct sockaddr_in6 *sin6, u_int rdomain)
844{
845	in6_pcbnotify(&tcb6table, sin6, 0,
846	    &sa6_any, 0, rdomain, PRC_MSGSIZE, NULL, tcp_mtudisc);
847}
848#endif /* INET6 */
849
850/*
851 * On receipt of path MTU corrections, flush old route and replace it
852 * with the new one.  Retransmit all unacknowledged packets, to ensure
853 * that all packets will be received.
854 */
855void
856tcp_mtudisc(struct inpcb *inp, int errno)
857{
858	struct tcpcb *tp = intotcpcb(inp);
859	struct rtentry *rt;
860	int orig_maxseg, change = 0;
861
862	if (tp == NULL)
863		return;
864	orig_maxseg = tp->t_maxseg;
865
866	rt = in_pcbrtentry(inp);
867	if (rt != NULL) {
868		unsigned int orig_mtulock = (rt->rt_locks & RTV_MTU);
869
870		/*
871		 * If this was not a host route, remove and realloc.
872		 */
873		if ((rt->rt_flags & RTF_HOST) == 0) {
874			in_rtchange(inp, errno);
875			if ((rt = in_pcbrtentry(inp)) == NULL)
876				return;
877		}
878		if (orig_mtulock < (rt->rt_locks & RTV_MTU))
879			change = 1;
880	}
881	tcp_mss(tp, -1);
882	if (orig_maxseg > tp->t_maxseg)
883		change = 1;
884
885	/*
886	 * Resend unacknowledged packets
887	 */
888	tp->snd_nxt = tp->snd_una;
889	if (change || errno > 0)
890		tcp_output(tp);
891}
892
893void
894tcp_mtudisc_increase(struct inpcb *inp, int errno)
895{
896	struct tcpcb *tp = intotcpcb(inp);
897	struct rtentry *rt = in_pcbrtentry(inp);
898
899	if (tp != 0 && rt != 0) {
900		/*
901		 * If this was a host route, remove and realloc.
902		 */
903		if (rt->rt_flags & RTF_HOST)
904			in_rtchange(inp, errno);
905
906		/* also takes care of congestion window */
907		tcp_mss(tp, -1);
908	}
909}
910
911/*
912 * Generate new ISNs with a method based on RFC1948
913 */
914#define TCP_ISS_CONN_INC 4096
915
916void
917tcp_set_iss_tsm(struct tcpcb *tp)
918{
919	SHA2_CTX ctx;
920	union {
921		uint8_t bytes[SHA512_DIGEST_LENGTH];
922		uint32_t words[2];
923	} digest;
924	u_int rdomain = rtable_l2(tp->t_inpcb->inp_rtableid);
925	tcp_seq iss;
926
927	mtx_enter(&tcp_timer_mtx);
928	tcp_iss += TCP_ISS_CONN_INC;
929	iss = tcp_iss;
930	mtx_leave(&tcp_timer_mtx);
931
932	ctx = tcp_secret_ctx;
933	SHA512Update(&ctx, &rdomain, sizeof(rdomain));
934	SHA512Update(&ctx, &tp->t_inpcb->inp_lport, sizeof(u_short));
935	SHA512Update(&ctx, &tp->t_inpcb->inp_fport, sizeof(u_short));
936	if (tp->pf == AF_INET6) {
937		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr6,
938		    sizeof(struct in6_addr));
939		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr6,
940		    sizeof(struct in6_addr));
941	} else {
942		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr,
943		    sizeof(struct in_addr));
944		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr,
945		    sizeof(struct in_addr));
946	}
947	SHA512Final(digest.bytes, &ctx);
948	tp->iss = digest.words[0] + iss;
949	tp->ts_modulate = digest.words[1];
950}
951
952#ifdef TCP_SIGNATURE
953int
954tcp_signature_tdb_attach(void)
955{
956	return (0);
957}
958
959int
960tcp_signature_tdb_init(struct tdb *tdbp, const struct xformsw *xsp,
961    struct ipsecinit *ii)
962{
963	if ((ii->ii_authkeylen < 1) || (ii->ii_authkeylen > 80))
964		return (EINVAL);
965
966	tdbp->tdb_amxkey = malloc(ii->ii_authkeylen, M_XDATA, M_NOWAIT);
967	if (tdbp->tdb_amxkey == NULL)
968		return (ENOMEM);
969	memcpy(tdbp->tdb_amxkey, ii->ii_authkey, ii->ii_authkeylen);
970	tdbp->tdb_amxkeylen = ii->ii_authkeylen;
971
972	return (0);
973}
974
975int
976tcp_signature_tdb_zeroize(struct tdb *tdbp)
977{
978	if (tdbp->tdb_amxkey) {
979		explicit_bzero(tdbp->tdb_amxkey, tdbp->tdb_amxkeylen);
980		free(tdbp->tdb_amxkey, M_XDATA, tdbp->tdb_amxkeylen);
981		tdbp->tdb_amxkey = NULL;
982	}
983
984	return (0);
985}
986
987int
988tcp_signature_tdb_input(struct mbuf **mp, struct tdb *tdbp, int skip,
989    int protoff)
990{
991	m_freemp(mp);
992	return (IPPROTO_DONE);
993}
994
995int
996tcp_signature_tdb_output(struct mbuf *m, struct tdb *tdbp, int skip,
997    int protoff)
998{
999	m_freem(m);
1000	return (EINVAL);
1001}
1002
1003int
1004tcp_signature_apply(caddr_t fstate, caddr_t data, unsigned int len)
1005{
1006	MD5Update((MD5_CTX *)fstate, (char *)data, len);
1007	return 0;
1008}
1009
1010int
1011tcp_signature(struct tdb *tdb, int af, struct mbuf *m, struct tcphdr *th,
1012    int iphlen, int doswap, char *sig)
1013{
1014	MD5_CTX ctx;
1015	int len;
1016	struct tcphdr th0;
1017
1018	MD5Init(&ctx);
1019
1020	switch(af) {
1021	case 0:
1022	case AF_INET: {
1023		struct ippseudo ippseudo;
1024		struct ip *ip;
1025
1026		ip = mtod(m, struct ip *);
1027
1028		ippseudo.ippseudo_src = ip->ip_src;
1029		ippseudo.ippseudo_dst = ip->ip_dst;
1030		ippseudo.ippseudo_pad = 0;
1031		ippseudo.ippseudo_p = IPPROTO_TCP;
1032		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - iphlen);
1033
1034		MD5Update(&ctx, (char *)&ippseudo,
1035		    sizeof(struct ippseudo));
1036		break;
1037		}
1038#ifdef INET6
1039	case AF_INET6: {
1040		struct ip6_hdr_pseudo ip6pseudo;
1041		struct ip6_hdr *ip6;
1042
1043		ip6 = mtod(m, struct ip6_hdr *);
1044		bzero(&ip6pseudo, sizeof(ip6pseudo));
1045		ip6pseudo.ip6ph_src = ip6->ip6_src;
1046		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
1047		in6_clearscope(&ip6pseudo.ip6ph_src);
1048		in6_clearscope(&ip6pseudo.ip6ph_dst);
1049		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
1050		ip6pseudo.ip6ph_len = htonl(m->m_pkthdr.len - iphlen);
1051
1052		MD5Update(&ctx, (char *)&ip6pseudo,
1053		    sizeof(ip6pseudo));
1054		break;
1055		}
1056#endif
1057	}
1058
1059	th0 = *th;
1060	th0.th_sum = 0;
1061
1062	if (doswap) {
1063		th0.th_seq = htonl(th0.th_seq);
1064		th0.th_ack = htonl(th0.th_ack);
1065		th0.th_win = htons(th0.th_win);
1066		th0.th_urp = htons(th0.th_urp);
1067	}
1068	MD5Update(&ctx, (char *)&th0, sizeof(th0));
1069
1070	len = m->m_pkthdr.len - iphlen - th->th_off * sizeof(uint32_t);
1071
1072	if (len > 0 &&
1073	    m_apply(m, iphlen + th->th_off * sizeof(uint32_t), len,
1074	    tcp_signature_apply, (caddr_t)&ctx))
1075		return (-1);
1076
1077	MD5Update(&ctx, tdb->tdb_amxkey, tdb->tdb_amxkeylen);
1078	MD5Final(sig, &ctx);
1079
1080	return (0);
1081}
1082#endif /* TCP_SIGNATURE */
1083