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