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