]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/tcp_subr.c
xnu-344.tar.gz
[apple/xnu.git] / bsd / netinet / tcp_subr.c
1 /*
2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22 /*
23 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
24 * The Regents of the University of California. All rights reserved.
25 *
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
28 * are met:
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * SUCH DAMAGE.
53 *
54 * @(#)tcp_subr.c 8.2 (Berkeley) 5/24/95
55 * $FreeBSD: src/sys/netinet/tcp_subr.c,v 1.73.2.22 2001/08/22 00:59:12 silby Exp $
56 */
57
58
59 #include <sys/param.h>
60 #include <sys/systm.h>
61 #include <sys/callout.h>
62 #include <sys/kernel.h>
63 #include <sys/sysctl.h>
64 #include <sys/malloc.h>
65 #include <sys/mbuf.h>
66 #if INET6
67 #include <sys/domain.h>
68 #endif
69 #include <sys/proc.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/protosw.h>
73 #include <sys/random.h>
74 #include <sys/syslog.h>
75
76
77
78 #include <net/route.h>
79 #include <net/if.h>
80
81 #define _IP_VHL
82 #include <netinet/in.h>
83 #include <netinet/in_systm.h>
84 #include <netinet/ip.h>
85 #if INET6
86 #include <netinet/ip6.h>
87 #endif
88 #include <netinet/in_pcb.h>
89 #if INET6
90 #include <netinet6/in6_pcb.h>
91 #endif
92 #include <netinet/in_var.h>
93 #include <netinet/ip_var.h>
94 #if INET6
95 #include <netinet6/ip6_var.h>
96 #endif
97 #include <netinet/tcp.h>
98 #include <netinet/tcp_fsm.h>
99 #include <netinet/tcp_seq.h>
100 #include <netinet/tcp_timer.h>
101 #include <netinet/tcp_var.h>
102 #if INET6
103 #include <netinet6/tcp6_var.h>
104 #endif
105 #include <netinet/tcpip.h>
106 #if TCPDEBUG
107 #include <netinet/tcp_debug.h>
108 #endif
109 #include <netinet6/ip6protosw.h>
110
111 #if IPSEC
112 #include <netinet6/ipsec.h>
113 #if INET6
114 #include <netinet6/ipsec6.h>
115 #endif
116 #endif /*IPSEC*/
117
118 #include <sys/md5.h>
119 #include <sys/kdebug.h>
120
121 #define DBG_FNC_TCP_CLOSE NETDBG_CODE(DBG_NETTCP, ((5 << 8) | 2))
122
123
124 /* temporary: for testing */
125 #if IPSEC
126 extern int ipsec_bypass;
127 #endif
128
129 int tcp_mssdflt = TCP_MSS;
130 SYSCTL_INT(_net_inet_tcp, TCPCTL_MSSDFLT, mssdflt, CTLFLAG_RW,
131 &tcp_mssdflt , 0, "Default TCP Maximum Segment Size");
132
133 #if INET6
134 int tcp_v6mssdflt = TCP6_MSS;
135 SYSCTL_INT(_net_inet_tcp, TCPCTL_V6MSSDFLT, v6mssdflt,
136 CTLFLAG_RW, &tcp_v6mssdflt , 0,
137 "Default TCP Maximum Segment Size for IPv6");
138 #endif
139
140 static int tcp_do_rfc1323 = 1;
141 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1323, rfc1323, CTLFLAG_RW,
142 &tcp_do_rfc1323 , 0, "Enable rfc1323 (high performance TCP) extensions");
143
144 static int tcp_do_rfc1644 = 0;
145 SYSCTL_INT(_net_inet_tcp, TCPCTL_DO_RFC1644, rfc1644, CTLFLAG_RW,
146 &tcp_do_rfc1644 , 0, "Enable rfc1644 (TTCP) extensions");
147
148 static int tcp_tcbhashsize = 0;
149 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcbhashsize, CTLFLAG_RD,
150 &tcp_tcbhashsize, 0, "Size of TCP control-block hashtable");
151
152 static int do_tcpdrain = 1;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, do_tcpdrain, CTLFLAG_RW, &do_tcpdrain, 0,
154 "Enable tcp_drain routine for extra help when low on mbufs");
155
156 SYSCTL_INT(_net_inet_tcp, OID_AUTO, pcbcount, CTLFLAG_RD,
157 &tcbinfo.ipi_count, 0, "Number of active PCBs");
158
159 static int icmp_may_rst = 1;
160 SYSCTL_INT(_net_inet_tcp, OID_AUTO, icmp_may_rst, CTLFLAG_RW, &icmp_may_rst, 0,
161 "Certain ICMP unreachable messages may abort connections in SYN_SENT");
162
163 static int tcp_strict_rfc1948 = 0;
164 SYSCTL_INT(_net_inet_tcp, OID_AUTO, strict_rfc1948, CTLFLAG_RW,
165 &tcp_strict_rfc1948, 0, "Determines if RFC1948 is followed exactly");
166
167 static int tcp_isn_reseed_interval = 0;
168 SYSCTL_INT(_net_inet_tcp, OID_AUTO, isn_reseed_interval, CTLFLAG_RW,
169 &tcp_isn_reseed_interval, 0, "Seconds between reseeding of ISN secret");
170
171 static void tcp_cleartaocache __P((void));
172 static void tcp_notify __P((struct inpcb *, int));
173
174 /*
175 * Target size of TCP PCB hash tables. Must be a power of two.
176 *
177 * Note that this can be overridden by the kernel environment
178 * variable net.inet.tcp.tcbhashsize
179 */
180 #ifndef TCBHASHSIZE
181 #define TCBHASHSIZE 4096
182 #endif
183
184 /*
185 * This is the actual shape of what we allocate using the zone
186 * allocator. Doing it this way allows us to protect both structures
187 * using the same generation count, and also eliminates the overhead
188 * of allocating tcpcbs separately. By hiding the structure here,
189 * we avoid changing most of the rest of the code (although it needs
190 * to be changed, eventually, for greater efficiency).
191 */
192 #define ALIGNMENT 32
193 #define ALIGNM1 (ALIGNMENT - 1)
194 struct inp_tp {
195 union {
196 struct inpcb inp;
197 char align[(sizeof(struct inpcb) + ALIGNM1) & ~ALIGNM1];
198 } inp_tp_u;
199 struct tcpcb tcb;
200 #ifndef __APPLE__
201 struct callout inp_tp_rexmt, inp_tp_persist, inp_tp_keep, inp_tp_2msl;
202 struct callout inp_tp_delack;
203 #endif
204 };
205 #undef ALIGNMENT
206 #undef ALIGNM1
207
208 static struct tcpcb dummy_tcb;
209
210
211 extern struct inpcbhead time_wait_slots[];
212 extern int cur_tw_slot;
213 extern u_long *delack_bitmask;
214
215
216 int get_inpcb_str_size()
217 {
218 return sizeof(struct inpcb);
219 }
220
221
222 int get_tcp_str_size()
223 {
224 return sizeof(struct tcpcb);
225 }
226
227 int tcp_freeq __P((struct tcpcb *tp));
228
229
230 /*
231 * Tcp initialization
232 */
233 void
234 tcp_init()
235 {
236 int hashsize = TCBHASHSIZE;
237 vm_size_t str_size;
238 int i;
239
240 tcp_ccgen = 1;
241 tcp_cleartaocache();
242
243 tcp_delacktime = TCPTV_DELACK;
244 tcp_keepinit = TCPTV_KEEP_INIT;
245 tcp_keepidle = TCPTV_KEEP_IDLE;
246 tcp_keepintvl = TCPTV_KEEPINTVL;
247 tcp_maxpersistidle = TCPTV_KEEP_IDLE;
248 tcp_msl = TCPTV_MSL;
249
250 LIST_INIT(&tcb);
251 tcbinfo.listhead = &tcb;
252 #ifndef __APPLE__
253 TUNABLE_INT_FETCH("net.inet.tcp.tcbhashsize", &hashsize);
254 #endif
255 if (!powerof2(hashsize)) {
256 printf("WARNING: TCB hash size not a power of 2\n");
257 hashsize = 512; /* safe default */
258 }
259 tcp_tcbhashsize = hashsize;
260 tcbinfo.hashsize = hashsize;
261 tcbinfo.hashbase = hashinit(hashsize, M_PCB, &tcbinfo.hashmask);
262 tcbinfo.porthashbase = hashinit(hashsize, M_PCB,
263 &tcbinfo.porthashmask);
264 #ifdef __APPLE__
265 str_size = (vm_size_t) sizeof(struct inp_tp);
266 tcbinfo.ipi_zone = (void *) zinit(str_size, 120000*str_size, 8192, "tcpcb");
267 #else
268 tcbinfo.ipi_zone = zinit("tcpcb", sizeof(struct inp_tp), maxsockets,
269 ZONE_INTERRUPT, 0);
270 #endif
271 #if INET6
272 #define TCP_MINPROTOHDR (sizeof(struct ip6_hdr) + sizeof(struct tcphdr))
273 #else /* INET6 */
274 #define TCP_MINPROTOHDR (sizeof(struct tcpiphdr))
275 #endif /* INET6 */
276 if (max_protohdr < TCP_MINPROTOHDR)
277 max_protohdr = TCP_MINPROTOHDR;
278 if (max_linkhdr + TCP_MINPROTOHDR > MHLEN)
279 panic("tcp_init");
280 #undef TCP_MINPROTOHDR
281 tcbinfo.last_pcb = 0;
282 dummy_tcb.t_state = TCP_NSTATES;
283 dummy_tcb.t_flags = 0;
284 tcbinfo.dummy_cb = (caddr_t) &dummy_tcb;
285 in_pcb_nat_init(&tcbinfo, AF_INET, IPPROTO_TCP, SOCK_STREAM);
286
287 delack_bitmask = _MALLOC((4 * hashsize)/32, M_PCB, M_WAITOK);
288 if (delack_bitmask == 0)
289 panic("Delack Memory");
290
291 for (i=0; i < (tcbinfo.hashsize / 32); i++)
292 delack_bitmask[i] = 0;
293
294 for (i=0; i < N_TIME_WAIT_SLOTS; i++) {
295 LIST_INIT(&time_wait_slots[i]);
296 }
297 }
298
299 /*
300 * Fill in the IP and TCP headers for an outgoing packet, given the tcpcb.
301 * tcp_template used to store this data in mbufs, but we now recopy it out
302 * of the tcpcb each time to conserve mbufs.
303 */
304 void
305 tcp_fillheaders(tp, ip_ptr, tcp_ptr)
306 struct tcpcb *tp;
307 void *ip_ptr;
308 void *tcp_ptr;
309 {
310 struct inpcb *inp = tp->t_inpcb;
311 struct tcphdr *tcp_hdr = (struct tcphdr *)tcp_ptr;
312
313 #if INET6
314 if ((inp->inp_vflag & INP_IPV6) != 0) {
315 struct ip6_hdr *ip6;
316
317 ip6 = (struct ip6_hdr *)ip_ptr;
318 ip6->ip6_flow = (ip6->ip6_flow & ~IPV6_FLOWINFO_MASK) |
319 (inp->in6p_flowinfo & IPV6_FLOWINFO_MASK);
320 ip6->ip6_vfc = (ip6->ip6_vfc & ~IPV6_VERSION_MASK) |
321 (IPV6_VERSION & IPV6_VERSION_MASK);
322 ip6->ip6_nxt = IPPROTO_TCP;
323 ip6->ip6_plen = sizeof(struct tcphdr);
324 ip6->ip6_src = inp->in6p_laddr;
325 ip6->ip6_dst = inp->in6p_faddr;
326 tcp_hdr->th_sum = 0;
327 } else
328 #endif
329 {
330 struct ip *ip = (struct ip *) ip_ptr;
331
332 ip->ip_vhl = IP_VHL_BORING;
333 ip->ip_tos = 0;
334 ip->ip_len = 0;
335 ip->ip_id = 0;
336 ip->ip_off = 0;
337 ip->ip_ttl = 0;
338 ip->ip_sum = 0;
339 ip->ip_p = IPPROTO_TCP;
340 ip->ip_src = inp->inp_laddr;
341 ip->ip_dst = inp->inp_faddr;
342 tcp_hdr->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
343 htons(sizeof(struct tcphdr) + IPPROTO_TCP));
344 }
345
346 tcp_hdr->th_sport = inp->inp_lport;
347 tcp_hdr->th_dport = inp->inp_fport;
348 tcp_hdr->th_seq = 0;
349 tcp_hdr->th_ack = 0;
350 tcp_hdr->th_x2 = 0;
351 tcp_hdr->th_off = 5;
352 tcp_hdr->th_flags = 0;
353 tcp_hdr->th_win = 0;
354 tcp_hdr->th_urp = 0;
355 }
356
357 /*
358 * Create template to be used to send tcp packets on a connection.
359 * Allocates an mbuf and fills in a skeletal tcp/ip header. The only
360 * use for this function is in keepalives, which use tcp_respond.
361 */
362 struct tcptemp *
363 tcp_maketemplate(tp)
364 struct tcpcb *tp;
365 {
366 struct mbuf *m;
367 struct tcptemp *n;
368
369 m = m_get(M_DONTWAIT, MT_HEADER);
370 if (m == NULL)
371 return (0);
372 m->m_len = sizeof(struct tcptemp);
373 n = mtod(m, struct tcptemp *);
374
375 tcp_fillheaders(tp, (void *)&n->tt_ipgen, (void *)&n->tt_t);
376 return (n);
377 }
378
379 /*
380 * Send a single message to the TCP at address specified by
381 * the given TCP/IP header. If m == 0, then we make a copy
382 * of the tcpiphdr at ti and send directly to the addressed host.
383 * This is used to force keep alive messages out using the TCP
384 * template for a connection. If flags are given then we send
385 * a message back to the TCP which originated the * segment ti,
386 * and discard the mbuf containing it and any other attached mbufs.
387 *
388 * In any case the ack and sequence number of the transmitted
389 * segment are as specified by the parameters.
390 *
391 * NOTE: If m != NULL, then ti must point to *inside* the mbuf.
392 */
393 void
394 tcp_respond(tp, ipgen, th, m, ack, seq, flags)
395 struct tcpcb *tp;
396 void *ipgen;
397 register struct tcphdr *th;
398 register struct mbuf *m;
399 tcp_seq ack, seq;
400 int flags;
401 {
402 register int tlen;
403 int win = 0;
404 struct route *ro = 0;
405 struct route sro;
406 struct ip *ip;
407 struct tcphdr *nth;
408 #if INET6
409 struct route_in6 *ro6 = 0;
410 struct route_in6 sro6;
411 struct ip6_hdr *ip6;
412 int isipv6;
413 #endif /* INET6 */
414 int ipflags = 0;
415
416 #if INET6
417 isipv6 = IP_VHL_V(((struct ip *)ipgen)->ip_vhl) == 6;
418 ip6 = ipgen;
419 #endif /* INET6 */
420 ip = ipgen;
421
422 if (tp) {
423 if (!(flags & TH_RST)) {
424 win = sbspace(&tp->t_inpcb->inp_socket->so_rcv);
425 if (win > (long)TCP_MAXWIN << tp->rcv_scale)
426 win = (long)TCP_MAXWIN << tp->rcv_scale;
427 }
428 #if INET6
429 if (isipv6)
430 ro6 = &tp->t_inpcb->in6p_route;
431 else
432 #endif /* INET6 */
433 ro = &tp->t_inpcb->inp_route;
434 } else {
435 #if INET6
436 if (isipv6) {
437 ro6 = &sro6;
438 bzero(ro6, sizeof *ro6);
439 } else
440 #endif /* INET6 */
441 {
442 ro = &sro;
443 bzero(ro, sizeof *ro);
444 }
445 }
446 if (m == 0) {
447 m = m_gethdr(M_DONTWAIT, MT_HEADER);
448 if (m == NULL)
449 return;
450 tlen = 0;
451 m->m_data += max_linkhdr;
452 #if INET6
453 if (isipv6) {
454 bcopy((caddr_t)ip6, mtod(m, caddr_t),
455 sizeof(struct ip6_hdr));
456 ip6 = mtod(m, struct ip6_hdr *);
457 nth = (struct tcphdr *)(ip6 + 1);
458 } else
459 #endif /* INET6 */
460 {
461 bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
462 ip = mtod(m, struct ip *);
463 nth = (struct tcphdr *)(ip + 1);
464 }
465 bcopy((caddr_t)th, (caddr_t)nth, sizeof(struct tcphdr));
466 flags = TH_ACK;
467 } else {
468 m_freem(m->m_next);
469 m->m_next = 0;
470 m->m_data = (caddr_t)ipgen;
471 /* m_len is set later */
472 tlen = 0;
473 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
474 #if INET6
475 if (isipv6) {
476 xchg(ip6->ip6_dst, ip6->ip6_src, struct in6_addr);
477 nth = (struct tcphdr *)(ip6 + 1);
478 } else
479 #endif /* INET6 */
480 {
481 xchg(ip->ip_dst.s_addr, ip->ip_src.s_addr, n_long);
482 nth = (struct tcphdr *)(ip + 1);
483 }
484 if (th != nth) {
485 /*
486 * this is usually a case when an extension header
487 * exists between the IPv6 header and the
488 * TCP header.
489 */
490 nth->th_sport = th->th_sport;
491 nth->th_dport = th->th_dport;
492 }
493 xchg(nth->th_dport, nth->th_sport, n_short);
494 #undef xchg
495 }
496 #if INET6
497 if (isipv6) {
498 ip6->ip6_plen = htons((u_short)(sizeof (struct tcphdr) +
499 tlen));
500 tlen += sizeof (struct ip6_hdr) + sizeof (struct tcphdr);
501 } else
502 #endif
503 {
504 tlen += sizeof (struct tcpiphdr);
505 ip->ip_len = tlen;
506 ip->ip_ttl = ip_defttl;
507 }
508 m->m_len = tlen;
509 m->m_pkthdr.len = tlen;
510 m->m_pkthdr.rcvif = (struct ifnet *) 0;
511 nth->th_seq = htonl(seq);
512 nth->th_ack = htonl(ack);
513 nth->th_x2 = 0;
514 nth->th_off = sizeof (struct tcphdr) >> 2;
515 nth->th_flags = flags;
516 if (tp)
517 nth->th_win = htons((u_short) (win >> tp->rcv_scale));
518 else
519 nth->th_win = htons((u_short)win);
520 nth->th_urp = 0;
521 #if INET6
522 if (isipv6) {
523 nth->th_sum = 0;
524 nth->th_sum = in6_cksum(m, IPPROTO_TCP,
525 sizeof(struct ip6_hdr),
526 tlen - sizeof(struct ip6_hdr));
527 ip6->ip6_hlim = in6_selecthlim(tp ? tp->t_inpcb : NULL,
528 ro6 && ro6->ro_rt ?
529 ro6->ro_rt->rt_ifp :
530 NULL);
531 } else
532 #endif /* INET6 */
533 {
534 nth->th_sum = in_pseudo(ip->ip_src.s_addr, ip->ip_dst.s_addr,
535 htons((u_short)(tlen - sizeof(struct ip) + ip->ip_p)));
536 m->m_pkthdr.csum_flags = CSUM_TCP;
537 m->m_pkthdr.csum_data = offsetof(struct tcphdr, th_sum);
538 }
539 #if TCPDEBUG
540 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
541 tcp_trace(TA_OUTPUT, 0, tp, mtod(m, void *), th, 0);
542 #endif
543 #if IPSEC
544 if (ipsec_bypass == 0 && ipsec_setsocket(m, tp ? tp->t_inpcb->inp_socket : NULL) != 0) {
545 m_freem(m);
546 return;
547 }
548 #endif
549 #if INET6
550 if (isipv6) {
551 (void)ip6_output(m, NULL, ro6, ipflags, NULL, NULL);
552 if (ro6 == &sro6 && ro6->ro_rt) {
553 rtfree(ro6->ro_rt);
554 ro6->ro_rt = NULL;
555 }
556 } else
557 #endif /* INET6 */
558 {
559 (void) ip_output(m, NULL, ro, ipflags, NULL);
560 if (ro == &sro && ro->ro_rt) {
561 rtfree(ro->ro_rt);
562 ro->ro_rt = NULL;
563 }
564 }
565 }
566
567 /*
568 * Create a new TCP control block, making an
569 * empty reassembly queue and hooking it to the argument
570 * protocol control block. The `inp' parameter must have
571 * come from the zone allocator set up in tcp_init().
572 */
573 struct tcpcb *
574 tcp_newtcpcb(inp)
575 struct inpcb *inp;
576 {
577 struct inp_tp *it;
578 register struct tcpcb *tp;
579 register struct socket *so = inp->inp_socket;
580 #if INET6
581 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
582 #endif /* INET6 */
583
584 if (so->cached_in_sock_layer == 0) {
585 it = (struct inp_tp *)inp;
586 tp = &it->tcb;
587 }
588 else
589 tp = (struct tcpcb *) inp->inp_saved_ppcb;
590
591 bzero((char *) tp, sizeof(struct tcpcb));
592 LIST_INIT(&tp->t_segq);
593 tp->t_maxseg = tp->t_maxopd =
594 #if INET6
595 isipv6 ? tcp_v6mssdflt :
596 #endif /* INET6 */
597 tcp_mssdflt;
598
599 #ifndef __APPLE__
600 /* Set up our timeouts. */
601 callout_init(tp->tt_rexmt = &it->inp_tp_rexmt);
602 callout_init(tp->tt_persist = &it->inp_tp_persist);
603 callout_init(tp->tt_keep = &it->inp_tp_keep);
604 callout_init(tp->tt_2msl = &it->inp_tp_2msl);
605 callout_init(tp->tt_delack = &it->inp_tp_delack);
606 #endif
607
608 if (tcp_do_rfc1323)
609 tp->t_flags = (TF_REQ_SCALE|TF_REQ_TSTMP);
610 if (tcp_do_rfc1644)
611 tp->t_flags |= TF_REQ_CC;
612 tp->t_inpcb = inp; /* XXX */
613 /*
614 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
615 * rtt estimate. Set rttvar so that srtt + 4 * rttvar gives
616 * reasonable initial retransmit time.
617 */
618 tp->t_srtt = TCPTV_SRTTBASE;
619 tp->t_rttvar = ((TCPTV_RTOBASE - TCPTV_SRTTBASE) << TCP_RTTVAR_SHIFT) / 4;
620 tp->t_rttmin = TCPTV_MIN;
621 tp->t_rxtcur = TCPTV_RTOBASE;
622 tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
623 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
624 /*
625 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
626 * because the socket may be bound to an IPv6 wildcard address,
627 * which may match an IPv4-mapped IPv6 address.
628 */
629 inp->inp_ip_ttl = ip_defttl;
630 inp->inp_ppcb = (caddr_t)tp;
631 return (tp); /* XXX */
632 }
633
634 /*
635 * Drop a TCP connection, reporting
636 * the specified error. If connection is synchronized,
637 * then send a RST to peer.
638 */
639 struct tcpcb *
640 tcp_drop(tp, errno)
641 register struct tcpcb *tp;
642 int errno;
643 {
644 struct socket *so = tp->t_inpcb->inp_socket;
645
646 #ifdef __APPLE__
647 switch (tp->t_state)
648 {
649 case TCPS_ESTABLISHED:
650 case TCPS_FIN_WAIT_1:
651 case TCPS_CLOSING:
652 case TCPS_CLOSE_WAIT:
653 case TCPS_LAST_ACK:
654 break;
655 }
656 #endif
657
658 if (TCPS_HAVERCVDSYN(tp->t_state)) {
659 tp->t_state = TCPS_CLOSED;
660 (void) tcp_output(tp);
661 tcpstat.tcps_drops++;
662 } else
663 tcpstat.tcps_conndrops++;
664 if (errno == ETIMEDOUT && tp->t_softerror)
665 errno = tp->t_softerror;
666 so->so_error = errno;
667 return (tcp_close(tp));
668 }
669
670 /*
671 * Close a TCP control block:
672 * discard all space held by the tcp
673 * discard internet protocol block
674 * wake up any sleepers
675 */
676 struct tcpcb *
677 tcp_close(tp)
678 register struct tcpcb *tp;
679 {
680 register struct tseg_qent *q;
681 struct inpcb *inp = tp->t_inpcb;
682 struct socket *so = inp->inp_socket;
683 #if INET6
684 int isipv6 = (inp->inp_vflag & INP_IPV6) != 0;
685 #endif /* INET6 */
686 register struct rtentry *rt;
687 int dosavessthresh;
688
689 #ifndef __APPLE__
690 /*
691 * Make sure that all of our timers are stopped before we
692 * delete the PCB.
693 */
694 callout_stop(tp->tt_rexmt);
695 callout_stop(tp->tt_persist);
696 callout_stop(tp->tt_keep);
697 callout_stop(tp->tt_2msl);
698 callout_stop(tp->tt_delack);
699 #endif
700
701 KERNEL_DEBUG(DBG_FNC_TCP_CLOSE | DBG_FUNC_START, tp,0,0,0,0);
702 switch (tp->t_state)
703 {
704 case TCPS_ESTABLISHED:
705 case TCPS_FIN_WAIT_1:
706 case TCPS_CLOSING:
707 case TCPS_CLOSE_WAIT:
708 case TCPS_LAST_ACK:
709 break;
710 }
711
712
713 /*
714 * If we got enough samples through the srtt filter,
715 * save the rtt and rttvar in the routing entry.
716 * 'Enough' is arbitrarily defined as the 16 samples.
717 * 16 samples is enough for the srtt filter to converge
718 * to within 5% of the correct value; fewer samples and
719 * we could save a very bogus rtt.
720 *
721 * Don't update the default route's characteristics and don't
722 * update anything that the user "locked".
723 */
724 if (tp->t_rttupdated >= 16) {
725 register u_long i = 0;
726 #if INET6
727 if (isipv6) {
728 struct sockaddr_in6 *sin6;
729
730 if ((rt = inp->in6p_route.ro_rt) == NULL)
731 goto no_valid_rt;
732 sin6 = (struct sockaddr_in6 *)rt_key(rt);
733 if (IN6_IS_ADDR_UNSPECIFIED(&sin6->sin6_addr))
734 goto no_valid_rt;
735 }
736 else
737 #endif /* INET6 */
738 if ((rt = inp->inp_route.ro_rt) == NULL ||
739 ((struct sockaddr_in *)rt_key(rt))->sin_addr.s_addr
740 == INADDR_ANY)
741 goto no_valid_rt;
742
743 if ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0) {
744 i = tp->t_srtt *
745 (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
746 if (rt->rt_rmx.rmx_rtt && i)
747 /*
748 * filter this update to half the old & half
749 * the new values, converting scale.
750 * See route.h and tcp_var.h for a
751 * description of the scaling constants.
752 */
753 rt->rt_rmx.rmx_rtt =
754 (rt->rt_rmx.rmx_rtt + i) / 2;
755 else
756 rt->rt_rmx.rmx_rtt = i;
757 tcpstat.tcps_cachedrtt++;
758 }
759 if ((rt->rt_rmx.rmx_locks & RTV_RTTVAR) == 0) {
760 i = tp->t_rttvar *
761 (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
762 if (rt->rt_rmx.rmx_rttvar && i)
763 rt->rt_rmx.rmx_rttvar =
764 (rt->rt_rmx.rmx_rttvar + i) / 2;
765 else
766 rt->rt_rmx.rmx_rttvar = i;
767 tcpstat.tcps_cachedrttvar++;
768 }
769 /*
770 * The old comment here said:
771 * update the pipelimit (ssthresh) if it has been updated
772 * already or if a pipesize was specified & the threshhold
773 * got below half the pipesize. I.e., wait for bad news
774 * before we start updating, then update on both good
775 * and bad news.
776 *
777 * But we want to save the ssthresh even if no pipesize is
778 * specified explicitly in the route, because such
779 * connections still have an implicit pipesize specified
780 * by the global tcp_sendspace. In the absence of a reliable
781 * way to calculate the pipesize, it will have to do.
782 */
783 i = tp->snd_ssthresh;
784 if (rt->rt_rmx.rmx_sendpipe != 0)
785 dosavessthresh = (i < rt->rt_rmx.rmx_sendpipe / 2);
786 else
787 dosavessthresh = (i < so->so_snd.sb_hiwat / 2);
788 if (((rt->rt_rmx.rmx_locks & RTV_SSTHRESH) == 0 &&
789 i != 0 && rt->rt_rmx.rmx_ssthresh != 0)
790 || dosavessthresh) {
791 /*
792 * convert the limit from user data bytes to
793 * packets then to packet data bytes.
794 */
795 i = (i + tp->t_maxseg / 2) / tp->t_maxseg;
796 if (i < 2)
797 i = 2;
798 i *= (u_long)(tp->t_maxseg +
799 #if INET6
800 (isipv6 ? sizeof (struct ip6_hdr) +
801 sizeof (struct tcphdr) :
802 #endif
803 sizeof (struct tcpiphdr)
804 #if INET6
805 )
806 #endif
807 );
808 if (rt->rt_rmx.rmx_ssthresh)
809 rt->rt_rmx.rmx_ssthresh =
810 (rt->rt_rmx.rmx_ssthresh + i) / 2;
811 else
812 rt->rt_rmx.rmx_ssthresh = i;
813 tcpstat.tcps_cachedssthresh++;
814 }
815 }
816 rt = inp->inp_route.ro_rt;
817 if (rt) {
818 /*
819 * mark route for deletion if no information is
820 * cached.
821 */
822 if ((tp->t_flags & TF_LQ_OVERFLOW) &&
823 ((rt->rt_rmx.rmx_locks & RTV_RTT) == 0)){
824 if (rt->rt_rmx.rmx_rtt == 0)
825 rt->rt_flags |= RTF_DELCLONE;
826 }
827 }
828 no_valid_rt:
829 /* free the reassembly queue, if any */
830 (void) tcp_freeq(tp);
831
832 #ifdef __APPLE__
833 if (so->cached_in_sock_layer)
834 inp->inp_saved_ppcb = (caddr_t) tp;
835 #endif
836
837 inp->inp_ppcb = NULL;
838 soisdisconnected(so);
839 #if INET6
840 if (INP_CHECK_SOCKAF(so, AF_INET6))
841 in6_pcbdetach(inp);
842 else
843 #endif /* INET6 */
844 in_pcbdetach(inp);
845 tcpstat.tcps_closed++;
846 KERNEL_DEBUG(DBG_FNC_TCP_CLOSE | DBG_FUNC_END, tcpstat.tcps_closed,0,0,0,0);
847 return ((struct tcpcb *)0);
848 }
849
850 int
851 tcp_freeq(tp)
852 struct tcpcb *tp;
853 {
854
855 register struct tseg_qent *q;
856 int rv = 0;
857
858 while((q = LIST_FIRST(&tp->t_segq)) != NULL) {
859 LIST_REMOVE(q, tqe_q);
860 m_freem(q->tqe_m);
861 FREE(q, M_TSEGQ);
862 rv = 1;
863 }
864 return (rv);
865 }
866
867 void
868 tcp_drain()
869 {
870 if (do_tcpdrain)
871 {
872 struct inpcb *inpb;
873 struct tcpcb *tcpb;
874 struct tseg_qent *te;
875
876 /*
877 * Walk the tcpbs, if existing, and flush the reassembly queue,
878 * if there is one...
879 * XXX: The "Net/3" implementation doesn't imply that the TCP
880 * reassembly queue should be flushed, but in a situation
881 * where we're really low on mbufs, this is potentially
882 * usefull.
883 */
884 for (inpb = LIST_FIRST(tcbinfo.listhead); inpb;
885 inpb = LIST_NEXT(inpb, inp_list)) {
886 if ((tcpb = intotcpcb(inpb))) {
887 while ((te = LIST_FIRST(&tcpb->t_segq))
888 != NULL) {
889 LIST_REMOVE(te, tqe_q);
890 m_freem(te->tqe_m);
891 FREE(te, M_TSEGQ);
892 }
893 }
894 }
895
896 }
897 }
898
899 /*
900 * Notify a tcp user of an asynchronous error;
901 * store error as soft error, but wake up user
902 * (for now, won't do anything until can select for soft error).
903 *
904 * Do not wake up user since there currently is no mechanism for
905 * reporting soft errors (yet - a kqueue filter may be added).
906 */
907 static void
908 tcp_notify(inp, error)
909 struct inpcb *inp;
910 int error;
911 {
912 struct tcpcb *tp = (struct tcpcb *)inp->inp_ppcb;
913
914 /*
915 * Ignore some errors if we are hooked up.
916 * If connection hasn't completed, has retransmitted several times,
917 * and receives a second error, give up now. This is better
918 * than waiting a long time to establish a connection that
919 * can never complete.
920 */
921 if (tp->t_state == TCPS_ESTABLISHED &&
922 (error == EHOSTUNREACH || error == ENETUNREACH ||
923 error == EHOSTDOWN)) {
924 return;
925 } else if (tp->t_state < TCPS_ESTABLISHED && tp->t_rxtshift > 3 &&
926 tp->t_softerror)
927 tcp_drop(tp, error);
928 else
929 tp->t_softerror = error;
930 #if 0
931 wakeup((caddr_t) &so->so_timeo);
932 sorwakeup(so);
933 sowwakeup(so);
934 #endif
935 }
936
937 static int
938 tcp_pcblist SYSCTL_HANDLER_ARGS
939 {
940 int error, i, n, s;
941 struct inpcb *inp, **inp_list;
942 inp_gen_t gencnt;
943 struct xinpgen xig;
944
945 /*
946 * The process of preparing the TCB list is too time-consuming and
947 * resource-intensive to repeat twice on every request.
948 */
949 if (req->oldptr == 0) {
950 n = tcbinfo.ipi_count;
951 req->oldidx = 2 * (sizeof xig)
952 + (n + n/8) * sizeof(struct xtcpcb);
953 return 0;
954 }
955
956 if (req->newptr != 0)
957 return EPERM;
958
959 /*
960 * OK, now we're committed to doing something.
961 */
962 s = splnet();
963 gencnt = tcbinfo.ipi_gencnt;
964 n = tcbinfo.ipi_count;
965 splx(s);
966
967 xig.xig_len = sizeof xig;
968 xig.xig_count = n;
969 xig.xig_gen = gencnt;
970 xig.xig_sogen = so_gencnt;
971 error = SYSCTL_OUT(req, &xig, sizeof xig);
972 if (error)
973 return error;
974 /*
975 * We are done if there is no pcb
976 */
977 if (n == 0)
978 return 0;
979
980 inp_list = _MALLOC(n * sizeof *inp_list, M_TEMP, M_WAITOK);
981 if (inp_list == 0)
982 return ENOMEM;
983
984 s = splnet();
985 for (inp = LIST_FIRST(tcbinfo.listhead), i = 0; inp && i < n;
986 inp = LIST_NEXT(inp, inp_list)) {
987 #ifdef __APPLE__
988 if (inp->inp_gencnt <= gencnt)
989 #else
990 if (inp->inp_gencnt <= gencnt && !prison_xinpcb(req->p, inp))
991 #endif
992 inp_list[i++] = inp;
993 }
994 splx(s);
995 n = i;
996
997 error = 0;
998 for (i = 0; i < n; i++) {
999 inp = inp_list[i];
1000 if (inp->inp_gencnt <= gencnt) {
1001 struct xtcpcb xt;
1002 caddr_t inp_ppcb;
1003 xt.xt_len = sizeof xt;
1004 /* XXX should avoid extra copy */
1005 bcopy(inp, &xt.xt_inp, sizeof *inp);
1006 inp_ppcb = inp->inp_ppcb;
1007 if (inp_ppcb != NULL)
1008 bcopy(inp_ppcb, &xt.xt_tp, sizeof xt.xt_tp);
1009 else
1010 bzero((char *) &xt.xt_tp, sizeof xt.xt_tp);
1011 if (inp->inp_socket)
1012 sotoxsocket(inp->inp_socket, &xt.xt_socket);
1013 error = SYSCTL_OUT(req, &xt, sizeof xt);
1014 }
1015 }
1016 if (!error) {
1017 /*
1018 * Give the user an updated idea of our state.
1019 * If the generation differs from what we told
1020 * her before, she knows that something happened
1021 * while we were processing this request, and it
1022 * might be necessary to retry.
1023 */
1024 s = splnet();
1025 xig.xig_gen = tcbinfo.ipi_gencnt;
1026 xig.xig_sogen = so_gencnt;
1027 xig.xig_count = tcbinfo.ipi_count;
1028 splx(s);
1029 error = SYSCTL_OUT(req, &xig, sizeof xig);
1030 }
1031 FREE(inp_list, M_TEMP);
1032 return error;
1033 }
1034
1035 SYSCTL_PROC(_net_inet_tcp, TCPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
1036 tcp_pcblist, "S,xtcpcb", "List of active TCP connections");
1037
1038 #ifndef __APPLE__
1039 static int
1040 tcp_getcred(SYSCTL_HANDLER_ARGS)
1041 {
1042 struct sockaddr_in addrs[2];
1043 struct inpcb *inp;
1044 int error, s;
1045
1046 error = suser(req->p);
1047 if (error)
1048 return (error);
1049 error = SYSCTL_IN(req, addrs, sizeof(addrs));
1050 if (error)
1051 return (error);
1052 s = splnet();
1053 inp = in_pcblookup_hash(&tcbinfo, addrs[1].sin_addr, addrs[1].sin_port,
1054 addrs[0].sin_addr, addrs[0].sin_port, 0, NULL);
1055 if (inp == NULL || inp->inp_socket == NULL) {
1056 error = ENOENT;
1057 goto out;
1058 }
1059 error = SYSCTL_OUT(req, inp->inp_socket->so_cred, sizeof(struct ucred));
1060 out:
1061 splx(s);
1062 return (error);
1063 }
1064
1065 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
1066 0, 0, tcp_getcred, "S,ucred", "Get the ucred of a TCP connection");
1067
1068 #if INET6
1069 static int
1070 tcp6_getcred(SYSCTL_HANDLER_ARGS)
1071 {
1072 struct sockaddr_in6 addrs[2];
1073 struct inpcb *inp;
1074 int error, s, mapped = 0;
1075
1076 error = suser(req->p);
1077 if (error)
1078 return (error);
1079 error = SYSCTL_IN(req, addrs, sizeof(addrs));
1080 if (error)
1081 return (error);
1082 if (IN6_IS_ADDR_V4MAPPED(&addrs[0].sin6_addr)) {
1083 if (IN6_IS_ADDR_V4MAPPED(&addrs[1].sin6_addr))
1084 mapped = 1;
1085 else
1086 return (EINVAL);
1087 }
1088 s = splnet();
1089 if (mapped == 1)
1090 inp = in_pcblookup_hash(&tcbinfo,
1091 *(struct in_addr *)&addrs[1].sin6_addr.s6_addr[12],
1092 addrs[1].sin6_port,
1093 *(struct in_addr *)&addrs[0].sin6_addr.s6_addr[12],
1094 addrs[0].sin6_port,
1095 0, NULL);
1096 else
1097 inp = in6_pcblookup_hash(&tcbinfo, &addrs[1].sin6_addr,
1098 addrs[1].sin6_port,
1099 &addrs[0].sin6_addr, addrs[0].sin6_port,
1100 0, NULL);
1101 if (inp == NULL || inp->inp_socket == NULL) {
1102 error = ENOENT;
1103 goto out;
1104 }
1105 error = SYSCTL_OUT(req, inp->inp_socket->so_cred,
1106 sizeof(struct ucred));
1107 out:
1108 splx(s);
1109 return (error);
1110 }
1111
1112 SYSCTL_PROC(_net_inet6_tcp6, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
1113 0, 0,
1114 tcp6_getcred, "S,ucred", "Get the ucred of a TCP6 connection");
1115 #endif
1116 #endif /* __APPLE__*/
1117
1118 void
1119 tcp_ctlinput(cmd, sa, vip)
1120 int cmd;
1121 struct sockaddr *sa;
1122 void *vip;
1123 {
1124 struct ip *ip = vip;
1125 struct tcphdr *th;
1126 struct in_addr faddr;
1127 struct inpcb *inp;
1128 struct tcpcb *tp;
1129 void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1130 tcp_seq icmp_seq;
1131 int s;
1132
1133 faddr = ((struct sockaddr_in *)sa)->sin_addr;
1134 if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
1135 return;
1136
1137 if (cmd == PRC_QUENCH)
1138 notify = tcp_quench;
1139 else if (icmp_may_rst && (cmd == PRC_UNREACH_ADMIN_PROHIB ||
1140 cmd == PRC_UNREACH_PORT) && ip)
1141 notify = tcp_drop_syn_sent;
1142 else if (cmd == PRC_MSGSIZE)
1143 notify = tcp_mtudisc;
1144 else if (PRC_IS_REDIRECT(cmd)) {
1145 ip = 0;
1146 notify = in_rtchange;
1147 } else if (cmd == PRC_HOSTDEAD)
1148 ip = 0;
1149 else if ((unsigned)cmd > PRC_NCMDS || inetctlerrmap[cmd] == 0)
1150 return;
1151 if (ip) {
1152 s = splnet();
1153 th = (struct tcphdr *)((caddr_t)ip
1154 + (IP_VHL_HL(ip->ip_vhl) << 2));
1155 inp = in_pcblookup_hash(&tcbinfo, faddr, th->th_dport,
1156 ip->ip_src, th->th_sport, 0, NULL);
1157 if (inp != NULL && inp->inp_socket != NULL) {
1158 icmp_seq = htonl(th->th_seq);
1159 tp = intotcpcb(inp);
1160 if (SEQ_GEQ(icmp_seq, tp->snd_una) &&
1161 SEQ_LT(icmp_seq, tp->snd_max))
1162 (*notify)(inp, inetctlerrmap[cmd]);
1163 }
1164 splx(s);
1165 } else
1166 in_pcbnotifyall(&tcb, faddr, inetctlerrmap[cmd], notify);
1167 }
1168
1169 #if INET6
1170 void
1171 tcp6_ctlinput(cmd, sa, d)
1172 int cmd;
1173 struct sockaddr *sa;
1174 void *d;
1175 {
1176 struct tcphdr th;
1177 void (*notify) __P((struct inpcb *, int)) = tcp_notify;
1178 struct ip6_hdr *ip6;
1179 struct mbuf *m;
1180 struct ip6ctlparam *ip6cp = NULL;
1181 const struct sockaddr_in6 *sa6_src = NULL;
1182 int off;
1183 struct tcp_portonly {
1184 u_int16_t th_sport;
1185 u_int16_t th_dport;
1186 } *thp;
1187
1188 if (sa->sa_family != AF_INET6 ||
1189 sa->sa_len != sizeof(struct sockaddr_in6))
1190 return;
1191
1192 if (cmd == PRC_QUENCH)
1193 notify = tcp_quench;
1194 else if (cmd == PRC_MSGSIZE)
1195 notify = tcp_mtudisc;
1196 else if (!PRC_IS_REDIRECT(cmd) &&
1197 ((unsigned)cmd > PRC_NCMDS || inet6ctlerrmap[cmd] == 0))
1198 return;
1199
1200 /* if the parameter is from icmp6, decode it. */
1201 if (d != NULL) {
1202 ip6cp = (struct ip6ctlparam *)d;
1203 m = ip6cp->ip6c_m;
1204 ip6 = ip6cp->ip6c_ip6;
1205 off = ip6cp->ip6c_off;
1206 sa6_src = ip6cp->ip6c_src;
1207 } else {
1208 m = NULL;
1209 ip6 = NULL;
1210 off = 0; /* fool gcc */
1211 sa6_src = &sa6_any;
1212 }
1213
1214 if (ip6) {
1215 /*
1216 * XXX: We assume that when IPV6 is non NULL,
1217 * M and OFF are valid.
1218 */
1219
1220 /* check if we can safely examine src and dst ports */
1221 if (m->m_pkthdr.len < off + sizeof(*thp))
1222 return;
1223
1224 bzero(&th, sizeof(th));
1225 m_copydata(m, off, sizeof(*thp), (caddr_t)&th);
1226
1227 in6_pcbnotify(&tcb, sa, th.th_dport,
1228 (struct sockaddr *)ip6cp->ip6c_src,
1229 th.th_sport, cmd, notify);
1230 } else
1231 in6_pcbnotify(&tcb, sa, 0, (struct sockaddr *)sa6_src,
1232 0, cmd, notify);
1233 }
1234 #endif /* INET6 */
1235
1236
1237 /*
1238 * Following is where TCP initial sequence number generation occurs.
1239 *
1240 * There are two places where we must use initial sequence numbers:
1241 * 1. In SYN-ACK packets.
1242 * 2. In SYN packets.
1243 *
1244 * The ISNs in SYN-ACK packets have no monotonicity requirement,
1245 * and should be as unpredictable as possible to avoid the possibility
1246 * of spoofing and/or connection hijacking. To satisfy this
1247 * requirement, SYN-ACK ISNs are generated via the arc4random()
1248 * function. If exact RFC 1948 compliance is requested via sysctl,
1249 * these ISNs will be generated just like those in SYN packets.
1250 *
1251 * The ISNs in SYN packets must be monotonic; TIME_WAIT recycling
1252 * depends on this property. In addition, these ISNs should be
1253 * unguessable so as to prevent connection hijacking. To satisfy
1254 * the requirements of this situation, the algorithm outlined in
1255 * RFC 1948 is used to generate sequence numbers.
1256 *
1257 * For more information on the theory of operation, please see
1258 * RFC 1948.
1259 *
1260 * Implementation details:
1261 *
1262 * Time is based off the system timer, and is corrected so that it
1263 * increases by one megabyte per second. This allows for proper
1264 * recycling on high speed LANs while still leaving over an hour
1265 * before rollover.
1266 *
1267 * Two sysctls control the generation of ISNs:
1268 *
1269 * net.inet.tcp.isn_reseed_interval controls the number of seconds
1270 * between seeding of isn_secret. This is normally set to zero,
1271 * as reseeding should not be necessary.
1272 *
1273 * net.inet.tcp.strict_rfc1948 controls whether RFC 1948 is followed
1274 * strictly. When strict compliance is requested, reseeding is
1275 * disabled and SYN-ACKs will be generated in the same manner as
1276 * SYNs. Strict mode is disabled by default.
1277 *
1278 */
1279
1280 #define ISN_BYTES_PER_SECOND 1048576
1281
1282 u_char isn_secret[32];
1283 int isn_last_reseed;
1284 MD5_CTX isn_ctx;
1285
1286 tcp_seq
1287 tcp_new_isn(tp)
1288 struct tcpcb *tp;
1289 {
1290 u_int32_t md5_buffer[4];
1291 tcp_seq new_isn;
1292 struct timeval time;
1293
1294 /* Use arc4random for SYN-ACKs when not in exact RFC1948 mode. */
1295 if (((tp->t_state == TCPS_LISTEN) || (tp->t_state == TCPS_TIME_WAIT))
1296 && tcp_strict_rfc1948 == 0)
1297 #ifdef __APPLE__
1298 return random();
1299 #else
1300 return arc4random();
1301 #endif
1302
1303 /* Seed if this is the first use, reseed if requested. */
1304 if ((isn_last_reseed == 0) ||
1305 ((tcp_strict_rfc1948 == 0) && (tcp_isn_reseed_interval > 0) &&
1306 (((u_int)isn_last_reseed + (u_int)tcp_isn_reseed_interval*hz)
1307 < (u_int)time.tv_sec))) {
1308 #ifdef __APPLE__
1309 read_random(&isn_secret, sizeof(isn_secret));
1310 #else
1311 read_random_unlimited(&isn_secret, sizeof(isn_secret));
1312 #endif
1313 isn_last_reseed = time.tv_sec;
1314 }
1315
1316 /* Compute the md5 hash and return the ISN. */
1317 MD5Init(&isn_ctx);
1318 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_fport, sizeof(u_short));
1319 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_lport, sizeof(u_short));
1320 #if INET6
1321 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
1322 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_faddr,
1323 sizeof(struct in6_addr));
1324 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->in6p_laddr,
1325 sizeof(struct in6_addr));
1326 } else
1327 #endif
1328 {
1329 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_faddr,
1330 sizeof(struct in_addr));
1331 MD5Update(&isn_ctx, (u_char *) &tp->t_inpcb->inp_laddr,
1332 sizeof(struct in_addr));
1333 }
1334 MD5Update(&isn_ctx, (u_char *) &isn_secret, sizeof(isn_secret));
1335 MD5Final((u_char *) &md5_buffer, &isn_ctx);
1336 new_isn = (tcp_seq) md5_buffer[0];
1337 new_isn += time.tv_sec * (ISN_BYTES_PER_SECOND / hz);
1338 return new_isn;
1339 }
1340
1341 /*
1342 * When a source quench is received, close congestion window
1343 * to one segment. We will gradually open it again as we proceed.
1344 */
1345 void
1346 tcp_quench(inp, errno)
1347 struct inpcb *inp;
1348 int errno;
1349 {
1350 struct tcpcb *tp = intotcpcb(inp);
1351
1352 if (tp)
1353 tp->snd_cwnd = tp->t_maxseg;
1354 }
1355
1356 /*
1357 * When a specific ICMP unreachable message is received and the
1358 * connection state is SYN-SENT, drop the connection. This behavior
1359 * is controlled by the icmp_may_rst sysctl.
1360 */
1361 void
1362 tcp_drop_syn_sent(inp, errno)
1363 struct inpcb *inp;
1364 int errno;
1365 {
1366 struct tcpcb *tp = intotcpcb(inp);
1367
1368 if (tp && tp->t_state == TCPS_SYN_SENT)
1369 tcp_drop(tp, errno);
1370 }
1371
1372 /*
1373 * When `need fragmentation' ICMP is received, update our idea of the MSS
1374 * based on the new value in the route. Also nudge TCP to send something,
1375 * since we know the packet we just sent was dropped.
1376 * This duplicates some code in the tcp_mss() function in tcp_input.c.
1377 */
1378 void
1379 tcp_mtudisc(inp, errno)
1380 struct inpcb *inp;
1381 int errno;
1382 {
1383 struct tcpcb *tp = intotcpcb(inp);
1384 struct rtentry *rt;
1385 struct rmxp_tao *taop;
1386 struct socket *so = inp->inp_socket;
1387 int offered;
1388 int mss;
1389 #if INET6
1390 int isipv6 = (tp->t_inpcb->inp_vflag & INP_IPV6) != 0;
1391 #endif /* INET6 */
1392
1393 if (tp) {
1394 #if INET6
1395 if (isipv6)
1396 rt = tcp_rtlookup6(inp);
1397 else
1398 #endif /* INET6 */
1399 rt = tcp_rtlookup(inp);
1400 if (!rt || !rt->rt_rmx.rmx_mtu) {
1401 tp->t_maxopd = tp->t_maxseg =
1402 #if INET6
1403 isipv6 ? tcp_v6mssdflt :
1404 #endif /* INET6 */
1405 tcp_mssdflt;
1406 return;
1407 }
1408 taop = rmx_taop(rt->rt_rmx);
1409 offered = taop->tao_mssopt;
1410 mss = rt->rt_rmx.rmx_mtu -
1411 #if INET6
1412 (isipv6 ?
1413 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
1414 #endif /* INET6 */
1415 sizeof(struct tcpiphdr)
1416 #if INET6
1417 )
1418 #endif /* INET6 */
1419 ;
1420
1421 if (offered)
1422 mss = min(mss, offered);
1423 /*
1424 * XXX - The above conditional probably violates the TCP
1425 * spec. The problem is that, since we don't know the
1426 * other end's MSS, we are supposed to use a conservative
1427 * default. But, if we do that, then MTU discovery will
1428 * never actually take place, because the conservative
1429 * default is much less than the MTUs typically seen
1430 * on the Internet today. For the moment, we'll sweep
1431 * this under the carpet.
1432 *
1433 * The conservative default might not actually be a problem
1434 * if the only case this occurs is when sending an initial
1435 * SYN with options and data to a host we've never talked
1436 * to before. Then, they will reply with an MSS value which
1437 * will get recorded and the new parameters should get
1438 * recomputed. For Further Study.
1439 */
1440 if (tp->t_maxopd <= mss)
1441 return;
1442 tp->t_maxopd = mss;
1443
1444 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
1445 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP)
1446 mss -= TCPOLEN_TSTAMP_APPA;
1447 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
1448 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC)
1449 mss -= TCPOLEN_CC_APPA;
1450 #if (MCLBYTES & (MCLBYTES - 1)) == 0
1451 if (mss > MCLBYTES)
1452 mss &= ~(MCLBYTES-1);
1453 #else
1454 if (mss > MCLBYTES)
1455 mss = mss / MCLBYTES * MCLBYTES;
1456 #endif
1457 if (so->so_snd.sb_hiwat < mss)
1458 mss = so->so_snd.sb_hiwat;
1459
1460 tp->t_maxseg = mss;
1461
1462 tcpstat.tcps_mturesent++;
1463 tp->t_rtttime = 0;
1464 tp->snd_nxt = tp->snd_una;
1465 tcp_output(tp);
1466 }
1467 }
1468
1469 /*
1470 * Look-up the routing entry to the peer of this inpcb. If no route
1471 * is found and it cannot be allocated the return NULL. This routine
1472 * is called by TCP routines that access the rmx structure and by tcp_mss
1473 * to get the interface MTU.
1474 */
1475 struct rtentry *
1476 tcp_rtlookup(inp)
1477 struct inpcb *inp;
1478 {
1479 struct route *ro;
1480 struct rtentry *rt;
1481
1482 ro = &inp->inp_route;
1483 if (ro == NULL)
1484 return (NULL);
1485 rt = ro->ro_rt;
1486 if (rt == NULL || !(rt->rt_flags & RTF_UP)) {
1487 /* No route yet, so try to acquire one */
1488 if (inp->inp_faddr.s_addr != INADDR_ANY) {
1489 ro->ro_dst.sa_family = AF_INET;
1490 ro->ro_dst.sa_len = sizeof(struct sockaddr_in);
1491 ((struct sockaddr_in *) &ro->ro_dst)->sin_addr =
1492 inp->inp_faddr;
1493 rtalloc(ro);
1494 rt = ro->ro_rt;
1495 }
1496 }
1497 return rt;
1498 }
1499
1500 #if INET6
1501 struct rtentry *
1502 tcp_rtlookup6(inp)
1503 struct inpcb *inp;
1504 {
1505 struct route_in6 *ro6;
1506 struct rtentry *rt;
1507
1508 ro6 = &inp->in6p_route;
1509 rt = ro6->ro_rt;
1510 if (rt == NULL || !(rt->rt_flags & RTF_UP)) {
1511 /* No route yet, so try to acquire one */
1512 if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1513 struct sockaddr_in6 *dst6;
1514
1515 dst6 = (struct sockaddr_in6 *)&ro6->ro_dst;
1516 dst6->sin6_family = AF_INET6;
1517 dst6->sin6_len = sizeof(*dst6);
1518 dst6->sin6_addr = inp->in6p_faddr;
1519 rtalloc((struct route *)ro6);
1520 rt = ro6->ro_rt;
1521 }
1522 }
1523 return rt;
1524 }
1525 #endif /* INET6 */
1526
1527 #if IPSEC
1528 /* compute ESP/AH header size for TCP, including outer IP header. */
1529 size_t
1530 ipsec_hdrsiz_tcp(tp)
1531 struct tcpcb *tp;
1532 {
1533 struct inpcb *inp;
1534 struct mbuf *m;
1535 size_t hdrsiz;
1536 struct ip *ip;
1537 #if INET6
1538 struct ip6_hdr *ip6 = NULL;
1539 #endif /* INET6 */
1540 struct tcphdr *th;
1541
1542 if ((tp == NULL) || ((inp = tp->t_inpcb) == NULL))
1543 return 0;
1544 MGETHDR(m, M_DONTWAIT, MT_DATA);
1545 if (!m)
1546 return 0;
1547
1548 #if INET6
1549 if ((inp->inp_vflag & INP_IPV6) != 0) {
1550 ip6 = mtod(m, struct ip6_hdr *);
1551 th = (struct tcphdr *)(ip6 + 1);
1552 m->m_pkthdr.len = m->m_len =
1553 sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
1554 tcp_fillheaders(tp, ip6, th);
1555 hdrsiz = ipsec6_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1556 } else
1557 #endif /* INET6 */
1558 {
1559 ip = mtod(m, struct ip *);
1560 th = (struct tcphdr *)(ip + 1);
1561 m->m_pkthdr.len = m->m_len = sizeof(struct tcpiphdr);
1562 tcp_fillheaders(tp, ip, th);
1563 hdrsiz = ipsec4_hdrsiz(m, IPSEC_DIR_OUTBOUND, inp);
1564 }
1565
1566 m_free(m);
1567 return hdrsiz;
1568 }
1569 #endif /*IPSEC*/
1570
1571 /*
1572 * Return a pointer to the cached information about the remote host.
1573 * The cached information is stored in the protocol specific part of
1574 * the route metrics.
1575 */
1576 struct rmxp_tao *
1577 tcp_gettaocache(inp)
1578 struct inpcb *inp;
1579 {
1580 struct rtentry *rt;
1581
1582 #if INET6
1583 if ((inp->inp_vflag & INP_IPV6) != 0)
1584 rt = tcp_rtlookup6(inp);
1585 else
1586 #endif /* INET6 */
1587 rt = tcp_rtlookup(inp);
1588
1589 /* Make sure this is a host route and is up. */
1590 if (rt == NULL ||
1591 (rt->rt_flags & (RTF_UP|RTF_HOST)) != (RTF_UP|RTF_HOST))
1592 return NULL;
1593
1594 return rmx_taop(rt->rt_rmx);
1595 }
1596
1597 /*
1598 * Clear all the TAO cache entries, called from tcp_init.
1599 *
1600 * XXX
1601 * This routine is just an empty one, because we assume that the routing
1602 * routing tables are initialized at the same time when TCP, so there is
1603 * nothing in the cache left over.
1604 */
1605 static void
1606 tcp_cleartaocache()
1607 {
1608 }