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