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