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