Follow NOFSCHG if defined. (It's needed to be able to run make installworld
[dragonfly.git] / sys / netinet / tcp_input.c
CommitLineData
984263bc 1/*
66d6c637
JH
2 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2002, 2003, 2004 The DragonFly Project. All rights reserved.
95b22adf 4 *
66d6c637
JH
5 * This code is derived from software contributed to The DragonFly Project
6 * by Jeffrey M. Hsu.
95b22adf 7 *
66d6c637
JH
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
95b22adf 19 *
66d6c637
JH
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 */
33
34/*
35 * Copyright (c) 2002, 2003, 2004 Jeffrey M. Hsu. All rights reserved.
36 *
37 * License terms: all terms for the DragonFly license above plus the following:
38 *
39 * 4. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
41 *
42 * This product includes software developed by Jeffrey M. Hsu
43 * for the DragonFly Project.
44 *
45 * This requirement may be waived with permission from Jeffrey Hsu.
46 * This requirement will sunset and may be removed on July 8 2005,
47 * after which the standard DragonFly license (as shown above) will
48 * apply.
49 */
50
51/*
984263bc
MD
52 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
53 * The Regents of the University of California. All rights reserved.
54 *
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
57 * are met:
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * 3. All advertising materials mentioning features or use of this software
64 * must display the following acknowledgement:
65 * This product includes software developed by the University of
66 * California, Berkeley and its contributors.
67 * 4. Neither the name of the University nor the names of its contributors
68 * may be used to endorse or promote products derived from this software
69 * without specific prior written permission.
70 *
71 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
81 * SUCH DAMAGE.
82 *
83 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
84 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
86ac74c4 85 * $DragonFly: src/sys/netinet/tcp_input.c,v 1.39 2004/11/17 02:18:17 dillon Exp $
984263bc
MD
86 */
87
88#include "opt_ipfw.h" /* for ipfw_fwd */
89#include "opt_inet6.h"
90#include "opt_ipsec.h"
91#include "opt_tcpdebug.h"
92#include "opt_tcp_input.h"
93
94#include <sys/param.h>
95#include <sys/systm.h>
96#include <sys/kernel.h>
97#include <sys/sysctl.h>
98#include <sys/malloc.h>
99#include <sys/mbuf.h>
100#include <sys/proc.h> /* for proc0 declaration */
101#include <sys/protosw.h>
102#include <sys/socket.h>
103#include <sys/socketvar.h>
104#include <sys/syslog.h>
3f9db7f8 105#include <sys/in_cksum.h>
984263bc
MD
106
107#include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
a00138cb 108#include <machine/stdarg.h>
984263bc
MD
109
110#include <net/if.h>
111#include <net/route.h>
112
113#include <netinet/in.h>
114#include <netinet/in_systm.h>
115#include <netinet/ip.h>
95b22adf 116#include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
984263bc 117#include <netinet/in_var.h>
95b22adf 118#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
984263bc
MD
119#include <netinet/in_pcb.h>
120#include <netinet/ip_var.h>
121#include <netinet/ip6.h>
122#include <netinet/icmp6.h>
123#include <netinet6/nd6.h>
124#include <netinet6/ip6_var.h>
125#include <netinet6/in6_pcb.h>
126#include <netinet/tcp.h>
127#include <netinet/tcp_fsm.h>
128#include <netinet/tcp_seq.h>
129#include <netinet/tcp_timer.h>
130#include <netinet/tcp_var.h>
131#include <netinet6/tcp6_var.h>
132#include <netinet/tcpip.h>
95b22adf 133
984263bc
MD
134#ifdef TCPDEBUG
135#include <netinet/tcp_debug.h>
136
95b22adf 137u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
984263bc 138struct tcphdr tcp_savetcp;
95b22adf 139#endif
984263bc
MD
140
141#ifdef FAST_IPSEC
bf844ffa
JH
142#include <netproto/ipsec/ipsec.h>
143#include <netproto/ipsec/ipsec6.h>
984263bc
MD
144#endif
145
146#ifdef IPSEC
147#include <netinet6/ipsec.h>
148#include <netinet6/ipsec6.h>
d2438d69 149#include <netproto/key/key.h>
95b22adf 150#endif
984263bc 151
984263bc
MD
152MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
153
984263bc 154tcp_cc tcp_ccgen;
984263bc 155static int log_in_vain = 0;
d24ce1dc 156SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
984263bc
MD
157 &log_in_vain, 0, "Log all incoming TCP connections");
158
159static int blackhole = 0;
160SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
161 &blackhole, 0, "Do not send RST when dropping refused connections");
162
163int tcp_delack_enabled = 1;
d24ce1dc
JH
164SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
165 &tcp_delack_enabled, 0,
984263bc
MD
166 "Delay ACK to try and piggyback it onto a data packet");
167
168#ifdef TCP_DROP_SYNFIN
169static int drop_synfin = 0;
170SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
171 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
172#endif
173
33abdd1c
MD
174static int tcp_do_limitedtransmit = 1;
175SYSCTL_INT(_net_inet_tcp, OID_AUTO, limitedtransmit, CTLFLAG_RW,
176 &tcp_do_limitedtransmit, 0, "Enable RFC 3042 (Limited Transmit)");
177
91489f6b 178static int tcp_do_early_retransmit = 1;
8819433a
JH
179SYSCTL_INT(_net_inet_tcp, OID_AUTO, earlyretransmit, CTLFLAG_RW,
180 &tcp_do_early_retransmit, 0, "Early retransmit");
181
4b52d5ee
JH
182static int tcp_do_rfc3390 = 1;
183SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
184 &tcp_do_rfc3390, 0,
185 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
186
efd4b327
JH
187static int tcp_do_eifel_detect = 1;
188SYSCTL_INT(_net_inet_tcp, OID_AUTO, eifel, CTLFLAG_RW,
189 &tcp_do_eifel_detect, 0, "Eifel detection algorithm (RFC 3522)");
190
91489f6b
JH
191/*
192 * Define as tunable for easy testing with SACK on and off.
193 * Warning: do not change setting in the middle of an existing active TCP flow,
194 * else strange things might happen to that flow.
195 */
86ac74c4 196int tcp_do_sack = 0;
91489f6b
JH
197SYSCTL_INT(_net_inet_tcp, OID_AUTO, sack, CTLFLAG_RW,
198 &tcp_do_sack, 0, "Enable SACK Algorithms");
199
200int tcp_do_smartsack = 1;
201SYSCTL_INT(_net_inet_tcp, OID_AUTO, smartsack, CTLFLAG_RW,
202 &tcp_do_smartsack, 0, "Enable Smart SACK Algorithms");
203
3edf7c37
RG
204SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
205 "TCP Segment Reassembly Queue");
206
207int tcp_reass_maxseg = 0;
208SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RD,
209 &tcp_reass_maxseg, 0,
210 "Global maximum number of TCP Segments in Reassembly Queue");
211
212int tcp_reass_qsize = 0;
213SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
214 &tcp_reass_qsize, 0,
215 "Global number of TCP Segments currently in Reassembly Queue");
216
217static int tcp_reass_overflows = 0;
218SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
219 &tcp_reass_overflows, 0,
220 "Global number of TCP Segment Reassembly Queue Overflows");
221
95b22adf 222static void tcp_dooptions(struct tcpopt *, u_char *, int, boolean_t);
984263bc
MD
223static void tcp_pulloutofband(struct socket *,
224 struct tcphdr *, struct mbuf *, int);
225static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
226 struct mbuf *);
227static void tcp_xmit_timer(struct tcpcb *, int);
91489f6b
JH
228static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *, int);
229static void tcp_sack_rexmt(struct tcpcb *, struct tcphdr *);
984263bc
MD
230
231/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
232#ifdef INET6
233#define ND6_HINT(tp) \
234do { \
235 if ((tp) && (tp)->t_inpcb && \
61896e3c 236 ((tp)->t_inpcb->inp_vflag & INP_IPV6) && \
984263bc
MD
237 (tp)->t_inpcb->in6p_route.ro_rt) \
238 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
239} while (0)
240#else
241#define ND6_HINT(tp)
242#endif
243
244/*
245 * Indicate whether this ack should be delayed. We can delay the ack if
246 * - delayed acks are enabled and
247 * - there is no delayed ack timer in progress and
248 * - our last ack wasn't a 0-sized window. We never want to delay
249 * the ack that opens up a 0-sized window.
250 */
251#define DELAY_ACK(tp) \
252 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
61896e3c 253 !(tp->t_flags & TF_RXWIN0SENT))
984263bc
MD
254
255static int
95b22adf 256tcp_reass(struct tcpcb *tp, struct tcphdr *th, int *tlenp, struct mbuf *m)
984263bc
MD
257{
258 struct tseg_qent *q;
259 struct tseg_qent *p = NULL;
984263bc
MD
260 struct tseg_qent *te;
261 struct socket *so = tp->t_inpcb->inp_socket;
262 int flags;
263
264 /*
61896e3c 265 * Call with th == NULL after become established to
984263bc
MD
266 * force pre-ESTABLISHED data up to user socket.
267 */
61896e3c 268 if (th == NULL)
984263bc
MD
269 goto present;
270
3edf7c37
RG
271 /*
272 * Limit the number of segments in the reassembly queue to prevent
273 * holding on to too many segments (and thus running out of mbufs).
274 * Make sure to let the missing segment through which caused this
275 * queue. Always keep one global queue entry spare to be able to
276 * process the missing segment.
277 */
278 if (th->th_seq != tp->rcv_nxt &&
279 tcp_reass_qsize + 1 >= tcp_reass_maxseg) {
280 tcp_reass_overflows++;
281 tcpstat.tcps_rcvmemdrop++;
282 m_freem(m);
91489f6b
JH
283 /* no SACK block to report */
284 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
3edf7c37
RG
285 return (0);
286 }
287
ba4e3dbe 288 /* Allocate a new queue entry. */
984263bc 289 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
ba4e3dbe 290 M_INTWAIT | M_NULLOK);
984263bc
MD
291 if (te == NULL) {
292 tcpstat.tcps_rcvmemdrop++;
293 m_freem(m);
91489f6b
JH
294 /* no SACK block to report */
295 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
984263bc
MD
296 return (0);
297 }
3edf7c37 298 tcp_reass_qsize++;
984263bc
MD
299
300 /*
301 * Find a segment which begins after this one does.
302 */
303 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
304 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
305 break;
306 p = q;
307 }
308
309 /*
310 * If there is a preceding segment, it may provide some of
311 * our data already. If so, drop the data from the incoming
312 * segment. If it provides all of our data, drop us.
313 */
314 if (p != NULL) {
2256ba69 315 int i;
91489f6b 316
984263bc
MD
317 /* conversion to int (in i) handles seq wraparound */
318 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
91489f6b
JH
319 if (i > 0) { /* overlaps preceding segment */
320 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
321 /* enclosing block starts w/ preceding segment */
322 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
984263bc 323 if (i >= *tlenp) {
91489f6b
JH
324 /* preceding encloses incoming segment */
325 tp->encloseblk.rblk_end = p->tqe_th->th_seq +
326 p->tqe_len;
984263bc
MD
327 tcpstat.tcps_rcvduppack++;
328 tcpstat.tcps_rcvdupbyte += *tlenp;
329 m_freem(m);
330 free(te, M_TSEGQ);
3edf7c37 331 tcp_reass_qsize--;
984263bc
MD
332 /*
333 * Try to present any queued data
334 * at the left window edge to the user.
335 * This is needed after the 3-WHS
336 * completes.
337 */
338 goto present; /* ??? */
339 }
340 m_adj(m, i);
341 *tlenp -= i;
342 th->th_seq += i;
91489f6b
JH
343 /* incoming segment end is enclosing block end */
344 tp->encloseblk.rblk_end = th->th_seq + *tlenp +
345 ((th->th_flags & TH_FIN) != 0);
346 /* trim end of reported D-SACK block */
347 tp->reportblk.rblk_end = th->th_seq;
984263bc
MD
348 }
349 }
350 tcpstat.tcps_rcvoopack++;
351 tcpstat.tcps_rcvoobyte += *tlenp;
352
353 /*
354 * While we overlap succeeding segments trim them or,
355 * if they are completely covered, dequeue them.
356 */
357 while (q) {
2256ba69 358 int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
91489f6b
JH
359 tcp_seq qend = q->tqe_th->th_seq + q->tqe_len;
360 struct tseg_qent *nq;
361
984263bc
MD
362 if (i <= 0)
363 break;
91489f6b
JH
364 if (!(tp->t_flags & TF_DUPSEG)) { /* first time through */
365 tp->t_flags |= (TF_DUPSEG | TF_ENCLOSESEG);
366 tp->encloseblk = tp->reportblk;
367 /* report trailing duplicate D-SACK segment */
368 tp->reportblk.rblk_start = q->tqe_th->th_seq;
369 }
370 if ((tp->t_flags & TF_ENCLOSESEG) &&
371 SEQ_GT(qend, tp->encloseblk.rblk_end)) {
372 /* extend enclosing block if one exists */
373 tp->encloseblk.rblk_end = qend;
374 }
984263bc
MD
375 if (i < q->tqe_len) {
376 q->tqe_th->th_seq += i;
377 q->tqe_len -= i;
378 m_adj(q->tqe_m, i);
379 break;
380 }
381
382 nq = LIST_NEXT(q, tqe_q);
383 LIST_REMOVE(q, tqe_q);
384 m_freem(q->tqe_m);
385 free(q, M_TSEGQ);
3edf7c37 386 tcp_reass_qsize--;
984263bc
MD
387 q = nq;
388 }
389
390 /* Insert the new segment queue entry into place. */
391 te->tqe_m = m;
392 te->tqe_th = th;
393 te->tqe_len = *tlenp;
394
91489f6b
JH
395 /* check if can coalesce with following segment */
396 if (q != NULL && (th->th_seq + *tlenp == q->tqe_th->th_seq)) {
397 tcp_seq tend = te->tqe_th->th_seq + te->tqe_len;
398
399 te->tqe_len += q->tqe_len;
400 m_cat(te->tqe_m, q->tqe_m);
401 tp->encloseblk.rblk_end = tend;
402 /*
403 * When not reporting a duplicate segment, use
404 * the larger enclosing block as the SACK block.
405 */
406 if (!(tp->t_flags & TF_DUPSEG))
407 tp->reportblk.rblk_end = tend;
408 LIST_REMOVE(q, tqe_q);
409 free(q, M_TSEGQ);
410 tcp_reass_qsize--;
411 }
412
984263bc
MD
413 if (p == NULL) {
414 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
415 } else {
91489f6b
JH
416 /* check if can coalesce with preceding segment */
417 if (p->tqe_th->th_seq + p->tqe_len == th->th_seq) {
418 p->tqe_len += *tlenp;
419 m_cat(p->tqe_m, m);
420 tp->encloseblk.rblk_start = p->tqe_th->th_seq;
421 /*
422 * When not reporting a duplicate segment, use
423 * the larger enclosing block as the SACK block.
424 */
425 if (!(tp->t_flags & TF_DUPSEG))
426 tp->reportblk.rblk_start = p->tqe_th->th_seq;
427 free(te, M_TSEGQ); tcp_reass_qsize--;
428 } else
429 LIST_INSERT_AFTER(p, te, tqe_q);
984263bc
MD
430 }
431
432present:
433 /*
434 * Present data to user, advancing rcv_nxt through
435 * completed sequence space.
436 */
437 if (!TCPS_HAVEESTABLISHED(tp->t_state))
438 return (0);
439 q = LIST_FIRST(&tp->t_segq);
61896e3c 440 if (q == NULL || q->tqe_th->th_seq != tp->rcv_nxt)
984263bc 441 return (0);
91489f6b
JH
442 tp->rcv_nxt += q->tqe_len;
443 if (!(tp->t_flags & TF_DUPSEG)) {
444 /* no SACK block to report since ACK advanced */
445 tp->reportblk.rblk_start = tp->reportblk.rblk_end;
446 }
447 /* no enclosing block to report since ACK advanced */
448 tp->t_flags &= ~TF_ENCLOSESEG;
449 flags = q->tqe_th->th_flags & TH_FIN;
450 LIST_REMOVE(q, tqe_q);
451 KASSERT(LIST_EMPTY(&tp->t_segq) ||
452 LIST_FIRST(&tp->t_segq)->tqe_th->th_seq != tp->rcv_nxt,
453 ("segment not coalesced"));
454 if (so->so_state & SS_CANTRCVMORE)
455 m_freem(q->tqe_m);
456 else
457 sbappend(&so->so_rcv, q->tqe_m);
458 free(q, M_TSEGQ);
459 tcp_reass_qsize--;
984263bc
MD
460 ND6_HINT(tp);
461 sorwakeup(so);
462 return (flags);
463}
464
465/*
466 * TCP input routine, follows pages 65-76 of the
467 * protocol specification dated September, 1981 very closely.
468 */
469#ifdef INET6
470int
95b22adf 471tcp6_input(struct mbuf **mp, int *offp, int proto)
984263bc 472{
2256ba69 473 struct mbuf *m = *mp;
984263bc
MD
474 struct in6_ifaddr *ia6;
475
476 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
477
478 /*
479 * draft-itojun-ipv6-tcp-to-anycast
480 * better place to put this in?
481 */
482 ia6 = ip6_getdstifaddr(m);
d24ce1dc 483 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
984263bc
MD
484 struct ip6_hdr *ip6;
485
486 ip6 = mtod(m, struct ip6_hdr *);
487 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
488 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
d24ce1dc 489 return (IPPROTO_DONE);
984263bc
MD
490 }
491
492 tcp_input(m, *offp, proto);
d24ce1dc 493 return (IPPROTO_DONE);
984263bc
MD
494}
495#endif
496
497void
a00138cb 498tcp_input(struct mbuf *m, ...)
984263bc 499{
a00138cb
JS
500 __va_list ap;
501 int off0, proto;
2256ba69
RG
502 struct tcphdr *th;
503 struct ip *ip = NULL;
504 struct ipovly *ipov;
505 struct inpcb *inp = NULL;
984263bc
MD
506 u_char *optp = NULL;
507 int optlen = 0;
508 int len, tlen, off;
509 int drop_hdrlen;
2256ba69
RG
510 struct tcpcb *tp = NULL;
511 int thflags;
984263bc 512 struct socket *so = 0;
61896e3c
JH
513 int todrop, acked;
514 boolean_t ourfinisacked, needoutput = FALSE;
984263bc 515 u_long tiwin;
61896e3c 516 int recvwin;
984263bc
MD
517 struct tcpopt to; /* options in this segment */
518 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
519 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
520 struct sockaddr_in *next_hop = NULL;
521 int rstreason; /* For badport_bandlim accounting purposes */
d371a63a 522 int cpu;
984263bc
MD
523 struct ip6_hdr *ip6 = NULL;
524#ifdef INET6
d24ce1dc 525 boolean_t isipv6;
984263bc 526#else
d24ce1dc 527 const boolean_t isipv6 = FALSE;
984263bc
MD
528#endif
529#ifdef TCPDEBUG
530 short ostate = 0;
531#endif
532
a00138cb
JS
533 __va_start(ap, m);
534 off0 = __va_arg(ap, int);
535 proto = __va_arg(ap, int);
536 __va_end(ap);
537
d24ce1dc
JH
538 tcpstat.tcps_rcvtotal++;
539
540 /* Grab info from and strip MT_TAG mbufs prepended to the chain. */
541 while (m->m_type == MT_TAG) {
984263bc
MD
542 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
543 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
d24ce1dc 544 m = m->m_next;
984263bc 545 }
d24ce1dc 546
984263bc 547#ifdef INET6
d24ce1dc 548 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? TRUE : FALSE;
984263bc 549#endif
984263bc
MD
550
551 if (isipv6) {
552 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
553 ip6 = mtod(m, struct ip6_hdr *);
554 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
555 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
556 tcpstat.tcps_rcvbadsum++;
557 goto drop;
558 }
559 th = (struct tcphdr *)((caddr_t)ip6 + off0);
560
561 /*
562 * Be proactive about unspecified IPv6 address in source.
563 * As we use all-zero to indicate unbounded/unconnected pcb,
564 * unspecified IPv6 address can be used to confuse us.
565 *
566 * Note that packets with unspecified IPv6 destination is
567 * already dropped in ip6_input.
568 */
569 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
570 /* XXX stat */
571 goto drop;
572 }
573 } else {
574 /*
575 * Get IP and TCP header together in first mbuf.
576 * Note: IP leaves IP header in first mbuf.
577 */
578 if (off0 > sizeof(struct ip)) {
bddf0751 579 ip_stripoptions(m);
984263bc
MD
580 off0 = sizeof(struct ip);
581 }
55d829f8
JH
582 /* already checked and pulled up in ip_demux() */
583 KASSERT(m->m_len >= sizeof(struct tcpiphdr),
61896e3c 584 ("TCP header not in one mbuf: m->m_len %d", m->m_len));
984263bc
MD
585 ip = mtod(m, struct ip *);
586 ipov = (struct ipovly *)ip;
587 th = (struct tcphdr *)((caddr_t)ip + off0);
588 tlen = ip->ip_len;
589
590 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
591 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
592 th->th_sum = m->m_pkthdr.csum_data;
593 else
594 th->th_sum = in_pseudo(ip->ip_src.s_addr,
595 ip->ip_dst.s_addr,
596 htonl(m->m_pkthdr.csum_data +
597 ip->ip_len +
598 IPPROTO_TCP));
599 th->th_sum ^= 0xffff;
600 } else {
601 /*
602 * Checksum extended TCP header and data.
603 */
604 len = sizeof(struct ip) + tlen;
605 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
606 ipov->ih_len = (u_short)tlen;
607 ipov->ih_len = htons(ipov->ih_len);
608 th->th_sum = in_cksum(m, len);
609 }
610 if (th->th_sum) {
611 tcpstat.tcps_rcvbadsum++;
612 goto drop;
613 }
614#ifdef INET6
615 /* Re-initialization for later version check */
616 ip->ip_v = IPVERSION;
617#endif
618 }
619
620 /*
621 * Check that TCP offset makes sense,
622 * pull out TCP options and adjust length. XXX
623 */
624 off = th->th_off << 2;
55d829f8
JH
625 /* already checked and pulled up in ip_demux() */
626 KASSERT(off >= sizeof(struct tcphdr) && off <= tlen,
61896e3c 627 ("bad TCP data offset %d (tlen %d)", off, tlen));
984263bc
MD
628 tlen -= off; /* tlen is used instead of ti->ti_len */
629 if (off > sizeof(struct tcphdr)) {
630 if (isipv6) {
631 IP6_EXTHDR_CHECK(m, off0, off, );
632 ip6 = mtod(m, struct ip6_hdr *);
633 th = (struct tcphdr *)((caddr_t)ip6 + off0);
634 } else {
55d829f8
JH
635 /* already pulled up in ip_demux() */
636 KASSERT(m->m_len >= sizeof(struct ip) + off,
61896e3c
JH
637 ("TCP header and options not in one mbuf: "
638 "m_len %d, off %d", m->m_len, off));
984263bc
MD
639 }
640 optlen = off - sizeof(struct tcphdr);
641 optp = (u_char *)(th + 1);
642 }
643 thflags = th->th_flags;
644
645#ifdef TCP_DROP_SYNFIN
646 /*
647 * If the drop_synfin option is enabled, drop all packets with
648 * both the SYN and FIN bits set. This prevents e.g. nmap from
649 * identifying the TCP/IP stack.
650 *
651 * This is a violation of the TCP specification.
652 */
61896e3c 653 if (drop_synfin && (thflags & (TH_SYN | TH_FIN)) == (TH_SYN | TH_FIN))
984263bc
MD
654 goto drop;
655#endif
656
657 /*
658 * Convert TCP protocol specific fields to host format.
659 */
660 th->th_seq = ntohl(th->th_seq);
661 th->th_ack = ntohl(th->th_ack);
662 th->th_win = ntohs(th->th_win);
663 th->th_urp = ntohs(th->th_urp);
664
665 /*
d24ce1dc 666 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
984263bc
MD
667 * until after ip6_savecontrol() is called and before other functions
668 * which don't want those proto headers.
669 * Because ip6_savecontrol() is going to parse the mbuf to
670 * search for data to be passed up to user-land, it wants mbuf
671 * parameters to be unchanged.
672 * XXX: the call of ip6_savecontrol() has been obsoleted based on
673 * latest version of the advanced API (20020110).
674 */
675 drop_hdrlen = off0 + off;
676
677 /*
678 * Locate pcb for segment.
679 */
680findpcb:
681 /* IPFIREWALL_FORWARD section */
d24ce1dc 682 if (next_hop != NULL && !isipv6) { /* IPv6 support is not there yet */
984263bc
MD
683 /*
684 * Transparently forwarded. Pretend to be the destination.
d24ce1dc 685 * already got one like this?
984263bc 686 */
6ca1a1cd 687 cpu = mycpu->gd_cpuid;
6ca1a1cd 688 inp = in_pcblookup_hash(&tcbinfo[cpu],
d371a63a 689 ip->ip_src, th->th_sport,
984263bc
MD
690 ip->ip_dst, th->th_dport,
691 0, m->m_pkthdr.rcvif);
692 if (!inp) {
83be63fe
JH
693 /*
694 * It's new. Try to find the ambushing socket.
695 */
696
697 /*
698 * The rest of the ipfw code stores the port in
699 * host order. XXX
700 * (The IP address is still in network order.)
701 */
702 in_port_t dport = next_hop->sin_port ?
703 htons(next_hop->sin_port) :
704 th->th_dport;
705
d371a63a 706 cpu = tcp_addrcpu(ip->ip_src.s_addr, th->th_sport,
83be63fe 707 next_hop->sin_addr.s_addr, dport);
d371a63a 708 inp = in_pcblookup_hash(&tcbinfo[cpu],
984263bc 709 ip->ip_src, th->th_sport,
83be63fe 710 next_hop->sin_addr, dport,
984263bc
MD
711 1, m->m_pkthdr.rcvif);
712 }
713 } else {
6ca1a1cd 714 if (isipv6) {
d371a63a 715 inp = in6_pcblookup_hash(&tcbinfo[0],
984263bc
MD
716 &ip6->ip6_src, th->th_sport,
717 &ip6->ip6_dst, th->th_dport,
718 1, m->m_pkthdr.rcvif);
6ca1a1cd 719 } else {
6ca1a1cd 720 cpu = mycpu->gd_cpuid;
6ca1a1cd 721 inp = in_pcblookup_hash(&tcbinfo[cpu],
984263bc
MD
722 ip->ip_src, th->th_sport,
723 ip->ip_dst, th->th_dport,
724 1, m->m_pkthdr.rcvif);
6ca1a1cd 725 }
984263bc 726 }
984263bc
MD
727
728 /*
729 * If the state is CLOSED (i.e., TCB does not exist) then
730 * all data in the incoming segment is discarded.
731 * If the TCB exists but is in CLOSED state, it is embryonic,
732 * but should either do a listen or a connect soon.
733 */
734 if (inp == NULL) {
735 if (log_in_vain) {
736#ifdef INET6
737 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
738#else
d24ce1dc 739 char dbuf[4 * sizeof "123"], sbuf[4 * sizeof "123"];
984263bc
MD
740#endif
741 if (isipv6) {
742 strcpy(dbuf, "[");
984263bc 743 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
984263bc 744 strcat(dbuf, "]");
95b22adf
JH
745 strcpy(sbuf, "[");
746 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
984263bc
MD
747 strcat(sbuf, "]");
748 } else {
749 strcpy(dbuf, inet_ntoa(ip->ip_dst));
750 strcpy(sbuf, inet_ntoa(ip->ip_src));
751 }
752 switch (log_in_vain) {
753 case 1:
61896e3c 754 if (!(thflags & TH_SYN))
984263bc
MD
755 break;
756 case 2:
757 log(LOG_INFO,
758 "Connection attempt to TCP %s:%d "
759 "from %s:%d flags:0x%02x\n",
760 dbuf, ntohs(th->th_dport), sbuf,
761 ntohs(th->th_sport), thflags);
762 break;
763 default:
764 break;
765 }
766 }
d24ce1dc 767 if (blackhole) {
984263bc
MD
768 switch (blackhole) {
769 case 1:
770 if (thflags & TH_SYN)
771 goto drop;
772 break;
773 case 2:
774 goto drop;
775 default:
776 goto drop;
777 }
778 }
779 rstreason = BANDLIM_RST_CLOSEDPORT;
780 goto dropwithreset;
781 }
61896e3c
JH
782
783#ifdef IPSEC
784 if (isipv6) {
785 if (ipsec6_in_reject_so(m, inp->inp_socket)) {
786 ipsec6stat.in_polvio++;
787 goto drop;
788 }
789 } else {
790 if (ipsec4_in_reject_so(m, inp->inp_socket)) {
791 ipsecstat.in_polvio++;
792 goto drop;
793 }
794 }
795#endif
796#ifdef FAST_IPSEC
797 if (isipv6) {
798 if (ipsec6_in_reject(m, inp))
799 goto drop;
800 } else {
801 if (ipsec4_in_reject(m, inp))
802 goto drop;
803 }
804#endif
805
984263bc
MD
806 tp = intotcpcb(inp);
807 if (tp == NULL) {
808 rstreason = BANDLIM_RST_CLOSEDPORT;
809 goto dropwithreset;
810 }
eb594563 811 if (tp->t_state <= TCPS_CLOSED)
984263bc
MD
812 goto drop;
813
814 /* Unscale the window into a 32-bit value. */
95b22adf 815 if (!(thflags & TH_SYN))
984263bc
MD
816 tiwin = th->th_win << tp->snd_scale;
817 else
818 tiwin = th->th_win;
819
820 so = inp->inp_socket;
47654766 821
984263bc 822#ifdef TCPDEBUG
47654766
JH
823 if (so->so_options & SO_DEBUG) {
824 ostate = tp->t_state;
825 if (isipv6)
95b22adf 826 bcopy(ip6, tcp_saveipgen, sizeof(*ip6));
47654766 827 else
95b22adf 828 bcopy(ip, tcp_saveipgen, sizeof(*ip));
47654766
JH
829 tcp_savetcp = *th;
830 }
984263bc 831#endif
47654766 832
95b22adf 833 bzero(&to, sizeof(to));
d24ce1dc 834
47654766
JH
835 if (so->so_options & SO_ACCEPTCONN) {
836 struct in_conninfo inc;
837
984263bc 838#ifdef INET6
d24ce1dc 839 inc.inc_isipv6 = (isipv6 == TRUE);
984263bc
MD
840#endif
841 if (isipv6) {
842 inc.inc6_faddr = ip6->ip6_src;
843 inc.inc6_laddr = ip6->ip6_dst;
844 inc.inc6_route.ro_rt = NULL; /* XXX */
845 } else {
846 inc.inc_faddr = ip->ip_src;
847 inc.inc_laddr = ip->ip_dst;
848 inc.inc_route.ro_rt = NULL; /* XXX */
849 }
850 inc.inc_fport = th->th_sport;
851 inc.inc_lport = th->th_dport;
852
61896e3c
JH
853 /*
854 * If the state is LISTEN then ignore segment if it contains
984263bc
MD
855 * a RST. If the segment contains an ACK then it is bad and
856 * send a RST. If it does not contain a SYN then it is not
857 * interesting; drop it.
858 *
859 * If the state is SYN_RECEIVED (syncache) and seg contains
860 * an ACK, but not for our SYN/ACK, send a RST. If the seg
861 * contains a RST, check the sequence number to see if it
862 * is a valid reset segment.
863 */
61896e3c
JH
864 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) != TH_SYN) {
865 if ((thflags & (TH_RST | TH_ACK | TH_SYN)) == TH_ACK) {
984263bc
MD
866 if (!syncache_expand(&inc, th, &so, m)) {
867 /*
868 * No syncache entry, or ACK was not
869 * for our SYN/ACK. Send a RST.
870 */
871 tcpstat.tcps_badsyn++;
872 rstreason = BANDLIM_RST_OPENPORT;
873 goto dropwithreset;
874 }
875 if (so == NULL)
876 /*
877 * Could not complete 3-way handshake,
878 * connection is being closed down, and
879 * syncache will free mbuf.
880 */
881 return;
882 /*
883 * Socket is created in state SYN_RECEIVED.
884 * Continue processing segment.
885 */
886 inp = sotoinpcb(so);
887 tp = intotcpcb(inp);
888 /*
889 * This is what would have happened in
890 * tcp_output() when the SYN,ACK was sent.
891 */
892 tp->snd_up = tp->snd_una;
893 tp->snd_max = tp->snd_nxt = tp->iss + 1;
894 tp->last_ack_sent = tp->rcv_nxt;
895/*
896 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
897 * until the _second_ ACK is received:
898 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
899 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
61896e3c 900 * move to ESTAB, set snd_wnd to tiwin.
d24ce1dc 901 */
984263bc
MD
902 tp->snd_wnd = tiwin; /* unscaled */
903 goto after_listen;
904 }
905 if (thflags & TH_RST) {
906 syncache_chkrst(&inc, th);
907 goto drop;
908 }
909 if (thflags & TH_ACK) {
910 syncache_badack(&inc);
911 tcpstat.tcps_badsyn++;
912 rstreason = BANDLIM_RST_OPENPORT;
913 goto dropwithreset;
914 }
915 goto drop;
916 }
917
918 /*
61896e3c 919 * Segment's flags are (SYN) or (SYN | FIN).
984263bc
MD
920 */
921#ifdef INET6
922 /*
923 * If deprecated address is forbidden,
924 * we do not accept SYN to deprecated interface
925 * address to prevent any new inbound connection from
926 * getting established.
927 * When we do not accept SYN, we send a TCP RST,
928 * with deprecated source address (instead of dropping
929 * it). We compromise it as it is much better for peer
930 * to send a RST, and RST will be the final packet
931 * for the exchange.
932 *
933 * If we do not forbid deprecated addresses, we accept
934 * the SYN packet. RFC2462 does not suggest dropping
935 * SYN in this case.
936 * If we decipher RFC2462 5.5.4, it says like this:
937 * 1. use of deprecated addr with existing
938 * communication is okay - "SHOULD continue to be
939 * used"
940 * 2. use of it with new communication:
941 * (2a) "SHOULD NOT be used if alternate address
61896e3c 942 * with sufficient scope is available"
984263bc
MD
943 * (2b) nothing mentioned otherwise.
944 * Here we fall into (2b) case as we have no choice in
945 * our source address selection - we must obey the peer.
946 *
947 * The wording in RFC2462 is confusing, and there are
948 * multiple description text for deprecated address
949 * handling - worse, they are not exactly the same.
950 * I believe 5.5.4 is the best one, so we follow 5.5.4.
951 */
952 if (isipv6 && !ip6_use_deprecated) {
953 struct in6_ifaddr *ia6;
954
955 if ((ia6 = ip6_getdstifaddr(m)) &&
956 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
957 tp = NULL;
958 rstreason = BANDLIM_RST_OPENPORT;
959 goto dropwithreset;
960 }
961 }
962#endif
963 /*
964 * If it is from this socket, drop it, it must be forged.
965 * Don't bother responding if the destination was a broadcast.
966 */
967 if (th->th_dport == th->th_sport) {
968 if (isipv6) {
969 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
970 &ip6->ip6_src))
971 goto drop;
972 } else {
973 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
974 goto drop;
975 }
976 }
977 /*
978 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
979 *
980 * Note that it is quite possible to receive unicast
981 * link-layer packets with a broadcast IP address. Use
982 * in_broadcast() to find them.
983 */
61896e3c 984 if (m->m_flags & (M_BCAST | M_MCAST))
984263bc
MD
985 goto drop;
986 if (isipv6) {
987 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
988 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
989 goto drop;
990 } else {
991 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
992 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
993 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
994 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
995 goto drop;
996 }
997 /*
998 * SYN appears to be valid; create compressed TCP state
999 * for syncache, or perform t/tcp connection.
1000 */
1001 if (so->so_qlen <= so->so_qlimit) {
95b22adf 1002 tcp_dooptions(&to, optp, optlen, TRUE);
984263bc
MD
1003 if (!syncache_add(&inc, &to, th, &so, m))
1004 goto drop;
1005 if (so == NULL)
1006 /*
1007 * Entry added to syncache, mbuf used to
1008 * send SYN,ACK packet.
1009 */
1010 return;
1011 /*
1012 * Segment passed TAO tests.
1013 */
1014 inp = sotoinpcb(so);
1015 tp = intotcpcb(inp);
1016 tp->snd_wnd = tiwin;
1017 tp->t_starttime = ticks;
1018 tp->t_state = TCPS_ESTABLISHED;
1019
1020 /*
1021 * If there is a FIN, or if there is data and the
1022 * connection is local, then delay SYN,ACK(SYN) in
1023 * the hope of piggy-backing it on a response
1024 * segment. Otherwise must send ACK now in case
1025 * the other side is slow starting.
1026 */
1027 if (DELAY_ACK(tp) &&
1028 ((thflags & TH_FIN) ||
1029 (tlen != 0 &&
1030 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
1031 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
d24ce1dc
JH
1032 callout_reset(tp->tt_delack, tcp_delacktime,
1033 tcp_timer_delack, tp);
984263bc 1034 tp->t_flags |= TF_NEEDSYN;
d24ce1dc 1035 } else
984263bc
MD
1036 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1037
1038 tcpstat.tcps_connects++;
1039 soisconnected(so);
1040 goto trimthenstep6;
1041 }
1042 goto drop;
1043 }
1044after_listen:
1045
984263bc 1046 /* should not happen - syncache should pick up these connections */
61896e3c 1047 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN state"));
984263bc
MD
1048
1049 /*
1050 * Segment received on connection.
1051 * Reset idle time and keep-alive timer.
1052 */
1053 tp->t_rcvtime = ticks;
1054 if (TCPS_HAVEESTABLISHED(tp->t_state))
1055 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1056
1057 /*
1058 * Process options.
1059 * XXX this is tradtitional behavior, may need to be cleaned up.
1060 */
95b22adf 1061 tcp_dooptions(&to, optp, optlen, (thflags & TH_SYN) != 0);
984263bc
MD
1062 if (thflags & TH_SYN) {
1063 if (to.to_flags & TOF_SCALE) {
1064 tp->t_flags |= TF_RCVD_SCALE;
1065 tp->requested_s_scale = to.to_requested_s_scale;
1066 }
1067 if (to.to_flags & TOF_TS) {
1068 tp->t_flags |= TF_RCVD_TSTMP;
1069 tp->ts_recent = to.to_tsval;
1070 tp->ts_recent_age = ticks;
1071 }
61896e3c 1072 if (to.to_flags & (TOF_CC | TOF_CCNEW))
984263bc
MD
1073 tp->t_flags |= TF_RCVD_CC;
1074 if (to.to_flags & TOF_MSS)
1075 tcp_mss(tp, to.to_mss);
91489f6b
JH
1076 /*
1077 * Only set the TF_SACK_PERMITTED per-connection flag
1078 * if we got a SACK_PERMITTED option from the other side
1079 * and the global tcp_do_sack variable is true.
1080 */
1081 if (tcp_do_sack && (to.to_flags & TOF_SACK_PERMITTED))
1082 tp->t_flags |= TF_SACK_PERMITTED;
984263bc
MD
1083 }
1084
1085 /*
1086 * Header prediction: check for the two common cases
1087 * of a uni-directional data xfer. If the packet has
1088 * no control flags, is in-sequence, the window didn't
1089 * change and we're not retransmitting, it's a
1090 * candidate. If the length is zero and the ack moved
1091 * forward, we're the sender side of the xfer. Just
1092 * free the data acked & wake any higher level process
1093 * that was blocked waiting for space. If the length
1094 * is non-zero and the ack didn't move, we're the
1095 * receiver side. If we're getting packets in-order
1096 * (the reassembly queue is empty), add the data to
1097 * the socket buffer and note that we need a delayed ack.
1098 * Make sure that the hidden state-flags are also off.
1099 * Since we check for TCPS_ESTABLISHED above, it can only
1100 * be TH_NEEDSYN.
1101 */
1102 if (tp->t_state == TCPS_ESTABLISHED &&
1103 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
61896e3c
JH
1104 !(tp->t_flags & (TF_NEEDSYN | TF_NEEDFIN)) &&
1105 (!(to.to_flags & TOF_TS) ||
984263bc
MD
1106 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1107 /*
1108 * Using the CC option is compulsory if once started:
1109 * the segment is OK if no T/TCP was negotiated or
1110 * if the segment has a CC option equal to CCrecv
1111 */
1112 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
61896e3c 1113 ((to.to_flags & TOF_CC) && to.to_cc == tp->cc_recv)) &&
984263bc
MD
1114 th->th_seq == tp->rcv_nxt &&
1115 tiwin && tiwin == tp->snd_wnd &&
1116 tp->snd_nxt == tp->snd_max) {
1117
1118 /*
1119 * If last ACK falls within this segment's sequence numbers,
1120 * record the timestamp.
1121 * NOTE that the test is modified according to the latest
1122 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1123 */
61896e3c 1124 if ((to.to_flags & TOF_TS) &&
984263bc
MD
1125 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1126 tp->ts_recent_age = ticks;
1127 tp->ts_recent = to.to_tsval;
1128 }
1129
1130 if (tlen == 0) {
1131 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1132 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1133 tp->snd_cwnd >= tp->snd_wnd &&
95b22adf 1134 !IN_FASTRECOVERY(tp)) {
984263bc
MD
1135 /*
1136 * this is a pure ack for outstanding data.
1137 */
1138 ++tcpstat.tcps_predack;
1139 /*
1140 * "bad retransmit" recovery
bfdb979e
JH
1141 *
1142 * If Eifel detection applies, then
1143 * it is deterministic, so use it
1144 * unconditionally over the old heuristic.
1145 * Otherwise, fall back to the old heuristic.
984263bc 1146 */
bfdb979e
JH
1147 if (tcp_do_eifel_detect &&
1148 (to.to_flags & TOF_TS) && to.to_tsecr &&
1149 (tp->t_flags & TF_FIRSTACCACK)) {
1150 /* Eifel detection applicable. */
1151 if (to.to_tsecr < tp->t_rexmtTS) {
1152 tcp_revert_congestion_state(tp);
1153 ++tcpstat.tcps_eifeldetected;
1154 }
1155 } else if (tp->t_rxtshift == 1 &&
1156 ticks < tp->t_badrxtwin) {
1157 tcp_revert_congestion_state(tp);
1158 ++tcpstat.tcps_rttdetected;
984263bc 1159 }
8819433a
JH
1160 tp->t_flags &= ~(TF_FIRSTACCACK |
1161 TF_FASTREXMT | TF_EARLYREXMT);
984263bc
MD
1162 /*
1163 * Recalculate the retransmit timer / rtt.
1164 *
d24ce1dc 1165 * Some machines (certain windows boxes)
984263bc
MD
1166 * send broken timestamp replies during the
1167 * SYN+ACK phase, ignore timestamps of 0.
1168 */
95b22adf 1169 if ((to.to_flags & TOF_TS) && to.to_tsecr) {
984263bc 1170 tcp_xmit_timer(tp,
95b22adf 1171 ticks - to.to_tsecr + 1);
984263bc 1172 } else if (tp->t_rtttime &&
95b22adf 1173 SEQ_GT(th->th_ack, tp->t_rtseq)) {
984263bc
MD
1174 tcp_xmit_timer(tp,
1175 ticks - tp->t_rtttime);
1176 }
1177 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1178 acked = th->th_ack - tp->snd_una;
1179 tcpstat.tcps_rcvackpack++;
1180 tcpstat.tcps_rcvackbyte += acked;
1181 sbdrop(&so->so_snd, acked);
cfb3f3f4 1182 tp->snd_recover = th->th_ack - 1;
9845754e 1183 tp->snd_una = th->th_ack;
984263bc
MD
1184 tp->t_dupacks = 0;
1185 m_freem(m);
1186 ND6_HINT(tp); /* some progress has been done */
1187
1188 /*
1189 * If all outstanding data are acked, stop
1190 * retransmit timer, otherwise restart timer
1191 * using current (possibly backed-off) value.
1192 * If process is waiting for space,
1193 * wakeup/selwakeup/signal. If data
1194 * are ready to send, let tcp_output
1195 * decide between more output or persist.
1196 */
1197 if (tp->snd_una == tp->snd_max)
1198 callout_stop(tp->tt_rexmt);
1199 else if (!callout_active(tp->tt_persist))
d24ce1dc 1200 callout_reset(tp->tt_rexmt,
984263bc
MD
1201 tp->t_rxtcur,
1202 tcp_timer_rexmt, tp);
1203
1204 sowwakeup(so);
1205 if (so->so_snd.sb_cc)
1206 (void) tcp_output(tp);
1207 return;
1208 }
1209 } else if (th->th_ack == tp->snd_una &&
1210 LIST_EMPTY(&tp->t_segq) &&
1211 tlen <= sbspace(&so->so_rcv)) {
1212 /*
1213 * this is a pure, in-sequence data packet
1214 * with nothing on the reassembly queue and
1215 * we have enough buffer space to take it.
1216 */
1217 ++tcpstat.tcps_preddat;
1218 tp->rcv_nxt += tlen;
1219 tcpstat.tcps_rcvpack++;
1220 tcpstat.tcps_rcvbyte += tlen;
1221 ND6_HINT(tp); /* some progress has been done */
1222 /*
1223 * Add data to socket buffer.
1224 */
1225 if (so->so_state & SS_CANTRCVMORE) {
1226 m_freem(m);
1227 } else {
09cf73e0 1228 m_adj(m, drop_hdrlen); /* delayed header drop */
984263bc
MD
1229 sbappend(&so->so_rcv, m);
1230 }
1231 sorwakeup(so);
2b1ce38a
MD
1232
1233 /*
1234 * This code is responsible for most of the ACKs
1235 * the TCP stack sends back after receiving a data
1236 * packet. Note that the DELAY_ACK check fails if
1237 * the delack timer is already running, which results
1238 * in an ack being sent every other packet (which is
1239 * what we want).
1240 */
984263bc 1241 if (DELAY_ACK(tp)) {
61896e3c
JH
1242 callout_reset(tp->tt_delack, tcp_delacktime,
1243 tcp_timer_delack, tp);
984263bc
MD
1244 } else {
1245 tp->t_flags |= TF_ACKNOW;
61896e3c 1246 if (!(tp->t_flags & TF_ONOUTPUTQ)) {
2b1ce38a
MD
1247 tp->t_flags |= TF_ONOUTPUTQ;
1248 tp->tt_cpu = mycpu->gd_cpuid;
1249 TAILQ_INSERT_TAIL(
1250 &tcpcbackq[tp->tt_cpu],
1251 tp, t_outputq);
1252 }
984263bc
MD
1253 }
1254 return;
1255 }
1256 }
1257
1258 /*
1259 * Calculate amount of space in receive window,
1260 * and then do TCP input processing.
1261 * Receive window is amount of space in rcv queue,
1262 * but not less than advertised window.
1263 */
61896e3c
JH
1264 recvwin = sbspace(&so->so_rcv);
1265 if (recvwin < 0)
1266 recvwin = 0;
1267 tp->rcv_wnd = imax(recvwin, (int)(tp->rcv_adv - tp->rcv_nxt));
984263bc
MD
1268
1269 switch (tp->t_state) {
984263bc
MD
1270 /*
1271 * If the state is SYN_RECEIVED:
1272 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1273 */
1274 case TCPS_SYN_RECEIVED:
1275 if ((thflags & TH_ACK) &&
1276 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1277 SEQ_GT(th->th_ack, tp->snd_max))) {
1278 rstreason = BANDLIM_RST_OPENPORT;
1279 goto dropwithreset;
1280 }
1281 break;
1282
1283 /*
1284 * If the state is SYN_SENT:
1285 * if seg contains an ACK, but not for our SYN, drop the input.
1286 * if seg contains a RST, then drop the connection.
1287 * if seg does not contain SYN, then drop it.
1288 * Otherwise this is an acceptable SYN segment
1289 * initialize tp->rcv_nxt and tp->irs
1290 * if seg contains ack then advance tp->snd_una
1291 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1292 * arrange for segment to be acked (eventually)
1293 * continue processing rest of data/controls, beginning with URG
1294 */
1295 case TCPS_SYN_SENT:
1296 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1297 taop = &tao_noncached;
1298 bzero(taop, sizeof(*taop));
1299 }
1300
1301 if ((thflags & TH_ACK) &&
1302 (SEQ_LEQ(th->th_ack, tp->iss) ||
1303 SEQ_GT(th->th_ack, tp->snd_max))) {
1304 /*
1305 * If we have a cached CCsent for the remote host,
1306 * hence we haven't just crashed and restarted,
1307 * do not send a RST. This may be a retransmission
1308 * from the other side after our earlier ACK was lost.
1309 * Our new SYN, when it arrives, will serve as the
1310 * needed ACK.
1311 */
1312 if (taop->tao_ccsent != 0)
1313 goto drop;
1314 else {
1315 rstreason = BANDLIM_UNLIMITED;
1316 goto dropwithreset;
1317 }
1318 }
1319 if (thflags & TH_RST) {
1320 if (thflags & TH_ACK)
1321 tp = tcp_drop(tp, ECONNREFUSED);
1322 goto drop;
1323 }
61896e3c 1324 if (!(thflags & TH_SYN))
984263bc
MD
1325 goto drop;
1326 tp->snd_wnd = th->th_win; /* initial send window */
1327 tp->cc_recv = to.to_cc; /* foreign CC */
1328
1329 tp->irs = th->th_seq;
1330 tcp_rcvseqinit(tp);
1331 if (thflags & TH_ACK) {
1332 /*
1333 * Our SYN was acked. If segment contains CC.ECHO
1334 * option, check it to make sure this segment really
1335 * matches our SYN. If not, just drop it as old
1336 * duplicate, but send an RST if we're still playing
1337 * by the old rules. If no CC.ECHO option, make sure
1338 * we don't get fooled into using T/TCP.
1339 */
1340 if (to.to_flags & TOF_CCECHO) {
1341 if (tp->cc_send != to.to_ccecho) {
1342 if (taop->tao_ccsent != 0)
1343 goto drop;
1344 else {
1345 rstreason = BANDLIM_UNLIMITED;
1346 goto dropwithreset;
1347 }
1348 }
1349 } else
1350 tp->t_flags &= ~TF_RCVD_CC;
1351 tcpstat.tcps_connects++;
1352 soisconnected(so);
1353 /* Do window scaling on this connection? */
61896e3c 1354 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
b5572302 1355 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
984263bc
MD
1356 tp->snd_scale = tp->requested_s_scale;
1357 tp->rcv_scale = tp->request_r_scale;
1358 }
1359 /* Segment is acceptable, update cache if undefined. */
1360 if (taop->tao_ccsent == 0)
1361 taop->tao_ccsent = to.to_ccecho;
1362
1363 tp->rcv_adv += tp->rcv_wnd;
1364 tp->snd_una++; /* SYN is acked */
91489f6b 1365 callout_stop(tp->tt_rexmt);
984263bc
MD
1366 /*
1367 * If there's data, delay ACK; if there's also a FIN
1368 * ACKNOW will be turned on later.
1369 */
1370 if (DELAY_ACK(tp) && tlen != 0)
61896e3c
JH
1371 callout_reset(tp->tt_delack, tcp_delacktime,
1372 tcp_timer_delack, tp);
984263bc
MD
1373 else
1374 tp->t_flags |= TF_ACKNOW;
1375 /*
1376 * Received <SYN,ACK> in SYN_SENT[*] state.
1377 * Transitions:
1378 * SYN_SENT --> ESTABLISHED
1379 * SYN_SENT* --> FIN_WAIT_1
1380 */
1381 tp->t_starttime = ticks;
1382 if (tp->t_flags & TF_NEEDFIN) {
1383 tp->t_state = TCPS_FIN_WAIT_1;
1384 tp->t_flags &= ~TF_NEEDFIN;
1385 thflags &= ~TH_SYN;
1386 } else {
1387 tp->t_state = TCPS_ESTABLISHED;
1388 callout_reset(tp->tt_keep, tcp_keepidle,
1389 tcp_timer_keep, tp);
1390 }
1391 } else {
1392 /*
95b22adf
JH
1393 * Received initial SYN in SYN-SENT[*] state =>
1394 * simultaneous open. If segment contains CC option
1395 * and there is a cached CC, apply TAO test.
1396 * If it succeeds, connection is * half-synchronized.
1397 * Otherwise, do 3-way handshake:
61896e3c
JH
1398 * SYN-SENT -> SYN-RECEIVED
1399 * SYN-SENT* -> SYN-RECEIVED*
95b22adf
JH
1400 * If there was no CC option, clear cached CC value.
1401 */
984263bc
MD
1402 tp->t_flags |= TF_ACKNOW;
1403 callout_stop(tp->tt_rexmt);
1404 if (to.to_flags & TOF_CC) {
1405 if (taop->tao_cc != 0 &&
1406 CC_GT(to.to_cc, taop->tao_cc)) {
1407 /*
1408 * update cache and make transition:
61896e3c
JH
1409 * SYN-SENT -> ESTABLISHED*
1410 * SYN-SENT* -> FIN-WAIT-1*
984263bc
MD
1411 */
1412 taop->tao_cc = to.to_cc;
1413 tp->t_starttime = ticks;
1414 if (tp->t_flags & TF_NEEDFIN) {
1415 tp->t_state = TCPS_FIN_WAIT_1;
1416 tp->t_flags &= ~TF_NEEDFIN;
1417 } else {
1418 tp->t_state = TCPS_ESTABLISHED;
1419 callout_reset(tp->tt_keep,
1420 tcp_keepidle,
1421 tcp_timer_keep,
1422 tp);
1423 }
1424 tp->t_flags |= TF_NEEDSYN;
1425 } else
1426 tp->t_state = TCPS_SYN_RECEIVED;
1427 } else {
1428 /* CC.NEW or no option => invalidate cache */
1429 taop->tao_cc = 0;
1430 tp->t_state = TCPS_SYN_RECEIVED;
1431 }
1432 }
1433
1434trimthenstep6:
1435 /*
1436 * Advance th->th_seq to correspond to first data byte.
1437 * If data, trim to stay within window,
1438 * dropping FIN if necessary.
1439 */
1440 th->th_seq++;
1441 if (tlen > tp->rcv_wnd) {
1442 todrop = tlen - tp->rcv_wnd;
1443 m_adj(m, -todrop);
1444 tlen = tp->rcv_wnd;
1445 thflags &= ~TH_FIN;
1446 tcpstat.tcps_rcvpackafterwin++;
1447 tcpstat.tcps_rcvbyteafterwin += todrop;
1448 }
1449 tp->snd_wl1 = th->th_seq - 1;
1450 tp->rcv_up = th->th_seq;
1451 /*
1452 * Client side of transaction: already sent SYN and data.
1453 * If the remote host used T/TCP to validate the SYN,
1454 * our data will be ACK'd; if so, enter normal data segment
1455 * processing in the middle of step 5, ack processing.
1456 * Otherwise, goto step 6.
1457 */
95b22adf 1458 if (thflags & TH_ACK)
984263bc
MD
1459 goto process_ACK;
1460
1461 goto step6;
1462
1463 /*
1464 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1465 * if segment contains a SYN and CC [not CC.NEW] option:
61896e3c
JH
1466 * if state == TIME_WAIT and connection duration > MSL,
1467 * drop packet and send RST;
984263bc
MD
1468 *
1469 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1470 * ack the FIN (and data) in retransmission queue.
61896e3c
JH
1471 * Complete close and delete TCPCB. Then reprocess
1472 * segment, hoping to find new TCPCB in LISTEN state;
984263bc
MD
1473 *
1474 * else must be old SYN; drop it.
61896e3c 1475 * else do normal processing.
984263bc
MD
1476 */
1477 case TCPS_LAST_ACK:
1478 case TCPS_CLOSING:
1479 case TCPS_TIME_WAIT:
1480 if ((thflags & TH_SYN) &&
1481 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1482 if (tp->t_state == TCPS_TIME_WAIT &&
1483 (ticks - tp->t_starttime) > tcp_msl) {
1484 rstreason = BANDLIM_UNLIMITED;
1485 goto dropwithreset;
1486 }
1487 if (CC_GT(to.to_cc, tp->cc_recv)) {
1488 tp = tcp_close(tp);
1489 goto findpcb;
1490 }
1491 else
1492 goto drop;
1493 }
95b22adf 1494 break; /* continue normal processing */
984263bc
MD
1495 }
1496
1497 /*
1498 * States other than LISTEN or SYN_SENT.
1499 * First check the RST flag and sequence number since reset segments
1500 * are exempt from the timestamp and connection count tests. This
1501 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1502 * below which allowed reset segments in half the sequence space
1503 * to fall though and be processed (which gives forged reset
1504 * segments with a random sequence number a 50 percent chance of
1505 * killing a connection).
1506 * Then check timestamp, if present.
1507 * Then check the connection count, if present.
1508 * Then check that at least some bytes of segment are within
1509 * receive window. If segment begins before rcv_nxt,
1510 * drop leading data (and SYN); if nothing left, just ack.
1511 *
1512 *
1513 * If the RST bit is set, check the sequence number to see
1514 * if this is a valid reset segment.
1515 * RFC 793 page 37:
1516 * In all states except SYN-SENT, all reset (RST) segments
1517 * are validated by checking their SEQ-fields. A reset is
1518 * valid if its sequence number is in the window.
1519 * Note: this does not take into account delayed ACKs, so
1520 * we should test against last_ack_sent instead of rcv_nxt.
1521 * The sequence number in the reset segment is normally an
91489f6b 1522 * echo of our outgoing acknowledgement numbers, but some hosts
984263bc
MD
1523 * send a reset with the sequence number at the rightmost edge
1524 * of our receive window, and we have to handle this case.
1525 * If we have multiple segments in flight, the intial reset
1526 * segment sequence numbers will be to the left of last_ack_sent,
1527 * but they will eventually catch up.
1528 * In any case, it never made sense to trim reset segments to
1529 * fit the receive window since RFC 1122 says:
1530 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1531 *
1532 * A TCP SHOULD allow a received RST segment to include data.
1533 *
1534 * DISCUSSION
61896e3c
JH
1535 * It has been suggested that a RST segment could contain
1536 * ASCII text that encoded and explained the cause of the
91489f6b 1537 * RST. No standard has yet been established for such
61896e3c 1538 * data.
984263bc
MD
1539 *
1540 * If the reset segment passes the sequence number test examine
1541 * the state:
1542 * SYN_RECEIVED STATE:
1543 * If passive open, return to LISTEN state.
1544 * If active open, inform user that connection was refused.
1545 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1546 * Inform user that connection was reset, and close tcb.
1547 * CLOSING, LAST_ACK STATES:
1548 * Close the tcb.
1549 * TIME_WAIT STATE:
1550 * Drop the segment - see Stevens, vol. 2, p. 964 and
61896e3c 1551 * RFC 1337.
984263bc
MD
1552 */
1553 if (thflags & TH_RST) {
1554 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1555 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1556 switch (tp->t_state) {
1557
1558 case TCPS_SYN_RECEIVED:
1559 so->so_error = ECONNREFUSED;
1560 goto close;
1561
1562 case TCPS_ESTABLISHED:
1563 case TCPS_FIN_WAIT_1:
1564 case TCPS_FIN_WAIT_2:
1565 case TCPS_CLOSE_WAIT:
1566 so->so_error = ECONNRESET;
1567 close:
1568 tp->t_state = TCPS_CLOSED;
1569 tcpstat.tcps_drops++;
1570 tp = tcp_close(tp);
1571 break;
1572
1573 case TCPS_CLOSING:
1574 case TCPS_LAST_ACK:
1575 tp = tcp_close(tp);
1576 break;
1577
1578 case TCPS_TIME_WAIT:
1579 break;
1580 }
1581 }
1582 goto drop;
1583 }
1584
1585 /*
1586 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1587 * and it's less than ts_recent, drop it.
1588 */
61896e3c 1589 if ((to.to_flags & TOF_TS) && tp->ts_recent != 0 &&
984263bc
MD
1590 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1591
1592 /* Check to see if ts_recent is over 24 days old. */
1593 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1594 /*
1595 * Invalidate ts_recent. If this segment updates
1596 * ts_recent, the age will be reset later and ts_recent
1597 * will get a valid value. If it does not, setting
1598 * ts_recent to zero will at least satisfy the
1599 * requirement that zero be placed in the timestamp
1600 * echo reply when ts_recent isn't valid. The
1601 * age isn't reset until we get a valid ts_recent
1602 * because we don't want out-of-order segments to be
1603 * dropped when ts_recent is old.
1604 */
1605 tp->ts_recent = 0;
1606 } else {
1607 tcpstat.tcps_rcvduppack++;
1608 tcpstat.tcps_rcvdupbyte += tlen;
1609 tcpstat.tcps_pawsdrop++;
1610 if (tlen)
1611 goto dropafterack;
1612 goto drop;
1613 }
1614 }
1615
1616 /*
1617 * T/TCP mechanism
1618 * If T/TCP was negotiated and the segment doesn't have CC,
1619 * or if its CC is wrong then drop the segment.
1620 * RST segments do not have to comply with this.
1621 */
1622 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
61896e3c 1623 (!(to.to_flags & TOF_CC) || tp->cc_recv != to.to_cc))
95b22adf 1624 goto dropafterack;
984263bc
MD
1625
1626 /*
1627 * In the SYN-RECEIVED state, validate that the packet belongs to
1628 * this connection before trimming the data to fit the receive
1629 * window. Check the sequence number versus IRS since we know
1630 * the sequence numbers haven't wrapped. This is a partial fix
1631 * for the "LAND" DoS attack.
1632 */
1633 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1634 rstreason = BANDLIM_RST_OPENPORT;
1635 goto dropwithreset;
1636 }
1637
1638 todrop = tp->rcv_nxt - th->th_seq;
1639 if (todrop > 0) {
91489f6b
JH
1640 if (TCP_DO_SACK(tp)) {
1641 /* Report duplicate segment at head of packet. */
1642 tp->reportblk.rblk_start = th->th_seq;
1643 tp->reportblk.rblk_end = th->th_seq + tlen;
1644 if (thflags & TH_FIN)
1645 ++tp->reportblk.rblk_end;
1646 if (SEQ_GT(tp->reportblk.rblk_end, tp->rcv_nxt))
1647 tp->reportblk.rblk_end = tp->rcv_nxt;
1648 tp->t_flags |= (TF_DUPSEG | TF_SACKLEFT | TF_ACKNOW);
1649 }
984263bc
MD
1650 if (thflags & TH_SYN) {
1651 thflags &= ~TH_SYN;
1652 th->th_seq++;
1653 if (th->th_urp > 1)
1654 th->th_urp--;
1655 else
1656 thflags &= ~TH_URG;
1657 todrop--;
1658 }
1659 /*
1660 * Following if statement from Stevens, vol. 2, p. 960.
1661 */
61896e3c
JH
1662 if (todrop > tlen ||
1663 (todrop == tlen && !(thflags & TH_FIN))) {
984263bc
MD
1664 /*
1665 * Any valid FIN must be to the left of the window.
1666 * At this point the FIN must be a duplicate or out
1667 * of sequence; drop it.
1668 */
1669 thflags &= ~TH_FIN;
1670
1671 /*
1672 * Send an ACK to resynchronize and drop any data.
1673 * But keep on processing for RST or ACK.
1674 */
1675 tp->t_flags |= TF_ACKNOW;
1676 todrop = tlen;
1677 tcpstat.tcps_rcvduppack++;
1678 tcpstat.tcps_rcvdupbyte += todrop;
1679 } else {
1680 tcpstat.tcps_rcvpartduppack++;
1681 tcpstat.tcps_rcvpartdupbyte += todrop;
1682 }
1683 drop_hdrlen += todrop; /* drop from the top afterwards */
1684 th->th_seq += todrop;
1685 tlen -= todrop;
1686 if (th->th_urp > todrop)
1687 th->th_urp -= todrop;
1688 else {
1689 thflags &= ~TH_URG;
1690 th->th_urp = 0;
1691 }
1692 }
1693
1694 /*
1695 * If new data are received on a connection after the
1696 * user processes are gone, then RST the other end.
1697 */
1698 if ((so->so_state & SS_NOFDREF) &&
1699 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1700 tp = tcp_close(tp);
1701 tcpstat.tcps_rcvafterclose++;
1702 rstreason = BANDLIM_UNLIMITED;
1703 goto dropwithreset;
1704 }
1705
1706 /*
1707 * If segment ends after window, drop trailing data
1708 * (and PUSH and FIN); if nothing left, just ACK.
1709 */
61896e3c 1710 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
984263bc
MD
1711 if (todrop > 0) {
1712 tcpstat.tcps_rcvpackafterwin++;
1713 if (todrop >= tlen) {
1714 tcpstat.tcps_rcvbyteafterwin += tlen;
1715 /*
1716 * If a new connection request is received
1717 * while in TIME_WAIT, drop the old connection
1718 * and start over if the sequence numbers
1719 * are above the previous ones.
1720 */
1721 if (thflags & TH_SYN &&
1722 tp->t_state == TCPS_TIME_WAIT &&
1723 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1724 tp = tcp_close(tp);
1725 goto findpcb;
1726 }
1727 /*
1728 * If window is closed can only take segments at
1729 * window edge, and have to drop data and PUSH from
1730 * incoming segments. Continue processing, but
1731 * remember to ack. Otherwise, drop segment
1732 * and ack.
1733 */
1734 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1735 tp->t_flags |= TF_ACKNOW;
1736 tcpstat.tcps_rcvwinprobe++;
1737 } else
1738 goto dropafterack;
1739 } else
1740 tcpstat.tcps_rcvbyteafterwin += todrop;
1741 m_adj(m, -todrop);
1742 tlen -= todrop;
61896e3c 1743 thflags &= ~(TH_PUSH | TH_FIN);
984263bc
MD
1744 }
1745
1746 /*
1747 * If last ACK falls within this segment's sequence numbers,
1748 * record its timestamp.
1749 * NOTE that the test is modified according to the latest
1750 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1751 */
61896e3c 1752 if ((to.to_flags & TOF_TS) && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
984263bc
MD
1753 tp->ts_recent_age = ticks;
1754 tp->ts_recent = to.to_tsval;
1755 }
1756
1757 /*
1758 * If a SYN is in the window, then this is an
1759 * error and we send an RST and drop the connection.
1760 */
1761 if (thflags & TH_SYN) {
1762 tp = tcp_drop(tp, ECONNRESET);
1763 rstreason = BANDLIM_UNLIMITED;
1764 goto dropwithreset;
1765 }
1766
1767 /*
1768 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1769 * flag is on (half-synchronized state), then queue data for
1770 * later processing; else drop segment and return.
1771 */
61896e3c 1772 if (!(thflags & TH_ACK)) {
984263bc
MD
1773 if (tp->t_state == TCPS_SYN_RECEIVED ||
1774 (tp->t_flags & TF_NEEDSYN))
1775 goto step6;
1776 else
1777 goto drop;
1778 }
1779
1780 /*
1781 * Ack processing.
1782 */
1783 switch (tp->t_state) {
984263bc 1784 /*
91489f6b 1785 * In SYN_RECEIVED state, the ACK acknowledges our SYN, so enter
984263bc
MD
1786 * ESTABLISHED state and continue processing.
1787 * The ACK was checked above.
1788 */
1789 case TCPS_SYN_RECEIVED:
1790
1791 tcpstat.tcps_connects++;
1792 soisconnected(so);
1793 /* Do window scaling? */
61896e3c 1794 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
b5572302 1795 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
984263bc
MD
1796 tp->snd_scale = tp->requested_s_scale;
1797 tp->rcv_scale = tp->request_r_scale;
1798 }
1799 /*
1800 * Upon successful completion of 3-way handshake,
1801 * update cache.CC if it was undefined, pass any queued
1802 * data to the user, and advance state appropriately.
1803 */
1804 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1805 taop->tao_cc == 0)
1806 taop->tao_cc = tp->cc_recv;
1807
1808 /*
1809 * Make transitions:
1810 * SYN-RECEIVED -> ESTABLISHED
1811 * SYN-RECEIVED* -> FIN-WAIT-1
1812 */
1813 tp->t_starttime = ticks;
1814 if (tp->t_flags & TF_NEEDFIN) {
1815 tp->t_state = TCPS_FIN_WAIT_1;
1816 tp->t_flags &= ~TF_NEEDFIN;
1817 } else {
1818 tp->t_state = TCPS_ESTABLISHED;
d24ce1dc 1819 callout_reset(tp->tt_keep, tcp_keepidle,
984263bc
MD
1820 tcp_timer_keep, tp);
1821 }
1822 /*
1823 * If segment contains data or ACK, will call tcp_reass()
1824 * later; if not, do so now to pass queued data to user.
1825 */
61896e3c
JH
1826 if (tlen == 0 && !(thflags & TH_FIN))
1827 (void) tcp_reass(tp, NULL, NULL, NULL);
984263bc
MD
1828 /* fall into ... */
1829
1830 /*
1831 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1832 * ACKs. If the ack is in the range
1833 * tp->snd_una < th->th_ack <= tp->snd_max
1834 * then advance tp->snd_una to th->th_ack and drop
1835 * data from the retransmission queue. If this ACK reflects
1836 * more up to date window information we update our window information.
1837 */
1838 case TCPS_ESTABLISHED:
1839 case TCPS_FIN_WAIT_1:
1840 case TCPS_FIN_WAIT_2:
1841 case TCPS_CLOSE_WAIT:
1842 case TCPS_CLOSING:
1843 case TCPS_LAST_ACK:
1844 case TCPS_TIME_WAIT:
1845
1846 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
91489f6b
JH
1847 if (TCP_DO_SACK(tp))
1848 tcp_sack_update_scoreboard(tp, &to);
95b22adf
JH
1849 if (tlen != 0 || tiwin != tp->snd_wnd) {
1850 tp->t_dupacks = 0;
1851 break;
1852 }
1853 tcpstat.tcps_rcvdupack++;
91489f6b
JH
1854 if (!callout_active(tp->tt_rexmt) ||
1855 th->th_ack != tp->snd_una) {
1856 tp->t_dupacks = 0;
1857 break;
1858 }
95b22adf 1859 /*
91489f6b 1860 * We have outstanding data (other than
95b22adf
JH
1861 * a window probe), this is a completely
1862 * duplicate ack (ie, window info didn't
1863 * change), the ack is the biggest we've
1864 * seen and we've seen exactly our rexmt
91489f6b 1865 * threshhold of them, so assume a packet
95b22adf
JH
1866 * has been dropped and retransmit it.
1867 * Kludge snd_nxt & the congestion
1868 * window so we send only this one
1869 * packet.
95b22adf 1870 */
91489f6b
JH
1871 if (IN_FASTRECOVERY(tp)) {
1872 if (TCP_DO_SACK(tp)) {
1873 /* No artifical cwnd inflation. */
1874 tcp_sack_rexmt(tp, th);
1875 } else {
1876 /*
1877 * Dup acks mean that packets
1878 * have left the network
1879 * (they're now cached at the
1880 * receiver) so bump cwnd by
1881 * the amount in the receiver
1882 * to keep a constant cwnd
1883 * packets in the network.
1884 */
1885 tp->snd_cwnd += tp->t_maxseg;
1886 (void) tcp_output(tp);
1887 }
1888 } else if (SEQ_LT(th->th_ack, tp->snd_recover)) {
95b22adf
JH
1889 tp->t_dupacks = 0;
1890 break;
95b22adf 1891 } else if (++tp->t_dupacks == tcprexmtthresh) {
91489f6b 1892 tcp_seq old_snd_nxt;
95b22adf
JH
1893 u_int win;
1894
8819433a 1895fastretransmit:
95b22adf
JH
1896 if (tcp_do_eifel_detect &&
1897 (tp->t_flags & TF_RCVD_TSTMP)) {
1898 tcp_save_congestion_state(tp);
1899 tp->t_flags |= TF_FASTREXMT;
1900 }
91489f6b
JH
1901 /*
1902 * We know we're losing at the current
1903 * window size, so do congestion avoidance:
1904 * set ssthresh to half the current window
1905 * and pull our congestion window back to the
1906 * new ssthresh.
1907 */
95b22adf
JH
1908 win = min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1909 tp->t_maxseg;
1910 if (win < 2)
1911 win = 2;
1912 tp->snd_ssthresh = win * tp->t_maxseg;
1913 ENTER_FASTRECOVERY(tp);
1914 tp->snd_recover = tp->snd_max;
1915 callout_stop(tp->tt_rexmt);
1916 tp->t_rtttime = 0;
91489f6b 1917 old_snd_nxt = tp->snd_nxt;
95b22adf
JH
1918 tp->snd_nxt = th->th_ack;
1919 tp->snd_cwnd = tp->t_maxseg;
1920 (void) tcp_output(tp);
1921 ++tcpstat.tcps_sndfastrexmit;
91489f6b
JH
1922 tp->snd_cwnd = tp->snd_ssthresh;
1923 tp->rexmt_high = tp->snd_nxt;
1924 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
1925 tp->snd_nxt = old_snd_nxt;
95b22adf
JH
1926 KASSERT(tp->snd_limited <= 2,
1927 ("tp->snd_limited too big"));
91489f6b
JH
1928 if (TCP_DO_SACK(tp))
1929 tcp_sack_rexmt(tp, th);
1930 else
1931 tp->snd_cwnd += tp->t_maxseg *
1932 (tp->t_dupacks - tp->snd_limited);
95b22adf
JH
1933 } else if (tcp_do_limitedtransmit) {
1934 u_long oldcwnd = tp->snd_cwnd;
1935 tcp_seq oldsndmax = tp->snd_max;
1936 /* outstanding data */
1937 uint32_t ownd = tp->snd_max - tp->snd_una;
1938 u_int sent;
ca94b4a6 1939
8819433a
JH
1940#define iceildiv(n, d) (((n)+(d)-1) / (d))
1941
95b22adf
JH
1942 KASSERT(tp->t_dupacks == 1 ||
1943 tp->t_dupacks == 2,
1944 ("dupacks not 1 or 2"));
1945 if (tp->t_dupacks == 1)
1946 tp->snd_limited = 0;
1947 tp->snd_cwnd = ownd +
1948 (tp->t_dupacks - tp->snd_limited) *
1949 tp->t_maxseg;
1950 (void) tcp_output(tp);
1951 tp->snd_cwnd = oldcwnd;
1952 sent = tp->snd_max - oldsndmax;
1953 if (sent > tp->t_maxseg) {
1954 KASSERT((tp->t_dupacks == 2 &&
1955 tp->snd_limited == 0) ||
1956 (sent == tp->t_maxseg + 1 &&
1957 tp->t_flags & TF_SENTFIN),
1958 ("sent too much"));
1959 KASSERT(sent <= tp->t_maxseg * 2,
1960 ("sent too many segments"));
1961 tp->snd_limited = 2;
1962 tcpstat.tcps_sndlimited += 2;
1963 } else if (sent > 0) {
1964 ++tp->snd_limited;
1965 ++tcpstat.tcps_sndlimited;
1966 } else if (tcp_do_early_retransmit &&
1967 (tcp_do_eifel_detect &&
1968 (tp->t_flags & TF_RCVD_TSTMP)) &&
91489f6b 1969 ownd < 4 * tp->t_maxseg &&
95b22adf 1970 tp->t_dupacks + 1 >=
91489f6b
JH
1971 iceildiv(ownd, tp->t_maxseg) &&
1972 (!TCP_DO_SACK(tp) ||
1973 ownd <= tp->t_maxseg ||
1974 tcp_sack_has_sacked(&tp->scb,
1975 ownd - tp->t_maxseg))) {
95b22adf
JH
1976 ++tcpstat.tcps_sndearlyrexmit;
1977 tp->t_flags |= TF_EARLYREXMT;
1978 goto fastretransmit;
984263bc 1979 }
95b22adf
JH
1980 }
1981 goto drop;
984263bc
MD
1982 }
1983
1984 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
984263bc
MD
1985 tp->t_dupacks = 0;
1986 if (SEQ_GT(th->th_ack, tp->snd_max)) {
5a274421
JH
1987 /*
1988 * Detected optimistic ACK attack.
1989 * Force slow-start to de-synchronize attack.
1990 */
1991 tp->snd_cwnd = tp->t_maxseg;
1992
984263bc
MD
1993 tcpstat.tcps_rcvacktoomuch++;
1994 goto dropafterack;
1995 }
1996 /*
1997 * If we reach this point, ACK is not a duplicate,
1998 * i.e., it ACKs something we sent.
1999 */
2000 if (tp->t_flags & TF_NEEDSYN) {
2001 /*
2002 * T/TCP: Connection was half-synchronized, and our
2003 * SYN has been ACK'd (so connection is now fully
2004 * synchronized). Go to non-starred state,
2005 * increment snd_una for ACK of SYN, and check if
2006 * we can do window scaling.
2007 */
2008 tp->t_flags &= ~TF_NEEDSYN;
2009 tp->snd_una++;
2010 /* Do window scaling? */
61896e3c
JH
2011 if ((tp->t_flags & (TF_RCVD_SCALE | TF_REQ_SCALE)) ==
2012 (TF_RCVD_SCALE | TF_REQ_SCALE)) {
984263bc
MD
2013 tp->snd_scale = tp->requested_s_scale;
2014 tp->rcv_scale = tp->request_r_scale;
2015 }
2016 }
2017
2018process_ACK:
2019 acked = th->th_ack - tp->snd_una;
2020 tcpstat.tcps_rcvackpack++;
2021 tcpstat.tcps_rcvackbyte += acked;
2022
b5572302 2023 if (tcp_do_eifel_detect && acked > 0 &&
95b22adf 2024 (to.to_flags & TOF_TS) && (to.to_tsecr != 0) &&
bfdb979e
JH
2025 (tp->t_flags & TF_FIRSTACCACK)) {
2026 /* Eifel detection applicable. */
2027 if (to.to_tsecr < tp->t_rexmtTS) {
bfdb979e 2028 ++tcpstat.tcps_eifeldetected;
8819433a
JH
2029 tcp_revert_congestion_state(tp);
2030 if (tp->t_rxtshift == 1 &&
2031 ticks >= tp->t_badrxtwin)
2032 ++tcpstat.tcps_rttcantdetect;
bfdb979e
JH
2033 }
2034 } else if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
b5572302
JH
2035 /*
2036 * If we just performed our first retransmit,
2037 * and the ACK arrives within our recovery window,
2038 * then it was a mistake to do the retransmit
91489f6b 2039 * in the first place. Recover our original cwnd
b5572302
JH
2040 * and ssthresh, and proceed to transmit where we
2041 * left off.
2042 */
bfdb979e
JH
2043 tcp_revert_congestion_state(tp);
2044 ++tcpstat.tcps_rttdetected;
984263bc
MD
2045 }
2046
2047 /*
2048 * If we have a timestamp reply, update smoothed
2049 * round trip time. If no timestamp is present but
2050 * transmit timer is running and timed sequence
2051 * number was acked, update smoothed round trip time.
2052 * Since we now have an rtt measurement, cancel the
2053 * timer backoff (cf., Phil Karn's retransmit alg.).
2054 * Recompute the initial retransmit timer.
2055 *
2056 * Some machines (certain windows boxes) send broken
d24ce1dc 2057 * timestamp replies during the SYN+ACK phase, ignore
984263bc
MD
2058 * timestamps of 0.
2059 */
95b22adf 2060 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0))
984263bc 2061 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
95b22adf 2062 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
984263bc 2063 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
984263bc
MD
2064 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2065
984263bc
MD
2066 /*
2067 * If no data (only SYN) was ACK'd,
2068 * skip rest of ACK processing.
2069 */
2070 if (acked == 0)
2071 goto step6;
2072
efd4b327 2073 /* Stop looking for an acceptable ACK since one was received. */
8819433a 2074 tp->t_flags &= ~(TF_FIRSTACCACK | TF_FASTREXMT | TF_EARLYREXMT);
efd4b327 2075
984263bc
MD
2076 if (acked > so->so_snd.sb_cc) {
2077 tp->snd_wnd -= so->so_snd.sb_cc;
2078 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
61896e3c 2079 ourfinisacked = TRUE;
984263bc
MD
2080 } else {
2081 sbdrop(&so->so_snd, acked);
2082 tp->snd_wnd -= acked;
61896e3c 2083 ourfinisacked = FALSE;
984263bc
MD
2084 }
2085 sowwakeup(so);
91489f6b
JH
2086
2087 /*
2088 * Update window information.
2089 * Don't look at window if no ACK:
2090 * TAC's send garbage on first SYN.
2091 */
2092 if (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2093 (tp->snd_wl1 == th->th_seq &&
2094 (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2095 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)))) {
2096 /* keep track of pure window updates */
2097 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2098 tiwin > tp->snd_wnd)
2099 tcpstat.tcps_rcvwinupd++;
2100 tp->snd_wnd = tiwin;
2101 tp->snd_wl1 = th->th_seq;
2102 tp->snd_wl2 = th->th_ack;
2103 if (tp->snd_wnd > tp->max_sndwnd)
2104 tp->max_sndwnd = tp->snd_wnd;
2105 needoutput = TRUE;
2106 }
2107
2108 tp->snd_una = th->th_ack;
2109 if (TCP_DO_SACK(tp))
2110 tcp_sack_update_scoreboard(tp, &to);
95b22adf 2111 if (IN_FASTRECOVERY(tp)) {
91489f6b 2112 if (SEQ_GEQ(th->th_ack, tp->snd_recover)) {
95b22adf 2113 EXIT_FASTRECOVERY(tp);
91489f6b
JH
2114 needoutput = TRUE;
2115 /*
2116 * If the congestion window was inflated
2117 * to account for the other side's
2118 * cached packets, retract it.
2119 *
2120 * Window inflation should have left us
2121 * with approximately snd_ssthresh outstanding
2122 * data. But, in case we would be inclined
2123 * to send a burst, better do it using
2124 * slow start.
2125 */
2126 if (!TCP_DO_SACK(tp))
2127 tp->snd_cwnd = tp->snd_ssthresh;
2128
2129 if (SEQ_GT(th->th_ack + tp->snd_cwnd,
2130 tp->snd_max + 2 * tp->t_maxseg))
2131 tp->snd_cwnd =
2132 (tp->snd_max - tp->snd_una) +
2133 2 * tp->t_maxseg;
2134 } else {
2135 if (TCP_DO_SACK(tp)) {
2136 tp->snd_max_rexmt = tp->snd_max;
2137 tcp_sack_rexmt(tp, th);
2138 } else {
2139 tcp_newreno_partial_ack(tp, th, acked);
2140 }
2141 needoutput = FALSE;
2142 }
95b22adf 2143 } else {
91489f6b
JH
2144 /*
2145 * When new data is acked, open the congestion window.
2146 * If the window gives us less than ssthresh packets
2147 * in flight, open exponentially (maxseg per packet).
2148 * Otherwise open linearly: maxseg per window
2149 * (maxseg^2 / cwnd per packet).
2150 */
2151 u_int cw = tp->snd_cwnd;
2152 u_int incr;
2153
2154 if (cw > tp->snd_ssthresh)
2155 incr = tp->t_maxseg * tp->t_maxseg / cw;
2156 else
2157 incr = tp->t_maxseg;
2158 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
95b22adf 2159 tp->snd_recover = th->th_ack - 1;
cfb3f3f4 2160 }
984263bc
MD
2161 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2162 tp->snd_nxt = tp->snd_una;
2163
91489f6b
JH
2164 /*
2165 * If all outstanding data is acked, stop retransmit
2166 * timer and remember to restart (more output or persist).
2167 * If there is more data to be acked, restart retransmit
2168 * timer, using current (possibly backed-off) value.
2169 */
2170 if (th->th_ack == tp->snd_max) {
2171 callout_stop(tp->tt_rexmt);
2172 needoutput = TRUE;
2173 } else if (!callout_active(tp->tt_persist))
2174 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2175 tcp_timer_rexmt, tp);
2176
984263bc 2177 switch (tp->t_state) {
984263bc
MD
2178 /*
2179 * In FIN_WAIT_1 STATE in addition to the processing
2180 * for the ESTABLISHED state if our FIN is now acknowledged
2181 * then enter FIN_WAIT_2.
2182 */
2183 case TCPS_FIN_WAIT_1:
2184 if (ourfinisacked) {
2185 /*
2186 * If we can't receive any more
2187 * data, then closing user can proceed.
2188 * Starting the timer is contrary to the
2189 * specification, but if we don't get a FIN
2190 * we'll hang forever.
2191 */
2192 if (so->so_state & SS_CANTRCVMORE) {
2193 soisdisconnected(so);
2194 callout_reset(tp->tt_2msl, tcp_maxidle,
2195 tcp_timer_2msl, tp);
2196 }
2197 tp->t_state = TCPS_FIN_WAIT_2;
2198 }
2199 break;
2200
95b22adf 2201 /*
984263bc
MD
2202 * In CLOSING STATE in addition to the processing for
2203 * the ESTABLISHED state if the ACK acknowledges our FIN
2204 * then enter the TIME-WAIT state, otherwise ignore
2205 * the segment.
2206 */
2207 case TCPS_CLOSING:
2208 if (ourfinisacked) {
2209 tp->t_state = TCPS_TIME_WAIT;
2210 tcp_canceltimers(tp);
2211 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2212 if (tp->cc_recv != 0 &&
2213 (ticks - tp->t_starttime) < tcp_msl)
2214 callout_reset(tp->tt_2msl,
b5572302
JH
2215 tp->t_rxtcur * TCPTV_TWTRUNC,
2216 tcp_timer_2msl, tp);
984263bc
MD
2217 else
2218 callout_reset(tp->tt_2msl, 2 * tcp_msl,
b5572302 2219 tcp_timer_2msl, tp);
984263bc
MD
2220 soisdisconnected(so);
2221 }
2222 break;
2223
2224 /*
2225 * In LAST_ACK, we may still be waiting for data to drain
2226 * and/or to be acked, as well as for the ack of our FIN.
2227 * If our FIN is now acknowledged, delete the TCB,
2228 * enter the closed state and return.
2229 */
2230 case TCPS_LAST_ACK:
2231 if (ourfinisacked) {
2232 tp = tcp_close(tp);
2233 goto drop;
2234 }
2235 break;
2236
2237 /*
2238 * In TIME_WAIT state the only thing that should arrive
2239 * is a retransmission of the remote FIN. Acknowledge
2240 * it and restart the finack timer.
2241 */
2242 case TCPS_TIME_WAIT:
2243 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2244 tcp_timer_2msl, tp);
2245 goto dropafterack;
2246 }
2247 }
2248
2249step6:
2250 /*
2251 * Update window information.
2252 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2253 */
2254 if ((thflags & TH_ACK) &&
2255 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2256 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2257 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2258 /* keep track of pure window updates */
b5572302
JH
2259 if (tlen == 0 && tp->snd_wl2 == th->th_ack &&
2260 tiwin > tp->snd_wnd)
984263bc
MD
2261 tcpstat.tcps_rcvwinupd++;
2262 tp->snd_wnd = tiwin;
2263 tp->snd_wl1 = th->th_seq;
2264 tp->snd_wl2 = th->th_ack;
2265 if (tp->snd_wnd > tp->max_sndwnd)
2266 tp->max_sndwnd = tp->snd_wnd;
61896e3c 2267 needoutput = TRUE;
984263bc
MD
2268 }
2269
2270 /*
2271 * Process segments with URG.
2272 */
2273 if ((thflags & TH_URG) && th->th_urp &&
95b22adf 2274 !TCPS_HAVERCVDFIN(tp->t_state)) {
984263bc
MD
2275 /*
2276 * This is a kludge, but if we receive and accept
2277 * random urgent pointers, we'll crash in
2278 * soreceive. It's hard to imagine someone
2279 * actually wanting to send this much urgent data.
2280 */
2281 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2282 th->th_urp = 0; /* XXX */
2283 thflags &= ~TH_URG; /* XXX */
2284 goto dodata; /* XXX */
2285 }
2286 /*
2287 * If this segment advances the known urgent pointer,
2288 * then mark the data stream. This should not happen
2289 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2290 * a FIN has been received from the remote side.
2291 * In these states we ignore the URG.
2292 *
2293 * According to RFC961 (Assigned Protocols),
2294 * the urgent pointer points to the last octet
2295 * of urgent data. We continue, however,
2296 * to consider it to indicate the first octet
2297 * of data past the urgent section as the original
2298 * spec states (in one of two places).
2299 */
61896e3c 2300 if (SEQ_GT(th->th_seq + th->th_urp, tp->rcv_up)) {
984263bc
MD
2301 tp->rcv_up = th->th_seq + th->th_urp;
2302 so->so_oobmark = so->so_rcv.sb_cc +
2303 (tp->rcv_up - tp->rcv_nxt) - 1;
2304 if (so->so_oobmark == 0)
2305 so->so_state |= SS_RCVATMARK;
2306 sohasoutofband(so);
2307 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2308 }
2309 /*
2310 * Remove out of band data so doesn't get presented to user.
2311 * This can happen independent of advancing the URG pointer,
2312 * but if two URG's are pending at once, some out-of-band
2313 * data may creep in... ick.
2314 */
61896e3c
JH
2315 if (th->th_urp <= (u_long)tlen &&
2316 !(so->so_options & SO_OOBINLINE)) {
2317 /* hdr drop is delayed */
2318 tcp_pulloutofband(so, th, m, drop_hdrlen);
2319 }
984263bc
MD
2320 } else {
2321 /*
2322 * If no out of band data is expected,
2323 * pull receive urgent pointer along
2324 * with the receive window.
2325 */
2326 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2327 tp->rcv_up = tp->rcv_nxt;
2328 }
984263bc 2329
61896e3c 2330dodata: /* XXX */
984263bc
MD
2331 /*
2332 * Process the segment text, merging it into the TCP sequencing queue,
2333 * and arranging for acknowledgment of receipt if necessary.
2334 * This process logically involves adjusting tp->rcv_wnd as data
2335 * is presented to the user (this happens in tcp_usrreq.c,
2336 * case PRU_RCVD). If a FIN has already been received on this
2337 * connection then we just ignore the text.
2338 */
95b22adf 2339 if ((tlen || (thflags & TH_FIN)) && !TCPS_HAVERCVDFIN(tp->t_state)) {
984263bc
MD
2340 m_adj(m, drop_hdrlen); /* delayed header drop */
2341 /*
2342 * Insert segment which includes th into TCP reassembly queue
2343 * with control block tp. Set thflags to whether reassembly now
2344 * includes a segment with FIN. This handles the common case
2345 * inline (segment is the next to be received on an established
2346 * connection, and the queue is empty), avoiding linkage into
2347 * and removal from the queue and repetition of various
2348 * conversions.
2349 * Set DELACK for segments received in order, but ack
2350 * immediately when segments are out of order (so
2351 * fast retransmit can work).
2352 */
2353 if (th->th_seq == tp->rcv_nxt &&
2354 LIST_EMPTY(&tp->t_segq) &&
2355 TCPS_HAVEESTABLISHED(tp->t_state)) {
2356 if (DELAY_ACK(tp))
2357 callout_reset(tp->tt_delack, tcp_delacktime,
2358 tcp_timer_delack, tp);
2359 else
2360 tp->t_flags |= TF_ACKNOW;
2361 tp->rcv_nxt += tlen;
2362 thflags = th->th_flags & TH_FIN;
2363 tcpstat.tcps_rcvpack++;
2364 tcpstat.tcps_rcvbyte += tlen;
2365 ND6_HINT(tp);
2366 if (so->so_state & SS_CANTRCVMORE)
2367 m_freem(m);
2368 else
2369 sbappend(&so->so_rcv, m);
2370 sorwakeup(so);
2371 } else {
91489f6b
JH
2372 if (!(tp->t_flags & TF_DUPSEG)) {
2373 /* Initialize SACK report block. */
2374 tp->reportblk.rblk_start = th->th_seq;
2375 tp->reportblk.rblk_end = th->th_seq + tlen +
2376 ((thflags & TH_FIN) != 0);
2377 }
984263bc
MD
2378 thflags = tcp_reass(tp, th, &tlen, m);
2379 tp->t_flags |= TF_ACKNOW;
2380 }
2381
2382 /*
2383 * Note the amount of data that peer has sent into
2384 * our window, in order to estimate the sender's
2385 * buffer size.
2386 */
2387 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2388 } else {
2389 m_freem(m);
2390 thflags &= ~TH_FIN;
2391 }
2392
2393 /*
2394 * If FIN is received ACK the FIN and let the user know
2395 * that the connection is closing.
2396 */
2397 if (thflags & TH_FIN) {
95b22adf 2398 if (!TCPS_HAVERCVDFIN(tp->t_state)) {
984263bc
MD
2399 socantrcvmore(so);
2400 /*
2401 * If connection is half-synchronized
2402 * (ie NEEDSYN flag on) then delay ACK,
2403 * so it may be piggybacked when SYN is sent.
2404 * Otherwise, since we received a FIN then no
2405 * more input can be expected, send ACK now.
2406 */
2407 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
61896e3c
JH
2408 callout_reset(tp->tt_delack, tcp_delacktime,
2409 tcp_timer_delack, tp);
984263bc
MD
2410 else
2411 tp->t_flags |= TF_ACKNOW;
2412 tp->rcv_nxt++;
2413 }
984263bc 2414
61896e3c 2415 switch (tp->t_state) {
95b22adf 2416 /*
984263bc
MD
2417 * In SYN_RECEIVED and ESTABLISHED STATES
2418 * enter the CLOSE_WAIT state.
2419 */
2420 case TCPS_SYN_RECEIVED:
2421 tp->t_starttime = ticks;
2422 /*FALLTHROUGH*/
2423 case TCPS_ESTABLISHED:
2424 tp->t_state = TCPS_CLOSE_WAIT;
2425 break;
2426
95b22adf 2427 /*
984263bc
MD
2428 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2429 * enter the CLOSING state.
2430 */
2431 case TCPS_FIN_WAIT_1:
2432 tp->t_state = TCPS_CLOSING;
2433 break;
2434
95b22adf 2435 /*
984263bc
MD
2436 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2437 * starting the time-wait timer, turning off the other
2438 * standard timers.
2439 */
2440 case TCPS_FIN_WAIT_2:
2441 tp->t_state = TCPS_TIME_WAIT;
2442 tcp_canceltimers(tp);
2443 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2444 if (tp->cc_recv != 0 &&
2445 (ticks - tp->t_starttime) < tcp_msl) {
2446 callout_reset(tp->tt_2msl,
2447 tp->t_rxtcur * TCPTV_TWTRUNC,
2448 tcp_timer_2msl, tp);
2449 /* For transaction client, force ACK now. */
2450 tp->t_flags |= TF_ACKNOW;
2451 }
2452 else
2453 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2454 tcp_timer_2msl, tp);
2455 soisdisconnected(so);
2456 break;
2457
2458 /*
2459 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2460 */
2461 case TCPS_TIME_WAIT:
2462 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2463 tcp_timer_2msl, tp);
2464 break;
2465 }
2466 }
61896e3c 2467
984263bc
MD
2468#ifdef TCPDEBUG
2469 if (so->so_options & SO_DEBUG)
2470 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2471 &tcp_savetcp, 0);
2472#endif
2473
2474 /*
2475 * Return any desired output.
2476 */
2477 if (needoutput || (tp->t_flags & TF_ACKNOW))
2478 (void) tcp_output(tp);
2479 return;
2480
2481dropafterack:
2482 /*
2483 * Generate an ACK dropping incoming segment if it occupies
2484 * sequence space, where the ACK reflects our state.
2485 *
2486 * We can now skip the test for the RST flag since all
2487 * paths to this code happen after packets containing
2488 * RST have been dropped.
2489 *
2490 * In the SYN-RECEIVED state, don't send an ACK unless the
2491 * segment we received passes the SYN-RECEIVED ACK test.
2492 * If it fails send a RST. This breaks the loop in the
2493 * "LAND" DoS attack, and also prevents an ACK storm
2494 * between two listening ports that have been sent forged
2495 * SYN segments, each with the source address of the other.
2496 */
2497 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2498 (SEQ_GT(tp->snd_una, th->th_ack) ||
2499 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2500 rstreason = BANDLIM_RST_OPENPORT;
2501 goto dropwithreset;
2502 }
2503#ifdef TCPDEBUG
2504 if (so->so_options & SO_DEBUG)
2505 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2506 &tcp_savetcp, 0);
2507#endif
2508 m_freem(m);
2509 tp->t_flags |= TF_ACKNOW;
2510 (void) tcp_output(tp);
2511 return;
2512
2513dropwithreset:
2514 /*
2515 * Generate a RST, dropping incoming segment.
2516 * Make ACK acceptable to originator of segment.
2517 * Don't bother to respond if destination was broadcast/multicast.
2518 */
61896e3c 2519 if ((thflags & TH_RST) || m->m_flags & (M_BCAST | M_MCAST))
984263bc
MD
2520 goto drop;
2521 if (isipv6) {
2522 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2523 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2524 goto drop;
2525 } else {
2526 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2527 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
95b22adf
JH
2528 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2529 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
984263bc
MD
2530 goto drop;
2531 }
2532 /* IPv6 anycast check is done at tcp6_input() */
2533
2534 /*
2535 * Perform bandwidth limiting.
2536 */
2537#ifdef ICMP_BANDLIM
2538 if (badport_bandlim(rstreason) < 0)
2539 goto drop;
2540#endif
2541
2542#ifdef TCPDEBUG
2543 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2544 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2545 &tcp_savetcp, 0);
2546#endif
2547 if (thflags & TH_ACK)
2548 /* mtod() below is safe as long as hdr dropping is delayed */
2549 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2550 TH_RST);
2551 else {
2552 if (thflags & TH_SYN)
2553 tlen++;
2554 /* mtod() below is safe as long as hdr dropping is delayed */
61896e3c
JH
2555 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq + tlen,
2556 (tcp_seq)0, TH_RST | TH_ACK);
984263bc
MD
2557 }
2558 return;
2559
2560drop:
2561 /*
2562 * Drop space held by incoming segment and return.
2563 */
2564#ifdef TCPDEBUG
2565 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2566 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2567 &tcp_savetcp, 0);
2568#endif
2569 m_freem(m);
2570 return;
2571}
2572
2573/*
2574 * Parse TCP options and place in tcpopt.
2575 */
2576static void
95b22adf 2577tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, boolean_t is_syn)
984263bc 2578{
91489f6b 2579 int opt, optlen, i;
984263bc
MD
2580
2581 to->to_flags = 0;
2582 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2583 opt = cp[0];
2584 if (opt == TCPOPT_EOL)
2585 break;
2586 if (opt == TCPOPT_NOP)
2587 optlen = 1;
2588 else {
2589 if (cnt < 2)
2590 break;
2591 optlen = cp[1];
2592 if (optlen < 2 || optlen > cnt)
2593 break;
2594 }
2595 switch (opt) {
2596 case TCPOPT_MAXSEG:
2597 if (optlen != TCPOLEN_MAXSEG)
2598 continue;
2599 if (!is_syn)
2600 continue;
2601 to->to_flags |= TOF_MSS;
95b22adf 2602 bcopy(cp + 2, &to->to_mss, sizeof(to->to_mss));
984263bc
MD
2603 to->to_mss = ntohs(to->to_mss);
2604 break;
2605 case TCPOPT_WINDOW:
2606 if (optlen != TCPOLEN_WINDOW)
2607 continue;
95b22adf 2608 if (!is_syn)
984263bc
MD
2609 continue;
2610 to->to_flags |= TOF_SCALE;
2611 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2612 break;
2613 case TCPOPT_TIMESTAMP:
2614 if (optlen != TCPOLEN_TIMESTAMP)
2615 continue;
2616 to->to_flags |= TOF_TS;
95b22adf 2617 bcopy(cp + 2, &to->to_tsval, sizeof(to->to_tsval));
984263bc 2618 to->to_tsval = ntohl(to->to_tsval);
95b22adf 2619 bcopy(cp + 6, &to->to_tsecr, sizeof(to->to_tsecr));
984263bc
MD
2620 to->to_tsecr = ntohl(to->to_tsecr);
2621 break;
2622 case TCPOPT_CC:
2623 if (optlen != TCPOLEN_CC)
2624 continue;
2625 to->to_flags |= TOF_CC;
95b22adf 2626 bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
984263bc
MD
2627 to->to_cc = ntohl(to->to_cc);
2628 break;
2629 case TCPOPT_CCNEW:
2630 if (optlen != TCPOLEN_CC)
2631 continue;
2632 if (!is_syn)
2633 continue;
2634 to->to_flags |= TOF_CCNEW;
95b22adf 2635 bcopy(cp + 2, &to->to_cc, sizeof(to->to_cc));
984263bc
MD
2636 to->to_cc = ntohl(to->to_cc);
2637 break;
2638 case TCPOPT_CCECHO:
2639 if (optlen != TCPOLEN_CC)
2640 continue;
2641 if (!is_syn)
2642 continue;
2643 to->to_flags |= TOF_CCECHO;
95b22adf 2644 bcopy(cp + 2, &to->to_ccecho, sizeof(to->to_ccecho));
984263bc
MD
2645 to->to_ccecho = ntohl(to->to_ccecho);
2646 break;
91489f6b
JH
2647 case TCPOPT_SACK_PERMITTED:
2648 if (optlen != TCPOLEN_SACK_PERMITTED)
2649 continue;
2650 if (!is_syn)
2651 continue;
2652 to->to_flags |= TOF_SACK_PERMITTED;
2653 break;
2654 case TCPOPT_SACK:
2655 if ((optlen - 2) & 0x07) /* not multiple of 8 */
2656 continue;
2657 to->to_nsackblocks = (optlen - 2) / 8;
2658 to->to_sackblocks = (struct raw_sackblock *) (cp + 2);
2659 to->to_flags |= TOF_SACK;
2660 for (i = 0; i < to->to_nsackblocks; i++) {
2661 struct raw_sackblock *r = &to->to_sackblocks[i];
2662
2663 r->rblk_start = ntohl(r->rblk_start);
2664 r->rblk_end = ntohl(r->rblk_end);
2665 }
2666 break;
984263bc
MD
2667 default:
2668 continue;
2669 }
2670 }
2671}
2672
2673/*
2674 * Pull out of band byte out of a segment so
2675 * it doesn't appear in the user's data queue.
2676 * It is still reflected in the segment length for
2677 * sequencing purposes.
95b22adf 2678 * "off" is the delayed to be dropped hdrlen.
984263bc
MD
2679 */
2680static void
95b22adf 2681tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m, int off)
984263bc
MD
2682{
2683 int cnt = off + th->th_urp - 1;
2684
2685 while (cnt >= 0) {
2686 if (m->m_len > cnt) {
2687 char *cp = mtod(m, caddr_t) + cnt;
2688 struct tcpcb *tp = sototcpcb(so);
2689
2690 tp->t_iobc = *cp;
2691 tp->t_oobflags |= TCPOOB_HAVEDATA;
95b22adf 2692 bcopy(cp + 1, cp, m->m_len - cnt - 1);
984263bc
MD
2693 m->m_len--;
2694 if (m->m_flags & M_PKTHDR)
2695 m->m_pkthdr.len--;
2696 return;
2697 }
2698 cnt -= m->m_len;
2699 m = m->m_next;
2700 if (m == 0)
2701 break;
2702 }
2703 panic("tcp_pulloutofband");
2704}
2705
2706/*
2707 * Collect new round-trip time estimate
2708 * and update averages and current timeout.
2709 */
2710static void
95b22adf 2711tcp_xmit_timer(struct tcpcb *tp, int rtt)
984263bc 2712{
2256ba69 2713 int delta;
984263bc
MD
2714
2715 tcpstat.tcps_rttupdated++;
2716 tp->t_rttupdated++;
2717 if (tp->t_srtt != 0) {
2718 /*
2719 * srtt is stored as fixed point with 5 bits after the
2720 * binary point (i.e., scaled by 8). The following magic
2721 * is equivalent to the smoothing algorithm in rfc793 with
2722 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2723 * point). Adjust rtt to origin 0.
2724 */
2725 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2726 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2727
2728 if ((tp->t_srtt += delta) <= 0)
2729 tp->t_srtt = 1;
2730
2731 /*
2732 * We accumulate a smoothed rtt variance (actually, a
2733 * smoothed mean difference), then set the retransmit
2734 * timer to smoothed rtt + 4 times the smoothed variance.
2735 * rttvar is stored as fixed point with 4 bits after the
2736 * binary point (scaled by 16). The following is
2737 * equivalent to rfc793 smoothing with an alpha of .75
2738 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2739 * rfc793's wired-in beta.
2740 */
2741 if (delta < 0)
2742 delta = -delta;
2743 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2744 if ((tp->t_rttvar += delta) <= 0)
2745 tp->t_rttvar = 1;
2746 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2747 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2748 } else {
2749 /*
2750 * No rtt measurement yet - use the unsmoothed rtt.
2751 * Set the variance to half the rtt (so our first
2752 * retransmit happens at 3*rtt).
2753 */
2754 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2755 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2756 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2757 }
2758 tp->t_rtttime = 0;
2759 tp->t_rxtshift = 0;
2760
2761 /*
2762 * the retransmit should happen at rtt + 4 * rttvar.
2763 * Because of the way we do the smoothing, srtt and rttvar
2764 * will each average +1/2 tick of bias. When we compute
2765 * the retransmit timer, we want 1/2 tick of rounding and
2766 * 1 extra tick because of +-1/2 tick uncertainty in the
2767 * firing of the timer. The bias will give us exactly the
2768 * 1.5 tick we need. But, because the bias is
2769 * statistical, we have to test that we don't drop below
2770 * the minimum feasible timer (which is 2 ticks).
2771 */
2772 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2773 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2774
2775 /*
2776 * We received an ack for a packet that wasn't retransmitted;
2777 * it is probably safe to discard any error indications we've
2778 * received recently. This isn't quite right, but close enough
2779 * for now (a route might have failed after we sent a segment,
2780 * and the return path might not be symmetrical).
2781 */
2782 tp->t_softerror = 0;
2783}
2784
2785/*
2786 * Determine a reasonable value for maxseg size.
2787 * If the route is known, check route for mtu.
2788 * If none, use an mss that can be handled on the outgoing
2789 * interface without forcing IP to fragment; if bigger than
2790 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2791 * to utilize large mbufs. If no route is found, route has no mtu,
2792 * or the destination isn't local, use a default, hopefully conservative
2793 * size (usually 512 or the default IP max size, but no more than the mtu
2794 * of the interface), as we can't discover anything about intervening
2795 * gateways or networks. We also initialize the congestion/slow start
2796 * window to be a single segment if the destination isn't local.
2797 * While looking at the routing entry, we also initialize other path-dependent
2798 * parameters from pre-set or cached values in the routing entry.
2799 *
2800 * Also take into account the space needed for options that we
2801 * send regularly. Make maxseg shorter by that amount to assure
2802 * that we can send maxseg amount of data even when the options
2803 * are present. Store the upper limit of the length of options plus
2804 * data in maxopd.
2805 *
2806 * NOTE that this routine is only called when we process an incoming
2807 * segment, for outgoing segments only tcp_mssopt is called.
2808 *
2809 * In case of T/TCP, we call this routine during implicit connection
2810 * setup as well (offer = -1), to initialize maxseg from the cached
2811 * MSS of our peer.
2812 */
2813void
95b22adf 2814tcp_mss(struct tcpcb *tp, int offer)
984263bc 2815{
2256ba69 2816 struct rtentry *rt;
984263bc 2817 struct ifnet *ifp;
2256ba69 2818 int rtt, mss;
984263bc
MD
2819 u_long bufsize;
2820 struct inpcb *inp = tp->t_inpcb;
2821 struct socket *so;
2822 struct rmxp_tao *taop;
2823 int origoffer = offer;
2824#ifdef INET6
d24ce1dc 2825 boolean_t isipv6 = ((inp->inp_vflag & INP_IPV6) ? TRUE : FALSE);
984263bc
MD
2826 size_t min_protoh = isipv6 ?
2827 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2828 sizeof(struct tcpiphdr);
2829#else
d24ce1dc 2830 const boolean_t isipv6 = FALSE;
984263bc
MD
2831 const size_t min_protoh = sizeof(struct tcpiphdr);
2832#endif
2833
2834 if (isipv6)
2835 rt = tcp_rtlookup6(&inp->inp_inc);
2836 else
2837 rt = tcp_rtlookup(&inp->inp_inc);
2838 if (rt == NULL) {
2839 tp->t_maxopd = tp->t_maxseg =
d24ce1dc 2840 (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
984263bc
MD
2841 return;
2842 }
2843 ifp = rt->rt_ifp;
2844 so = inp->inp_socket;
2845
2846 taop = rmx_taop(rt->rt_rmx);
2847 /*
2848 * Offer == -1 means that we didn't receive SYN yet,
2849 * use cached value in that case;
2850 */
2851 if (offer == -1)
2852 offer = taop->tao_mssopt;
2853 /*
2854 * Offer == 0 means that there was no MSS on the SYN segment,
2855 * in this case we use tcp_mssdflt.
2856 */
2857 if (offer == 0)
d24ce1dc 2858 offer = (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
984263bc
MD
2859 else
2860 /*
2861 * Sanity check: make sure that maxopd will be large
2862 * enough to allow some data on segments even is the
2863 * all the option space is used (40bytes). Otherwise
2864 * funny things may happen in tcp_output.
2865 */
2866 offer = max(offer, 64);
2867 taop->tao_mssopt = offer;
2868
2869 /*
2870 * While we're here, check if there's an initial rtt
2871 * or rttvar. Convert from the route-table units
2872 * to scaled multiples of the slow timeout timer.
2873 */
2874 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2875 /*
2876 * XXX the lock bit for RTT indicates that the value
2877 * is also a minimum value; this is subject to time.
2878 */
2879 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2880 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2881 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2882 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2883 tcpstat.tcps_usedrtt++;
2884 if (rt->rt_rmx.rmx_rttvar) {
2885 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2886 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2887 tcpstat.tcps_usedrttvar++;
2888 } else {
2889 /* default variation is +- 1 rtt */
2890 tp->t_rttvar =
2891 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2892 }
2893 TCPT_RANGESET(tp->t_rxtcur,
2894 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2895 tp->t_rttmin, TCPTV_REXMTMAX);
2896 }
2897 /*
2898 * if there's an mtu associated with the route, use it
2899 * else, use the link mtu.
2900 */
2901 if (rt->rt_rmx.rmx_mtu)
2902 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2903 else {
2904 if (isipv6) {
2905 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2906 min_protoh;
2907 if (!in6_localaddr(&inp->in6p_faddr))
2908 mss = min(mss, tcp_v6mssdflt);
2909 } else {
2910 mss = ifp->if_mtu - min_protoh;
2911 if (!in_localaddr(inp->inp_faddr))
2912 mss = min(mss, tcp_mssdflt);
2913 }
2914 }
2915 mss = min(mss, offer);
2916 /*
2917 * maxopd stores the maximum length of data AND options
2918 * in a segment; maxseg is the amount of data in a normal
2919 * segment. We need to store this value (maxopd) apart
2920 * from maxseg, because now every segment carries options
2921 * and thus we normally have somewhat less data in segments.
2922 */
2923 tp->t_maxopd = mss;
2924
2925 /*
2926 * In case of T/TCP, origoffer==-1 indicates, that no segments
2927 * were received yet. In this case we just guess, otherwise
2928 * we do the same as before T/TCP.
2929 */
61896e3c 2930 if ((tp->t_flags & (TF_REQ_TSTMP | TF_NOOPT)) == TF_REQ_TSTMP &&
984263bc
MD
2931 (origoffer == -1 ||
2932 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2933 mss -= TCPOLEN_TSTAMP_APPA;
61896e3c 2934 if ((tp->t_flags & (TF_REQ_CC | TF_NOOPT)) == TF_REQ_CC &&
984263bc
MD
2935 (origoffer == -1 ||
2936 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2937 mss -= TCPOLEN_CC_APPA;
2938
2939#if (MCLBYTES & (MCLBYTES - 1)) == 0
2940 if (mss > MCLBYTES)
2941 mss &= ~(MCLBYTES-1);
2942#else
2943 if (mss > MCLBYTES)
2944 mss = mss / MCLBYTES * MCLBYTES;
2945#endif
2946 /*
2947 * If there's a pipesize, change the socket buffer
2948 * to that size. Make the socket buffers an integral
2949 * number of mss units; if the mss is larger than
2950 * the socket buffer, decrease the mss.
2951 */
2952#ifdef RTV_SPIPE
2953 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2954#endif
2955 bufsize = so->so_snd.sb_hiwat;
2956 if (bufsize < mss)
2957 mss = bufsize;
2958 else {
2959 bufsize = roundup(bufsize, mss);
2960 if (bufsize > sb_max)
2961 bufsize = sb_max;
2962 if (bufsize > so->so_snd.sb_hiwat)
2963 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2964 }
2965 tp->t_maxseg = mss;
2966
2967#ifdef RTV_RPIPE
2968 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2969#endif
2970 bufsize = so->so_rcv.sb_hiwat;
2971 if (bufsize > mss) {
2972 bufsize = roundup(bufsize, mss);
2973 if (bufsize > sb_max)
2974 bufsize = sb_max;
2975 if (bufsize > so->so_rcv.sb_hiwat)
2976 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2977 }
2978
2979 /*
2980 * Set the slow-start flight size depending on whether this
2981 * is a local network or not.
2982 */
4b52d5ee
JH
2983 if (tcp_do_rfc3390)
2984 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
2985 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2986 (!isipv6 && in_localaddr(inp->inp_faddr)))
984263bc 2987 tp->snd_cwnd = mss * ss_fltsz_local;
4b52d5ee 2988 else
984263bc
MD
2989 tp->snd_cwnd = mss * ss_fltsz;
2990
2991 if (rt->rt_rmx.rmx_ssthresh) {
2992 /*
2993 * There's some sort of gateway or interface
2994 * buffer limit on the path. Use this to set
2995 * the slow start threshhold, but set the
2996 * threshold to no less than 2*mss.
2997 */
2998 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2999 tcpstat.tcps_usedssthresh++;
3000 }
3001}
3002
3003/*
3004 * Determine the MSS option to send on an outgoing SYN.
3005 */
3006int
95b22adf 3007tcp_mssopt(struct tcpcb *tp)
984263bc
MD
3008{
3009 struct rtentry *rt;
3010#ifdef INET6
d24ce1dc
JH
3011 boolean_t isipv6 =
3012 ((tp->t_inpcb->inp_vflag & INP_IPV6) ? TRUE : FALSE);
984263bc
MD
3013 int min_protoh = isipv6 ?
3014 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
3015 sizeof(struct tcpiphdr);
3016#else
d24ce1dc 3017 const boolean_t isipv6 = FALSE;
984263bc
MD
3018 const size_t min_protoh = sizeof(struct tcpiphdr);
3019#endif
3020
3021 if (isipv6)
3022 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
3023 else
3024 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
3025 if (rt == NULL)
3026 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
3027
3028 return (rt->rt_ifp->if_mtu - min_protoh);
3029}
3030
984263bc
MD
3031/*
3032 * When a partial ack arrives, force the retransmission of the
91489f6b
JH
3033 * next unacknowledged segment. Do not exit Fast Recovery.
3034 *
3035 * Implement the Slow-but-Steady variant of NewReno by restarting the
3036 * the retransmission timer. Turn it off here so it can be restarted
3037 * later in tcp_output().
984263bc
MD
3038 */
3039static void
91489f6b 3040tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th, int acked)
984263bc 3041{
91489f6b
JH
3042 tcp_seq old_snd_nxt = tp->snd_nxt;
3043 u_long ocwnd = tp->snd_cwnd;
984263bc
MD
3044
3045 callout_stop(tp->tt_rexmt);
3046 tp->t_rtttime = 0;
3047 tp->snd_nxt = th->th_ack;
91489f6b
JH
3048 /* Set snd_cwnd to one segment beyond acknowledged offset. */
3049 tp->snd_cwnd = tp->t_maxseg;
984263bc
MD
3050 tp->t_flags |= TF_ACKNOW;
3051 (void) tcp_output(tp);
91489f6b
JH
3052 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3053 tp->snd_nxt = old_snd_nxt;
3054 /* partial window deflation */
3055 tp->snd_cwnd = ocwnd - acked + tp->t_maxseg;
3056}
3057
3058/*
3059 * In contrast to the Slow-but-Steady NewReno variant,
3060 * we do not reset the retransmission timer for SACK retransmissions,
3061 * except when retransmitting snd_una.
3062 */
3063static void
3064tcp_sack_rexmt(struct tcpcb *tp, struct tcphdr *th)
3065{
3066 uint32_t pipe, seglen;
3067 tcp_seq nextrexmt;
3068 boolean_t lostdup;
3069 tcp_seq old_snd_nxt = tp->snd_nxt;
3070 u_long ocwnd = tp->snd_cwnd;
3071 int nseg = 0; /* consecutive new segments */
3072#define MAXBURST 4 /* limit burst of new packets on partial ack */
3073
3074 tp->t_rtttime = 0;
3075 pipe = tcp_sack_compute_pipe(tp);
3076 while ((tcp_seq_diff_t)(ocwnd - pipe) >= (tcp_seq_diff_t)tp->t_maxseg &&
3077 (!tcp_do_smartsack || nseg < MAXBURST) &&
3078 tcp_sack_nextseg(tp, &nextrexmt, &seglen, &lostdup)) {
3079 uint32_t sent;
3080 tcp_seq old_snd_max;
3081 int error;
3082
3083 if (nextrexmt == tp->snd_max) ++nseg;
3084 tp->snd_nxt = nextrexmt;
3085 tp->snd_cwnd = nextrexmt - tp->snd_una + seglen;
3086 old_snd_max = tp->snd_max;
3087 if (nextrexmt == tp->snd_una)
3088 callout_stop(tp->tt_rexmt);
3089 error = tcp_output(tp);
3090 if (error != 0)
3091 break;
3092 sent = tp->snd_nxt - nextrexmt;
3093 if (sent <= 0)
3094 break;
3095 if (!lostdup)
3096 pipe += sent;
3097 tcpstat.tcps_sndsackpack++;
3098 tcpstat.tcps_sndsackbyte += sent;
3099 if (SEQ_LT(nextrexmt, old_snd_max) &&
3100 SEQ_LT(tp->rexmt_high, tp->snd_nxt))
3101 tp->rexmt_high = seq_min(tp->snd_nxt, old_snd_max);
3102 }
3103 if (SEQ_GT(old_snd_nxt, tp->snd_nxt))
3104 tp->snd_nxt = old_snd_nxt;
984263bc 3105 tp->snd_cwnd = ocwnd;
984263bc 3106}