slirp: Drop statistic code
[qemu] / slirp / tcp_input.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)tcp_input.c 8.5 (Berkeley) 4/10/94
30  * tcp_input.c,v 1.10 1994/10/13 18:36:32 wollman Exp
31  */
32
33 /*
34  * Changes and additions relating to SLiRP
35  * Copyright (c) 1995 Danny Gasparovski.
36  *
37  * Please read the file COPYRIGHT for the
38  * terms and conditions of the copyright.
39  */
40
41 #include <slirp.h>
42 #include "ip_icmp.h"
43
44 struct socket tcb;
45
46 #define TCPREXMTTHRESH 3
47 struct  socket *tcp_last_so = &tcb;
48
49 tcp_seq tcp_iss;                /* tcp initial send seq # */
50
51 #define TCP_PAWS_IDLE   (24 * 24 * 60 * 60 * PR_SLOWHZ)
52
53 /* for modulo comparisons of timestamps */
54 #define TSTMP_LT(a,b)   ((int)((a)-(b)) < 0)
55 #define TSTMP_GEQ(a,b)  ((int)((a)-(b)) >= 0)
56
57 /*
58  * Insert segment ti into reassembly queue of tcp with
59  * control block tp.  Return TH_FIN if reassembly now includes
60  * a segment with FIN.  The macro form does the common case inline
61  * (segment is the next to be received on an established connection,
62  * and the queue is empty), avoiding linkage into and removal
63  * from the queue and repetition of various conversions.
64  * Set DELACK for segments received in order, but ack immediately
65  * when segments are out of order (so fast retransmit can work).
66  */
67 #ifdef TCP_ACK_HACK
68 #define TCP_REASS(tp, ti, m, so, flags) {\
69        if ((ti)->ti_seq == (tp)->rcv_nxt && \
70            tcpfrag_list_empty(tp) && \
71            (tp)->t_state == TCPS_ESTABLISHED) {\
72                if (ti->ti_flags & TH_PUSH) \
73                        tp->t_flags |= TF_ACKNOW; \
74                else \
75                        tp->t_flags |= TF_DELACK; \
76                (tp)->rcv_nxt += (ti)->ti_len; \
77                flags = (ti)->ti_flags & TH_FIN; \
78                if (so->so_emu) { \
79                        if (tcp_emu((so),(m))) sbappend((so), (m)); \
80                } else \
81                        sbappend((so), (m)); \
82         } else {\
83                (flags) = tcp_reass((tp), (ti), (m)); \
84                tp->t_flags |= TF_ACKNOW; \
85        } \
86 }
87 #else
88 #define TCP_REASS(tp, ti, m, so, flags) { \
89         if ((ti)->ti_seq == (tp)->rcv_nxt && \
90         tcpfrag_list_empty(tp) && \
91             (tp)->t_state == TCPS_ESTABLISHED) { \
92                 tp->t_flags |= TF_DELACK; \
93                 (tp)->rcv_nxt += (ti)->ti_len; \
94                 flags = (ti)->ti_flags & TH_FIN; \
95                 if (so->so_emu) { \
96                         if (tcp_emu((so),(m))) sbappend(so, (m)); \
97                 } else \
98                         sbappend((so), (m)); \
99         } else { \
100                 (flags) = tcp_reass((tp), (ti), (m)); \
101                 tp->t_flags |= TF_ACKNOW; \
102         } \
103 }
104 #endif
105 static void tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt,
106                           struct tcpiphdr *ti);
107 static void tcp_xmit_timer(register struct tcpcb *tp, int rtt);
108
109 static int
110 tcp_reass(register struct tcpcb *tp, register struct tcpiphdr *ti,
111           struct mbuf *m)
112 {
113         register struct tcpiphdr *q;
114         struct socket *so = tp->t_socket;
115         int flags;
116
117         /*
118          * Call with ti==NULL after become established to
119          * force pre-ESTABLISHED data up to user socket.
120          */
121         if (ti == NULL)
122                 goto present;
123
124         /*
125          * Find a segment which begins after this one does.
126          */
127         for (q = tcpfrag_list_first(tp); !tcpfrag_list_end(q, tp);
128             q = tcpiphdr_next(q))
129                 if (SEQ_GT(q->ti_seq, ti->ti_seq))
130                         break;
131
132         /*
133          * If there is a preceding segment, it may provide some of
134          * our data already.  If so, drop the data from the incoming
135          * segment.  If it provides all of our data, drop us.
136          */
137         if (!tcpfrag_list_end(tcpiphdr_prev(q), tp)) {
138                 register int i;
139                 q = tcpiphdr_prev(q);
140                 /* conversion to int (in i) handles seq wraparound */
141                 i = q->ti_seq + q->ti_len - ti->ti_seq;
142                 if (i > 0) {
143                         if (i >= ti->ti_len) {
144                                 m_freem(m);
145                                 /*
146                                  * Try to present any queued data
147                                  * at the left window edge to the user.
148                                  * This is needed after the 3-WHS
149                                  * completes.
150                                  */
151                                 goto present;   /* ??? */
152                         }
153                         m_adj(m, i);
154                         ti->ti_len -= i;
155                         ti->ti_seq += i;
156                 }
157                 q = tcpiphdr_next(q);
158         }
159         ti->ti_mbuf = m;
160
161         /*
162          * While we overlap succeeding segments trim them or,
163          * if they are completely covered, dequeue them.
164          */
165         while (!tcpfrag_list_end(q, tp)) {
166                 register int i = (ti->ti_seq + ti->ti_len) - q->ti_seq;
167                 if (i <= 0)
168                         break;
169                 if (i < q->ti_len) {
170                         q->ti_seq += i;
171                         q->ti_len -= i;
172                         m_adj(q->ti_mbuf, i);
173                         break;
174                 }
175                 q = tcpiphdr_next(q);
176                 m = tcpiphdr_prev(q)->ti_mbuf;
177                 remque(tcpiphdr2qlink(tcpiphdr_prev(q)));
178                 m_freem(m);
179         }
180
181         /*
182          * Stick new segment in its place.
183          */
184         insque(tcpiphdr2qlink(ti), tcpiphdr2qlink(tcpiphdr_prev(q)));
185
186 present:
187         /*
188          * Present data to user, advancing rcv_nxt through
189          * completed sequence space.
190          */
191         if (!TCPS_HAVEESTABLISHED(tp->t_state))
192                 return (0);
193         ti = tcpfrag_list_first(tp);
194         if (tcpfrag_list_end(ti, tp) || ti->ti_seq != tp->rcv_nxt)
195                 return (0);
196         if (tp->t_state == TCPS_SYN_RECEIVED && ti->ti_len)
197                 return (0);
198         do {
199                 tp->rcv_nxt += ti->ti_len;
200                 flags = ti->ti_flags & TH_FIN;
201                 remque(tcpiphdr2qlink(ti));
202                 m = ti->ti_mbuf;
203                 ti = tcpiphdr_next(ti);
204                 if (so->so_state & SS_FCANTSENDMORE)
205                         m_freem(m);
206                 else {
207                         if (so->so_emu) {
208                                 if (tcp_emu(so,m)) sbappend(so, m);
209                         } else
210                                 sbappend(so, m);
211                 }
212         } while (ti != (struct tcpiphdr *)tp && ti->ti_seq == tp->rcv_nxt);
213         return (flags);
214 }
215
216 /*
217  * TCP input routine, follows pages 65-76 of the
218  * protocol specification dated September, 1981 very closely.
219  */
220 void
221 tcp_input(struct mbuf *m, int iphlen, struct socket *inso)
222 {
223         struct ip save_ip, *ip;
224         register struct tcpiphdr *ti;
225         caddr_t optp = NULL;
226         int optlen = 0;
227         int len, tlen, off;
228         register struct tcpcb *tp = NULL;
229         register int tiflags;
230         struct socket *so = NULL;
231         int todrop, acked, ourfinisacked, needoutput = 0;
232         int iss = 0;
233         u_long tiwin;
234         int ret;
235     struct ex_list *ex_ptr;
236
237         DEBUG_CALL("tcp_input");
238         DEBUG_ARGS((dfd," m = %8lx  iphlen = %2d  inso = %lx\n",
239                     (long )m, iphlen, (long )inso ));
240
241         /*
242          * If called with m == 0, then we're continuing the connect
243          */
244         if (m == NULL) {
245                 so = inso;
246
247                 /* Re-set a few variables */
248                 tp = sototcpcb(so);
249                 m = so->so_m;
250                 so->so_m = NULL;
251                 ti = so->so_ti;
252                 tiwin = ti->ti_win;
253                 tiflags = ti->ti_flags;
254
255                 goto cont_conn;
256         }
257
258         /*
259          * Get IP and TCP header together in first mbuf.
260          * Note: IP leaves IP header in first mbuf.
261          */
262         ti = mtod(m, struct tcpiphdr *);
263         if (iphlen > sizeof(struct ip )) {
264           ip_stripoptions(m, (struct mbuf *)0);
265           iphlen=sizeof(struct ip );
266         }
267         /* XXX Check if too short */
268
269
270         /*
271          * Save a copy of the IP header in case we want restore it
272          * for sending an ICMP error message in response.
273          */
274         ip=mtod(m, struct ip *);
275         save_ip = *ip;
276         save_ip.ip_len+= iphlen;
277
278         /*
279          * Checksum extended TCP header and data.
280          */
281         tlen = ((struct ip *)ti)->ip_len;
282         tcpiphdr2qlink(ti)->next = tcpiphdr2qlink(ti)->prev = NULL;
283         memset(&ti->ti_i.ih_mbuf, 0 , sizeof(struct mbuf_ptr));
284         ti->ti_x1 = 0;
285         ti->ti_len = htons((u_int16_t)tlen);
286         len = sizeof(struct ip ) + tlen;
287         if(cksum(m, len)) {
288           goto drop;
289         }
290
291         /*
292          * Check that TCP offset makes sense,
293          * pull out TCP options and adjust length.              XXX
294          */
295         off = ti->ti_off << 2;
296         if (off < sizeof (struct tcphdr) || off > tlen) {
297           goto drop;
298         }
299         tlen -= off;
300         ti->ti_len = tlen;
301         if (off > sizeof (struct tcphdr)) {
302           optlen = off - sizeof (struct tcphdr);
303           optp = mtod(m, caddr_t) + sizeof (struct tcpiphdr);
304         }
305         tiflags = ti->ti_flags;
306
307         /*
308          * Convert TCP protocol specific fields to host format.
309          */
310         NTOHL(ti->ti_seq);
311         NTOHL(ti->ti_ack);
312         NTOHS(ti->ti_win);
313         NTOHS(ti->ti_urp);
314
315         /*
316          * Drop TCP, IP headers and TCP options.
317          */
318         m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
319         m->m_len  -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
320
321     if (slirp_restrict) {
322         for (ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
323             if (ex_ptr->ex_fport == ti->ti_dport &&
324                 ti->ti_dst.s_addr == ex_ptr->ex_addr.s_addr) {
325                 break;
326             }
327         }
328         if (!ex_ptr)
329             goto drop;
330     }
331         /*
332          * Locate pcb for segment.
333          */
334 findso:
335         so = tcp_last_so;
336         if (so->so_fport != ti->ti_dport ||
337             so->so_lport != ti->ti_sport ||
338             so->so_laddr.s_addr != ti->ti_src.s_addr ||
339             so->so_faddr.s_addr != ti->ti_dst.s_addr) {
340                 so = solookup(&tcb, ti->ti_src, ti->ti_sport,
341                                ti->ti_dst, ti->ti_dport);
342                 if (so)
343                         tcp_last_so = so;
344         }
345
346         /*
347          * If the state is CLOSED (i.e., TCB does not exist) then
348          * all data in the incoming segment is discarded.
349          * If the TCB exists but is in CLOSED state, it is embryonic,
350          * but should either do a listen or a connect soon.
351          *
352          * state == CLOSED means we've done socreate() but haven't
353          * attached it to a protocol yet...
354          *
355          * XXX If a TCB does not exist, and the TH_SYN flag is
356          * the only flag set, then create a session, mark it
357          * as if it was LISTENING, and continue...
358          */
359         if (so == NULL) {
360           if ((tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) != TH_SYN)
361             goto dropwithreset;
362
363           if ((so = socreate()) == NULL)
364             goto dropwithreset;
365           if (tcp_attach(so) < 0) {
366             free(so); /* Not sofree (if it failed, it's not insqued) */
367             goto dropwithreset;
368           }
369
370           sbreserve(&so->so_snd, TCP_SNDSPACE);
371           sbreserve(&so->so_rcv, TCP_RCVSPACE);
372
373           so->so_laddr = ti->ti_src;
374           so->so_lport = ti->ti_sport;
375           so->so_faddr = ti->ti_dst;
376           so->so_fport = ti->ti_dport;
377
378           if ((so->so_iptos = tcp_tos(so)) == 0)
379             so->so_iptos = ((struct ip *)ti)->ip_tos;
380
381           tp = sototcpcb(so);
382           tp->t_state = TCPS_LISTEN;
383         }
384
385         /*
386          * If this is a still-connecting socket, this probably
387          * a retransmit of the SYN.  Whether it's a retransmit SYN
388          * or something else, we nuke it.
389          */
390         if (so->so_state & SS_ISFCONNECTING)
391                 goto drop;
392
393         tp = sototcpcb(so);
394
395         /* XXX Should never fail */
396         if (tp == NULL)
397                 goto dropwithreset;
398         if (tp->t_state == TCPS_CLOSED)
399                 goto drop;
400
401         tiwin = ti->ti_win;
402
403         /*
404          * Segment received on connection.
405          * Reset idle time and keep-alive timer.
406          */
407         tp->t_idle = 0;
408         if (SO_OPTIONS)
409            tp->t_timer[TCPT_KEEP] = TCPTV_KEEPINTVL;
410         else
411            tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_IDLE;
412
413         /*
414          * Process options if not in LISTEN state,
415          * else do it below (after getting remote address).
416          */
417         if (optp && tp->t_state != TCPS_LISTEN)
418                 tcp_dooptions(tp, (u_char *)optp, optlen, ti);
419
420         /*
421          * Header prediction: check for the two common cases
422          * of a uni-directional data xfer.  If the packet has
423          * no control flags, is in-sequence, the window didn't
424          * change and we're not retransmitting, it's a
425          * candidate.  If the length is zero and the ack moved
426          * forward, we're the sender side of the xfer.  Just
427          * free the data acked & wake any higher level process
428          * that was blocked waiting for space.  If the length
429          * is non-zero and the ack didn't move, we're the
430          * receiver side.  If we're getting packets in-order
431          * (the reassembly queue is empty), add the data to
432          * the socket buffer and note that we need a delayed ack.
433          *
434          * XXX Some of these tests are not needed
435          * eg: the tiwin == tp->snd_wnd prevents many more
436          * predictions.. with no *real* advantage..
437          */
438         if (tp->t_state == TCPS_ESTABLISHED &&
439             (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
440             ti->ti_seq == tp->rcv_nxt &&
441             tiwin && tiwin == tp->snd_wnd &&
442             tp->snd_nxt == tp->snd_max) {
443                 if (ti->ti_len == 0) {
444                         if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
445                             SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
446                             tp->snd_cwnd >= tp->snd_wnd) {
447                                 /*
448                                  * this is a pure ack for outstanding data.
449                                  */
450                                 if (tp->t_rtt &&
451                                     SEQ_GT(ti->ti_ack, tp->t_rtseq))
452                                         tcp_xmit_timer(tp, tp->t_rtt);
453                                 acked = ti->ti_ack - tp->snd_una;
454                                 sbdrop(&so->so_snd, acked);
455                                 tp->snd_una = ti->ti_ack;
456                                 m_freem(m);
457
458                                 /*
459                                  * If all outstanding data are acked, stop
460                                  * retransmit timer, otherwise restart timer
461                                  * using current (possibly backed-off) value.
462                                  * If process is waiting for space,
463                                  * wakeup/selwakeup/signal.  If data
464                                  * are ready to send, let tcp_output
465                                  * decide between more output or persist.
466                                  */
467                                 if (tp->snd_una == tp->snd_max)
468                                         tp->t_timer[TCPT_REXMT] = 0;
469                                 else if (tp->t_timer[TCPT_PERSIST] == 0)
470                                         tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
471
472                                 /*
473                                  * This is called because sowwakeup might have
474                                  * put data into so_snd.  Since we don't so sowwakeup,
475                                  * we don't need this.. XXX???
476                                  */
477                                 if (so->so_snd.sb_cc)
478                                         (void) tcp_output(tp);
479
480                                 return;
481                         }
482                 } else if (ti->ti_ack == tp->snd_una &&
483                     tcpfrag_list_empty(tp) &&
484                     ti->ti_len <= sbspace(&so->so_rcv)) {
485                         /*
486                          * this is a pure, in-sequence data packet
487                          * with nothing on the reassembly queue and
488                          * we have enough buffer space to take it.
489                          */
490                         tp->rcv_nxt += ti->ti_len;
491                         /*
492                          * Add data to socket buffer.
493                          */
494                         if (so->so_emu) {
495                                 if (tcp_emu(so,m)) sbappend(so, m);
496                         } else
497                                 sbappend(so, m);
498
499                         /*
500                          * If this is a short packet, then ACK now - with Nagel
501                          *      congestion avoidance sender won't send more until
502                          *      he gets an ACK.
503                          *
504                          * It is better to not delay acks at all to maximize
505                          * TCP throughput.  See RFC 2581.
506                          */
507                         tp->t_flags |= TF_ACKNOW;
508                         tcp_output(tp);
509                         return;
510                 }
511         } /* header prediction */
512         /*
513          * Calculate amount of space in receive window,
514          * and then do TCP input processing.
515          * Receive window is amount of space in rcv queue,
516          * but not less than advertised window.
517          */
518         { int win;
519           win = sbspace(&so->so_rcv);
520           if (win < 0)
521             win = 0;
522           tp->rcv_wnd = max(win, (int)(tp->rcv_adv - tp->rcv_nxt));
523         }
524
525         switch (tp->t_state) {
526
527         /*
528          * If the state is LISTEN then ignore segment if it contains an RST.
529          * If the segment contains an ACK then it is bad and send a RST.
530          * If it does not contain a SYN then it is not interesting; drop it.
531          * Don't bother responding if the destination was a broadcast.
532          * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
533          * tp->iss, and send a segment:
534          *     <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
535          * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
536          * Fill in remote peer address fields if not previously specified.
537          * Enter SYN_RECEIVED state, and process any other fields of this
538          * segment in this state.
539          */
540         case TCPS_LISTEN: {
541
542           if (tiflags & TH_RST)
543             goto drop;
544           if (tiflags & TH_ACK)
545             goto dropwithreset;
546           if ((tiflags & TH_SYN) == 0)
547             goto drop;
548
549           /*
550            * This has way too many gotos...
551            * But a bit of spaghetti code never hurt anybody :)
552            */
553
554           /*
555            * If this is destined for the control address, then flag to
556            * tcp_ctl once connected, otherwise connect
557            */
558           if ((so->so_faddr.s_addr & vnetwork_mask.s_addr) ==
559               vnetwork_addr.s_addr) {
560             if (so->so_faddr.s_addr != vhost_addr.s_addr &&
561                 so->so_faddr.s_addr != vnameserver_addr.s_addr) {
562                 /* May be an add exec */
563                 for(ex_ptr = exec_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
564                   if(ex_ptr->ex_fport == so->so_fport &&
565                      so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {
566                     so->so_state |= SS_CTL;
567                     break;
568                   }
569                 }
570                 if (so->so_state & SS_CTL) {
571                     goto cont_input;
572                 }
573             }
574             /* CTL_ALIAS: Do nothing, tcp_fconnect will be called on it */
575           }
576
577           if (so->so_emu & EMU_NOCONNECT) {
578             so->so_emu &= ~EMU_NOCONNECT;
579             goto cont_input;
580           }
581
582           if((tcp_fconnect(so) == -1) && (errno != EINPROGRESS) && (errno != EWOULDBLOCK)) {
583             u_char code=ICMP_UNREACH_NET;
584             DEBUG_MISC((dfd," tcp fconnect errno = %d-%s\n",
585                         errno,strerror(errno)));
586             if(errno == ECONNREFUSED) {
587               /* ACK the SYN, send RST to refuse the connection */
588               tcp_respond(tp, ti, m, ti->ti_seq+1, (tcp_seq)0,
589                           TH_RST|TH_ACK);
590             } else {
591               if(errno == EHOSTUNREACH) code=ICMP_UNREACH_HOST;
592               HTONL(ti->ti_seq);             /* restore tcp header */
593               HTONL(ti->ti_ack);
594               HTONS(ti->ti_win);
595               HTONS(ti->ti_urp);
596               m->m_data -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
597               m->m_len  += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
598               *ip=save_ip;
599               icmp_error(m, ICMP_UNREACH,code, 0,strerror(errno));
600             }
601             tp = tcp_close(tp);
602             m_free(m);
603           } else {
604             /*
605              * Haven't connected yet, save the current mbuf
606              * and ti, and return
607              * XXX Some OS's don't tell us whether the connect()
608              * succeeded or not.  So we must time it out.
609              */
610             so->so_m = m;
611             so->so_ti = ti;
612             tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
613             tp->t_state = TCPS_SYN_RECEIVED;
614           }
615           return;
616
617         cont_conn:
618           /* m==NULL
619            * Check if the connect succeeded
620            */
621           if (so->so_state & SS_NOFDREF) {
622             tp = tcp_close(tp);
623             goto dropwithreset;
624           }
625         cont_input:
626           tcp_template(tp);
627
628           if (optp)
629             tcp_dooptions(tp, (u_char *)optp, optlen, ti);
630
631           if (iss)
632             tp->iss = iss;
633           else
634             tp->iss = tcp_iss;
635           tcp_iss += TCP_ISSINCR/2;
636           tp->irs = ti->ti_seq;
637           tcp_sendseqinit(tp);
638           tcp_rcvseqinit(tp);
639           tp->t_flags |= TF_ACKNOW;
640           tp->t_state = TCPS_SYN_RECEIVED;
641           tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
642           goto trimthenstep6;
643         } /* case TCPS_LISTEN */
644
645         /*
646          * If the state is SYN_SENT:
647          *      if seg contains an ACK, but not for our SYN, drop the input.
648          *      if seg contains a RST, then drop the connection.
649          *      if seg does not contain SYN, then drop it.
650          * Otherwise this is an acceptable SYN segment
651          *      initialize tp->rcv_nxt and tp->irs
652          *      if seg contains ack then advance tp->snd_una
653          *      if SYN has been acked change to ESTABLISHED else SYN_RCVD state
654          *      arrange for segment to be acked (eventually)
655          *      continue processing rest of data/controls, beginning with URG
656          */
657         case TCPS_SYN_SENT:
658                 if ((tiflags & TH_ACK) &&
659                     (SEQ_LEQ(ti->ti_ack, tp->iss) ||
660                      SEQ_GT(ti->ti_ack, tp->snd_max)))
661                         goto dropwithreset;
662
663                 if (tiflags & TH_RST) {
664                         if (tiflags & TH_ACK)
665                                 tp = tcp_drop(tp,0); /* XXX Check t_softerror! */
666                         goto drop;
667                 }
668
669                 if ((tiflags & TH_SYN) == 0)
670                         goto drop;
671                 if (tiflags & TH_ACK) {
672                         tp->snd_una = ti->ti_ack;
673                         if (SEQ_LT(tp->snd_nxt, tp->snd_una))
674                                 tp->snd_nxt = tp->snd_una;
675                 }
676
677                 tp->t_timer[TCPT_REXMT] = 0;
678                 tp->irs = ti->ti_seq;
679                 tcp_rcvseqinit(tp);
680                 tp->t_flags |= TF_ACKNOW;
681                 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
682                         soisfconnected(so);
683                         tp->t_state = TCPS_ESTABLISHED;
684
685                         (void) tcp_reass(tp, (struct tcpiphdr *)0,
686                                 (struct mbuf *)0);
687                         /*
688                          * if we didn't have to retransmit the SYN,
689                          * use its rtt as our initial srtt & rtt var.
690                          */
691                         if (tp->t_rtt)
692                                 tcp_xmit_timer(tp, tp->t_rtt);
693                 } else
694                         tp->t_state = TCPS_SYN_RECEIVED;
695
696 trimthenstep6:
697                 /*
698                  * Advance ti->ti_seq to correspond to first data byte.
699                  * If data, trim to stay within window,
700                  * dropping FIN if necessary.
701                  */
702                 ti->ti_seq++;
703                 if (ti->ti_len > tp->rcv_wnd) {
704                         todrop = ti->ti_len - tp->rcv_wnd;
705                         m_adj(m, -todrop);
706                         ti->ti_len = tp->rcv_wnd;
707                         tiflags &= ~TH_FIN;
708                 }
709                 tp->snd_wl1 = ti->ti_seq - 1;
710                 tp->rcv_up = ti->ti_seq;
711                 goto step6;
712         } /* switch tp->t_state */
713         /*
714          * States other than LISTEN or SYN_SENT.
715          * Check that at least some bytes of segment are within
716          * receive window.  If segment begins before rcv_nxt,
717          * drop leading data (and SYN); if nothing left, just ack.
718          */
719         todrop = tp->rcv_nxt - ti->ti_seq;
720         if (todrop > 0) {
721                 if (tiflags & TH_SYN) {
722                         tiflags &= ~TH_SYN;
723                         ti->ti_seq++;
724                         if (ti->ti_urp > 1)
725                                 ti->ti_urp--;
726                         else
727                                 tiflags &= ~TH_URG;
728                         todrop--;
729                 }
730                 /*
731                  * Following if statement from Stevens, vol. 2, p. 960.
732                  */
733                 if (todrop > ti->ti_len
734                     || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
735                         /*
736                          * Any valid FIN must be to the left of the window.
737                          * At this point the FIN must be a duplicate or out
738                          * of sequence; drop it.
739                          */
740                         tiflags &= ~TH_FIN;
741
742                         /*
743                          * Send an ACK to resynchronize and drop any data.
744                          * But keep on processing for RST or ACK.
745                          */
746                         tp->t_flags |= TF_ACKNOW;
747                         todrop = ti->ti_len;
748                 }
749                 m_adj(m, todrop);
750                 ti->ti_seq += todrop;
751                 ti->ti_len -= todrop;
752                 if (ti->ti_urp > todrop)
753                         ti->ti_urp -= todrop;
754                 else {
755                         tiflags &= ~TH_URG;
756                         ti->ti_urp = 0;
757                 }
758         }
759         /*
760          * If new data are received on a connection after the
761          * user processes are gone, then RST the other end.
762          */
763         if ((so->so_state & SS_NOFDREF) &&
764             tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
765                 tp = tcp_close(tp);
766                 goto dropwithreset;
767         }
768
769         /*
770          * If segment ends after window, drop trailing data
771          * (and PUSH and FIN); if nothing left, just ACK.
772          */
773         todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
774         if (todrop > 0) {
775                 if (todrop >= ti->ti_len) {
776                         /*
777                          * If a new connection request is received
778                          * while in TIME_WAIT, drop the old connection
779                          * and start over if the sequence numbers
780                          * are above the previous ones.
781                          */
782                         if (tiflags & TH_SYN &&
783                             tp->t_state == TCPS_TIME_WAIT &&
784                             SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
785                                 iss = tp->rcv_nxt + TCP_ISSINCR;
786                                 tp = tcp_close(tp);
787                                 goto findso;
788                         }
789                         /*
790                          * If window is closed can only take segments at
791                          * window edge, and have to drop data and PUSH from
792                          * incoming segments.  Continue processing, but
793                          * remember to ack.  Otherwise, drop segment
794                          * and ack.
795                          */
796                         if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
797                                 tp->t_flags |= TF_ACKNOW;
798                         } else {
799                                 goto dropafterack;
800                         }
801                 }
802                 m_adj(m, -todrop);
803                 ti->ti_len -= todrop;
804                 tiflags &= ~(TH_PUSH|TH_FIN);
805         }
806
807         /*
808          * If the RST bit is set examine the state:
809          *    SYN_RECEIVED STATE:
810          *      If passive open, return to LISTEN state.
811          *      If active open, inform user that connection was refused.
812          *    ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
813          *      Inform user that connection was reset, and close tcb.
814          *    CLOSING, LAST_ACK, TIME_WAIT STATES
815          *      Close the tcb.
816          */
817         if (tiflags&TH_RST) switch (tp->t_state) {
818
819         case TCPS_SYN_RECEIVED:
820         case TCPS_ESTABLISHED:
821         case TCPS_FIN_WAIT_1:
822         case TCPS_FIN_WAIT_2:
823         case TCPS_CLOSE_WAIT:
824                 tp->t_state = TCPS_CLOSED;
825                 tp = tcp_close(tp);
826                 goto drop;
827
828         case TCPS_CLOSING:
829         case TCPS_LAST_ACK:
830         case TCPS_TIME_WAIT:
831                 tp = tcp_close(tp);
832                 goto drop;
833         }
834
835         /*
836          * If a SYN is in the window, then this is an
837          * error and we send an RST and drop the connection.
838          */
839         if (tiflags & TH_SYN) {
840                 tp = tcp_drop(tp,0);
841                 goto dropwithreset;
842         }
843
844         /*
845          * If the ACK bit is off we drop the segment and return.
846          */
847         if ((tiflags & TH_ACK) == 0) goto drop;
848
849         /*
850          * Ack processing.
851          */
852         switch (tp->t_state) {
853         /*
854          * In SYN_RECEIVED state if the ack ACKs our SYN then enter
855          * ESTABLISHED state and continue processing, otherwise
856          * send an RST.  una<=ack<=max
857          */
858         case TCPS_SYN_RECEIVED:
859
860                 if (SEQ_GT(tp->snd_una, ti->ti_ack) ||
861                     SEQ_GT(ti->ti_ack, tp->snd_max))
862                         goto dropwithreset;
863                 tp->t_state = TCPS_ESTABLISHED;
864                 /*
865                  * The sent SYN is ack'ed with our sequence number +1
866                  * The first data byte already in the buffer will get
867                  * lost if no correction is made.  This is only needed for
868                  * SS_CTL since the buffer is empty otherwise.
869                  * tp->snd_una++; or:
870                  */
871                 tp->snd_una=ti->ti_ack;
872                 if (so->so_state & SS_CTL) {
873                   /* So tcp_ctl reports the right state */
874                   ret = tcp_ctl(so);
875                   if (ret == 1) {
876                     soisfconnected(so);
877                     so->so_state &= ~SS_CTL;   /* success XXX */
878                   } else if (ret == 2) {
879                     so->so_state &= SS_PERSISTENT_MASK;
880                     so->so_state |= SS_NOFDREF; /* CTL_CMD */
881                   } else {
882                     needoutput = 1;
883                     tp->t_state = TCPS_FIN_WAIT_1;
884                   }
885                 } else {
886                   soisfconnected(so);
887                 }
888
889                 (void) tcp_reass(tp, (struct tcpiphdr *)0, (struct mbuf *)0);
890                 tp->snd_wl1 = ti->ti_seq - 1;
891                 /* Avoid ack processing; snd_una==ti_ack  =>  dup ack */
892                 goto synrx_to_est;
893                 /* fall into ... */
894
895         /*
896          * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
897          * ACKs.  If the ack is in the range
898          *      tp->snd_una < ti->ti_ack <= tp->snd_max
899          * then advance tp->snd_una to ti->ti_ack and drop
900          * data from the retransmission queue.  If this ACK reflects
901          * more up to date window information we update our window information.
902          */
903         case TCPS_ESTABLISHED:
904         case TCPS_FIN_WAIT_1:
905         case TCPS_FIN_WAIT_2:
906         case TCPS_CLOSE_WAIT:
907         case TCPS_CLOSING:
908         case TCPS_LAST_ACK:
909         case TCPS_TIME_WAIT:
910
911                 if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
912                         if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
913                           DEBUG_MISC((dfd," dup ack  m = %lx  so = %lx \n",
914                                       (long )m, (long )so));
915                                 /*
916                                  * If we have outstanding data (other than
917                                  * a window probe), this is a completely
918                                  * duplicate ack (ie, window info didn't
919                                  * change), the ack is the biggest we've
920                                  * seen and we've seen exactly our rexmt
921                                  * threshold of them, assume a packet
922                                  * has been dropped and retransmit it.
923                                  * Kludge snd_nxt & the congestion
924                                  * window so we send only this one
925                                  * packet.
926                                  *
927                                  * We know we're losing at the current
928                                  * window size so do congestion avoidance
929                                  * (set ssthresh to half the current window
930                                  * and pull our congestion window back to
931                                  * the new ssthresh).
932                                  *
933                                  * Dup acks mean that packets have left the
934                                  * network (they're now cached at the receiver)
935                                  * so bump cwnd by the amount in the receiver
936                                  * to keep a constant cwnd packets in the
937                                  * network.
938                                  */
939                                 if (tp->t_timer[TCPT_REXMT] == 0 ||
940                                     ti->ti_ack != tp->snd_una)
941                                         tp->t_dupacks = 0;
942                                 else if (++tp->t_dupacks == TCPREXMTTHRESH) {
943                                         tcp_seq onxt = tp->snd_nxt;
944                                         u_int win =
945                                             min(tp->snd_wnd, tp->snd_cwnd) / 2 /
946                                                 tp->t_maxseg;
947
948                                         if (win < 2)
949                                                 win = 2;
950                                         tp->snd_ssthresh = win * tp->t_maxseg;
951                                         tp->t_timer[TCPT_REXMT] = 0;
952                                         tp->t_rtt = 0;
953                                         tp->snd_nxt = ti->ti_ack;
954                                         tp->snd_cwnd = tp->t_maxseg;
955                                         (void) tcp_output(tp);
956                                         tp->snd_cwnd = tp->snd_ssthresh +
957                                                tp->t_maxseg * tp->t_dupacks;
958                                         if (SEQ_GT(onxt, tp->snd_nxt))
959                                                 tp->snd_nxt = onxt;
960                                         goto drop;
961                                 } else if (tp->t_dupacks > TCPREXMTTHRESH) {
962                                         tp->snd_cwnd += tp->t_maxseg;
963                                         (void) tcp_output(tp);
964                                         goto drop;
965                                 }
966                         } else
967                                 tp->t_dupacks = 0;
968                         break;
969                 }
970         synrx_to_est:
971                 /*
972                  * If the congestion window was inflated to account
973                  * for the other side's cached packets, retract it.
974                  */
975                 if (tp->t_dupacks > TCPREXMTTHRESH &&
976                     tp->snd_cwnd > tp->snd_ssthresh)
977                         tp->snd_cwnd = tp->snd_ssthresh;
978                 tp->t_dupacks = 0;
979                 if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
980                         goto dropafterack;
981                 }
982                 acked = ti->ti_ack - tp->snd_una;
983
984                 /*
985                  * If transmit timer is running and timed sequence
986                  * number was acked, update smoothed round trip time.
987                  * Since we now have an rtt measurement, cancel the
988                  * timer backoff (cf., Phil Karn's retransmit alg.).
989                  * Recompute the initial retransmit timer.
990                  */
991                 if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
992                         tcp_xmit_timer(tp,tp->t_rtt);
993
994                 /*
995                  * If all outstanding data is acked, stop retransmit
996                  * timer and remember to restart (more output or persist).
997                  * If there is more data to be acked, restart retransmit
998                  * timer, using current (possibly backed-off) value.
999                  */
1000                 if (ti->ti_ack == tp->snd_max) {
1001                         tp->t_timer[TCPT_REXMT] = 0;
1002                         needoutput = 1;
1003                 } else if (tp->t_timer[TCPT_PERSIST] == 0)
1004                         tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1005                 /*
1006                  * When new data is acked, open the congestion window.
1007                  * If the window gives us less than ssthresh packets
1008                  * in flight, open exponentially (maxseg per packet).
1009                  * Otherwise open linearly: maxseg per window
1010                  * (maxseg^2 / cwnd per packet).
1011                  */
1012                 {
1013                   register u_int cw = tp->snd_cwnd;
1014                   register u_int incr = tp->t_maxseg;
1015
1016                   if (cw > tp->snd_ssthresh)
1017                     incr = incr * incr / cw;
1018                   tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1019                 }
1020                 if (acked > so->so_snd.sb_cc) {
1021                         tp->snd_wnd -= so->so_snd.sb_cc;
1022                         sbdrop(&so->so_snd, (int )so->so_snd.sb_cc);
1023                         ourfinisacked = 1;
1024                 } else {
1025                         sbdrop(&so->so_snd, acked);
1026                         tp->snd_wnd -= acked;
1027                         ourfinisacked = 0;
1028                 }
1029                 tp->snd_una = ti->ti_ack;
1030                 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1031                         tp->snd_nxt = tp->snd_una;
1032
1033                 switch (tp->t_state) {
1034
1035                 /*
1036                  * In FIN_WAIT_1 STATE in addition to the processing
1037                  * for the ESTABLISHED state if our FIN is now acknowledged
1038                  * then enter FIN_WAIT_2.
1039                  */
1040                 case TCPS_FIN_WAIT_1:
1041                         if (ourfinisacked) {
1042                                 /*
1043                                  * If we can't receive any more
1044                                  * data, then closing user can proceed.
1045                                  * Starting the timer is contrary to the
1046                                  * specification, but if we don't get a FIN
1047                                  * we'll hang forever.
1048                                  */
1049                                 if (so->so_state & SS_FCANTRCVMORE) {
1050                                         tp->t_timer[TCPT_2MSL] = TCP_MAXIDLE;
1051                                 }
1052                                 tp->t_state = TCPS_FIN_WAIT_2;
1053                         }
1054                         break;
1055
1056                 /*
1057                  * In CLOSING STATE in addition to the processing for
1058                  * the ESTABLISHED state if the ACK acknowledges our FIN
1059                  * then enter the TIME-WAIT state, otherwise ignore
1060                  * the segment.
1061                  */
1062                 case TCPS_CLOSING:
1063                         if (ourfinisacked) {
1064                                 tp->t_state = TCPS_TIME_WAIT;
1065                                 tcp_canceltimers(tp);
1066                                 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1067                         }
1068                         break;
1069
1070                 /*
1071                  * In LAST_ACK, we may still be waiting for data to drain
1072                  * and/or to be acked, as well as for the ack of our FIN.
1073                  * If our FIN is now acknowledged, delete the TCB,
1074                  * enter the closed state and return.
1075                  */
1076                 case TCPS_LAST_ACK:
1077                         if (ourfinisacked) {
1078                                 tp = tcp_close(tp);
1079                                 goto drop;
1080                         }
1081                         break;
1082
1083                 /*
1084                  * In TIME_WAIT state the only thing that should arrive
1085                  * is a retransmission of the remote FIN.  Acknowledge
1086                  * it and restart the finack timer.
1087                  */
1088                 case TCPS_TIME_WAIT:
1089                         tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1090                         goto dropafterack;
1091                 }
1092         } /* switch(tp->t_state) */
1093
1094 step6:
1095         /*
1096          * Update window information.
1097          * Don't look at window if no ACK: TAC's send garbage on first SYN.
1098          */
1099         if ((tiflags & TH_ACK) &&
1100             (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1101             (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1102             (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1103                 tp->snd_wnd = tiwin;
1104                 tp->snd_wl1 = ti->ti_seq;
1105                 tp->snd_wl2 = ti->ti_ack;
1106                 if (tp->snd_wnd > tp->max_sndwnd)
1107                         tp->max_sndwnd = tp->snd_wnd;
1108                 needoutput = 1;
1109         }
1110
1111         /*
1112          * Process segments with URG.
1113          */
1114         if ((tiflags & TH_URG) && ti->ti_urp &&
1115             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1116                 /*
1117                  * This is a kludge, but if we receive and accept
1118                  * random urgent pointers, we'll crash in
1119                  * soreceive.  It's hard to imagine someone
1120                  * actually wanting to send this much urgent data.
1121                  */
1122                 if (ti->ti_urp + so->so_rcv.sb_cc > so->so_rcv.sb_datalen) {
1123                         ti->ti_urp = 0;
1124                         tiflags &= ~TH_URG;
1125                         goto dodata;
1126                 }
1127                 /*
1128                  * If this segment advances the known urgent pointer,
1129                  * then mark the data stream.  This should not happen
1130                  * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1131                  * a FIN has been received from the remote side.
1132                  * In these states we ignore the URG.
1133                  *
1134                  * According to RFC961 (Assigned Protocols),
1135                  * the urgent pointer points to the last octet
1136                  * of urgent data.  We continue, however,
1137                  * to consider it to indicate the first octet
1138                  * of data past the urgent section as the original
1139                  * spec states (in one of two places).
1140                  */
1141                 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1142                         tp->rcv_up = ti->ti_seq + ti->ti_urp;
1143                         so->so_urgc =  so->so_rcv.sb_cc +
1144                                 (tp->rcv_up - tp->rcv_nxt); /* -1; */
1145                         tp->rcv_up = ti->ti_seq + ti->ti_urp;
1146
1147                 }
1148         } else
1149                 /*
1150                  * If no out of band data is expected,
1151                  * pull receive urgent pointer along
1152                  * with the receive window.
1153                  */
1154                 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1155                         tp->rcv_up = tp->rcv_nxt;
1156 dodata:
1157
1158         /*
1159          * Process the segment text, merging it into the TCP sequencing queue,
1160          * and arranging for acknowledgment of receipt if necessary.
1161          * This process logically involves adjusting tp->rcv_wnd as data
1162          * is presented to the user (this happens in tcp_usrreq.c,
1163          * case PRU_RCVD).  If a FIN has already been received on this
1164          * connection then we just ignore the text.
1165          */
1166         if ((ti->ti_len || (tiflags&TH_FIN)) &&
1167             TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1168                 TCP_REASS(tp, ti, m, so, tiflags);
1169                 /*
1170                  * Note the amount of data that peer has sent into
1171                  * our window, in order to estimate the sender's
1172                  * buffer size.
1173                  */
1174                 len = so->so_rcv.sb_datalen - (tp->rcv_adv - tp->rcv_nxt);
1175         } else {
1176                 m_free(m);
1177                 tiflags &= ~TH_FIN;
1178         }
1179
1180         /*
1181          * If FIN is received ACK the FIN and let the user know
1182          * that the connection is closing.
1183          */
1184         if (tiflags & TH_FIN) {
1185                 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1186                         /*
1187                          * If we receive a FIN we can't send more data,
1188                          * set it SS_FDRAIN
1189                          * Shutdown the socket if there is no rx data in the
1190                          * buffer.
1191                          * soread() is called on completion of shutdown() and
1192                          * will got to TCPS_LAST_ACK, and use tcp_output()
1193                          * to send the FIN.
1194                          */
1195                         sofwdrain(so);
1196
1197                         tp->t_flags |= TF_ACKNOW;
1198                         tp->rcv_nxt++;
1199                 }
1200                 switch (tp->t_state) {
1201
1202                 /*
1203                  * In SYN_RECEIVED and ESTABLISHED STATES
1204                  * enter the CLOSE_WAIT state.
1205                  */
1206                 case TCPS_SYN_RECEIVED:
1207                 case TCPS_ESTABLISHED:
1208                   if(so->so_emu == EMU_CTL)        /* no shutdown on socket */
1209                     tp->t_state = TCPS_LAST_ACK;
1210                   else
1211                     tp->t_state = TCPS_CLOSE_WAIT;
1212                   break;
1213
1214                 /*
1215                  * If still in FIN_WAIT_1 STATE FIN has not been acked so
1216                  * enter the CLOSING state.
1217                  */
1218                 case TCPS_FIN_WAIT_1:
1219                         tp->t_state = TCPS_CLOSING;
1220                         break;
1221
1222                 /*
1223                  * In FIN_WAIT_2 state enter the TIME_WAIT state,
1224                  * starting the time-wait timer, turning off the other
1225                  * standard timers.
1226                  */
1227                 case TCPS_FIN_WAIT_2:
1228                         tp->t_state = TCPS_TIME_WAIT;
1229                         tcp_canceltimers(tp);
1230                         tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1231                         break;
1232
1233                 /*
1234                  * In TIME_WAIT state restart the 2 MSL time_wait timer.
1235                  */
1236                 case TCPS_TIME_WAIT:
1237                         tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1238                         break;
1239                 }
1240         }
1241
1242         /*
1243          * If this is a small packet, then ACK now - with Nagel
1244          *      congestion avoidance sender won't send more until
1245          *      he gets an ACK.
1246          *
1247          * See above.
1248          */
1249         if (ti->ti_len && (unsigned)ti->ti_len <= 5 &&
1250             ((struct tcpiphdr_2 *)ti)->first_char == (char)27) {
1251                 tp->t_flags |= TF_ACKNOW;
1252         }
1253
1254         /*
1255          * Return any desired output.
1256          */
1257         if (needoutput || (tp->t_flags & TF_ACKNOW)) {
1258                 (void) tcp_output(tp);
1259         }
1260         return;
1261
1262 dropafterack:
1263         /*
1264          * Generate an ACK dropping incoming segment if it occupies
1265          * sequence space, where the ACK reflects our state.
1266          */
1267         if (tiflags & TH_RST)
1268                 goto drop;
1269         m_freem(m);
1270         tp->t_flags |= TF_ACKNOW;
1271         (void) tcp_output(tp);
1272         return;
1273
1274 dropwithreset:
1275         /* reuses m if m!=NULL, m_free() unnecessary */
1276         if (tiflags & TH_ACK)
1277                 tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1278         else {
1279                 if (tiflags & TH_SYN) ti->ti_len++;
1280                 tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1281                     TH_RST|TH_ACK);
1282         }
1283
1284         return;
1285
1286 drop:
1287         /*
1288          * Drop space held by incoming segment and return.
1289          */
1290         m_free(m);
1291
1292         return;
1293 }
1294
1295 static void
1296 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcpiphdr *ti)
1297 {
1298         u_int16_t mss;
1299         int opt, optlen;
1300
1301         DEBUG_CALL("tcp_dooptions");
1302         DEBUG_ARGS((dfd," tp = %lx  cnt=%i \n", (long )tp, cnt));
1303
1304         for (; cnt > 0; cnt -= optlen, cp += optlen) {
1305                 opt = cp[0];
1306                 if (opt == TCPOPT_EOL)
1307                         break;
1308                 if (opt == TCPOPT_NOP)
1309                         optlen = 1;
1310                 else {
1311                         optlen = cp[1];
1312                         if (optlen <= 0)
1313                                 break;
1314                 }
1315                 switch (opt) {
1316
1317                 default:
1318                         continue;
1319
1320                 case TCPOPT_MAXSEG:
1321                         if (optlen != TCPOLEN_MAXSEG)
1322                                 continue;
1323                         if (!(ti->ti_flags & TH_SYN))
1324                                 continue;
1325                         memcpy((char *) &mss, (char *) cp + 2, sizeof(mss));
1326                         NTOHS(mss);
1327                         (void) tcp_mss(tp, mss);        /* sets t_maxseg */
1328                         break;
1329                 }
1330         }
1331 }
1332
1333
1334 /*
1335  * Pull out of band byte out of a segment so
1336  * it doesn't appear in the user's data queue.
1337  * It is still reflected in the segment length for
1338  * sequencing purposes.
1339  */
1340
1341 #ifdef notdef
1342
1343 void
1344 tcp_pulloutofband(so, ti, m)
1345         struct socket *so;
1346         struct tcpiphdr *ti;
1347         register struct mbuf *m;
1348 {
1349         int cnt = ti->ti_urp - 1;
1350
1351         while (cnt >= 0) {
1352                 if (m->m_len > cnt) {
1353                         char *cp = mtod(m, caddr_t) + cnt;
1354                         struct tcpcb *tp = sototcpcb(so);
1355
1356                         tp->t_iobc = *cp;
1357                         tp->t_oobflags |= TCPOOB_HAVEDATA;
1358                         memcpy(sp, cp+1, (unsigned)(m->m_len - cnt - 1));
1359                         m->m_len--;
1360                         return;
1361                 }
1362                 cnt -= m->m_len;
1363                 m = m->m_next; /* XXX WRONG! Fix it! */
1364                 if (m == 0)
1365                         break;
1366         }
1367         panic("tcp_pulloutofband");
1368 }
1369
1370 #endif /* notdef */
1371
1372 /*
1373  * Collect new round-trip time estimate
1374  * and update averages and current timeout.
1375  */
1376
1377 static void
1378 tcp_xmit_timer(register struct tcpcb *tp, int rtt)
1379 {
1380         register short delta;
1381
1382         DEBUG_CALL("tcp_xmit_timer");
1383         DEBUG_ARG("tp = %lx", (long)tp);
1384         DEBUG_ARG("rtt = %d", rtt);
1385
1386         if (tp->t_srtt != 0) {
1387                 /*
1388                  * srtt is stored as fixed point with 3 bits after the
1389                  * binary point (i.e., scaled by 8).  The following magic
1390                  * is equivalent to the smoothing algorithm in rfc793 with
1391                  * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1392                  * point).  Adjust rtt to origin 0.
1393                  */
1394                 delta = rtt - 1 - (tp->t_srtt >> TCP_RTT_SHIFT);
1395                 if ((tp->t_srtt += delta) <= 0)
1396                         tp->t_srtt = 1;
1397                 /*
1398                  * We accumulate a smoothed rtt variance (actually, a
1399                  * smoothed mean difference), then set the retransmit
1400                  * timer to smoothed rtt + 4 times the smoothed variance.
1401                  * rttvar is stored as fixed point with 2 bits after the
1402                  * binary point (scaled by 4).  The following is
1403                  * equivalent to rfc793 smoothing with an alpha of .75
1404                  * (rttvar = rttvar*3/4 + |delta| / 4).  This replaces
1405                  * rfc793's wired-in beta.
1406                  */
1407                 if (delta < 0)
1408                         delta = -delta;
1409                 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
1410                 if ((tp->t_rttvar += delta) <= 0)
1411                         tp->t_rttvar = 1;
1412         } else {
1413                 /*
1414                  * No rtt measurement yet - use the unsmoothed rtt.
1415                  * Set the variance to half the rtt (so our first
1416                  * retransmit happens at 3*rtt).
1417                  */
1418                 tp->t_srtt = rtt << TCP_RTT_SHIFT;
1419                 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
1420         }
1421         tp->t_rtt = 0;
1422         tp->t_rxtshift = 0;
1423
1424         /*
1425          * the retransmit should happen at rtt + 4 * rttvar.
1426          * Because of the way we do the smoothing, srtt and rttvar
1427          * will each average +1/2 tick of bias.  When we compute
1428          * the retransmit timer, we want 1/2 tick of rounding and
1429          * 1 extra tick because of +-1/2 tick uncertainty in the
1430          * firing of the timer.  The bias will give us exactly the
1431          * 1.5 tick we need.  But, because the bias is
1432          * statistical, we have to test that we don't drop below
1433          * the minimum feasible timer (which is 2 ticks).
1434          */
1435         TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
1436             (short)tp->t_rttmin, TCPTV_REXMTMAX); /* XXX */
1437
1438         /*
1439          * We received an ack for a packet that wasn't retransmitted;
1440          * it is probably safe to discard any error indications we've
1441          * received recently.  This isn't quite right, but close enough
1442          * for now (a route might have failed after we sent a segment,
1443          * and the return path might not be symmetrical).
1444          */
1445         tp->t_softerror = 0;
1446 }
1447
1448 /*
1449  * Determine a reasonable value for maxseg size.
1450  * If the route is known, check route for mtu.
1451  * If none, use an mss that can be handled on the outgoing
1452  * interface without forcing IP to fragment; if bigger than
1453  * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
1454  * to utilize large mbufs.  If no route is found, route has no mtu,
1455  * or the destination isn't local, use a default, hopefully conservative
1456  * size (usually 512 or the default IP max size, but no more than the mtu
1457  * of the interface), as we can't discover anything about intervening
1458  * gateways or networks.  We also initialize the congestion/slow start
1459  * window to be a single segment if the destination isn't local.
1460  * While looking at the routing entry, we also initialize other path-dependent
1461  * parameters from pre-set or cached values in the routing entry.
1462  */
1463
1464 int
1465 tcp_mss(struct tcpcb *tp, u_int offer)
1466 {
1467         struct socket *so = tp->t_socket;
1468         int mss;
1469
1470         DEBUG_CALL("tcp_mss");
1471         DEBUG_ARG("tp = %lx", (long)tp);
1472         DEBUG_ARG("offer = %d", offer);
1473
1474         mss = min(IF_MTU, IF_MRU) - sizeof(struct tcpiphdr);
1475         if (offer)
1476                 mss = min(mss, offer);
1477         mss = max(mss, 32);
1478         if (mss < tp->t_maxseg || offer != 0)
1479            tp->t_maxseg = mss;
1480
1481         tp->snd_cwnd = mss;
1482
1483         sbreserve(&so->so_snd, TCP_SNDSPACE + ((TCP_SNDSPACE % mss) ?
1484                                                (mss - (TCP_SNDSPACE % mss)) :
1485                                                0));
1486         sbreserve(&so->so_rcv, TCP_RCVSPACE + ((TCP_RCVSPACE % mss) ?
1487                                                (mss - (TCP_RCVSPACE % mss)) :
1488                                                0));
1489
1490         DEBUG_MISC((dfd, " returning mss = %d\n", mss));
1491
1492         return mss;
1493 }