xref: /netbsd-src/sys/netinet/tcp_subr.c (revision 3cec974c61d7fac0a37c0377723a33214a458c8b)
1 /*	$NetBSD: tcp_subr.c,v 1.107 2001/02/11 06:49:49 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1997, 1998, 2000 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
38  * Facility, NASA Ames Research Center.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *	This product includes software developed by the NetBSD
51  *	Foundation, Inc. and its contributors.
52  * 4. Neither the name of The NetBSD Foundation nor the names of its
53  *    contributors may be used to endorse or promote products derived
54  *    from this software without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66  * POSSIBILITY OF SUCH DAMAGE.
67  */
68 
69 /*
70  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
71  *	The Regents of the University of California.  All rights reserved.
72  *
73  * Redistribution and use in source and binary forms, with or without
74  * modification, are permitted provided that the following conditions
75  * are met:
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  * 2. Redistributions in binary form must reproduce the above copyright
79  *    notice, this list of conditions and the following disclaimer in the
80  *    documentation and/or other materials provided with the distribution.
81  * 3. All advertising materials mentioning features or use of this software
82  *    must display the following acknowledgement:
83  *	This product includes software developed by the University of
84  *	California, Berkeley and its contributors.
85  * 4. Neither the name of the University nor the names of its contributors
86  *    may be used to endorse or promote products derived from this software
87  *    without specific prior written permission.
88  *
89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  *
101  *	@(#)tcp_subr.c	8.2 (Berkeley) 5/24/95
102  */
103 
104 #include "opt_inet.h"
105 #include "opt_ipsec.h"
106 #include "opt_tcp_compat_42.h"
107 #include "rnd.h"
108 
109 #include <sys/param.h>
110 #include <sys/proc.h>
111 #include <sys/systm.h>
112 #include <sys/malloc.h>
113 #include <sys/mbuf.h>
114 #include <sys/socket.h>
115 #include <sys/socketvar.h>
116 #include <sys/protosw.h>
117 #include <sys/errno.h>
118 #include <sys/kernel.h>
119 #include <sys/pool.h>
120 #if NRND > 0
121 #include <sys/rnd.h>
122 #endif
123 
124 #include <net/route.h>
125 #include <net/if.h>
126 
127 #include <netinet/in.h>
128 #include <netinet/in_systm.h>
129 #include <netinet/ip.h>
130 #include <netinet/in_pcb.h>
131 #include <netinet/ip_var.h>
132 #include <netinet/ip_icmp.h>
133 
134 #ifdef INET6
135 #ifndef INET
136 #include <netinet/in.h>
137 #endif
138 #include <netinet/ip6.h>
139 #include <netinet6/in6_pcb.h>
140 #include <netinet6/ip6_var.h>
141 #include <netinet6/in6_var.h>
142 #include <netinet6/ip6protosw.h>
143 #include <netinet/icmp6.h>
144 #endif
145 
146 #include <netinet/tcp.h>
147 #include <netinet/tcp_fsm.h>
148 #include <netinet/tcp_seq.h>
149 #include <netinet/tcp_timer.h>
150 #include <netinet/tcp_var.h>
151 #include <netinet/tcpip.h>
152 
153 #ifdef IPSEC
154 #include <netinet6/ipsec.h>
155 #endif /*IPSEC*/
156 
157 #ifdef INET6
158 struct in6pcb tcb6;
159 #endif
160 
161 /* patchable/settable parameters for tcp */
162 int 	tcp_mssdflt = TCP_MSS;
163 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
164 int	tcp_do_rfc1323 = 1;	/* window scaling / timestamps (obsolete) */
165 int	tcp_do_sack = 1;	/* selective acknowledgement */
166 int	tcp_do_win_scale = 1;	/* RFC1323 window scaling */
167 int	tcp_do_timestamps = 1;	/* RFC1323 timestamps */
168 int	tcp_do_newreno = 0;	/* Use the New Reno algorithms */
169 int	tcp_ack_on_push = 0;	/* set to enable immediate ACK-on-PUSH */
170 int	tcp_init_win = 1;
171 int	tcp_mss_ifmtu = 0;
172 #ifdef TCP_COMPAT_42
173 int	tcp_compat_42 = 1;
174 #else
175 int	tcp_compat_42 = 0;
176 #endif
177 int	tcp_rst_ppslim = 100;	/* 100pps */
178 
179 /* tcb hash */
180 #ifndef TCBHASHSIZE
181 #define	TCBHASHSIZE	128
182 #endif
183 int	tcbhashsize = TCBHASHSIZE;
184 
185 /* syn hash parameters */
186 #define	TCP_SYN_HASH_SIZE	293
187 #define	TCP_SYN_BUCKET_SIZE	35
188 int	tcp_syn_cache_size = TCP_SYN_HASH_SIZE;
189 int	tcp_syn_cache_limit = TCP_SYN_HASH_SIZE*TCP_SYN_BUCKET_SIZE;
190 int	tcp_syn_bucket_limit = 3*TCP_SYN_BUCKET_SIZE;
191 struct	syn_cache_head tcp_syn_cache[TCP_SYN_HASH_SIZE];
192 int	tcp_syn_cache_interval = 1;	/* runs timer twice a second */
193 
194 int	tcp_freeq __P((struct tcpcb *));
195 
196 #ifdef INET
197 void	tcp_mtudisc_callback __P((struct in_addr));
198 #endif
199 #ifdef INET6
200 void	tcp6_mtudisc_callback __P((struct in6_addr *));
201 #endif
202 
203 void	tcp_mtudisc __P((struct inpcb *, int));
204 #ifdef INET6
205 void	tcp6_mtudisc __P((struct in6pcb *, int));
206 #endif
207 
208 struct pool tcpcb_pool;
209 
210 /*
211  * Tcp initialization
212  */
213 void
214 tcp_init()
215 {
216 	int hlen;
217 
218 	pool_init(&tcpcb_pool, sizeof(struct tcpcb), 0, 0, 0, "tcpcbpl",
219 	    0, NULL, NULL, M_PCB);
220 	in_pcbinit(&tcbtable, tcbhashsize, tcbhashsize);
221 #ifdef INET6
222 	tcb6.in6p_next = tcb6.in6p_prev = &tcb6;
223 #endif
224 	LIST_INIT(&tcp_delacks);
225 
226 	hlen = sizeof(struct ip) + sizeof(struct tcphdr);
227 #ifdef INET6
228 	if (sizeof(struct ip) < sizeof(struct ip6_hdr))
229 		hlen = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
230 #endif
231 	if (max_protohdr < hlen)
232 		max_protohdr = hlen;
233 	if (max_linkhdr + hlen > MHLEN)
234 		panic("tcp_init");
235 
236 #ifdef INET
237 	icmp_mtudisc_callback_register(tcp_mtudisc_callback);
238 #endif
239 #ifdef INET6
240 	icmp6_mtudisc_callback_register(tcp6_mtudisc_callback);
241 #endif
242 
243 	/* Initialize the compressed state engine. */
244 	syn_cache_init();
245 }
246 
247 /*
248  * Create template to be used to send tcp packets on a connection.
249  * Call after host entry created, allocates an mbuf and fills
250  * in a skeletal tcp/ip header, minimizing the amount of work
251  * necessary when the connection is used.
252  */
253 struct mbuf *
254 tcp_template(tp)
255 	struct tcpcb *tp;
256 {
257 	struct inpcb *inp = tp->t_inpcb;
258 #ifdef INET6
259 	struct in6pcb *in6p = tp->t_in6pcb;
260 #endif
261 	struct tcphdr *n;
262 	struct mbuf *m;
263 	int hlen;
264 
265 	switch (tp->t_family) {
266 	case AF_INET:
267 		hlen = sizeof(struct ip);
268 		if (inp)
269 			break;
270 #ifdef INET6
271 		if (in6p) {
272 			/* mapped addr case */
273 			if (IN6_IS_ADDR_V4MAPPED(&in6p->in6p_laddr)
274 			 && IN6_IS_ADDR_V4MAPPED(&in6p->in6p_faddr))
275 				break;
276 		}
277 #endif
278 		return NULL;	/*EINVAL*/
279 #ifdef INET6
280 	case AF_INET6:
281 		hlen = sizeof(struct ip6_hdr);
282 		if (in6p) {
283 			/* more sainty check? */
284 			break;
285 		}
286 		return NULL;	/*EINVAL*/
287 #endif
288 	default:
289 		hlen = 0;	/*pacify gcc*/
290 		return NULL;	/*EAFNOSUPPORT*/
291 	}
292 #ifdef DIAGNOSTIC
293 	if (hlen + sizeof(struct tcphdr) > MCLBYTES)
294 		panic("mclbytes too small for t_template");
295 #endif
296 	m = tp->t_template;
297 	if (m && m->m_len == hlen + sizeof(struct tcphdr))
298 		;
299 	else {
300 		if (m)
301 			m_freem(m);
302 		m = tp->t_template = NULL;
303 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
304 		if (m && hlen + sizeof(struct tcphdr) > MHLEN) {
305 			MCLGET(m, M_DONTWAIT);
306 			if ((m->m_flags & M_EXT) == 0) {
307 				m_free(m);
308 				m = NULL;
309 			}
310 		}
311 		if (m == NULL)
312 			return NULL;
313 		m->m_pkthdr.len = m->m_len = hlen + sizeof(struct tcphdr);
314 	}
315 	bzero(mtod(m, caddr_t), m->m_len);
316 	switch (tp->t_family) {
317 	case AF_INET:
318 	    {
319 		struct ipovly *ipov;
320 		mtod(m, struct ip *)->ip_v = 4;
321 		ipov = mtod(m, struct ipovly *);
322 		ipov->ih_pr = IPPROTO_TCP;
323 		ipov->ih_len = htons(sizeof(struct tcphdr));
324 		if (inp) {
325 			ipov->ih_src = inp->inp_laddr;
326 			ipov->ih_dst = inp->inp_faddr;
327 		}
328 #ifdef INET6
329 		else if (in6p) {
330 			/* mapped addr case */
331 			bcopy(&in6p->in6p_laddr.s6_addr32[3], &ipov->ih_src,
332 				sizeof(ipov->ih_src));
333 			bcopy(&in6p->in6p_faddr.s6_addr32[3], &ipov->ih_dst,
334 				sizeof(ipov->ih_dst));
335 		}
336 #endif
337 		break;
338 	    }
339 #ifdef INET6
340 	case AF_INET6:
341 	    {
342 		struct ip6_hdr *ip6;
343 		mtod(m, struct ip *)->ip_v = 6;
344 		ip6 = mtod(m, struct ip6_hdr *);
345 		ip6->ip6_nxt = IPPROTO_TCP;
346 		ip6->ip6_plen = htons(sizeof(struct tcphdr));
347 		ip6->ip6_src = in6p->in6p_laddr;
348 		ip6->ip6_dst = in6p->in6p_faddr;
349 		ip6->ip6_flow = in6p->in6p_flowinfo & IPV6_FLOWINFO_MASK;
350 		if (ip6_auto_flowlabel) {
351 			ip6->ip6_flow &= ~IPV6_FLOWLABEL_MASK;
352 			ip6->ip6_flow |=
353 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
354 		}
355 		ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
356 		ip6->ip6_vfc |= IPV6_VERSION;
357 		break;
358 	    }
359 #endif
360 	}
361 	n = (struct tcphdr *)(mtod(m, caddr_t) + hlen);
362 	if (inp) {
363 		n->th_sport = inp->inp_lport;
364 		n->th_dport = inp->inp_fport;
365 	}
366 #ifdef INET6
367 	else if (in6p) {
368 		n->th_sport = in6p->in6p_lport;
369 		n->th_dport = in6p->in6p_fport;
370 	}
371 #endif
372 	n->th_seq = 0;
373 	n->th_ack = 0;
374 	n->th_x2 = 0;
375 	n->th_off = 5;
376 	n->th_flags = 0;
377 	n->th_win = 0;
378 	n->th_sum = 0;
379 	n->th_urp = 0;
380 	return (m);
381 }
382 
383 /*
384  * Send a single message to the TCP at address specified by
385  * the given TCP/IP header.  If m == 0, then we make a copy
386  * of the tcpiphdr at ti and send directly to the addressed host.
387  * This is used to force keep alive messages out using the TCP
388  * template for a connection tp->t_template.  If flags are given
389  * then we send a message back to the TCP which originated the
390  * segment ti, and discard the mbuf containing it and any other
391  * attached mbufs.
392  *
393  * In any case the ack and sequence number of the transmitted
394  * segment are as specified by the parameters.
395  */
396 int
397 tcp_respond(tp, template, m, th0, ack, seq, flags)
398 	struct tcpcb *tp;
399 	struct mbuf *template;
400 	struct mbuf *m;
401 	struct tcphdr *th0;
402 	tcp_seq ack, seq;
403 	int flags;
404 {
405 	struct route *ro;
406 	int error, tlen, win = 0;
407 	int hlen;
408 	struct ip *ip;
409 #ifdef INET6
410 	struct ip6_hdr *ip6;
411 #endif
412 	int family;	/* family on packet, not inpcb/in6pcb! */
413 	struct tcphdr *th;
414 
415 	if (tp != NULL && (flags & TH_RST) == 0) {
416 #ifdef DIAGNOSTIC
417 		if (tp->t_inpcb && tp->t_in6pcb)
418 			panic("tcp_respond: both t_inpcb and t_in6pcb are set");
419 #endif
420 #ifdef INET
421 		if (tp->t_inpcb)
422 			win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
423 #endif
424 #ifdef INET6
425 		if (tp->t_in6pcb)
426 			win = sbspace(&tp->t_in6pcb->in6p_socket->so_rcv);
427 #endif
428 	}
429 
430 	ip = NULL;
431 #ifdef INET6
432 	ip6 = NULL;
433 #endif
434 	if (m == 0) {
435 		if (!template)
436 			return EINVAL;
437 
438 		/* get family information from template */
439 		switch (mtod(template, struct ip *)->ip_v) {
440 		case 4:
441 			family = AF_INET;
442 			hlen = sizeof(struct ip);
443 			break;
444 #ifdef INET6
445 		case 6:
446 			family = AF_INET6;
447 			hlen = sizeof(struct ip6_hdr);
448 			break;
449 #endif
450 		default:
451 			return EAFNOSUPPORT;
452 		}
453 
454 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
455 		if (m) {
456 			MCLGET(m, M_DONTWAIT);
457 			if ((m->m_flags & M_EXT) == 0) {
458 				m_free(m);
459 				m = NULL;
460 			}
461 		}
462 		if (m == NULL)
463 			return (ENOBUFS);
464 
465 		if (tcp_compat_42)
466 			tlen = 1;
467 		else
468 			tlen = 0;
469 
470 		m->m_data += max_linkhdr;
471 		bcopy(mtod(template, caddr_t), mtod(m, caddr_t),
472 			template->m_len);
473 		switch (family) {
474 		case AF_INET:
475 			ip = mtod(m, struct ip *);
476 			th = (struct tcphdr *)(ip + 1);
477 			break;
478 #ifdef INET6
479 		case AF_INET6:
480 			ip6 = mtod(m, struct ip6_hdr *);
481 			th = (struct tcphdr *)(ip6 + 1);
482 			break;
483 #endif
484 #if 0
485 		default:
486 			/* noone will visit here */
487 			m_freem(m);
488 			return EAFNOSUPPORT;
489 #endif
490 		}
491 		flags = TH_ACK;
492 	} else {
493 
494 		if ((m->m_flags & M_PKTHDR) == 0) {
495 #if 0
496 			printf("non PKTHDR to tcp_respond\n");
497 #endif
498 			m_freem(m);
499 			return EINVAL;
500 		}
501 #ifdef DIAGNOSTIC
502 		if (!th0)
503 			panic("th0 == NULL in tcp_respond");
504 #endif
505 
506 		/* get family information from m */
507 		switch (mtod(m, struct ip *)->ip_v) {
508 		case 4:
509 			family = AF_INET;
510 			hlen = sizeof(struct ip);
511 			ip = mtod(m, struct ip *);
512 			break;
513 #ifdef INET6
514 		case 6:
515 			family = AF_INET6;
516 			hlen = sizeof(struct ip6_hdr);
517 			ip6 = mtod(m, struct ip6_hdr *);
518 			break;
519 #endif
520 		default:
521 			m_freem(m);
522 			return EAFNOSUPPORT;
523 		}
524 		if ((flags & TH_SYN) == 0 || sizeof(*th0) > (th0->th_off << 2))
525 			tlen = sizeof(*th0);
526 		else
527 			tlen = th0->th_off << 2;
528 
529 		if (m->m_len > hlen + tlen && (m->m_flags & M_EXT) == 0 &&
530 		    mtod(m, caddr_t) + hlen == (caddr_t)th0) {
531 			m->m_len = hlen + tlen;
532 			m_freem(m->m_next);
533 			m->m_next = NULL;
534 		} else {
535 			struct mbuf *n;
536 
537 #ifdef DIAGNOSTIC
538 			if (max_linkhdr + hlen + tlen > MCLBYTES) {
539 				m_freem(m);
540 				return EMSGSIZE;
541 			}
542 #endif
543 			MGETHDR(n, M_DONTWAIT, MT_HEADER);
544 			if (n && max_linkhdr + hlen + tlen > MHLEN) {
545 				MCLGET(n, M_DONTWAIT);
546 				if ((n->m_flags & M_EXT) == 0) {
547 					m_freem(n);
548 					n = NULL;
549 				}
550 			}
551 			if (!n) {
552 				m_freem(m);
553 				return ENOBUFS;
554 			}
555 
556 			n->m_data += max_linkhdr;
557 			n->m_len = hlen + tlen;
558 			m_copyback(n, 0, hlen, mtod(m, caddr_t));
559 			m_copyback(n, hlen, tlen, (caddr_t)th0);
560 
561 			m_freem(m);
562 			m = n;
563 			n = NULL;
564 		}
565 
566 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
567 		switch (family) {
568 		case AF_INET:
569 			ip = mtod(m, struct ip *);
570 			th = (struct tcphdr *)(ip + 1);
571 			ip->ip_p = IPPROTO_TCP;
572 			xchg(ip->ip_dst, ip->ip_src, struct in_addr);
573 			ip->ip_p = IPPROTO_TCP;
574 			break;
575 #ifdef INET6
576 		case AF_INET6:
577 			ip6 = mtod(m, struct ip6_hdr *);
578 			th = (struct tcphdr *)(ip6 + 1);
579 			ip6->ip6_nxt = IPPROTO_TCP;
580 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
581 			ip6->ip6_nxt = IPPROTO_TCP;
582 			break;
583 #endif
584 #if 0
585 		default:
586 			/* noone will visit here */
587 			m_freem(m);
588 			return EAFNOSUPPORT;
589 #endif
590 		}
591 		xchg(th->th_dport, th->th_sport, u_int16_t);
592 #undef xchg
593 		tlen = 0;	/*be friendly with the following code*/
594 	}
595 	th->th_seq = htonl(seq);
596 	th->th_ack = htonl(ack);
597 	th->th_x2 = 0;
598 	if ((flags & TH_SYN) == 0) {
599 		if (tp)
600 			win >>= tp->rcv_scale;
601 		if (win > TCP_MAXWIN)
602 			win = TCP_MAXWIN;
603 		th->th_win = htons((u_int16_t)win);
604 		th->th_off = sizeof (struct tcphdr) >> 2;
605 		tlen += sizeof(*th);
606 	} else
607 		tlen += th->th_off << 2;
608 	m->m_len = hlen + tlen;
609 	m->m_pkthdr.len = hlen + tlen;
610 	m->m_pkthdr.rcvif = (struct ifnet *) 0;
611 	th->th_flags = flags;
612 	th->th_urp = 0;
613 
614 	switch (family) {
615 #ifdef INET
616 	case AF_INET:
617 	    {
618 		struct ipovly *ipov = (struct ipovly *)ip;
619 		bzero(ipov->ih_x1, sizeof ipov->ih_x1);
620 		ipov->ih_len = htons((u_int16_t)tlen);
621 
622 		th->th_sum = 0;
623 		th->th_sum = in_cksum(m, hlen + tlen);
624 		ip->ip_len = hlen + tlen;	/*will be flipped on output*/
625 		ip->ip_ttl = ip_defttl;
626 		break;
627 	    }
628 #endif
629 #ifdef INET6
630 	case AF_INET6:
631 	    {
632 		th->th_sum = 0;
633 		th->th_sum = in6_cksum(m, IPPROTO_TCP, sizeof(struct ip6_hdr),
634 				tlen);
635 		ip6->ip6_plen = ntohs(tlen);
636 		if (tp && tp->t_in6pcb) {
637 			struct ifnet *oifp;
638 			ro = (struct route *)&tp->t_in6pcb->in6p_route;
639 			oifp = ro->ro_rt ? ro->ro_rt->rt_ifp : NULL;
640 			ip6->ip6_hlim = in6_selecthlim(tp->t_in6pcb, oifp);
641 		} else
642 			ip6->ip6_hlim = ip6_defhlim;
643 		ip6->ip6_flow &= ~IPV6_FLOWINFO_MASK;
644 		if (ip6_auto_flowlabel) {
645 			ip6->ip6_flow |=
646 				(htonl(ip6_flow_seq++) & IPV6_FLOWLABEL_MASK);
647 		}
648 		break;
649 	    }
650 #endif
651 	}
652 
653 #ifdef IPSEC
654 	(void)ipsec_setsocket(m, NULL);
655 #endif /*IPSEC*/
656 
657 	if (tp != NULL && tp->t_inpcb != NULL) {
658 		ro = &tp->t_inpcb->inp_route;
659 #ifdef IPSEC
660 		if (ipsec_setsocket(m, tp->t_inpcb->inp_socket) != 0) {
661 			m_freem(m);
662 			return ENOBUFS;
663 		}
664 #endif
665 #ifdef DIAGNOSTIC
666 		if (family != AF_INET)
667 			panic("tcp_respond: address family mismatch");
668 		if (!in_hosteq(ip->ip_dst, tp->t_inpcb->inp_faddr)) {
669 			panic("tcp_respond: ip_dst %x != inp_faddr %x",
670 			    ntohl(ip->ip_dst.s_addr),
671 			    ntohl(tp->t_inpcb->inp_faddr.s_addr));
672 		}
673 #endif
674 	}
675 #ifdef INET6
676 	else if (tp != NULL && tp->t_in6pcb != NULL) {
677 		ro = (struct route *)&tp->t_in6pcb->in6p_route;
678 #ifdef IPSEC
679 		if (ipsec_setsocket(m, tp->t_in6pcb->in6p_socket) != 0) {
680 			m_freem(m);
681 			return ENOBUFS;
682 		}
683 #endif
684 #ifdef DIAGNOSTIC
685 		if (family == AF_INET) {
686 			if (!IN6_IS_ADDR_V4MAPPED(&tp->t_in6pcb->in6p_faddr))
687 				panic("tcp_respond: not mapped addr");
688 			if (bcmp(&ip->ip_dst,
689 					&tp->t_in6pcb->in6p_faddr.s6_addr32[3],
690 					sizeof(ip->ip_dst)) != 0) {
691 				panic("tcp_respond: ip_dst != in6p_faddr");
692 			}
693 		} else if (family == AF_INET6) {
694 			if (!IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &tp->t_in6pcb->in6p_faddr))
695 				panic("tcp_respond: ip6_dst != in6p_faddr");
696 		} else
697 			panic("tcp_respond: address family mismatch");
698 #endif
699 	}
700 #endif
701 	else
702 		ro = NULL;
703 
704 	switch (family) {
705 #ifdef INET
706 	case AF_INET:
707 		error = ip_output(m, NULL, ro,
708 		    (ip_mtudisc ? IP_MTUDISC : 0),
709 		    NULL);
710 		break;
711 #endif
712 #ifdef INET6
713 	case AF_INET6:
714 		error = ip6_output(m, NULL, (struct route_in6 *)ro, 0, NULL,
715 			NULL);
716 		break;
717 #endif
718 	default:
719 		error = EAFNOSUPPORT;
720 		break;
721 	}
722 
723 	return (error);
724 }
725 
726 /*
727  * Create a new TCP control block, making an
728  * empty reassembly queue and hooking it to the argument
729  * protocol control block.
730  */
731 struct tcpcb *
732 tcp_newtcpcb(family, aux)
733 	int family;	/* selects inpcb, or in6pcb */
734 	void *aux;
735 {
736 	struct tcpcb *tp;
737 
738 	switch (family) {
739 	case PF_INET:
740 		break;
741 #ifdef INET6
742 	case PF_INET6:
743 		break;
744 #endif
745 	default:
746 		return NULL;
747 	}
748 
749 	tp = pool_get(&tcpcb_pool, PR_NOWAIT);
750 	if (tp == NULL)
751 		return (NULL);
752 	bzero((caddr_t)tp, sizeof(struct tcpcb));
753 	LIST_INIT(&tp->segq);
754 	LIST_INIT(&tp->timeq);
755 	tp->t_family = family;		/* may be overridden later on */
756 	tp->t_peermss = tcp_mssdflt;
757 	tp->t_ourmss = tcp_mssdflt;
758 	tp->t_segsz = tcp_mssdflt;
759 	LIST_INIT(&tp->t_sc);
760 
761 	tp->t_flags = 0;
762 	if (tcp_do_rfc1323 && tcp_do_win_scale)
763 		tp->t_flags |= TF_REQ_SCALE;
764 	if (tcp_do_rfc1323 && tcp_do_timestamps)
765 		tp->t_flags |= TF_REQ_TSTMP;
766 	if (tcp_do_sack == 2)
767 		tp->t_flags |= TF_WILL_SACK;
768 	else if (tcp_do_sack == 1)
769 		tp->t_flags |= TF_WILL_SACK|TF_IGNR_RXSACK;
770 	tp->t_flags |= TF_CANT_TXSACK;
771 	switch (family) {
772 	case PF_INET:
773 		tp->t_inpcb = (struct inpcb *)aux;
774 		break;
775 #ifdef INET6
776 	case PF_INET6:
777 		tp->t_in6pcb = (struct in6pcb *)aux;
778 		break;
779 #endif
780 	}
781 	/*
782 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
783 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
784 	 * reasonable initial retransmit time.
785 	 */
786 	tp->t_srtt = TCPTV_SRTTBASE;
787 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << (TCP_RTTVAR_SHIFT + 2 - 1);
788 	tp->t_rttmin = TCPTV_MIN;
789 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
790 	    TCPTV_MIN, TCPTV_REXMTMAX);
791 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
792 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
793 	if (family == AF_INET) {
794 		struct inpcb *inp = (struct inpcb *)aux;
795 		inp->inp_ip.ip_ttl = ip_defttl;
796 		inp->inp_ppcb = (caddr_t)tp;
797 	}
798 #ifdef INET6
799 	else if (family == AF_INET6) {
800 		struct in6pcb *in6p = (struct in6pcb *)aux;
801 		in6p->in6p_ip6.ip6_hlim = in6_selecthlim(in6p,
802 			in6p->in6p_route.ro_rt ? in6p->in6p_route.ro_rt->rt_ifp
803 					       : NULL);
804 		in6p->in6p_ppcb = (caddr_t)tp;
805 	}
806 #endif
807 	return (tp);
808 }
809 
810 /*
811  * Drop a TCP connection, reporting
812  * the specified error.  If connection is synchronized,
813  * then send a RST to peer.
814  */
815 struct tcpcb *
816 tcp_drop(tp, errno)
817 	struct tcpcb *tp;
818 	int errno;
819 {
820 	struct socket *so = NULL;
821 
822 #ifdef DIAGNOSTIC
823 	if (tp->t_inpcb && tp->t_in6pcb)
824 		panic("tcp_drop: both t_inpcb and t_in6pcb are set");
825 #endif
826 #ifdef INET
827 	if (tp->t_inpcb)
828 		so = tp->t_inpcb->inp_socket;
829 #endif
830 #ifdef INET6
831 	if (tp->t_in6pcb)
832 		so = tp->t_in6pcb->in6p_socket;
833 #endif
834 	if (!so)
835 		return NULL;
836 
837 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
838 		tp->t_state = TCPS_CLOSED;
839 		(void) tcp_output(tp);
840 		tcpstat.tcps_drops++;
841 	} else
842 		tcpstat.tcps_conndrops++;
843 	if (errno == ETIMEDOUT && tp->t_softerror)
844 		errno = tp->t_softerror;
845 	so->so_error = errno;
846 	return (tcp_close(tp));
847 }
848 
849 /*
850  * Close a TCP control block:
851  *	discard all space held by the tcp
852  *	discard internet protocol block
853  *	wake up any sleepers
854  */
855 struct tcpcb *
856 tcp_close(tp)
857 	struct tcpcb *tp;
858 {
859 	struct inpcb *inp;
860 #ifdef INET6
861 	struct in6pcb *in6p;
862 #endif
863 	struct socket *so;
864 #ifdef RTV_RTT
865 	struct rtentry *rt;
866 #endif
867 	struct route *ro;
868 
869 	inp = tp->t_inpcb;
870 #ifdef INET6
871 	in6p = tp->t_in6pcb;
872 #endif
873 	so = NULL;
874 	ro = NULL;
875 	if (inp) {
876 		so = inp->inp_socket;
877 		ro = &inp->inp_route;
878 	}
879 #ifdef INET6
880 	else if (in6p) {
881 		so = in6p->in6p_socket;
882 		ro = (struct route *)&in6p->in6p_route;
883 	}
884 #endif
885 
886 #ifdef RTV_RTT
887 	/*
888 	 * If we sent enough data to get some meaningful characteristics,
889 	 * save them in the routing entry.  'Enough' is arbitrarily
890 	 * defined as the sendpipesize (default 4K) * 16.  This would
891 	 * give us 16 rtt samples assuming we only get one sample per
892 	 * window (the usual case on a long haul net).  16 samples is
893 	 * enough for the srtt filter to converge to within 5% of the correct
894 	 * value; fewer samples and we could save a very bogus rtt.
895 	 *
896 	 * Don't update the default route's characteristics and don't
897 	 * update anything that the user "locked".
898 	 */
899 	if (SEQ_LT(tp->iss + so->so_snd.sb_hiwat * 16, tp->snd_max) &&
900 	    ro && (rt = ro->ro_rt) &&
901 	    !in_nullhost(satosin(rt_key(rt))->sin_addr)) {
902 		u_long i = 0;
903 
904 		if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
905 			i = tp->t_srtt *
906 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
907 			if (rt->rt_rmx.rmx_rtt && i)
908 				/*
909 				 * filter this update to half the old & half
910 				 * the new values, converting scale.
911 				 * See route.h and tcp_var.h for a
912 				 * description of the scaling constants.
913 				 */
914 				rt->rt_rmx.rmx_rtt =
915 				    (rt->rt_rmx.rmx_rtt + i) / 2;
916 			else
917 				rt->rt_rmx.rmx_rtt = i;
918 		}
919 		if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
920 			i = tp->t_rttvar *
921 			    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTTVAR_SHIFT + 2));
922 			if (rt->rt_rmx.rmx_rttvar && i)
923 				rt->rt_rmx.rmx_rttvar =
924 				    (rt->rt_rmx.rmx_rttvar + i) / 2;
925 			else
926 				rt->rt_rmx.rmx_rttvar = i;
927 		}
928 		/*
929 		 * update the pipelimit (ssthresh) if it has been updated
930 		 * already or if a pipesize was specified & the threshhold
931 		 * got below half the pipesize.  I.e., wait for bad news
932 		 * before we start updating, then update on both good
933 		 * and bad news.
934 		 */
935 		if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
936 		    (i = tp->snd_ssthresh) && rt->rt_rmx.rmx_ssthresh) ||
937 		    i < (rt->rt_rmx.rmx_sendpipe / 2)) {
938 			/*
939 			 * convert the limit from user data bytes to
940 			 * packets then to packet data bytes.
941 			 */
942 			i = (i + tp->t_segsz / 2) / tp->t_segsz;
943 			if (i < 2)
944 				i = 2;
945 			i *= (u_long)(tp->t_segsz + sizeof (struct tcpiphdr));
946 			if (rt->rt_rmx.rmx_ssthresh)
947 				rt->rt_rmx.rmx_ssthresh =
948 				    (rt->rt_rmx.rmx_ssthresh + i) / 2;
949 			else
950 				rt->rt_rmx.rmx_ssthresh = i;
951 		}
952 	}
953 #endif /* RTV_RTT */
954 	/* free the reassembly queue, if any */
955 	TCP_REASS_LOCK(tp);
956 	(void) tcp_freeq(tp);
957 	TCP_REASS_UNLOCK(tp);
958 
959 	TCP_CLEAR_DELACK(tp);
960 	syn_cache_cleanup(tp);
961 
962 	if (tp->t_template) {
963 		m_free(tp->t_template);
964 		tp->t_template = NULL;
965 	}
966 	pool_put(&tcpcb_pool, tp);
967 	if (inp) {
968 		inp->inp_ppcb = 0;
969 		soisdisconnected(so);
970 		in_pcbdetach(inp);
971 	}
972 #ifdef INET6
973 	else if (in6p) {
974 		in6p->in6p_ppcb = 0;
975 		soisdisconnected(so);
976 		in6_pcbdetach(in6p);
977 	}
978 #endif
979 	tcpstat.tcps_closed++;
980 	return ((struct tcpcb *)0);
981 }
982 
983 int
984 tcp_freeq(tp)
985 	struct tcpcb *tp;
986 {
987 	struct ipqent *qe;
988 	int rv = 0;
989 #ifdef TCPREASS_DEBUG
990 	int i = 0;
991 #endif
992 
993 	TCP_REASS_LOCK_CHECK(tp);
994 
995 	while ((qe = tp->segq.lh_first) != NULL) {
996 #ifdef TCPREASS_DEBUG
997 		printf("tcp_freeq[%p,%d]: %u:%u(%u) 0x%02x\n",
998 			tp, i++, qe->ipqe_seq, qe->ipqe_seq + qe->ipqe_len,
999 			qe->ipqe_len, qe->ipqe_flags & (TH_SYN|TH_FIN|TH_RST));
1000 #endif
1001 		LIST_REMOVE(qe, ipqe_q);
1002 		LIST_REMOVE(qe, ipqe_timeq);
1003 		m_freem(qe->ipqe_m);
1004 		pool_put(&ipqent_pool, qe);
1005 		rv = 1;
1006 	}
1007 	return (rv);
1008 }
1009 
1010 /*
1011  * Protocol drain routine.  Called when memory is in short supply.
1012  */
1013 void
1014 tcp_drain()
1015 {
1016 	struct inpcb *inp;
1017 	struct tcpcb *tp;
1018 
1019 	/*
1020 	 * Free the sequence queue of all TCP connections.
1021 	 */
1022 	inp = tcbtable.inpt_queue.cqh_first;
1023 	if (inp)						/* XXX */
1024 	for (; inp != (struct inpcb *)&tcbtable.inpt_queue;
1025 	    inp = inp->inp_queue.cqe_next) {
1026 		if ((tp = intotcpcb(inp)) != NULL) {
1027 			/*
1028 			 * We may be called from a device's interrupt
1029 			 * context.  If the tcpcb is already busy,
1030 			 * just bail out now.
1031 			 */
1032 			if (tcp_reass_lock_try(tp) == 0)
1033 				continue;
1034 			if (tcp_freeq(tp))
1035 				tcpstat.tcps_connsdrained++;
1036 			TCP_REASS_UNLOCK(tp);
1037 		}
1038 	}
1039 }
1040 
1041 /*
1042  * Notify a tcp user of an asynchronous error;
1043  * store error as soft error, but wake up user
1044  * (for now, won't do anything until can select for soft error).
1045  */
1046 void
1047 tcp_notify(inp, error)
1048 	struct inpcb *inp;
1049 	int error;
1050 {
1051 	struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
1052 	struct socket *so = inp->inp_socket;
1053 
1054 	/*
1055 	 * Ignore some errors if we are hooked up.
1056 	 * If connection hasn't completed, has retransmitted several times,
1057 	 * and receives a second error, give up now.  This is better
1058 	 * than waiting a long time to establish a connection that
1059 	 * can never complete.
1060 	 */
1061 	if (tp->t_state == TCPS_ESTABLISHED &&
1062 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1063 	      error == EHOSTDOWN)) {
1064 		return;
1065 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1066 	    tp->t_rxtshift > 3 && tp->t_softerror)
1067 		so->so_error = error;
1068 	else
1069 		tp->t_softerror = error;
1070 	wakeup((caddr_t) &so->so_timeo);
1071 	sorwakeup(so);
1072 	sowwakeup(so);
1073 }
1074 
1075 #ifdef INET6
1076 void
1077 tcp6_notify(in6p, error)
1078 	struct in6pcb *in6p;
1079 	int error;
1080 {
1081 	struct tcpcb *tp = (struct tcpcb *)in6p->in6p_ppcb;
1082 	struct socket *so = in6p->in6p_socket;
1083 
1084 	/*
1085 	 * Ignore some errors if we are hooked up.
1086 	 * If connection hasn't completed, has retransmitted several times,
1087 	 * and receives a second error, give up now.  This is better
1088 	 * than waiting a long time to establish a connection that
1089 	 * can never complete.
1090 	 */
1091 	if (tp->t_state == TCPS_ESTABLISHED &&
1092 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
1093 	      error == EHOSTDOWN)) {
1094 		return;
1095 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
1096 	    tp->t_rxtshift > 3 && tp->t_softerror)
1097 		so->so_error = error;
1098 	else
1099 		tp->t_softerror = error;
1100 	wakeup((caddr_t) &so->so_timeo);
1101 	sorwakeup(so);
1102 	sowwakeup(so);
1103 }
1104 #endif
1105 
1106 #ifdef INET6
1107 void
1108 tcp6_ctlinput(cmd, sa, d)
1109 	int cmd;
1110 	struct sockaddr *sa;
1111 	void *d;
1112 {
1113 	struct tcphdr th;
1114 	void (*notify) __P((struct in6pcb *, int)) = tcp6_notify;
1115 	int nmatch;
1116 	struct ip6_hdr *ip6;
1117 	const struct sockaddr_in6 *sa6_src = NULL;
1118 	struct sockaddr_in6 *sa6 = (struct sockaddr_in6 *)sa;
1119 	struct mbuf *m;
1120 	int off;
1121 
1122 	if (sa->sa_family != AF_INET6 ||
1123 	    sa->sa_len != sizeof(struct sockaddr_in6))
1124 		return;
1125 	if ((unsigned)cmd >= PRC_NCMDS)
1126 		return;
1127 	else if (cmd == PRC_QUENCH) {
1128 		/* XXX there's no PRC_QUENCH in IPv6 */
1129 		notify = tcp6_quench;
1130 	} else if (PRC_IS_REDIRECT(cmd))
1131 		notify = in6_rtchange, d = NULL;
1132 	else if (cmd == PRC_MSGSIZE)
1133 		; /* special code is present, see below */
1134 	else if (cmd == PRC_HOSTDEAD)
1135 		d = NULL;
1136 	else if (inet6ctlerrmap[cmd] == 0)
1137 		return;
1138 
1139 	/* if the parameter is from icmp6, decode it. */
1140 	if (d != NULL) {
1141 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
1142 		m = ip6cp->ip6c_m;
1143 		ip6 = ip6cp->ip6c_ip6;
1144 		off = ip6cp->ip6c_off;
1145 		sa6_src = ip6cp->ip6c_src;
1146 	} else {
1147 		m = NULL;
1148 		ip6 = NULL;
1149 		sa6_src = &sa6_any;
1150 	}
1151 
1152 	if (ip6) {
1153 		/*
1154 		 * XXX: We assume that when ip6 is non NULL,
1155 		 * M and OFF are valid.
1156 		 */
1157 
1158 		/* check if we can safely examine src and dst ports */
1159 		if (m->m_pkthdr.len < off + sizeof(th))
1160 			return;
1161 
1162 		bzero(&th, sizeof(th));
1163 		m_copydata(m, off, sizeof(th), (caddr_t)&th);
1164 
1165 		if (cmd == PRC_MSGSIZE) {
1166 			int valid = 0;
1167 
1168 			/*
1169 			 * Check to see if we have a valid TCP connection
1170 			 * corresponding to the address in the ICMPv6 message
1171 			 * payload.
1172 			 */
1173 			if (in6_pcblookup_connect(&tcb6, &sa6->sin6_addr,
1174 			    th.th_dport, (struct in6_addr *)&sa6_src->sin6_addr,
1175 			    th.th_sport, 0))
1176 				valid++;
1177 
1178 			/*
1179 			 * Depending on the value of "valid" and routing table
1180 			 * size (mtudisc_{hi,lo}wat), we will:
1181 			 * - recalcurate the new MTU and create the
1182 			 *   corresponding routing entry, or
1183 			 * - ignore the MTU change notification.
1184 			 */
1185 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
1186 
1187 			/*
1188 			 * no need to call in6_pcbnotify, it should have been
1189 			 * called via callback if necessary
1190 			 */
1191 			return;
1192 		}
1193 
1194 		nmatch = in6_pcbnotify(&tcb6, sa, th.th_dport,
1195 		    (struct sockaddr *)sa6_src, th.th_sport, cmd, NULL, notify);
1196 		if (nmatch == 0 && syn_cache_count &&
1197 		    (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
1198 		     inet6ctlerrmap[cmd] == ENETUNREACH ||
1199 		     inet6ctlerrmap[cmd] == EHOSTDOWN))
1200 			syn_cache_unreach((struct sockaddr *)sa6_src,
1201 					  sa, &th);
1202 	} else {
1203 		(void) in6_pcbnotify(&tcb6, sa, 0, (struct sockaddr *)sa6_src,
1204 		    0, cmd, NULL, notify);
1205 	}
1206 }
1207 #endif
1208 
1209 #ifdef INET
1210 /* assumes that ip header and tcp header are contiguous on mbuf */
1211 void *
1212 tcp_ctlinput(cmd, sa, v)
1213 	int cmd;
1214 	struct sockaddr *sa;
1215 	void *v;
1216 {
1217 	struct ip *ip = v;
1218 	struct tcphdr *th;
1219 	struct icmp *icp;
1220 	extern int inetctlerrmap[];
1221 	void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1222 	int errno;
1223 	int nmatch;
1224 
1225 	if (sa->sa_family != AF_INET ||
1226 	    sa->sa_len != sizeof(struct sockaddr_in))
1227 		return NULL;
1228 	if ((unsigned)cmd >= PRC_NCMDS)
1229 		return NULL;
1230 	errno = inetctlerrmap[cmd];
1231 	if (cmd == PRC_QUENCH)
1232 		notify = tcp_quench;
1233 	else if (PRC_IS_REDIRECT(cmd))
1234 		notify = in_rtchange, ip = 0;
1235 	else if (cmd == PRC_MSGSIZE && ip_mtudisc && ip && ip->ip_v == 4) {
1236 		/*
1237 		 * Check to see if we have a valid TCP connection
1238 		 * corresponding to the address in the ICMP message
1239 		 * payload.
1240 		 */
1241 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1242 		if (in_pcblookup_connect(&tcbtable,
1243 					 ip->ip_dst, th->th_dport,
1244 					 ip->ip_src, th->th_sport) == NULL)
1245 			return NULL;
1246 
1247 		/*
1248 		 * Now that we've validated that we are actually communicating
1249 		 * with the host indicated in the ICMP message, locate the
1250 		 * ICMP header, recalculate the new MTU, and create the
1251 		 * corresponding routing entry.
1252 		 */
1253 		icp = (struct icmp *)((caddr_t)ip -
1254 		    offsetof(struct icmp, icmp_ip));
1255 		icmp_mtudisc(icp, ip->ip_dst);
1256 
1257 		return NULL;
1258 	} else if (cmd == PRC_HOSTDEAD)
1259 		ip = 0;
1260 	else if (errno == 0)
1261 		return NULL;
1262 	if (ip && ip->ip_v == 4 && sa->sa_family == AF_INET) {
1263 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
1264 		nmatch = in_pcbnotify(&tcbtable, satosin(sa)->sin_addr,
1265 		    th->th_dport, ip->ip_src, th->th_sport, errno, notify);
1266 		if (nmatch == 0 && syn_cache_count &&
1267 		    (inetctlerrmap[cmd] == EHOSTUNREACH ||
1268 		    inetctlerrmap[cmd] == ENETUNREACH ||
1269 		    inetctlerrmap[cmd] == EHOSTDOWN)) {
1270 			struct sockaddr_in sin;
1271 			bzero(&sin, sizeof(sin));
1272 			sin.sin_len = sizeof(sin);
1273 			sin.sin_family = AF_INET;
1274 			sin.sin_port = th->th_sport;
1275 			sin.sin_addr = ip->ip_src;
1276 			syn_cache_unreach((struct sockaddr *)&sin, sa, th);
1277 		}
1278 
1279 		/* XXX mapped address case */
1280 	} else
1281 		in_pcbnotifyall(&tcbtable, satosin(sa)->sin_addr, errno,
1282 		    notify);
1283 	return NULL;
1284 }
1285 
1286 /*
1287  * When a source quence is received, we are being notifed of congestion.
1288  * Close the congestion window down to the Loss Window (one segment).
1289  * We will gradually open it again as we proceed.
1290  */
1291 void
1292 tcp_quench(inp, errno)
1293 	struct inpcb *inp;
1294 	int errno;
1295 {
1296 	struct tcpcb *tp = intotcpcb(inp);
1297 
1298 	if (tp)
1299 		tp->snd_cwnd = tp->t_segsz;
1300 }
1301 #endif
1302 
1303 #ifdef INET6
1304 void
1305 tcp6_quench(in6p, errno)
1306 	struct in6pcb *in6p;
1307 	int errno;
1308 {
1309 	struct tcpcb *tp = in6totcpcb(in6p);
1310 
1311 	if (tp)
1312 		tp->snd_cwnd = tp->t_segsz;
1313 }
1314 #endif
1315 
1316 #ifdef INET
1317 /*
1318  * Path MTU Discovery handlers.
1319  */
1320 void
1321 tcp_mtudisc_callback(faddr)
1322 	struct in_addr faddr;
1323 {
1324 
1325 	in_pcbnotifyall(&tcbtable, faddr, EMSGSIZE, tcp_mtudisc);
1326 }
1327 
1328 /*
1329  * On receipt of path MTU corrections, flush old route and replace it
1330  * with the new one.  Retransmit all unacknowledged packets, to ensure
1331  * that all packets will be received.
1332  */
1333 void
1334 tcp_mtudisc(inp, errno)
1335 	struct inpcb *inp;
1336 	int errno;
1337 {
1338 	struct tcpcb *tp = intotcpcb(inp);
1339 	struct rtentry *rt = in_pcbrtentry(inp);
1340 
1341 	if (tp != 0) {
1342 		if (rt != 0) {
1343 			/*
1344 			 * If this was not a host route, remove and realloc.
1345 			 */
1346 			if ((rt->rt_flags & RTF_HOST) == 0) {
1347 				in_rtchange(inp, errno);
1348 				if ((rt = in_pcbrtentry(inp)) == 0)
1349 					return;
1350 			}
1351 
1352 			/*
1353 			 * Slow start out of the error condition.  We
1354 			 * use the MTU because we know it's smaller
1355 			 * than the previously transmitted segment.
1356 			 *
1357 			 * Note: This is more conservative than the
1358 			 * suggestion in draft-floyd-incr-init-win-03.
1359 			 */
1360 			if (rt->rt_rmx.rmx_mtu != 0)
1361 				tp->snd_cwnd =
1362 				    TCP_INITIAL_WINDOW(tcp_init_win,
1363 				    rt->rt_rmx.rmx_mtu);
1364 		}
1365 
1366 		/*
1367 		 * Resend unacknowledged packets.
1368 		 */
1369 		tp->snd_nxt = tp->snd_una;
1370 		tcp_output(tp);
1371 	}
1372 }
1373 #endif
1374 
1375 #ifdef INET6
1376 /*
1377  * Path MTU Discovery handlers.
1378  */
1379 void
1380 tcp6_mtudisc_callback(faddr)
1381 	struct in6_addr *faddr;
1382 {
1383 	struct sockaddr_in6 sin6;
1384 
1385 	bzero(&sin6, sizeof(sin6));
1386 	sin6.sin6_family = AF_INET6;
1387 	sin6.sin6_len = sizeof(struct sockaddr_in6);
1388 	sin6.sin6_addr = *faddr;
1389 	(void) in6_pcbnotify(&tcb6, (struct sockaddr *)&sin6, 0,
1390 	    (struct sockaddr *)&sa6_any, 0, PRC_MSGSIZE, NULL, tcp6_mtudisc);
1391 }
1392 
1393 void
1394 tcp6_mtudisc(in6p, errno)
1395 	struct in6pcb *in6p;
1396 	int errno;
1397 {
1398 	struct tcpcb *tp = in6totcpcb(in6p);
1399 	struct rtentry *rt = in6_pcbrtentry(in6p);
1400 
1401 	if (tp != 0) {
1402 		if (rt != 0) {
1403 			/*
1404 			 * If this was not a host route, remove and realloc.
1405 			 */
1406 			if ((rt->rt_flags & RTF_HOST) == 0) {
1407 				in6_rtchange(in6p, errno);
1408 				if ((rt = in6_pcbrtentry(in6p)) == 0)
1409 					return;
1410 			}
1411 
1412 			/*
1413 			 * Slow start out of the error condition.  We
1414 			 * use the MTU because we know it's smaller
1415 			 * than the previously transmitted segment.
1416 			 *
1417 			 * Note: This is more conservative than the
1418 			 * suggestion in draft-floyd-incr-init-win-03.
1419 			 */
1420 			if (rt->rt_rmx.rmx_mtu != 0)
1421 				tp->snd_cwnd =
1422 				    TCP_INITIAL_WINDOW(tcp_init_win,
1423 				    rt->rt_rmx.rmx_mtu);
1424 		}
1425 
1426 		/*
1427 		 * Resend unacknowledged packets.
1428 		 */
1429 		tp->snd_nxt = tp->snd_una;
1430 		tcp_output(tp);
1431 	}
1432 }
1433 #endif /* INET6 */
1434 
1435 /*
1436  * Compute the MSS to advertise to the peer.  Called only during
1437  * the 3-way handshake.  If we are the server (peer initiated
1438  * connection), we are called with a pointer to the interface
1439  * on which the SYN packet arrived.  If we are the client (we
1440  * initiated connection), we are called with a pointer to the
1441  * interface out which this connection should go.
1442  *
1443  * NOTE: Do not subtract IP option/extension header size nor IPsec
1444  * header size from MSS advertisement.  MSS option must hold the maximum
1445  * segment size we can accept, so it must always be:
1446  *	 max(if mtu) - ip header - tcp header
1447  */
1448 u_long
1449 tcp_mss_to_advertise(ifp, af)
1450 	const struct ifnet *ifp;
1451 	int af;
1452 {
1453 	extern u_long in_maxmtu;
1454 	u_long mss = 0;
1455 	u_long hdrsiz;
1456 
1457 	/*
1458 	 * In order to avoid defeating path MTU discovery on the peer,
1459 	 * we advertise the max MTU of all attached networks as our MSS,
1460 	 * per RFC 1191, section 3.1.
1461 	 *
1462 	 * We provide the option to advertise just the MTU of
1463 	 * the interface on which we hope this connection will
1464 	 * be receiving.  If we are responding to a SYN, we
1465 	 * will have a pretty good idea about this, but when
1466 	 * initiating a connection there is a bit more doubt.
1467 	 *
1468 	 * We also need to ensure that loopback has a large enough
1469 	 * MSS, as the loopback MTU is never included in in_maxmtu.
1470 	 */
1471 
1472 	if (ifp != NULL)
1473 		mss = ifp->if_mtu;
1474 
1475 	if (tcp_mss_ifmtu == 0)
1476 		mss = max(in_maxmtu, mss);
1477 
1478 	switch (af) {
1479 	case AF_INET:
1480 		hdrsiz = sizeof(struct ip);
1481 		break;
1482 #ifdef INET6
1483 	case AF_INET6:
1484 		hdrsiz = sizeof(struct ip6_hdr);
1485 		break;
1486 #endif
1487 	default:
1488 		hdrsiz = 0;
1489 		break;
1490 	}
1491 	hdrsiz += sizeof(struct tcphdr);
1492 	if (mss > hdrsiz)
1493 		mss -= hdrsiz;
1494 
1495 	mss = max(tcp_mssdflt, mss);
1496 	return (mss);
1497 }
1498 
1499 /*
1500  * Set connection variables based on the peer's advertised MSS.
1501  * We are passed the TCPCB for the actual connection.  If we
1502  * are the server, we are called by the compressed state engine
1503  * when the 3-way handshake is complete.  If we are the client,
1504  * we are called when we recieve the SYN,ACK from the server.
1505  *
1506  * NOTE: Our advertised MSS value must be initialized in the TCPCB
1507  * before this routine is called!
1508  */
1509 void
1510 tcp_mss_from_peer(tp, offer)
1511 	struct tcpcb *tp;
1512 	int offer;
1513 {
1514 	struct socket *so;
1515 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1516 	struct rtentry *rt;
1517 #endif
1518 	u_long bufsize;
1519 	int mss;
1520 
1521 #ifdef DIAGNOSTIC
1522 	if (tp->t_inpcb && tp->t_in6pcb)
1523 		panic("tcp_mss_from_peer: both t_inpcb and t_in6pcb are set");
1524 #endif
1525 	so = NULL;
1526 	rt = NULL;
1527 #ifdef INET
1528 	if (tp->t_inpcb) {
1529 		so = tp->t_inpcb->inp_socket;
1530 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1531 		rt = in_pcbrtentry(tp->t_inpcb);
1532 #endif
1533 	}
1534 #endif
1535 #ifdef INET6
1536 	if (tp->t_in6pcb) {
1537 		so = tp->t_in6pcb->in6p_socket;
1538 #if defined(RTV_SPIPE) || defined(RTV_SSTHRESH)
1539 		rt = in6_pcbrtentry(tp->t_in6pcb);
1540 #endif
1541 	}
1542 #endif
1543 
1544 	/*
1545 	 * As per RFC1122, use the default MSS value, unless they
1546 	 * sent us an offer.  Do not accept offers less than 32 bytes.
1547 	 */
1548 	mss = tcp_mssdflt;
1549 	if (offer)
1550 		mss = offer;
1551 	mss = max(mss, 32);		/* sanity */
1552 	tp->t_peermss = mss;
1553 	mss -= tcp_optlen(tp);
1554 #ifdef INET
1555 	if (tp->t_inpcb)
1556 		mss -= ip_optlen(tp->t_inpcb);
1557 #endif
1558 #ifdef INET6
1559 	if (tp->t_in6pcb)
1560 		mss -= ip6_optlen(tp->t_in6pcb);
1561 #endif
1562 
1563 	/*
1564 	 * If there's a pipesize, change the socket buffer to that size.
1565 	 * Make the socket buffer an integral number of MSS units.  If
1566 	 * the MSS is larger than the socket buffer, artificially decrease
1567 	 * the MSS.
1568 	 */
1569 #ifdef RTV_SPIPE
1570 	if (rt != NULL && rt->rt_rmx.rmx_sendpipe != 0)
1571 		bufsize = rt->rt_rmx.rmx_sendpipe;
1572 	else
1573 #endif
1574 		bufsize = so->so_snd.sb_hiwat;
1575 	if (bufsize < mss)
1576 		mss = bufsize;
1577 	else {
1578 		bufsize = roundup(bufsize, mss);
1579 		if (bufsize > sb_max)
1580 			bufsize = sb_max;
1581 		(void) sbreserve(&so->so_snd, bufsize);
1582 	}
1583 	tp->t_segsz = mss;
1584 
1585 #ifdef RTV_SSTHRESH
1586 	if (rt != NULL && rt->rt_rmx.rmx_ssthresh) {
1587 		/*
1588 		 * There's some sort of gateway or interface buffer
1589 		 * limit on the path.  Use this to set the slow
1590 		 * start threshold, but set the threshold to no less
1591 		 * than 2 * MSS.
1592 		 */
1593 		tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
1594 	}
1595 #endif
1596 }
1597 
1598 /*
1599  * Processing necessary when a TCP connection is established.
1600  */
1601 void
1602 tcp_established(tp)
1603 	struct tcpcb *tp;
1604 {
1605 	struct socket *so;
1606 #ifdef RTV_RPIPE
1607 	struct rtentry *rt;
1608 #endif
1609 	u_long bufsize;
1610 
1611 #ifdef DIAGNOSTIC
1612 	if (tp->t_inpcb && tp->t_in6pcb)
1613 		panic("tcp_established: both t_inpcb and t_in6pcb are set");
1614 #endif
1615 	so = NULL;
1616 	rt = NULL;
1617 #ifdef INET
1618 	if (tp->t_inpcb) {
1619 		so = tp->t_inpcb->inp_socket;
1620 #if defined(RTV_RPIPE)
1621 		rt = in_pcbrtentry(tp->t_inpcb);
1622 #endif
1623 	}
1624 #endif
1625 #ifdef INET6
1626 	if (tp->t_in6pcb) {
1627 		so = tp->t_in6pcb->in6p_socket;
1628 #if defined(RTV_RPIPE)
1629 		rt = in6_pcbrtentry(tp->t_in6pcb);
1630 #endif
1631 	}
1632 #endif
1633 
1634 	tp->t_state = TCPS_ESTABLISHED;
1635 	TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1636 
1637 #ifdef RTV_RPIPE
1638 	if (rt != NULL && rt->rt_rmx.rmx_recvpipe != 0)
1639 		bufsize = rt->rt_rmx.rmx_recvpipe;
1640 	else
1641 #endif
1642 		bufsize = so->so_rcv.sb_hiwat;
1643 	if (bufsize > tp->t_ourmss) {
1644 		bufsize = roundup(bufsize, tp->t_ourmss);
1645 		if (bufsize > sb_max)
1646 			bufsize = sb_max;
1647 		(void) sbreserve(&so->so_rcv, bufsize);
1648 	}
1649 }
1650 
1651 /*
1652  * Check if there's an initial rtt or rttvar.  Convert from the
1653  * route-table units to scaled multiples of the slow timeout timer.
1654  * Called only during the 3-way handshake.
1655  */
1656 void
1657 tcp_rmx_rtt(tp)
1658 	struct tcpcb *tp;
1659 {
1660 #ifdef RTV_RTT
1661 	struct rtentry *rt = NULL;
1662 	int rtt;
1663 
1664 #ifdef DIAGNOSTIC
1665 	if (tp->t_inpcb && tp->t_in6pcb)
1666 		panic("tcp_rmx_rtt: both t_inpcb and t_in6pcb are set");
1667 #endif
1668 #ifdef INET
1669 	if (tp->t_inpcb)
1670 		rt = in_pcbrtentry(tp->t_inpcb);
1671 #endif
1672 #ifdef INET6
1673 	if (tp->t_in6pcb)
1674 		rt = in6_pcbrtentry(tp->t_in6pcb);
1675 #endif
1676 	if (rt == NULL)
1677 		return;
1678 
1679 	if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
1680 		/*
1681 		 * XXX The lock bit for MTU indicates that the value
1682 		 * is also a minimum value; this is subject to time.
1683 		 */
1684 		if (rt->rt_rmx.rmx_locks & RTV_RTT)
1685 			TCPT_RANGESET(tp->t_rttmin,
1686 			    rtt / (RTM_RTTUNIT / PR_SLOWHZ),
1687 			    TCPTV_MIN, TCPTV_REXMTMAX);
1688 		tp->t_srtt = rtt /
1689 		    ((RTM_RTTUNIT / PR_SLOWHZ) >> (TCP_RTT_SHIFT + 2));
1690 		if (rt->rt_rmx.rmx_rttvar) {
1691 			tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
1692 			    ((RTM_RTTUNIT / PR_SLOWHZ) >>
1693 				(TCP_RTTVAR_SHIFT + 2));
1694 		} else {
1695 			/* Default variation is +- 1 rtt */
1696 			tp->t_rttvar =
1697 			    tp->t_srtt >> (TCP_RTT_SHIFT - TCP_RTTVAR_SHIFT);
1698 		}
1699 		TCPT_RANGESET(tp->t_rxtcur,
1700 		    ((tp->t_srtt >> 2) + tp->t_rttvar) >> (1 + 2),
1701 		    tp->t_rttmin, TCPTV_REXMTMAX);
1702 	}
1703 #endif
1704 }
1705 
1706 tcp_seq	 tcp_iss_seq = 0;	/* tcp initial seq # */
1707 
1708 /*
1709  * Get a new sequence value given a tcp control block
1710  */
1711 tcp_seq
1712 tcp_new_iss(tp, len, addin)
1713 	void            *tp;
1714 	u_long           len;
1715 	tcp_seq		 addin;
1716 {
1717 	tcp_seq          tcp_iss;
1718 
1719 	/*
1720 	 * Randomize.
1721 	 */
1722 #if NRND > 0
1723 	rnd_extract_data(&tcp_iss, sizeof(tcp_iss), RND_EXTRACT_ANY);
1724 #else
1725 	tcp_iss = random();
1726 #endif
1727 
1728 	/*
1729 	 * If we were asked to add some amount to a known value,
1730 	 * we will take a random value obtained above, mask off the upper
1731 	 * bits, and add in the known value.  We also add in a constant to
1732 	 * ensure that we are at least a certain distance from the original
1733 	 * value.
1734 	 *
1735 	 * This is used when an old connection is in timed wait
1736 	 * and we have a new one coming in, for instance.
1737 	 */
1738 	if (addin != 0) {
1739 #ifdef TCPISS_DEBUG
1740 		printf("Random %08x, ", tcp_iss);
1741 #endif
1742 		tcp_iss &= TCP_ISS_RANDOM_MASK;
1743 		tcp_iss += addin + TCP_ISSINCR;
1744 #ifdef TCPISS_DEBUG
1745 		printf("Old ISS %08x, ISS %08x\n", addin, tcp_iss);
1746 #endif
1747 	} else {
1748 		tcp_iss &= TCP_ISS_RANDOM_MASK;
1749 		tcp_iss += tcp_iss_seq;
1750 		tcp_iss_seq += TCP_ISSINCR;
1751 #ifdef TCPISS_DEBUG
1752 		printf("ISS %08x\n", tcp_iss);
1753 #endif
1754 	}
1755 
1756 	if (tcp_compat_42) {
1757 		/*
1758 		 * Limit it to the positive range for really old TCP
1759 		 * implementations.
1760 		 */
1761 		if (tcp_iss >= 0x80000000)
1762 			tcp_iss &= 0x7fffffff;		/* XXX */
1763 	}
1764 
1765 	return tcp_iss;
1766 }
1767 
1768 #ifdef IPSEC
1769 /* compute ESP/AH header size for TCP, including outer IP header. */
1770 size_t
1771 ipsec4_hdrsiz_tcp(tp)
1772 	struct tcpcb *tp;
1773 {
1774 	struct inpcb *inp;
1775 	size_t hdrsiz;
1776 
1777 	/* XXX mapped addr case (tp->t_in6pcb) */
1778 	if (!tp || !tp->t_template || !(inp = tp->t_inpcb))
1779 		return 0;
1780 	switch (tp->t_family) {
1781 	case AF_INET:
1782 		/* XXX: should use currect direction. */
1783 		hdrsiz = ipsec4_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, inp);
1784 		break;
1785 	default:
1786 		hdrsiz = 0;
1787 		break;
1788 	}
1789 
1790 	return hdrsiz;
1791 }
1792 
1793 #ifdef INET6
1794 size_t
1795 ipsec6_hdrsiz_tcp(tp)
1796 	struct tcpcb *tp;
1797 {
1798 	struct in6pcb *in6p;
1799 	size_t hdrsiz;
1800 
1801 	if (!tp || !tp->t_template || !(in6p = tp->t_in6pcb))
1802 		return 0;
1803 	switch (tp->t_family) {
1804 	case AF_INET6:
1805 		/* XXX: should use currect direction. */
1806 		hdrsiz = ipsec6_hdrsiz(tp->t_template, IPSEC_DIR_OUTBOUND, in6p);
1807 		break;
1808 	case AF_INET:
1809 		/* mapped address case - tricky */
1810 	default:
1811 		hdrsiz = 0;
1812 		break;
1813 	}
1814 
1815 	return hdrsiz;
1816 }
1817 #endif
1818 #endif /*IPSEC*/
1819 
1820 /*
1821  * Determine the length of the TCP options for this connection.
1822  *
1823  * XXX:  What do we do for SACK, when we add that?  Just reserve
1824  *       all of the space?  Otherwise we can't exactly be incrementing
1825  *       cwnd by an amount that varies depending on the amount we last
1826  *       had to SACK!
1827  */
1828 
1829 u_int
1830 tcp_optlen(tp)
1831 	struct tcpcb *tp;
1832 {
1833 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP|TF_NOOPT)) ==
1834 	    (TF_REQ_TSTMP | TF_RCVD_TSTMP))
1835 		return TCPOLEN_TSTAMP_APPA;
1836 	else
1837 		return 0;
1838 }
1839