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