1 //==========================================================================
3 // src/sys/netinet/tcp_input.c
5 //==========================================================================
6 //####BSDCOPYRIGHTBEGIN####
8 // -------------------------------------------
10 // Portions of this software may have been derived from OpenBSD,
11 // FreeBSD or other sources, and are covered by the appropriate
12 // copyright disclaimers included herein.
14 // Portions created by Red Hat are
15 // Copyright (C) 2002 Red Hat, Inc. All Rights Reserved.
17 // -------------------------------------------
19 //####BSDCOPYRIGHTEND####
20 //==========================================================================
23 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
24 * The Regents of the University of California. All rights reserved.
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
54 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
55 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.16 2001/08/22 00:59:12 silby Exp $
58 #include <sys/param.h>
59 #include <sys/malloc.h>
61 #include <sys/protosw.h>
62 #include <sys/socket.h>
63 #include <sys/sysctl.h>
64 #include <sys/socketvar.h>
67 #include <net/route.h>
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/ip.h>
72 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
73 #include <netinet/in_var.h>
74 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
75 #include <netinet/in_pcb.h>
76 #include <netinet/ip_var.h>
78 #include <netinet/ip6.h>
79 #include <netinet/icmp6.h>
80 #include <netinet6/nd6.h>
81 #include <netinet6/ip6_var.h>
82 #include <netinet6/in6_pcb.h>
84 #include <netinet/tcp.h>
85 #include <netinet/tcp_fsm.h>
86 #include <netinet/tcp_seq.h>
87 #include <netinet/tcp_timer.h>
88 #include <netinet/tcp_var.h>
91 #include <netinet6/tcp6_var.h>
93 #include <netinet/tcpip.h>
95 #include <netinet/tcp_debug.h>
97 u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
98 struct tcphdr tcp_savetcp;
102 #include <netinet6/ipsec.h>
103 #include <netkey/key.h>
106 static int tcprexmtthresh = 3;
109 struct tcpstat tcpstat;
110 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RD,
111 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
113 static int log_in_vain = 0;
114 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
115 &log_in_vain, 0, "Log all incoming TCP connections");
117 static int blackhole = 0;
118 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
119 &blackhole, 0, "Do not send RST when dropping refused connections");
121 int tcp_delack_enabled = 1;
122 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
123 &tcp_delack_enabled, 0,
124 "Delay ACK to try and piggyback it onto a data packet");
126 int tcp_lq_overflow = 1;
127 SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_lq_overflow, CTLFLAG_RW,
129 "Listen Queue Overflow");
131 #ifdef TCP_DROP_SYNFIN
132 static int drop_synfin = 0;
133 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
134 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
137 struct inpcbhead tcb;
138 #define tcb6 tcb /* for KAME src sync over BSD*'s */
139 struct inpcbinfo tcbinfo;
141 static void tcp_dooptions __P((struct tcpcb *,
142 u_char *, int, struct tcphdr *, struct tcpopt *));
143 static void tcp_pulloutofband __P((struct socket *,
144 struct tcphdr *, struct mbuf *, int));
145 static int tcp_reass __P((struct tcpcb *, struct tcphdr *, int *,
147 static void tcp_xmit_timer __P((struct tcpcb *, int));
148 static int tcp_newreno __P((struct tcpcb *, struct tcphdr *));
150 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
152 #define ND6_HINT(tp) \
154 if ((tp) && (tp)->t_inpcb && \
155 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
156 (tp)->t_inpcb->in6p_route.ro_rt) \
157 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
164 * Indicate whether this ack should be delayed.
166 #define DELAY_ACK(tp) \
167 (tcp_delack_enabled && !callout_pending(tp->tt_delack))
170 tcp_reass(tp, th, tlenp, m)
171 register struct tcpcb *tp;
172 register struct tcphdr *th;
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;
184 * Call with th==0 after become established to
185 * force pre-ESTABLISHED data up to user socket.
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,
194 tcpstat.tcps_rcvmemdrop++;
200 * Find a segment which begins after this one does.
202 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
203 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
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.
215 /* conversion to int (in i) handles seq wraparound */
216 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
219 tcpstat.tcps_rcvduppack++;
220 tcpstat.tcps_rcvdupbyte += *tlenp;
224 * Try to present any queued data
225 * at the left window edge to the user.
226 * This is needed after the 3-WHS
229 goto present; /* ??? */
236 tcpstat.tcps_rcvoopack++;
237 tcpstat.tcps_rcvoobyte += *tlenp;
240 * While we overlap succeeding segments trim them or,
241 * if they are completely covered, dequeue them.
244 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
247 if (i < q->tqe_len) {
248 q->tqe_th->th_seq += i;
254 nq = LIST_NEXT(q, tqe_q);
255 LIST_REMOVE(q, tqe_q);
261 /* Insert the new segment queue entry into place. */
264 te->tqe_len = *tlenp;
267 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
269 LIST_INSERT_AFTER(p, te, tqe_q);
274 * Present data to user, advancing rcv_nxt through
275 * completed sequence space.
277 if (!TCPS_HAVEESTABLISHED(tp->t_state))
279 q = LIST_FIRST(&tp->t_segq);
280 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
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)
290 sbappend(&so->so_rcv, q->tqe_m);
293 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
300 * TCP input routine, follows pages 65-76 of the
301 * protocol specification dated September, 1981 very closely.
305 tcp6_input(mp, offp, proto)
309 register struct mbuf *m = *mp;
310 struct in6_ifaddr *ia6;
312 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
315 * draft-itojun-ipv6-tcp-to-anycast
316 * better place to put this in?
318 ia6 = ip6_getdstifaddr(m);
319 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
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);
335 register struct mbuf *m;
338 register struct tcphdr *th;
339 register struct ip *ip = NULL;
340 register struct ipovly *ipov;
341 register struct inpcb *inp;
346 register struct tcpcb *tp = 0;
347 register int thflags;
348 struct socket *so = 0;
349 int todrop, acked, ourfinisacked, needoutput = 0;
350 struct in_addr laddr;
352 struct in6_addr laddr6;
357 struct tcpopt to; /* options in this segment */
358 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
359 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
364 struct ip6_hdr *ip6 = NULL;
367 int rstreason; /* For badport_bandlim accounting purposes */
370 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
372 bzero((char *)&to, sizeof(to));
374 tcpstat.tcps_rcvtotal++;
378 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
379 ip6 = mtod(m, struct ip6_hdr *);
380 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
381 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
382 tcpstat.tcps_rcvbadsum++;
385 th = (struct tcphdr *)((caddr_t)ip6 + off0);
388 * Be proactive about unspecified IPv6 address in source.
389 * As we use all-zero to indicate unbounded/unconnected pcb,
390 * unspecified IPv6 address can be used to confuse us.
392 * Note that packets with unspecified IPv6 destination is
393 * already dropped in ip6_input.
395 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
403 * Get IP and TCP header together in first mbuf.
404 * Note: IP leaves IP header in first mbuf.
406 if (off0 > sizeof (struct ip)) {
407 ip_stripoptions(m, (struct mbuf *)0);
408 off0 = sizeof(struct ip);
410 if (m->m_len < sizeof (struct tcpiphdr)) {
411 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
412 tcpstat.tcps_rcvshort++;
416 ip = mtod(m, struct ip *);
417 ipov = (struct ipovly *)ip;
418 th = (struct tcphdr *)((caddr_t)ip + off0);
421 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
422 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
423 th->th_sum = m->m_pkthdr.csum_data;
425 th->th_sum = in_pseudo(ip->ip_src.s_addr,
426 ip->ip_dst.s_addr, htonl(m->m_pkthdr.csum_data +
427 ip->ip_len + IPPROTO_TCP));
428 th->th_sum ^= 0xffff;
431 * Checksum extended TCP header and data.
433 len = sizeof (struct ip) + tlen;
434 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
435 ipov->ih_len = (u_short)tlen;
437 th->th_sum = in_cksum(m, len);
440 tcpstat.tcps_rcvbadsum++;
444 /* Re-initialization for later version check */
445 ip->ip_v = IPVERSION;
450 * Check that TCP offset makes sense,
451 * pull out TCP options and adjust length. XXX
453 off = th->th_off << 2;
454 if (off < sizeof (struct tcphdr) || off > tlen) {
455 tcpstat.tcps_rcvbadoff++;
458 tlen -= off; /* tlen is used instead of ti->ti_len */
459 if (off > sizeof (struct tcphdr)) {
462 IP6_EXTHDR_CHECK(m, off0, off, );
463 ip6 = mtod(m, struct ip6_hdr *);
464 th = (struct tcphdr *)((caddr_t)ip6 + off0);
468 if (m->m_len < sizeof(struct ip) + off) {
469 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
470 tcpstat.tcps_rcvshort++;
473 ip = mtod(m, struct ip *);
474 ipov = (struct ipovly *)ip;
475 th = (struct tcphdr *)((caddr_t)ip + off0);
478 optlen = off - sizeof (struct tcphdr);
479 optp = (u_char *)(th + 1);
481 thflags = th->th_flags;
483 #ifdef TCP_DROP_SYNFIN
485 * If the drop_synfin option is enabled, drop all packets with
486 * both the SYN and FIN bits set. This prevents e.g. nmap from
487 * identifying the TCP/IP stack.
489 * This is incompatible with RFC1644 extensions (T/TCP).
491 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
496 * Convert TCP protocol specific fields to host format.
504 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
505 * until after ip6_savecontrol() is called and before other functions
506 * which don't want those proto headers.
507 * Because ip6_savecontrol() is going to parse the mbuf to
508 * search for data to be passed up to user-land, it wants mbuf
509 * parameters to be unchanged.
511 drop_hdrlen = off0 + off;
514 * Locate pcb for segment.
517 #ifdef IPFIREWALL_FORWARD
518 if (ip_fw_fwd_addr != NULL
520 && isipv6 == NULL /* IPv6 support is not yet */
524 * Diverted. Pretend to be the destination.
525 * already got one like this?
527 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
528 ip->ip_dst, th->th_dport, 0, m->m_pkthdr.rcvif);
531 * No, then it's new. Try find the ambushing socket
533 if (!ip_fw_fwd_addr->sin_port) {
534 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src,
535 th->th_sport, ip_fw_fwd_addr->sin_addr,
536 th->th_dport, 1, m->m_pkthdr.rcvif);
538 inp = in_pcblookup_hash(&tcbinfo,
539 ip->ip_src, th->th_sport,
540 ip_fw_fwd_addr->sin_addr,
541 ntohs(ip_fw_fwd_addr->sin_port), 1,
545 ip_fw_fwd_addr = NULL;
547 #endif /* IPFIREWALL_FORWARD */
551 inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_src, th->th_sport,
552 &ip6->ip6_dst, th->th_dport, 1,
556 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
557 ip->ip_dst, th->th_dport, 1, m->m_pkthdr.rcvif);
563 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
564 ipsec6stat.in_polvio++;
569 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
570 ipsecstat.in_polvio++;
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.
584 char dbuf[INET6_ADDRSTRLEN], sbuf[INET6_ADDRSTRLEN];
586 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
591 strcpy(dbuf, ip6_sprintf(&ip6->ip6_dst));
592 strcpy(sbuf, ip6_sprintf(&ip6->ip6_src));
596 strcpy(dbuf, inet_ntoa(ip->ip_dst));
597 strcpy(sbuf, inet_ntoa(ip->ip_src));
599 switch (log_in_vain) {
603 "Connection attempt to TCP %s:%d from %s:%d\n",
604 dbuf, ntohs(th->th_dport),
606 ntohs(th->th_sport));
610 "Connection attempt to TCP %s:%d from %s:%d flags:0x%x\n",
611 dbuf, ntohs(th->th_dport), sbuf,
612 ntohs(th->th_sport), thflags);
621 if (thflags & TH_SYN)
630 rstreason = BANDLIM_RST_CLOSEDPORT;
635 rstreason = BANDLIM_RST_CLOSEDPORT;
638 if (tp->t_state == TCPS_CLOSED)
641 /* Unscale the window into a 32-bit value. */
642 if ((thflags & TH_SYN) == 0)
643 tiwin = th->th_win << tp->snd_scale;
647 so = inp->inp_socket;
648 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
650 if (so->so_options & SO_DEBUG) {
651 ostate = tp->t_state;
654 bcopy((char *)ip6, (char *)tcp_saveipgen,
658 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
662 if (so->so_options & SO_ACCEPTCONN) {
663 register struct tcpcb *tp0 = tp;
669 struct inpcb *oinp = sotoinpcb(so);
674 * Current IPsec implementation makes incorrect IPsec
675 * cache if this check is done here.
676 * So delay this until duplicated socket is created.
678 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
680 * Note: dropwithreset makes sure we don't
681 * send a RST in response to a RST.
683 if (thflags & TH_ACK) {
684 tcpstat.tcps_badsyn++;
685 rstreason = BANDLIM_RST_OPENPORT;
694 * If deprecated address is forbidden,
695 * we do not accept SYN to deprecated interface
696 * address to prevent any new inbound connection from
697 * getting established.
698 * When we do not accept SYN, we send a TCP RST,
699 * with deprecated source address (instead of dropping
700 * it). We compromise it as it is much better for peer
701 * to send a RST, and RST will be the final packet
704 * If we do not forbid deprecated addresses, we accept
705 * the SYN packet. RFC2462 does not suggest dropping
707 * If we decipher RFC2462 5.5.4, it says like this:
708 * 1. use of deprecated addr with existing
709 * communication is okay - "SHOULD continue to be
711 * 2. use of it with new communication:
712 * (2a) "SHOULD NOT be used if alternate address
713 * with sufficient scope is available"
714 * (2b) nothing mentioned otherwise.
715 * Here we fall into (2b) case as we have no choice in
716 * our source address selection - we must obey the peer.
718 * The wording in RFC2462 is confusing, and there are
719 * multiple description text for deprecated address
720 * handling - worse, they are not exactly the same.
721 * I believe 5.5.4 is the best one, so we follow 5.5.4.
723 if (isipv6 && !ip6_use_deprecated) {
724 struct in6_ifaddr *ia6;
726 if ((ia6 = ip6_getdstifaddr(m)) &&
727 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
729 rstreason = BANDLIM_RST_OPENPORT;
735 so2 = sonewconn(so, 0);
737 tcpstat.tcps_listendrop++;
738 so2 = sodropablereq(so);
741 sototcpcb(so2)->t_flags |=
743 tcp_drop(sototcpcb(so2), ETIMEDOUT);
744 so2 = sonewconn(so, 0);
754 * This is ugly, but ....
756 * Mark socket as temporary until we're
757 * committed to keeping it. The code at
758 * ``drop'' and ``dropwithreset'' check the
759 * flag dropsocket to see if the temporary
760 * socket created here should be discarded.
761 * We mark the socket as discardable until
762 * we're committed to it below in TCPS_LISTEN.
765 inp = (struct inpcb *)so->so_pcb;
768 inp->in6p_laddr = ip6->ip6_dst;
770 inp->inp_vflag &= ~INP_IPV6;
771 inp->inp_vflag |= INP_IPV4;
773 inp->inp_laddr = ip->ip_dst;
777 inp->inp_lport = th->th_dport;
778 if (in_pcbinshash(inp) != 0) {
780 * Undo the assignments above if we failed to
781 * put the PCB on the hash lists.
785 inp->in6p_laddr = in6addr_any;
788 inp->inp_laddr.s_addr = INADDR_ANY;
794 * To avoid creating incorrectly cached IPsec
795 * association, this is need to be done here.
797 * Subject: (KAME-snap 748)
798 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
799 * ftp://ftp.kame.net/pub/mail-list/snap-users/748
801 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
803 * Note: dropwithreset makes sure we don't
804 * send a RST in response to a RST.
806 if (thflags & TH_ACK) {
807 tcpstat.tcps_badsyn++;
808 rstreason = BANDLIM_RST_OPENPORT;
817 * Inherit socket options from the listening
819 * Note that in6p_inputopts are not (even
820 * should not be) copied, since it stores
821 * previously received options and is used to
822 * detect if each new option is different than
823 * the previous one and hence should be passed
825 * If we copied in6p_inputopts, a user would
826 * not be able to receive options just after
827 * calling the accept system call.
830 oinp->inp_flags & INP_CONTROLOPTS;
831 if (oinp->in6p_outputopts)
832 inp->in6p_outputopts =
833 ip6_copypktopts(oinp->in6p_outputopts,
837 inp->inp_options = ip_srcroute();
839 /* copy old policy into new socket's */
840 if (ipsec_copy_policy(sotoinpcb(oso)->inp_sp,
842 printf("tcp_input: could not copy policy\n");
845 tp->t_state = TCPS_LISTEN;
846 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
848 /* Compute proper scaling value from buffer space */
849 while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
850 TCP_MAXWIN << tp->request_r_scale <
852 tp->request_r_scale++;
857 /* save packet options if user wanted */
858 if (isipv6 && (inp->in6p_flags & INP_CONTROLOPTS) != 0) {
859 struct ip6_recvpktopts opts6;
862 * Temporarily re-adjusting the mbuf before ip6_savecontrol(),
863 * which is necessary for FreeBSD only due to difference from
865 * XXX: we'll soon make a more natural fix after getting a
868 ip6_savecontrol(inp, ip6, m, &opts6, &inp->in6p_inputopts);
869 if (inp->in6p_inputopts)
870 ip6_update_recvpcbopt(inp->in6p_inputopts, &opts6);
872 if (sbappendcontrol(&inp->in6p_socket->so_rcv,
881 * Segment received on connection.
882 * Reset idle time and keep-alive timer.
884 tp->t_rcvtime = ticks;
885 if (TCPS_HAVEESTABLISHED(tp->t_state))
886 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
889 * Process options if not in LISTEN state,
890 * else do it below (after getting remote address).
892 if (tp->t_state != TCPS_LISTEN)
893 tcp_dooptions(tp, optp, optlen, th, &to);
896 * Header prediction: check for the two common cases
897 * of a uni-directional data xfer. If the packet has
898 * no control flags, is in-sequence, the window didn't
899 * change and we're not retransmitting, it's a
900 * candidate. If the length is zero and the ack moved
901 * forward, we're the sender side of the xfer. Just
902 * free the data acked & wake any higher level process
903 * that was blocked waiting for space. If the length
904 * is non-zero and the ack didn't move, we're the
905 * receiver side. If we're getting packets in-order
906 * (the reassembly queue is empty), add the data to
907 * the socket buffer and note that we need a delayed ack.
908 * Make sure that the hidden state-flags are also off.
909 * Since we check for TCPS_ESTABLISHED above, it can only
912 if (tp->t_state == TCPS_ESTABLISHED &&
913 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
914 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
915 ((to.to_flag & TOF_TS) == 0 ||
916 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
918 * Using the CC option is compulsory if once started:
919 * the segment is OK if no T/TCP was negotiated or
920 * if the segment has a CC option equal to CCrecv
922 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
923 ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
924 th->th_seq == tp->rcv_nxt &&
925 tiwin && tiwin == tp->snd_wnd &&
926 tp->snd_nxt == tp->snd_max) {
929 * If last ACK falls within this segment's sequence numbers,
930 * record the timestamp.
931 * NOTE that the test is modified according to the latest
932 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
934 if ((to.to_flag & TOF_TS) != 0 &&
935 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
936 tp->ts_recent_age = ticks;
937 tp->ts_recent = to.to_tsval;
941 if (SEQ_GT(th->th_ack, tp->snd_una) &&
942 SEQ_LEQ(th->th_ack, tp->snd_max) &&
943 tp->snd_cwnd >= tp->snd_wnd &&
944 tp->t_dupacks < tcprexmtthresh) {
946 * this is a pure ack for outstanding data.
948 ++tcpstat.tcps_predack;
950 * "bad retransmit" recovery
952 if (tp->t_rxtshift == 1 &&
953 ticks < tp->t_badrxtwin) {
954 tp->snd_cwnd = tp->snd_cwnd_prev;
956 tp->snd_ssthresh_prev;
957 tp->snd_nxt = tp->snd_max;
960 if ((to.to_flag & TOF_TS) != 0)
962 ticks - to.to_tsecr + 1);
963 else if (tp->t_rtttime &&
964 SEQ_GT(th->th_ack, tp->t_rtseq))
965 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
966 acked = th->th_ack - tp->snd_una;
967 tcpstat.tcps_rcvackpack++;
968 tcpstat.tcps_rcvackbyte += acked;
969 sbdrop(&so->so_snd, acked);
970 tp->snd_una = th->th_ack;
972 ND6_HINT(tp); /* some progress has been done */
975 * If all outstanding data are acked, stop
976 * retransmit timer, otherwise restart timer
977 * using current (possibly backed-off) value.
978 * If process is waiting for space,
979 * wakeup/selwakeup/signal. If data
980 * are ready to send, let tcp_output
981 * decide between more output or persist.
983 if (tp->snd_una == tp->snd_max)
984 callout_stop(tp->tt_rexmt);
985 else if (!callout_active(tp->tt_persist))
986 callout_reset(tp->tt_rexmt,
988 tcp_timer_rexmt, tp);
991 if (so->so_snd.sb_cc)
992 (void) tcp_output(tp);
995 } else if (th->th_ack == tp->snd_una &&
996 LIST_EMPTY(&tp->t_segq) &&
997 tlen <= sbspace(&so->so_rcv)) {
999 * this is a pure, in-sequence data packet
1000 * with nothing on the reassembly queue and
1001 * we have enough buffer space to take it.
1003 ++tcpstat.tcps_preddat;
1004 tp->rcv_nxt += tlen;
1005 tcpstat.tcps_rcvpack++;
1006 tcpstat.tcps_rcvbyte += tlen;
1007 ND6_HINT(tp); /* some progress has been done */
1009 * Add data to socket buffer.
1011 m_adj(m, drop_hdrlen); /* delayed header drop */
1012 sbappend(&so->so_rcv, m);
1014 if (DELAY_ACK(tp)) {
1015 callout_reset(tp->tt_delack, tcp_delacktime,
1016 tcp_timer_delack, tp);
1018 tp->t_flags |= TF_ACKNOW;
1026 * Calculate amount of space in receive window,
1027 * and then do TCP input processing.
1028 * Receive window is amount of space in rcv queue,
1029 * but not less than advertised window.
1033 win = sbspace(&so->so_rcv);
1036 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1039 switch (tp->t_state) {
1042 * If the state is LISTEN then ignore segment if it contains an RST.
1043 * If the segment contains an ACK then it is bad and send a RST.
1044 * If it does not contain a SYN then it is not interesting; drop it.
1045 * If it is from this socket, drop it, it must be forged.
1046 * Don't bother responding if the destination was a broadcast.
1047 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1048 * tp->iss, and send a segment:
1049 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1050 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1051 * Fill in remote peer address fields if not previously specified.
1052 * Enter SYN_RECEIVED state, and process any other fields of this
1053 * segment in this state.
1056 register struct sockaddr_in *sin;
1058 register struct sockaddr_in6 *sin6;
1061 if (thflags & TH_RST)
1063 if (thflags & TH_ACK) {
1064 rstreason = BANDLIM_RST_OPENPORT;
1067 if ((thflags & TH_SYN) == 0)
1069 if (th->th_dport == th->th_sport) {
1072 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1077 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1081 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1082 * in_broadcast() should never return true on a received
1083 * packet with M_BCAST not set.
1085 * Packets with a multicast source address should also
1088 if (m->m_flags & (M_BCAST|M_MCAST))
1092 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
1093 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
1097 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1098 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1099 ip->ip_src.s_addr == htonl(INADDR_BROADCAST))
1103 MALLOC(sin6, struct sockaddr_in6 *, sizeof *sin6,
1104 M_SONAME, M_NOWAIT);
1107 bzero(sin6, sizeof(*sin6));
1108 sin6->sin6_family = AF_INET6;
1109 sin6->sin6_len = sizeof(*sin6);
1110 sin6->sin6_addr = ip6->ip6_src;
1111 sin6->sin6_port = th->th_sport;
1112 laddr6 = inp->in6p_laddr;
1113 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1114 inp->in6p_laddr = ip6->ip6_dst;
1115 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
1116 (struct proc *)&proc0)) {
1117 inp->in6p_laddr = laddr6;
1118 FREE(sin6, M_SONAME);
1121 FREE(sin6, M_SONAME);
1125 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
1129 sin->sin_family = AF_INET;
1130 sin->sin_len = sizeof(*sin);
1131 sin->sin_addr = ip->ip_src;
1132 sin->sin_port = th->th_sport;
1133 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
1134 laddr = inp->inp_laddr;
1135 if (inp->inp_laddr.s_addr == INADDR_ANY)
1136 inp->inp_laddr = ip->ip_dst;
1137 if (in_pcbconnect(inp, (struct sockaddr *)sin, proc0)) {
1138 inp->inp_laddr = laddr;
1139 FREE(sin, M_SONAME);
1142 FREE(sin, M_SONAME);
1144 if ((taop = tcp_gettaocache(inp)) == NULL) {
1145 taop = &tao_noncached;
1146 bzero(taop, sizeof(*taop));
1148 tcp_dooptions(tp, optp, optlen, th, &to);
1152 tp->iss = tcp_new_isn(tp);
1154 tp->irs = th->th_seq;
1155 tcp_sendseqinit(tp);
1157 tp->snd_recover = tp->snd_una;
1159 * Initialization of the tcpcb for transaction;
1160 * set SND.WND = SEG.WND,
1161 * initialize CCsend and CCrecv.
1163 tp->snd_wnd = tiwin; /* initial send-window */
1164 tp->cc_send = CC_INC(tcp_ccgen);
1165 tp->cc_recv = to.to_cc;
1167 * Perform TAO test on incoming CC (SEG.CC) option, if any.
1168 * - compare SEG.CC against cached CC from the same host,
1170 * - if SEG.CC > chached value, SYN must be new and is accepted
1171 * immediately: save new CC in the cache, mark the socket
1172 * connected, enter ESTABLISHED state, turn on flag to
1173 * send a SYN in the next segment.
1174 * A virtual advertised window is set in rcv_adv to
1175 * initialize SWS prevention. Then enter normal segment
1176 * processing: drop SYN, process data and FIN.
1177 * - otherwise do a normal 3-way handshake.
1179 if ((to.to_flag & TOF_CC) != 0) {
1180 if (((tp->t_flags & TF_NOPUSH) != 0) &&
1181 taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
1183 taop->tao_cc = to.to_cc;
1184 tp->t_starttime = ticks;
1185 tp->t_state = TCPS_ESTABLISHED;
1188 * If there is a FIN, or if there is data and the
1189 * connection is local, then delay SYN,ACK(SYN) in
1190 * the hope of piggy-backing it on a response
1191 * segment. Otherwise must send ACK now in case
1192 * the other side is slow starting.
1194 if (DELAY_ACK(tp) && ((thflags & TH_FIN) ||
1197 ((isipv6 && in6_localaddr(&inp->in6p_faddr))
1201 in_localaddr(inp->inp_faddr)
1206 callout_reset(tp->tt_delack, tcp_delacktime,
1207 tcp_timer_delack, tp);
1208 tp->t_flags |= TF_NEEDSYN;
1210 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1213 * Limit the `virtual advertised window' to TCP_MAXWIN
1214 * here. Even if we requested window scaling, it will
1215 * become effective only later when our SYN is acked.
1217 tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
1218 tcpstat.tcps_connects++;
1220 callout_reset(tp->tt_keep, tcp_keepinit,
1221 tcp_timer_keep, tp);
1222 dropsocket = 0; /* committed to socket */
1223 tcpstat.tcps_accepts++;
1226 /* else do standard 3-way handshake */
1229 * No CC option, but maybe CC.NEW:
1230 * invalidate cached value.
1235 * TAO test failed or there was no CC option,
1236 * do a standard 3-way handshake.
1238 tp->t_flags |= TF_ACKNOW;
1239 tp->t_state = TCPS_SYN_RECEIVED;
1240 callout_reset(tp->tt_keep, tcp_keepinit, tcp_timer_keep, tp);
1241 dropsocket = 0; /* committed to socket */
1242 tcpstat.tcps_accepts++;
1247 * If the state is SYN_RECEIVED:
1248 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1250 case TCPS_SYN_RECEIVED:
1251 if ((thflags & TH_ACK) &&
1252 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1253 SEQ_GT(th->th_ack, tp->snd_max))) {
1254 rstreason = BANDLIM_RST_OPENPORT;
1260 * If the state is SYN_SENT:
1261 * if seg contains an ACK, but not for our SYN, drop the input.
1262 * if seg contains a RST, then drop the connection.
1263 * if seg does not contain SYN, then drop it.
1264 * Otherwise this is an acceptable SYN segment
1265 * initialize tp->rcv_nxt and tp->irs
1266 * if seg contains ack then advance tp->snd_una
1267 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1268 * arrange for segment to be acked (eventually)
1269 * continue processing rest of data/controls, beginning with URG
1272 if ((taop = tcp_gettaocache(inp)) == NULL) {
1273 taop = &tao_noncached;
1274 bzero(taop, sizeof(*taop));
1277 if ((thflags & TH_ACK) &&
1278 (SEQ_LEQ(th->th_ack, tp->iss) ||
1279 SEQ_GT(th->th_ack, tp->snd_max))) {
1281 * If we have a cached CCsent for the remote host,
1282 * hence we haven't just crashed and restarted,
1283 * do not send a RST. This may be a retransmission
1284 * from the other side after our earlier ACK was lost.
1285 * Our new SYN, when it arrives, will serve as the
1288 if (taop->tao_ccsent != 0)
1291 rstreason = BANDLIM_UNLIMITED;
1295 if (thflags & TH_RST) {
1296 if (thflags & TH_ACK)
1297 tp = tcp_drop(tp, ECONNREFUSED);
1300 if ((thflags & TH_SYN) == 0)
1302 tp->snd_wnd = th->th_win; /* initial send window */
1303 tp->cc_recv = to.to_cc; /* foreign CC */
1305 tp->irs = th->th_seq;
1307 if (thflags & TH_ACK) {
1309 * Our SYN was acked. If segment contains CC.ECHO
1310 * option, check it to make sure this segment really
1311 * matches our SYN. If not, just drop it as old
1312 * duplicate, but send an RST if we're still playing
1313 * by the old rules. If no CC.ECHO option, make sure
1314 * we don't get fooled into using T/TCP.
1316 if (to.to_flag & TOF_CCECHO) {
1317 if (tp->cc_send != to.to_ccecho) {
1318 if (taop->tao_ccsent != 0)
1321 rstreason = BANDLIM_UNLIMITED;
1326 tp->t_flags &= ~TF_RCVD_CC;
1327 tcpstat.tcps_connects++;
1329 /* Do window scaling on this connection? */
1330 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1331 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1332 tp->snd_scale = tp->requested_s_scale;
1333 tp->rcv_scale = tp->request_r_scale;
1335 /* Segment is acceptable, update cache if undefined. */
1336 if (taop->tao_ccsent == 0)
1337 taop->tao_ccsent = to.to_ccecho;
1339 tp->rcv_adv += tp->rcv_wnd;
1340 tp->snd_una++; /* SYN is acked */
1342 * If there's data, delay ACK; if there's also a FIN
1343 * ACKNOW will be turned on later.
1345 if (DELAY_ACK(tp) && tlen != 0)
1346 callout_reset(tp->tt_delack, tcp_delacktime,
1347 tcp_timer_delack, tp);
1349 tp->t_flags |= TF_ACKNOW;
1351 * Received <SYN,ACK> in SYN_SENT[*] state.
1353 * SYN_SENT --> ESTABLISHED
1354 * SYN_SENT* --> FIN_WAIT_1
1356 tp->t_starttime = ticks;
1357 if (tp->t_flags & TF_NEEDFIN) {
1358 tp->t_state = TCPS_FIN_WAIT_1;
1359 tp->t_flags &= ~TF_NEEDFIN;
1362 tp->t_state = TCPS_ESTABLISHED;
1363 callout_reset(tp->tt_keep, tcp_keepidle,
1364 tcp_timer_keep, tp);
1368 * Received initial SYN in SYN-SENT[*] state => simul-
1369 * taneous open. If segment contains CC option and there is
1370 * a cached CC, apply TAO test; if it succeeds, connection is
1371 * half-synchronized. Otherwise, do 3-way handshake:
1372 * SYN-SENT -> SYN-RECEIVED
1373 * SYN-SENT* -> SYN-RECEIVED*
1374 * If there was no CC option, clear cached CC value.
1376 tp->t_flags |= TF_ACKNOW;
1377 callout_stop(tp->tt_rexmt);
1378 if (to.to_flag & TOF_CC) {
1379 if (taop->tao_cc != 0 &&
1380 CC_GT(to.to_cc, taop->tao_cc)) {
1382 * update cache and make transition:
1383 * SYN-SENT -> ESTABLISHED*
1384 * SYN-SENT* -> FIN-WAIT-1*
1386 taop->tao_cc = to.to_cc;
1387 tp->t_starttime = ticks;
1388 if (tp->t_flags & TF_NEEDFIN) {
1389 tp->t_state = TCPS_FIN_WAIT_1;
1390 tp->t_flags &= ~TF_NEEDFIN;
1392 tp->t_state = TCPS_ESTABLISHED;
1393 callout_reset(tp->tt_keep,
1398 tp->t_flags |= TF_NEEDSYN;
1400 tp->t_state = TCPS_SYN_RECEIVED;
1402 /* CC.NEW or no option => invalidate cache */
1404 tp->t_state = TCPS_SYN_RECEIVED;
1410 * Advance th->th_seq to correspond to first data byte.
1411 * If data, trim to stay within window,
1412 * dropping FIN if necessary.
1415 if (tlen > tp->rcv_wnd) {
1416 todrop = tlen - tp->rcv_wnd;
1420 tcpstat.tcps_rcvpackafterwin++;
1421 tcpstat.tcps_rcvbyteafterwin += todrop;
1423 tp->snd_wl1 = th->th_seq - 1;
1424 tp->rcv_up = th->th_seq;
1426 * Client side of transaction: already sent SYN and data.
1427 * If the remote host used T/TCP to validate the SYN,
1428 * our data will be ACK'd; if so, enter normal data segment
1429 * processing in the middle of step 5, ack processing.
1430 * Otherwise, goto step 6.
1432 if (thflags & TH_ACK)
1436 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1437 * if segment contains a SYN and CC [not CC.NEW] option:
1438 * if state == TIME_WAIT and connection duration > MSL,
1439 * drop packet and send RST;
1441 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1442 * ack the FIN (and data) in retransmission queue.
1443 * Complete close and delete TCPCB. Then reprocess
1444 * segment, hoping to find new TCPCB in LISTEN state;
1446 * else must be old SYN; drop it.
1447 * else do normal processing.
1451 case TCPS_TIME_WAIT:
1452 if ((thflags & TH_SYN) &&
1453 (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
1454 if (tp->t_state == TCPS_TIME_WAIT &&
1455 (ticks - tp->t_starttime) > tcp_msl) {
1456 rstreason = BANDLIM_UNLIMITED;
1459 if (CC_GT(to.to_cc, tp->cc_recv)) {
1466 break; /* continue normal processing */
1470 * States other than LISTEN or SYN_SENT.
1471 * First check the RST flag and sequence number since reset segments
1472 * are exempt from the timestamp and connection count tests. This
1473 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1474 * below which allowed reset segments in half the sequence space
1475 * to fall though and be processed (which gives forged reset
1476 * segments with a random sequence number a 50 percent chance of
1477 * killing a connection).
1478 * Then check timestamp, if present.
1479 * Then check the connection count, if present.
1480 * Then check that at least some bytes of segment are within
1481 * receive window. If segment begins before rcv_nxt,
1482 * drop leading data (and SYN); if nothing left, just ack.
1485 * If the RST bit is set, check the sequence number to see
1486 * if this is a valid reset segment.
1488 * In all states except SYN-SENT, all reset (RST) segments
1489 * are validated by checking their SEQ-fields. A reset is
1490 * valid if its sequence number is in the window.
1491 * Note: this does not take into account delayed ACKs, so
1492 * we should test against last_ack_sent instead of rcv_nxt.
1493 * The sequence number in the reset segment is normally an
1494 * echo of our outgoing acknowlegement numbers, but some hosts
1495 * send a reset with the sequence number at the rightmost edge
1496 * of our receive window, and we have to handle this case.
1497 * If we have multiple segments in flight, the intial reset
1498 * segment sequence numbers will be to the left of last_ack_sent,
1499 * but they will eventually catch up.
1500 * In any case, it never made sense to trim reset segments to
1501 * fit the receive window since RFC 1122 says:
1502 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1504 * A TCP SHOULD allow a received RST segment to include data.
1507 * It has been suggested that a RST segment could contain
1508 * ASCII text that encoded and explained the cause of the
1509 * RST. No standard has yet been established for such
1512 * If the reset segment passes the sequence number test examine
1514 * SYN_RECEIVED STATE:
1515 * If passive open, return to LISTEN state.
1516 * If active open, inform user that connection was refused.
1517 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1518 * Inform user that connection was reset, and close tcb.
1519 * CLOSING, LAST_ACK STATES:
1522 * Drop the segment - see Stevens, vol. 2, p. 964 and
1525 if (thflags & TH_RST) {
1526 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1527 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1528 switch (tp->t_state) {
1530 case TCPS_SYN_RECEIVED:
1531 so->so_error = ECONNREFUSED;
1534 case TCPS_ESTABLISHED:
1535 case TCPS_FIN_WAIT_1:
1536 case TCPS_FIN_WAIT_2:
1537 case TCPS_CLOSE_WAIT:
1538 so->so_error = ECONNRESET;
1540 tp->t_state = TCPS_CLOSED;
1541 tcpstat.tcps_drops++;
1550 case TCPS_TIME_WAIT:
1558 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1559 * and it's less than ts_recent, drop it.
1561 if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1562 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1564 /* Check to see if ts_recent is over 24 days old. */
1565 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1567 * Invalidate ts_recent. If this segment updates
1568 * ts_recent, the age will be reset later and ts_recent
1569 * will get a valid value. If it does not, setting
1570 * ts_recent to zero will at least satisfy the
1571 * requirement that zero be placed in the timestamp
1572 * echo reply when ts_recent isn't valid. The
1573 * age isn't reset until we get a valid ts_recent
1574 * because we don't want out-of-order segments to be
1575 * dropped when ts_recent is old.
1579 tcpstat.tcps_rcvduppack++;
1580 tcpstat.tcps_rcvdupbyte += tlen;
1581 tcpstat.tcps_pawsdrop++;
1588 * If T/TCP was negotiated and the segment doesn't have CC,
1589 * or if its CC is wrong then drop the segment.
1590 * RST segments do not have to comply with this.
1592 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1593 ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1597 * In the SYN-RECEIVED state, validate that the packet belongs to
1598 * this connection before trimming the data to fit the receive
1599 * window. Check the sequence number versus IRS since we know
1600 * the sequence numbers haven't wrapped. This is a partial fix
1601 * for the "LAND" DoS attack.
1603 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1604 rstreason = BANDLIM_UNLIMITED;
1608 todrop = tp->rcv_nxt - th->th_seq;
1610 if (thflags & TH_SYN) {
1620 * Following if statement from Stevens, vol. 2, p. 960.
1623 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1625 * Any valid FIN must be to the left of the window.
1626 * At this point the FIN must be a duplicate or out
1627 * of sequence; drop it.
1632 * Send an ACK to resynchronize and drop any data.
1633 * But keep on processing for RST or ACK.
1635 tp->t_flags |= TF_ACKNOW;
1637 tcpstat.tcps_rcvduppack++;
1638 tcpstat.tcps_rcvdupbyte += todrop;
1640 tcpstat.tcps_rcvpartduppack++;
1641 tcpstat.tcps_rcvpartdupbyte += todrop;
1643 drop_hdrlen += todrop; /* drop from the top afterwards */
1644 th->th_seq += todrop;
1646 if (th->th_urp > todrop)
1647 th->th_urp -= todrop;
1655 * If new data are received on a connection after the
1656 * user processes are gone, then RST the other end.
1658 if ((so->so_state & SS_NOFDREF) &&
1659 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1661 tcpstat.tcps_rcvafterclose++;
1662 rstreason = BANDLIM_UNLIMITED;
1667 * If segment ends after window, drop trailing data
1668 * (and PUSH and FIN); if nothing left, just ACK.
1670 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1672 tcpstat.tcps_rcvpackafterwin++;
1673 if (todrop >= tlen) {
1674 tcpstat.tcps_rcvbyteafterwin += tlen;
1676 * If a new connection request is received
1677 * while in TIME_WAIT, drop the old connection
1678 * and start over if the sequence numbers
1679 * are above the previous ones.
1681 if (thflags & TH_SYN &&
1682 tp->t_state == TCPS_TIME_WAIT &&
1683 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1684 iss = tcp_new_isn(tp);
1689 * If window is closed can only take segments at
1690 * window edge, and have to drop data and PUSH from
1691 * incoming segments. Continue processing, but
1692 * remember to ack. Otherwise, drop segment
1695 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1696 tp->t_flags |= TF_ACKNOW;
1697 tcpstat.tcps_rcvwinprobe++;
1701 tcpstat.tcps_rcvbyteafterwin += todrop;
1704 thflags &= ~(TH_PUSH|TH_FIN);
1708 * If last ACK falls within this segment's sequence numbers,
1709 * record its timestamp.
1710 * NOTE that the test is modified according to the latest
1711 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1713 if ((to.to_flag & TOF_TS) != 0 &&
1714 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1715 tp->ts_recent_age = ticks;
1716 tp->ts_recent = to.to_tsval;
1720 * If a SYN is in the window, then this is an
1721 * error and we send an RST and drop the connection.
1723 if (thflags & TH_SYN) {
1724 tp = tcp_drop(tp, ECONNRESET);
1725 rstreason = BANDLIM_UNLIMITED;
1730 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1731 * flag is on (half-synchronized state), then queue data for
1732 * later processing; else drop segment and return.
1734 if ((thflags & TH_ACK) == 0) {
1735 if (tp->t_state == TCPS_SYN_RECEIVED ||
1736 (tp->t_flags & TF_NEEDSYN))
1745 switch (tp->t_state) {
1748 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1749 * ESTABLISHED state and continue processing.
1750 * The ACK was checked above.
1752 case TCPS_SYN_RECEIVED:
1754 tcpstat.tcps_connects++;
1756 /* Do window scaling? */
1757 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1758 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1759 tp->snd_scale = tp->requested_s_scale;
1760 tp->rcv_scale = tp->request_r_scale;
1763 * Upon successful completion of 3-way handshake,
1764 * update cache.CC if it was undefined, pass any queued
1765 * data to the user, and advance state appropriately.
1767 if ((taop = tcp_gettaocache(inp)) != NULL &&
1769 taop->tao_cc = tp->cc_recv;
1773 * SYN-RECEIVED -> ESTABLISHED
1774 * SYN-RECEIVED* -> FIN-WAIT-1
1776 tp->t_starttime = ticks;
1777 if (tp->t_flags & TF_NEEDFIN) {
1778 tp->t_state = TCPS_FIN_WAIT_1;
1779 tp->t_flags &= ~TF_NEEDFIN;
1781 tp->t_state = TCPS_ESTABLISHED;
1782 callout_reset(tp->tt_keep, tcp_keepidle,
1783 tcp_timer_keep, tp);
1786 * If segment contains data or ACK, will call tcp_reass()
1787 * later; if not, do so now to pass queued data to user.
1789 if (tlen == 0 && (thflags & TH_FIN) == 0)
1790 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1792 tp->snd_wl1 = th->th_seq - 1;
1796 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1797 * ACKs. If the ack is in the range
1798 * tp->snd_una < th->th_ack <= tp->snd_max
1799 * then advance tp->snd_una to th->th_ack and drop
1800 * data from the retransmission queue. If this ACK reflects
1801 * more up to date window information we update our window information.
1803 case TCPS_ESTABLISHED:
1804 case TCPS_FIN_WAIT_1:
1805 case TCPS_FIN_WAIT_2:
1806 case TCPS_CLOSE_WAIT:
1809 case TCPS_TIME_WAIT:
1811 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1812 if (tlen == 0 && tiwin == tp->snd_wnd) {
1813 tcpstat.tcps_rcvdupack++;
1815 * If we have outstanding data (other than
1816 * a window probe), this is a completely
1817 * duplicate ack (ie, window info didn't
1818 * change), the ack is the biggest we've
1819 * seen and we've seen exactly our rexmt
1820 * threshhold of them, assume a packet
1821 * has been dropped and retransmit it.
1822 * Kludge snd_nxt & the congestion
1823 * window so we send only this one
1826 * We know we're losing at the current
1827 * window size so do congestion avoidance
1828 * (set ssthresh to half the current window
1829 * and pull our congestion window back to
1830 * the new ssthresh).
1832 * Dup acks mean that packets have left the
1833 * network (they're now cached at the receiver)
1834 * so bump cwnd by the amount in the receiver
1835 * to keep a constant cwnd packets in the
1838 if (!callout_active(tp->tt_rexmt) ||
1839 th->th_ack != tp->snd_una)
1841 else if (++tp->t_dupacks == tcprexmtthresh) {
1842 tcp_seq onxt = tp->snd_nxt;
1844 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1846 if (tcp_do_newreno && SEQ_LT(th->th_ack,
1848 /* False retransmit, should not
1851 tp->snd_cwnd += tp->t_maxseg;
1853 (void) tcp_output(tp);
1858 tp->snd_ssthresh = win * tp->t_maxseg;
1859 tp->snd_recover = tp->snd_max;
1860 callout_stop(tp->tt_rexmt);
1862 tp->snd_nxt = th->th_ack;
1863 tp->snd_cwnd = tp->t_maxseg;
1864 (void) tcp_output(tp);
1865 tp->snd_cwnd = tp->snd_ssthresh +
1866 tp->t_maxseg * tp->t_dupacks;
1867 if (SEQ_GT(onxt, tp->snd_nxt))
1870 } else if (tp->t_dupacks > tcprexmtthresh) {
1871 tp->snd_cwnd += tp->t_maxseg;
1872 (void) tcp_output(tp);
1880 * If the congestion window was inflated to account
1881 * for the other side's cached packets, retract it.
1883 if (tcp_do_newreno == 0) {
1884 if (tp->t_dupacks >= tcprexmtthresh &&
1885 tp->snd_cwnd > tp->snd_ssthresh)
1886 tp->snd_cwnd = tp->snd_ssthresh;
1888 } else if (tp->t_dupacks >= tcprexmtthresh &&
1889 !tcp_newreno(tp, th)) {
1891 * Window inflation should have left us with approx.
1892 * snd_ssthresh outstanding data. But in case we
1893 * would be inclined to send a burst, better to do
1894 * it via the slow start mechanism.
1896 if (SEQ_GT(th->th_ack + tp->snd_ssthresh, tp->snd_max))
1898 tp->snd_max - th->th_ack + tp->t_maxseg;
1900 tp->snd_cwnd = tp->snd_ssthresh;
1903 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1904 tcpstat.tcps_rcvacktoomuch++;
1908 * If we reach this point, ACK is not a duplicate,
1909 * i.e., it ACKs something we sent.
1911 if (tp->t_flags & TF_NEEDSYN) {
1913 * T/TCP: Connection was half-synchronized, and our
1914 * SYN has been ACK'd (so connection is now fully
1915 * synchronized). Go to non-starred state,
1916 * increment snd_una for ACK of SYN, and check if
1917 * we can do window scaling.
1919 tp->t_flags &= ~TF_NEEDSYN;
1921 /* Do window scaling? */
1922 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1923 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1924 tp->snd_scale = tp->requested_s_scale;
1925 tp->rcv_scale = tp->request_r_scale;
1930 acked = th->th_ack - tp->snd_una;
1931 tcpstat.tcps_rcvackpack++;
1932 tcpstat.tcps_rcvackbyte += acked;
1935 * If we just performed our first retransmit, and the ACK
1936 * arrives within our recovery window, then it was a mistake
1937 * to do the retransmit in the first place. Recover our
1938 * original cwnd and ssthresh, and proceed to transmit where
1941 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1942 tp->snd_cwnd = tp->snd_cwnd_prev;
1943 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1944 tp->snd_nxt = tp->snd_max;
1945 tp->t_badrxtwin = 0; /* XXX probably not required */
1949 * If we have a timestamp reply, update smoothed
1950 * round trip time. If no timestamp is present but
1951 * transmit timer is running and timed sequence
1952 * number was acked, update smoothed round trip time.
1953 * Since we now have an rtt measurement, cancel the
1954 * timer backoff (cf., Phil Karn's retransmit alg.).
1955 * Recompute the initial retransmit timer.
1957 if (to.to_flag & TOF_TS)
1958 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1959 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
1960 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1963 * If all outstanding data is acked, stop retransmit
1964 * timer and remember to restart (more output or persist).
1965 * If there is more data to be acked, restart retransmit
1966 * timer, using current (possibly backed-off) value.
1968 if (th->th_ack == tp->snd_max) {
1969 callout_stop(tp->tt_rexmt);
1971 } else if (!callout_active(tp->tt_persist))
1972 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1973 tcp_timer_rexmt, tp);
1976 * If no data (only SYN) was ACK'd,
1977 * skip rest of ACK processing.
1983 * When new data is acked, open the congestion window.
1984 * If the window gives us less than ssthresh packets
1985 * in flight, open exponentially (maxseg per packet).
1986 * Otherwise open linearly: maxseg per window
1987 * (maxseg^2 / cwnd per packet).
1990 register u_int cw = tp->snd_cwnd;
1991 register u_int incr = tp->t_maxseg;
1993 if (cw > tp->snd_ssthresh)
1994 incr = incr * incr / cw;
1996 * If t_dupacks != 0 here, it indicates that we are still
1997 * in NewReno fast recovery mode, so we leave the congestion
2000 if (tcp_do_newreno == 0 || tp->t_dupacks == 0)
2001 tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
2003 if (acked > so->so_snd.sb_cc) {
2004 tp->snd_wnd -= so->so_snd.sb_cc;
2005 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2008 sbdrop(&so->so_snd, acked);
2009 tp->snd_wnd -= acked;
2013 tp->snd_una = th->th_ack;
2014 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2015 tp->snd_nxt = tp->snd_una;
2017 switch (tp->t_state) {
2020 * In FIN_WAIT_1 STATE in addition to the processing
2021 * for the ESTABLISHED state if our FIN is now acknowledged
2022 * then enter FIN_WAIT_2.
2024 case TCPS_FIN_WAIT_1:
2025 if (ourfinisacked) {
2027 * If we can't receive any more
2028 * data, then closing user can proceed.
2029 * Starting the timer is contrary to the
2030 * specification, but if we don't get a FIN
2031 * we'll hang forever.
2033 if (so->so_state & SS_CANTRCVMORE) {
2034 soisdisconnected(so);
2035 callout_reset(tp->tt_2msl, tcp_maxidle,
2036 tcp_timer_2msl, tp);
2038 tp->t_state = TCPS_FIN_WAIT_2;
2043 * In CLOSING STATE in addition to the processing for
2044 * the ESTABLISHED state if the ACK acknowledges our FIN
2045 * then enter the TIME-WAIT state, otherwise ignore
2049 if (ourfinisacked) {
2050 tp->t_state = TCPS_TIME_WAIT;
2051 tcp_canceltimers(tp);
2052 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2053 if (tp->cc_recv != 0 &&
2054 (ticks - tp->t_starttime) < tcp_msl) {
2055 callout_reset(tp->tt_2msl,
2058 tcp_timer_2msl, tp);
2061 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2062 tcp_timer_2msl, tp);
2064 soisdisconnected(so);
2069 * In LAST_ACK, we may still be waiting for data to drain
2070 * and/or to be acked, as well as for the ack of our FIN.
2071 * If our FIN is now acknowledged, delete the TCB,
2072 * enter the closed state and return.
2075 if (ourfinisacked) {
2082 * In TIME_WAIT state the only thing that should arrive
2083 * is a retransmission of the remote FIN. Acknowledge
2084 * it and restart the finack timer.
2086 case TCPS_TIME_WAIT:
2087 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2088 tcp_timer_2msl, tp);
2095 * Update window information.
2096 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2098 if ((thflags & TH_ACK) &&
2099 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2100 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2101 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2102 /* keep track of pure window updates */
2104 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2105 tcpstat.tcps_rcvwinupd++;
2106 tp->snd_wnd = tiwin;
2107 tp->snd_wl1 = th->th_seq;
2108 tp->snd_wl2 = th->th_ack;
2109 if (tp->snd_wnd > tp->max_sndwnd)
2110 tp->max_sndwnd = tp->snd_wnd;
2115 * Process segments with URG.
2117 if ((thflags & TH_URG) && th->th_urp &&
2118 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2120 * This is a kludge, but if we receive and accept
2121 * random urgent pointers, we'll crash in
2122 * soreceive. It's hard to imagine someone
2123 * actually wanting to send this much urgent data.
2125 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2126 th->th_urp = 0; /* XXX */
2127 thflags &= ~TH_URG; /* XXX */
2128 goto dodata; /* XXX */
2131 * If this segment advances the known urgent pointer,
2132 * then mark the data stream. This should not happen
2133 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2134 * a FIN has been received from the remote side.
2135 * In these states we ignore the URG.
2137 * According to RFC961 (Assigned Protocols),
2138 * the urgent pointer points to the last octet
2139 * of urgent data. We continue, however,
2140 * to consider it to indicate the first octet
2141 * of data past the urgent section as the original
2142 * spec states (in one of two places).
2144 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2145 tp->rcv_up = th->th_seq + th->th_urp;
2146 so->so_oobmark = so->so_rcv.sb_cc +
2147 (tp->rcv_up - tp->rcv_nxt) - 1;
2148 if (so->so_oobmark == 0)
2149 so->so_state |= SS_RCVATMARK;
2151 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2154 * Remove out of band data so doesn't get presented to user.
2155 * This can happen independent of advancing the URG pointer,
2156 * but if two URG's are pending at once, some out-of-band
2157 * data may creep in... ick.
2159 if (th->th_urp <= (u_long)tlen
2161 && (so->so_options & SO_OOBINLINE) == 0
2164 tcp_pulloutofband(so, th, m,
2165 drop_hdrlen); /* hdr drop is delayed */
2168 * If no out of band data is expected,
2169 * pull receive urgent pointer along
2170 * with the receive window.
2172 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2173 tp->rcv_up = tp->rcv_nxt;
2177 * Process the segment text, merging it into the TCP sequencing queue,
2178 * and arranging for acknowledgment of receipt if necessary.
2179 * This process logically involves adjusting tp->rcv_wnd as data
2180 * is presented to the user (this happens in tcp_usrreq.c,
2181 * case PRU_RCVD). If a FIN has already been received on this
2182 * connection then we just ignore the text.
2184 if ((tlen || (thflags&TH_FIN)) &&
2185 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2186 m_adj(m, drop_hdrlen); /* delayed header drop */
2188 * Insert segment which inludes th into reassembly queue of tcp with
2189 * control block tp. Return TH_FIN if reassembly now includes
2190 * a segment with FIN. This handle the common case inline (segment
2191 * is the next to be received on an established connection, and the
2192 * queue is empty), avoiding linkage into and removal from the queue
2193 * and repetition of various conversions.
2194 * Set DELACK for segments received in order, but ack immediately
2195 * when segments are out of order (so fast retransmit can work).
2197 if (th->th_seq == tp->rcv_nxt &&
2198 LIST_EMPTY(&tp->t_segq) &&
2199 TCPS_HAVEESTABLISHED(tp->t_state)) {
2201 callout_reset(tp->tt_delack, tcp_delacktime,
2202 tcp_timer_delack, tp);
2204 tp->t_flags |= TF_ACKNOW;
2205 tp->rcv_nxt += tlen;
2206 thflags = th->th_flags & TH_FIN;
2207 tcpstat.tcps_rcvpack++;
2208 tcpstat.tcps_rcvbyte += tlen;
2210 sbappend(&so->so_rcv, m);
2213 thflags = tcp_reass(tp, th, &tlen, m);
2214 tp->t_flags |= TF_ACKNOW;
2218 * Note the amount of data that peer has sent into
2219 * our window, in order to estimate the sender's
2222 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2229 * If FIN is received ACK the FIN and let the user know
2230 * that the connection is closing.
2232 if (thflags & TH_FIN) {
2233 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2236 * If connection is half-synchronized
2237 * (ie NEEDSYN flag on) then delay ACK,
2238 * so it may be piggybacked when SYN is sent.
2239 * Otherwise, since we received a FIN then no
2240 * more input can be expected, send ACK now.
2242 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2243 callout_reset(tp->tt_delack, tcp_delacktime,
2244 tcp_timer_delack, tp);
2246 tp->t_flags |= TF_ACKNOW;
2249 switch (tp->t_state) {
2252 * In SYN_RECEIVED and ESTABLISHED STATES
2253 * enter the CLOSE_WAIT state.
2255 case TCPS_SYN_RECEIVED:
2256 tp->t_starttime = ticks;
2258 case TCPS_ESTABLISHED:
2259 tp->t_state = TCPS_CLOSE_WAIT;
2263 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2264 * enter the CLOSING state.
2266 case TCPS_FIN_WAIT_1:
2267 tp->t_state = TCPS_CLOSING;
2271 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2272 * starting the time-wait timer, turning off the other
2275 case TCPS_FIN_WAIT_2:
2276 tp->t_state = TCPS_TIME_WAIT;
2277 tcp_canceltimers(tp);
2278 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2279 if (tp->cc_recv != 0 &&
2280 (ticks - tp->t_starttime) < tcp_msl) {
2281 callout_reset(tp->tt_2msl,
2282 tp->t_rxtcur * TCPTV_TWTRUNC,
2283 tcp_timer_2msl, tp);
2284 /* For transaction client, force ACK now. */
2285 tp->t_flags |= TF_ACKNOW;
2288 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2289 tcp_timer_2msl, tp);
2291 soisdisconnected(so);
2295 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2297 case TCPS_TIME_WAIT:
2298 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2299 tcp_timer_2msl, tp);
2304 if (so->so_options & SO_DEBUG)
2305 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2310 * Return any desired output.
2312 if (needoutput || (tp->t_flags & TF_ACKNOW))
2313 (void) tcp_output(tp);
2318 * Generate an ACK dropping incoming segment if it occupies
2319 * sequence space, where the ACK reflects our state.
2321 * We can now skip the test for the RST flag since all
2322 * paths to this code happen after packets containing
2323 * RST have been dropped.
2325 * In the SYN-RECEIVED state, don't send an ACK unless the
2326 * segment we received passes the SYN-RECEIVED ACK test.
2327 * If it fails send a RST. This breaks the loop in the
2328 * "LAND" DoS attack, and also prevents an ACK storm
2329 * between two listening ports that have been sent forged
2330 * SYN segments, each with the source address of the other.
2332 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2333 (SEQ_GT(tp->snd_una, th->th_ack) ||
2334 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2335 rstreason = BANDLIM_RST_OPENPORT;
2339 if (so->so_options & SO_DEBUG)
2340 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2344 tp->t_flags |= TF_ACKNOW;
2345 (void) tcp_output(tp);
2350 * Generate a RST, dropping incoming segment.
2351 * Make ACK acceptable to originator of segment.
2352 * Don't bother to respond if destination was broadcast/multicast.
2354 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2358 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2359 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2363 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2364 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2365 ip->ip_src.s_addr == htonl(INADDR_BROADCAST))
2367 /* IPv6 anycast check is done at tcp6_input() */
2370 * Perform bandwidth limiting.
2373 if (badport_bandlim(rstreason) < 0)
2378 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2379 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2382 if (thflags & TH_ACK)
2383 /* mtod() below is safe as long as hdr dropping is delayed */
2384 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2387 if (thflags & TH_SYN)
2389 /* mtod() below is safe as long as hdr dropping is delayed */
2390 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2391 (tcp_seq)0, TH_RST|TH_ACK);
2393 /* destroy temporarily created socket */
2400 * Drop space held by incoming segment and return.
2403 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2404 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2408 /* destroy temporarily created socket */
2415 tcp_dooptions(tp, cp, cnt, th, to)
2425 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2427 if (opt == TCPOPT_EOL)
2429 if (opt == TCPOPT_NOP)
2435 if (optlen < 2 || optlen > cnt)
2444 if (optlen != TCPOLEN_MAXSEG)
2446 if (!(th->th_flags & TH_SYN))
2448 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
2453 if (optlen != TCPOLEN_WINDOW)
2455 if (!(th->th_flags & TH_SYN))
2457 tp->t_flags |= TF_RCVD_SCALE;
2458 tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2461 case TCPOPT_TIMESTAMP:
2462 if (optlen != TCPOLEN_TIMESTAMP)
2464 to->to_flag |= TOF_TS;
2465 bcopy((char *)cp + 2,
2466 (char *)&to->to_tsval, sizeof(to->to_tsval));
2467 NTOHL(to->to_tsval);
2468 bcopy((char *)cp + 6,
2469 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2470 NTOHL(to->to_tsecr);
2473 * A timestamp received in a SYN makes
2474 * it ok to send timestamp requests and replies.
2476 if (th->th_flags & TH_SYN) {
2477 tp->t_flags |= TF_RCVD_TSTMP;
2478 tp->ts_recent = to->to_tsval;
2479 tp->ts_recent_age = ticks;
2483 if (optlen != TCPOLEN_CC)
2485 to->to_flag |= TOF_CC;
2486 bcopy((char *)cp + 2,
2487 (char *)&to->to_cc, sizeof(to->to_cc));
2490 * A CC or CC.new option received in a SYN makes
2491 * it ok to send CC in subsequent segments.
2493 if (th->th_flags & TH_SYN)
2494 tp->t_flags |= TF_RCVD_CC;
2497 if (optlen != TCPOLEN_CC)
2499 if (!(th->th_flags & TH_SYN))
2501 to->to_flag |= TOF_CCNEW;
2502 bcopy((char *)cp + 2,
2503 (char *)&to->to_cc, sizeof(to->to_cc));
2506 * A CC or CC.new option received in a SYN makes
2507 * it ok to send CC in subsequent segments.
2509 tp->t_flags |= TF_RCVD_CC;
2512 if (optlen != TCPOLEN_CC)
2514 if (!(th->th_flags & TH_SYN))
2516 to->to_flag |= TOF_CCECHO;
2517 bcopy((char *)cp + 2,
2518 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2519 NTOHL(to->to_ccecho);
2523 if (th->th_flags & TH_SYN)
2524 tcp_mss(tp, mss); /* sets t_maxseg */
2528 * Pull out of band byte out of a segment so
2529 * it doesn't appear in the user's data queue.
2530 * It is still reflected in the segment length for
2531 * sequencing purposes.
2534 tcp_pulloutofband(so, th, m, off)
2537 register struct mbuf *m;
2538 int off; /* delayed to be droped hdrlen */
2540 int cnt = off + th->th_urp - 1;
2543 if (m->m_len > cnt) {
2544 char *cp = mtod(m, caddr_t) + cnt;
2545 struct tcpcb *tp = sototcpcb(so);
2548 tp->t_oobflags |= TCPOOB_HAVEDATA;
2549 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2551 if (m->m_flags & M_PKTHDR)
2560 panic("tcp_pulloutofband");
2564 * Collect new round-trip time estimate
2565 * and update averages and current timeout.
2568 tcp_xmit_timer(tp, rtt)
2569 register struct tcpcb *tp;
2574 tcpstat.tcps_rttupdated++;
2576 if (tp->t_srtt != 0) {
2578 * srtt is stored as fixed point with 5 bits after the
2579 * binary point (i.e., scaled by 8). The following magic
2580 * is equivalent to the smoothing algorithm in rfc793 with
2581 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2582 * point). Adjust rtt to origin 0.
2584 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2585 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2587 if ((tp->t_srtt += delta) <= 0)
2591 * We accumulate a smoothed rtt variance (actually, a
2592 * smoothed mean difference), then set the retransmit
2593 * timer to smoothed rtt + 4 times the smoothed variance.
2594 * rttvar is stored as fixed point with 4 bits after the
2595 * binary point (scaled by 16). The following is
2596 * equivalent to rfc793 smoothing with an alpha of .75
2597 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2598 * rfc793's wired-in beta.
2602 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2603 if ((tp->t_rttvar += delta) <= 0)
2607 * No rtt measurement yet - use the unsmoothed rtt.
2608 * Set the variance to half the rtt (so our first
2609 * retransmit happens at 3*rtt).
2611 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2612 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2618 * the retransmit should happen at rtt + 4 * rttvar.
2619 * Because of the way we do the smoothing, srtt and rttvar
2620 * will each average +1/2 tick of bias. When we compute
2621 * the retransmit timer, we want 1/2 tick of rounding and
2622 * 1 extra tick because of +-1/2 tick uncertainty in the
2623 * firing of the timer. The bias will give us exactly the
2624 * 1.5 tick we need. But, because the bias is
2625 * statistical, we have to test that we don't drop below
2626 * the minimum feasible timer (which is 2 ticks).
2628 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2629 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2632 * We received an ack for a packet that wasn't retransmitted;
2633 * it is probably safe to discard any error indications we've
2634 * received recently. This isn't quite right, but close enough
2635 * for now (a route might have failed after we sent a segment,
2636 * and the return path might not be symmetrical).
2638 tp->t_softerror = 0;
2642 * Determine a reasonable value for maxseg size.
2643 * If the route is known, check route for mtu.
2644 * If none, use an mss that can be handled on the outgoing
2645 * interface without forcing IP to fragment; if bigger than
2646 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2647 * to utilize large mbufs. If no route is found, route has no mtu,
2648 * or the destination isn't local, use a default, hopefully conservative
2649 * size (usually 512 or the default IP max size, but no more than the mtu
2650 * of the interface), as we can't discover anything about intervening
2651 * gateways or networks. We also initialize the congestion/slow start
2652 * window to be a single segment if the destination isn't local.
2653 * While looking at the routing entry, we also initialize other path-dependent
2654 * parameters from pre-set or cached values in the routing entry.
2656 * Also take into account the space needed for options that we
2657 * send regularly. Make maxseg shorter by that amount to assure
2658 * that we can send maxseg amount of data even when the options
2659 * are present. Store the upper limit of the length of options plus
2662 * NOTE that this routine is only called when we process an incoming
2663 * segment, for outgoing segments only tcp_mssopt is called.
2665 * In case of T/TCP, we call this routine during implicit connection
2666 * setup as well (offer = -1), to initialize maxseg from the cached
2674 register struct rtentry *rt;
2676 register int rtt, mss;
2680 struct rmxp_tao *taop;
2681 int origoffer = offer;
2689 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2690 min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
2691 : sizeof (struct tcpiphdr);
2693 #define min_protoh (sizeof (struct tcpiphdr))
2697 rt = tcp_rtlookup6(inp);
2700 rt = tcp_rtlookup(inp);
2702 tp->t_maxopd = tp->t_maxseg =
2704 isipv6 ? tcp_v6mssdflt :
2710 so = inp->inp_socket;
2712 taop = rmx_taop(rt->rt_rmx);
2714 * Offer == -1 means that we didn't receive SYN yet,
2715 * use cached value in that case;
2718 offer = taop->tao_mssopt;
2720 * Offer == 0 means that there was no MSS on the SYN segment,
2721 * in this case we use tcp_mssdflt.
2726 isipv6 ? tcp_v6mssdflt :
2731 * Sanity check: make sure that maxopd will be large
2732 * enough to allow some data on segments even is the
2733 * all the option space is used (40bytes). Otherwise
2734 * funny things may happen in tcp_output.
2736 offer = max(offer, 64);
2737 taop->tao_mssopt = offer;
2740 * While we're here, check if there's an initial rtt
2741 * or rttvar. Convert from the route-table units
2742 * to scaled multiples of the slow timeout timer.
2744 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2746 * XXX the lock bit for RTT indicates that the value
2747 * is also a minimum value; this is subject to time.
2749 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2750 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2751 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2752 tcpstat.tcps_usedrtt++;
2753 if (rt->rt_rmx.rmx_rttvar) {
2754 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2755 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2756 tcpstat.tcps_usedrttvar++;
2758 /* default variation is +- 1 rtt */
2760 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2762 TCPT_RANGESET(tp->t_rxtcur,
2763 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2764 tp->t_rttmin, TCPTV_REXMTMAX);
2767 * if there's an mtu associated with the route, use it
2768 * else, use the link mtu.
2770 if (rt->rt_rmx.rmx_mtu)
2771 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2776 (isipv6 ? nd_ifinfo[rt->rt_ifp->if_index].linkmtu :
2785 if (!in6_localaddr(&inp->in6p_faddr))
2786 mss = min(mss, tcp_v6mssdflt);
2789 if (!in_localaddr(inp->inp_faddr))
2790 mss = min(mss, tcp_mssdflt);
2792 mss = min(mss, offer);
2794 * maxopd stores the maximum length of data AND options
2795 * in a segment; maxseg is the amount of data in a normal
2796 * segment. We need to store this value (maxopd) apart
2797 * from maxseg, because now every segment carries options
2798 * and thus we normally have somewhat less data in segments.
2803 * In case of T/TCP, origoffer==-1 indicates, that no segments
2804 * were received yet. In this case we just guess, otherwise
2805 * we do the same as before T/TCP.
2807 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2809 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2810 mss -= TCPOLEN_TSTAMP_APPA;
2811 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2813 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2814 mss -= TCPOLEN_CC_APPA;
2816 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2818 mss &= ~(MCLBYTES-1);
2821 mss = mss / MCLBYTES * MCLBYTES;
2824 * If there's a pipesize, change the socket buffer
2825 * to that size. Make the socket buffers an integral
2826 * number of mss units; if the mss is larger than
2827 * the socket buffer, decrease the mss.
2830 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2832 bufsize = so->so_snd.sb_hiwat;
2836 bufsize = roundup(bufsize, mss);
2837 if (bufsize > sb_max)
2839 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2844 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2846 bufsize = so->so_rcv.sb_hiwat;
2847 if (bufsize > mss) {
2848 bufsize = roundup(bufsize, mss);
2849 if (bufsize > sb_max)
2851 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2855 * Set the slow-start flight size depending on whether this
2856 * is a local network or not.
2860 (isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2863 in_localaddr(inp->inp_faddr)
2868 tp->snd_cwnd = mss * ss_fltsz_local;
2870 tp->snd_cwnd = mss * ss_fltsz;
2872 if (rt->rt_rmx.rmx_ssthresh) {
2874 * There's some sort of gateway or interface
2875 * buffer limit on the path. Use this to set
2876 * the slow start threshhold, but set the
2877 * threshold to no less than 2*mss.
2879 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2880 tcpstat.tcps_usedssthresh++;
2885 * Determine the MSS option to send on an outgoing SYN.
2898 isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2899 min_protoh = isipv6 ? sizeof (struct ip6_hdr) + sizeof (struct tcphdr)
2900 : sizeof (struct tcpiphdr);
2902 #define min_protoh (sizeof (struct tcpiphdr))
2906 rt = tcp_rtlookup6(tp->t_inpcb);
2909 rt = tcp_rtlookup(tp->t_inpcb);
2913 isipv6 ? tcp_v6mssdflt :
2917 return rt->rt_ifp->if_mtu - min_protoh;
2922 * Checks for partial ack. If partial ack arrives, force the retransmission
2923 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
2924 * 1. By setting snd_nxt to ti_ack, this forces retransmission timer to
2925 * be started again. If the ack advances at least to tp->snd_recover, return 0.
2932 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2933 tcp_seq onxt = tp->snd_nxt;
2934 u_long ocwnd = tp->snd_cwnd;
2936 callout_stop(tp->tt_rexmt);
2938 tp->snd_nxt = th->th_ack;
2940 * Set snd_cwnd to one segment beyond acknowledged offset
2941 * (tp->snd_una has not yet been updated when this function
2944 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2945 (void) tcp_output(tp);
2946 tp->snd_cwnd = ocwnd;
2947 if (SEQ_GT(onxt, tp->snd_nxt))
2950 * Partial window deflation. Relies on fact that tp->snd_una
2953 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);