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