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