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