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