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