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