source: rtems/cpukit/libnetworking/netinet/tcp_input.c @ b6ea96ef

4.104.114.84.95
Last change on this file since b6ea96ef was 3fb76805, checked in by Joel Sherrill <joel.sherrill@…>, on 10/04/02 at 14:47:11

2002-10-04 Jay Monkman <jtm@…>

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