2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * @(#)tcp_input.c 8.5 (Berkeley) 4/10/94
30 * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp
34 * Changes and additions relating to SLiRP
35 * Copyright (c) 1995 Danny Gasparovski.
37 * Please read the file COPYRIGHT for the
38 * terms and conditions of the copyright.
44 #define TCPREXMTTHRESH 3
46 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
48 /* for modulo comparisons of timestamps */
49 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
50 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
53 * Insert segment ti into reassembly queue of tcp with
54 * control block tp. Return TH_FIN if reassembly now includes
55 * a segment with FIN. The macro form does the common case inline
56 * (segment is the next to be received on an established connection,
57 * and the queue is empty), avoiding linkage into and removal
58 * from the queue and repetition of various conversions.
59 * Set DELACK for segments received in order, but ack immediately
60 * when segments are out of order (so fast retransmit can work).
63 #define TCP_REASS(tp, ti, m, so, flags) {\
64 if ((ti)->ti_seq == (tp)->rcv_nxt && \
65 tcpfrag_list_empty(tp) && \
66 (tp)->t_state == TCPS_ESTABLISHED) {\
67 if (ti->ti_flags & TH_PUSH) \
68 tp->t_flags |= TF_ACKNOW; \
70 tp->t_flags |= TF_DELACK; \
71 (tp)->rcv_nxt += (ti)->ti_len; \
72 flags = (ti)->ti_flags & TH_FIN; \
74 if (tcp_emu((so),(m))) sbappend((so), (m)); \
76 sbappend((so), (m)); \
78 (flags) = tcp_reass((tp), (ti), (m)); \
79 tp->t_flags |= TF_ACKNOW; \
83 #define TCP_REASS(tp, ti, m, so, flags) { \
84 if ((ti)->ti_seq == (tp)->rcv_nxt && \
85 tcpfrag_list_empty(tp) && \
86 (tp)->t_state == TCPS_ESTABLISHED) { \
87 tp->t_flags |= TF_DELACK; \
88 (tp)->rcv_nxt += (ti)->ti_len; \
89 flags = (ti)->ti_flags & TH_FIN; \
91 if (tcp_emu((so),(m))) sbappend(so, (m)); \
93 sbappend((so), (m)); \
95 (flags) = tcp_reass((tp), (ti), (m)); \
96 tp->t_flags |= TF_ACKNOW; \
100 static void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,
101 struct tcpiphdr *ti);
102 static void tcp_xmit_timer(register struct tcpcb *tp, int rtt);
105 tcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,
108 register struct tcpiphdr *q;
109 struct socket *so = tp->t_socket;
113 * Call with ti==NULL after become established to
114 * force pre-ESTABLISHED data up to user socket.
120 * Find a segment which begins after this one does.
122 for (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);
123 q = tcpiphdr_next(q))
124 if (SEQ_GT(q->ti_seq, ti->ti_seq))
128 * If there is a preceding segment, it may provide some of
129 * our data already. If so, drop the data from the incoming
130 * segment. If it provides all of our data, drop us.
132 if (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {
134 q = tcpiphdr_prev(q);
135 /* conversion to int (in i) handles seq wraparound */
136 i = q->ti_seq + q->ti_len - ti->ti_seq;
138 if (i >= ti->ti_len) {
141 * Try to present any queued data
142 * at the left window edge to the user.
143 * This is needed after the 3-WHS
146 goto present; /* ??? */
152 q = tcpiphdr_next(q);
157 * While we overlap succeeding segments trim them or,
158 * if they are completely covered, dequeue them.
160 while (!tcpfrag_list_end(q, tp)) {
161 register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
167 m_adj(q->ti_mbuf, i);
170 q = tcpiphdr_next(q);
171 m = tcpiphdr_prev(q)->ti_mbuf;
172 remque(tcpiphdr2qlink(tcpiphdr_prev(q)));
177 * Stick new segment in its place.
179 insque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));
183 * Present data to user, advancing rcv_nxt through
184 * completed sequence space.
186 if (!TCPS_HAVEESTABLISHED(tp->t_state))
188 ti = tcpfrag_list_first(tp);
189 if (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)
191 if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
194 tp->rcv_nxt += ti->ti_len;
195 flags = ti->ti_flags & TH_FIN;
196 remque(tcpiphdr2qlink(ti));
198 ti = tcpiphdr_next(ti);
199 if (so->so_state & SS_FCANTSENDMORE)
203 if (tcp_emu(so,m)) sbappend(so, m);
207 } while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
212 * TCP input routine, follows pages 65-76 of the
213 * protocol specification dated September, 1981 very closely.
216 tcp_input(struct mbuf *m, int iphlen, struct socket *inso)
218 struct ip save_ip, *ip;
219 register struct tcpiphdr *ti;
223 register struct tcpcb *tp = NULL;
224 register int tiflags;
225 struct socket *so = NULL;
226 int todrop, acked, ourfinisacked, needoutput = 0;
230 struct ex_list *ex_ptr;
233 DEBUG_CALL("tcp_input");
234 DEBUG_ARGS((dfd, " m = %8lx iphlen = %2d inso = %lx\n",
235 (long )m, iphlen, (long )inso ));
238 * If called with m == 0, then we're continuing the connect
244 /* Re-set a few variables */
250 tiflags = ti->ti_flags;
257 * Get IP and TCP header together in first mbuf.
258 * Note: IP leaves IP header in first mbuf.
260 ti = mtod(m, struct tcpiphdr *);
261 if (iphlen > sizeof(struct ip )) {
262 ip_stripoptions(m, (struct mbuf *)0);
263 iphlen=sizeof(struct ip );
265 /* XXX Check if too short */
269 * Save a copy of the IP header in case we want restore it
270 * for sending an ICMP error message in response.
272 ip=mtod(m, struct ip *);
274 save_ip.ip_len+= iphlen;
277 * Checksum extended TCP header and data.
279 tlen = ((struct ip *)ti)->ip_len;
280 tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;
281 memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));
283 ti->ti_len = htons((uint16_t)tlen);
284 len = sizeof(struct ip ) + tlen;
290 * Check that TCP offset makes sense,
291 * pull out TCP options and adjust length. XXX
293 off = ti->ti_off << 2;
294 if (off < sizeof (struct tcphdr) || off > tlen) {
299 if (off > sizeof (struct tcphdr)) {
300 optlen = off - sizeof (struct tcphdr);
301 optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
303 tiflags = ti->ti_flags;
306 * Convert TCP protocol specific fields to host format.
314 * Drop TCP, IP headers and TCP options.
316 m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
317 m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
320 * Locate pcb for segment.
323 so = slirp->tcp_last_so;
324 if (so->so_fport != ti->ti_dport ||
325 so->so_lport != ti->ti_sport ||
326 so->so_laddr.s_addr != ti->ti_src.s_addr ||
327 so->so_faddr.s_addr != ti->ti_dst.s_addr) {
328 so = solookup(&slirp->tcb, ti->ti_src, ti->ti_sport,
329 ti->ti_dst, ti->ti_dport);
331 slirp->tcp_last_so = so;
335 * If the state is CLOSED (i.e., TCB does not exist) then
336 * all data in the incoming segment is discarded.
337 * If the TCB exists but is in CLOSED state, it is embryonic,
338 * but should either do a listen or a connect soon.
340 * state == CLOSED means we've done socreate() but haven't
341 * attached it to a protocol yet...
343 * XXX If a TCB does not exist, and the TH_SYN flag is
344 * the only flag set, then create a session, mark it
345 * as if it was LISTENING, and continue...
348 if (slirp->restricted) {
349 /* Any hostfwds will have an existing socket, so we only get here
350 * for non-hostfwd connections. These should be dropped, unless it
351 * happens to be a guestfwd.
353 for (ex_ptr = slirp->exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
354 if (ex_ptr->ex_fport == ti->ti_dport &&
355 ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {
364 if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)
367 if ((so = socreate(slirp)) == NULL)
369 if (tcp_attach(so) < 0) {
370 free(so); /* Not sofree (if it failed, it's not insqued) */
374 sbreserve(&so->so_snd, TCP_SNDSPACE);
375 sbreserve(&so->so_rcv, TCP_RCVSPACE);
377 so->so_laddr = ti->ti_src;
378 so->so_lport = ti->ti_sport;
379 so->so_faddr = ti->ti_dst;
380 so->so_fport = ti->ti_dport;
382 if ((so->so_iptos = tcp_tos(so)) == 0)
383 so->so_iptos = ((struct ip *)ti)->ip_tos;
386 tp->t_state = TCPS_LISTEN;
390 * If this is a still-connecting socket, this probably
391 * a retransmit of the SYN. Whether it's a retransmit SYN
392 * or something else, we nuke it.
394 if (so->so_state & SS_ISFCONNECTING)
399 /* XXX Should never fail */
402 if (tp->t_state == TCPS_CLOSED)
408 * Segment received on connection.
409 * Reset idle time and keep-alive timer.
413 tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;
415 tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;
418 * Process options if not in LISTEN state,
419 * else do it below (after getting remote address).
421 if (optp && tp->t_state != TCPS_LISTEN)
422 tcp_dooptions(tp, (u_char *)optp, optlen, ti);
425 * Header prediction: check for the two common cases
426 * of a uni-directional data xfer. If the packet has
427 * no control flags, is in-sequence, the window didn't
428 * change and we're not retransmitting, it's a
429 * candidate. If the length is zero and the ack moved
430 * forward, we're the sender side of the xfer. Just
431 * free the data acked & wake any higher level process
432 * that was blocked waiting for space. If the length
433 * is non-zero and the ack didn't move, we're the
434 * receiver side. If we're getting packets in-order
435 * (the reassembly queue is empty), add the data to
436 * the socket buffer and note that we need a delayed ack.
438 * XXX Some of these tests are not needed
439 * eg: the tiwin == tp->snd_wnd prevents many more
440 * predictions.. with no *real* advantage..
442 if (tp->t_state == TCPS_ESTABLISHED &&
443 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
444 ti->ti_seq == tp->rcv_nxt &&
445 tiwin && tiwin == tp->snd_wnd &&
446 tp->snd_nxt == tp->snd_max) {
447 if (ti->ti_len == 0) {
448 if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
449 SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
450 tp->snd_cwnd >= tp->snd_wnd) {
452 * this is a pure ack for outstanding data.
455 SEQ_GT(ti->ti_ack, tp->t_rtseq))
456 tcp_xmit_timer(tp, tp->t_rtt);
457 acked = ti->ti_ack - tp->snd_una;
458 sbdrop(&so->so_snd, acked);
459 tp->snd_una = ti->ti_ack;
463 * If all outstanding data are acked, stop
464 * retransmit timer, otherwise restart timer
465 * using current (possibly backed-off) value.
466 * If process is waiting for space,
467 * wakeup/selwakeup/signal. If data
468 * are ready to send, let tcp_output
469 * decide between more output or persist.
471 if (tp->snd_una == tp->snd_max)
472 tp->t_timer[TCPT_REXMT] = 0;
473 else if (tp->t_timer[TCPT_PERSIST] == 0)
474 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
477 * This is called because sowwakeup might have
478 * put data into so_snd. Since we don't so sowwakeup,
479 * we don't need this.. XXX???
481 if (so->so_snd.sb_cc)
482 (void) tcp_output(tp);
486 } else if (ti->ti_ack == tp->snd_una &&
487 tcpfrag_list_empty(tp) &&
488 ti->ti_len <= sbspace(&so->so_rcv)) {
490 * this is a pure, in-sequence data packet
491 * with nothing on the reassembly queue and
492 * we have enough buffer space to take it.
494 tp->rcv_nxt += ti->ti_len;
496 * Add data to socket buffer.
499 if (tcp_emu(so,m)) sbappend(so, m);
504 * If this is a short packet, then ACK now - with Nagel
505 * congestion avoidance sender won't send more until
508 * It is better to not delay acks at all to maximize
509 * TCP throughput. See RFC 2581.
511 tp->t_flags |= TF_ACKNOW;
515 } /* header prediction */
517 * Calculate amount of space in receive window,
518 * and then do TCP input processing.
519 * Receive window is amount of space in rcv queue,
520 * but not less than advertised window.
523 win = sbspace(&so->so_rcv);
526 tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
529 switch (tp->t_state) {
532 * If the state is LISTEN then ignore segment if it contains an RST.
533 * If the segment contains an ACK then it is bad and send a RST.
534 * If it does not contain a SYN then it is not interesting; drop it.
535 * Don't bother responding if the destination was a broadcast.
536 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
537 * tp->iss, and send a segment:
538 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
539 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
540 * Fill in remote peer address fields if not previously specified.
541 * Enter SYN_RECEIVED state, and process any other fields of this
542 * segment in this state.
546 if (tiflags & TH_RST)
548 if (tiflags & TH_ACK)
550 if ((tiflags & TH_SYN) == 0)
554 * This has way too many gotos...
555 * But a bit of spaghetti code never hurt anybody :)
559 * If this is destined for the control address, then flag to
560 * tcp_ctl once connected, otherwise connect
562 if ((so->so_faddr.s_addr & slirp->vnetwork_mask.s_addr) ==
563 slirp->vnetwork_addr.s_addr) {
564 if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr &&
565 so->so_faddr.s_addr != slirp->vnameserver_addr.s_addr) {
566 /* May be an add exec */
567 for (ex_ptr = slirp->exec_list; ex_ptr;
568 ex_ptr = ex_ptr->ex_next) {
569 if(ex_ptr->ex_fport == so->so_fport &&
570 so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {
571 so->so_state |= SS_CTL;
575 if (so->so_state & SS_CTL) {
579 /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */
582 if (so->so_emu & EMU_NOCONNECT) {
583 so->so_emu &= ~EMU_NOCONNECT;
587 if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {
588 u_char code=ICMP_UNREACH_NET;
589 DEBUG_MISC((dfd, " tcp fconnect errno = %d-%s\n",
590 errno,strerror(errno)));
591 if(errno == ECONNREFUSED) {
592 /* ACK the SYN, send RST to refuse the connection */
593 tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,
596 if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
597 HTONL(ti->ti_seq); /* restore tcp header */
601 m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
602 m->m_len += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
604 icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));
610 * Haven't connected yet, save the current mbuf
612 * XXX Some OS's don't tell us whether the connect()
613 * succeeded or not. So we must time it out.
617 tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
618 tp->t_state = TCPS_SYN_RECEIVED;
625 * Check if the connect succeeded
627 if (so->so_state & SS_NOFDREF) {
635 tcp_dooptions(tp, (u_char *)optp, optlen, ti);
640 tp->iss = slirp->tcp_iss;
641 slirp->tcp_iss += TCP_ISSINCR/2;
642 tp->irs = ti->ti_seq;
645 tp->t_flags |= TF_ACKNOW;
646 tp->t_state = TCPS_SYN_RECEIVED;
647 tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
649 } /* case TCPS_LISTEN */
652 * If the state is SYN_SENT:
653 * if seg contains an ACK, but not for our SYN, drop the input.
654 * if seg contains a RST, then drop the connection.
655 * if seg does not contain SYN, then drop it.
656 * Otherwise this is an acceptable SYN segment
657 * initialize tp->rcv_nxt and tp->irs
658 * if seg contains ack then advance tp->snd_una
659 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
660 * arrange for segment to be acked (eventually)
661 * continue processing rest of data/controls, beginning with URG
664 if ((tiflags & TH_ACK) &&
665 (SEQ_LEQ(ti->ti_ack, tp->iss) ||
666 SEQ_GT(ti->ti_ack, tp->snd_max)))
669 if (tiflags & TH_RST) {
670 if (tiflags & TH_ACK) {
671 tcp_drop(tp, 0); /* XXX Check t_softerror! */
676 if ((tiflags & TH_SYN) == 0)
678 if (tiflags & TH_ACK) {
679 tp->snd_una = ti->ti_ack;
680 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
681 tp->snd_nxt = tp->snd_una;
684 tp->t_timer[TCPT_REXMT] = 0;
685 tp->irs = ti->ti_seq;
687 tp->t_flags |= TF_ACKNOW;
688 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
690 tp->t_state = TCPS_ESTABLISHED;
692 (void) tcp_reass(tp, (struct tcpiphdr *)0,
695 * if we didn't have to retransmit the SYN,
696 * use its rtt as our initial srtt & rtt var.
699 tcp_xmit_timer(tp, tp->t_rtt);
701 tp->t_state = TCPS_SYN_RECEIVED;
705 * Advance ti->ti_seq to correspond to first data byte.
706 * If data, trim to stay within window,
707 * dropping FIN if necessary.
710 if (ti->ti_len > tp->rcv_wnd) {
711 todrop = ti->ti_len - tp->rcv_wnd;
713 ti->ti_len = tp->rcv_wnd;
716 tp->snd_wl1 = ti->ti_seq - 1;
717 tp->rcv_up = ti->ti_seq;
719 } /* switch tp->t_state */
721 * States other than LISTEN or SYN_SENT.
722 * Check that at least some bytes of segment are within
723 * receive window. If segment begins before rcv_nxt,
724 * drop leading data (and SYN); if nothing left, just ack.
726 todrop = tp->rcv_nxt - ti->ti_seq;
728 if (tiflags & TH_SYN) {
738 * Following if statement from Stevens, vol. 2, p. 960.
740 if (todrop > ti->ti_len
741 || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
743 * Any valid FIN must be to the left of the window.
744 * At this point the FIN must be a duplicate or out
745 * of sequence; drop it.
750 * Send an ACK to resynchronize and drop any data.
751 * But keep on processing for RST or ACK.
753 tp->t_flags |= TF_ACKNOW;
757 ti->ti_seq += todrop;
758 ti->ti_len -= todrop;
759 if (ti->ti_urp > todrop)
760 ti->ti_urp -= todrop;
767 * If new data are received on a connection after the
768 * user processes are gone, then RST the other end.
770 if ((so->so_state & SS_NOFDREF) &&
771 tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
777 * If segment ends after window, drop trailing data
778 * (and PUSH and FIN); if nothing left, just ACK.
780 todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
782 if (todrop >= ti->ti_len) {
784 * If a new connection request is received
785 * while in TIME_WAIT, drop the old connection
786 * and start over if the sequence numbers
787 * are above the previous ones.
789 if (tiflags & TH_SYN &&
790 tp->t_state == TCPS_TIME_WAIT &&
791 SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
792 iss = tp->rcv_nxt + TCP_ISSINCR;
797 * If window is closed can only take segments at
798 * window edge, and have to drop data and PUSH from
799 * incoming segments. Continue processing, but
800 * remember to ack. Otherwise, drop segment
803 if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
804 tp->t_flags |= TF_ACKNOW;
810 ti->ti_len -= todrop;
811 tiflags &= ~(TH_PUSH|TH_FIN);
815 * If the RST bit is set examine the state:
816 * SYN_RECEIVED STATE:
817 * If passive open, return to LISTEN state.
818 * If active open, inform user that connection was refused.
819 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
820 * Inform user that connection was reset, and close tcb.
821 * CLOSING, LAST_ACK, TIME_WAIT STATES
824 if (tiflags&TH_RST) switch (tp->t_state) {
826 case TCPS_SYN_RECEIVED:
827 case TCPS_ESTABLISHED:
828 case TCPS_FIN_WAIT_1:
829 case TCPS_FIN_WAIT_2:
830 case TCPS_CLOSE_WAIT:
831 tp->t_state = TCPS_CLOSED;
843 * If a SYN is in the window, then this is an
844 * error and we send an RST and drop the connection.
846 if (tiflags & TH_SYN) {
852 * If the ACK bit is off we drop the segment and return.
854 if ((tiflags & TH_ACK) == 0) goto drop;
859 switch (tp->t_state) {
861 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
862 * ESTABLISHED state and continue processing, otherwise
863 * send an RST. una<=ack<=max
865 case TCPS_SYN_RECEIVED:
867 if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
868 SEQ_GT(ti->ti_ack, tp->snd_max))
870 tp->t_state = TCPS_ESTABLISHED;
872 * The sent SYN is ack'ed with our sequence number +1
873 * The first data byte already in the buffer will get
874 * lost if no correction is made. This is only needed for
875 * SS_CTL since the buffer is empty otherwise.
878 tp->snd_una=ti->ti_ack;
879 if (so->so_state & SS_CTL) {
880 /* So tcp_ctl reports the right state */
884 so->so_state &= ~SS_CTL; /* success XXX */
885 } else if (ret == 2) {
886 so->so_state &= SS_PERSISTENT_MASK;
887 so->so_state |= SS_NOFDREF; /* CTL_CMD */
890 tp->t_state = TCPS_FIN_WAIT_1;
896 (void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
897 tp->snd_wl1 = ti->ti_seq - 1;
898 /* Avoid ack processing; snd_una==ti_ack => dup ack */
903 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
904 * ACKs. If the ack is in the range
905 * tp->snd_una < ti->ti_ack <= tp->snd_max
906 * then advance tp->snd_una to ti->ti_ack and drop
907 * data from the retransmission queue. If this ACK reflects
908 * more up to date window information we update our window information.
910 case TCPS_ESTABLISHED:
911 case TCPS_FIN_WAIT_1:
912 case TCPS_FIN_WAIT_2:
913 case TCPS_CLOSE_WAIT:
918 if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
919 if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
920 DEBUG_MISC((dfd, " dup ack m = %lx so = %lx\n",
921 (long )m, (long )so));
923 * If we have outstanding data (other than
924 * a window probe), this is a completely
925 * duplicate ack (ie, window info didn't
926 * change), the ack is the biggest we've
927 * seen and we've seen exactly our rexmt
928 * threshold of them, assume a packet
929 * has been dropped and retransmit it.
930 * Kludge snd_nxt & the congestion
931 * window so we send only this one
934 * We know we're losing at the current
935 * window size so do congestion avoidance
936 * (set ssthresh to half the current window
937 * and pull our congestion window back to
940 * Dup acks mean that packets have left the
941 * network (they're now cached at the receiver)
942 * so bump cwnd by the amount in the receiver
943 * to keep a constant cwnd packets in the
946 if (tp->t_timer[TCPT_REXMT] == 0 ||
947 ti->ti_ack != tp->snd_una)
949 else if (++tp->t_dupacks == TCPREXMTTHRESH) {
950 tcp_seq onxt = tp->snd_nxt;
952 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
957 tp->snd_ssthresh = win * tp->t_maxseg;
958 tp->t_timer[TCPT_REXMT] = 0;
960 tp->snd_nxt = ti->ti_ack;
961 tp->snd_cwnd = tp->t_maxseg;
962 (void) tcp_output(tp);
963 tp->snd_cwnd = tp->snd_ssthresh +
964 tp->t_maxseg * tp->t_dupacks;
965 if (SEQ_GT(onxt, tp->snd_nxt))
968 } else if (tp->t_dupacks > TCPREXMTTHRESH) {
969 tp->snd_cwnd += tp->t_maxseg;
970 (void) tcp_output(tp);
979 * If the congestion window was inflated to account
980 * for the other side's cached packets, retract it.
982 if (tp->t_dupacks > TCPREXMTTHRESH &&
983 tp->snd_cwnd > tp->snd_ssthresh)
984 tp->snd_cwnd = tp->snd_ssthresh;
986 if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
989 acked = ti->ti_ack - tp->snd_una;
992 * If transmit timer is running and timed sequence
993 * number was acked, update smoothed round trip time.
994 * Since we now have an rtt measurement, cancel the
995 * timer backoff (cf., Phil Karn's retransmit alg.).
996 * Recompute the initial retransmit timer.
998 if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
999 tcp_xmit_timer(tp,tp->t_rtt);
1002 * If all outstanding data is acked, stop retransmit
1003 * timer and remember to restart (more output or persist).
1004 * If there is more data to be acked, restart retransmit
1005 * timer, using current (possibly backed-off) value.
1007 if (ti->ti_ack == tp->snd_max) {
1008 tp->t_timer[TCPT_REXMT] = 0;
1010 } else if (tp->t_timer[TCPT_PERSIST] == 0)
1011 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1013 * When new data is acked, open the congestion window.
1014 * If the window gives us less than ssthresh packets
1015 * in flight, open exponentially (maxseg per packet).
1016 * Otherwise open linearly: maxseg per window
1017 * (maxseg^2 / cwnd per packet).
1020 register u_int cw = tp->snd_cwnd;
1021 register u_int incr = tp->t_maxseg;
1023 if (cw > tp->snd_ssthresh)
1024 incr = incr * incr / cw;
1025 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1027 if (acked > so->so_snd.sb_cc) {
1028 tp->snd_wnd -= so->so_snd.sb_cc;
1029 sbdrop(&so->so_snd, (int )so->so_snd.sb_cc);
1032 sbdrop(&so->so_snd, acked);
1033 tp->snd_wnd -= acked;
1036 tp->snd_una = ti->ti_ack;
1037 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1038 tp->snd_nxt = tp->snd_una;
1040 switch (tp->t_state) {
1043 * In FIN_WAIT_1 STATE in addition to the processing
1044 * for the ESTABLISHED state if our FIN is now acknowledged
1045 * then enter FIN_WAIT_2.
1047 case TCPS_FIN_WAIT_1:
1048 if (ourfinisacked) {
1050 * If we can't receive any more
1051 * data, then closing user can proceed.
1052 * Starting the timer is contrary to the
1053 * specification, but if we don't get a FIN
1054 * we'll hang forever.
1056 if (so->so_state & SS_FCANTRCVMORE) {
1057 tp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;
1059 tp->t_state = TCPS_FIN_WAIT_2;
1064 * In CLOSING STATE in addition to the processing for
1065 * the ESTABLISHED state if the ACK acknowledges our FIN
1066 * then enter the TIME-WAIT state, otherwise ignore
1070 if (ourfinisacked) {
1071 tp->t_state = TCPS_TIME_WAIT;
1072 tcp_canceltimers(tp);
1073 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1078 * In LAST_ACK, we may still be waiting for data to drain
1079 * and/or to be acked, as well as for the ack of our FIN.
1080 * If our FIN is now acknowledged, delete the TCB,
1081 * enter the closed state and return.
1084 if (ourfinisacked) {
1091 * In TIME_WAIT state the only thing that should arrive
1092 * is a retransmission of the remote FIN. Acknowledge
1093 * it and restart the finack timer.
1095 case TCPS_TIME_WAIT:
1096 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1099 } /* switch(tp->t_state) */
1103 * Update window information.
1104 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1106 if ((tiflags & TH_ACK) &&
1107 (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1108 (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1109 (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1110 tp->snd_wnd = tiwin;
1111 tp->snd_wl1 = ti->ti_seq;
1112 tp->snd_wl2 = ti->ti_ack;
1113 if (tp->snd_wnd > tp->max_sndwnd)
1114 tp->max_sndwnd = tp->snd_wnd;
1119 * Process segments with URG.
1121 if ((tiflags & TH_URG) && ti->ti_urp &&
1122 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1124 * This is a kludge, but if we receive and accept
1125 * random urgent pointers, we'll crash in
1126 * soreceive. It's hard to imagine someone
1127 * actually wanting to send this much urgent data.
1129 if (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {
1135 * If this segment advances the known urgent pointer,
1136 * then mark the data stream. This should not happen
1137 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1138 * a FIN has been received from the remote side.
1139 * In these states we ignore the URG.
1141 * According to RFC961 (Assigned Protocols),
1142 * the urgent pointer points to the last octet
1143 * of urgent data. We continue, however,
1144 * to consider it to indicate the first octet
1145 * of data past the urgent section as the original
1146 * spec states (in one of two places).
1148 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1149 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1150 so->so_urgc = so->so_rcv.sb_cc +
1151 (tp->rcv_up - tp->rcv_nxt); /* -1; */
1152 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1157 * If no out of band data is expected,
1158 * pull receive urgent pointer along
1159 * with the receive window.
1161 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1162 tp->rcv_up = tp->rcv_nxt;
1166 * If this is a small packet, then ACK now - with Nagel
1167 * congestion avoidance sender won't send more until
1170 if (ti->ti_len && (unsigned)ti->ti_len <= 5 &&
1171 ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {
1172 tp->t_flags |= TF_ACKNOW;
1176 * Process the segment text, merging it into the TCP sequencing queue,
1177 * and arranging for acknowledgment of receipt if necessary.
1178 * This process logically involves adjusting tp->rcv_wnd as data
1179 * is presented to the user (this happens in tcp_usrreq.c,
1180 * case PRU_RCVD). If a FIN has already been received on this
1181 * connection then we just ignore the text.
1183 if ((ti->ti_len || (tiflags&TH_FIN)) &&
1184 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1185 TCP_REASS(tp, ti, m, so, tiflags);
1192 * If FIN is received ACK the FIN and let the user know
1193 * that the connection is closing.
1195 if (tiflags & TH_FIN) {
1196 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1198 * If we receive a FIN we can't send more data,
1200 * Shutdown the socket if there is no rx data in the
1202 * soread() is called on completion of shutdown() and
1203 * will got to TCPS_LAST_ACK, and use tcp_output()
1208 tp->t_flags |= TF_ACKNOW;
1211 switch (tp->t_state) {
1214 * In SYN_RECEIVED and ESTABLISHED STATES
1215 * enter the CLOSE_WAIT state.
1217 case TCPS_SYN_RECEIVED:
1218 case TCPS_ESTABLISHED:
1219 if(so->so_emu == EMU_CTL) /* no shutdown on socket */
1220 tp->t_state = TCPS_LAST_ACK;
1222 tp->t_state = TCPS_CLOSE_WAIT;
1226 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1227 * enter the CLOSING state.
1229 case TCPS_FIN_WAIT_1:
1230 tp->t_state = TCPS_CLOSING;
1234 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1235 * starting the time-wait timer, turning off the other
1238 case TCPS_FIN_WAIT_2:
1239 tp->t_state = TCPS_TIME_WAIT;
1240 tcp_canceltimers(tp);
1241 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1245 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1247 case TCPS_TIME_WAIT:
1248 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1254 * Return any desired output.
1256 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
1257 (void) tcp_output(tp);
1263 * Generate an ACK dropping incoming segment if it occupies
1264 * sequence space, where the ACK reflects our state.
1266 if (tiflags & TH_RST)
1269 tp->t_flags |= TF_ACKNOW;
1270 (void) tcp_output(tp);
1274 /* reuses m if m!=NULL, m_free() unnecessary */
1275 if (tiflags & TH_ACK)
1276 tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1278 if (tiflags & TH_SYN) ti->ti_len++;
1279 tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1287 * Drop space held by incoming segment and return.
1293 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)
1298 DEBUG_CALL("tcp_dooptions");
1299 DEBUG_ARGS((dfd, " tp = %lx cnt=%i\n", (long)tp, cnt));
1301 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1303 if (opt == TCPOPT_EOL)
1305 if (opt == TCPOPT_NOP)
1318 if (optlen != TCPOLEN_MAXSEG)
1320 if (!(ti->ti_flags & TH_SYN))
1322 memcpy((char *) &mss, (char *) cp + 2, sizeof(mss));
1324 (void) tcp_mss(tp, mss); /* sets t_maxseg */
1332 * Pull out of band byte out of a segment so
1333 * it doesn't appear in the user's data queue.
1334 * It is still reflected in the segment length for
1335 * sequencing purposes.
1341 tcp_pulloutofband(so, ti, m)
1343 struct tcpiphdr *ti;
1344 register struct mbuf *m;
1346 int cnt = ti->ti_urp - 1;
1349 if (m->m_len > cnt) {
1350 char *cp = mtod(m, caddr_t) + cnt;
1351 struct tcpcb *tp = sototcpcb(so);
1354 tp->t_oobflags |= TCPOOB_HAVEDATA;
1355 memcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));
1360 m = m->m_next; /* XXX WRONG! Fix it! */
1364 panic("tcp_pulloutofband");
1370 * Collect new round-trip time estimate
1371 * and update averages and current timeout.
1375 tcp_xmit_timer(register struct tcpcb *tp, int rtt)
1377 register short delta;
1379 DEBUG_CALL("tcp_xmit_timer");
1380 DEBUG_ARG("tp = %lx", (long)tp);
1381 DEBUG_ARG("rtt = %d", rtt);
1383 if (tp->t_srtt != 0) {
1385 * srtt is stored as fixed point with 3 bits after the
1386 * binary point (i.e., scaled by 8). The following magic
1387 * is equivalent to the smoothing algorithm in rfc793 with
1388 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1389 * point). Adjust rtt to origin 0.
1391 delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1392 if ((tp->t_srtt += delta) <= 0)
1395 * We accumulate a smoothed rtt variance (actually, a
1396 * smoothed mean difference), then set the retransmit
1397 * timer to smoothed rtt + 4 times the smoothed variance.
1398 * rttvar is stored as fixed point with 2 bits after the
1399 * binary point (scaled by 4). The following is
1400 * equivalent to rfc793 smoothing with an alpha of .75
1401 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1402 * rfc793's wired-in beta.
1406 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1407 if ((tp->t_rttvar += delta) <= 0)
1411 * No rtt measurement yet - use the unsmoothed rtt.
1412 * Set the variance to half the rtt (so our first
1413 * retransmit happens at 3*rtt).
1415 tp->t_srtt = rtt << TCP_RTT_SHIFT;
1416 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1422 * the retransmit should happen at rtt + 4 * rttvar.
1423 * Because of the way we do the smoothing, srtt and rttvar
1424 * will each average +1/2 tick of bias. When we compute
1425 * the retransmit timer, we want 1/2 tick of rounding and
1426 * 1 extra tick because of +-1/2 tick uncertainty in the
1427 * firing of the timer. The bias will give us exactly the
1428 * 1.5 tick we need. But, because the bias is
1429 * statistical, we have to test that we don't drop below
1430 * the minimum feasible timer (which is 2 ticks).
1432 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1433 (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */
1436 * We received an ack for a packet that wasn't retransmitted;
1437 * it is probably safe to discard any error indications we've
1438 * received recently. This isn't quite right, but close enough
1439 * for now (a route might have failed after we sent a segment,
1440 * and the return path might not be symmetrical).
1442 tp->t_softerror = 0;
1446 * Determine a reasonable value for maxseg size.
1447 * If the route is known, check route for mtu.
1448 * If none, use an mss that can be handled on the outgoing
1449 * interface without forcing IP to fragment; if bigger than
1450 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1451 * to utilize large mbufs. If no route is found, route has no mtu,
1452 * or the destination isn't local, use a default, hopefully conservative
1453 * size (usually 512 or the default IP max size, but no more than the mtu
1454 * of the interface), as we can't discover anything about intervening
1455 * gateways or networks. We also initialize the congestion/slow start
1456 * window to be a single segment if the destination isn't local.
1457 * While looking at the routing entry, we also initialize other path-dependent
1458 * parameters from pre-set or cached values in the routing entry.
1462 tcp_mss(struct tcpcb *tp, u_int offer)
1464 struct socket *so = tp->t_socket;
1467 DEBUG_CALL("tcp_mss");
1468 DEBUG_ARG("tp = %lx", (long)tp);
1469 DEBUG_ARG("offer = %d", offer);
1471 mss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);
1473 mss = min(mss, offer);
1475 if (mss < tp->t_maxseg || offer != 0)
1480 sbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?
1481 (mss - (TCP_SNDSPACE % mss)) :
1483 sbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?
1484 (mss - (TCP_RCVSPACE % mss)) :
1487 DEBUG_MISC((dfd, " returning mss = %d\n", mss));