source: rtems/cpukit/libnetworking/netinet/tcp_input.c @ 4c02385

5
Last change on this file since 4c02385 was 657e6c93, checked in by Christian Mauderer <Christian.Mauderer@…>, on 06/24/16 at 05:57:17

libnetworking: Import current <netinet/in.h>

Import the <netinet/in.h> from current FreeBSD. This allows to build
some current software (e.g. libressl).

Add legacy support like

  • prototype for in_cksum(),
  • IPPORT_USERRESERVED,
  • deprecated IPCTL_RT* defines,
  • ip_fw_chk_t and ip_fw_ctl_t,
  • ip_nat_... (IP NAT hooks), and
  • IP_NAT option for get/setsockopt()

to new <rtems/rtems_netinet_in.h>.

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