xref: /openbsd-src/sys/netinet/tcp_subr.c (revision 0b7734b3d77bb9b21afec6f4621cae6c805dbd45)
1 /*	$OpenBSD: tcp_subr.c,v 1.151 2016/03/07 18:44:00 naddy 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/socket.h>
75 #include <sys/socketvar.h>
76 #include <sys/timeout.h>
77 #include <sys/protosw.h>
78 #include <sys/kernel.h>
79 #include <sys/pool.h>
80 
81 #include <net/route.h>
82 
83 #include <netinet/in.h>
84 #include <netinet/ip.h>
85 #include <netinet/in_pcb.h>
86 #include <netinet/ip_var.h>
87 #include <netinet/ip_icmp.h>
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/tcpip.h>
94 
95 #ifdef INET6
96 #include <netinet6/ip6protosw.h>
97 #endif /* INET6 */
98 
99 #include <crypto/md5.h>
100 #include <crypto/sha2.h>
101 
102 /* patchable/settable parameters for tcp */
103 int	tcp_mssdflt = TCP_MSS;
104 int	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
105 
106 /* values controllable via sysctl */
107 int	tcp_do_rfc1323 = 1;
108 #ifdef TCP_SACK
109 int	tcp_do_sack = 1;	/* RFC 2018 selective ACKs */
110 #endif
111 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
112 #ifdef TCP_ECN
113 int	tcp_do_ecn = 0;		/* RFC3168 ECN enabled/disabled? */
114 #endif
115 int	tcp_do_rfc3390 = 2;	/* Increase TCP's Initial Window to 10*mss */
116 
117 u_int32_t	tcp_now = 1;
118 
119 #ifndef TCB_INITIAL_HASH_SIZE
120 #define	TCB_INITIAL_HASH_SIZE	128
121 #endif
122 
123 int tcp_reass_limit = NMBCLUSTERS / 2; /* hardlimit for tcpqe_pool */
124 #ifdef TCP_SACK
125 int tcp_sackhole_limit = 32*1024; /* hardlimit for sackhl_pool */
126 #endif
127 
128 struct pool tcpcb_pool;
129 struct pool tcpqe_pool;
130 #ifdef TCP_SACK
131 struct pool sackhl_pool;
132 #endif
133 
134 struct tcpstat tcpstat;		/* tcp statistics */
135 tcp_seq  tcp_iss;
136 
137 /*
138  * Tcp initialization
139  */
140 void
141 tcp_init(void)
142 {
143 	tcp_iss = 1;		/* wrong */
144 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcb", NULL);
145 	pool_init(&tcpqe_pool, sizeof(struct tcpqent), 0, 0, 0, "tcpqe", NULL);
146 	pool_sethardlimit(&tcpqe_pool, tcp_reass_limit, NULL, 0);
147 #ifdef TCP_SACK
148 	pool_init(&sackhl_pool, sizeof(struct sackhole), 0, 0, 0, "sackhl",
149 	    NULL);
150 	pool_sethardlimit(&sackhl_pool, tcp_sackhole_limit, NULL, 0);
151 #endif /* TCP_SACK */
152 	in_pcbinit(&tcbtable, TCB_INITIAL_HASH_SIZE);
153 
154 #ifdef INET6
155 	/*
156 	 * Since sizeof(struct ip6_hdr) > sizeof(struct ip), we
157 	 * do max length checks/computations only on the former.
158 	 */
159 	if (max_protohdr < (sizeof(struct ip6_hdr) + sizeof(struct tcphdr)))
160 		max_protohdr = (sizeof(struct ip6_hdr) + sizeof(struct tcphdr));
161 	if ((max_linkhdr + sizeof(struct ip6_hdr) + sizeof(struct tcphdr)) >
162 	    MHLEN)
163 		panic("tcp_init");
164 
165 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
166 #endif /* INET6 */
167 
168 	/* Initialize the compressed state engine. */
169 	syn_cache_init();
170 
171 	/* Initialize timer state. */
172 	tcp_timer_init();
173 }
174 
175 /*
176  * Create template to be used to send tcp packets on a connection.
177  * Call after host entry created, allocates an mbuf and fills
178  * in a skeletal tcp/ip header, minimizing the amount of work
179  * necessary when the connection is used.
180  *
181  * To support IPv6 in addition to IPv4 and considering that the sizes of
182  * the IPv4 and IPv6 headers are not the same, we now use a separate pointer
183  * for the TCP header.  Also, we made the former tcpiphdr header pointer
184  * into just an IP overlay pointer, with casting as appropriate for v6. rja
185  */
186 struct mbuf *
187 tcp_template(tp)
188 	struct tcpcb *tp;
189 {
190 	struct inpcb *inp = tp->t_inpcb;
191 	struct mbuf *m;
192 	struct tcphdr *th;
193 
194 	if ((m = tp->t_template) == 0) {
195 		m = m_get(M_DONTWAIT, MT_HEADER);
196 		if (m == NULL)
197 			return (0);
198 
199 		switch (tp->pf) {
200 		case 0:	/*default to PF_INET*/
201 		case AF_INET:
202 			m->m_len = sizeof(struct ip);
203 			break;
204 #ifdef INET6
205 		case AF_INET6:
206 			m->m_len = sizeof(struct ip6_hdr);
207 			break;
208 #endif /* INET6 */
209 		}
210 		m->m_len += sizeof (struct tcphdr);
211 
212 		/*
213 		 * The link header, network header, TCP header, and TCP options
214 		 * all must fit in this mbuf. For now, assume the worst case of
215 		 * TCP options size. Eventually, compute this from tp flags.
216 		 */
217 		if (m->m_len + MAX_TCPOPTLEN + max_linkhdr >= MHLEN) {
218 			MCLGET(m, M_DONTWAIT);
219 			if ((m->m_flags & M_EXT) == 0) {
220 				m_free(m);
221 				return (0);
222 			}
223 		}
224 	}
225 
226 	switch(tp->pf) {
227 	case AF_INET:
228 		{
229 			struct ipovly *ipovly;
230 
231 			ipovly = mtod(m, struct ipovly *);
232 
233 			bzero(ipovly->ih_x1, sizeof ipovly->ih_x1);
234 			ipovly->ih_pr = IPPROTO_TCP;
235 			ipovly->ih_len = htons(sizeof (struct tcphdr));
236 			ipovly->ih_src = inp->inp_laddr;
237 			ipovly->ih_dst = inp->inp_faddr;
238 
239 			th = (struct tcphdr *)(mtod(m, caddr_t) +
240 				sizeof(struct ip));
241 		}
242 		break;
243 #ifdef INET6
244 	case AF_INET6:
245 		{
246 			struct ip6_hdr *ip6;
247 
248 			ip6 = mtod(m, struct ip6_hdr *);
249 
250 			ip6->ip6_src = inp->inp_laddr6;
251 			ip6->ip6_dst = inp->inp_faddr6;
252 			ip6->ip6_flow = htonl(0x60000000) |
253 			    (inp->inp_flowinfo & IPV6_FLOWLABEL_MASK);
254 
255 			ip6->ip6_nxt = IPPROTO_TCP;
256 			ip6->ip6_plen = htons(sizeof(struct tcphdr)); /*XXX*/
257 			ip6->ip6_hlim = in6_selecthlim(inp);	/*XXX*/
258 
259 			th = (struct tcphdr *)(mtod(m, caddr_t) +
260 				sizeof(struct ip6_hdr));
261 		}
262 		break;
263 #endif /* INET6 */
264 	}
265 
266 	th->th_sport = inp->inp_lport;
267 	th->th_dport = inp->inp_fport;
268 	th->th_seq = 0;
269 	th->th_ack = 0;
270 	th->th_x2  = 0;
271 	th->th_off = 5;
272 	th->th_flags = 0;
273 	th->th_win = 0;
274 	th->th_urp = 0;
275 	th->th_sum = 0;
276 	return (m);
277 }
278 
279 /*
280  * Send a single message to the TCP at address specified by
281  * the given TCP/IP header.  If m == 0, then we make a copy
282  * of the tcpiphdr at ti and send directly to the addressed host.
283  * This is used to force keep alive messages out using the TCP
284  * template for a connection tp->t_template.  If flags are given
285  * then we send a message back to the TCP which originated the
286  * segment ti, and discard the mbuf containing it and any other
287  * attached mbufs.
288  *
289  * In any case the ack and sequence number of the transmitted
290  * segment are as specified by the parameters.
291  */
292 void
293 tcp_respond(struct tcpcb *tp, caddr_t template, struct tcphdr *th0,
294     tcp_seq ack, tcp_seq seq, int flags, u_int rtableid)
295 {
296 	int tlen;
297 	int win = 0;
298 	struct mbuf *m = NULL;
299 	struct route *ro = NULL;
300 	struct tcphdr *th;
301 	struct ip *ip;
302 #ifdef INET6
303 	struct ip6_hdr *ip6;
304 #endif
305 	int af;		/* af on wire */
306 
307 	if (tp) {
308 		win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
309 		/*
310 		 * If this is called with an unconnected
311 		 * socket/tp/pcb (tp->pf is 0), we lose.
312 		 */
313 		af = tp->pf;
314 
315 		/*
316 		 * The route/route6 distinction is meaningless
317 		 * unless you're allocating space or passing parameters.
318 		 */
319 		ro = &tp->t_inpcb->inp_route;
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(tcp_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 		    (struct route_in6 *)ro, 0, NULL,
408 		    tp ? tp->t_inpcb : NULL);
409 		break;
410 #endif /* INET6 */
411 	case AF_INET:
412 		ip->ip_len = htons(tlen);
413 		ip->ip_ttl = ip_defttl;
414 		ip->ip_tos = 0;
415 		ip_output(m, NULL, ro, ip_mtudisc ? IP_MTUDISC : 0,
416 		    NULL, tp ? tp->t_inpcb : NULL, 0);
417 	}
418 }
419 
420 /*
421  * Create a new TCP control block, making an
422  * empty reassembly queue and hooking it to the argument
423  * protocol control block.
424  */
425 struct tcpcb *
426 tcp_newtcpcb(struct inpcb *inp)
427 {
428 	struct tcpcb *tp;
429 	int i;
430 
431 	tp = pool_get(&tcpcb_pool, PR_NOWAIT|PR_ZERO);
432 	if (tp == NULL)
433 		return (NULL);
434 	TAILQ_INIT(&tp->t_segq);
435 	tp->t_maxseg = tcp_mssdflt;
436 	tp->t_maxopd = 0;
437 
438 	TCP_INIT_DELACK(tp);
439 	for (i = 0; i < TCPT_NTIMERS; i++)
440 		TCP_TIMER_INIT(tp, i);
441 	timeout_set(&tp->t_reap_to, tcp_reaper, tp);
442 
443 #ifdef TCP_SACK
444 	tp->sack_enable = tcp_do_sack;
445 #endif
446 	tp->t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
447 	tp->t_inpcb = inp;
448 	/*
449 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
450 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
451 	 * reasonable initial retransmit time.
452 	 */
453 	tp->t_srtt = TCPTV_SRTTBASE;
454 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ <<
455 	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT - 1);
456 	tp->t_rttmin = TCPTV_MIN;
457 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
458 	    TCPTV_MIN, TCPTV_REXMTMAX);
459 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
460 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
461 
462 	tp->t_pmtud_mtu_sent = 0;
463 	tp->t_pmtud_mss_acked = 0;
464 
465 #ifdef INET6
466 	/* we disallow IPv4 mapped address completely. */
467 	if ((inp->inp_flags & INP_IPV6) == 0)
468 		tp->pf = PF_INET;
469 	else
470 		tp->pf = PF_INET6;
471 #else
472 	tp->pf = PF_INET;
473 #endif
474 
475 #ifdef INET6
476 	if (inp->inp_flags & INP_IPV6)
477 		inp->inp_ipv6.ip6_hlim = ip6_defhlim;
478 	else
479 #endif /* INET6 */
480 		inp->inp_ip.ip_ttl = ip_defttl;
481 
482 	inp->inp_ppcb = (caddr_t)tp;
483 	return (tp);
484 }
485 
486 /*
487  * Drop a TCP connection, reporting
488  * the specified error.  If connection is synchronized,
489  * then send a RST to peer.
490  */
491 struct tcpcb *
492 tcp_drop(tp, errno)
493 	struct tcpcb *tp;
494 	int errno;
495 {
496 	struct socket *so = tp->t_inpcb->inp_socket;
497 
498 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
499 		tp->t_state = TCPS_CLOSED;
500 		(void) tcp_output(tp);
501 		tcpstat.tcps_drops++;
502 	} else
503 		tcpstat.tcps_conndrops++;
504 	if (errno == ETIMEDOUT && tp->t_softerror)
505 		errno = tp->t_softerror;
506 	so->so_error = errno;
507 	return (tcp_close(tp));
508 }
509 
510 /*
511  * Close a TCP control block:
512  *	discard all space held by the tcp
513  *	discard internet protocol block
514  *	wake up any sleepers
515  */
516 struct tcpcb *
517 tcp_close(struct tcpcb *tp)
518 {
519 	struct inpcb *inp = tp->t_inpcb;
520 	struct socket *so = inp->inp_socket;
521 #ifdef TCP_SACK
522 	struct sackhole *p, *q;
523 #endif
524 
525 	/* free the reassembly queue, if any */
526 	tcp_freeq(tp);
527 
528 	tcp_canceltimers(tp);
529 	TCP_CLEAR_DELACK(tp);
530 	syn_cache_cleanup(tp);
531 
532 #ifdef TCP_SACK
533 	/* Free SACK holes. */
534 	q = p = tp->snd_holes;
535 	while (p != 0) {
536 		q = p->next;
537 		pool_put(&sackhl_pool, p);
538 		p = q;
539 	}
540 #endif
541 	if (tp->t_template)
542 		(void) m_free(tp->t_template);
543 
544 	tp->t_flags |= TF_DEAD;
545 	timeout_add(&tp->t_reap_to, 0);
546 
547 	inp->inp_ppcb = 0;
548 	soisdisconnected(so);
549 	in_pcbdetach(inp);
550 	return (NULL);
551 }
552 
553 void
554 tcp_reaper(void *arg)
555 {
556 	struct tcpcb *tp = arg;
557 	int s;
558 
559 	s = splsoftnet();
560 	pool_put(&tcpcb_pool, tp);
561 	splx(s);
562 	tcpstat.tcps_closed++;
563 }
564 
565 int
566 tcp_freeq(struct tcpcb *tp)
567 {
568 	struct tcpqent *qe;
569 	int rv = 0;
570 
571 	while ((qe = TAILQ_FIRST(&tp->t_segq)) != NULL) {
572 		TAILQ_REMOVE(&tp->t_segq, qe, tcpqe_q);
573 		m_freem(qe->tcpqe_m);
574 		pool_put(&tcpqe_pool, qe);
575 		rv = 1;
576 	}
577 	return (rv);
578 }
579 
580 /*
581  * Compute proper scaling value for receiver window from buffer space
582  */
583 
584 void
585 tcp_rscale(struct tcpcb *tp, u_long hiwat)
586 {
587 	tp->request_r_scale = 0;
588 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
589 	       TCP_MAXWIN << tp->request_r_scale < hiwat)
590 		tp->request_r_scale++;
591 }
592 
593 /*
594  * Notify a tcp user of an asynchronous error;
595  * store error as soft error, but wake up user
596  * (for now, won't do anything until can select for soft error).
597  */
598 void
599 tcp_notify(inp, error)
600 	struct inpcb *inp;
601 	int error;
602 {
603 	struct tcpcb *tp = intotcpcb(inp);
604 	struct socket *so = inp->inp_socket;
605 
606 	/*
607 	 * Ignore some errors if we are hooked up.
608 	 * If connection hasn't completed, has retransmitted several times,
609 	 * and receives a second error, give up now.  This is better
610 	 * than waiting a long time to establish a connection that
611 	 * can never complete.
612 	 */
613 	if (tp->t_state == TCPS_ESTABLISHED &&
614 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
615 	      error == EHOSTDOWN)) {
616 		return;
617 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
618 	    tp->t_rxtshift > 3 && tp->t_softerror)
619 		so->so_error = error;
620 	else
621 		tp->t_softerror = error;
622 	wakeup((caddr_t) &so->so_timeo);
623 	sorwakeup(so);
624 	sowwakeup(so);
625 }
626 
627 #ifdef INET6
628 void
629 tcp6_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *d)
630 {
631 	struct tcphdr th;
632 	struct tcpcb *tp;
633 	void (*notify)(struct inpcb *, int) = tcp_notify;
634 	struct ip6_hdr *ip6;
635 	const struct sockaddr_in6 *sa6_src = NULL;
636 	struct sockaddr_in6 *sa6 = satosin6(sa);
637 	struct inpcb *inp;
638 	struct mbuf *m;
639 	tcp_seq seq;
640 	int off;
641 	struct {
642 		u_int16_t th_sport;
643 		u_int16_t th_dport;
644 		u_int32_t th_seq;
645 	} *thp;
646 
647 	if (sa->sa_family != AF_INET6 ||
648 	    sa->sa_len != sizeof(struct sockaddr_in6) ||
649 	    IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
650 	    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
651 		return;
652 	if ((unsigned)cmd >= PRC_NCMDS)
653 		return;
654 	else if (cmd == PRC_QUENCH) {
655 		/*
656 		 * Don't honor ICMP Source Quench messages meant for
657 		 * TCP connections.
658 		 */
659 		/* XXX there's no PRC_QUENCH in IPv6 */
660 		return;
661 	} else if (PRC_IS_REDIRECT(cmd))
662 		notify = in_rtchange, d = NULL;
663 	else if (cmd == PRC_MSGSIZE)
664 		; /* special code is present, see below */
665 	else if (cmd == PRC_HOSTDEAD)
666 		d = NULL;
667 	else if (inet6ctlerrmap[cmd] == 0)
668 		return;
669 
670 	/* if the parameter is from icmp6, decode it. */
671 	if (d != NULL) {
672 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
673 		m = ip6cp->ip6c_m;
674 		ip6 = ip6cp->ip6c_ip6;
675 		off = ip6cp->ip6c_off;
676 		sa6_src = ip6cp->ip6c_src;
677 	} else {
678 		m = NULL;
679 		ip6 = NULL;
680 		sa6_src = &sa6_any;
681 	}
682 
683 	if (ip6) {
684 		/*
685 		 * XXX: We assume that when ip6 is non NULL,
686 		 * M and OFF are valid.
687 		 */
688 
689 		/* check if we can safely examine src and dst ports */
690 		if (m->m_pkthdr.len < off + sizeof(*thp))
691 			return;
692 
693 		bzero(&th, sizeof(th));
694 #ifdef DIAGNOSTIC
695 		if (sizeof(*thp) > sizeof(th))
696 			panic("assumption failed in tcp6_ctlinput");
697 #endif
698 		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
699 
700 		/*
701 		 * Check to see if we have a valid TCP connection
702 		 * corresponding to the address in the ICMPv6 message
703 		 * payload.
704 		 */
705 		inp = in6_pcbhashlookup(&tcbtable, &sa6->sin6_addr,
706 		    th.th_dport, (struct in6_addr *)&sa6_src->sin6_addr,
707 		    th.th_sport, rdomain);
708 		if (cmd == PRC_MSGSIZE) {
709 			/*
710 			 * Depending on the value of "valid" and routing table
711 			 * size (mtudisc_{hi,lo}wat), we will:
712 			 * - recalcurate the new MTU and create the
713 			 *   corresponding routing entry, or
714 			 * - ignore the MTU change notification.
715 			 */
716 			icmp6_mtudisc_update((struct ip6ctlparam *)d, inp != NULL);
717 			return;
718 		}
719 		if (inp) {
720 			seq = ntohl(th.th_seq);
721 			if (inp->inp_socket &&
722 			    (tp = intotcpcb(inp)) &&
723 			    SEQ_GEQ(seq, tp->snd_una) &&
724 			    SEQ_LT(seq, tp->snd_max))
725 				notify(inp, inet6ctlerrmap[cmd]);
726 		} else if (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
727 		    inet6ctlerrmap[cmd] == ENETUNREACH ||
728 		    inet6ctlerrmap[cmd] == EHOSTDOWN)
729 			syn_cache_unreach((struct sockaddr *)sa6_src,
730 			    sa, &th, rdomain);
731 	} else {
732 		(void) in6_pcbnotify(&tcbtable, sa6, 0,
733 		    sa6_src, 0, rdomain, cmd, NULL, notify);
734 	}
735 }
736 #endif
737 
738 void *
739 tcp_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
740 {
741 	struct ip *ip = v;
742 	struct tcphdr *th;
743 	struct tcpcb *tp;
744 	struct inpcb *inp;
745 	struct in_addr faddr;
746 	tcp_seq seq;
747 	u_int mtu;
748 	void (*notify)(struct inpcb *, int) = tcp_notify;
749 	int errno;
750 
751 	if (sa->sa_family != AF_INET)
752 		return NULL;
753 	faddr = satosin(sa)->sin_addr;
754 	if (faddr.s_addr == INADDR_ANY)
755 		return NULL;
756 
757 	if ((unsigned)cmd >= PRC_NCMDS)
758 		return NULL;
759 	errno = inetctlerrmap[cmd];
760 	if (cmd == PRC_QUENCH)
761 		/*
762 		 * Don't honor ICMP Source Quench messages meant for
763 		 * TCP connections.
764 		 */
765 		return NULL;
766 	else if (PRC_IS_REDIRECT(cmd))
767 		notify = in_rtchange, ip = 0;
768 	else if (cmd == PRC_MSGSIZE && ip_mtudisc && ip) {
769 		/*
770 		 * Verify that the packet in the icmp payload refers
771 		 * to an existing TCP connection.
772 		 */
773 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
774 		seq = ntohl(th->th_seq);
775 		inp = in_pcbhashlookup(&tcbtable,
776 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
777 		    rdomain);
778 		if (inp && (tp = intotcpcb(inp)) &&
779 		    SEQ_GEQ(seq, tp->snd_una) &&
780 		    SEQ_LT(seq, tp->snd_max)) {
781 			struct icmp *icp;
782 			icp = (struct icmp *)((caddr_t)ip -
783 					      offsetof(struct icmp, icmp_ip));
784 
785 			/*
786 			 * If the ICMP message advertises a Next-Hop MTU
787 			 * equal or larger than the maximum packet size we have
788 			 * ever sent, drop the message.
789 			 */
790 			mtu = (u_int)ntohs(icp->icmp_nextmtu);
791 			if (mtu >= tp->t_pmtud_mtu_sent)
792 				return NULL;
793 			if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
794 				/*
795 				 * Calculate new MTU, and create corresponding
796 				 * route (traditional PMTUD).
797 				 */
798 				tp->t_flags &= ~TF_PMTUD_PEND;
799 				icmp_mtudisc(icp, inp->inp_rtableid);
800 			} else {
801 				/*
802 				 * Record the information got in the ICMP
803 				 * message; act on it later.
804 				 * If we had already recorded an ICMP message,
805 				 * replace the old one only if the new message
806 				 * refers to an older TCP segment
807 				 */
808 				if (tp->t_flags & TF_PMTUD_PEND) {
809 					if (SEQ_LT(tp->t_pmtud_th_seq, seq))
810 						return NULL;
811 				} else
812 					tp->t_flags |= TF_PMTUD_PEND;
813 				tp->t_pmtud_th_seq = seq;
814 				tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
815 				tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
816 				tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
817 				return NULL;
818 			}
819 		} else {
820 			/* ignore if we don't have a matching connection */
821 			return NULL;
822 		}
823 		notify = tcp_mtudisc, ip = 0;
824 	} else if (cmd == PRC_MTUINC)
825 		notify = tcp_mtudisc_increase, ip = 0;
826 	else if (cmd == PRC_HOSTDEAD)
827 		ip = 0;
828 	else if (errno == 0)
829 		return NULL;
830 
831 	if (ip) {
832 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
833 		inp = in_pcbhashlookup(&tcbtable,
834 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
835 		    rdomain);
836 		if (inp) {
837 			seq = ntohl(th->th_seq);
838 			if (inp->inp_socket &&
839 			    (tp = intotcpcb(inp)) &&
840 			    SEQ_GEQ(seq, tp->snd_una) &&
841 			    SEQ_LT(seq, tp->snd_max))
842 				notify(inp, errno);
843 		} else if (inetctlerrmap[cmd] == EHOSTUNREACH ||
844 		    inetctlerrmap[cmd] == ENETUNREACH ||
845 		    inetctlerrmap[cmd] == EHOSTDOWN) {
846 			struct sockaddr_in sin;
847 
848 			bzero(&sin, sizeof(sin));
849 			sin.sin_len = sizeof(sin);
850 			sin.sin_family = AF_INET;
851 			sin.sin_port = th->th_sport;
852 			sin.sin_addr = ip->ip_src;
853 			syn_cache_unreach(sintosa(&sin), sa, th, rdomain);
854 		}
855 	} else
856 		in_pcbnotifyall(&tcbtable, sa, rdomain, errno, notify);
857 
858 	return NULL;
859 }
860 
861 
862 #ifdef INET6
863 /*
864  * Path MTU Discovery handlers.
865  */
866 void
867 tcp6_mtudisc_callback(sin6, rdomain)
868 	struct sockaddr_in6 *sin6;
869 	u_int rdomain;
870 {
871 	(void) in6_pcbnotify(&tcbtable, sin6, 0,
872 	    &sa6_any, 0, rdomain, PRC_MSGSIZE, NULL, tcp_mtudisc);
873 }
874 #endif /* INET6 */
875 
876 /*
877  * On receipt of path MTU corrections, flush old route and replace it
878  * with the new one.  Retransmit all unacknowledged packets, to ensure
879  * that all packets will be received.
880  */
881 void
882 tcp_mtudisc(inp, errno)
883 	struct inpcb *inp;
884 	int errno;
885 {
886 	struct tcpcb *tp = intotcpcb(inp);
887 	struct rtentry *rt = in_pcbrtentry(inp);
888 	int change = 0;
889 
890 	if (tp != 0) {
891 		int orig_maxseg = tp->t_maxseg;
892 		if (rt != 0) {
893 			/*
894 			 * If this was not a host route, remove and realloc.
895 			 */
896 			if ((rt->rt_flags & RTF_HOST) == 0) {
897 				in_rtchange(inp, errno);
898 				if ((rt = in_pcbrtentry(inp)) == 0)
899 					return;
900 			}
901 			if (orig_maxseg != tp->t_maxseg ||
902 			    (rt->rt_rmx.rmx_locks & RTV_MTU))
903 				change = 1;
904 		}
905 		tcp_mss(tp, -1);
906 
907 		/*
908 		 * Resend unacknowledged packets
909 		 */
910 		tp->snd_nxt = tp->snd_una;
911 		if (change || errno > 0)
912 			tcp_output(tp);
913 	}
914 }
915 
916 void
917 tcp_mtudisc_increase(inp, errno)
918 	struct inpcb *inp;
919 	int errno;
920 {
921 	struct tcpcb *tp = intotcpcb(inp);
922 	struct rtentry *rt = in_pcbrtentry(inp);
923 
924 	if (tp != 0 && rt != 0) {
925 		/*
926 		 * If this was a host route, remove and realloc.
927 		 */
928 		if (rt->rt_flags & RTF_HOST)
929 			in_rtchange(inp, errno);
930 
931 		/* also takes care of congestion window */
932 		tcp_mss(tp, -1);
933 	}
934 }
935 
936 /*
937  * Generate new ISNs with a method based on RFC1948
938  */
939 #define TCP_ISS_CONN_INC 4096
940 int tcp_secret_init;
941 u_char tcp_secret[16];
942 SHA2_CTX tcp_secret_ctx;
943 
944 void
945 tcp_set_iss_tsm(struct tcpcb *tp)
946 {
947 	SHA2_CTX ctx;
948 	union {
949 		uint8_t bytes[SHA512_DIGEST_LENGTH];
950 		uint32_t words[2];
951 	} digest;
952 	u_int rdomain = rtable_l2(tp->t_inpcb->inp_rtableid);
953 
954 	if (tcp_secret_init == 0) {
955 		arc4random_buf(tcp_secret, sizeof(tcp_secret));
956 		SHA512Init(&tcp_secret_ctx);
957 		SHA512Update(&tcp_secret_ctx, tcp_secret, sizeof(tcp_secret));
958 		tcp_secret_init = 1;
959 	}
960 	ctx = tcp_secret_ctx;
961 	SHA512Update(&ctx, &rdomain, sizeof(rdomain));
962 	SHA512Update(&ctx, &tp->t_inpcb->inp_lport, sizeof(u_short));
963 	SHA512Update(&ctx, &tp->t_inpcb->inp_fport, sizeof(u_short));
964 	if (tp->pf == AF_INET6) {
965 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr6,
966 		    sizeof(struct in6_addr));
967 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr6,
968 		    sizeof(struct in6_addr));
969 	} else {
970 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr,
971 		    sizeof(struct in_addr));
972 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr,
973 		    sizeof(struct in_addr));
974 	}
975 	SHA512Final(digest.bytes, &ctx);
976 	tcp_iss += TCP_ISS_CONN_INC;
977 	tp->iss = digest.words[0] + tcp_iss;
978 	tp->ts_modulate = digest.words[1];
979 }
980 
981 #ifdef TCP_SIGNATURE
982 int
983 tcp_signature_tdb_attach(void)
984 {
985 	return (0);
986 }
987 
988 int
989 tcp_signature_tdb_init(tdbp, xsp, ii)
990 	struct tdb *tdbp;
991 	struct xformsw *xsp;
992 	struct ipsecinit *ii;
993 {
994 	if ((ii->ii_authkeylen < 1) || (ii->ii_authkeylen > 80))
995 		return (EINVAL);
996 
997 	tdbp->tdb_amxkey = malloc(ii->ii_authkeylen, M_XDATA, M_NOWAIT);
998 	if (tdbp->tdb_amxkey == NULL)
999 		return (ENOMEM);
1000 	bcopy(ii->ii_authkey, tdbp->tdb_amxkey, ii->ii_authkeylen);
1001 	tdbp->tdb_amxkeylen = ii->ii_authkeylen;
1002 
1003 	return (0);
1004 }
1005 
1006 int
1007 tcp_signature_tdb_zeroize(tdbp)
1008 	struct tdb *tdbp;
1009 {
1010 	if (tdbp->tdb_amxkey) {
1011 		explicit_bzero(tdbp->tdb_amxkey, tdbp->tdb_amxkeylen);
1012 		free(tdbp->tdb_amxkey, M_XDATA, 0);
1013 		tdbp->tdb_amxkey = NULL;
1014 	}
1015 
1016 	return (0);
1017 }
1018 
1019 int
1020 tcp_signature_tdb_input(m, tdbp, skip, protoff)
1021 	struct mbuf *m;
1022 	struct tdb *tdbp;
1023 	int skip, protoff;
1024 {
1025 	return (0);
1026 }
1027 
1028 int
1029 tcp_signature_tdb_output(m, tdbp, mp, skip, protoff)
1030 	struct mbuf *m;
1031 	struct tdb *tdbp;
1032 	struct mbuf **mp;
1033 	int skip, protoff;
1034 {
1035 	return (EINVAL);
1036 }
1037 
1038 int
1039 tcp_signature_apply(fstate, data, len)
1040 	caddr_t fstate;
1041 	caddr_t data;
1042 	unsigned int len;
1043 {
1044 	MD5Update((MD5_CTX *)fstate, (char *)data, len);
1045 	return 0;
1046 }
1047 
1048 int
1049 tcp_signature(struct tdb *tdb, int af, struct mbuf *m, struct tcphdr *th,
1050     int iphlen, int doswap, char *sig)
1051 {
1052 	MD5_CTX ctx;
1053 	int len;
1054 	struct tcphdr th0;
1055 
1056 	MD5Init(&ctx);
1057 
1058 	switch(af) {
1059 	case 0:
1060 	case AF_INET: {
1061 		struct ippseudo ippseudo;
1062 		struct ip *ip;
1063 
1064 		ip = mtod(m, struct ip *);
1065 
1066 		ippseudo.ippseudo_src = ip->ip_src;
1067 		ippseudo.ippseudo_dst = ip->ip_dst;
1068 		ippseudo.ippseudo_pad = 0;
1069 		ippseudo.ippseudo_p = IPPROTO_TCP;
1070 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - iphlen);
1071 
1072 		MD5Update(&ctx, (char *)&ippseudo,
1073 		    sizeof(struct ippseudo));
1074 		break;
1075 		}
1076 #ifdef INET6
1077 	case AF_INET6: {
1078 		struct ip6_hdr_pseudo ip6pseudo;
1079 		struct ip6_hdr *ip6;
1080 
1081 		ip6 = mtod(m, struct ip6_hdr *);
1082 		bzero(&ip6pseudo, sizeof(ip6pseudo));
1083 		ip6pseudo.ip6ph_src = ip6->ip6_src;
1084 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
1085 		in6_clearscope(&ip6pseudo.ip6ph_src);
1086 		in6_clearscope(&ip6pseudo.ip6ph_dst);
1087 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
1088 		ip6pseudo.ip6ph_len = htonl(m->m_pkthdr.len - iphlen);
1089 
1090 		MD5Update(&ctx, (char *)&ip6pseudo,
1091 		    sizeof(ip6pseudo));
1092 		break;
1093 		}
1094 #endif
1095 	}
1096 
1097 	th0 = *th;
1098 	th0.th_sum = 0;
1099 
1100 	if (doswap) {
1101 		th0.th_seq = htonl(th0.th_seq);
1102 		th0.th_ack = htonl(th0.th_ack);
1103 		th0.th_win = htons(th0.th_win);
1104 		th0.th_urp = htons(th0.th_urp);
1105 	}
1106 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
1107 
1108 	len = m->m_pkthdr.len - iphlen - th->th_off * sizeof(uint32_t);
1109 
1110 	if (len > 0 &&
1111 	    m_apply(m, iphlen + th->th_off * sizeof(uint32_t), len,
1112 	    tcp_signature_apply, (caddr_t)&ctx))
1113 		return (-1);
1114 
1115 	MD5Update(&ctx, tdb->tdb_amxkey, tdb->tdb_amxkeylen);
1116 	MD5Final(sig, &ctx);
1117 
1118 	return (0);
1119 }
1120 #endif /* TCP_SIGNATURE */
1121