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