source: rtems/cpukit/libnetworking/netinet/tcp_input.c @ 91d6372

4.104.115
Last change on this file since 91d6372 was dd967330, checked in by Ralf Corsepius <ralf.corsepius@…>, on 09/01/08 at 06:36:17

Stop using old-style function definitions.

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