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