source: rtems/cpukit/libnetworking/netinet/tcp_input.c @ 33679ec4

4.104.114.84.95
Last change on this file since 33679ec4 was 33679ec4, checked in by Joel Sherrill <joel.sherrill@…>, on 08/21/98 at 13:04:55

All warnings removed.

  • Property mode set to 100644
File size: 60.0 KB
Line 
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 *      The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *      This product includes software developed by the University of
16 *      California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *      @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
34 *      $Id$
35 */
36
37#include "opt_tcpdebug.h"
38
39#ifndef TUBA_INCLUDE
40#include <sys/param.h>
41#include <sys/queue.h>
42#include <sys/systm.h>
43#include <sys/kernel.h>
44#include <sys/sysctl.h>
45#include <sys/malloc.h>
46#include <sys/mbuf.h>
47#include <sys/protosw.h>
48#include <sys/socket.h>
49#include <sys/socketvar.h>
50#include <sys/errno.h>
51#include <sys/syslog.h>
52
53#include <machine/cpu.h>        /* before tcp_seq.h, for tcp_random18() */
54
55#include <net/if.h>
56#include <net/route.h>
57
58#include <netinet/in.h>
59#include <netinet/in_systm.h>
60#include <netinet/ip.h>
61#include <netinet/in_pcb.h>
62#include <netinet/ip_var.h>
63#include <netinet/tcp.h>
64#include <netinet/tcp_fsm.h>
65#include <netinet/tcp_seq.h>
66#include <netinet/tcp_timer.h>
67#include <netinet/tcp_var.h>
68#include <netinet/tcpip.h>
69#ifdef TCPDEBUG
70#include <netinet/tcp_debug.h>
71static struct   tcpiphdr tcp_saveti;
72#endif
73
74static int      tcprexmtthresh = 3;
75tcp_seq tcp_iss;
76tcp_cc  tcp_ccgen;
77
78struct  tcpstat tcpstat;
79SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats,
80        CTLFLAG_RD, &tcpstat , tcpstat, "");
81
82static int log_in_vain = 0;
83SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
84        &log_in_vain, 0, "");
85
86u_long  tcp_now;
87struct inpcbhead tcb;
88struct inpcbinfo tcbinfo;
89
90static void      tcp_dooptions __P((struct tcpcb *,
91            u_char *, int, struct tcpiphdr *, struct tcpopt *));
92static void      tcp_pulloutofband __P((struct socket *,
93            struct tcpiphdr *, struct mbuf *));
94static int       tcp_reass __P((struct tcpcb *, struct tcpiphdr *, struct mbuf *));
95static void      tcp_xmit_timer __P((struct tcpcb *, int));
96
97#endif /* TUBA_INCLUDE */
98
99/*
100 * Insert segment ti into reassembly queue of tcp with
101 * control block tp.  Return TH_FIN if reassembly now includes
102 * a segment with FIN.  The macro form does the common case inline
103 * (segment is the next to be received on an established connection,
104 * and the queue is empty), avoiding linkage into and removal
105 * from the queue and repetition of various conversions.
106 * Set DELACK for segments received in order, but ack immediately
107 * when segments are out of order (so fast retransmit can work).
108 */
109#ifdef TCP_ACK_HACK
110#define TCP_REASS(tp, ti, m, so, flags) { \
111        if ((ti)->ti_seq == (tp)->rcv_nxt && \
112            (tp)->seg_next == (struct tcpiphdr *)(tp) && \
113            (tp)->t_state == TCPS_ESTABLISHED) { \
114                if (ti->ti_flags & TH_PUSH) \
115                        tp->t_flags |= TF_ACKNOW; \
116                else \
117                        tp->t_flags |= TF_DELACK; \
118                (tp)->rcv_nxt += (ti)->ti_len; \
119                flags = (ti)->ti_flags & TH_FIN; \
120                tcpstat.tcps_rcvpack++;\
121                tcpstat.tcps_rcvbyte += (ti)->ti_len;\
122                sbappend(&(so)->so_rcv, (m)); \
123                sorwakeup(so); \
124        } else { \
125                (flags) = tcp_reass((tp), (ti), (m)); \
126                tp->t_flags |= TF_ACKNOW; \
127        } \
128}
129#else
130#define TCP_REASS(tp, ti, m, so, flags) { \
131        if ((ti)->ti_seq == (tp)->rcv_nxt && \
132            (tp)->seg_next == (struct tcpiphdr *)(tp) && \
133            (tp)->t_state == TCPS_ESTABLISHED) { \
134                tp->t_flags |= TF_DELACK; \
135                (tp)->rcv_nxt += (ti)->ti_len; \
136                flags = (ti)->ti_flags & TH_FIN; \
137                tcpstat.tcps_rcvpack++;\
138                tcpstat.tcps_rcvbyte += (ti)->ti_len;\
139                sbappend(&(so)->so_rcv, (m)); \
140                sorwakeup(so); \
141        } else { \
142                (flags) = tcp_reass((tp), (ti), (m)); \
143                tp->t_flags |= TF_ACKNOW; \
144        } \
145}
146#endif
147#ifndef TUBA_INCLUDE
148
149static int
150tcp_reass(tp, ti, m)
151        register struct tcpcb *tp;
152        register struct tcpiphdr *ti;
153        struct mbuf *m;
154{
155        register struct tcpiphdr *q;
156        struct socket *so = tp->t_inpcb->inp_socket;
157        int flags;
158
159        /*
160         * Call with ti==0 after become established to
161         * force pre-ESTABLISHED data up to user socket.
162         */
163        if (ti == 0)
164                goto present;
165
166        /*
167         * Find a segment which begins after this one does.
168         */
169        for (q = tp->seg_next; q != (struct tcpiphdr *)tp;
170            q = (struct tcpiphdr *)q->ti_next)
171                if (SEQ_GT(q->ti_seq, ti->ti_seq))
172                        break;
173
174        /*
175         * If there is a preceding segment, it may provide some of
176         * our data already.  If so, drop the data from the incoming
177         * segment.  If it provides all of our data, drop us.
178         */
179        if ((struct tcpiphdr *)q->ti_prev != (struct tcpiphdr *)tp) {
180                register int i;
181                q = (struct tcpiphdr *)q->ti_prev;
182                /* conversion to int (in i) handles seq wraparound */
183                i = q->ti_seq + q->ti_len - ti->ti_seq;
184                if (i > 0) {
185                        if (i >= ti->ti_len) {
186                                tcpstat.tcps_rcvduppack++;
187                                tcpstat.tcps_rcvdupbyte += ti->ti_len;
188                                m_freem(m);
189                                /*
190                                 * Try to present any queued data
191                                 * at the left window edge to the user.
192                                 * This is needed after the 3-WHS
193                                 * completes.
194                                 */
195                                goto present;   /* ??? */
196                        }
197                        m_adj(m, i);
198                        ti->ti_len -= i;
199                        ti->ti_seq += i;
200                }
201                q = (struct tcpiphdr *)(q->ti_next);
202        }
203        tcpstat.tcps_rcvoopack++;
204        tcpstat.tcps_rcvoobyte += ti->ti_len;
205        REASS_MBUF(ti) = m;             /* XXX */
206
207        /*
208         * While we overlap succeeding segments trim them or,
209         * if they are completely covered, dequeue them.
210         */
211        while (q != (struct tcpiphdr *)tp) {
212                register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
213                if (i <= 0)
214                        break;
215                if (i < q->ti_len) {
216                        q->ti_seq += i;
217                        q->ti_len -= i;
218                        m_adj(REASS_MBUF(q), i);
219                        break;
220                }
221                q = (struct tcpiphdr *)q->ti_next;
222                m = REASS_MBUF((struct tcpiphdr *)q->ti_prev);
223                remque(q->ti_prev);
224                m_freem(m);
225        }
226
227        /*
228         * Stick new segment in its place.
229         */
230        insque(ti, q->ti_prev);
231
232present:
233        /*
234         * Present data to user, advancing rcv_nxt through
235         * completed sequence space.
236         */
237        if (!TCPS_HAVEESTABLISHED(tp->t_state))
238                return (0);
239        ti = tp->seg_next;
240        if (ti == (struct tcpiphdr *)tp || ti->ti_seq != tp->rcv_nxt)
241                return (0);
242        do {
243                tp->rcv_nxt += ti->ti_len;
244                flags = ti->ti_flags & TH_FIN;
245                remque(ti);
246                m = REASS_MBUF(ti);
247                ti = (struct tcpiphdr *)ti->ti_next;
248                if (so->so_state & SS_CANTRCVMORE)
249                        m_freem(m);
250                else
251                        sbappend(&so->so_rcv, m);
252        } while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
253        sorwakeup(so);
254        return (flags);
255}
256
257/*
258 * TCP input routine, follows pages 65-76 of the
259 * protocol specification dated September, 1981 very closely.
260 */
261void
262tcp_input(m, iphlen)
263        register struct mbuf *m;
264        int iphlen;
265{
266        register struct tcpiphdr *ti;
267        register struct inpcb *inp;
268        u_char *optp = NULL;
269        int optlen = 0;
270        int len, tlen, off;
271        register struct tcpcb *tp = 0;
272        register int tiflags;
273        struct socket *so = 0;
274        int todrop, acked, ourfinisacked, needoutput = 0;
275        struct in_addr laddr;
276        int dropsocket = 0;
277        int iss = 0;
278        u_long tiwin;
279        struct tcpopt to;               /* options in this segment */
280        struct rmxp_tao *taop;          /* pointer to our TAO cache entry */
281        struct rmxp_tao tao_noncached;  /* in case there's no cached entry */
282#ifdef TCPDEBUG
283        short ostate = 0;
284#endif
285
286        bzero((char *)&to, sizeof(to));
287
288        tcpstat.tcps_rcvtotal++;
289        /*
290         * Get IP and TCP header together in first mbuf.
291         * Note: IP leaves IP header in first mbuf.
292         */
293        ti = mtod(m, struct tcpiphdr *);
294        if (iphlen > sizeof (struct ip))
295                ip_stripoptions(m, (struct mbuf *)0);
296        if (m->m_len < sizeof (struct tcpiphdr)) {
297                if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
298                        tcpstat.tcps_rcvshort++;
299                        return;
300                }
301                ti = mtod(m, struct tcpiphdr *);
302        }
303
304        /*
305         * Checksum extended TCP header and data.
306         */
307        tlen = ((struct ip *)ti)->ip_len;
308        len = sizeof (struct ip) + tlen;
309        ti->ti_next = ti->ti_prev = 0;
310        ti->ti_x1 = 0;
311        ti->ti_len = (u_short)tlen;
312        HTONS(ti->ti_len);
313        ti->ti_sum = in_cksum(m, len);
314        if (ti->ti_sum) {
315                tcpstat.tcps_rcvbadsum++;
316                goto drop;
317        }
318#endif /* TUBA_INCLUDE */
319
320        /*
321         * Check that TCP offset makes sense,
322         * pull out TCP options and adjust length.              XXX
323         */
324        off = ti->ti_off << 2;
325        if (off < sizeof (struct tcphdr) || off > tlen) {
326                tcpstat.tcps_rcvbadoff++;
327                goto drop;
328        }
329        tlen -= off;
330        ti->ti_len = tlen;
331        if (off > sizeof (struct tcphdr)) {
332                if (m->m_len < sizeof(struct ip) + off) {
333                        if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
334                                tcpstat.tcps_rcvshort++;
335                                return;
336                        }
337                        ti = mtod(m, struct tcpiphdr *);
338                }
339                optlen = off - sizeof (struct tcphdr);
340                optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
341        }
342        tiflags = ti->ti_flags;
343
344        /*
345         * Convert TCP protocol specific fields to host format.
346         */
347        NTOHL(ti->ti_seq);
348        NTOHL(ti->ti_ack);
349        NTOHS(ti->ti_win);
350        NTOHS(ti->ti_urp);
351
352        /*
353         * Drop TCP, IP headers and TCP options.
354         */
355        m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
356        m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
357
358        /*
359         * Locate pcb for segment.
360         */
361findpcb:
362        inp = in_pcblookuphash(&tcbinfo, ti->ti_src, ti->ti_sport,
363            ti->ti_dst, ti->ti_dport, 1);
364
365        /*
366         * If the state is CLOSED (i.e., TCB does not exist) then
367         * all data in the incoming segment is discarded.
368         * If the TCB exists but is in CLOSED state, it is embryonic,
369         * but should either do a listen or a connect soon.
370         */
371        if (inp == NULL) {
372                if (log_in_vain && tiflags & TH_SYN) {
373                        char buf[4*sizeof "123"];
374
375                        strcpy(buf, inet_ntoa(ti->ti_dst));
376                        log(LOG_INFO, "Connection attempt to TCP %s:%d"
377                            " from %s:%d\n",
378                            buf, ntohs(ti->ti_dport),
379                            inet_ntoa(ti->ti_src), ntohs(ti->ti_sport));
380                }
381                goto dropwithreset;
382        }
383        tp = intotcpcb(inp);
384        if (tp == 0)
385                goto dropwithreset;
386        if (tp->t_state == TCPS_CLOSED)
387                goto drop;
388
389        /* Unscale the window into a 32-bit value. */
390        if ((tiflags & TH_SYN) == 0)
391                tiwin = ti->ti_win << tp->snd_scale;
392        else
393                tiwin = ti->ti_win;
394
395        so = inp->inp_socket;
396        if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
397#ifdef TCPDEBUG
398                if (so->so_options & SO_DEBUG) {
399                        ostate = tp->t_state;
400                        tcp_saveti = *ti;
401                }
402#endif
403                if (so->so_options & SO_ACCEPTCONN) {
404                        register struct tcpcb *tp0 = tp;
405                        struct socket *so2;
406                        if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
407                                /*
408                                 * Note: dropwithreset makes sure we don't
409                                 * send a RST in response to a RST.
410                                 */
411                                if (tiflags & TH_ACK) {
412                                        tcpstat.tcps_badsyn++;
413                                        goto dropwithreset;
414                                }
415                                goto drop;
416                        }
417                        so2 = sonewconn(so, 0);
418                        if (so2 == 0) {
419                                tcpstat.tcps_listendrop++;
420                                so2 = sodropablereq(so);
421                                if (so2) {
422                                        tcp_drop(sototcpcb(so2), ETIMEDOUT);
423                                        so2 = sonewconn(so, 0);
424                                }
425                                if (!so2)
426                                        goto drop;
427                        }
428                        so = so2;
429                        /*
430                         * This is ugly, but ....
431                         *
432                         * Mark socket as temporary until we're
433                         * committed to keeping it.  The code at
434                         * ``drop'' and ``dropwithreset'' check the
435                         * flag dropsocket to see if the temporary
436                         * socket created here should be discarded.
437                         * We mark the socket as discardable until
438                         * we're committed to it below in TCPS_LISTEN.
439                         */
440                        dropsocket++;
441                        inp = (struct inpcb *)so->so_pcb;
442                        inp->inp_laddr = ti->ti_dst;
443                        inp->inp_lport = ti->ti_dport;
444                        in_pcbrehash(inp);
445#if BSD>=43
446                        inp->inp_options = ip_srcroute();
447#endif
448                        tp = intotcpcb(inp);
449                        tp->t_state = TCPS_LISTEN;
450                        tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
451
452                        /* Compute proper scaling value from buffer space */
453                        while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
454                           TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
455                                tp->request_r_scale++;
456                }
457        }
458
459        /*
460         * Segment received on connection.
461         * Reset idle time and keep-alive timer.
462         */
463        tp->t_idle = 0;
464        if (TCPS_HAVEESTABLISHED(tp->t_state))
465                tp->t_timer[TCPT_KEEP] = tcp_keepidle;
466
467        /*
468         * Process options if not in LISTEN state,
469         * else do it below (after getting remote address).
470         */
471        if (tp->t_state != TCPS_LISTEN)
472                tcp_dooptions(tp, optp, optlen, ti, &to);
473
474        /*
475         * Header prediction: check for the two common cases
476         * of a uni-directional data xfer.  If the packet has
477         * no control flags, is in-sequence, the window didn't
478         * change and we're not retransmitting, it's a
479         * candidate.  If the length is zero and the ack moved
480         * forward, we're the sender side of the xfer.  Just
481         * free the data acked & wake any higher level process
482         * that was blocked waiting for space.  If the length
483         * is non-zero and the ack didn't move, we're the
484         * receiver side.  If we're getting packets in-order
485         * (the reassembly queue is empty), add the data to
486         * the socket buffer and note that we need a delayed ack.
487         * Make sure that the hidden state-flags are also off.
488         * Since we check for TCPS_ESTABLISHED above, it can only
489         * be TH_NEEDSYN.
490         */
491        if (tp->t_state == TCPS_ESTABLISHED &&
492            (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
493            ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
494            ((to.to_flag & TOF_TS) == 0 ||
495             TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
496            /*
497             * Using the CC option is compulsory if once started:
498             *   the segment is OK if no T/TCP was negotiated or
499             *   if the segment has a CC option equal to CCrecv
500             */
501            ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
502             ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
503            ti->ti_seq == tp->rcv_nxt &&
504            tiwin && tiwin == tp->snd_wnd &&
505            tp->snd_nxt == tp->snd_max) {
506
507                /*
508                 * If last ACK falls within this segment's sequence numbers,
509                 * record the timestamp.
510                 * NOTE that the test is modified according to the latest
511                 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
512                 */
513                if ((to.to_flag & TOF_TS) != 0 &&
514                   SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
515                        tp->ts_recent_age = tcp_now;
516                        tp->ts_recent = to.to_tsval;
517                }
518
519                if (ti->ti_len == 0) {
520                        if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
521                            SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
522                            tp->snd_cwnd >= tp->snd_wnd &&
523                            tp->t_dupacks < tcprexmtthresh) {
524                                /*
525                                 * this is a pure ack for outstanding data.
526                                 */
527                                ++tcpstat.tcps_predack;
528                                if ((to.to_flag & TOF_TS) != 0)
529                                        tcp_xmit_timer(tp,
530                                            tcp_now - to.to_tsecr + 1);
531                                else if (tp->t_rtt &&
532                                            SEQ_GT(ti->ti_ack, tp->t_rtseq))
533                                        tcp_xmit_timer(tp, tp->t_rtt);
534                                acked = ti->ti_ack - tp->snd_una;
535                                tcpstat.tcps_rcvackpack++;
536                                tcpstat.tcps_rcvackbyte += acked;
537                                sbdrop(&so->so_snd, acked);
538                                tp->snd_una = ti->ti_ack;
539                                m_freem(m);
540
541                                /*
542                                 * If all outstanding data are acked, stop
543                                 * retransmit timer, otherwise restart timer
544                                 * using current (possibly backed-off) value.
545                                 * If process is waiting for space,
546                                 * wakeup/selwakeup/signal.  If data
547                                 * are ready to send, let tcp_output
548                                 * decide between more output or persist.
549                                 */
550                                if (tp->snd_una == tp->snd_max)
551                                        tp->t_timer[TCPT_REXMT] = 0;
552                                else if (tp->t_timer[TCPT_PERSIST] == 0)
553                                        tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
554
555                                if (so->so_snd.sb_flags & SB_NOTIFY)
556                                        sowwakeup(so);
557                                if (so->so_snd.sb_cc)
558                                        (void) tcp_output(tp);
559                                return;
560                        }
561                } else if (ti->ti_ack == tp->snd_una &&
562                    tp->seg_next == (struct tcpiphdr *)tp &&
563                    ti->ti_len <= sbspace(&so->so_rcv)) {
564                        /*
565                         * this is a pure, in-sequence data packet
566                         * with nothing on the reassembly queue and
567                         * we have enough buffer space to take it.
568                         */
569                        ++tcpstat.tcps_preddat;
570                        tp->rcv_nxt += ti->ti_len;
571                        tcpstat.tcps_rcvpack++;
572                        tcpstat.tcps_rcvbyte += ti->ti_len;
573                        /*
574                         * Add data to socket buffer.
575                         */
576                        sbappend(&so->so_rcv, m);
577                        sorwakeup(so);
578#ifdef TCP_ACK_HACK
579                        /*
580                         * If this is a short packet, then ACK now - with Nagel
581                         *      congestion avoidance sender won't send more until
582                         *      he gets an ACK.
583                         */
584                        if (tiflags & TH_PUSH) {
585                                tp->t_flags |= TF_ACKNOW;
586                                tcp_output(tp);
587                        } else {
588                                tp->t_flags |= TF_DELACK;
589                        }
590#else
591                        tp->t_flags |= TF_DELACK;
592#endif
593                        return;
594                }
595        }
596
597        /*
598         * Calculate amount of space in receive window,
599         * and then do TCP input processing.
600         * Receive window is amount of space in rcv queue,
601         * but not less than advertised window.
602         */
603        { int win;
604
605        win = sbspace(&so->so_rcv);
606        if (win < 0)
607                win = 0;
608        tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
609        }
610
611        switch (tp->t_state) {
612
613        /*
614         * If the state is LISTEN then ignore segment if it contains an RST.
615         * If the segment contains an ACK then it is bad and send a RST.
616         * If it does not contain a SYN then it is not interesting; drop it.
617         * If it is from this socket, drop it, it must be forged.
618         * Don't bother responding if the destination was a broadcast.
619         * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
620         * tp->iss, and send a segment:
621         *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
622         * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
623         * Fill in remote peer address fields if not previously specified.
624         * Enter SYN_RECEIVED state, and process any other fields of this
625         * segment in this state.
626         */
627        case TCPS_LISTEN: {
628                struct mbuf *am;
629                register struct sockaddr_in *sin;
630
631                if (tiflags & TH_RST)
632                        goto drop;
633                if (tiflags & TH_ACK)
634                        goto dropwithreset;
635                if ((tiflags & TH_SYN) == 0)
636                        goto drop;
637                if ((ti->ti_dport == ti->ti_sport) &&
638                    (ti->ti_dst.s_addr == ti->ti_src.s_addr))
639                        goto drop;
640                /*
641                 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
642                 * in_broadcast() should never return true on a received
643                 * packet with M_BCAST not set.
644                 */
645                if (m->m_flags & (M_BCAST|M_MCAST) ||
646                    IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
647                        goto drop;
648                am = m_get(M_DONTWAIT, MT_SONAME);      /* XXX */
649                if (am == NULL)
650                        goto drop;
651                am->m_len = sizeof (struct sockaddr_in);
652                sin = mtod(am, struct sockaddr_in *);
653                sin->sin_family = AF_INET;
654                sin->sin_len = sizeof(*sin);
655                sin->sin_addr = ti->ti_src;
656                sin->sin_port = ti->ti_sport;
657                bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
658                laddr = inp->inp_laddr;
659                if (inp->inp_laddr.s_addr == INADDR_ANY)
660                        inp->inp_laddr = ti->ti_dst;
661                if (in_pcbconnect(inp, am)) {
662                        inp->inp_laddr = laddr;
663                        (void) m_free(am);
664                        goto drop;
665                }
666                (void) m_free(am);
667                tp->t_template = tcp_template(tp);
668                if (tp->t_template == 0) {
669                        tp = tcp_drop(tp, ENOBUFS);
670                        dropsocket = 0;         /* socket is already gone */
671                        goto drop;
672                }
673                if ((taop = tcp_gettaocache(inp)) == NULL) {
674                        taop = &tao_noncached;
675                        bzero(taop, sizeof(*taop));
676                }
677                tcp_dooptions(tp, optp, optlen, ti, &to);
678                if (iss)
679                        tp->iss = iss;
680                else
681                        tp->iss = tcp_iss;
682                tcp_iss += TCP_ISSINCR/4;
683                tp->irs = ti->ti_seq;
684                tcp_sendseqinit(tp);
685                tcp_rcvseqinit(tp);
686                /*
687                 * Initialization of the tcpcb for transaction;
688                 *   set SND.WND = SEG.WND,
689                 *   initialize CCsend and CCrecv.
690                 */
691                tp->snd_wnd = tiwin;    /* initial send-window */
692                tp->cc_send = CC_INC(tcp_ccgen);
693                tp->cc_recv = to.to_cc;
694                /*
695                 * Perform TAO test on incoming CC (SEG.CC) option, if any.
696                 * - compare SEG.CC against cached CC from the same host,
697                 *      if any.
698                 * - if SEG.CC > chached value, SYN must be new and is accepted
699                 *      immediately: save new CC in the cache, mark the socket
700                 *      connected, enter ESTABLISHED state, turn on flag to
701                 *      send a SYN in the next segment.
702                 *      A virtual advertised window is set in rcv_adv to
703                 *      initialize SWS prevention.  Then enter normal segment
704                 *      processing: drop SYN, process data and FIN.
705                 * - otherwise do a normal 3-way handshake.
706                 */
707                if ((to.to_flag & TOF_CC) != 0) {
708                    if (taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
709                        taop->tao_cc = to.to_cc;
710                        tp->t_state = TCPS_ESTABLISHED;
711
712                        /*
713                         * If there is a FIN, or if there is data and the
714                         * connection is local, then delay SYN,ACK(SYN) in
715                         * the hope of piggy-backing it on a response
716                         * segment.  Otherwise must send ACK now in case
717                         * the other side is slow starting.
718                         */
719                        if ((tiflags & TH_FIN) || (ti->ti_len != 0 &&
720                            in_localaddr(inp->inp_faddr)))
721                                tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
722                        else
723                                tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
724
725                        /*
726                         * Limit the `virtual advertised window' to TCP_MAXWIN
727                         * here.  Even if we requested window scaling, it will
728                         * become effective only later when our SYN is acked.
729                         */
730                        tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
731                        tcpstat.tcps_connects++;
732                        soisconnected(so);
733                        tp->t_timer[TCPT_KEEP] = tcp_keepinit;
734                        dropsocket = 0;         /* committed to socket */
735                        tcpstat.tcps_accepts++;
736                        goto trimthenstep6;
737                    }
738                /* else do standard 3-way handshake */
739                } else {
740                    /*
741                     * No CC option, but maybe CC.NEW:
742                     *   invalidate cached value.
743                     */
744                     taop->tao_cc = 0;
745                }
746                /*
747                 * TAO test failed or there was no CC option,
748                 *    do a standard 3-way handshake.
749                 */
750                tp->t_flags |= TF_ACKNOW;
751                tp->t_state = TCPS_SYN_RECEIVED;
752                tp->t_timer[TCPT_KEEP] = tcp_keepinit;
753                dropsocket = 0;         /* committed to socket */
754                tcpstat.tcps_accepts++;
755                goto trimthenstep6;
756                }
757
758        /*
759         * If the state is SYN_RECEIVED:
760         *      if seg contains SYN/ACK, send a RST.
761         *      if seg contains an ACK, but not for our SYN/ACK, send a RST.
762         */
763        case TCPS_SYN_RECEIVED:
764                if (tiflags & TH_ACK) {
765                        if (tiflags & TH_SYN) {
766                                tcpstat.tcps_badsyn++;
767                                goto dropwithreset;
768                        }
769                        if (SEQ_LEQ(ti->ti_ack, tp->snd_una) ||
770                            SEQ_GT(ti->ti_ack, tp->snd_max))
771                                goto dropwithreset;
772                }
773                break;
774
775        /*
776         * If the state is SYN_SENT:
777         *      if seg contains an ACK, but not for our SYN, drop the input.
778         *      if seg contains a RST, then drop the connection.
779         *      if seg does not contain SYN, then drop it.
780         * Otherwise this is an acceptable SYN segment
781         *      initialize tp->rcv_nxt and tp->irs
782         *      if seg contains ack then advance tp->snd_una
783         *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
784         *      arrange for segment to be acked (eventually)
785         *      continue processing rest of data/controls, beginning with URG
786         */
787        case TCPS_SYN_SENT:
788                if ((taop = tcp_gettaocache(inp)) == NULL) {
789                        taop = &tao_noncached;
790                        bzero(taop, sizeof(*taop));
791                }
792
793                if ((tiflags & TH_ACK) &&
794                    (SEQ_LEQ(ti->ti_ack, tp->iss) ||
795                     SEQ_GT(ti->ti_ack, tp->snd_max))) {
796                        /*
797                         * If we have a cached CCsent for the remote host,
798                         * hence we haven't just crashed and restarted,
799                         * do not send a RST.  This may be a retransmission
800                         * from the other side after our earlier ACK was lost.
801                         * Our new SYN, when it arrives, will serve as the
802                         * needed ACK.
803                         */
804                        if (taop->tao_ccsent != 0)
805                                goto drop;
806                        else
807                                goto dropwithreset;
808                }
809                if (tiflags & TH_RST) {
810                        if (tiflags & TH_ACK)
811                                tp = tcp_drop(tp, ECONNREFUSED);
812                        goto drop;
813                }
814                if ((tiflags & TH_SYN) == 0)
815                        goto drop;
816                tp->snd_wnd = ti->ti_win;       /* initial send window */
817                tp->cc_recv = to.to_cc;         /* foreign CC */
818
819                tp->irs = ti->ti_seq;
820                tcp_rcvseqinit(tp);
821                if (tiflags & TH_ACK) {
822                        /*
823                         * Our SYN was acked.  If segment contains CC.ECHO
824                         * option, check it to make sure this segment really
825                         * matches our SYN.  If not, just drop it as old
826                         * duplicate, but send an RST if we're still playing
827                         * by the old rules.  If no CC.ECHO option, make sure
828                         * we don't get fooled into using T/TCP.
829                         */
830                        if (to.to_flag & TOF_CCECHO) {
831                                if (tp->cc_send != to.to_ccecho)
832                                        if (taop->tao_ccsent != 0)
833                                                goto drop;
834                                        else
835                                                goto dropwithreset;
836                        } else
837                                tp->t_flags &= ~TF_RCVD_CC;
838                        tcpstat.tcps_connects++;
839                        soisconnected(so);
840                        /* Do window scaling on this connection? */
841                        if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
842                                (TF_RCVD_SCALE|TF_REQ_SCALE)) {
843                                tp->snd_scale = tp->requested_s_scale;
844                                tp->rcv_scale = tp->request_r_scale;
845                        }
846                        /* Segment is acceptable, update cache if undefined. */
847                        if (taop->tao_ccsent == 0)
848                                taop->tao_ccsent = to.to_ccecho;
849
850                        tp->rcv_adv += tp->rcv_wnd;
851                        tp->snd_una++;          /* SYN is acked */
852                        /*
853                         * If there's data, delay ACK; if there's also a FIN
854                         * ACKNOW will be turned on later.
855                         */
856                        if (ti->ti_len != 0)
857                                tp->t_flags |= TF_DELACK;
858                        else
859                                tp->t_flags |= TF_ACKNOW;
860                        /*
861                         * Received <SYN,ACK> in SYN_SENT[*] state.
862                         * Transitions:
863                         *      SYN_SENT  --> ESTABLISHED
864                         *      SYN_SENT* --> FIN_WAIT_1
865                         */
866                        if (tp->t_flags & TF_NEEDFIN) {
867                                tp->t_state = TCPS_FIN_WAIT_1;
868                                tp->t_flags &= ~TF_NEEDFIN;
869                                tiflags &= ~TH_SYN;
870                        } else {
871                                tp->t_state = TCPS_ESTABLISHED;
872                                tp->t_timer[TCPT_KEEP] = tcp_keepidle;
873                        }
874                } else {
875                /*
876                 *  Received initial SYN in SYN-SENT[*] state => simul-
877                 *  taneous open.  If segment contains CC option and there is
878                 *  a cached CC, apply TAO test; if it succeeds, connection is
879                 *  half-synchronized.  Otherwise, do 3-way handshake:
880                 *        SYN-SENT -> SYN-RECEIVED
881                 *        SYN-SENT* -> SYN-RECEIVED*
882                 *  If there was no CC option, clear cached CC value.
883                 */
884                        tp->t_flags |= TF_ACKNOW;
885                        tp->t_timer[TCPT_REXMT] = 0;
886                        if (to.to_flag & TOF_CC) {
887                                if (taop->tao_cc != 0 &&
888                                    CC_GT(to.to_cc, taop->tao_cc)) {
889                                        /*
890                                         * update cache and make transition:
891                                         *        SYN-SENT -> ESTABLISHED*
892                                         *        SYN-SENT* -> FIN-WAIT-1*
893                                         */
894                                        taop->tao_cc = to.to_cc;
895                                        if (tp->t_flags & TF_NEEDFIN) {
896                                                tp->t_state = TCPS_FIN_WAIT_1;
897                                                tp->t_flags &= ~TF_NEEDFIN;
898                                        } else {
899                                                tp->t_state = TCPS_ESTABLISHED;
900                                                tp->t_timer[TCPT_KEEP] = tcp_keepidle;
901                                        }
902                                        tp->t_flags |= TF_NEEDSYN;
903                                } else
904                                        tp->t_state = TCPS_SYN_RECEIVED;
905                        } else {
906                                /* CC.NEW or no option => invalidate cache */
907                                taop->tao_cc = 0;
908                                tp->t_state = TCPS_SYN_RECEIVED;
909                        }
910                }
911
912trimthenstep6:
913                /*
914                 * Advance ti->ti_seq to correspond to first data byte.
915                 * If data, trim to stay within window,
916                 * dropping FIN if necessary.
917                 */
918                ti->ti_seq++;
919                if (ti->ti_len > tp->rcv_wnd) {
920                        todrop = ti->ti_len - tp->rcv_wnd;
921                        m_adj(m, -todrop);
922                        ti->ti_len = tp->rcv_wnd;
923                        tiflags &= ~TH_FIN;
924                        tcpstat.tcps_rcvpackafterwin++;
925                        tcpstat.tcps_rcvbyteafterwin += todrop;
926                }
927                tp->snd_wl1 = ti->ti_seq - 1;
928                tp->rcv_up = ti->ti_seq;
929                /*
930                 *  Client side of transaction: already sent SYN and data.
931                 *  If the remote host used T/TCP to validate the SYN,
932                 *  our data will be ACK'd; if so, enter normal data segment
933                 *  processing in the middle of step 5, ack processing.
934                 *  Otherwise, goto step 6.
935                 */
936                if (tiflags & TH_ACK)
937                        goto process_ACK;
938                goto step6;
939        /*
940         * If the state is LAST_ACK or CLOSING or TIME_WAIT:
941         *      if segment contains a SYN and CC [not CC.NEW] option:
942         *              if state == TIME_WAIT and connection duration > MSL,
943         *                  drop packet and send RST;
944         *
945         *              if SEG.CC > CCrecv then is new SYN, and can implicitly
946         *                  ack the FIN (and data) in retransmission queue.
947         *                  Complete close and delete TCPCB.  Then reprocess
948         *                  segment, hoping to find new TCPCB in LISTEN state;
949         *
950         *              else must be old SYN; drop it.
951         *      else do normal processing.
952         */
953        case TCPS_LAST_ACK:
954        case TCPS_CLOSING:
955        case TCPS_TIME_WAIT:
956                if ((tiflags & TH_SYN) &&
957                    (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
958                        if (tp->t_state == TCPS_TIME_WAIT &&
959                                        tp->t_duration > TCPTV_MSL)
960                                goto dropwithreset;
961                        if (CC_GT(to.to_cc, tp->cc_recv)) {
962                                tp = tcp_close(tp);
963                                goto findpcb;
964                        }
965                        else
966                                goto drop;
967                }
968                break;  /* continue normal processing */
969        }
970
971        /*
972         * States other than LISTEN or SYN_SENT.
973         * First check timestamp, if present.
974         * Then check the connection count, if present.
975         * Then check that at least some bytes of segment are within
976         * receive window.  If segment begins before rcv_nxt,
977         * drop leading data (and SYN); if nothing left, just ack.
978         *
979         * RFC 1323 PAWS: If we have a timestamp reply on this segment
980         * and it's less than ts_recent, drop it.
981         */
982        if ((to.to_flag & TOF_TS) != 0 && (tiflags & TH_RST) == 0 &&
983            tp->ts_recent && TSTMP_LT(to.to_tsval, tp->ts_recent)) {
984
985                /* Check to see if ts_recent is over 24 days old.  */
986                if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
987                        /*
988                         * Invalidate ts_recent.  If this segment updates
989                         * ts_recent, the age will be reset later and ts_recent
990                         * will get a valid value.  If it does not, setting
991                         * ts_recent to zero will at least satisfy the
992                         * requirement that zero be placed in the timestamp
993                         * echo reply when ts_recent isn't valid.  The
994                         * age isn't reset until we get a valid ts_recent
995                         * because we don't want out-of-order segments to be
996                         * dropped when ts_recent is old.
997                         */
998                        tp->ts_recent = 0;
999                } else {
1000                        tcpstat.tcps_rcvduppack++;
1001                        tcpstat.tcps_rcvdupbyte += ti->ti_len;
1002                        tcpstat.tcps_pawsdrop++;
1003                        goto dropafterack;
1004                }
1005        }
1006
1007        /*
1008         * T/TCP mechanism
1009         *   If T/TCP was negotiated and the segment doesn't have CC,
1010         *   or if it's CC is wrong then drop the segment.
1011         *   RST segments do not have to comply with this.
1012         */
1013        if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1014            ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc) &&
1015            (tiflags & TH_RST) == 0)
1016                goto dropafterack;
1017
1018        todrop = tp->rcv_nxt - ti->ti_seq;
1019        if (todrop > 0) {
1020                if (tiflags & TH_SYN) {
1021                        tiflags &= ~TH_SYN;
1022                        ti->ti_seq++;
1023                        if (ti->ti_urp > 1)
1024                                ti->ti_urp--;
1025                        else
1026                                tiflags &= ~TH_URG;
1027                        todrop--;
1028                }
1029                /*
1030                 * Following if statement from Stevens, vol. 2, p. 960.
1031                 */
1032                if (todrop > ti->ti_len
1033                    || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
1034                        /*
1035                         * Any valid FIN must be to the left of the window.
1036                         * At this point the FIN must be a duplicate or out
1037                         * of sequence; drop it.
1038                         */
1039                        tiflags &= ~TH_FIN;
1040
1041                        /*
1042                         * Send an ACK to resynchronize and drop any data.
1043                         * But keep on processing for RST or ACK.
1044                         */
1045                        tp->t_flags |= TF_ACKNOW;
1046                        todrop = ti->ti_len;
1047                        tcpstat.tcps_rcvduppack++;
1048                        tcpstat.tcps_rcvdupbyte += todrop;
1049                } else {
1050                        tcpstat.tcps_rcvpartduppack++;
1051                        tcpstat.tcps_rcvpartdupbyte += todrop;
1052                }
1053                m_adj(m, todrop);
1054                ti->ti_seq += todrop;
1055                ti->ti_len -= todrop;
1056                if (ti->ti_urp > todrop)
1057                        ti->ti_urp -= todrop;
1058                else {
1059                        tiflags &= ~TH_URG;
1060                        ti->ti_urp = 0;
1061                }
1062        }
1063
1064        /*
1065         * If new data are received on a connection after the
1066         * user processes are gone, then RST the other end.
1067         */
1068        if ((so->so_state & SS_NOFDREF) &&
1069            tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
1070                tp = tcp_close(tp);
1071                tcpstat.tcps_rcvafterclose++;
1072                goto dropwithreset;
1073        }
1074
1075        /*
1076         * If segment ends after window, drop trailing data
1077         * (and PUSH and FIN); if nothing left, just ACK.
1078         */
1079        todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
1080        if (todrop > 0) {
1081                tcpstat.tcps_rcvpackafterwin++;
1082                if (todrop >= ti->ti_len) {
1083                        tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
1084                        /*
1085                         * If a new connection request is received
1086                         * while in TIME_WAIT, drop the old connection
1087                         * and start over if the sequence numbers
1088                         * are above the previous ones.
1089                         */
1090                        if (tiflags & TH_SYN &&
1091                            tp->t_state == TCPS_TIME_WAIT &&
1092                            SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1093                                iss = tp->rcv_nxt + TCP_ISSINCR;
1094                                tp = tcp_close(tp);
1095                                goto findpcb;
1096                        }
1097                        /*
1098                         * If window is closed can only take segments at
1099                         * window edge, and have to drop data and PUSH from
1100                         * incoming segments.  Continue processing, but
1101                         * remember to ack.  Otherwise, drop segment
1102                         * and ack.
1103                         */
1104                        if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1105                                tp->t_flags |= TF_ACKNOW;
1106                                tcpstat.tcps_rcvwinprobe++;
1107                        } else
1108                                goto dropafterack;
1109                } else
1110                        tcpstat.tcps_rcvbyteafterwin += todrop;
1111                m_adj(m, -todrop);
1112                ti->ti_len -= todrop;
1113                tiflags &= ~(TH_PUSH|TH_FIN);
1114        }
1115
1116        /*
1117         * If last ACK falls within this segment's sequence numbers,
1118         * record its timestamp.
1119         * NOTE that the test is modified according to the latest
1120         * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1121         */
1122        if ((to.to_flag & TOF_TS) != 0 &&
1123            SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
1124                tp->ts_recent_age = tcp_now;
1125                tp->ts_recent = to.to_tsval;
1126        }
1127
1128        /*
1129         * If the RST bit is set examine the state:
1130         *    SYN_RECEIVED STATE:
1131         *      If passive open, return to LISTEN state.
1132         *      If active open, inform user that connection was refused.
1133         *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1134         *      Inform user that connection was reset, and close tcb.
1135         *    CLOSING, LAST_ACK, TIME_WAIT STATES
1136         *      Close the tcb.
1137         */
1138        if (tiflags&TH_RST) switch (tp->t_state) {
1139
1140        case TCPS_SYN_RECEIVED:
1141                so->so_error = ECONNREFUSED;
1142                goto close;
1143
1144        case TCPS_ESTABLISHED:
1145        case TCPS_FIN_WAIT_1:
1146        case TCPS_FIN_WAIT_2:
1147        case TCPS_CLOSE_WAIT:
1148                so->so_error = ECONNRESET;
1149        close:
1150                tp->t_state = TCPS_CLOSED;
1151                tcpstat.tcps_drops++;
1152                tp = tcp_close(tp);
1153                goto drop;
1154
1155        case TCPS_CLOSING:
1156        case TCPS_LAST_ACK:
1157        case TCPS_TIME_WAIT:
1158                tp = tcp_close(tp);
1159                goto drop;
1160        }
1161
1162        /*
1163         * If a SYN is in the window, then this is an
1164         * error and we send an RST and drop the connection.
1165         */
1166        if (tiflags & TH_SYN) {
1167                tp = tcp_drop(tp, ECONNRESET);
1168                goto dropwithreset;
1169        }
1170
1171        /*
1172         * If the ACK bit is off:  if in SYN-RECEIVED state or SENDSYN
1173         * flag is on (half-synchronized state), then queue data for
1174         * later processing; else drop segment and return.
1175         */
1176        if ((tiflags & TH_ACK) == 0) {
1177                if (tp->t_state == TCPS_SYN_RECEIVED ||
1178                    (tp->t_flags & TF_NEEDSYN))
1179                        goto step6;
1180                else
1181                        goto drop;
1182        }
1183
1184        /*
1185         * Ack processing.
1186         */
1187        switch (tp->t_state) {
1188
1189        /*
1190         * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1191         * ESTABLISHED state and continue processing.
1192         * The ACK was checked above.
1193         */
1194        case TCPS_SYN_RECEIVED:
1195
1196                tcpstat.tcps_connects++;
1197                soisconnected(so);
1198                /* Do window scaling? */
1199                if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1200                        (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1201                        tp->snd_scale = tp->requested_s_scale;
1202                        tp->rcv_scale = tp->request_r_scale;
1203                }
1204                /*
1205                 * Upon successful completion of 3-way handshake,
1206                 * update cache.CC if it was undefined, pass any queued
1207                 * data to the user, and advance state appropriately.
1208                 */
1209                if ((taop = tcp_gettaocache(inp)) != NULL &&
1210                    taop->tao_cc == 0)
1211                        taop->tao_cc = tp->cc_recv;
1212
1213                /*
1214                 * Make transitions:
1215                 *      SYN-RECEIVED  -> ESTABLISHED
1216                 *      SYN-RECEIVED* -> FIN-WAIT-1
1217                 */
1218                if (tp->t_flags & TF_NEEDFIN) {
1219                        tp->t_state = TCPS_FIN_WAIT_1;
1220                        tp->t_flags &= ~TF_NEEDFIN;
1221                } else {
1222                        tp->t_state = TCPS_ESTABLISHED;
1223                        tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1224                }
1225                /*
1226                 * If segment contains data or ACK, will call tcp_reass()
1227                 * later; if not, do so now to pass queued data to user.
1228                 */
1229                if (ti->ti_len == 0 && (tiflags & TH_FIN) == 0)
1230                        (void) tcp_reass(tp, (struct tcpiphdr *)0,
1231                            (struct mbuf *)0);
1232                tp->snd_wl1 = ti->ti_seq - 1;
1233                /* fall into ... */
1234
1235        /*
1236         * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1237         * ACKs.  If the ack is in the range
1238         *      tp->snd_una < ti->ti_ack <= tp->snd_max
1239         * then advance tp->snd_una to ti->ti_ack and drop
1240         * data from the retransmission queue.  If this ACK reflects
1241         * more up to date window information we update our window information.
1242         */
1243        case TCPS_ESTABLISHED:
1244        case TCPS_FIN_WAIT_1:
1245        case TCPS_FIN_WAIT_2:
1246        case TCPS_CLOSE_WAIT:
1247        case TCPS_CLOSING:
1248        case TCPS_LAST_ACK:
1249        case TCPS_TIME_WAIT:
1250
1251                if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1252                        if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1253                                tcpstat.tcps_rcvdupack++;
1254                                /*
1255                                 * If we have outstanding data (other than
1256                                 * a window probe), this is a completely
1257                                 * duplicate ack (ie, window info didn't
1258                                 * change), the ack is the biggest we've
1259                                 * seen and we've seen exactly our rexmt
1260                                 * threshhold of them, assume a packet
1261                                 * has been dropped and retransmit it.
1262                                 * Kludge snd_nxt & the congestion
1263                                 * window so we send only this one
1264                                 * packet.
1265                                 *
1266                                 * We know we're losing at the current
1267                                 * window size so do congestion avoidance
1268                                 * (set ssthresh to half the current window
1269                                 * and pull our congestion window back to
1270                                 * the new ssthresh).
1271                                 *
1272                                 * Dup acks mean that packets have left the
1273                                 * network (they're now cached at the receiver)
1274                                 * so bump cwnd by the amount in the receiver
1275                                 * to keep a constant cwnd packets in the
1276                                 * network.
1277                                 */
1278                                if (tp->t_timer[TCPT_REXMT] == 0 ||
1279                                    ti->ti_ack != tp->snd_una)
1280                                        tp->t_dupacks = 0;
1281                                else if (++tp->t_dupacks == tcprexmtthresh) {
1282                                        tcp_seq onxt = tp->snd_nxt;
1283                                        u_int win =
1284                                            min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1285                                                tp->t_maxseg;
1286
1287                                        if (win < 2)
1288                                                win = 2;
1289                                        tp->snd_ssthresh = win * tp->t_maxseg;
1290                                        tp->t_timer[TCPT_REXMT] = 0;
1291                                        tp->t_rtt = 0;
1292                                        tp->snd_nxt = ti->ti_ack;
1293                                        tp->snd_cwnd = tp->t_maxseg;
1294                                        (void) tcp_output(tp);
1295                                        tp->snd_cwnd = tp->snd_ssthresh +
1296                                               tp->t_maxseg * tp->t_dupacks;
1297                                        if (SEQ_GT(onxt, tp->snd_nxt))
1298                                                tp->snd_nxt = onxt;
1299                                        goto drop;
1300                                } else if (tp->t_dupacks > tcprexmtthresh) {
1301                                        tp->snd_cwnd += tp->t_maxseg;
1302                                        (void) tcp_output(tp);
1303                                        goto drop;
1304                                }
1305                        } else
1306                                tp->t_dupacks = 0;
1307                        break;
1308                }
1309                /*
1310                 * If the congestion window was inflated to account
1311                 * for the other side's cached packets, retract it.
1312                 */
1313                if (tp->t_dupacks >= tcprexmtthresh &&
1314                    tp->snd_cwnd > tp->snd_ssthresh)
1315                        tp->snd_cwnd = tp->snd_ssthresh;
1316                tp->t_dupacks = 0;
1317                if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1318                        tcpstat.tcps_rcvacktoomuch++;
1319                        goto dropafterack;
1320                }
1321                /*
1322                 *  If we reach this point, ACK is not a duplicate,
1323                 *     i.e., it ACKs something we sent.
1324                 */
1325                if (tp->t_flags & TF_NEEDSYN) {
1326                        /*
1327                         * T/TCP: Connection was half-synchronized, and our
1328                         * SYN has been ACK'd (so connection is now fully
1329                         * synchronized).  Go to non-starred state,
1330                         * increment snd_una for ACK of SYN, and check if
1331                         * we can do window scaling.
1332                         */
1333                        tp->t_flags &= ~TF_NEEDSYN;
1334                        tp->snd_una++;
1335                        /* Do window scaling? */
1336                        if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1337                                (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1338                                tp->snd_scale = tp->requested_s_scale;
1339                                tp->rcv_scale = tp->request_r_scale;
1340                        }
1341                }
1342
1343process_ACK:
1344                acked = ti->ti_ack - tp->snd_una;
1345                tcpstat.tcps_rcvackpack++;
1346                tcpstat.tcps_rcvackbyte += acked;
1347
1348                /*
1349                 * If we have a timestamp reply, update smoothed
1350                 * round trip time.  If no timestamp is present but
1351                 * transmit timer is running and timed sequence
1352                 * number was acked, update smoothed round trip time.
1353                 * Since we now have an rtt measurement, cancel the
1354                 * timer backoff (cf., Phil Karn's retransmit alg.).
1355                 * Recompute the initial retransmit timer.
1356                 */
1357                if (to.to_flag & TOF_TS)
1358                        tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1359                else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1360                        tcp_xmit_timer(tp,tp->t_rtt);
1361
1362                /*
1363                 * If all outstanding data is acked, stop retransmit
1364                 * timer and remember to restart (more output or persist).
1365                 * If there is more data to be acked, restart retransmit
1366                 * timer, using current (possibly backed-off) value.
1367                 */
1368                if (ti->ti_ack == tp->snd_max) {
1369                        tp->t_timer[TCPT_REXMT] = 0;
1370                        needoutput = 1;
1371                } else if (tp->t_timer[TCPT_PERSIST] == 0)
1372                        tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1373
1374                /*
1375                 * If no data (only SYN) was ACK'd,
1376                 *    skip rest of ACK processing.
1377                 */
1378                if (acked == 0)
1379                        goto step6;
1380
1381                /*
1382                 * When new data is acked, open the congestion window.
1383                 * If the window gives us less than ssthresh packets
1384                 * in flight, open exponentially (maxseg per packet).
1385                 * Otherwise open linearly: maxseg per window
1386                 * (maxseg^2 / cwnd per packet).
1387                 */
1388                {
1389                register u_int cw = tp->snd_cwnd;
1390                register u_int incr = tp->t_maxseg;
1391
1392                if (cw > tp->snd_ssthresh)
1393                        incr = incr * incr / cw;
1394                tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1395                }
1396                if (acked > so->so_snd.sb_cc) {
1397                        tp->snd_wnd -= so->so_snd.sb_cc;
1398                        sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1399                        ourfinisacked = 1;
1400                } else {
1401                        sbdrop(&so->so_snd, acked);
1402                        tp->snd_wnd -= acked;
1403                        ourfinisacked = 0;
1404                }
1405                if (so->so_snd.sb_flags & SB_NOTIFY)
1406                        sowwakeup(so);
1407                tp->snd_una = ti->ti_ack;
1408                if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1409                        tp->snd_nxt = tp->snd_una;
1410
1411                switch (tp->t_state) {
1412
1413                /*
1414                 * In FIN_WAIT_1 STATE in addition to the processing
1415                 * for the ESTABLISHED state if our FIN is now acknowledged
1416                 * then enter FIN_WAIT_2.
1417                 */
1418                case TCPS_FIN_WAIT_1:
1419                        if (ourfinisacked) {
1420                                /*
1421                                 * If we can't receive any more
1422                                 * data, then closing user can proceed.
1423                                 * Starting the timer is contrary to the
1424                                 * specification, but if we don't get a FIN
1425                                 * we'll hang forever.
1426                                 */
1427                                if (so->so_state & SS_CANTRCVMORE) {
1428                                        soisdisconnected(so);
1429                                        tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1430                                }
1431                                tp->t_state = TCPS_FIN_WAIT_2;
1432                        }
1433                        break;
1434
1435                /*
1436                 * In CLOSING STATE in addition to the processing for
1437                 * the ESTABLISHED state if the ACK acknowledges our FIN
1438                 * then enter the TIME-WAIT state, otherwise ignore
1439                 * the segment.
1440                 */
1441                case TCPS_CLOSING:
1442                        if (ourfinisacked) {
1443                                tp->t_state = TCPS_TIME_WAIT;
1444                                tcp_canceltimers(tp);
1445                                /* Shorten TIME_WAIT [RFC-1644, p.28] */
1446                                if (tp->cc_recv != 0 &&
1447                                    tp->t_duration < TCPTV_MSL)
1448                                        tp->t_timer[TCPT_2MSL] =
1449                                            tp->t_rxtcur * TCPTV_TWTRUNC;
1450                                else
1451                                        tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1452                                soisdisconnected(so);
1453                        }
1454                        break;
1455
1456                /*
1457                 * In LAST_ACK, we may still be waiting for data to drain
1458                 * and/or to be acked, as well as for the ack of our FIN.
1459                 * If our FIN is now acknowledged, delete the TCB,
1460                 * enter the closed state and return.
1461                 */
1462                case TCPS_LAST_ACK:
1463                        if (ourfinisacked) {
1464                                tp = tcp_close(tp);
1465                                goto drop;
1466                        }
1467                        break;
1468
1469                /*
1470                 * In TIME_WAIT state the only thing that should arrive
1471                 * is a retransmission of the remote FIN.  Acknowledge
1472                 * it and restart the finack timer.
1473                 */
1474                case TCPS_TIME_WAIT:
1475                        tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1476                        goto dropafterack;
1477                }
1478        }
1479
1480step6:
1481        /*
1482         * Update window information.
1483         * Don't look at window if no ACK: TAC's send garbage on first SYN.
1484         */
1485        if ((tiflags & TH_ACK) &&
1486            (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1487            (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1488             (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1489                /* keep track of pure window updates */
1490                if (ti->ti_len == 0 &&
1491                    tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1492                        tcpstat.tcps_rcvwinupd++;
1493                tp->snd_wnd = tiwin;
1494                tp->snd_wl1 = ti->ti_seq;
1495                tp->snd_wl2 = ti->ti_ack;
1496                if (tp->snd_wnd > tp->max_sndwnd)
1497                        tp->max_sndwnd = tp->snd_wnd;
1498                needoutput = 1;
1499        }
1500
1501        /*
1502         * Process segments with URG.
1503         */
1504        if ((tiflags & TH_URG) && ti->ti_urp &&
1505            TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1506                /*
1507                 * This is a kludge, but if we receive and accept
1508                 * random urgent pointers, we'll crash in
1509                 * soreceive.  It's hard to imagine someone
1510                 * actually wanting to send this much urgent data.
1511                 */
1512                if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1513                        ti->ti_urp = 0;                 /* XXX */
1514                        tiflags &= ~TH_URG;             /* XXX */
1515                        goto dodata;                    /* XXX */
1516                }
1517                /*
1518                 * If this segment advances the known urgent pointer,
1519                 * then mark the data stream.  This should not happen
1520                 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1521                 * a FIN has been received from the remote side.
1522                 * In these states we ignore the URG.
1523                 *
1524                 * According to RFC961 (Assigned Protocols),
1525                 * the urgent pointer points to the last octet
1526                 * of urgent data.  We continue, however,
1527                 * to consider it to indicate the first octet
1528                 * of data past the urgent section as the original
1529                 * spec states (in one of two places).
1530                 */
1531                if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1532                        tp->rcv_up = ti->ti_seq + ti->ti_urp;
1533                        so->so_oobmark = so->so_rcv.sb_cc +
1534                            (tp->rcv_up - tp->rcv_nxt) - 1;
1535                        if (so->so_oobmark == 0)
1536                                so->so_state |= SS_RCVATMARK;
1537                        sohasoutofband(so);
1538                        tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1539                }
1540                /*
1541                 * Remove out of band data so doesn't get presented to user.
1542                 * This can happen independent of advancing the URG pointer,
1543                 * but if two URG's are pending at once, some out-of-band
1544                 * data may creep in... ick.
1545                 */
1546                if (ti->ti_urp <= (u_long)ti->ti_len
1547#ifdef SO_OOBINLINE
1548                     && (so->so_options & SO_OOBINLINE) == 0
1549#endif
1550                     )
1551                        tcp_pulloutofband(so, ti, m);
1552        } else
1553                /*
1554                 * If no out of band data is expected,
1555                 * pull receive urgent pointer along
1556                 * with the receive window.
1557                 */
1558                if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1559                        tp->rcv_up = tp->rcv_nxt;
1560dodata:                                                 /* XXX */
1561
1562        /*
1563         * Process the segment text, merging it into the TCP sequencing queue,
1564         * and arranging for acknowledgment of receipt if necessary.
1565         * This process logically involves adjusting tp->rcv_wnd as data
1566         * is presented to the user (this happens in tcp_usrreq.c,
1567         * case PRU_RCVD).  If a FIN has already been received on this
1568         * connection then we just ignore the text.
1569         */
1570        if ((ti->ti_len || (tiflags&TH_FIN)) &&
1571            TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1572                TCP_REASS(tp, ti, m, so, tiflags);
1573                /*
1574                 * Note the amount of data that peer has sent into
1575                 * our window, in order to estimate the sender's
1576                 * buffer size.
1577                 */
1578                len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1579        } else {
1580                m_freem(m);
1581                tiflags &= ~TH_FIN;
1582        }
1583
1584        /*
1585         * If FIN is received ACK the FIN and let the user know
1586         * that the connection is closing.
1587         */
1588        if (tiflags & TH_FIN) {
1589                if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1590                        socantrcvmore(so);
1591                        /*
1592                         *  If connection is half-synchronized
1593                         *  (ie NEEDSYN flag on) then delay ACK,
1594                         *  so it may be piggybacked when SYN is sent.
1595                         *  Otherwise, since we received a FIN then no
1596                         *  more input can be expected, send ACK now.
1597                         */
1598                        if (tp->t_flags & TF_NEEDSYN)
1599                                tp->t_flags |= TF_DELACK;
1600                        else
1601                                tp->t_flags |= TF_ACKNOW;
1602                        tp->rcv_nxt++;
1603                }
1604                switch (tp->t_state) {
1605
1606                /*
1607                 * In SYN_RECEIVED and ESTABLISHED STATES
1608                 * enter the CLOSE_WAIT state.
1609                 */
1610                case TCPS_SYN_RECEIVED:
1611                case TCPS_ESTABLISHED:
1612                        tp->t_state = TCPS_CLOSE_WAIT;
1613                        break;
1614
1615                /*
1616                 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1617                 * enter the CLOSING state.
1618                 */
1619                case TCPS_FIN_WAIT_1:
1620                        tp->t_state = TCPS_CLOSING;
1621                        break;
1622
1623                /*
1624                 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1625                 * starting the time-wait timer, turning off the other
1626                 * standard timers.
1627                 */
1628                case TCPS_FIN_WAIT_2:
1629                        tp->t_state = TCPS_TIME_WAIT;
1630                        tcp_canceltimers(tp);
1631                        /* Shorten TIME_WAIT [RFC-1644, p.28] */
1632                        if (tp->cc_recv != 0 &&
1633                            tp->t_duration < TCPTV_MSL) {
1634                                tp->t_timer[TCPT_2MSL] =
1635                                    tp->t_rxtcur * TCPTV_TWTRUNC;
1636                                /* For transaction client, force ACK now. */
1637                                tp->t_flags |= TF_ACKNOW;
1638                        }
1639                        else
1640                                tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1641                        soisdisconnected(so);
1642                        break;
1643
1644                /*
1645                 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1646                 */
1647                case TCPS_TIME_WAIT:
1648                        tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1649                        break;
1650                }
1651        }
1652#ifdef TCPDEBUG
1653        if (so->so_options & SO_DEBUG)
1654                tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1655#endif
1656
1657        /*
1658         * Return any desired output.
1659         */
1660        if (needoutput || (tp->t_flags & TF_ACKNOW))
1661                (void) tcp_output(tp);
1662        return;
1663
1664dropafterack:
1665        /*
1666         * Generate an ACK dropping incoming segment if it occupies
1667         * sequence space, where the ACK reflects our state.
1668         */
1669        if (tiflags & TH_RST)
1670                goto drop;
1671#ifdef TCPDEBUG
1672        if (so->so_options & SO_DEBUG)
1673                tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1674#endif
1675        m_freem(m);
1676        tp->t_flags |= TF_ACKNOW;
1677        (void) tcp_output(tp);
1678        return;
1679
1680dropwithreset:
1681        /*
1682         * Generate a RST, dropping incoming segment.
1683         * Make ACK acceptable to originator of segment.
1684         * Don't bother to respond if destination was broadcast/multicast.
1685         */
1686        if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1687            IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1688                goto drop;
1689#ifdef TCPDEBUG
1690        if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1691                tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1692#endif
1693        if (tiflags & TH_ACK)
1694                tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1695        else {
1696                if (tiflags & TH_SYN)
1697                        ti->ti_len++;
1698                tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1699                    TH_RST|TH_ACK);
1700        }
1701        /* destroy temporarily created socket */
1702        if (dropsocket)
1703                (void) soabort(so);
1704        return;
1705
1706drop:
1707        /*
1708         * Drop space held by incoming segment and return.
1709         */
1710#ifdef TCPDEBUG
1711        if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1712                tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1713#endif
1714        m_freem(m);
1715        /* destroy temporarily created socket */
1716        if (dropsocket)
1717                (void) soabort(so);
1718        return;
1719#ifndef TUBA_INCLUDE
1720}
1721
1722static void
1723tcp_dooptions(tp, cp, cnt, ti, to)
1724        struct tcpcb *tp;
1725        u_char *cp;
1726        int cnt;
1727        struct tcpiphdr *ti;
1728        struct tcpopt *to;
1729{
1730        u_short mss = 0;
1731        int opt, optlen;
1732
1733        for (; cnt > 0; cnt -= optlen, cp += optlen) {
1734                opt = cp[0];
1735                if (opt == TCPOPT_EOL)
1736                        break;
1737                if (opt == TCPOPT_NOP)
1738                        optlen = 1;
1739                else {
1740                        optlen = cp[1];
1741                        if (optlen <= 0)
1742                                break;
1743                }
1744                switch (opt) {
1745
1746                default:
1747                        continue;
1748
1749                case TCPOPT_MAXSEG:
1750                        if (optlen != TCPOLEN_MAXSEG)
1751                                continue;
1752                        if (!(ti->ti_flags & TH_SYN))
1753                                continue;
1754                        bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1755                        NTOHS(mss);
1756                        break;
1757
1758                case TCPOPT_WINDOW:
1759                        if (optlen != TCPOLEN_WINDOW)
1760                                continue;
1761                        if (!(ti->ti_flags & TH_SYN))
1762                                continue;
1763                        tp->t_flags |= TF_RCVD_SCALE;
1764                        tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1765                        break;
1766
1767                case TCPOPT_TIMESTAMP:
1768                        if (optlen != TCPOLEN_TIMESTAMP)
1769                                continue;
1770                        to->to_flag |= TOF_TS;
1771                        bcopy((char *)cp + 2,
1772                            (char *)&to->to_tsval, sizeof(to->to_tsval));
1773                        NTOHL(to->to_tsval);
1774                        bcopy((char *)cp + 6,
1775                            (char *)&to->to_tsecr, sizeof(to->to_tsecr));
1776                        NTOHL(to->to_tsecr);
1777
1778                        /*
1779                         * A timestamp received in a SYN makes
1780                         * it ok to send timestamp requests and replies.
1781                         */
1782                        if (ti->ti_flags & TH_SYN) {
1783                                tp->t_flags |= TF_RCVD_TSTMP;
1784                                tp->ts_recent = to->to_tsval;
1785                                tp->ts_recent_age = tcp_now;
1786                        }
1787                        break;
1788                case TCPOPT_CC:
1789                        if (optlen != TCPOLEN_CC)
1790                                continue;
1791                        to->to_flag |= TOF_CC;
1792                        bcopy((char *)cp + 2,
1793                            (char *)&to->to_cc, sizeof(to->to_cc));
1794                        NTOHL(to->to_cc);
1795                        /*
1796                         * A CC or CC.new option received in a SYN makes
1797                         * it ok to send CC in subsequent segments.
1798                         */
1799                        if (ti->ti_flags & TH_SYN)
1800                                tp->t_flags |= TF_RCVD_CC;
1801                        break;
1802                case TCPOPT_CCNEW:
1803                        if (optlen != TCPOLEN_CC)
1804                                continue;
1805                        if (!(ti->ti_flags & TH_SYN))
1806                                continue;
1807                        to->to_flag |= TOF_CCNEW;
1808                        bcopy((char *)cp + 2,
1809                            (char *)&to->to_cc, sizeof(to->to_cc));
1810                        NTOHL(to->to_cc);
1811                        /*
1812                         * A CC or CC.new option received in a SYN makes
1813                         * it ok to send CC in subsequent segments.
1814                         */
1815                        tp->t_flags |= TF_RCVD_CC;
1816                        break;
1817                case TCPOPT_CCECHO:
1818                        if (optlen != TCPOLEN_CC)
1819                                continue;
1820                        if (!(ti->ti_flags & TH_SYN))
1821                                continue;
1822                        to->to_flag |= TOF_CCECHO;
1823                        bcopy((char *)cp + 2,
1824                            (char *)&to->to_ccecho, sizeof(to->to_ccecho));
1825                        NTOHL(to->to_ccecho);
1826                        break;
1827                }
1828        }
1829        if (ti->ti_flags & TH_SYN)
1830                tcp_mss(tp, mss);       /* sets t_maxseg */
1831}
1832
1833/*
1834 * Pull out of band byte out of a segment so
1835 * it doesn't appear in the user's data queue.
1836 * It is still reflected in the segment length for
1837 * sequencing purposes.
1838 */
1839static void
1840tcp_pulloutofband(so, ti, m)
1841        struct socket *so;
1842        struct tcpiphdr *ti;
1843        register struct mbuf *m;
1844{
1845        int cnt = ti->ti_urp - 1;
1846
1847        while (cnt >= 0) {
1848                if (m->m_len > cnt) {
1849                        char *cp = mtod(m, caddr_t) + cnt;
1850                        struct tcpcb *tp = sototcpcb(so);
1851
1852                        tp->t_iobc = *cp;
1853                        tp->t_oobflags |= TCPOOB_HAVEDATA;
1854                        bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1855                        m->m_len--;
1856                        return;
1857                }
1858                cnt -= m->m_len;
1859                m = m->m_next;
1860                if (m == 0)
1861                        break;
1862        }
1863        panic("tcp_pulloutofband");
1864}
1865
1866/*
1867 * Collect new round-trip time estimate
1868 * and update averages and current timeout.
1869 */
1870static void
1871tcp_xmit_timer(tp, rtt)
1872        register struct tcpcb *tp;
1873        short rtt;
1874{
1875        register int delta;
1876
1877        tcpstat.tcps_rttupdated++;
1878        tp->t_rttupdated++;
1879        if (tp->t_srtt != 0) {
1880                /*
1881                 * srtt is stored as fixed point with 5 bits after the
1882                 * binary point (i.e., scaled by 8).  The following magic
1883                 * is equivalent to the smoothing algorithm in rfc793 with
1884                 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1885                 * point).  Adjust rtt to origin 0.
1886                 */
1887                delta = ((rtt - 1) << TCP_DELTA_SHIFT)
1888                        - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
1889
1890                if ((tp->t_srtt += delta) <= 0)
1891                        tp->t_srtt = 1;
1892
1893                /*
1894                 * We accumulate a smoothed rtt variance (actually, a
1895                 * smoothed mean difference), then set the retransmit
1896                 * timer to smoothed rtt + 4 times the smoothed variance.
1897                 * rttvar is stored as fixed point with 4 bits after the
1898                 * binary point (scaled by 16).  The following is
1899                 * equivalent to rfc793 smoothing with an alpha of .75
1900                 * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1901                 * rfc793's wired-in beta.
1902                 */
1903                if (delta < 0)
1904                        delta = -delta;
1905                delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
1906                if ((tp->t_rttvar += delta) <= 0)
1907                        tp->t_rttvar = 1;
1908        } else {
1909                /*
1910                 * No rtt measurement yet - use the unsmoothed rtt.
1911                 * Set the variance to half the rtt (so our first
1912                 * retransmit happens at 3*rtt).
1913                 */
1914                tp->t_srtt = rtt << TCP_RTT_SHIFT;
1915                tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1916        }
1917        tp->t_rtt = 0;
1918        tp->t_rxtshift = 0;
1919
1920        /*
1921         * the retransmit should happen at rtt + 4 * rttvar.
1922         * Because of the way we do the smoothing, srtt and rttvar
1923         * will each average +1/2 tick of bias.  When we compute
1924         * the retransmit timer, we want 1/2 tick of rounding and
1925         * 1 extra tick because of +-1/2 tick uncertainty in the
1926         * firing of the timer.  The bias will give us exactly the
1927         * 1.5 tick we need.  But, because the bias is
1928         * statistical, we have to test that we don't drop below
1929         * the minimum feasible timer (which is 2 ticks).
1930         */
1931        TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1932                      max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
1933
1934        /*
1935         * We received an ack for a packet that wasn't retransmitted;
1936         * it is probably safe to discard any error indications we've
1937         * received recently.  This isn't quite right, but close enough
1938         * for now (a route might have failed after we sent a segment,
1939         * and the return path might not be symmetrical).
1940         */
1941        tp->t_softerror = 0;
1942}
1943
1944/*
1945 * Determine a reasonable value for maxseg size.
1946 * If the route is known, check route for mtu.
1947 * If none, use an mss that can be handled on the outgoing
1948 * interface without forcing IP to fragment; if bigger than
1949 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1950 * to utilize large mbufs.  If no route is found, route has no mtu,
1951 * or the destination isn't local, use a default, hopefully conservative
1952 * size (usually 512 or the default IP max size, but no more than the mtu
1953 * of the interface), as we can't discover anything about intervening
1954 * gateways or networks.  We also initialize the congestion/slow start
1955 * window to be a single segment if the destination isn't local.
1956 * While looking at the routing entry, we also initialize other path-dependent
1957 * parameters from pre-set or cached values in the routing entry.
1958 *
1959 * Also take into account the space needed for options that we
1960 * send regularly.  Make maxseg shorter by that amount to assure
1961 * that we can send maxseg amount of data even when the options
1962 * are present.  Store the upper limit of the length of options plus
1963 * data in maxopd.
1964 *
1965 * NOTE that this routine is only called when we process an incoming
1966 * segment, for outgoing segments only tcp_mssopt is called.
1967 *
1968 * In case of T/TCP, we call this routine during implicit connection
1969 * setup as well (offer = -1), to initialize maxseg from the cached
1970 * MSS of our peer.
1971 */
1972void
1973tcp_mss(tp, offer)
1974        struct tcpcb *tp;
1975        int offer;
1976{
1977        register struct rtentry *rt;
1978        struct ifnet *ifp;
1979        register int rtt, mss;
1980        u_long bufsize;
1981        struct inpcb *inp;
1982        struct socket *so;
1983        struct rmxp_tao *taop;
1984        int origoffer = offer;
1985
1986        inp = tp->t_inpcb;
1987        if ((rt = tcp_rtlookup(inp)) == NULL) {
1988                tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
1989                return;
1990        }
1991        ifp = rt->rt_ifp;
1992        so = inp->inp_socket;
1993
1994        taop = rmx_taop(rt->rt_rmx);
1995        /*
1996         * Offer == -1 means that we didn't receive SYN yet,
1997         * use cached value in that case;
1998         */
1999        if (offer == -1)
2000                offer = taop->tao_mssopt;
2001        /*
2002         * Offer == 0 means that there was no MSS on the SYN segment,
2003         * in this case we use tcp_mssdflt.
2004         */
2005        if (offer == 0)
2006                offer = tcp_mssdflt;
2007        else
2008                /*
2009                 * Sanity check: make sure that maxopd will be large
2010                 * enough to allow some data on segments even is the
2011                 * all the option space is used (40bytes).  Otherwise
2012                 * funny things may happen in tcp_output.
2013                 */
2014                offer = max(offer, 64);
2015        taop->tao_mssopt = offer;
2016
2017        /*
2018         * While we're here, check if there's an initial rtt
2019         * or rttvar.  Convert from the route-table units
2020         * to scaled multiples of the slow timeout timer.
2021         */
2022        if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2023                /*
2024                 * XXX the lock bit for RTT indicates that the value
2025                 * is also a minimum value; this is subject to time.
2026                 */
2027                if (rt->rt_rmx.rmx_locks & RTV_RTT)
2028                        tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2029                tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2030                tcpstat.tcps_usedrtt++;
2031                if (rt->rt_rmx.rmx_rttvar) {
2032                        tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2033                            (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2034                        tcpstat.tcps_usedrttvar++;
2035                } else {
2036                        /* default variation is +- 1 rtt */
2037                        tp->t_rttvar =
2038                            tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2039                }
2040                TCPT_RANGESET(tp->t_rxtcur,
2041                    ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2042                    tp->t_rttmin, TCPTV_REXMTMAX);
2043        }
2044        /*
2045         * if there's an mtu associated with the route, use it
2046         */
2047        if (rt->rt_rmx.rmx_mtu)
2048                mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
2049        else
2050        {
2051                mss = ifp->if_mtu - sizeof(struct tcpiphdr);
2052                if (!in_localaddr(inp->inp_faddr))
2053                        mss = min(mss, tcp_mssdflt);
2054        }
2055        mss = min(mss, offer);
2056        /*
2057         * maxopd stores the maximum length of data AND options
2058         * in a segment; maxseg is the amount of data in a normal
2059         * segment.  We need to store this value (maxopd) apart
2060         * from maxseg, because now every segment carries options
2061         * and thus we normally have somewhat less data in segments.
2062         */
2063        tp->t_maxopd = mss;
2064
2065        /*
2066         * In case of T/TCP, origoffer==-1 indicates, that no segments
2067         * were received yet.  In this case we just guess, otherwise
2068         * we do the same as before T/TCP.
2069         */
2070        if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2071            (origoffer == -1 ||
2072             (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2073                mss -= TCPOLEN_TSTAMP_APPA;
2074        if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2075            (origoffer == -1 ||
2076             (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2077                mss -= TCPOLEN_CC_APPA;
2078
2079#if     (MCLBYTES & (MCLBYTES - 1)) == 0
2080                if (mss > MCLBYTES)
2081                        mss &= ~(MCLBYTES-1);
2082#else
2083                if (mss > MCLBYTES)
2084                        mss = mss / MCLBYTES * MCLBYTES;
2085#endif
2086        /*
2087         * If there's a pipesize, change the socket buffer
2088         * to that size.  Make the socket buffers an integral
2089         * number of mss units; if the mss is larger than
2090         * the socket buffer, decrease the mss.
2091         */
2092#ifdef RTV_SPIPE
2093        if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2094#endif
2095                bufsize = so->so_snd.sb_hiwat;
2096        if (bufsize < mss)
2097                mss = bufsize;
2098        else {
2099                bufsize = roundup(bufsize, mss);
2100                if (bufsize > sb_max)
2101                        bufsize = sb_max;
2102                (void)sbreserve(&so->so_snd, bufsize);
2103        }
2104        tp->t_maxseg = mss;
2105
2106#ifdef RTV_RPIPE
2107        if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2108#endif
2109                bufsize = so->so_rcv.sb_hiwat;
2110        if (bufsize > mss) {
2111                bufsize = roundup(bufsize, mss);
2112                if (bufsize > sb_max)
2113                        bufsize = sb_max;
2114                (void)sbreserve(&so->so_rcv, bufsize);
2115        }
2116        /*
2117         * Don't force slow-start on local network.
2118         */
2119        if (!in_localaddr(inp->inp_faddr))
2120                tp->snd_cwnd = mss;
2121
2122        if (rt->rt_rmx.rmx_ssthresh) {
2123                /*
2124                 * There's some sort of gateway or interface
2125                 * buffer limit on the path.  Use this to set
2126                 * the slow start threshhold, but set the
2127                 * threshold to no less than 2*mss.
2128                 */
2129                tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2130                tcpstat.tcps_usedssthresh++;
2131        }
2132}
2133
2134/*
2135 * Determine the MSS option to send on an outgoing SYN.
2136 */
2137int
2138tcp_mssopt(tp)
2139        struct tcpcb *tp;
2140{
2141        struct rtentry *rt;
2142
2143        rt = tcp_rtlookup(tp->t_inpcb);
2144        if (rt == NULL)
2145                return tcp_mssdflt;
2146
2147        return rt->rt_ifp->if_mtu - sizeof(struct tcpiphdr);
2148}
2149#endif /* TUBA_INCLUDE */
Note: See TracBrowser for help on using the repository browser.