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