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