xref: /openbsd-src/sys/netinet/tcp_subr.c (revision d1df930ffab53da22f3324c32bed7ac5709915e6)
1 /*	$OpenBSD: tcp_subr.c,v 1.173 2018/09/20 18:59:10 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 	CTASSERT(sizeof(struct ip) + sizeof(struct tcphdr) <= MHLEN);
195 	CTASSERT(sizeof(struct ip6_hdr) + sizeof(struct tcphdr) <= MHLEN);
196 
197 	if ((m = tp->t_template) == 0) {
198 		m = m_get(M_DONTWAIT, MT_HEADER);
199 		if (m == NULL)
200 			return (0);
201 
202 		switch (tp->pf) {
203 		case 0:	/*default to PF_INET*/
204 		case AF_INET:
205 			m->m_len = sizeof(struct ip);
206 			break;
207 #ifdef INET6
208 		case AF_INET6:
209 			m->m_len = sizeof(struct ip6_hdr);
210 			break;
211 #endif /* INET6 */
212 		}
213 		m->m_len += sizeof (struct tcphdr);
214 	}
215 
216 	switch(tp->pf) {
217 	case AF_INET:
218 		{
219 			struct ipovly *ipovly;
220 
221 			ipovly = mtod(m, struct ipovly *);
222 
223 			bzero(ipovly->ih_x1, sizeof ipovly->ih_x1);
224 			ipovly->ih_pr = IPPROTO_TCP;
225 			ipovly->ih_len = htons(sizeof (struct tcphdr));
226 			ipovly->ih_src = inp->inp_laddr;
227 			ipovly->ih_dst = inp->inp_faddr;
228 
229 			th = (struct tcphdr *)(mtod(m, caddr_t) +
230 				sizeof(struct ip));
231 		}
232 		break;
233 #ifdef INET6
234 	case AF_INET6:
235 		{
236 			struct ip6_hdr *ip6;
237 
238 			ip6 = mtod(m, struct ip6_hdr *);
239 
240 			ip6->ip6_src = inp->inp_laddr6;
241 			ip6->ip6_dst = inp->inp_faddr6;
242 			ip6->ip6_flow = htonl(0x60000000) |
243 			    (inp->inp_flowinfo & IPV6_FLOWLABEL_MASK);
244 
245 			ip6->ip6_nxt = IPPROTO_TCP;
246 			ip6->ip6_plen = htons(sizeof(struct tcphdr)); /*XXX*/
247 			ip6->ip6_hlim = in6_selecthlim(inp);	/*XXX*/
248 
249 			th = (struct tcphdr *)(mtod(m, caddr_t) +
250 				sizeof(struct ip6_hdr));
251 		}
252 		break;
253 #endif /* INET6 */
254 	}
255 
256 	th->th_sport = inp->inp_lport;
257 	th->th_dport = inp->inp_fport;
258 	th->th_seq = 0;
259 	th->th_ack = 0;
260 	th->th_x2  = 0;
261 	th->th_off = 5;
262 	th->th_flags = 0;
263 	th->th_win = 0;
264 	th->th_urp = 0;
265 	th->th_sum = 0;
266 	return (m);
267 }
268 
269 /*
270  * Send a single message to the TCP at address specified by
271  * the given TCP/IP header.  If m == 0, then we make a copy
272  * of the tcpiphdr at ti and send directly to the addressed host.
273  * This is used to force keep alive messages out using the TCP
274  * template for a connection tp->t_template.  If flags are given
275  * then we send a message back to the TCP which originated the
276  * segment ti, and discard the mbuf containing it and any other
277  * attached mbufs.
278  *
279  * In any case the ack and sequence number of the transmitted
280  * segment are as specified by the parameters.
281  */
282 void
283 tcp_respond(struct tcpcb *tp, caddr_t template, struct tcphdr *th0,
284     tcp_seq ack, tcp_seq seq, int flags, u_int rtableid)
285 {
286 	int tlen;
287 	int win = 0;
288 	struct mbuf *m = NULL;
289 	struct tcphdr *th;
290 	struct ip *ip;
291 #ifdef INET6
292 	struct ip6_hdr *ip6;
293 #endif
294 	int af;		/* af on wire */
295 
296 	if (tp) {
297 		struct socket *so = tp->t_inpcb->inp_socket;
298 		win = sbspace(so, &so->so_rcv);
299 		/*
300 		 * If this is called with an unconnected
301 		 * socket/tp/pcb (tp->pf is 0), we lose.
302 		 */
303 		af = tp->pf;
304 	} else
305 		af = (((struct ip *)template)->ip_v == 6) ? AF_INET6 : AF_INET;
306 
307 	m = m_gethdr(M_DONTWAIT, MT_HEADER);
308 	if (m == NULL)
309 		return;
310 	m->m_data += max_linkhdr;
311 	tlen = 0;
312 
313 #define xchg(a,b,type) do { type t; t=a; a=b; b=t; } while (0)
314 	switch (af) {
315 #ifdef INET6
316 	case AF_INET6:
317 		ip6 = mtod(m, struct ip6_hdr *);
318 		th = (struct tcphdr *)(ip6 + 1);
319 		tlen = sizeof(*ip6) + sizeof(*th);
320 		if (th0) {
321 			bcopy(template, ip6, sizeof(*ip6));
322 			bcopy(th0, th, sizeof(*th));
323 			xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
324 		} else {
325 			bcopy(template, ip6, tlen);
326 		}
327 		break;
328 #endif /* INET6 */
329 	case AF_INET:
330 		ip = mtod(m, struct ip *);
331 		th = (struct tcphdr *)(ip + 1);
332 		tlen = sizeof(*ip) + sizeof(*th);
333 		if (th0) {
334 			bcopy(template, ip, sizeof(*ip));
335 			bcopy(th0, th, sizeof(*th));
336 			xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, u_int32_t);
337 		} else {
338 			bcopy(template, ip, tlen);
339 		}
340 		break;
341 	}
342 	if (th0)
343 		xchg(th->th_dport, th->th_sport, u_int16_t);
344 	else
345 		flags = TH_ACK;
346 #undef xchg
347 
348 	th->th_seq = htonl(seq);
349 	th->th_ack = htonl(ack);
350 	th->th_x2 = 0;
351 	th->th_off = sizeof (struct tcphdr) >> 2;
352 	th->th_flags = flags;
353 	if (tp)
354 		win >>= tp->rcv_scale;
355 	if (win > TCP_MAXWIN)
356 		win = TCP_MAXWIN;
357 	th->th_win = htons((u_int16_t)win);
358 	th->th_urp = 0;
359 
360 	if (tp && (tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
361 	    (flags & TH_RST) == 0 && (tp->t_flags & TF_RCVD_TSTMP)) {
362 		u_int32_t *lp = (u_int32_t *)(th + 1);
363 		/* Form timestamp option as shown in appendix A of RFC 1323. */
364 		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
365 		*lp++ = htonl(tcp_now + tp->ts_modulate);
366 		*lp   = htonl(tp->ts_recent);
367 		tlen += TCPOLEN_TSTAMP_APPA;
368 		th->th_off = (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_APPA) >> 2;
369 	}
370 
371 	m->m_len = tlen;
372 	m->m_pkthdr.len = tlen;
373 	m->m_pkthdr.ph_ifidx = 0;
374 	m->m_pkthdr.csum_flags |= M_TCP_CSUM_OUT;
375 
376 	/* force routing table */
377 	if (tp)
378 		m->m_pkthdr.ph_rtableid = tp->t_inpcb->inp_rtableid;
379 	else
380 		m->m_pkthdr.ph_rtableid = rtableid;
381 
382 	switch (af) {
383 #ifdef INET6
384 	case AF_INET6:
385 		ip6->ip6_flow = htonl(0x60000000);
386 		ip6->ip6_nxt  = IPPROTO_TCP;
387 		ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL);	/*XXX*/
388 		ip6->ip6_plen = tlen - sizeof(struct ip6_hdr);
389 		ip6->ip6_plen = htons(ip6->ip6_plen);
390 		ip6_output(m, tp ? tp->t_inpcb->inp_outputopts6 : NULL,
391 		    tp ? &tp->t_inpcb->inp_route6 : NULL,
392 		    0, NULL,
393 		    tp ? tp->t_inpcb : NULL);
394 		break;
395 #endif /* INET6 */
396 	case AF_INET:
397 		ip->ip_len = htons(tlen);
398 		ip->ip_ttl = ip_defttl;
399 		ip->ip_tos = 0;
400 		ip_output(m, NULL,
401 		    tp ? &tp->t_inpcb->inp_route : NULL,
402 		    ip_mtudisc ? IP_MTUDISC : 0, NULL,
403 		    tp ? tp->t_inpcb : NULL, 0);
404 		break;
405 	}
406 }
407 
408 /*
409  * Create a new TCP control block, making an
410  * empty reassembly queue and hooking it to the argument
411  * protocol control block.
412  */
413 struct tcpcb *
414 tcp_newtcpcb(struct inpcb *inp)
415 {
416 	struct tcpcb *tp;
417 	int i;
418 
419 	tp = pool_get(&tcpcb_pool, PR_NOWAIT|PR_ZERO);
420 	if (tp == NULL)
421 		return (NULL);
422 	TAILQ_INIT(&tp->t_segq);
423 	tp->t_maxseg = tcp_mssdflt;
424 	tp->t_maxopd = 0;
425 
426 	for (i = 0; i < TCPT_NTIMERS; i++)
427 		TCP_TIMER_INIT(tp, i);
428 
429 	tp->sack_enable = tcp_do_sack;
430 	tp->t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
431 	tp->t_inpcb = inp;
432 	/*
433 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
434 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
435 	 * reasonable initial retransmit time.
436 	 */
437 	tp->t_srtt = TCPTV_SRTTBASE;
438 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ <<
439 	    (TCP_RTTVAR_SHIFT + TCP_RTT_BASE_SHIFT - 1);
440 	tp->t_rttmin = TCPTV_MIN;
441 	TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
442 	    TCPTV_MIN, TCPTV_REXMTMAX);
443 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
444 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
445 
446 	tp->t_pmtud_mtu_sent = 0;
447 	tp->t_pmtud_mss_acked = 0;
448 
449 #ifdef INET6
450 	/* we disallow IPv4 mapped address completely. */
451 	if ((inp->inp_flags & INP_IPV6) == 0)
452 		tp->pf = PF_INET;
453 	else
454 		tp->pf = PF_INET6;
455 #else
456 	tp->pf = PF_INET;
457 #endif
458 
459 #ifdef INET6
460 	if (inp->inp_flags & INP_IPV6)
461 		inp->inp_ipv6.ip6_hlim = ip6_defhlim;
462 	else
463 #endif /* INET6 */
464 		inp->inp_ip.ip_ttl = ip_defttl;
465 
466 	inp->inp_ppcb = (caddr_t)tp;
467 	return (tp);
468 }
469 
470 /*
471  * Drop a TCP connection, reporting
472  * the specified error.  If connection is synchronized,
473  * then send a RST to peer.
474  */
475 struct tcpcb *
476 tcp_drop(struct tcpcb *tp, int errno)
477 {
478 	struct socket *so = tp->t_inpcb->inp_socket;
479 
480 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
481 		tp->t_state = TCPS_CLOSED;
482 		(void) tcp_output(tp);
483 		tcpstat_inc(tcps_drops);
484 	} else
485 		tcpstat_inc(tcps_conndrops);
486 	if (errno == ETIMEDOUT && tp->t_softerror)
487 		errno = tp->t_softerror;
488 	so->so_error = errno;
489 	return (tcp_close(tp));
490 }
491 
492 /*
493  * Close a TCP control block:
494  *	discard all space held by the tcp
495  *	discard internet protocol block
496  *	wake up any sleepers
497  */
498 struct tcpcb *
499 tcp_close(struct tcpcb *tp)
500 {
501 	struct inpcb *inp = tp->t_inpcb;
502 	struct socket *so = inp->inp_socket;
503 	struct sackhole *p, *q;
504 
505 	/* free the reassembly queue, if any */
506 	tcp_freeq(tp);
507 
508 	tcp_canceltimers(tp);
509 	syn_cache_cleanup(tp);
510 
511 	/* Free SACK holes. */
512 	q = p = tp->snd_holes;
513 	while (p != 0) {
514 		q = p->next;
515 		pool_put(&sackhl_pool, p);
516 		p = q;
517 	}
518 
519 	m_free(tp->t_template);
520 	/* Free tcpcb after all pending timers have been run. */
521 	TCP_TIMER_ARM(tp, TCPT_REAPER, 0);
522 
523 	mtx_enter(&inp->inp_mtx);
524 	inp->inp_ppcb = NULL;
525 	mtx_leave(&inp->inp_mtx);
526 	soisdisconnected(so);
527 	in_pcbdetach(inp);
528 	return (NULL);
529 }
530 
531 int
532 tcp_freeq(struct tcpcb *tp)
533 {
534 	struct tcpqent *qe;
535 	int rv = 0;
536 
537 	while ((qe = TAILQ_FIRST(&tp->t_segq)) != NULL) {
538 		TAILQ_REMOVE(&tp->t_segq, qe, tcpqe_q);
539 		m_freem(qe->tcpqe_m);
540 		pool_put(&tcpqe_pool, qe);
541 		rv = 1;
542 	}
543 	return (rv);
544 }
545 
546 /*
547  * Compute proper scaling value for receiver window from buffer space
548  */
549 
550 void
551 tcp_rscale(struct tcpcb *tp, u_long hiwat)
552 {
553 	tp->request_r_scale = 0;
554 	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
555 	       TCP_MAXWIN << tp->request_r_scale < hiwat)
556 		tp->request_r_scale++;
557 }
558 
559 /*
560  * Notify a tcp user of an asynchronous error;
561  * store error as soft error, but wake up user
562  * (for now, won't do anything until can select for soft error).
563  */
564 void
565 tcp_notify(struct inpcb *inp, int error)
566 {
567 	struct tcpcb *tp = intotcpcb(inp);
568 	struct socket *so = inp->inp_socket;
569 
570 	/*
571 	 * Ignore some errors if we are hooked up.
572 	 * If connection hasn't completed, has retransmitted several times,
573 	 * and receives a second error, give up now.  This is better
574 	 * than waiting a long time to establish a connection that
575 	 * can never complete.
576 	 */
577 	if (tp->t_state == TCPS_ESTABLISHED &&
578 	     (error == EHOSTUNREACH || error == ENETUNREACH ||
579 	      error == EHOSTDOWN)) {
580 		return;
581 	} else if (TCPS_HAVEESTABLISHED(tp->t_state) == 0 &&
582 	    tp->t_rxtshift > 3 && tp->t_softerror)
583 		so->so_error = error;
584 	else
585 		tp->t_softerror = error;
586 	wakeup((caddr_t) &so->so_timeo);
587 	sorwakeup(so);
588 	sowwakeup(so);
589 }
590 
591 #ifdef INET6
592 void
593 tcp6_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *d)
594 {
595 	struct tcphdr th;
596 	struct tcpcb *tp;
597 	void (*notify)(struct inpcb *, int) = tcp_notify;
598 	struct ip6_hdr *ip6;
599 	const struct sockaddr_in6 *sa6_src = NULL;
600 	struct sockaddr_in6 *sa6 = satosin6(sa);
601 	struct inpcb *inp;
602 	struct mbuf *m;
603 	tcp_seq seq;
604 	int off;
605 	struct {
606 		u_int16_t th_sport;
607 		u_int16_t th_dport;
608 		u_int32_t th_seq;
609 	} *thp;
610 
611 	CTASSERT(sizeof(*thp) <= sizeof(th));
612 	if (sa->sa_family != AF_INET6 ||
613 	    sa->sa_len != sizeof(struct sockaddr_in6) ||
614 	    IN6_IS_ADDR_UNSPECIFIED(&sa6->sin6_addr) ||
615 	    IN6_IS_ADDR_V4MAPPED(&sa6->sin6_addr))
616 		return;
617 	if ((unsigned)cmd >= PRC_NCMDS)
618 		return;
619 	else if (cmd == PRC_QUENCH) {
620 		/*
621 		 * Don't honor ICMP Source Quench messages meant for
622 		 * TCP connections.
623 		 */
624 		/* XXX there's no PRC_QUENCH in IPv6 */
625 		return;
626 	} else if (PRC_IS_REDIRECT(cmd))
627 		notify = in_rtchange, d = NULL;
628 	else if (cmd == PRC_MSGSIZE)
629 		; /* special code is present, see below */
630 	else if (cmd == PRC_HOSTDEAD)
631 		d = NULL;
632 	else if (inet6ctlerrmap[cmd] == 0)
633 		return;
634 
635 	/* if the parameter is from icmp6, decode it. */
636 	if (d != NULL) {
637 		struct ip6ctlparam *ip6cp = (struct ip6ctlparam *)d;
638 		m = ip6cp->ip6c_m;
639 		ip6 = ip6cp->ip6c_ip6;
640 		off = ip6cp->ip6c_off;
641 		sa6_src = ip6cp->ip6c_src;
642 	} else {
643 		m = NULL;
644 		ip6 = NULL;
645 		sa6_src = &sa6_any;
646 	}
647 
648 	if (ip6) {
649 		/*
650 		 * XXX: We assume that when ip6 is non NULL,
651 		 * M and OFF are valid.
652 		 */
653 
654 		/* check if we can safely examine src and dst ports */
655 		if (m->m_pkthdr.len < off + sizeof(*thp))
656 			return;
657 
658 		bzero(&th, sizeof(th));
659 		m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
660 
661 		/*
662 		 * Check to see if we have a valid TCP connection
663 		 * corresponding to the address in the ICMPv6 message
664 		 * payload.
665 		 */
666 		inp = in6_pcbhashlookup(&tcbtable, &sa6->sin6_addr,
667 		    th.th_dport, &sa6_src->sin6_addr, th.th_sport, rdomain);
668 		if (cmd == PRC_MSGSIZE) {
669 			/*
670 			 * Depending on the value of "valid" and routing table
671 			 * size (mtudisc_{hi,lo}wat), we will:
672 			 * - recalcurate the new MTU and create the
673 			 *   corresponding routing entry, or
674 			 * - ignore the MTU change notification.
675 			 */
676 			icmp6_mtudisc_update((struct ip6ctlparam *)d, inp != NULL);
677 			return;
678 		}
679 		if (inp) {
680 			seq = ntohl(th.th_seq);
681 			if (inp->inp_socket &&
682 			    (tp = intotcpcb(inp)) &&
683 			    SEQ_GEQ(seq, tp->snd_una) &&
684 			    SEQ_LT(seq, tp->snd_max))
685 				notify(inp, inet6ctlerrmap[cmd]);
686 		} else if (inet6ctlerrmap[cmd] == EHOSTUNREACH ||
687 		    inet6ctlerrmap[cmd] == ENETUNREACH ||
688 		    inet6ctlerrmap[cmd] == EHOSTDOWN)
689 			syn_cache_unreach((struct sockaddr *)sa6_src,
690 			    sa, &th, rdomain);
691 	} else {
692 		(void) in6_pcbnotify(&tcbtable, sa6, 0,
693 		    sa6_src, 0, rdomain, cmd, NULL, notify);
694 	}
695 }
696 #endif
697 
698 void
699 tcp_ctlinput(int cmd, struct sockaddr *sa, u_int rdomain, void *v)
700 {
701 	struct ip *ip = v;
702 	struct tcphdr *th;
703 	struct tcpcb *tp;
704 	struct inpcb *inp;
705 	struct in_addr faddr;
706 	tcp_seq seq;
707 	u_int mtu;
708 	void (*notify)(struct inpcb *, int) = tcp_notify;
709 	int errno;
710 
711 	if (sa->sa_family != AF_INET)
712 		return;
713 	faddr = satosin(sa)->sin_addr;
714 	if (faddr.s_addr == INADDR_ANY)
715 		return;
716 
717 	if ((unsigned)cmd >= PRC_NCMDS)
718 		return;
719 	errno = inetctlerrmap[cmd];
720 	if (cmd == PRC_QUENCH)
721 		/*
722 		 * Don't honor ICMP Source Quench messages meant for
723 		 * TCP connections.
724 		 */
725 		return;
726 	else if (PRC_IS_REDIRECT(cmd))
727 		notify = in_rtchange, ip = 0;
728 	else if (cmd == PRC_MSGSIZE && ip_mtudisc && ip) {
729 		/*
730 		 * Verify that the packet in the icmp payload refers
731 		 * to an existing TCP connection.
732 		 */
733 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
734 		seq = ntohl(th->th_seq);
735 		inp = in_pcbhashlookup(&tcbtable,
736 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
737 		    rdomain);
738 		if (inp && (tp = intotcpcb(inp)) &&
739 		    SEQ_GEQ(seq, tp->snd_una) &&
740 		    SEQ_LT(seq, tp->snd_max)) {
741 			struct icmp *icp;
742 			icp = (struct icmp *)((caddr_t)ip -
743 					      offsetof(struct icmp, icmp_ip));
744 
745 			/*
746 			 * If the ICMP message advertises a Next-Hop MTU
747 			 * equal or larger than the maximum packet size we have
748 			 * ever sent, drop the message.
749 			 */
750 			mtu = (u_int)ntohs(icp->icmp_nextmtu);
751 			if (mtu >= tp->t_pmtud_mtu_sent)
752 				return;
753 			if (mtu >= tcp_hdrsz(tp) + tp->t_pmtud_mss_acked) {
754 				/*
755 				 * Calculate new MTU, and create corresponding
756 				 * route (traditional PMTUD).
757 				 */
758 				tp->t_flags &= ~TF_PMTUD_PEND;
759 				icmp_mtudisc(icp, inp->inp_rtableid);
760 			} else {
761 				/*
762 				 * Record the information got in the ICMP
763 				 * message; act on it later.
764 				 * If we had already recorded an ICMP message,
765 				 * replace the old one only if the new message
766 				 * refers to an older TCP segment
767 				 */
768 				if (tp->t_flags & TF_PMTUD_PEND) {
769 					if (SEQ_LT(tp->t_pmtud_th_seq, seq))
770 						return;
771 				} else
772 					tp->t_flags |= TF_PMTUD_PEND;
773 				tp->t_pmtud_th_seq = seq;
774 				tp->t_pmtud_nextmtu = icp->icmp_nextmtu;
775 				tp->t_pmtud_ip_len = icp->icmp_ip.ip_len;
776 				tp->t_pmtud_ip_hl = icp->icmp_ip.ip_hl;
777 				return;
778 			}
779 		} else {
780 			/* ignore if we don't have a matching connection */
781 			return;
782 		}
783 		notify = tcp_mtudisc, ip = 0;
784 	} else if (cmd == PRC_MTUINC)
785 		notify = tcp_mtudisc_increase, ip = 0;
786 	else if (cmd == PRC_HOSTDEAD)
787 		ip = 0;
788 	else if (errno == 0)
789 		return;
790 
791 	if (ip) {
792 		th = (struct tcphdr *)((caddr_t)ip + (ip->ip_hl << 2));
793 		inp = in_pcbhashlookup(&tcbtable,
794 		    ip->ip_dst, th->th_dport, ip->ip_src, th->th_sport,
795 		    rdomain);
796 		if (inp) {
797 			seq = ntohl(th->th_seq);
798 			if (inp->inp_socket &&
799 			    (tp = intotcpcb(inp)) &&
800 			    SEQ_GEQ(seq, tp->snd_una) &&
801 			    SEQ_LT(seq, tp->snd_max))
802 				notify(inp, errno);
803 		} else if (inetctlerrmap[cmd] == EHOSTUNREACH ||
804 		    inetctlerrmap[cmd] == ENETUNREACH ||
805 		    inetctlerrmap[cmd] == EHOSTDOWN) {
806 			struct sockaddr_in sin;
807 
808 			bzero(&sin, sizeof(sin));
809 			sin.sin_len = sizeof(sin);
810 			sin.sin_family = AF_INET;
811 			sin.sin_port = th->th_sport;
812 			sin.sin_addr = ip->ip_src;
813 			syn_cache_unreach(sintosa(&sin), sa, th, rdomain);
814 		}
815 	} else
816 		in_pcbnotifyall(&tcbtable, sa, rdomain, errno, notify);
817 }
818 
819 
820 #ifdef INET6
821 /*
822  * Path MTU Discovery handlers.
823  */
824 void
825 tcp6_mtudisc_callback(struct sockaddr_in6 *sin6, u_int rdomain)
826 {
827 	(void) in6_pcbnotify(&tcbtable, sin6, 0,
828 	    &sa6_any, 0, rdomain, PRC_MSGSIZE, NULL, tcp_mtudisc);
829 }
830 #endif /* INET6 */
831 
832 /*
833  * On receipt of path MTU corrections, flush old route and replace it
834  * with the new one.  Retransmit all unacknowledged packets, to ensure
835  * that all packets will be received.
836  */
837 void
838 tcp_mtudisc(struct inpcb *inp, int errno)
839 {
840 	struct tcpcb *tp = intotcpcb(inp);
841 	struct rtentry *rt;
842 	int change = 0;
843 
844 	if (tp == NULL)
845 		return;
846 
847 	rt = in_pcbrtentry(inp);
848 	if (rt != NULL) {
849 		int orig_maxseg = tp->t_maxseg;
850 
851 		/*
852 		 * If this was not a host route, remove and realloc.
853 		 */
854 		if ((rt->rt_flags & RTF_HOST) == 0) {
855 			in_rtchange(inp, errno);
856 			if ((rt = in_pcbrtentry(inp)) == NULL)
857 				return;
858 		}
859 		if (orig_maxseg != tp->t_maxseg ||
860 		    (rt->rt_locks & RTV_MTU))
861 			change = 1;
862 	}
863 	tcp_mss(tp, -1);
864 
865 	/*
866 	 * Resend unacknowledged packets
867 	 */
868 	tp->snd_nxt = tp->snd_una;
869 	if (change || errno > 0)
870 		tcp_output(tp);
871 }
872 
873 void
874 tcp_mtudisc_increase(struct inpcb *inp, int errno)
875 {
876 	struct tcpcb *tp = intotcpcb(inp);
877 	struct rtentry *rt = in_pcbrtentry(inp);
878 
879 	if (tp != 0 && rt != 0) {
880 		/*
881 		 * If this was a host route, remove and realloc.
882 		 */
883 		if (rt->rt_flags & RTF_HOST)
884 			in_rtchange(inp, errno);
885 
886 		/* also takes care of congestion window */
887 		tcp_mss(tp, -1);
888 	}
889 }
890 
891 /*
892  * Generate new ISNs with a method based on RFC1948
893  */
894 #define TCP_ISS_CONN_INC 4096
895 
896 void
897 tcp_set_iss_tsm(struct tcpcb *tp)
898 {
899 	SHA2_CTX ctx;
900 	union {
901 		uint8_t bytes[SHA512_DIGEST_LENGTH];
902 		uint32_t words[2];
903 	} digest;
904 	u_int rdomain = rtable_l2(tp->t_inpcb->inp_rtableid);
905 
906 	ctx = tcp_secret_ctx;
907 	SHA512Update(&ctx, &rdomain, sizeof(rdomain));
908 	SHA512Update(&ctx, &tp->t_inpcb->inp_lport, sizeof(u_short));
909 	SHA512Update(&ctx, &tp->t_inpcb->inp_fport, sizeof(u_short));
910 	if (tp->pf == AF_INET6) {
911 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr6,
912 		    sizeof(struct in6_addr));
913 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr6,
914 		    sizeof(struct in6_addr));
915 	} else {
916 		SHA512Update(&ctx, &tp->t_inpcb->inp_laddr,
917 		    sizeof(struct in_addr));
918 		SHA512Update(&ctx, &tp->t_inpcb->inp_faddr,
919 		    sizeof(struct in_addr));
920 	}
921 	SHA512Final(digest.bytes, &ctx);
922 	tcp_iss += TCP_ISS_CONN_INC;
923 	tp->iss = digest.words[0] + tcp_iss;
924 	tp->ts_modulate = digest.words[1];
925 }
926 
927 #ifdef TCP_SIGNATURE
928 int
929 tcp_signature_tdb_attach(void)
930 {
931 	return (0);
932 }
933 
934 int
935 tcp_signature_tdb_init(struct tdb *tdbp, struct xformsw *xsp,
936     struct ipsecinit *ii)
937 {
938 	if ((ii->ii_authkeylen < 1) || (ii->ii_authkeylen > 80))
939 		return (EINVAL);
940 
941 	tdbp->tdb_amxkey = malloc(ii->ii_authkeylen, M_XDATA, M_NOWAIT);
942 	if (tdbp->tdb_amxkey == NULL)
943 		return (ENOMEM);
944 	memcpy(tdbp->tdb_amxkey, ii->ii_authkey, ii->ii_authkeylen);
945 	tdbp->tdb_amxkeylen = ii->ii_authkeylen;
946 
947 	return (0);
948 }
949 
950 int
951 tcp_signature_tdb_zeroize(struct tdb *tdbp)
952 {
953 	if (tdbp->tdb_amxkey) {
954 		explicit_bzero(tdbp->tdb_amxkey, tdbp->tdb_amxkeylen);
955 		free(tdbp->tdb_amxkey, M_XDATA, tdbp->tdb_amxkeylen);
956 		tdbp->tdb_amxkey = NULL;
957 	}
958 
959 	return (0);
960 }
961 
962 int
963 tcp_signature_tdb_input(struct mbuf *m, struct tdb *tdbp, int skip, int protoff)
964 {
965 	return (0);
966 }
967 
968 int
969 tcp_signature_tdb_output(struct mbuf *m, struct tdb *tdbp, struct mbuf **mp,
970     int skip, int protoff)
971 {
972 	return (EINVAL);
973 }
974 
975 int
976 tcp_signature_apply(caddr_t fstate, caddr_t data, unsigned int len)
977 {
978 	MD5Update((MD5_CTX *)fstate, (char *)data, len);
979 	return 0;
980 }
981 
982 int
983 tcp_signature(struct tdb *tdb, int af, struct mbuf *m, struct tcphdr *th,
984     int iphlen, int doswap, char *sig)
985 {
986 	MD5_CTX ctx;
987 	int len;
988 	struct tcphdr th0;
989 
990 	MD5Init(&ctx);
991 
992 	switch(af) {
993 	case 0:
994 	case AF_INET: {
995 		struct ippseudo ippseudo;
996 		struct ip *ip;
997 
998 		ip = mtod(m, struct ip *);
999 
1000 		ippseudo.ippseudo_src = ip->ip_src;
1001 		ippseudo.ippseudo_dst = ip->ip_dst;
1002 		ippseudo.ippseudo_pad = 0;
1003 		ippseudo.ippseudo_p = IPPROTO_TCP;
1004 		ippseudo.ippseudo_len = htons(m->m_pkthdr.len - iphlen);
1005 
1006 		MD5Update(&ctx, (char *)&ippseudo,
1007 		    sizeof(struct ippseudo));
1008 		break;
1009 		}
1010 #ifdef INET6
1011 	case AF_INET6: {
1012 		struct ip6_hdr_pseudo ip6pseudo;
1013 		struct ip6_hdr *ip6;
1014 
1015 		ip6 = mtod(m, struct ip6_hdr *);
1016 		bzero(&ip6pseudo, sizeof(ip6pseudo));
1017 		ip6pseudo.ip6ph_src = ip6->ip6_src;
1018 		ip6pseudo.ip6ph_dst = ip6->ip6_dst;
1019 		in6_clearscope(&ip6pseudo.ip6ph_src);
1020 		in6_clearscope(&ip6pseudo.ip6ph_dst);
1021 		ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
1022 		ip6pseudo.ip6ph_len = htonl(m->m_pkthdr.len - iphlen);
1023 
1024 		MD5Update(&ctx, (char *)&ip6pseudo,
1025 		    sizeof(ip6pseudo));
1026 		break;
1027 		}
1028 #endif
1029 	}
1030 
1031 	th0 = *th;
1032 	th0.th_sum = 0;
1033 
1034 	if (doswap) {
1035 		th0.th_seq = htonl(th0.th_seq);
1036 		th0.th_ack = htonl(th0.th_ack);
1037 		th0.th_win = htons(th0.th_win);
1038 		th0.th_urp = htons(th0.th_urp);
1039 	}
1040 	MD5Update(&ctx, (char *)&th0, sizeof(th0));
1041 
1042 	len = m->m_pkthdr.len - iphlen - th->th_off * sizeof(uint32_t);
1043 
1044 	if (len > 0 &&
1045 	    m_apply(m, iphlen + th->th_off * sizeof(uint32_t), len,
1046 	    tcp_signature_apply, (caddr_t)&ctx))
1047 		return (-1);
1048 
1049 	MD5Update(&ctx, tdb->tdb_amxkey, tdb->tdb_amxkeylen);
1050 	MD5Final(sig, &ctx);
1051 
1052 	return (0);
1053 }
1054 #endif /* TCP_SIGNATURE */
1055