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