]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/tcp_input.c
b642c4298ba4c725747ff42622f7c8c8344093be
[apple/xnu.git] / bsd / netinet / tcp_input.c
1 /*
2 * Copyright (c) 2000-2008 Apple Inc. All rights reserved.
3 *
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5 *
6 * This file contains Original Code and/or Modifications of Original Code
7 * as defined in and that are subject to the Apple Public Source License
8 * Version 2.0 (the 'License'). You may not use this file except in
9 * compliance with the License. The rights granted to you under the License
10 * may not be used to create, or enable the creation or redistribution of,
11 * unlawful or unlicensed copies of an Apple operating system, or to
12 * circumvent, violate, or enable the circumvention or violation of, any
13 * terms of an Apple operating system software license agreement.
14 *
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
17 *
18 * The Original Code and all software distributed under the License are
19 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23 * Please see the License for the specific language governing rights and
24 * limitations under the License.
25 *
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27 */
28 /*
29 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
30 * The Regents of the University of California. All rights reserved.
31 *
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
34 * are met:
35 * 1. Redistributions of source code must retain the above copyright
36 * notice, this list of conditions and the following disclaimer.
37 * 2. Redistributions in binary form must reproduce the above copyright
38 * notice, this list of conditions and the following disclaimer in the
39 * documentation and/or other materials provided with the distribution.
40 * 3. All advertising materials mentioning features or use of this software
41 * must display the following acknowledgement:
42 * This product includes software developed by the University of
43 * California, Berkeley and its contributors.
44 * 4. Neither the name of the University nor the names of its contributors
45 * may be used to endorse or promote products derived from this software
46 * without specific prior written permission.
47 *
48 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58 * SUCH DAMAGE.
59 *
60 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
61 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
62 */
63 /*
64 * NOTICE: This file was modified by SPARTA, Inc. in 2005 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
67 * Version 2.0.
68 */
69
70 #include <sys/param.h>
71 #include <sys/systm.h>
72 #include <sys/kernel.h>
73 #include <sys/sysctl.h>
74 #include <sys/malloc.h>
75 #include <sys/mbuf.h>
76 #include <sys/proc.h> /* for proc0 declaration */
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/socketvar.h>
80 #include <sys/syslog.h>
81
82 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
83
84 #include <machine/endian.h>
85
86 #include <net/if.h>
87 #include <net/if_types.h>
88 #include <net/route.h>
89
90 #include <netinet/in.h>
91 #include <netinet/in_systm.h>
92 #include <netinet/ip.h>
93 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
94 #include <netinet/in_var.h>
95 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
96 #include <netinet/in_pcb.h>
97 #include <netinet/ip_var.h>
98 #if INET6
99 #include <netinet/ip6.h>
100 #include <netinet/icmp6.h>
101 #include <netinet6/nd6.h>
102 #include <netinet6/ip6_var.h>
103 #include <netinet6/in6_pcb.h>
104 #endif
105 #include <netinet/tcp.h>
106 #include <netinet/tcp_fsm.h>
107 #include <netinet/tcp_seq.h>
108 #include <netinet/tcp_timer.h>
109 #include <netinet/tcp_var.h>
110 #if INET6
111 #include <netinet6/tcp6_var.h>
112 #endif
113 #include <netinet/tcpip.h>
114 #if TCPDEBUG
115 #include <netinet/tcp_debug.h>
116 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
117 struct tcphdr tcp_savetcp;
118 #endif /* TCPDEBUG */
119
120 #if IPSEC
121 #include <netinet6/ipsec.h>
122 #if INET6
123 #include <netinet6/ipsec6.h>
124 #endif
125 #include <netkey/key.h>
126 #endif /*IPSEC*/
127
128 #if CONFIG_MACF_NET || CONFIG_MACF_SOCKET
129 #include <security/mac_framework.h>
130 #endif /* CONFIG_MACF_NET || CONFIG_MACF_SOCKET */
131
132 #include <sys/kdebug.h>
133
134 #ifndef __APPLE__
135 MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
136 #endif
137
138 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
139 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
140 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
141 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
142
143 static int tcprexmtthresh = 2;
144 tcp_cc tcp_ccgen;
145
146 #if IPSEC
147 extern int ipsec_bypass;
148 #endif
149
150 struct tcpstat tcpstat;
151
152 static int log_in_vain = 0;
153 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
154 &log_in_vain, 0, "Log all incoming TCP connections");
155
156 static int blackhole = 0;
157 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
158 &blackhole, 0, "Do not send RST when dropping refused connections");
159
160 int tcp_delack_enabled = 3;
161 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
162 &tcp_delack_enabled, 0,
163 "Delay ACK to try and piggyback it onto a data packet");
164
165 int tcp_lq_overflow = 1;
166 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_lq_overflow, CTLFLAG_RW,
167 &tcp_lq_overflow, 0,
168 "Listen Queue Overflow");
169
170 #if TCP_DROP_SYNFIN
171 static int drop_synfin = 1;
172 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
173 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
174 #endif
175
176 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW|CTLFLAG_LOCKED, 0,
177 "TCP Segment Reassembly Queue");
178
179 __private_extern__ int tcp_reass_maxseg = 0;
180 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RW,
181 &tcp_reass_maxseg, 0,
182 "Global maximum number of TCP Segments in Reassembly Queue");
183
184 __private_extern__ int tcp_reass_qsize = 0;
185 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
186 &tcp_reass_qsize, 0,
187 "Global number of TCP Segments currently in Reassembly Queue");
188
189 static int tcp_reass_overflows = 0;
190 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
191 &tcp_reass_overflows, 0,
192 "Global number of TCP Segment Reassembly Queue Overflows");
193
194
195 __private_extern__ int slowlink_wsize = 8192;
196 SYSCTL_INT(_net_inet_tcp, OID_AUTO, slowlink_wsize, CTLFLAG_RW,
197 &slowlink_wsize, 0, "Maximum advertised window size for slowlink");
198
199 static int maxseg_unacked = 8;
200 SYSCTL_INT(_net_inet_tcp, OID_AUTO, maxseg_unacked, CTLFLAG_RW,
201 &maxseg_unacked, 0, "Maximum number of outstanding segments left unacked");
202
203 static int tcp_do_rfc3465 = 1;
204 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
205 &tcp_do_rfc3465, 0, "");
206
207 static int tcp_do_rfc3465_lim2 = 1;
208 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3465_lim2, CTLFLAG_RW,
209 &tcp_do_rfc3465_lim2, 0, "Appropriate bytes counting w/ L=2*SMSS");
210
211 #if CONFIG_IFEF_NOWINDOWSCALE
212 int tcp_obey_ifef_nowindowscale = 0;
213 SYSCTL_INT(_net_inet_tcp, OID_AUTO, obey_ifef_nowindowscale, CTLFLAG_RW,
214 &tcp_obey_ifef_nowindowscale, 0, "");
215 #endif
216
217 extern int tcp_TCPTV_MIN;
218
219 u_int32_t tcp_now;
220
221 struct inpcbhead tcb;
222 #define tcb6 tcb /* for KAME src sync over BSD*'s */
223 struct inpcbinfo tcbinfo;
224
225 static void tcp_dooptions(struct tcpcb *,
226 u_char *, int, struct tcphdr *, struct tcpopt *, unsigned int);
227 static void tcp_pulloutofband(struct socket *,
228 struct tcphdr *, struct mbuf *, int);
229 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
230 struct mbuf *);
231 static void tcp_xmit_timer(struct tcpcb *, int);
232 static inline unsigned int tcp_maxmtu(struct rtentry *);
233 #if INET6
234 static inline unsigned int tcp_maxmtu6(struct rtentry *);
235 #endif
236
237 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
238 #if INET6
239 #define ND6_HINT(tp) \
240 do { \
241 if ((tp) && (tp)->t_inpcb && \
242 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
243 (tp)->t_inpcb->in6p_route.ro_rt) \
244 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
245 } while (0)
246 #else
247 #define ND6_HINT(tp)
248 #endif
249
250 extern u_int32_t *delack_bitmask;
251
252 extern void add_to_time_wait(struct tcpcb *);
253 extern void postevent(struct socket *, struct sockbuf *, int);
254
255 extern void ipfwsyslog( int level, const char *format,...);
256 extern int ChkAddressOK( __uint32_t dstaddr, __uint32_t srcaddr );
257 extern int fw_verbose;
258 __private_extern__ int tcp_sockthreshold;
259 __private_extern__ int tcp_win_scale;
260
261 #if IPFIREWALL
262 #define log_in_vain_log( a ) { \
263 if ( (log_in_vain == 3 ) && (fw_verbose == 2)) { /* Apple logging, log to ipfw.log */ \
264 ipfwsyslog a ; \
265 } \
266 else log a ; \
267 }
268 #else
269 #define log_in_vain_log( a ) { log a; }
270 #endif
271
272
273 /*
274 * Indicate whether this ack should be delayed.
275 * We can delay the ack if:
276 * - delayed acks are enabled (set to 1) and
277 * - our last ack wasn't a 0-sized window. We never want to delay
278 * the ack that opens up a 0-sized window.
279 * - delayed acks are enabled (set to 2, "more compatible") and
280 * - our last ack wasn't a 0-sized window.
281 * - if the peer hasn't sent us a TH_PUSH data packet (this solves 3649245)
282 * - the peer hasn't sent us a TH_PUSH data packet, if he did, take this as a clue that we
283 * need to ACK with no delay. This helps higher level protocols who won't send
284 * us more data even if the window is open because their last "segment" hasn't been ACKed
285 * - delayed acks are enabled (set to 3, "streaming detection") and
286 * - if we receive more than "maxseg_unacked" full packets per second on this socket
287 * - if we don't have more than "maxseg_unacked" delayed so far
288 * - if those criteria aren't met, acts like "2". Allowing faster acking while browsing for example.
289 *
290 */
291 #define DELAY_ACK(tp) \
292 (((tcp_delack_enabled == 1) && ((tp->t_flags & TF_RXWIN0SENT) == 0)) || \
293 (((tcp_delack_enabled == 2) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
294 ((thflags & TH_PUSH) == 0) && ((tp->t_flags & TF_DELACK) == 0)) || \
295 (((tcp_delack_enabled == 3) && (tp->t_flags & TF_RXWIN0SENT) == 0) && \
296 (tp->t_rcvtime == 0) && ((thflags & TH_PUSH) == 0) && \
297 (((tp->t_unacksegs == 0)) || \
298 ((tp->rcv_byps > (maxseg_unacked * tp->t_maxseg)) && (tp->t_unacksegs < maxseg_unacked)))))
299
300 static int tcp_dropdropablreq(struct socket *head);
301 static void tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th);
302
303
304 static int
305 tcp_reass(tp, th, tlenp, m)
306 register struct tcpcb *tp;
307 register struct tcphdr *th;
308 int *tlenp;
309 struct mbuf *m;
310 {
311 struct tseg_qent *q;
312 struct tseg_qent *p = NULL;
313 struct tseg_qent *nq;
314 struct tseg_qent *te = NULL;
315 struct socket *so = tp->t_inpcb->inp_socket;
316 int flags;
317 int dowakeup = 0;
318
319 /*
320 * Call with th==0 after become established to
321 * force pre-ESTABLISHED data up to user socket.
322 */
323 if (th == NULL)
324 goto present;
325
326 /*
327 * Limit the number of segments in the reassembly queue to prevent
328 * holding on to too many segments (and thus running out of mbufs).
329 * Make sure to let the missing segment through which caused this
330 * queue. Always keep one global queue entry spare to be able to
331 * process the missing segment.
332 */
333 if (th->th_seq != tp->rcv_nxt &&
334 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
335 tcp_reass_overflows++;
336 tcpstat.tcps_rcvmemdrop++;
337 m_freem(m);
338 *tlenp = 0;
339 return (0);
340 }
341
342 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
343 MALLOC(te, struct tseg_qent *, sizeof (struct tseg_qent), M_TSEGQ,
344 M_NOWAIT);
345 if (te == NULL) {
346 tcpstat.tcps_rcvmemdrop++;
347 m_freem(m);
348 return (0);
349 }
350 tcp_reass_qsize++;
351
352 /*
353 * Find a segment which begins after this one does.
354 */
355 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
356 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
357 break;
358 p = q;
359 }
360
361 /*
362 * If there is a preceding segment, it may provide some of
363 * our data already. If so, drop the data from the incoming
364 * segment. If it provides all of our data, drop us.
365 */
366 if (p != NULL) {
367 register int i;
368 /* conversion to int (in i) handles seq wraparound */
369 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
370 if (i > 0) {
371 if (i >= *tlenp) {
372 tcpstat.tcps_rcvduppack++;
373 tcpstat.tcps_rcvdupbyte += *tlenp;
374 m_freem(m);
375 FREE(te, M_TSEGQ);
376 tcp_reass_qsize--;
377 /*
378 * Try to present any queued data
379 * at the left window edge to the user.
380 * This is needed after the 3-WHS
381 * completes.
382 */
383 goto present; /* ??? */
384 }
385 m_adj(m, i);
386 *tlenp -= i;
387 th->th_seq += i;
388 }
389 }
390 tcpstat.tcps_rcvoopack++;
391 tcpstat.tcps_rcvoobyte += *tlenp;
392
393 /*
394 * While we overlap succeeding segments trim them or,
395 * if they are completely covered, dequeue them.
396 */
397 while (q) {
398 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
399 if (i <= 0)
400 break;
401 if (i < q->tqe_len) {
402 q->tqe_th->th_seq += i;
403 q->tqe_len -= i;
404 m_adj(q->tqe_m, i);
405 break;
406 }
407
408 nq = LIST_NEXT(q, tqe_q);
409 LIST_REMOVE(q, tqe_q);
410 m_freem(q->tqe_m);
411 FREE(q, M_TSEGQ);
412 tcp_reass_qsize--;
413 q = nq;
414 }
415
416 /* Insert the new segment queue entry into place. */
417 te->tqe_m = m;
418 te->tqe_th = th;
419 te->tqe_len = *tlenp;
420
421 if (p == NULL) {
422 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
423 } else {
424 LIST_INSERT_AFTER(p, te, tqe_q);
425 }
426
427 present:
428 /*
429 * Present data to user, advancing rcv_nxt through
430 * completed sequence space.
431 */
432 if (!TCPS_HAVEESTABLISHED(tp->t_state))
433 return (0);
434 q = LIST_FIRST(&tp->t_segq);
435 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
436 return (0);
437 do {
438 tp->rcv_nxt += q->tqe_len;
439 flags = q->tqe_th->th_flags & TH_FIN;
440 nq = LIST_NEXT(q, tqe_q);
441 LIST_REMOVE(q, tqe_q);
442 if (so->so_state & SS_CANTRCVMORE)
443 m_freem(q->tqe_m);
444 else {
445 if (sbappendstream(&so->so_rcv, q->tqe_m))
446 dowakeup = 1;
447 }
448 FREE(q, M_TSEGQ);
449 tcp_reass_qsize--;
450 q = nq;
451 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
452 ND6_HINT(tp);
453
454 #if INET6
455 if ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) {
456
457 KERNEL_DEBUG(DBG_LAYER_BEG,
458 ((tp->t_inpcb->inp_fport << 16) | tp->t_inpcb->inp_lport),
459 (((tp->t_inpcb->in6p_laddr.s6_addr16[0] & 0xffff) << 16) |
460 (tp->t_inpcb->in6p_faddr.s6_addr16[0] & 0xffff)),
461 0,0,0);
462 }
463 else
464 #endif
465 {
466 KERNEL_DEBUG(DBG_LAYER_BEG,
467 ((tp->t_inpcb->inp_fport << 16) | tp->t_inpcb->inp_lport),
468 (((tp->t_inpcb->inp_laddr.s_addr & 0xffff) << 16) |
469 (tp->t_inpcb->inp_faddr.s_addr & 0xffff)),
470 0,0,0);
471 }
472 if (dowakeup)
473 sorwakeup(so); /* done with socket lock held */
474 return (flags);
475
476 }
477
478 /*
479 * Reduce congestion window.
480 */
481 static void
482 tcp_reduce_congestion_window(
483 struct tcpcb *tp)
484 {
485 u_int win;
486
487 win = min(tp->snd_wnd, tp->snd_cwnd) /
488 2 / tp->t_maxseg;
489 if (win < 2)
490 win = 2;
491 tp->snd_ssthresh = win * tp->t_maxseg;
492 ENTER_FASTRECOVERY(tp);
493 tp->snd_recover = tp->snd_max;
494 tp->t_timer[TCPT_REXMT] = 0;
495 tp->t_rtttime = 0;
496 tp->ecn_flags |= TE_SENDCWR;
497 tp->snd_cwnd = tp->snd_ssthresh +
498 tp->t_maxseg * tcprexmtthresh;
499 }
500
501
502 /*
503 * TCP input routine, follows pages 65-76 of the
504 * protocol specification dated September, 1981 very closely.
505 */
506 #if INET6
507 int
508 tcp6_input(mp, offp)
509 struct mbuf **mp;
510 int *offp;
511 {
512 register struct mbuf *m = *mp;
513 struct in6_ifaddr *ia6;
514
515 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), return IPPROTO_DONE);
516
517 /*
518 * draft-itojun-ipv6-tcp-to-anycast
519 * better place to put this in?
520 */
521 ia6 = ip6_getdstifaddr(m);
522 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
523 struct ip6_hdr *ip6;
524
525 ip6 = mtod(m, struct ip6_hdr *);
526 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
527 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
528 return IPPROTO_DONE;
529 }
530
531 tcp_input(m, *offp);
532 return IPPROTO_DONE;
533 }
534 #endif
535
536 void
537 tcp_input(m, off0)
538 struct mbuf *m;
539 int off0;
540 {
541 register struct tcphdr *th;
542 register struct ip *ip = NULL;
543 register struct ipovly *ipov;
544 register struct inpcb *inp;
545 u_char *optp = NULL;
546 int optlen = 0;
547 int len, tlen, off;
548 int drop_hdrlen;
549 register struct tcpcb *tp = 0;
550 register int thflags;
551 struct socket *so = 0;
552 int todrop, acked, ourfinisacked, needoutput = 0;
553 struct in_addr laddr;
554 #if INET6
555 struct in6_addr laddr6;
556 #endif
557 int dropsocket = 0;
558 int iss = 0;
559 int nosock = 0;
560 u_int32_t tiwin;
561 struct tcpopt to; /* options in this segment */
562 struct sockaddr_in *next_hop = NULL;
563 #if TCPDEBUG
564 short ostate = 0;
565 #endif
566 struct m_tag *fwd_tag;
567 u_char ip_ecn = IPTOS_ECN_NOTECT;
568 unsigned int ifscope;
569
570 /*
571 * Record the interface where this segment arrived on; this does not
572 * affect normal data output (for non-detached TCP) as it provides a
573 * hint about which route and interface to use for sending in the
574 * absence of a PCB, when scoped routing (and thus source interface
575 * selection) are enabled.
576 */
577 if ((m->m_flags & M_PKTHDR) && m->m_pkthdr.rcvif != NULL)
578 ifscope = m->m_pkthdr.rcvif->if_index;
579 else
580 ifscope = IFSCOPE_NONE;
581
582 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
583 if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
584 fwd_tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
585 KERNEL_TAG_TYPE_IPFORWARD, NULL);
586 } else {
587 fwd_tag = NULL;
588 }
589 if (fwd_tag != NULL) {
590 struct ip_fwd_tag *ipfwd_tag = (struct ip_fwd_tag *)(fwd_tag+1);
591
592 next_hop = ipfwd_tag->next_hop;
593 m_tag_delete(m, fwd_tag);
594 }
595
596 #if INET6
597 struct ip6_hdr *ip6 = NULL;
598 int isipv6;
599 #endif /* INET6 */
600 int rstreason; /* For badport_bandlim accounting purposes */
601 struct proc *proc0=current_proc();
602
603 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_START,0,0,0,0,0);
604
605 #if INET6
606 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
607 #endif
608 bzero((char *)&to, sizeof(to));
609
610 tcpstat.tcps_rcvtotal++;
611
612
613
614 #if INET6
615 if (isipv6) {
616 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
617 ip6 = mtod(m, struct ip6_hdr *);
618 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
619 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
620 tcpstat.tcps_rcvbadsum++;
621 goto dropnosock;
622 }
623 th = (struct tcphdr *)((caddr_t)ip6 + off0);
624
625 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
626 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
627 th->th_seq, th->th_ack, th->th_win);
628 /*
629 * Be proactive about unspecified IPv6 address in source.
630 * As we use all-zero to indicate unbounded/unconnected pcb,
631 * unspecified IPv6 address can be used to confuse us.
632 *
633 * Note that packets with unspecified IPv6 destination is
634 * already dropped in ip6_input.
635 */
636 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
637 /* XXX stat */
638 goto dropnosock;
639 }
640 } else
641 #endif /* INET6 */
642 {
643 /*
644 * Get IP and TCP header together in first mbuf.
645 * Note: IP leaves IP header in first mbuf.
646 */
647 if (off0 > sizeof (struct ip)) {
648 ip_stripoptions(m, (struct mbuf *)0);
649 off0 = sizeof(struct ip);
650 if (m->m_pkthdr.csum_flags & CSUM_TCP_SUM16)
651 m->m_pkthdr.csum_flags = 0; /* invalidate hwcksuming */
652
653 }
654 if (m->m_len < sizeof (struct tcpiphdr)) {
655 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
656 tcpstat.tcps_rcvshort++;
657 return;
658 }
659 }
660 ip = mtod(m, struct ip *);
661 ipov = (struct ipovly *)ip;
662 th = (struct tcphdr *)((caddr_t)ip + off0);
663 tlen = ip->ip_len;
664
665 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
666 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
667 th->th_seq, th->th_ack, th->th_win);
668
669 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
670 if (m->m_pkthdr.csum_flags & CSUM_TCP_SUM16) {
671 u_short pseudo;
672 char b[9];
673 *(uint32_t*)&b[0] = *(uint32_t*)&ipov->ih_x1[0];
674 *(uint32_t*)&b[4] = *(uint32_t*)&ipov->ih_x1[4];
675 *(uint8_t*)&b[8] = *(uint8_t*)&ipov->ih_x1[8];
676
677 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
678 ipov->ih_len = (u_short)tlen;
679
680 #if BYTE_ORDER != BIG_ENDIAN
681 HTONS(ipov->ih_len);
682 #endif
683
684 pseudo = in_cksum(m, sizeof (struct ip));
685
686 *(uint32_t*)&ipov->ih_x1[0] = *(uint32_t*)&b[0];
687 *(uint32_t*)&ipov->ih_x1[4] = *(uint32_t*)&b[4];
688 *(uint8_t*)&ipov->ih_x1[8] = *(uint8_t*)&b[8];
689
690 th->th_sum = in_addword(pseudo, (m->m_pkthdr.csum_data & 0xFFFF));
691 } else {
692 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
693 th->th_sum = m->m_pkthdr.csum_data;
694 else
695 th->th_sum = in_pseudo(ip->ip_src.s_addr,
696 ip->ip_dst.s_addr, htonl(m->m_pkthdr.csum_data +
697 ip->ip_len + IPPROTO_TCP));
698 }
699 th->th_sum ^= 0xffff;
700 } else {
701 char b[9];
702 /*
703 * Checksum extended TCP header and data.
704 */
705 *(uint32_t*)&b[0] = *(uint32_t*)&ipov->ih_x1[0];
706 *(uint32_t*)&b[4] = *(uint32_t*)&ipov->ih_x1[4];
707 *(uint8_t*)&b[8] = *(uint8_t*)&ipov->ih_x1[8];
708
709 len = sizeof (struct ip) + tlen;
710 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
711 ipov->ih_len = (u_short)tlen;
712
713 #if BYTE_ORDER != BIG_ENDIAN
714 HTONS(ipov->ih_len);
715 #endif
716
717 th->th_sum = in_cksum(m, len);
718
719 *(uint32_t*)&ipov->ih_x1[0] = *(uint32_t*)&b[0];
720 *(uint32_t*)&ipov->ih_x1[4] = *(uint32_t*)&b[4];
721 *(uint8_t*)&ipov->ih_x1[8] = *(uint8_t*)&b[8];
722
723 tcp_in_cksum_stats(len);
724 }
725 if (th->th_sum) {
726 tcpstat.tcps_rcvbadsum++;
727 goto dropnosock;
728 }
729 #if INET6
730 /* Re-initialization for later version check */
731 ip->ip_v = IPVERSION;
732 #endif
733 ip_ecn = (ip->ip_tos & IPTOS_ECN_MASK);
734 }
735
736 /*
737 * Check that TCP offset makes sense,
738 * pull out TCP options and adjust length. XXX
739 */
740 off = th->th_off << 2;
741 if (off < sizeof (struct tcphdr) || off > tlen) {
742 tcpstat.tcps_rcvbadoff++;
743 goto dropnosock;
744 }
745 tlen -= off; /* tlen is used instead of ti->ti_len */
746 if (off > sizeof (struct tcphdr)) {
747 #if INET6
748 if (isipv6) {
749 IP6_EXTHDR_CHECK(m, off0, off, return);
750 ip6 = mtod(m, struct ip6_hdr *);
751 th = (struct tcphdr *)((caddr_t)ip6 + off0);
752 } else
753 #endif /* INET6 */
754 {
755 if (m->m_len < sizeof(struct ip) + off) {
756 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
757 tcpstat.tcps_rcvshort++;
758 return;
759 }
760 ip = mtod(m, struct ip *);
761 ipov = (struct ipovly *)ip;
762 th = (struct tcphdr *)((caddr_t)ip + off0);
763 }
764 }
765 optlen = off - sizeof (struct tcphdr);
766 optp = (u_char *)(th + 1);
767 /*
768 * Do quick retrieval of timestamp options ("options
769 * prediction?"). If timestamp is the only option and it's
770 * formatted as recommended in RFC 1323 appendix A, we
771 * quickly get the values now and not bother calling
772 * tcp_dooptions(), etc.
773 */
774 if ((optlen == TCPOLEN_TSTAMP_APPA ||
775 (optlen > TCPOLEN_TSTAMP_APPA &&
776 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
777 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
778 (th->th_flags & TH_SYN) == 0) {
779 to.to_flags |= TOF_TS;
780 to.to_tsval = ntohl(*(u_int32_t *)(optp + 4));
781 to.to_tsecr = ntohl(*(u_int32_t *)(optp + 8));
782 optp = NULL; /* we've parsed the options */
783 }
784 }
785 thflags = th->th_flags;
786
787 #if TCP_DROP_SYNFIN
788 /*
789 * If the drop_synfin option is enabled, drop all packets with
790 * both the SYN and FIN bits set. This prevents e.g. nmap from
791 * identifying the TCP/IP stack.
792 *
793 * This is a violation of the TCP specification.
794 */
795 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
796 goto dropnosock;
797 #endif
798
799 /*
800 * Convert TCP protocol specific fields to host format.
801 */
802
803 #if BYTE_ORDER != BIG_ENDIAN
804 NTOHL(th->th_seq);
805 NTOHL(th->th_ack);
806 NTOHS(th->th_win);
807 NTOHS(th->th_urp);
808 #endif
809
810 /*
811 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
812 * until after ip6_savecontrol() is called and before other functions
813 * which don't want those proto headers.
814 * Because ip6_savecontrol() is going to parse the mbuf to
815 * search for data to be passed up to user-land, it wants mbuf
816 * parameters to be unchanged.
817 */
818 drop_hdrlen = off0 + off;
819
820 /*
821 * Locate pcb for segment.
822 */
823 findpcb:
824 #if IPFIREWALL_FORWARD
825 if (next_hop != NULL
826 #if INET6
827 && isipv6 == 0 /* IPv6 support is not yet */
828 #endif /* INET6 */
829 ) {
830 /*
831 * Diverted. Pretend to be the destination.
832 * already got one like this?
833 */
834 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
835 ip->ip_dst, th->th_dport, 0, m->m_pkthdr.rcvif);
836 if (!inp) {
837 /*
838 * No, then it's new. Try find the ambushing socket
839 */
840 if (!next_hop->sin_port) {
841 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src,
842 th->th_sport, next_hop->sin_addr,
843 th->th_dport, 1, m->m_pkthdr.rcvif);
844 } else {
845 inp = in_pcblookup_hash(&tcbinfo,
846 ip->ip_src, th->th_sport,
847 next_hop->sin_addr,
848 ntohs(next_hop->sin_port), 1,
849 m->m_pkthdr.rcvif);
850 }
851 }
852 } else
853 #endif /* IPFIREWALL_FORWARD */
854 {
855 #if INET6
856 if (isipv6)
857 inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_src, th->th_sport,
858 &ip6->ip6_dst, th->th_dport, 1,
859 m->m_pkthdr.rcvif);
860 else
861 #endif /* INET6 */
862 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
863 ip->ip_dst, th->th_dport, 1, m->m_pkthdr.rcvif);
864 }
865
866 /*
867 * Use the interface scope information from the PCB for outbound
868 * segments. If the PCB isn't present and if scoped routing is
869 * enabled, tcp_respond will use the scope of the interface where
870 * the segment arrived on.
871 */
872 if (inp != NULL && (inp->inp_flags & INP_BOUND_IF))
873 ifscope = inp->inp_boundif;
874 #if IPSEC
875 if (ipsec_bypass == 0) {
876 #if INET6
877 if (isipv6) {
878 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
879 IPSEC_STAT_INCREMENT(ipsec6stat.in_polvio);
880 if (in_pcb_checkstate(inp, WNT_RELEASE, 0) == WNT_STOPUSING)
881 inp = NULL; // pretend we didn't find it
882 goto dropnosock;
883 }
884 } else
885 #endif /* INET6 */
886 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
887 IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
888 if (in_pcb_checkstate(inp, WNT_RELEASE, 0) == WNT_STOPUSING)
889 inp = NULL; // pretend we didn't find it
890 goto dropnosock;
891 }
892 }
893 #endif /*IPSEC*/
894
895 /*
896 * If the state is CLOSED (i.e., TCB does not exist) then
897 * all data in the incoming segment is discarded.
898 * If the TCB exists but is in CLOSED state, it is embryonic,
899 * but should either do a listen or a connect soon.
900 */
901 if (inp == NULL) {
902 if (log_in_vain) {
903 #if INET6
904 char dbuf[MAX_IPv6_STR_LEN], sbuf[MAX_IPv6_STR_LEN];
905 #else /* INET6 */
906 char dbuf[MAX_IPv4_STR_LEN], sbuf[MAX_IPv4_STR_LEN];
907 #endif /* INET6 */
908
909 #if INET6
910 if (isipv6) {
911 inet_ntop(AF_INET6, &ip6->ip6_dst, dbuf, sizeof(dbuf));
912 inet_ntop(AF_INET6, &ip6->ip6_src, sbuf, sizeof(sbuf));
913 } else
914 #endif
915 {
916 inet_ntop(AF_INET, &ip->ip_dst, dbuf, sizeof(dbuf));
917 inet_ntop(AF_INET, &ip->ip_src, sbuf, sizeof(sbuf));
918 }
919 switch (log_in_vain) {
920 case 1:
921 if(thflags & TH_SYN)
922 log(LOG_INFO,
923 "Connection attempt to TCP %s:%d from %s:%d\n",
924 dbuf, ntohs(th->th_dport),
925 sbuf,
926 ntohs(th->th_sport));
927 break;
928 case 2:
929 log(LOG_INFO,
930 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
931 dbuf, ntohs(th->th_dport), sbuf,
932 ntohs(th->th_sport), thflags);
933 break;
934 case 3:
935 if ((thflags & TH_SYN) &&
936 !(m->m_flags & (M_BCAST | M_MCAST)) &&
937 #if INET6
938 ((isipv6 && !IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) ||
939 (!isipv6 && ip->ip_dst.s_addr != ip->ip_src.s_addr))
940 #else
941 ip->ip_dst.s_addr != ip->ip_src.s_addr
942 #endif
943 )
944 log_in_vain_log((LOG_INFO,
945 "Stealth Mode connection attempt to TCP %s:%d from %s:%d\n",
946 dbuf, ntohs(th->th_dport),
947 sbuf,
948 ntohs(th->th_sport)));
949 break;
950 default:
951 break;
952 }
953 }
954 if (blackhole) {
955 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type != IFT_LOOP)
956 switch (blackhole) {
957 case 1:
958 if (thflags & TH_SYN)
959 goto dropnosock;
960 break;
961 case 2:
962 goto dropnosock;
963 default:
964 goto dropnosock;
965 }
966 }
967 rstreason = BANDLIM_RST_CLOSEDPORT;
968 goto dropwithresetnosock;
969 }
970 so = inp->inp_socket;
971 if (so == NULL) {
972 /* This case shouldn't happen as the socket shouldn't be null
973 * if inp_state isn't set to INPCB_STATE_DEAD
974 * But just in case, we pretend we didn't find the socket if we hit this case
975 * as this isn't cause for a panic (the socket might be leaked however)...
976 */
977 inp = NULL;
978 #if TEMPDEBUG
979 printf("tcp_input: no more socket for inp=%x. This shouldn't happen\n", inp);
980 #endif
981 goto dropnosock;
982 }
983
984 tcp_lock(so, 1, (void *)2);
985 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
986 tcp_unlock(so, 1, (void *)2);
987 inp = NULL; // pretend we didn't find it
988 goto dropnosock;
989 }
990
991 tp = intotcpcb(inp);
992 if (tp == 0) {
993 rstreason = BANDLIM_RST_CLOSEDPORT;
994 goto dropwithreset;
995 }
996 if (tp->t_state == TCPS_CLOSED)
997 goto drop;
998
999 /* Unscale the window into a 32-bit value. */
1000 if ((thflags & TH_SYN) == 0)
1001 tiwin = th->th_win << tp->snd_scale;
1002 else
1003 tiwin = th->th_win;
1004
1005 #if CONFIG_MACF_NET
1006 if (mac_inpcb_check_deliver(inp, m, AF_INET, SOCK_STREAM))
1007 goto drop;
1008 #endif
1009
1010 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
1011 #if TCPDEBUG
1012 if (so->so_options & SO_DEBUG) {
1013 ostate = tp->t_state;
1014 #if INET6
1015 if (isipv6)
1016 bcopy((char *)ip6, (char *)tcp_saveipgen,
1017 sizeof(*ip6));
1018 else
1019 #endif /* INET6 */
1020 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
1021 tcp_savetcp = *th;
1022 }
1023 #endif
1024 if (so->so_options & SO_ACCEPTCONN) {
1025 register struct tcpcb *tp0 = tp;
1026 struct socket *so2;
1027 struct socket *oso;
1028 struct sockaddr_storage from;
1029 #if INET6
1030 struct inpcb *oinp = sotoinpcb(so);
1031 #endif /* INET6 */
1032 unsigned int head_ifscope;
1033
1034 /* Get listener's bound-to-interface, if any */
1035 head_ifscope = (inp->inp_flags & INP_BOUND_IF) ?
1036 inp->inp_boundif : IFSCOPE_NONE;
1037
1038 #if !IPSEC
1039 /*
1040 * Current IPsec implementation makes incorrect IPsec
1041 * cache if this check is done here.
1042 * So delay this until duplicated socket is created.
1043 */
1044 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1045 /*
1046 * Note: dropwithreset makes sure we don't
1047 * send a RST in response to a RST.
1048 */
1049 if (thflags & TH_ACK) {
1050 tcpstat.tcps_badsyn++;
1051 rstreason = BANDLIM_RST_OPENPORT;
1052 goto dropwithreset;
1053 }
1054 goto drop;
1055 }
1056 #endif
1057 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START,0,0,0,0,0);
1058
1059 #if INET6
1060 /*
1061 * If deprecated address is forbidden,
1062 * we do not accept SYN to deprecated interface
1063 * address to prevent any new inbound connection from
1064 * getting established.
1065 * When we do not accept SYN, we send a TCP RST,
1066 * with deprecated source address (instead of dropping
1067 * it). We compromise it as it is much better for peer
1068 * to send a RST, and RST will be the final packet
1069 * for the exchange.
1070 *
1071 * If we do not forbid deprecated addresses, we accept
1072 * the SYN packet. RFC2462 does not suggest dropping
1073 * SYN in this case.
1074 * If we decipher RFC2462 5.5.4, it says like this:
1075 * 1. use of deprecated addr with existing
1076 * communication is okay - "SHOULD continue to be
1077 * used"
1078 * 2. use of it with new communication:
1079 * (2a) "SHOULD NOT be used if alternate address
1080 * with sufficient scope is available"
1081 * (2b) nothing mentioned otherwise.
1082 * Here we fall into (2b) case as we have no choice in
1083 * our source address selection - we must obey the peer.
1084 *
1085 * The wording in RFC2462 is confusing, and there are
1086 * multiple description text for deprecated address
1087 * handling - worse, they are not exactly the same.
1088 * I believe 5.5.4 is the best one, so we follow 5.5.4.
1089 */
1090 if (isipv6 && !ip6_use_deprecated) {
1091 struct in6_ifaddr *ia6;
1092
1093 if ((ia6 = ip6_getdstifaddr(m)) &&
1094 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1095 tp = NULL;
1096 rstreason = BANDLIM_RST_OPENPORT;
1097 goto dropwithreset;
1098 }
1099 }
1100 #endif
1101 if (so->so_filt) {
1102 #if INET6
1103 if (isipv6) {
1104 struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)&from;
1105
1106 sin6->sin6_len = sizeof(*sin6);
1107 sin6->sin6_family = AF_INET6;
1108 sin6->sin6_port = th->th_sport;
1109 sin6->sin6_flowinfo = 0;
1110 sin6->sin6_addr = ip6->ip6_src;
1111 sin6->sin6_scope_id = 0;
1112 }
1113 else
1114 #endif
1115 {
1116 struct sockaddr_in *sin = (struct sockaddr_in*)&from;
1117
1118 sin->sin_len = sizeof(*sin);
1119 sin->sin_family = AF_INET;
1120 sin->sin_port = th->th_sport;
1121 sin->sin_addr = ip->ip_src;
1122 }
1123 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
1124 } else {
1125 so2 = sonewconn(so, 0, NULL);
1126 }
1127 if (so2 == 0) {
1128 tcpstat.tcps_listendrop++;
1129 if (tcp_dropdropablreq(so)) {
1130 if (so->so_filt)
1131 so2 = sonewconn(so, 0, (struct sockaddr*)&from);
1132 else
1133 so2 = sonewconn(so, 0, NULL);
1134 }
1135 if (!so2)
1136 goto drop;
1137 }
1138
1139 /* Point "inp" and "tp" in tandem to new socket */
1140 inp = (struct inpcb *)so2->so_pcb;
1141 tp = intotcpcb(inp);
1142
1143 oso = so;
1144 tcp_unlock(so, 0, 0); /* Unlock but keep a reference on listener for now */
1145
1146 so = so2;
1147 tcp_lock(so, 1, 0);
1148 /*
1149 * This is ugly, but ....
1150 *
1151 * Mark socket as temporary until we're
1152 * committed to keeping it. The code at
1153 * ``drop'' and ``dropwithreset'' check the
1154 * flag dropsocket to see if the temporary
1155 * socket created here should be discarded.
1156 * We mark the socket as discardable until
1157 * we're committed to it below in TCPS_LISTEN.
1158 */
1159 dropsocket++;
1160
1161 /*
1162 * Inherit INP_BOUND_IF from listener; testing if
1163 * head_ifscope is non-zero is sufficient, since it
1164 * can only be set to a non-zero value earlier if
1165 * the listener has such a flag set.
1166 */
1167 #if INET6
1168 if (head_ifscope != IFSCOPE_NONE && !isipv6) {
1169 #else
1170 if (head_ifscope != IFSCOPE_NONE) {
1171 #endif /* INET6 */
1172 inp->inp_flags |= INP_BOUND_IF;
1173 inp->inp_boundif = head_ifscope;
1174 }
1175 #if INET6
1176 if (isipv6)
1177 inp->in6p_laddr = ip6->ip6_dst;
1178 else {
1179 inp->inp_vflag &= ~INP_IPV6;
1180 inp->inp_vflag |= INP_IPV4;
1181 #endif /* INET6 */
1182 inp->inp_laddr = ip->ip_dst;
1183 #if INET6
1184 }
1185 #endif /* INET6 */
1186 inp->inp_lport = th->th_dport;
1187 if (in_pcbinshash(inp, 0) != 0) {
1188 /*
1189 * Undo the assignments above if we failed to
1190 * put the PCB on the hash lists.
1191 */
1192 #if INET6
1193 if (isipv6)
1194 inp->in6p_laddr = in6addr_any;
1195 else
1196 #endif /* INET6 */
1197 inp->inp_laddr.s_addr = INADDR_ANY;
1198 inp->inp_lport = 0;
1199 tcp_lock(oso, 0, 0); /* release ref on parent */
1200 tcp_unlock(oso, 1, 0);
1201 goto drop;
1202 }
1203 #if IPSEC
1204 /*
1205 * To avoid creating incorrectly cached IPsec
1206 * association, this is need to be done here.
1207 *
1208 * Subject: (KAME-snap 748)
1209 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
1210 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
1211 */
1212 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1213 /*
1214 * Note: dropwithreset makes sure we don't
1215 * send a RST in response to a RST.
1216 */
1217 tcp_lock(oso, 0, 0); /* release ref on parent */
1218 tcp_unlock(oso, 1, 0);
1219 if (thflags & TH_ACK) {
1220 tcpstat.tcps_badsyn++;
1221 rstreason = BANDLIM_RST_OPENPORT;
1222 goto dropwithreset;
1223 }
1224 goto drop;
1225 }
1226 #endif
1227 #if INET6
1228 if (isipv6) {
1229 /*
1230 * Inherit socket options from the listening
1231 * socket.
1232 * Note that in6p_inputopts are not (even
1233 * should not be) copied, since it stores
1234 * previously received options and is used to
1235 * detect if each new option is different than
1236 * the previous one and hence should be passed
1237 * to a user.
1238 * If we copied in6p_inputopts, a user would
1239 * not be able to receive options just after
1240 * calling the accept system call.
1241 */
1242 inp->inp_flags |=
1243 oinp->inp_flags & INP_CONTROLOPTS;
1244 if (oinp->in6p_outputopts)
1245 inp->in6p_outputopts =
1246 ip6_copypktopts(oinp->in6p_outputopts,
1247 M_NOWAIT);
1248 } else
1249 #endif /* INET6 */
1250 inp->inp_options = ip_srcroute();
1251 tcp_lock(oso, 0, 0);
1252 #if IPSEC
1253 /* copy old policy into new socket's */
1254 if (sotoinpcb(oso)->inp_sp)
1255 {
1256 int error = 0;
1257 /* Is it a security hole here to silently fail to copy the policy? */
1258 if (inp->inp_sp != NULL)
1259 error = ipsec_init_policy(so, &inp->inp_sp);
1260 if (error != 0 || ipsec_copy_policy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
1261 printf("tcp_input: could not copy policy\n");
1262 }
1263 #endif
1264 /* inherit states from the listener */
1265 tp->t_state = TCPS_LISTEN;
1266 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT|TF_NODELAY);
1267 tp->t_keepinit = tp0->t_keepinit;
1268 tp->t_inpcb->inp_ip_ttl = tp0->t_inpcb->inp_ip_ttl;
1269
1270 /* now drop the reference on the listener */
1271 tcp_unlock(oso, 1, 0);
1272
1273 /* Compute proper scaling value from buffer space */
1274 if (inp->inp_pcbinfo->ipi_count < tcp_sockthreshold) {
1275 tp->request_r_scale = max(tcp_win_scale, tp->request_r_scale);
1276 so->so_rcv.sb_hiwat = imin(TCP_MAXWIN << tp->request_r_scale, (sb_max / (MSIZE+MCLBYTES)) * MCLBYTES);
1277 }
1278 else {
1279 while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
1280 TCP_MAXWIN << tp->request_r_scale <
1281 so->so_rcv.sb_hiwat)
1282 tp->request_r_scale++;
1283 }
1284
1285 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END,0,0,0,0,0);
1286 }
1287 }
1288
1289 #if 1
1290 lck_mtx_assert(((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
1291 #endif
1292 /*
1293 * Radar 3529618
1294 * This is the second part of the MSS DoS prevention code (after
1295 * minmss on the sending side) and it deals with too many too small
1296 * tcp packets in a too short timeframe (1 second).
1297 *
1298 * For every full second we count the number of received packets
1299 * and bytes. If we get a lot of packets per second for this connection
1300 * (tcp_minmssoverload) we take a closer look at it and compute the
1301 * average packet size for the past second. If that is less than
1302 * tcp_minmss we get too many packets with very small payload which
1303 * is not good and burdens our system (and every packet generates
1304 * a wakeup to the process connected to our socket). We can reasonable
1305 * expect this to be small packet DoS attack to exhaust our CPU
1306 * cycles.
1307 *
1308 * Care has to be taken for the minimum packet overload value. This
1309 * value defines the minimum number of packets per second before we
1310 * start to worry. This must not be too low to avoid killing for
1311 * example interactive connections with many small packets like
1312 * telnet or SSH.
1313 *
1314 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1315 * this check.
1316 *
1317 * Account for packet if payload packet, skip over ACK, etc.
1318 *
1319 * The packet per second count is done all the time and is also used
1320 * by "DELAY_ACK" to detect streaming situations.
1321 *
1322 */
1323 if (tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
1324 if (tp->rcv_reset > tcp_now) {
1325 tp->rcv_pps++;
1326 tp->rcv_byps += tlen + off;
1327 if (tp->rcv_byps > tp->rcv_maxbyps)
1328 tp->rcv_maxbyps = tp->rcv_byps;
1329 /*
1330 * Setting either tcp_minmssoverload or tcp_minmss to "0" disables
1331 * the check.
1332 */
1333 if (tcp_minmss && tcp_minmssoverload && tp->rcv_pps > tcp_minmssoverload) {
1334 if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
1335 char ipstrbuf[MAX_IPv6_STR_LEN];
1336 printf("too many small tcp packets from "
1337 "%s:%u, av. %ubyte/packet, "
1338 "dropping connection\n",
1339 #if INET6
1340 isipv6 ?
1341 inet_ntop(AF_INET6, &inp->in6p_faddr, ipstrbuf,
1342 sizeof(ipstrbuf)) :
1343 #endif
1344 inet_ntop(AF_INET, &inp->inp_faddr, ipstrbuf,
1345 sizeof(ipstrbuf)),
1346 inp->inp_fport,
1347 tp->rcv_byps / tp->rcv_pps);
1348 tp = tcp_drop(tp, ECONNRESET);
1349 /* tcpstat.tcps_minmssdrops++; */
1350 goto drop;
1351 }
1352 }
1353 } else {
1354 tp->rcv_reset = tcp_now + TCP_RETRANSHZ;
1355 tp->rcv_pps = 1;
1356 tp->rcv_byps = tlen + off;
1357 }
1358 }
1359
1360 #if TRAFFIC_MGT
1361 if (so->so_traffic_mgt_flags & TRAFFIC_MGT_SO_BACKGROUND) {
1362 tcpstat.tcps_bg_rcvtotal++;
1363
1364 /* Take snapshots of pkts recv;
1365 * tcpcb should have been initialized to 0 when allocated,
1366 * so if 0 then this is the first time we're doing this
1367 */
1368 if (!tp->tot_recv_snapshot) {
1369 tp->tot_recv_snapshot = tcpstat.tcps_rcvtotal;
1370 }
1371 if (!tp->bg_recv_snapshot) {
1372 tp->bg_recv_snapshot = tcpstat.tcps_bg_rcvtotal;
1373 }
1374 }
1375 #endif /* TRAFFIC_MGT */
1376
1377 /*
1378 Explicit Congestion Notification - Flag that we need to send ECT if
1379 + The IP Congestion experienced flag was set.
1380 + Socket is in established state
1381 + We negotiated ECN in the TCP setup
1382 + This isn't a pure ack (tlen > 0)
1383 + The data is in the valid window
1384
1385 TE_SENDECE will be cleared when we receive a packet with TH_CWR set.
1386 */
1387 if (ip_ecn == IPTOS_ECN_CE && tp->t_state == TCPS_ESTABLISHED &&
1388 (tp->ecn_flags & (TE_SETUPSENT | TE_SETUPRECEIVED)) ==
1389 (TE_SETUPSENT | TE_SETUPRECEIVED) && tlen > 0 &&
1390 SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1391 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1392 tp->ecn_flags |= TE_SENDECE;
1393 }
1394
1395 /*
1396 Clear TE_SENDECE if TH_CWR is set. This is harmless, so we don't
1397 bother doing extensive checks for state and whatnot.
1398 */
1399 if ((thflags & TH_CWR) == TH_CWR) {
1400 tp->ecn_flags &= ~TE_SENDECE;
1401 }
1402
1403 /*
1404 * Segment received on connection.
1405 * Reset idle time and keep-alive timer.
1406 */
1407 tp->t_rcvtime = 0;
1408 if (TCPS_HAVEESTABLISHED(tp->t_state))
1409 tp->t_timer[TCPT_KEEP] = TCP_KEEPIDLE(tp);
1410
1411 /*
1412 * Process options if not in LISTEN state,
1413 * else do it below (after getting remote address).
1414 */
1415 if (tp->t_state != TCPS_LISTEN && optp)
1416 tcp_dooptions(tp, optp, optlen, th, &to, ifscope);
1417
1418 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1419 if (to.to_flags & TOF_SCALE) {
1420 tp->t_flags |= TF_RCVD_SCALE;
1421 tp->requested_s_scale = to.to_requested_s_scale;
1422 tp->snd_wnd = th->th_win << tp->snd_scale;
1423 tiwin = tp->snd_wnd;
1424 }
1425 if (to.to_flags & TOF_TS) {
1426 tp->t_flags |= TF_RCVD_TSTMP;
1427 tp->ts_recent = to.to_tsval;
1428 tp->ts_recent_age = tcp_now;
1429 }
1430 if (to.to_flags & TOF_MSS)
1431 tcp_mss(tp, to.to_mss, ifscope);
1432 if (tp->sack_enable) {
1433 if (!(to.to_flags & TOF_SACK))
1434 tp->sack_enable = 0;
1435 else
1436 tp->t_flags |= TF_SACK_PERMIT;
1437 }
1438 }
1439
1440 /*
1441 * Header prediction: check for the two common cases
1442 * of a uni-directional data xfer. If the packet has
1443 * no control flags, is in-sequence, the window didn't
1444 * change and we're not retransmitting, it's a
1445 * candidate. If the length is zero and the ack moved
1446 * forward, we're the sender side of the xfer. Just
1447 * free the data acked & wake any higher level process
1448 * that was blocked waiting for space. If the length
1449 * is non-zero and the ack didn't move, we're the
1450 * receiver side. If we're getting packets in-order
1451 * (the reassembly queue is empty), add the data to
1452 * the socket buffer and note that we need a delayed ack.
1453 * Make sure that the hidden state-flags are also off.
1454 * Since we check for TCPS_ESTABLISHED above, it can only
1455 * be TH_NEEDSYN.
1456 */
1457 if (tp->t_state == TCPS_ESTABLISHED &&
1458 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK|TH_ECE)) == TH_ACK &&
1459 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1460 ((to.to_flags & TOF_TS) == 0 ||
1461 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1462 th->th_seq == tp->rcv_nxt &&
1463 tiwin && tiwin == tp->snd_wnd &&
1464 tp->snd_nxt == tp->snd_max) {
1465
1466 /*
1467 * If last ACK falls within this segment's sequence numbers,
1468 * record the timestamp.
1469 * NOTE that the test is modified according to the latest
1470 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1471 */
1472 if ((to.to_flags & TOF_TS) != 0 &&
1473 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1474 tp->ts_recent_age = tcp_now;
1475 tp->ts_recent = to.to_tsval;
1476 }
1477
1478 /* Force acknowledgment if we received a FIN */
1479
1480 if (thflags & TH_FIN)
1481 tp->t_flags |= TF_ACKNOW;
1482
1483 if (tlen == 0) {
1484 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1485 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1486 tp->snd_cwnd >= tp->snd_ssthresh &&
1487 ((!tcp_do_newreno && !tp->sack_enable &&
1488 tp->t_dupacks < tcprexmtthresh) ||
1489 ((tcp_do_newreno || tp->sack_enable) &&
1490 !IN_FASTRECOVERY(tp) && to.to_nsacks == 0 &&
1491 TAILQ_EMPTY(&tp->snd_holes)))) {
1492 /*
1493 * this is a pure ack for outstanding data.
1494 */
1495 ++tcpstat.tcps_predack;
1496 /*
1497 * "bad retransmit" recovery
1498 */
1499 if (tp->t_rxtshift == 1 &&
1500 tcp_now < tp->t_badrxtwin) {
1501 ++tcpstat.tcps_sndrexmitbad;
1502 tp->snd_cwnd = tp->snd_cwnd_prev;
1503 tp->snd_ssthresh =
1504 tp->snd_ssthresh_prev;
1505 tp->snd_recover = tp->snd_recover_prev;
1506 if (tp->t_flags & TF_WASFRECOVERY)
1507 ENTER_FASTRECOVERY(tp);
1508 tp->snd_nxt = tp->snd_max;
1509 tp->t_badrxtwin = 0;
1510 }
1511 /*
1512 * Recalculate the transmit timer / rtt.
1513 *
1514 * Some boxes send broken timestamp replies
1515 * during the SYN+ACK phase, ignore
1516 * timestamps of 0 or we could calculate a
1517 * huge RTT and blow up the retransmit timer.
1518 */
1519 if (((to.to_flags & TOF_TS) != 0) && (to.to_tsecr != 0)) { /* Makes sure we already have a TS */
1520 if (!tp->t_rttlow ||
1521 tp->t_rttlow > tcp_now - to.to_tsecr)
1522 tp->t_rttlow = tcp_now - to.to_tsecr;
1523 tcp_xmit_timer(tp,
1524 tcp_now - to.to_tsecr);
1525 } else if (tp->t_rtttime &&
1526 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1527 if (!tp->t_rttlow ||
1528 tp->t_rttlow > tcp_now - tp->t_rtttime)
1529 tp->t_rttlow = tcp_now - tp->t_rtttime;
1530 tcp_xmit_timer(tp, tp->t_rtttime);
1531 }
1532 acked = th->th_ack - tp->snd_una;
1533 tcpstat.tcps_rcvackpack++;
1534 tcpstat.tcps_rcvackbyte += acked;
1535 /*
1536 * Grow the congestion window, if the
1537 * connection is cwnd bound.
1538 */
1539 if (tp->snd_cwnd < tp->snd_wnd) {
1540 tp->t_bytes_acked += acked;
1541 if (tp->t_bytes_acked > tp->snd_cwnd) {
1542 tp->t_bytes_acked -= tp->snd_cwnd;
1543 tp->snd_cwnd += tp->t_maxseg;
1544 }
1545 }
1546 sbdrop(&so->so_snd, acked);
1547 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1548 SEQ_LEQ(th->th_ack, tp->snd_recover))
1549 tp->snd_recover = th->th_ack - 1;
1550 tp->snd_una = th->th_ack;
1551 /*
1552 * pull snd_wl2 up to prevent seq wrap relative
1553 * to th_ack.
1554 */
1555 tp->snd_wl2 = th->th_ack;
1556 tp->t_dupacks = 0;
1557 m_freem(m);
1558 ND6_HINT(tp); /* some progress has been done */
1559
1560 /*
1561 * If all outstanding data are acked, stop
1562 * retransmit timer, otherwise restart timer
1563 * using current (possibly backed-off) value.
1564 * If process is waiting for space,
1565 * wakeup/selwakeup/signal. If data
1566 * are ready to send, let tcp_output
1567 * decide between more output or persist.
1568 */
1569 if (tp->snd_una == tp->snd_max)
1570 tp->t_timer[TCPT_REXMT] = 0;
1571 else if (tp->t_timer[TCPT_PERSIST] == 0)
1572 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1573
1574 sowwakeup(so); /* has to be done with socket lock held */
1575 if ((so->so_snd.sb_cc) || (tp->t_flags & TF_ACKNOW)) {
1576 tp->t_unacksegs = 0;
1577 (void) tcp_output(tp);
1578 }
1579 tcp_unlock(so, 1, 0);
1580 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
1581 return;
1582 }
1583 } else if (th->th_ack == tp->snd_una &&
1584 LIST_EMPTY(&tp->t_segq) &&
1585 tlen <= tcp_sbspace(tp)) {
1586 /*
1587 * this is a pure, in-sequence data packet
1588 * with nothing on the reassembly queue and
1589 * we have enough buffer space to take it.
1590 */
1591 /* Clean receiver SACK report if present */
1592 if (tp->sack_enable && tp->rcv_numsacks)
1593 tcp_clean_sackreport(tp);
1594 ++tcpstat.tcps_preddat;
1595 tp->rcv_nxt += tlen;
1596 /*
1597 * Pull snd_wl1 up to prevent seq wrap relative to
1598 * th_seq.
1599 */
1600 tp->snd_wl1 = th->th_seq;
1601 /*
1602 * Pull rcv_up up to prevent seq wrap relative to
1603 * rcv_nxt.
1604 */
1605 tp->rcv_up = tp->rcv_nxt;
1606 tcpstat.tcps_rcvpack++;
1607 tcpstat.tcps_rcvbyte += tlen;
1608 ND6_HINT(tp); /* some progress has been done */
1609 /*
1610 * Add data to socket buffer.
1611 */
1612 m_adj(m, drop_hdrlen); /* delayed header drop */
1613 if (sbappendstream(&so->so_rcv, m))
1614 sorwakeup(so);
1615 #if INET6
1616 if (isipv6) {
1617 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
1618 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
1619 th->th_seq, th->th_ack, th->th_win);
1620 }
1621 else
1622 #endif
1623 {
1624 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
1625 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
1626 th->th_seq, th->th_ack, th->th_win);
1627 }
1628 if (DELAY_ACK(tp)) {
1629 tp->t_flags |= TF_DELACK;
1630 tp->t_unacksegs++;
1631 } else {
1632 tp->t_unacksegs = 0;
1633 tp->t_flags |= TF_ACKNOW;
1634 tcp_output(tp);
1635 }
1636 tcp_unlock(so, 1, 0);
1637 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
1638 return;
1639 }
1640 }
1641
1642 /*
1643 * Calculate amount of space in receive window,
1644 * and then do TCP input processing.
1645 * Receive window is amount of space in rcv queue,
1646 * but not less than advertised window.
1647 */
1648 #if 1
1649 lck_mtx_assert(((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
1650 #endif
1651 { int win;
1652
1653 win = tcp_sbspace(tp);
1654
1655 if (win < 0)
1656 win = 0;
1657 else { /* clip rcv window to 4K for modems */
1658 if (tp->t_flags & TF_SLOWLINK && slowlink_wsize > 0)
1659 win = min(win, slowlink_wsize);
1660 }
1661 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1662 }
1663
1664 switch (tp->t_state) {
1665
1666 /*
1667 * If the state is LISTEN then ignore segment if it contains an RST.
1668 * If the segment contains an ACK then it is bad and send a RST.
1669 * If it does not contain a SYN then it is not interesting; drop it.
1670 * If it is from this socket, drop it, it must be forged.
1671 * Don't bother responding if the destination was a broadcast.
1672 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1673 * tp->iss, and send a segment:
1674 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1675 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1676 * Fill in remote peer address fields if not previously specified.
1677 * Enter SYN_RECEIVED state, and process any other fields of this
1678 * segment in this state.
1679 */
1680 case TCPS_LISTEN: {
1681 register struct sockaddr_in *sin;
1682 #if INET6
1683 register struct sockaddr_in6 *sin6;
1684 #endif
1685
1686 #if 1
1687 lck_mtx_assert(((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
1688 #endif
1689 if (thflags & TH_RST)
1690 goto drop;
1691 if (thflags & TH_ACK) {
1692 rstreason = BANDLIM_RST_OPENPORT;
1693 goto dropwithreset;
1694 }
1695 if ((thflags & TH_SYN) == 0)
1696 goto drop;
1697 if (th->th_dport == th->th_sport) {
1698 #if INET6
1699 if (isipv6) {
1700 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1701 &ip6->ip6_src))
1702 goto drop;
1703 } else
1704 #endif /* INET6 */
1705 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1706 goto drop;
1707 }
1708 /*
1709 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1710 * in_broadcast() should never return true on a received
1711 * packet with M_BCAST not set.
1712 *
1713 * Packets with a multicast source address should also
1714 * be discarded.
1715 */
1716 if (m->m_flags & (M_BCAST|M_MCAST))
1717 goto drop;
1718 #if INET6
1719 if (isipv6) {
1720 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1721 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1722 goto drop;
1723 } else
1724 #endif
1725 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1726 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1727 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1728 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1729 goto drop;
1730 #if INET6
1731 if (isipv6) {
1732 MALLOC(sin6, struct sockaddr_in6 *, sizeof *sin6,
1733 M_SONAME, M_NOWAIT);
1734 if (sin6 == NULL)
1735 goto drop;
1736 bzero(sin6, sizeof(*sin6));
1737 sin6->sin6_family = AF_INET6;
1738 sin6->sin6_len = sizeof(*sin6);
1739 sin6->sin6_addr = ip6->ip6_src;
1740 sin6->sin6_port = th->th_sport;
1741 laddr6 = inp->in6p_laddr;
1742 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1743 inp->in6p_laddr = ip6->ip6_dst;
1744 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
1745 proc0)) {
1746 inp->in6p_laddr = laddr6;
1747 FREE(sin6, M_SONAME);
1748 goto drop;
1749 }
1750 FREE(sin6, M_SONAME);
1751 } else
1752 #endif
1753 {
1754 #if 0
1755 lck_mtx_assert(((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
1756 #endif
1757 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
1758 M_NOWAIT);
1759 if (sin == NULL)
1760 goto drop;
1761 sin->sin_family = AF_INET;
1762 sin->sin_len = sizeof(*sin);
1763 sin->sin_addr = ip->ip_src;
1764 sin->sin_port = th->th_sport;
1765 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
1766 laddr = inp->inp_laddr;
1767 if (inp->inp_laddr.s_addr == INADDR_ANY)
1768 inp->inp_laddr = ip->ip_dst;
1769 if (in_pcbconnect(inp, (struct sockaddr *)sin, proc0)) {
1770 inp->inp_laddr = laddr;
1771 FREE(sin, M_SONAME);
1772 goto drop;
1773 }
1774 FREE(sin, M_SONAME);
1775 }
1776
1777 tcp_dooptions(tp, optp, optlen, th, &to, ifscope);
1778
1779 if (tp->sack_enable) {
1780 if (!(to.to_flags & TOF_SACK))
1781 tp->sack_enable = 0;
1782 else
1783 tp->t_flags |= TF_SACK_PERMIT;
1784 }
1785
1786 if (iss)
1787 tp->iss = iss;
1788 else {
1789 tp->iss = tcp_new_isn(tp);
1790 }
1791 tp->irs = th->th_seq;
1792 tcp_sendseqinit(tp);
1793 tcp_rcvseqinit(tp);
1794 tp->snd_recover = tp->snd_una;
1795 /*
1796 * Initialization of the tcpcb for transaction;
1797 * set SND.WND = SEG.WND,
1798 * initialize CCsend and CCrecv.
1799 */
1800 tp->snd_wnd = tiwin; /* initial send-window */
1801 tp->t_flags |= TF_ACKNOW;
1802 tp->t_unacksegs = 0;
1803 tp->t_state = TCPS_SYN_RECEIVED;
1804 tp->t_timer[TCPT_KEEP] = tp->t_keepinit ? tp->t_keepinit : tcp_keepinit;
1805 dropsocket = 0; /* committed to socket */
1806 tcpstat.tcps_accepts++;
1807 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE | TH_CWR)) {
1808 /* ECN-setup SYN */
1809 tp->ecn_flags |= (TE_SETUPRECEIVED | TE_SENDIPECT);
1810 }
1811 #if CONFIG_IFEF_NOWINDOWSCALE
1812 if (tcp_obey_ifef_nowindowscale && m->m_pkthdr.rcvif != NULL &&
1813 (m->m_pkthdr.rcvif->if_eflags & IFEF_NOWINDOWSCALE)) {
1814 /* Window scaling is not enabled on this interface */
1815 tp->t_flags &= ~TF_REQ_SCALE;
1816 }
1817 #endif
1818 goto trimthenstep6;
1819 }
1820
1821 /*
1822 * If the state is SYN_RECEIVED:
1823 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1824 */
1825 case TCPS_SYN_RECEIVED:
1826 if ((thflags & TH_ACK) &&
1827 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1828 SEQ_GT(th->th_ack, tp->snd_max))) {
1829 rstreason = BANDLIM_RST_OPENPORT;
1830 goto dropwithreset;
1831 }
1832 break;
1833
1834 /*
1835 * If the state is SYN_SENT:
1836 * if seg contains an ACK, but not for our SYN, drop the input.
1837 * if seg contains a RST, then drop the connection.
1838 * if seg does not contain SYN, then drop it.
1839 * Otherwise this is an acceptable SYN segment
1840 * initialize tp->rcv_nxt and tp->irs
1841 * if seg contains ack then advance tp->snd_una
1842 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1843 * arrange for segment to be acked (eventually)
1844 * continue processing rest of data/controls, beginning with URG
1845 */
1846 case TCPS_SYN_SENT:
1847 if ((thflags & TH_ACK) &&
1848 (SEQ_LEQ(th->th_ack, tp->iss) ||
1849 SEQ_GT(th->th_ack, tp->snd_max))) {
1850 rstreason = BANDLIM_UNLIMITED;
1851 goto dropwithreset;
1852 }
1853 if (thflags & TH_RST) {
1854 if ((thflags & TH_ACK) != 0) {
1855 tp = tcp_drop(tp, ECONNREFUSED);
1856 postevent(so, 0, EV_RESET);
1857 }
1858 goto drop;
1859 }
1860 if ((thflags & TH_SYN) == 0)
1861 goto drop;
1862 tp->snd_wnd = th->th_win; /* initial send window */
1863
1864 tp->irs = th->th_seq;
1865 tcp_rcvseqinit(tp);
1866 if (thflags & TH_ACK) {
1867 tcpstat.tcps_connects++;
1868
1869 if ((thflags & (TH_ECE | TH_CWR)) == (TH_ECE)) {
1870 /* ECN-setup SYN-ACK */
1871 tp->ecn_flags |= TE_SETUPRECEIVED;
1872 }
1873 else {
1874 /* non-ECN-setup SYN-ACK */
1875 tp->ecn_flags &= ~TE_SENDIPECT;
1876 }
1877
1878 #if CONFIG_MACF_NET && CONFIG_MACF_SOCKET
1879 /* XXXMAC: recursive lock: SOCK_LOCK(so); */
1880 mac_socketpeer_label_associate_mbuf(m, so);
1881 /* XXXMAC: SOCK_UNLOCK(so); */
1882 #endif
1883 /* Do window scaling on this connection? */
1884 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1885 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1886 tp->snd_scale = tp->requested_s_scale;
1887 tp->rcv_scale = tp->request_r_scale;
1888 }
1889 tp->rcv_adv += tp->rcv_wnd;
1890 tp->snd_una++; /* SYN is acked */
1891 /*
1892 * If there's data, delay ACK; if there's also a FIN
1893 * ACKNOW will be turned on later.
1894 */
1895 if (DELAY_ACK(tp) && tlen != 0) {
1896 tp->t_flags |= TF_DELACK;
1897 tp->t_unacksegs++;
1898 }
1899 else {
1900 tp->t_flags |= TF_ACKNOW;
1901 tp->t_unacksegs = 0;
1902 }
1903 /*
1904 * Received <SYN,ACK> in SYN_SENT[*] state.
1905 * Transitions:
1906 * SYN_SENT --> ESTABLISHED
1907 * SYN_SENT* --> FIN_WAIT_1
1908 */
1909 tp->t_starttime = 0;
1910 if (tp->t_flags & TF_NEEDFIN) {
1911 tp->t_state = TCPS_FIN_WAIT_1;
1912 tp->t_flags &= ~TF_NEEDFIN;
1913 thflags &= ~TH_SYN;
1914 } else {
1915 tp->t_state = TCPS_ESTABLISHED;
1916 tp->t_timer[TCPT_KEEP] = TCP_KEEPIDLE(tp);
1917 }
1918 /* soisconnected may lead to socket_unlock in case of upcalls,
1919 * make sure this is done when everything is setup.
1920 */
1921 soisconnected(so);
1922 } else {
1923 /*
1924 * Received initial SYN in SYN-SENT[*] state => simul-
1925 * taneous open. If segment contains CC option and there is
1926 * a cached CC, apply TAO test; if it succeeds, connection is
1927 * half-synchronized. Otherwise, do 3-way handshake:
1928 * SYN-SENT -> SYN-RECEIVED
1929 * SYN-SENT* -> SYN-RECEIVED*
1930 */
1931 tp->t_flags |= TF_ACKNOW;
1932 tp->t_timer[TCPT_REXMT] = 0;
1933 tp->t_state = TCPS_SYN_RECEIVED;
1934
1935 }
1936
1937 trimthenstep6:
1938 /*
1939 * Advance th->th_seq to correspond to first data byte.
1940 * If data, trim to stay within window,
1941 * dropping FIN if necessary.
1942 */
1943 th->th_seq++;
1944 if (tlen > tp->rcv_wnd) {
1945 todrop = tlen - tp->rcv_wnd;
1946 m_adj(m, -todrop);
1947 tlen = tp->rcv_wnd;
1948 thflags &= ~TH_FIN;
1949 tcpstat.tcps_rcvpackafterwin++;
1950 tcpstat.tcps_rcvbyteafterwin += todrop;
1951 }
1952 tp->snd_wl1 = th->th_seq - 1;
1953 tp->rcv_up = th->th_seq;
1954 /*
1955 * Client side of transaction: already sent SYN and data.
1956 * If the remote host used T/TCP to validate the SYN,
1957 * our data will be ACK'd; if so, enter normal data segment
1958 * processing in the middle of step 5, ack processing.
1959 * Otherwise, goto step 6.
1960 */
1961 if (thflags & TH_ACK)
1962 goto process_ACK;
1963 goto step6;
1964 /*
1965 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1966 * do normal processing.
1967 *
1968 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1969 */
1970 case TCPS_LAST_ACK:
1971 case TCPS_CLOSING:
1972 case TCPS_TIME_WAIT:
1973 break; /* continue normal processing */
1974
1975 /* Received a SYN while connection is already established.
1976 * This is a "half open connection and other anomalies" described
1977 * in RFC793 page 34, send an ACK so the remote reset the connection
1978 * or recovers by adjusting its sequence numberering
1979 */
1980 case TCPS_ESTABLISHED:
1981 if (thflags & TH_SYN)
1982 goto dropafterack;
1983 break;
1984 }
1985
1986 /*
1987 * States other than LISTEN or SYN_SENT.
1988 * First check the RST flag and sequence number since reset segments
1989 * are exempt from the timestamp and connection count tests. This
1990 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1991 * below which allowed reset segments in half the sequence space
1992 * to fall though and be processed (which gives forged reset
1993 * segments with a random sequence number a 50 percent chance of
1994 * killing a connection).
1995 * Then check timestamp, if present.
1996 * Then check the connection count, if present.
1997 * Then check that at least some bytes of segment are within
1998 * receive window. If segment begins before rcv_nxt,
1999 * drop leading data (and SYN); if nothing left, just ack.
2000 *
2001 *
2002 * If the RST bit is set, check the sequence number to see
2003 * if this is a valid reset segment.
2004 * RFC 793 page 37:
2005 * In all states except SYN-SENT, all reset (RST) segments
2006 * are validated by checking their SEQ-fields. A reset is
2007 * valid if its sequence number is in the window.
2008 * Note: this does not take into account delayed ACKs, so
2009 * we should test against last_ack_sent instead of rcv_nxt.
2010 * The sequence number in the reset segment is normally an
2011 * echo of our outgoing acknowlegement numbers, but some hosts
2012 * send a reset with the sequence number at the rightmost edge
2013 * of our receive window, and we have to handle this case.
2014 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
2015 * that brute force RST attacks are possible. To combat this,
2016 * we use a much stricter check while in the ESTABLISHED state,
2017 * only accepting RSTs where the sequence number is equal to
2018 * last_ack_sent. In all other states (the states in which a
2019 * RST is more likely), the more permissive check is used.
2020 * If we have multiple segments in flight, the intial reset
2021 * segment sequence numbers will be to the left of last_ack_sent,
2022 * but they will eventually catch up.
2023 * In any case, it never made sense to trim reset segments to
2024 * fit the receive window since RFC 1122 says:
2025 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
2026 *
2027 * A TCP SHOULD allow a received RST segment to include data.
2028 *
2029 * DISCUSSION
2030 * It has been suggested that a RST segment could contain
2031 * ASCII text that encoded and explained the cause of the
2032 * RST. No standard has yet been established for such
2033 * data.
2034 *
2035 * If the reset segment passes the sequence number test examine
2036 * the state:
2037 * SYN_RECEIVED STATE:
2038 * If passive open, return to LISTEN state.
2039 * If active open, inform user that connection was refused.
2040 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
2041 * Inform user that connection was reset, and close tcb.
2042 * CLOSING, LAST_ACK STATES:
2043 * Close the tcb.
2044 * TIME_WAIT STATE:
2045 * Drop the segment - see Stevens, vol. 2, p. 964 and
2046 * RFC 1337.
2047 *
2048 * Radar 4803931: Allows for the case where we ACKed the FIN but
2049 * there is already a RST in flight from the peer.
2050 * In that case, accept the RST for non-established
2051 * state if it's one off from last_ack_sent.
2052
2053 */
2054 if (thflags & TH_RST) {
2055 if ((SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
2056 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) ||
2057 (tp->rcv_wnd == 0 &&
2058 ((tp->last_ack_sent == th->th_seq) || ((tp->last_ack_sent -1) == th->th_seq)))) {
2059 switch (tp->t_state) {
2060
2061 case TCPS_SYN_RECEIVED:
2062 so->so_error = ECONNREFUSED;
2063 goto close;
2064
2065 case TCPS_ESTABLISHED:
2066 if (tp->last_ack_sent != th->th_seq) {
2067 tcpstat.tcps_badrst++;
2068 goto drop;
2069 }
2070 case TCPS_FIN_WAIT_1:
2071 case TCPS_CLOSE_WAIT:
2072 /*
2073 Drop through ...
2074 */
2075 case TCPS_FIN_WAIT_2:
2076 so->so_error = ECONNRESET;
2077 close:
2078 postevent(so, 0, EV_RESET);
2079 tp->t_state = TCPS_CLOSED;
2080 tcpstat.tcps_drops++;
2081 tp = tcp_close(tp);
2082 break;
2083
2084 case TCPS_CLOSING:
2085 case TCPS_LAST_ACK:
2086 tp = tcp_close(tp);
2087 break;
2088
2089 case TCPS_TIME_WAIT:
2090 break;
2091 }
2092 }
2093 goto drop;
2094 }
2095
2096 #if 0
2097 lck_mtx_assert(((struct inpcb *)so->so_pcb)->inpcb_mtx, LCK_MTX_ASSERT_OWNED);
2098 #endif
2099
2100 /*
2101 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2102 * and it's less than ts_recent, drop it.
2103 */
2104 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
2105 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
2106
2107 /* Check to see if ts_recent is over 24 days old. */
2108 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
2109 /*
2110 * Invalidate ts_recent. If this segment updates
2111 * ts_recent, the age will be reset later and ts_recent
2112 * will get a valid value. If it does not, setting
2113 * ts_recent to zero will at least satisfy the
2114 * requirement that zero be placed in the timestamp
2115 * echo reply when ts_recent isn't valid. The
2116 * age isn't reset until we get a valid ts_recent
2117 * because we don't want out-of-order segments to be
2118 * dropped when ts_recent is old.
2119 */
2120 tp->ts_recent = 0;
2121 } else {
2122 tcpstat.tcps_rcvduppack++;
2123 tcpstat.tcps_rcvdupbyte += tlen;
2124 tcpstat.tcps_pawsdrop++;
2125 if (tlen)
2126 goto dropafterack;
2127 goto drop;
2128 }
2129 }
2130
2131 /*
2132 * In the SYN-RECEIVED state, validate that the packet belongs to
2133 * this connection before trimming the data to fit the receive
2134 * window. Check the sequence number versus IRS since we know
2135 * the sequence numbers haven't wrapped. This is a partial fix
2136 * for the "LAND" DoS attack.
2137 */
2138 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
2139 rstreason = BANDLIM_RST_OPENPORT;
2140 goto dropwithreset;
2141 }
2142
2143 todrop = tp->rcv_nxt - th->th_seq;
2144 if (todrop > 0) {
2145 if (thflags & TH_SYN) {
2146 thflags &= ~TH_SYN;
2147 th->th_seq++;
2148 if (th->th_urp > 1)
2149 th->th_urp--;
2150 else
2151 thflags &= ~TH_URG;
2152 todrop--;
2153 }
2154 /*
2155 * Following if statement from Stevens, vol. 2, p. 960.
2156 */
2157 if (todrop > tlen
2158 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
2159 /*
2160 * Any valid FIN must be to the left of the window.
2161 * At this point the FIN must be a duplicate or out
2162 * of sequence; drop it.
2163 */
2164 thflags &= ~TH_FIN;
2165
2166 /*
2167 * Send an ACK to resynchronize and drop any data.
2168 * But keep on processing for RST or ACK.
2169 */
2170 tp->t_flags |= TF_ACKNOW;
2171 tp->t_unacksegs = 0;
2172 todrop = tlen;
2173 tcpstat.tcps_rcvduppack++;
2174 tcpstat.tcps_rcvdupbyte += todrop;
2175 } else {
2176 tcpstat.tcps_rcvpartduppack++;
2177 tcpstat.tcps_rcvpartdupbyte += todrop;
2178 }
2179 drop_hdrlen += todrop; /* drop from the top afterwards */
2180 th->th_seq += todrop;
2181 tlen -= todrop;
2182 if (th->th_urp > todrop)
2183 th->th_urp -= todrop;
2184 else {
2185 thflags &= ~TH_URG;
2186 th->th_urp = 0;
2187 }
2188 }
2189
2190 /*
2191 * If new data are received on a connection after the
2192 * user processes are gone, then RST the other end.
2193 */
2194 if ((so->so_state & SS_NOFDREF) &&
2195 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2196 tp = tcp_close(tp);
2197 tcpstat.tcps_rcvafterclose++;
2198 rstreason = BANDLIM_UNLIMITED;
2199 goto dropwithreset;
2200 }
2201
2202 /*
2203 * If segment ends after window, drop trailing data
2204 * (and PUSH and FIN); if nothing left, just ACK.
2205 */
2206 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
2207 if (todrop > 0) {
2208 tcpstat.tcps_rcvpackafterwin++;
2209 if (todrop >= tlen) {
2210 tcpstat.tcps_rcvbyteafterwin += tlen;
2211 /*
2212 * If a new connection request is received
2213 * while in TIME_WAIT, drop the old connection
2214 * and start over if the sequence numbers
2215 * are above the previous ones.
2216 */
2217 if (thflags & TH_SYN &&
2218 tp->t_state == TCPS_TIME_WAIT &&
2219 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2220 iss = tcp_new_isn(tp);
2221 tp = tcp_close(tp);
2222 tcp_unlock(so, 1, 0);
2223 goto findpcb;
2224 }
2225 /*
2226 * If window is closed can only take segments at
2227 * window edge, and have to drop data and PUSH from
2228 * incoming segments. Continue processing, but
2229 * remember to ack. Otherwise, drop segment
2230 * and ack.
2231 */
2232 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2233 tp->t_flags |= TF_ACKNOW;
2234 tp->t_unacksegs = 0;
2235 tcpstat.tcps_rcvwinprobe++;
2236 } else
2237 goto dropafterack;
2238 } else
2239 tcpstat.tcps_rcvbyteafterwin += todrop;
2240 m_adj(m, -todrop);
2241 tlen -= todrop;
2242 thflags &= ~(TH_PUSH|TH_FIN);
2243 }
2244
2245 /*
2246 * If last ACK falls within this segment's sequence numbers,
2247 * record its timestamp.
2248 * NOTE:
2249 * 1) That the test incorporates suggestions from the latest
2250 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
2251 * 2) That updating only on newer timestamps interferes with
2252 * our earlier PAWS tests, so this check should be solely
2253 * predicated on the sequence space of this segment.
2254 * 3) That we modify the segment boundary check to be
2255 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2256 * instead of RFC1323's
2257 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2258 * This modified check allows us to overcome RFC1323's
2259 * limitations as described in Stevens TCP/IP Illustrated
2260 * Vol. 2 p.869. In such cases, we can still calculate the
2261 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2262 */
2263 if ((to.to_flags & TOF_TS) != 0 &&
2264 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2265 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2266 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
2267 tp->ts_recent_age = tcp_now;
2268 tp->ts_recent = to.to_tsval;
2269 }
2270
2271 /*
2272 * If a SYN is in the window, then this is an
2273 * error and we send an RST and drop the connection.
2274 */
2275 if (thflags & TH_SYN) {
2276 tp = tcp_drop(tp, ECONNRESET);
2277 rstreason = BANDLIM_UNLIMITED;
2278 postevent(so, 0, EV_RESET);
2279 goto dropwithreset;
2280 }
2281
2282 /*
2283 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
2284 * flag is on (half-synchronized state), then queue data for
2285 * later processing; else drop segment and return.
2286 */
2287 if ((thflags & TH_ACK) == 0) {
2288 if (tp->t_state == TCPS_SYN_RECEIVED ||
2289 (tp->t_flags & TF_NEEDSYN))
2290 goto step6;
2291 else if (tp->t_flags & TF_ACKNOW)
2292 goto dropafterack;
2293 else
2294 goto drop;
2295 }
2296
2297 /*
2298 * Ack processing.
2299 */
2300 switch (tp->t_state) {
2301
2302 /*
2303 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
2304 * ESTABLISHED state and continue processing.
2305 * The ACK was checked above.
2306 */
2307 case TCPS_SYN_RECEIVED:
2308
2309 tcpstat.tcps_connects++;
2310
2311 /* Do window scaling? */
2312 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2313 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2314 tp->snd_scale = tp->requested_s_scale;
2315 tp->rcv_scale = tp->request_r_scale;
2316 }
2317 /*
2318 * Make transitions:
2319 * SYN-RECEIVED -> ESTABLISHED
2320 * SYN-RECEIVED* -> FIN-WAIT-1
2321 */
2322 tp->t_starttime = 0;
2323 if (tp->t_flags & TF_NEEDFIN) {
2324 tp->t_state = TCPS_FIN_WAIT_1;
2325 tp->t_flags &= ~TF_NEEDFIN;
2326 } else {
2327 tp->t_state = TCPS_ESTABLISHED;
2328 tp->t_timer[TCPT_KEEP] = TCP_KEEPIDLE(tp);
2329 }
2330 /*
2331 * If segment contains data or ACK, will call tcp_reass()
2332 * later; if not, do so now to pass queued data to user.
2333 */
2334 if (tlen == 0 && (thflags & TH_FIN) == 0)
2335 (void) tcp_reass(tp, (struct tcphdr *)0, &tlen,
2336 (struct mbuf *)0);
2337 tp->snd_wl1 = th->th_seq - 1;
2338
2339 /* FALLTHROUGH */
2340
2341 /* soisconnected may lead to socket_unlock in case of upcalls,
2342 * make sure this is done when everything is setup.
2343 */
2344 soisconnected(so);
2345
2346 /*
2347 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2348 * ACKs. If the ack is in the range
2349 * tp->snd_una < th->th_ack <= tp->snd_max
2350 * then advance tp->snd_una to th->th_ack and drop
2351 * data from the retransmission queue. If this ACK reflects
2352 * more up to date window information we update our window information.
2353 */
2354 case TCPS_ESTABLISHED:
2355 case TCPS_FIN_WAIT_1:
2356 case TCPS_FIN_WAIT_2:
2357 case TCPS_CLOSE_WAIT:
2358 case TCPS_CLOSING:
2359 case TCPS_LAST_ACK:
2360 case TCPS_TIME_WAIT:
2361 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2362 tcpstat.tcps_rcvacktoomuch++;
2363 goto dropafterack;
2364 }
2365 if (tp->sack_enable &&
2366 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes)))
2367 tcp_sack_doack(tp, &to, th->th_ack);
2368 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2369 if (tlen == 0 && tiwin == tp->snd_wnd) {
2370 tcpstat.tcps_rcvdupack++;
2371 /*
2372 * If we have outstanding data (other than
2373 * a window probe), this is a completely
2374 * duplicate ack (ie, window info didn't
2375 * change), the ack is the biggest we've
2376 * seen and we've seen exactly our rexmt
2377 * threshhold of them, assume a packet
2378 * has been dropped and retransmit it.
2379 * Kludge snd_nxt & the congestion
2380 * window so we send only this one
2381 * packet.
2382 *
2383 * We know we're losing at the current
2384 * window size so do congestion avoidance
2385 * (set ssthresh to half the current window
2386 * and pull our congestion window back to
2387 * the new ssthresh).
2388 *
2389 * Dup acks mean that packets have left the
2390 * network (they're now cached at the receiver)
2391 * so bump cwnd by the amount in the receiver
2392 * to keep a constant cwnd packets in the
2393 * network.
2394 */
2395 if (tp->t_timer[TCPT_REXMT] == 0 ||
2396 th->th_ack != tp->snd_una)
2397 tp->t_dupacks = 0;
2398 else if (++tp->t_dupacks > tcprexmtthresh ||
2399 ((tcp_do_newreno || tp->sack_enable) &&
2400 IN_FASTRECOVERY(tp))) {
2401 if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
2402 int awnd;
2403
2404 /*
2405 * Compute the amount of data in flight first.
2406 * We can inject new data into the pipe iff
2407 * we have less than 1/2 the original window's
2408 * worth of data in flight.
2409 */
2410 awnd = (tp->snd_nxt - tp->snd_fack) +
2411 tp->sackhint.sack_bytes_rexmit;
2412 if (awnd < tp->snd_ssthresh) {
2413 tp->snd_cwnd += tp->t_maxseg;
2414 if (tp->snd_cwnd > tp->snd_ssthresh)
2415 tp->snd_cwnd = tp->snd_ssthresh;
2416 }
2417 } else
2418 tp->snd_cwnd += tp->t_maxseg;
2419 tp->t_unacksegs = 0;
2420 (void) tcp_output(tp);
2421 goto drop;
2422 } else if (tp->t_dupacks == tcprexmtthresh) {
2423 tcp_seq onxt = tp->snd_nxt;
2424 u_int win;
2425
2426 /*
2427 * If we're doing sack, check to
2428 * see if we're already in sack
2429 * recovery. If we're not doing sack,
2430 * check to see if we're in newreno
2431 * recovery.
2432 */
2433 if (tp->sack_enable) {
2434 if (IN_FASTRECOVERY(tp)) {
2435 tp->t_dupacks = 0;
2436 break;
2437 }
2438 } else if (tcp_do_newreno) {
2439 if (SEQ_LEQ(th->th_ack,
2440 tp->snd_recover)) {
2441 tp->t_dupacks = 0;
2442 break;
2443 }
2444 }
2445 win = min(tp->snd_wnd, tp->snd_cwnd) /
2446 2 / tp->t_maxseg;
2447 if (win < 2)
2448 win = 2;
2449 tp->snd_ssthresh = win * tp->t_maxseg;
2450 ENTER_FASTRECOVERY(tp);
2451 tp->snd_recover = tp->snd_max;
2452 tp->t_timer[TCPT_REXMT] = 0;
2453 tp->t_rtttime = 0;
2454 tp->ecn_flags |= TE_SENDCWR;
2455 if (tp->sack_enable) {
2456 tcpstat.tcps_sack_recovery_episode++;
2457 tp->sack_newdata = tp->snd_nxt;
2458 tp->snd_cwnd = tp->t_maxseg;
2459 tp->t_unacksegs = 0;
2460 (void) tcp_output(tp);
2461 goto drop;
2462 }
2463 tp->snd_nxt = th->th_ack;
2464 tp->snd_cwnd = tp->t_maxseg;
2465 tp->t_unacksegs = 0;
2466 (void) tcp_output(tp);
2467 tp->snd_cwnd = tp->snd_ssthresh +
2468 tp->t_maxseg * tp->t_dupacks;
2469 if (SEQ_GT(onxt, tp->snd_nxt))
2470 tp->snd_nxt = onxt;
2471 goto drop;
2472 }
2473 } else
2474 tp->t_dupacks = 0;
2475 break;
2476 }
2477 /*
2478 * If the congestion window was inflated to account
2479 * for the other side's cached packets, retract it.
2480 */
2481 if (!IN_FASTRECOVERY(tp)) {
2482 /*
2483 * We were not in fast recovery. Reset the duplicate ack
2484 * counter.
2485 */
2486 tp->t_dupacks = 0;
2487 }
2488 /*
2489 * If the congestion window was inflated to account
2490 * for the other side's cached packets, retract it.
2491 */
2492 else {
2493 if (tcp_do_newreno || tp->sack_enable) {
2494 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2495 if (tp->sack_enable)
2496 tcp_sack_partialack(tp, th);
2497 else
2498 tcp_newreno_partial_ack(tp, th);
2499 }
2500 else {
2501 if (tcp_do_newreno) {
2502 int32_t ss = tp->snd_max - th->th_ack;
2503
2504 /*
2505 * Complete ack. Inflate the congestion window to
2506 * ssthresh and exit fast recovery.
2507 *
2508 * Window inflation should have left us with approx.
2509 * snd_ssthresh outstanding data. But in case we
2510 * would be inclined to send a burst, better to do
2511 * it via the slow start mechanism.
2512 */
2513 if (ss < tp->snd_ssthresh)
2514 tp->snd_cwnd = ss + tp->t_maxseg;
2515 else
2516 tp->snd_cwnd = tp->snd_ssthresh;
2517 }
2518 else {
2519 /*
2520 * Clamp the congestion window to the crossover point
2521 * and exit fast recovery.
2522 */
2523 if (tp->snd_cwnd > tp->snd_ssthresh)
2524 tp->snd_cwnd = tp->snd_ssthresh;
2525 }
2526
2527 EXIT_FASTRECOVERY(tp);
2528 tp->t_dupacks = 0;
2529 tp->t_bytes_acked = 0;
2530 }
2531 }
2532 else {
2533 /*
2534 * Clamp the congestion window to the crossover point
2535 * and exit fast recovery in non-newreno and non-SACK case.
2536 */
2537 if (tp->snd_cwnd > tp->snd_ssthresh)
2538 tp->snd_cwnd = tp->snd_ssthresh;
2539 EXIT_FASTRECOVERY(tp);
2540 tp->t_dupacks = 0;
2541 tp->t_bytes_acked = 0;
2542 }
2543 }
2544
2545
2546 /*
2547 * If we reach this point, ACK is not a duplicate,
2548 * i.e., it ACKs something we sent.
2549 */
2550 if (tp->t_flags & TF_NEEDSYN) {
2551 /*
2552 * T/TCP: Connection was half-synchronized, and our
2553 * SYN has been ACK'd (so connection is now fully
2554 * synchronized). Go to non-starred state,
2555 * increment snd_una for ACK of SYN, and check if
2556 * we can do window scaling.
2557 */
2558 tp->t_flags &= ~TF_NEEDSYN;
2559 tp->snd_una++;
2560 /* Do window scaling? */
2561 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2562 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2563 tp->snd_scale = tp->requested_s_scale;
2564 tp->rcv_scale = tp->request_r_scale;
2565 }
2566 }
2567
2568 process_ACK:
2569 acked = th->th_ack - tp->snd_una;
2570 tcpstat.tcps_rcvackpack++;
2571 tcpstat.tcps_rcvackbyte += acked;
2572
2573 /*
2574 * If we just performed our first retransmit, and the ACK
2575 * arrives within our recovery window, then it was a mistake
2576 * to do the retransmit in the first place. Recover our
2577 * original cwnd and ssthresh, and proceed to transmit where
2578 * we left off.
2579 */
2580 if (tp->t_rxtshift == 1 && tcp_now < tp->t_badrxtwin) {
2581 ++tcpstat.tcps_sndrexmitbad;
2582 tp->snd_cwnd = tp->snd_cwnd_prev;
2583 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2584 tp->snd_recover = tp->snd_recover_prev;
2585 if (tp->t_flags & TF_WASFRECOVERY)
2586 ENTER_FASTRECOVERY(tp);
2587 tp->snd_nxt = tp->snd_max;
2588 tp->t_badrxtwin = 0; /* XXX probably not required */
2589 }
2590
2591 /*
2592 * If we have a timestamp reply, update smoothed
2593 * round trip time. If no timestamp is present but
2594 * transmit timer is running and timed sequence
2595 * number was acked, update smoothed round trip time.
2596 * Since we now have an rtt measurement, cancel the
2597 * timer backoff (cf., Phil Karn's retransmit alg.).
2598 * Recompute the initial retransmit timer.
2599 * Also makes sure we have a valid time stamp in hand
2600 *
2601 * Some boxes send broken timestamp replies
2602 * during the SYN+ACK phase, ignore
2603 * timestamps of 0 or we could calculate a
2604 * huge RTT and blow up the retransmit timer.
2605 */
2606 if (((to.to_flags & TOF_TS) != 0) && (to.to_tsecr != 0)) {
2607 if (!tp->t_rttlow || tp->t_rttlow > tcp_now - to.to_tsecr)
2608 tp->t_rttlow = tcp_now - to.to_tsecr;
2609 tcp_xmit_timer(tp, tcp_now - to.to_tsecr);
2610 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2611 if (!tp->t_rttlow || tp->t_rttlow > tcp_now - tp->t_rtttime)
2612 tp->t_rttlow = tcp_now - tp->t_rtttime;
2613 tcp_xmit_timer(tp, tp->t_rtttime);
2614 }
2615
2616 /*
2617 * If all outstanding data is acked, stop retransmit
2618 * timer and remember to restart (more output or persist).
2619 * If there is more data to be acked, restart retransmit
2620 * timer, using current (possibly backed-off) value.
2621 */
2622 if (th->th_ack == tp->snd_max) {
2623 tp->t_timer[TCPT_REXMT] = 0;
2624 needoutput = 1;
2625 } else if (tp->t_timer[TCPT_PERSIST] == 0)
2626 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
2627
2628 /*
2629 * If no data (only SYN) was ACK'd,
2630 * skip rest of ACK processing.
2631 */
2632 if (acked == 0)
2633 goto step6;
2634
2635 /*
2636 * When new data is acked, open the congestion window.
2637 */
2638 if ((thflags & TH_ECE) != 0 &&
2639 (tp->ecn_flags & TE_SETUPSENT) != 0) {
2640 /*
2641 * Reduce the congestion window if we haven't done so.
2642 */
2643 if (!(tp->sack_enable && IN_FASTRECOVERY(tp)) &&
2644 !(tcp_do_newreno && SEQ_LEQ(th->th_ack, tp->snd_recover))) {
2645 tcp_reduce_congestion_window(tp);
2646 }
2647 } else if ((!tcp_do_newreno && !tp->sack_enable) ||
2648 !IN_FASTRECOVERY(tp)) {
2649 /*
2650 * RFC 3465 - Appropriate Byte Counting.
2651 *
2652 * If the window is currently less than ssthresh,
2653 * open the window by the number of bytes ACKed by
2654 * the last ACK, however clamp the window increase
2655 * to an upper limit "L".
2656 *
2657 * In congestion avoidance phase, open the window by
2658 * one segment each time "bytes_acked" grows to be
2659 * greater than or equal to the congestion window.
2660 */
2661
2662 register u_int cw = tp->snd_cwnd;
2663 register u_int incr = tp->t_maxseg;
2664
2665 if (tcp_do_rfc3465) {
2666
2667 if (cw >= tp->snd_ssthresh) {
2668 tp->t_bytes_acked += acked;
2669 if (tp->t_bytes_acked >= cw) {
2670 /* Time to increase the window. */
2671 tp->t_bytes_acked -= cw;
2672 } else {
2673 /* No need to increase yet. */
2674 incr = 0;
2675 }
2676 } else {
2677 /*
2678 * If the user explicitly enables RFC3465
2679 * use 2*SMSS for the "L" param. Otherwise
2680 * use the more conservative 1*SMSS.
2681 *
2682 * (See RFC 3465 2.3 Choosing the Limit)
2683 */
2684 u_int abc_lim;
2685
2686 abc_lim = (tcp_do_rfc3465_lim2 &&
2687 tp->snd_nxt == tp->snd_max) ? incr * 2 : incr;
2688
2689 incr = lmin(acked, abc_lim);
2690 }
2691 }
2692 else {
2693 /*
2694 * If the window gives us less than ssthresh packets
2695 * in flight, open exponentially (segsz per packet).
2696 * Otherwise open linearly: segsz per window
2697 * (segsz^2 / cwnd per packet).
2698 */
2699
2700 if (cw >= tp->snd_ssthresh) {
2701 incr = max((incr * incr / cw), 1);
2702 }
2703 }
2704
2705
2706 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2707 }
2708 if (acked > so->so_snd.sb_cc) {
2709 tp->snd_wnd -= so->so_snd.sb_cc;
2710 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2711 ourfinisacked = 1;
2712 } else {
2713 sbdrop(&so->so_snd, acked);
2714 tp->snd_wnd -= acked;
2715 ourfinisacked = 0;
2716 }
2717 /* detect una wraparound */
2718 if ((tcp_do_newreno || tp->sack_enable) &&
2719 !IN_FASTRECOVERY(tp) &&
2720 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2721 SEQ_LEQ(th->th_ack, tp->snd_recover))
2722 tp->snd_recover = th->th_ack - 1;
2723 if ((tcp_do_newreno || tp->sack_enable) &&
2724 IN_FASTRECOVERY(tp) &&
2725 SEQ_GEQ(th->th_ack, tp->snd_recover))
2726 EXIT_FASTRECOVERY(tp);
2727 tp->snd_una = th->th_ack;
2728 if (tp->sack_enable) {
2729 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2730 tp->snd_recover = tp->snd_una;
2731 }
2732 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2733 tp->snd_nxt = tp->snd_una;
2734
2735 /*
2736 * sowwakeup must happen after snd_una, et al. are updated so that
2737 * the sequence numbers are in sync with so_snd
2738 */
2739 sowwakeup(so);
2740
2741 switch (tp->t_state) {
2742
2743 /*
2744 * In FIN_WAIT_1 STATE in addition to the processing
2745 * for the ESTABLISHED state if our FIN is now acknowledged
2746 * then enter FIN_WAIT_2.
2747 */
2748 case TCPS_FIN_WAIT_1:
2749 if (ourfinisacked) {
2750 /*
2751 * If we can't receive any more
2752 * data, then closing user can proceed.
2753 * Starting the timer is contrary to the
2754 * specification, but if we don't get a FIN
2755 * we'll hang forever.
2756 */
2757 if (so->so_state & SS_CANTRCVMORE) {
2758 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
2759 add_to_time_wait(tp);
2760 soisdisconnected(so);
2761 }
2762 tp->t_state = TCPS_FIN_WAIT_2;
2763 /* fall through and make sure we also recognize data ACKed with the FIN */
2764 }
2765 tp->t_flags |= TF_ACKNOW;
2766 break;
2767
2768 /*
2769 * In CLOSING STATE in addition to the processing for
2770 * the ESTABLISHED state if the ACK acknowledges our FIN
2771 * then enter the TIME-WAIT state, otherwise ignore
2772 * the segment.
2773 */
2774 case TCPS_CLOSING:
2775 if (ourfinisacked) {
2776 tp->t_state = TCPS_TIME_WAIT;
2777 tcp_canceltimers(tp);
2778 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2779 if (tp->cc_recv != 0 &&
2780 tp->t_starttime < (u_int32_t)tcp_msl)
2781 tp->t_timer[TCPT_2MSL] =
2782 tp->t_rxtcur * TCPTV_TWTRUNC;
2783 else
2784 tp->t_timer[TCPT_2MSL] = 2 * tcp_msl;
2785 add_to_time_wait(tp);
2786 soisdisconnected(so);
2787 }
2788 tp->t_flags |= TF_ACKNOW;
2789 break;
2790
2791 /*
2792 * In LAST_ACK, we may still be waiting for data to drain
2793 * and/or to be acked, as well as for the ack of our FIN.
2794 * If our FIN is now acknowledged, delete the TCB,
2795 * enter the closed state and return.
2796 */
2797 case TCPS_LAST_ACK:
2798 if (ourfinisacked) {
2799 tp = tcp_close(tp);
2800 goto drop;
2801 }
2802 break;
2803
2804 /*
2805 * In TIME_WAIT state the only thing that should arrive
2806 * is a retransmission of the remote FIN. Acknowledge
2807 * it and restart the finack timer.
2808 */
2809 case TCPS_TIME_WAIT:
2810 tp->t_timer[TCPT_2MSL] = 2 * tcp_msl;
2811 add_to_time_wait(tp);
2812 goto dropafterack;
2813 }
2814 }
2815
2816 step6:
2817 /*
2818 * Update window information.
2819 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2820 */
2821 if ((thflags & TH_ACK) &&
2822 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2823 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2824 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2825 /* keep track of pure window updates */
2826 if (tlen == 0 &&
2827 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2828 tcpstat.tcps_rcvwinupd++;
2829 tp->snd_wnd = tiwin;
2830 tp->snd_wl1 = th->th_seq;
2831 tp->snd_wl2 = th->th_ack;
2832 if (tp->snd_wnd > tp->max_sndwnd)
2833 tp->max_sndwnd = tp->snd_wnd;
2834 needoutput = 1;
2835 }
2836
2837 /*
2838 * Process segments with URG.
2839 */
2840 if ((thflags & TH_URG) && th->th_urp &&
2841 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2842 /*
2843 * This is a kludge, but if we receive and accept
2844 * random urgent pointers, we'll crash in
2845 * soreceive. It's hard to imagine someone
2846 * actually wanting to send this much urgent data.
2847 */
2848 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2849 th->th_urp = 0; /* XXX */
2850 thflags &= ~TH_URG; /* XXX */
2851 goto dodata; /* XXX */
2852 }
2853 /*
2854 * If this segment advances the known urgent pointer,
2855 * then mark the data stream. This should not happen
2856 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2857 * a FIN has been received from the remote side.
2858 * In these states we ignore the URG.
2859 *
2860 * According to RFC961 (Assigned Protocols),
2861 * the urgent pointer points to the last octet
2862 * of urgent data. We continue, however,
2863 * to consider it to indicate the first octet
2864 * of data past the urgent section as the original
2865 * spec states (in one of two places).
2866 */
2867 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2868 tp->rcv_up = th->th_seq + th->th_urp;
2869 so->so_oobmark = so->so_rcv.sb_cc +
2870 (tp->rcv_up - tp->rcv_nxt) - 1;
2871 if (so->so_oobmark == 0) {
2872 so->so_state |= SS_RCVATMARK;
2873 postevent(so, 0, EV_OOB);
2874 }
2875 sohasoutofband(so);
2876 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2877 }
2878 /*
2879 * Remove out of band data so doesn't get presented to user.
2880 * This can happen independent of advancing the URG pointer,
2881 * but if two URG's are pending at once, some out-of-band
2882 * data may creep in... ick.
2883 */
2884 if (th->th_urp <= (u_int32_t)tlen
2885 #if SO_OOBINLINE
2886 && (so->so_options & SO_OOBINLINE) == 0
2887 #endif
2888 )
2889 tcp_pulloutofband(so, th, m,
2890 drop_hdrlen); /* hdr drop is delayed */
2891 } else
2892 /*
2893 * If no out of band data is expected,
2894 * pull receive urgent pointer along
2895 * with the receive window.
2896 */
2897 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2898 tp->rcv_up = tp->rcv_nxt;
2899 dodata: /* XXX */
2900
2901 /*
2902 * Process the segment text, merging it into the TCP sequencing queue,
2903 * and arranging for acknowledgment of receipt if necessary.
2904 * This process logically involves adjusting tp->rcv_wnd as data
2905 * is presented to the user (this happens in tcp_usrreq.c,
2906 * case PRU_RCVD). If a FIN has already been received on this
2907 * connection then we just ignore the text.
2908 */
2909 if ((tlen || (thflags & TH_FIN)) &&
2910 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2911 tcp_seq save_start = th->th_seq;
2912 tcp_seq save_end = th->th_seq + tlen;
2913 m_adj(m, drop_hdrlen); /* delayed header drop */
2914 /*
2915 * Insert segment which includes th into TCP reassembly queue
2916 * with control block tp. Set thflags to whether reassembly now
2917 * includes a segment with FIN. This handles the common case
2918 * inline (segment is the next to be received on an established
2919 * connection, and the queue is empty), avoiding linkage into
2920 * and removal from the queue and repetition of various
2921 * conversions.
2922 * Set DELACK for segments received in order, but ack
2923 * immediately when segments are out of order (so
2924 * fast retransmit can work).
2925 */
2926 if (th->th_seq == tp->rcv_nxt &&
2927 LIST_EMPTY(&tp->t_segq) &&
2928 TCPS_HAVEESTABLISHED(tp->t_state)) {
2929 if (DELAY_ACK(tp) && ((tp->t_flags & TF_ACKNOW) == 0)) {
2930 tp->t_flags |= TF_DELACK;
2931 tp->t_unacksegs++;
2932 }
2933 else {
2934 tp->t_unacksegs = 0;
2935 tp->t_flags |= TF_ACKNOW;
2936 }
2937 tp->rcv_nxt += tlen;
2938 thflags = th->th_flags & TH_FIN;
2939 tcpstat.tcps_rcvpack++;
2940 tcpstat.tcps_rcvbyte += tlen;
2941 ND6_HINT(tp);
2942 if (sbappendstream(&so->so_rcv, m))
2943 sorwakeup(so);
2944 } else {
2945 thflags = tcp_reass(tp, th, &tlen, m);
2946 tp->t_flags |= TF_ACKNOW;
2947 tp->t_unacksegs = 0;
2948 }
2949
2950 if (tlen > 0 && tp->sack_enable)
2951 tcp_update_sack_list(tp, save_start, save_end);
2952
2953 if (tp->t_flags & TF_DELACK)
2954 {
2955 #if INET6
2956 if (isipv6) {
2957 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
2958 (((ip6->ip6_src.s6_addr16[0]) << 16) | (ip6->ip6_dst.s6_addr16[0])),
2959 th->th_seq, th->th_ack, th->th_win);
2960 }
2961 else
2962 #endif
2963 {
2964 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
2965 (((ip->ip_src.s_addr & 0xffff) << 16) | (ip->ip_dst.s_addr & 0xffff)),
2966 th->th_seq, th->th_ack, th->th_win);
2967 }
2968
2969 }
2970 /*
2971 * Note the amount of data that peer has sent into
2972 * our window, in order to estimate the sender's
2973 * buffer size.
2974 */
2975 len = (u_int)(so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt));
2976 if (len > so->so_rcv.sb_maxused)
2977 so->so_rcv.sb_maxused = len;
2978 } else {
2979 m_freem(m);
2980 thflags &= ~TH_FIN;
2981 }
2982
2983 /*
2984 * If FIN is received ACK the FIN and let the user know
2985 * that the connection is closing.
2986 */
2987 if (thflags & TH_FIN) {
2988 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2989 socantrcvmore(so);
2990 postevent(so, 0, EV_FIN);
2991 /*
2992 * If connection is half-synchronized
2993 * (ie NEEDSYN flag on) then delay ACK,
2994 * If connection is half-synchronized
2995 * (ie NEEDSYN flag on) then delay ACK,
2996 * so it may be piggybacked when SYN is sent.
2997 * Otherwise, since we received a FIN then no
2998 * more input can be expected, send ACK now.
2999 */
3000 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN)) {
3001 tp->t_flags |= TF_DELACK;
3002 tp->t_unacksegs++;
3003 }
3004 else {
3005 tp->t_flags |= TF_ACKNOW;
3006 tp->t_unacksegs = 0;
3007 }
3008 tp->rcv_nxt++;
3009 }
3010 switch (tp->t_state) {
3011
3012 /*
3013 * In SYN_RECEIVED and ESTABLISHED STATES
3014 * enter the CLOSE_WAIT state.
3015 */
3016 case TCPS_SYN_RECEIVED:
3017 tp->t_starttime = 0;
3018 case TCPS_ESTABLISHED:
3019 tp->t_state = TCPS_CLOSE_WAIT;
3020 break;
3021
3022 /*
3023 * If still in FIN_WAIT_1 STATE FIN has not been acked so
3024 * enter the CLOSING state.
3025 */
3026 case TCPS_FIN_WAIT_1:
3027 tp->t_state = TCPS_CLOSING;
3028 break;
3029
3030 /*
3031 * In FIN_WAIT_2 state enter the TIME_WAIT state,
3032 * starting the time-wait timer, turning off the other
3033 * standard timers.
3034 */
3035 case TCPS_FIN_WAIT_2:
3036 tp->t_state = TCPS_TIME_WAIT;
3037 tcp_canceltimers(tp);
3038 /* Shorten TIME_WAIT [RFC-1644, p.28] */
3039 if (tp->cc_recv != 0 &&
3040 tp->t_starttime < (u_int32_t)tcp_msl) {
3041 tp->t_timer[TCPT_2MSL] =
3042 tp->t_rxtcur * TCPTV_TWTRUNC;
3043 /* For transaction client, force ACK now. */
3044 tp->t_flags |= TF_ACKNOW;
3045 tp->t_unacksegs = 0;
3046 }
3047 else
3048 tp->t_timer[TCPT_2MSL] = 2 * tcp_msl;
3049
3050 add_to_time_wait(tp);
3051 soisdisconnected(so);
3052 break;
3053
3054 /*
3055 * In TIME_WAIT state restart the 2 MSL time_wait timer.
3056 */
3057 case TCPS_TIME_WAIT:
3058 tp->t_timer[TCPT_2MSL] = 2 * tcp_msl;
3059 add_to_time_wait(tp);
3060 break;
3061 }
3062 }
3063 #if TCPDEBUG
3064 if (so->so_options & SO_DEBUG)
3065 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
3066 &tcp_savetcp, 0);
3067 #endif
3068
3069 /*
3070 * Return any desired output.
3071 */
3072 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
3073 tp->t_unacksegs = 0;
3074 (void) tcp_output(tp);
3075 }
3076 tcp_unlock(so, 1, 0);
3077 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
3078 return;
3079
3080 dropafterack:
3081 /*
3082 * Generate an ACK dropping incoming segment if it occupies
3083 * sequence space, where the ACK reflects our state.
3084 *
3085 * We can now skip the test for the RST flag since all
3086 * paths to this code happen after packets containing
3087 * RST have been dropped.
3088 *
3089 * In the SYN-RECEIVED state, don't send an ACK unless the
3090 * segment we received passes the SYN-RECEIVED ACK test.
3091 * If it fails send a RST. This breaks the loop in the
3092 * "LAND" DoS attack, and also prevents an ACK storm
3093 * between two listening ports that have been sent forged
3094 * SYN segments, each with the source address of the other.
3095 */
3096 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
3097 (SEQ_GT(tp->snd_una, th->th_ack) ||
3098 SEQ_GT(th->th_ack, tp->snd_max)) ) {
3099 rstreason = BANDLIM_RST_OPENPORT;
3100 goto dropwithreset;
3101 }
3102 #if TCPDEBUG
3103 if (so->so_options & SO_DEBUG)
3104 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3105 &tcp_savetcp, 0);
3106 #endif
3107 m_freem(m);
3108 tp->t_flags |= TF_ACKNOW;
3109 tp->t_unacksegs = 0;
3110 (void) tcp_output(tp);
3111 tcp_unlock(so, 1, 0);
3112 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
3113 return;
3114 dropwithresetnosock:
3115 nosock = 1;
3116 dropwithreset:
3117 /*
3118 * Generate a RST, dropping incoming segment.
3119 * Make ACK acceptable to originator of segment.
3120 * Don't bother to respond if destination was broadcast/multicast.
3121 */
3122 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
3123 goto drop;
3124 #if INET6
3125 if (isipv6) {
3126 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3127 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3128 goto drop;
3129 } else
3130 #endif /* INET6 */
3131 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3132 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3133 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3134 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3135 goto drop;
3136 /* IPv6 anycast check is done at tcp6_input() */
3137
3138 /*
3139 * Perform bandwidth limiting.
3140 */
3141 #if ICMP_BANDLIM
3142 if (badport_bandlim(rstreason) < 0)
3143 goto drop;
3144 #endif
3145
3146 #if TCPDEBUG
3147 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3148 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3149 &tcp_savetcp, 0);
3150 #endif
3151 if (thflags & TH_ACK)
3152 /* mtod() below is safe as long as hdr dropping is delayed */
3153 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
3154 TH_RST, ifscope);
3155 else {
3156 if (thflags & TH_SYN)
3157 tlen++;
3158 /* mtod() below is safe as long as hdr dropping is delayed */
3159 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
3160 (tcp_seq)0, TH_RST|TH_ACK, ifscope);
3161 }
3162 /* destroy temporarily created socket */
3163 if (dropsocket) {
3164 (void) soabort(so);
3165 tcp_unlock(so, 1, 0);
3166 }
3167 else
3168 if ((inp != NULL) && (nosock == 0))
3169 tcp_unlock(so, 1, 0);
3170 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
3171 return;
3172 dropnosock:
3173 nosock = 1;
3174 drop:
3175 /*
3176 * Drop space held by incoming segment and return.
3177 */
3178 #if TCPDEBUG
3179 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
3180 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
3181 &tcp_savetcp, 0);
3182 #endif
3183 m_freem(m);
3184 /* destroy temporarily created socket */
3185 if (dropsocket) {
3186 (void) soabort(so);
3187 tcp_unlock(so, 1, 0);
3188 }
3189 else
3190 if (nosock == 0)
3191 tcp_unlock(so, 1, 0);
3192 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
3193 return;
3194 }
3195
3196 static void
3197 tcp_dooptions(tp, cp, cnt, th, to, input_ifscope)
3198 /*
3199 * Parse TCP options and place in tcpopt.
3200 */
3201 struct tcpcb *tp;
3202 u_char *cp;
3203 int cnt;
3204 struct tcphdr *th;
3205 struct tcpopt *to;
3206 unsigned int input_ifscope;
3207 {
3208 u_short mss = 0;
3209 int opt, optlen;
3210
3211 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3212 opt = cp[0];
3213 if (opt == TCPOPT_EOL)
3214 break;
3215 if (opt == TCPOPT_NOP)
3216 optlen = 1;
3217 else {
3218 if (cnt < 2)
3219 break;
3220 optlen = cp[1];
3221 if (optlen < 2 || optlen > cnt)
3222 break;
3223 }
3224 switch (opt) {
3225
3226 default:
3227 continue;
3228
3229 case TCPOPT_MAXSEG:
3230 if (optlen != TCPOLEN_MAXSEG)
3231 continue;
3232 if (!(th->th_flags & TH_SYN))
3233 continue;
3234 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
3235
3236 #if BYTE_ORDER != BIG_ENDIAN
3237 NTOHS(mss);
3238 #endif
3239
3240 break;
3241
3242 case TCPOPT_WINDOW:
3243 if (optlen != TCPOLEN_WINDOW)
3244 continue;
3245 if (!(th->th_flags & TH_SYN))
3246 continue;
3247 tp->t_flags |= TF_RCVD_SCALE;
3248 tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
3249 break;
3250
3251 case TCPOPT_TIMESTAMP:
3252 if (optlen != TCPOLEN_TIMESTAMP)
3253 continue;
3254 to->to_flags |= TOF_TS;
3255 bcopy((char *)cp + 2,
3256 (char *)&to->to_tsval, sizeof(to->to_tsval));
3257
3258 #if BYTE_ORDER != BIG_ENDIAN
3259 NTOHL(to->to_tsval);
3260 #endif
3261
3262 bcopy((char *)cp + 6,
3263 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
3264
3265 #if BYTE_ORDER != BIG_ENDIAN
3266 NTOHL(to->to_tsecr);
3267 #endif
3268
3269 /*
3270 * A timestamp received in a SYN makes
3271 * it ok to send timestamp requests and replies.
3272 */
3273 if (th->th_flags & TH_SYN) {
3274 tp->t_flags |= TF_RCVD_TSTMP;
3275 tp->ts_recent = to->to_tsval;
3276 tp->ts_recent_age = tcp_now;
3277 }
3278 break;
3279 case TCPOPT_SACK_PERMITTED:
3280 if (!tcp_do_sack ||
3281 optlen != TCPOLEN_SACK_PERMITTED)
3282 continue;
3283 if (th->th_flags & TH_SYN)
3284 to->to_flags |= TOF_SACK;
3285 break;
3286 case TCPOPT_SACK:
3287 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
3288 continue;
3289 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
3290 to->to_sacks = cp + 2;
3291 tcpstat.tcps_sack_rcv_blocks++;
3292
3293 break;
3294 }
3295 }
3296 if (th->th_flags & TH_SYN)
3297 tcp_mss(tp, mss, input_ifscope); /* sets t_maxseg */
3298 }
3299
3300 /*
3301 * Pull out of band byte out of a segment so
3302 * it doesn't appear in the user's data queue.
3303 * It is still reflected in the segment length for
3304 * sequencing purposes.
3305 */
3306 static void
3307 tcp_pulloutofband(so, th, m, off)
3308 struct socket *so;
3309 struct tcphdr *th;
3310 register struct mbuf *m;
3311 int off; /* delayed to be droped hdrlen */
3312 {
3313 int cnt = off + th->th_urp - 1;
3314
3315 while (cnt >= 0) {
3316 if (m->m_len > cnt) {
3317 char *cp = mtod(m, caddr_t) + cnt;
3318 struct tcpcb *tp = sototcpcb(so);
3319
3320 tp->t_iobc = *cp;
3321 tp->t_oobflags |= TCPOOB_HAVEDATA;
3322 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3323 m->m_len--;
3324 if (m->m_flags & M_PKTHDR)
3325 m->m_pkthdr.len--;
3326 return;
3327 }
3328 cnt -= m->m_len;
3329 m = m->m_next;
3330 if (m == 0)
3331 break;
3332 }
3333 panic("tcp_pulloutofband");
3334 }
3335
3336 /*
3337 * Collect new round-trip time estimate
3338 * and update averages and current timeout.
3339 */
3340 static void
3341 tcp_xmit_timer(tp, rtt)
3342 register struct tcpcb *tp;
3343 int rtt;
3344 {
3345 register int delta;
3346
3347 tcpstat.tcps_rttupdated++;
3348 tp->t_rttupdated++;
3349 if (tp->t_srtt != 0) {
3350 /*
3351 * srtt is stored as fixed point with 5 bits after the
3352 * binary point (i.e., scaled by 8). The following magic
3353 * is equivalent to the smoothing algorithm in rfc793 with
3354 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3355 * point). Adjust rtt to origin 0.
3356 */
3357 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3358 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3359
3360 if ((tp->t_srtt += delta) <= 0)
3361 tp->t_srtt = 1;
3362
3363 /*
3364 * We accumulate a smoothed rtt variance (actually, a
3365 * smoothed mean difference), then set the retransmit
3366 * timer to smoothed rtt + 4 times the smoothed variance.
3367 * rttvar is stored as fixed point with 4 bits after the
3368 * binary point (scaled by 16). The following is
3369 * equivalent to rfc793 smoothing with an alpha of .75
3370 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3371 * rfc793's wired-in beta.
3372 */
3373 if (delta < 0)
3374 delta = -delta;
3375 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3376 if ((tp->t_rttvar += delta) <= 0)
3377 tp->t_rttvar = 1;
3378 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3379 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3380 } else {
3381 /*
3382 * No rtt measurement yet - use the unsmoothed rtt.
3383 * Set the variance to half the rtt (so our first
3384 * retransmit happens at 3*rtt).
3385 */
3386 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3387 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3388 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3389 }
3390 tp->t_rtttime = 0;
3391 tp->t_rxtshift = 0;
3392
3393 /*
3394 * the retransmit should happen at rtt + 4 * rttvar.
3395 * Because of the way we do the smoothing, srtt and rttvar
3396 * will each average +1/2 tick of bias. When we compute
3397 * the retransmit timer, we want 1/2 tick of rounding and
3398 * 1 extra tick because of +-1/2 tick uncertainty in the
3399 * firing of the timer. The bias will give us exactly the
3400 * 1.5 tick we need. But, because the bias is
3401 * statistical, we have to test that we don't drop below
3402 * the minimum feasible timer (which is 2 ticks).
3403 */
3404 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3405 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3406
3407 /*
3408 * We received an ack for a packet that wasn't retransmitted;
3409 * it is probably safe to discard any error indications we've
3410 * received recently. This isn't quite right, but close enough
3411 * for now (a route might have failed after we sent a segment,
3412 * and the return path might not be symmetrical).
3413 */
3414 tp->t_softerror = 0;
3415 }
3416
3417 static inline unsigned int
3418 tcp_maxmtu(struct rtentry *rt)
3419 {
3420 unsigned int maxmtu;
3421
3422 RT_LOCK_ASSERT_HELD(rt);
3423 if (rt->rt_rmx.rmx_mtu == 0)
3424 maxmtu = rt->rt_ifp->if_mtu;
3425 else
3426 maxmtu = MIN(rt->rt_rmx.rmx_mtu, rt->rt_ifp->if_mtu);
3427
3428 return (maxmtu);
3429 }
3430
3431 #if INET6
3432 static inline unsigned int
3433 tcp_maxmtu6(struct rtentry *rt)
3434 {
3435 unsigned int maxmtu;
3436
3437 RT_LOCK_ASSERT_HELD(rt);
3438 lck_rw_lock_shared(nd_if_rwlock);
3439 if (rt->rt_rmx.rmx_mtu == 0)
3440 maxmtu = IN6_LINKMTU(rt->rt_ifp);
3441 else
3442 maxmtu = MIN(rt->rt_rmx.rmx_mtu, IN6_LINKMTU(rt->rt_ifp));
3443 lck_rw_done(nd_if_rwlock);
3444
3445 return (maxmtu);
3446 }
3447 #endif
3448
3449 /*
3450 * Determine a reasonable value for maxseg size.
3451 * If the route is known, check route for mtu.
3452 * If none, use an mss that can be handled on the outgoing
3453 * interface without forcing IP to fragment; if bigger than
3454 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3455 * to utilize large mbufs. If no route is found, route has no mtu,
3456 * or the destination isn't local, use a default, hopefully conservative
3457 * size (usually 512 or the default IP max size, but no more than the mtu
3458 * of the interface), as we can't discover anything about intervening
3459 * gateways or networks. We also initialize the congestion/slow start
3460 * window to be a single segment if the destination isn't local.
3461 * While looking at the routing entry, we also initialize other path-dependent
3462 * parameters from pre-set or cached values in the routing entry.
3463 *
3464 * Also take into account the space needed for options that we
3465 * send regularly. Make maxseg shorter by that amount to assure
3466 * that we can send maxseg amount of data even when the options
3467 * are present. Store the upper limit of the length of options plus
3468 * data in maxopd.
3469 *
3470 * NOTE that this routine is only called when we process an incoming
3471 * segment, for outgoing segments only tcp_mssopt is called.
3472 *
3473 */
3474 void
3475 tcp_mss(tp, offer, input_ifscope)
3476 struct tcpcb *tp;
3477 int offer;
3478 unsigned int input_ifscope;
3479 {
3480 register struct rtentry *rt;
3481 struct ifnet *ifp;
3482 register int rtt, mss;
3483 u_int32_t bufsize;
3484 struct inpcb *inp;
3485 struct socket *so;
3486 struct rmxp_tao *taop;
3487 int origoffer = offer;
3488 u_int32_t sb_max_corrected;
3489 int isnetlocal = 0;
3490 #if INET6
3491 int isipv6;
3492 int min_protoh;
3493 #endif
3494
3495 inp = tp->t_inpcb;
3496 #if INET6
3497 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3498 min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
3499 : sizeof (struct tcpiphdr);
3500 #else
3501 #define min_protoh (sizeof (struct tcpiphdr))
3502 #endif
3503
3504 #if INET6
3505 if (isipv6) {
3506 rt = tcp_rtlookup6(inp);
3507 if (rt != NULL &&
3508 (IN6_IS_ADDR_LOOPBACK(&inp->in6p_faddr) ||
3509 IN6_IS_ADDR_LINKLOCAL(&inp->in6p_faddr) ||
3510 rt->rt_gateway->sa_family == AF_LINK))
3511 isnetlocal = TRUE;
3512 }
3513 else
3514 #endif /* INET6 */
3515 {
3516 rt = tcp_rtlookup(inp, input_ifscope);
3517 if (rt != NULL &&
3518 (rt->rt_gateway->sa_family == AF_LINK ||
3519 rt->rt_ifp->if_flags & IFF_LOOPBACK))
3520 isnetlocal = TRUE;
3521 }
3522 if (rt == NULL) {
3523 tp->t_maxopd = tp->t_maxseg =
3524 #if INET6
3525 isipv6 ? tcp_v6mssdflt :
3526 #endif /* INET6 */
3527 tcp_mssdflt;
3528 return;
3529 }
3530 ifp = rt->rt_ifp;
3531 /*
3532 * Slower link window correction:
3533 * If a value is specificied for slowlink_wsize use it for PPP links
3534 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3535 * it is the default value adversized by pseudo-devices over ppp.
3536 */
3537 if (ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
3538 ifp->if_baudrate > 9600 && ifp->if_baudrate <= 128000) {
3539 tp->t_flags |= TF_SLOWLINK;
3540 }
3541 so = inp->inp_socket;
3542
3543 taop = rmx_taop(rt->rt_rmx);
3544 /*
3545 * Offer == -1 means that we didn't receive SYN yet,
3546 * use cached value in that case;
3547 */
3548 if (offer == -1)
3549 offer = taop->tao_mssopt;
3550 /*
3551 * Offer == 0 means that there was no MSS on the SYN segment,
3552 * in this case we use tcp_mssdflt.
3553 */
3554 if (offer == 0)
3555 offer =
3556 #if INET6
3557 isipv6 ? tcp_v6mssdflt :
3558 #endif /* INET6 */
3559 tcp_mssdflt;
3560 else {
3561 /*
3562 * Prevent DoS attack with too small MSS. Round up
3563 * to at least minmss.
3564 */
3565 offer = max(offer, tcp_minmss);
3566 /*
3567 * Sanity check: make sure that maxopd will be large
3568 * enough to allow some data on segments even is the
3569 * all the option space is used (40bytes). Otherwise
3570 * funny things may happen in tcp_output.
3571 */
3572 offer = max(offer, 64);
3573 }
3574 taop->tao_mssopt = offer;
3575
3576 /*
3577 * While we're here, check if there's an initial rtt
3578 * or rttvar. Convert from the route-table units
3579 * to scaled multiples of the slow timeout timer.
3580 */
3581 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
3582 /*
3583 * XXX the lock bit for RTT indicates that the value
3584 * is also a minimum value; this is subject to time.
3585 */
3586 if (rt->rt_rmx.rmx_locks & RTV_RTT)
3587 tp->t_rttmin = rtt / (RTM_RTTUNIT / TCP_RETRANSHZ);
3588 else
3589 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCP_RETRANSHZ;
3590 tp->t_srtt = rtt / (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTT_SCALE));
3591 tcpstat.tcps_usedrtt++;
3592 if (rt->rt_rmx.rmx_rttvar) {
3593 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
3594 (RTM_RTTUNIT / (TCP_RETRANSHZ * TCP_RTTVAR_SCALE));
3595 tcpstat.tcps_usedrttvar++;
3596 } else {
3597 /* default variation is +- 1 rtt */
3598 tp->t_rttvar =
3599 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3600 }
3601 TCPT_RANGESET(tp->t_rxtcur,
3602 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3603 tp->t_rttmin, TCPTV_REXMTMAX);
3604 }
3605 else
3606 tp->t_rttmin = isnetlocal ? tcp_TCPTV_MIN : TCP_RETRANSHZ;
3607
3608 #if INET6
3609 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
3610 #else
3611 mss = tcp_maxmtu(rt);
3612 #endif
3613 mss -= min_protoh;
3614
3615 if (rt->rt_rmx.rmx_mtu == 0) {
3616 #if INET6
3617 if (isipv6) {
3618 if (!isnetlocal)
3619 mss = min(mss, tcp_v6mssdflt);
3620 } else
3621 #endif /* INET6 */
3622 if (!isnetlocal)
3623 mss = min(mss, tcp_mssdflt);
3624 }
3625
3626 mss = min(mss, offer);
3627 /*
3628 * maxopd stores the maximum length of data AND options
3629 * in a segment; maxseg is the amount of data in a normal
3630 * segment. We need to store this value (maxopd) apart
3631 * from maxseg, because now every segment carries options
3632 * and thus we normally have somewhat less data in segments.
3633 */
3634 tp->t_maxopd = mss;
3635
3636 /*
3637 * origoffer==-1 indicates, that no segments were received yet.
3638 * In this case we just guess.
3639 */
3640 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3641 (origoffer == -1 ||
3642 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3643 mss -= TCPOLEN_TSTAMP_APPA;
3644 tp->t_maxseg = mss;
3645
3646 /*
3647 * Calculate corrected value for sb_max; ensure to upgrade the
3648 * numerator for large sb_max values else it will overflow.
3649 */
3650 sb_max_corrected = (sb_max * (u_int64_t)MCLBYTES) / (MSIZE + MCLBYTES);
3651
3652 /*
3653 * If there's a pipesize (ie loopback), change the socket
3654 * buffer to that size only if it's bigger than the current
3655 * sockbuf size. Make the socket buffers an integral
3656 * number of mss units; if the mss is larger than
3657 * the socket buffer, decrease the mss.
3658 */
3659 #if RTV_SPIPE
3660 bufsize = rt->rt_rmx.rmx_sendpipe;
3661 if (bufsize < so->so_snd.sb_hiwat)
3662 #endif
3663 bufsize = so->so_snd.sb_hiwat;
3664 if (bufsize < mss)
3665 mss = bufsize;
3666 else {
3667 bufsize = (((bufsize + (u_int64_t)mss - 1) / (u_int64_t)mss) * (u_int64_t)mss);
3668 if (bufsize > sb_max_corrected)
3669 bufsize = sb_max_corrected;
3670 (void)sbreserve(&so->so_snd, bufsize);
3671 }
3672 tp->t_maxseg = mss;
3673
3674 #if RTV_RPIPE
3675 bufsize = rt->rt_rmx.rmx_recvpipe;
3676 if (bufsize < so->so_rcv.sb_hiwat)
3677 #endif
3678 bufsize = so->so_rcv.sb_hiwat;
3679 if (bufsize > mss) {
3680 bufsize = (((bufsize + (u_int64_t)mss - 1) / (u_int64_t)mss) * (u_int64_t)mss);
3681 if (bufsize > sb_max_corrected)
3682 bufsize = sb_max_corrected;
3683 (void)sbreserve(&so->so_rcv, bufsize);
3684 }
3685
3686 /*
3687 * Set the slow-start flight size depending on whether this
3688 * is a local network or not.
3689 */
3690 if (isnetlocal)
3691 tp->snd_cwnd = mss * ss_fltsz_local;
3692 else
3693 tp->snd_cwnd = mss * ss_fltsz;
3694
3695 if (rt->rt_rmx.rmx_ssthresh) {
3696 /*
3697 * There's some sort of gateway or interface
3698 * buffer limit on the path. Use this to set
3699 * the slow start threshhold, but set the
3700 * threshold to no less than 2*mss.
3701 */
3702 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
3703 tcpstat.tcps_usedssthresh++;
3704 } else {
3705 tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
3706 }
3707
3708 /* Route locked during lookup above */
3709 RT_UNLOCK(rt);
3710 }
3711
3712 /*
3713 * Determine the MSS option to send on an outgoing SYN.
3714 */
3715 int
3716 tcp_mssopt(tp)
3717 struct tcpcb *tp;
3718 {
3719 struct rtentry *rt;
3720 int mss;
3721 #if INET6
3722 int isipv6;
3723 int min_protoh;
3724 #endif
3725
3726 #if INET6
3727 isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3728 min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
3729 : sizeof (struct tcpiphdr);
3730 #else
3731 #define min_protoh (sizeof (struct tcpiphdr))
3732 #endif
3733
3734 #if INET6
3735 if (isipv6)
3736 rt = tcp_rtlookup6(tp->t_inpcb);
3737 else
3738 #endif /* INET6 */
3739 rt = tcp_rtlookup(tp->t_inpcb, IFSCOPE_NONE);
3740 if (rt == NULL) {
3741 return (
3742 #if INET6
3743 isipv6 ? tcp_v6mssdflt :
3744 #endif /* INET6 */
3745 tcp_mssdflt);
3746 }
3747 /*
3748 * Slower link window correction:
3749 * If a value is specificied for slowlink_wsize use it for PPP links
3750 * believed to be on a serial modem (speed <128Kbps). Excludes 9600bps as
3751 * it is the default value adversized by pseudo-devices over ppp.
3752 */
3753 if (rt->rt_ifp->if_type == IFT_PPP && slowlink_wsize > 0 &&
3754 rt->rt_ifp->if_baudrate > 9600 && rt->rt_ifp->if_baudrate <= 128000) {
3755 tp->t_flags |= TF_SLOWLINK;
3756 }
3757
3758 #if INET6
3759 mss = (isipv6 ? tcp_maxmtu6(rt) : tcp_maxmtu(rt));
3760 #else
3761 mss = tcp_maxmtu(rt);
3762 #endif
3763 /* Route locked during lookup above */
3764 RT_UNLOCK(rt);
3765 return (mss - min_protoh);
3766 }
3767
3768 /*
3769 * On a partial ack arrives, force the retransmission of the
3770 * next unacknowledged segment. Do not clear tp->t_dupacks.
3771 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3772 * be started again.
3773 */
3774 static void
3775 tcp_newreno_partial_ack(tp, th)
3776 struct tcpcb *tp;
3777 struct tcphdr *th;
3778 {
3779 tcp_seq onxt = tp->snd_nxt;
3780 u_int32_t ocwnd = tp->snd_cwnd;
3781 tp->t_timer[TCPT_REXMT] = 0;
3782 tp->t_rtttime = 0;
3783 tp->snd_nxt = th->th_ack;
3784 /*
3785 * Set snd_cwnd to one segment beyond acknowledged offset
3786 * (tp->snd_una has not yet been updated when this function
3787 * is called)
3788 */
3789 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3790 tp->t_flags |= TF_ACKNOW;
3791 tp->t_unacksegs = 0;
3792 (void) tcp_output(tp);
3793 tp->snd_cwnd = ocwnd;
3794 if (SEQ_GT(onxt, tp->snd_nxt))
3795 tp->snd_nxt = onxt;
3796 /*
3797 * Partial window deflation. Relies on fact that tp->snd_una
3798 * not updated yet.
3799 */
3800 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3801 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3802 else
3803 tp->snd_cwnd = 0;
3804 tp->snd_cwnd += tp->t_maxseg;
3805
3806 }
3807
3808 /*
3809 * Drop a random TCP connection that hasn't been serviced yet and
3810 * is eligible for discard. There is a one in qlen chance that
3811 * we will return a null, saying that there are no dropable
3812 * requests. In this case, the protocol specific code should drop
3813 * the new request. This insures fairness.
3814 *
3815 * The listening TCP socket "head" must be locked
3816 */
3817 static int
3818 tcp_dropdropablreq(struct socket *head)
3819 {
3820 struct socket *so, *sonext;
3821 unsigned int i, j, qlen;
3822 static int rnd;
3823 static struct timeval old_runtime;
3824 static unsigned int cur_cnt, old_cnt;
3825 struct timeval tv;
3826 struct inpcb *inp = NULL;
3827 struct tcpcb *tp;
3828
3829 if ((head->so_options & SO_ACCEPTCONN) == 0)
3830 return 0;
3831
3832 so = TAILQ_FIRST(&head->so_incomp);
3833 if (!so)
3834 return 0;
3835
3836 microtime(&tv);
3837 if ((i = (tv.tv_sec - old_runtime.tv_sec)) != 0) {
3838 old_runtime = tv;
3839 old_cnt = cur_cnt / i;
3840 cur_cnt = 0;
3841 }
3842
3843
3844 qlen = head->so_incqlen;
3845 if (++cur_cnt > qlen || old_cnt > qlen) {
3846 rnd = (314159 * rnd + 66329) & 0xffff;
3847 j = ((qlen + 1) * rnd) >> 16;
3848
3849 while (j-- && so)
3850 so = TAILQ_NEXT(so, so_list);
3851 }
3852 /* Find a connection that is not already closing (or being served) */
3853 while (so) {
3854 inp = (struct inpcb *)so->so_pcb;
3855
3856 sonext = TAILQ_NEXT(so, so_list);
3857
3858 if (in_pcb_checkstate(inp, WNT_ACQUIRE, 0) != WNT_STOPUSING) {
3859 /* Avoid the issue of a socket being accepted by one input thread
3860 * and being dropped by another input thread.
3861 * If we can't get a hold on this mutex, then grab the next socket in line.
3862 */
3863 if (lck_mtx_try_lock(inp->inpcb_mtx)) {
3864 so->so_usecount++;
3865 if ((so->so_usecount == 2) && so->so_state & SS_INCOMP)
3866 break;
3867 else {/* don't use if beeing accepted or used in any other way */
3868 in_pcb_checkstate(inp, WNT_RELEASE, 1);
3869 tcp_unlock(so, 1, 0);
3870 }
3871 }
3872 else {
3873 /* do not try to lock the inp in in_pcb_checkstate
3874 * because the lock is already held in some other thread.
3875 * Only drop the inp_wntcnt reference.
3876 */
3877 in_pcb_checkstate(inp, WNT_RELEASE, 1);
3878 }
3879 }
3880 so = sonext;
3881
3882 }
3883 if (!so)
3884 return 0;
3885
3886 TAILQ_REMOVE(&head->so_incomp, so, so_list);
3887 tcp_unlock(head, 0, 0);
3888
3889 /* Makes sure socket is still in the right state to be discarded */
3890
3891 if (in_pcb_checkstate(inp, WNT_RELEASE, 1) == WNT_STOPUSING) {
3892 tcp_unlock(so, 1, 0);
3893 tcp_lock(head, 0, 0);
3894 return 0;
3895 }
3896
3897 if (so->so_usecount != 2 || !(so->so_state & SS_INCOMP)) {
3898 /* do not discard: that socket is beeing accepted */
3899 tcp_unlock(so, 1, 0);
3900 tcp_lock(head, 0, 0);
3901 return 0;
3902 }
3903
3904 so->so_head = NULL;
3905
3906 /*
3907 * We do not want to lose track of the PCB right away in case we receive
3908 * more segments from the peer
3909 */
3910 tp = sototcpcb(so);
3911 so->so_flags |= SOF_OVERFLOW;
3912 tp->t_state = TCPS_TIME_WAIT;
3913 (void) tcp_close(tp);
3914 tp->t_unacksegs = 0;
3915 tcpstat.tcps_drops++;
3916 tcp_canceltimers(tp);
3917 add_to_time_wait(tp);
3918
3919 tcp_unlock(so, 1, 0);
3920 tcp_lock(head, 0, 0);
3921 head->so_incqlen--;
3922 head->so_qlen--;
3923 return 1;
3924 }
3925
3926 static int
3927 tcp_getstat SYSCTL_HANDLER_ARGS
3928 {
3929 #pragma unused(oidp, arg1, arg2)
3930
3931 int error;
3932
3933 if (req->oldptr == 0) {
3934 req->oldlen= (size_t)sizeof(struct tcpstat);
3935 }
3936
3937 error = SYSCTL_OUT(req, &tcpstat, MIN(sizeof (tcpstat), req->oldlen));
3938
3939 return (error);
3940
3941 }
3942
3943 SYSCTL_PROC(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RD, 0, 0,
3944 tcp_getstat, "S,tcpstat", "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
3945
3946 static int
3947 sysctl_rexmtthresh SYSCTL_HANDLER_ARGS
3948 {
3949 #pragma unused(arg1, arg2)
3950
3951 int error, val = tcprexmtthresh;
3952
3953 error = sysctl_handle_int(oidp, &val, 0, req);
3954 if (error || !req->newptr)
3955 return (error);
3956
3957 /*
3958 * Constrain the number of duplicate ACKs
3959 * to consider for TCP fast retransmit
3960 * to either 2 or 3
3961 */
3962
3963 if (val < 2 || val > 3)
3964 return (EINVAL);
3965
3966 tcprexmtthresh = val;
3967
3968 return (0);
3969 }
3970
3971 SYSCTL_PROC(_net_inet_tcp, OID_AUTO, rexmt_thresh, CTLTYPE_INT|CTLFLAG_RW,
3972 &tcprexmtthresh, 0, &sysctl_rexmtthresh, "I", "Duplicate ACK Threshold for Fast Retransmit");