source: rtems/cpukit/libnetworking/netinet/tcp_input.c @ 65c6425

4.115
Last change on this file since 65c6425 was 65c6425, checked in by Joel Sherrill <joel.sherrill@…>, on 05/03/12 at 17:24:46

Remove CVS Id Strings (manual edits after script)

These modifications were required by hand after running the script.
In some cases, the file names did not match patterns. In others,
the format of the file did not match any common patterns.

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