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