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