Initial import from FreeBSD RELENG_4:
[dragonfly.git] / sys / netinet / tcp_input.c
CommitLineData
984263bc
MD
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
34 * $FreeBSD: src/sys/netinet/tcp_input.c,v 1.107.2.38 2003/05/21 04:46:41 cjc Exp $
35 */
36
37#include "opt_ipfw.h" /* for ipfw_fwd */
38#include "opt_inet6.h"
39#include "opt_ipsec.h"
40#include "opt_tcpdebug.h"
41#include "opt_tcp_input.h"
42
43#include <sys/param.h>
44#include <sys/systm.h>
45#include <sys/kernel.h>
46#include <sys/sysctl.h>
47#include <sys/malloc.h>
48#include <sys/mbuf.h>
49#include <sys/proc.h> /* for proc0 declaration */
50#include <sys/protosw.h>
51#include <sys/socket.h>
52#include <sys/socketvar.h>
53#include <sys/syslog.h>
54
55#include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
56
57#include <net/if.h>
58#include <net/route.h>
59
60#include <netinet/in.h>
61#include <netinet/in_systm.h>
62#include <netinet/ip.h>
63#include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
64#include <netinet/in_var.h>
65#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
66#include <netinet/in_pcb.h>
67#include <netinet/ip_var.h>
68#include <netinet/ip6.h>
69#include <netinet/icmp6.h>
70#include <netinet6/nd6.h>
71#include <netinet6/ip6_var.h>
72#include <netinet6/in6_pcb.h>
73#include <netinet/tcp.h>
74#include <netinet/tcp_fsm.h>
75#include <netinet/tcp_seq.h>
76#include <netinet/tcp_timer.h>
77#include <netinet/tcp_var.h>
78#include <netinet6/tcp6_var.h>
79#include <netinet/tcpip.h>
80#ifdef TCPDEBUG
81#include <netinet/tcp_debug.h>
82
83u_char tcp_saveipgen[40]; /* the size must be of max ip header, now IPv6 */
84struct tcphdr tcp_savetcp;
85#endif /* TCPDEBUG */
86
87#ifdef FAST_IPSEC
88#include <netipsec/ipsec.h>
89#include <netipsec/ipsec6.h>
90#endif
91
92#ifdef IPSEC
93#include <netinet6/ipsec.h>
94#include <netinet6/ipsec6.h>
95#include <netkey/key.h>
96#endif /*IPSEC*/
97
98#include <machine/in_cksum.h>
99
100MALLOC_DEFINE(M_TSEGQ, "tseg_qent", "TCP segment queue entry");
101
102static const int tcprexmtthresh = 3;
103tcp_cc tcp_ccgen;
104
105struct tcpstat tcpstat;
106SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
107 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
108
109static int log_in_vain = 0;
110SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
111 &log_in_vain, 0, "Log all incoming TCP connections");
112
113static int blackhole = 0;
114SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
115 &blackhole, 0, "Do not send RST when dropping refused connections");
116
117int tcp_delack_enabled = 1;
118SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
119 &tcp_delack_enabled, 0,
120 "Delay ACK to try and piggyback it onto a data packet");
121
122#ifdef TCP_DROP_SYNFIN
123static int drop_synfin = 0;
124SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
125 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
126#endif
127
128struct inpcbhead tcb;
129#define tcb6 tcb /* for KAME src sync over BSD*'s */
130struct inpcbinfo tcbinfo;
131
132static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
133static void tcp_pulloutofband(struct socket *,
134 struct tcphdr *, struct mbuf *, int);
135static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
136 struct mbuf *);
137static void tcp_xmit_timer(struct tcpcb *, int);
138static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
139
140/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
141#ifdef INET6
142#define ND6_HINT(tp) \
143do { \
144 if ((tp) && (tp)->t_inpcb && \
145 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0 && \
146 (tp)->t_inpcb->in6p_route.ro_rt) \
147 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL, 0); \
148} while (0)
149#else
150#define ND6_HINT(tp)
151#endif
152
153/*
154 * Indicate whether this ack should be delayed. We can delay the ack if
155 * - delayed acks are enabled and
156 * - there is no delayed ack timer in progress and
157 * - our last ack wasn't a 0-sized window. We never want to delay
158 * the ack that opens up a 0-sized window.
159 */
160#define DELAY_ACK(tp) \
161 (tcp_delack_enabled && !callout_pending(tp->tt_delack) && \
162 (tp->t_flags & TF_RXWIN0SENT) == 0)
163
164static int
165tcp_reass(tp, th, tlenp, m)
166 register struct tcpcb *tp;
167 register struct tcphdr *th;
168 int *tlenp;
169 struct mbuf *m;
170{
171 struct tseg_qent *q;
172 struct tseg_qent *p = NULL;
173 struct tseg_qent *nq;
174 struct tseg_qent *te;
175 struct socket *so = tp->t_inpcb->inp_socket;
176 int flags;
177
178 /*
179 * Call with th==0 after become established to
180 * force pre-ESTABLISHED data up to user socket.
181 */
182 if (th == 0)
183 goto present;
184
185 /* Allocate a new queue entry. If we can't, just drop the pkt. XXX */
186 MALLOC(te, struct tseg_qent *, sizeof(struct tseg_qent), M_TSEGQ,
187 M_NOWAIT);
188 if (te == NULL) {
189 tcpstat.tcps_rcvmemdrop++;
190 m_freem(m);
191 return (0);
192 }
193
194 /*
195 * Find a segment which begins after this one does.
196 */
197 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
198 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
199 break;
200 p = q;
201 }
202
203 /*
204 * If there is a preceding segment, it may provide some of
205 * our data already. If so, drop the data from the incoming
206 * segment. If it provides all of our data, drop us.
207 */
208 if (p != NULL) {
209 register int i;
210 /* conversion to int (in i) handles seq wraparound */
211 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
212 if (i > 0) {
213 if (i >= *tlenp) {
214 tcpstat.tcps_rcvduppack++;
215 tcpstat.tcps_rcvdupbyte += *tlenp;
216 m_freem(m);
217 free(te, M_TSEGQ);
218 /*
219 * Try to present any queued data
220 * at the left window edge to the user.
221 * This is needed after the 3-WHS
222 * completes.
223 */
224 goto present; /* ??? */
225 }
226 m_adj(m, i);
227 *tlenp -= i;
228 th->th_seq += i;
229 }
230 }
231 tcpstat.tcps_rcvoopack++;
232 tcpstat.tcps_rcvoobyte += *tlenp;
233
234 /*
235 * While we overlap succeeding segments trim them or,
236 * if they are completely covered, dequeue them.
237 */
238 while (q) {
239 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
240 if (i <= 0)
241 break;
242 if (i < q->tqe_len) {
243 q->tqe_th->th_seq += i;
244 q->tqe_len -= i;
245 m_adj(q->tqe_m, i);
246 break;
247 }
248
249 nq = LIST_NEXT(q, tqe_q);
250 LIST_REMOVE(q, tqe_q);
251 m_freem(q->tqe_m);
252 free(q, M_TSEGQ);
253 q = nq;
254 }
255
256 /* Insert the new segment queue entry into place. */
257 te->tqe_m = m;
258 te->tqe_th = th;
259 te->tqe_len = *tlenp;
260
261 if (p == NULL) {
262 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
263 } else {
264 LIST_INSERT_AFTER(p, te, tqe_q);
265 }
266
267present:
268 /*
269 * Present data to user, advancing rcv_nxt through
270 * completed sequence space.
271 */
272 if (!TCPS_HAVEESTABLISHED(tp->t_state))
273 return (0);
274 q = LIST_FIRST(&tp->t_segq);
275 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
276 return (0);
277 do {
278 tp->rcv_nxt += q->tqe_len;
279 flags = q->tqe_th->th_flags & TH_FIN;
280 nq = LIST_NEXT(q, tqe_q);
281 LIST_REMOVE(q, tqe_q);
282 if (so->so_state & SS_CANTRCVMORE)
283 m_freem(q->tqe_m);
284 else
285 sbappend(&so->so_rcv, q->tqe_m);
286 free(q, M_TSEGQ);
287 q = nq;
288 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
289 ND6_HINT(tp);
290 sorwakeup(so);
291 return (flags);
292}
293
294/*
295 * TCP input routine, follows pages 65-76 of the
296 * protocol specification dated September, 1981 very closely.
297 */
298#ifdef INET6
299int
300tcp6_input(mp, offp, proto)
301 struct mbuf **mp;
302 int *offp, proto;
303{
304 register struct mbuf *m = *mp;
305 struct in6_ifaddr *ia6;
306
307 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
308
309 /*
310 * draft-itojun-ipv6-tcp-to-anycast
311 * better place to put this in?
312 */
313 ia6 = ip6_getdstifaddr(m);
314 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
315 struct ip6_hdr *ip6;
316
317 ip6 = mtod(m, struct ip6_hdr *);
318 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
319 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
320 return IPPROTO_DONE;
321 }
322
323 tcp_input(m, *offp, proto);
324 return IPPROTO_DONE;
325}
326#endif
327
328void
329tcp_input(m, off0, proto)
330 register struct mbuf *m;
331 int off0, proto;
332{
333 register struct tcphdr *th;
334 register struct ip *ip = NULL;
335 register struct ipovly *ipov;
336 register struct inpcb *inp = NULL;
337 u_char *optp = NULL;
338 int optlen = 0;
339 int len, tlen, off;
340 int drop_hdrlen;
341 register struct tcpcb *tp = NULL;
342 register int thflags;
343 struct socket *so = 0;
344 int todrop, acked, ourfinisacked, needoutput = 0;
345 u_long tiwin;
346 struct tcpopt to; /* options in this segment */
347 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
348 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
349 struct sockaddr_in *next_hop = NULL;
350 int rstreason; /* For badport_bandlim accounting purposes */
351 struct ip6_hdr *ip6 = NULL;
352#ifdef INET6
353 int isipv6;
354#else
355 const int isipv6 = 0;
356#endif
357#ifdef TCPDEBUG
358 short ostate = 0;
359#endif
360
361 /* Grab info from MT_TAG mbufs prepended to the chain. */
362 for (;m && m->m_type == MT_TAG; m = m->m_next) {
363 if (m->_m_tag_id == PACKET_TAG_IPFORWARD)
364 next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
365 }
366#ifdef INET6
367 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
368#endif
369 bzero((char *)&to, sizeof(to));
370
371 tcpstat.tcps_rcvtotal++;
372
373 if (isipv6) {
374 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
375 ip6 = mtod(m, struct ip6_hdr *);
376 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
377 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
378 tcpstat.tcps_rcvbadsum++;
379 goto drop;
380 }
381 th = (struct tcphdr *)((caddr_t)ip6 + off0);
382
383 /*
384 * Be proactive about unspecified IPv6 address in source.
385 * As we use all-zero to indicate unbounded/unconnected pcb,
386 * unspecified IPv6 address can be used to confuse us.
387 *
388 * Note that packets with unspecified IPv6 destination is
389 * already dropped in ip6_input.
390 */
391 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
392 /* XXX stat */
393 goto drop;
394 }
395 } else {
396 /*
397 * Get IP and TCP header together in first mbuf.
398 * Note: IP leaves IP header in first mbuf.
399 */
400 if (off0 > sizeof(struct ip)) {
401 ip_stripoptions(m, (struct mbuf *)0);
402 off0 = sizeof(struct ip);
403 }
404 if (m->m_len < sizeof(struct tcpiphdr)) {
405 if ((m = m_pullup(m, sizeof(struct tcpiphdr))) == 0) {
406 tcpstat.tcps_rcvshort++;
407 return;
408 }
409 }
410 ip = mtod(m, struct ip *);
411 ipov = (struct ipovly *)ip;
412 th = (struct tcphdr *)((caddr_t)ip + off0);
413 tlen = ip->ip_len;
414
415 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
416 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
417 th->th_sum = m->m_pkthdr.csum_data;
418 else
419 th->th_sum = in_pseudo(ip->ip_src.s_addr,
420 ip->ip_dst.s_addr,
421 htonl(m->m_pkthdr.csum_data +
422 ip->ip_len +
423 IPPROTO_TCP));
424 th->th_sum ^= 0xffff;
425 } else {
426 /*
427 * Checksum extended TCP header and data.
428 */
429 len = sizeof(struct ip) + tlen;
430 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
431 ipov->ih_len = (u_short)tlen;
432 ipov->ih_len = htons(ipov->ih_len);
433 th->th_sum = in_cksum(m, len);
434 }
435 if (th->th_sum) {
436 tcpstat.tcps_rcvbadsum++;
437 goto drop;
438 }
439#ifdef INET6
440 /* Re-initialization for later version check */
441 ip->ip_v = IPVERSION;
442#endif
443 }
444
445 /*
446 * Check that TCP offset makes sense,
447 * pull out TCP options and adjust length. XXX
448 */
449 off = th->th_off << 2;
450 if (off < sizeof(struct tcphdr) || off > tlen) {
451 tcpstat.tcps_rcvbadoff++;
452 goto drop;
453 }
454 tlen -= off; /* tlen is used instead of ti->ti_len */
455 if (off > sizeof(struct tcphdr)) {
456 if (isipv6) {
457 IP6_EXTHDR_CHECK(m, off0, off, );
458 ip6 = mtod(m, struct ip6_hdr *);
459 th = (struct tcphdr *)((caddr_t)ip6 + off0);
460 } else {
461 if (m->m_len < sizeof(struct ip) + off) {
462 if ((m = m_pullup(m, sizeof(struct ip) + off))
463 == 0) {
464 tcpstat.tcps_rcvshort++;
465 return;
466 }
467 ip = mtod(m, struct ip *);
468 ipov = (struct ipovly *)ip;
469 th = (struct tcphdr *)((caddr_t)ip + off0);
470 }
471 }
472 optlen = off - sizeof(struct tcphdr);
473 optp = (u_char *)(th + 1);
474 }
475 thflags = th->th_flags;
476
477#ifdef TCP_DROP_SYNFIN
478 /*
479 * If the drop_synfin option is enabled, drop all packets with
480 * both the SYN and FIN bits set. This prevents e.g. nmap from
481 * identifying the TCP/IP stack.
482 *
483 * This is a violation of the TCP specification.
484 */
485 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
486 goto drop;
487#endif
488
489 /*
490 * Convert TCP protocol specific fields to host format.
491 */
492 th->th_seq = ntohl(th->th_seq);
493 th->th_ack = ntohl(th->th_ack);
494 th->th_win = ntohs(th->th_win);
495 th->th_urp = ntohs(th->th_urp);
496
497 /*
498 * Delay droping TCP, IP headers, IPv6 ext headers, and TCP options,
499 * until after ip6_savecontrol() is called and before other functions
500 * which don't want those proto headers.
501 * Because ip6_savecontrol() is going to parse the mbuf to
502 * search for data to be passed up to user-land, it wants mbuf
503 * parameters to be unchanged.
504 * XXX: the call of ip6_savecontrol() has been obsoleted based on
505 * latest version of the advanced API (20020110).
506 */
507 drop_hdrlen = off0 + off;
508
509 /*
510 * Locate pcb for segment.
511 */
512findpcb:
513 /* IPFIREWALL_FORWARD section */
514 if (next_hop != NULL && isipv6 == 0) { /* IPv6 support is not yet */
515 /*
516 * Transparently forwarded. Pretend to be the destination.
517 * already got one like this?
518 */
519 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
520 ip->ip_dst, th->th_dport,
521 0, m->m_pkthdr.rcvif);
522 if (!inp) {
523 /* It's new. Try find the ambushing socket. */
524 inp = in_pcblookup_hash(&tcbinfo,
525 ip->ip_src, th->th_sport,
526 next_hop->sin_addr,
527 next_hop->sin_port ?
528 ntohs(next_hop->sin_port) :
529 th->th_dport,
530 1, m->m_pkthdr.rcvif);
531 }
532 } else {
533 if (isipv6)
534 inp = in6_pcblookup_hash(&tcbinfo,
535 &ip6->ip6_src, th->th_sport,
536 &ip6->ip6_dst, th->th_dport,
537 1, m->m_pkthdr.rcvif);
538 else
539 inp = in_pcblookup_hash(&tcbinfo,
540 ip->ip_src, th->th_sport,
541 ip->ip_dst, th->th_dport,
542 1, m->m_pkthdr.rcvif);
543 }
544
545#ifdef IPSEC
546 if (isipv6) {
547 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
548 ipsec6stat.in_polvio++;
549 goto drop;
550 }
551 } else {
552 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
553 ipsecstat.in_polvio++;
554 goto drop;
555 }
556 }
557#endif
558#ifdef FAST_IPSEC
559 if (isipv6) {
560 if (inp != NULL && ipsec6_in_reject(m, inp)) {
561 goto drop;
562 }
563 } else {
564 if (inp != NULL && ipsec4_in_reject(m, inp)) {
565 goto drop;
566 }
567 }
568#endif
569
570 /*
571 * If the state is CLOSED (i.e., TCB does not exist) then
572 * all data in the incoming segment is discarded.
573 * If the TCB exists but is in CLOSED state, it is embryonic,
574 * but should either do a listen or a connect soon.
575 */
576 if (inp == NULL) {
577 if (log_in_vain) {
578#ifdef INET6
579 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
580#else
581 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
582#endif
583 if (isipv6) {
584 strcpy(dbuf, "[");
585 strcpy(sbuf, "[");
586 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
587 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
588 strcat(dbuf, "]");
589 strcat(sbuf, "]");
590 } else {
591 strcpy(dbuf, inet_ntoa(ip->ip_dst));
592 strcpy(sbuf, inet_ntoa(ip->ip_src));
593 }
594 switch (log_in_vain) {
595 case 1:
596 if ((thflags & TH_SYN) == 0)
597 break;
598 case 2:
599 log(LOG_INFO,
600 "Connection attempt to TCP %s:%d "
601 "from %s:%d flags:0x%02x\n",
602 dbuf, ntohs(th->th_dport), sbuf,
603 ntohs(th->th_sport), thflags);
604 break;
605 default:
606 break;
607 }
608 }
609 if (blackhole) {
610 switch (blackhole) {
611 case 1:
612 if (thflags & TH_SYN)
613 goto drop;
614 break;
615 case 2:
616 goto drop;
617 default:
618 goto drop;
619 }
620 }
621 rstreason = BANDLIM_RST_CLOSEDPORT;
622 goto dropwithreset;
623 }
624 tp = intotcpcb(inp);
625 if (tp == NULL) {
626 rstreason = BANDLIM_RST_CLOSEDPORT;
627 goto dropwithreset;
628 }
629 if (tp->t_state == TCPS_CLOSED)
630 goto drop;
631
632 /* Unscale the window into a 32-bit value. */
633 if ((thflags & TH_SYN) == 0)
634 tiwin = th->th_win << tp->snd_scale;
635 else
636 tiwin = th->th_win;
637
638 so = inp->inp_socket;
639 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
640 struct in_conninfo inc;
641#ifdef TCPDEBUG
642 if (so->so_options & SO_DEBUG) {
643 ostate = tp->t_state;
644 if (isipv6)
645 bcopy((char *)ip6, (char *)tcp_saveipgen,
646 sizeof(*ip6));
647 else
648 bcopy((char *)ip, (char *)tcp_saveipgen,
649 sizeof(*ip));
650 tcp_savetcp = *th;
651 }
652#endif
653 /* skip if this isn't a listen socket */
654 if ((so->so_options & SO_ACCEPTCONN) == 0)
655 goto after_listen;
656#ifdef INET6
657 inc.inc_isipv6 = isipv6;
658#endif
659 if (isipv6) {
660 inc.inc6_faddr = ip6->ip6_src;
661 inc.inc6_laddr = ip6->ip6_dst;
662 inc.inc6_route.ro_rt = NULL; /* XXX */
663 } else {
664 inc.inc_faddr = ip->ip_src;
665 inc.inc_laddr = ip->ip_dst;
666 inc.inc_route.ro_rt = NULL; /* XXX */
667 }
668 inc.inc_fport = th->th_sport;
669 inc.inc_lport = th->th_dport;
670
671 /*
672 * If the state is LISTEN then ignore segment if it contains
673 * a RST. If the segment contains an ACK then it is bad and
674 * send a RST. If it does not contain a SYN then it is not
675 * interesting; drop it.
676 *
677 * If the state is SYN_RECEIVED (syncache) and seg contains
678 * an ACK, but not for our SYN/ACK, send a RST. If the seg
679 * contains a RST, check the sequence number to see if it
680 * is a valid reset segment.
681 */
682 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
683 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
684 if (!syncache_expand(&inc, th, &so, m)) {
685 /*
686 * No syncache entry, or ACK was not
687 * for our SYN/ACK. Send a RST.
688 */
689 tcpstat.tcps_badsyn++;
690 rstreason = BANDLIM_RST_OPENPORT;
691 goto dropwithreset;
692 }
693 if (so == NULL)
694 /*
695 * Could not complete 3-way handshake,
696 * connection is being closed down, and
697 * syncache will free mbuf.
698 */
699 return;
700 /*
701 * Socket is created in state SYN_RECEIVED.
702 * Continue processing segment.
703 */
704 inp = sotoinpcb(so);
705 tp = intotcpcb(inp);
706 /*
707 * This is what would have happened in
708 * tcp_output() when the SYN,ACK was sent.
709 */
710 tp->snd_up = tp->snd_una;
711 tp->snd_max = tp->snd_nxt = tp->iss + 1;
712 tp->last_ack_sent = tp->rcv_nxt;
713/*
714 * XXX possible bug - it doesn't appear that tp->snd_wnd is unscaled
715 * until the _second_ ACK is received:
716 * rcv SYN (set wscale opts) --> send SYN/ACK, set snd_wnd = window.
717 * rcv ACK, calculate tiwin --> process SYN_RECEIVED, determine wscale,
718 * move to ESTAB, set snd_wnd to tiwin.
719 */
720 tp->snd_wnd = tiwin; /* unscaled */
721 goto after_listen;
722 }
723 if (thflags & TH_RST) {
724 syncache_chkrst(&inc, th);
725 goto drop;
726 }
727 if (thflags & TH_ACK) {
728 syncache_badack(&inc);
729 tcpstat.tcps_badsyn++;
730 rstreason = BANDLIM_RST_OPENPORT;
731 goto dropwithreset;
732 }
733 goto drop;
734 }
735
736 /*
737 * Segment's flags are (SYN) or (SYN|FIN).
738 */
739#ifdef INET6
740 /*
741 * If deprecated address is forbidden,
742 * we do not accept SYN to deprecated interface
743 * address to prevent any new inbound connection from
744 * getting established.
745 * When we do not accept SYN, we send a TCP RST,
746 * with deprecated source address (instead of dropping
747 * it). We compromise it as it is much better for peer
748 * to send a RST, and RST will be the final packet
749 * for the exchange.
750 *
751 * If we do not forbid deprecated addresses, we accept
752 * the SYN packet. RFC2462 does not suggest dropping
753 * SYN in this case.
754 * If we decipher RFC2462 5.5.4, it says like this:
755 * 1. use of deprecated addr with existing
756 * communication is okay - "SHOULD continue to be
757 * used"
758 * 2. use of it with new communication:
759 * (2a) "SHOULD NOT be used if alternate address
760 * with sufficient scope is available"
761 * (2b) nothing mentioned otherwise.
762 * Here we fall into (2b) case as we have no choice in
763 * our source address selection - we must obey the peer.
764 *
765 * The wording in RFC2462 is confusing, and there are
766 * multiple description text for deprecated address
767 * handling - worse, they are not exactly the same.
768 * I believe 5.5.4 is the best one, so we follow 5.5.4.
769 */
770 if (isipv6 && !ip6_use_deprecated) {
771 struct in6_ifaddr *ia6;
772
773 if ((ia6 = ip6_getdstifaddr(m)) &&
774 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
775 tp = NULL;
776 rstreason = BANDLIM_RST_OPENPORT;
777 goto dropwithreset;
778 }
779 }
780#endif
781 /*
782 * If it is from this socket, drop it, it must be forged.
783 * Don't bother responding if the destination was a broadcast.
784 */
785 if (th->th_dport == th->th_sport) {
786 if (isipv6) {
787 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
788 &ip6->ip6_src))
789 goto drop;
790 } else {
791 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
792 goto drop;
793 }
794 }
795 /*
796 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
797 *
798 * Note that it is quite possible to receive unicast
799 * link-layer packets with a broadcast IP address. Use
800 * in_broadcast() to find them.
801 */
802 if (m->m_flags & (M_BCAST|M_MCAST))
803 goto drop;
804 if (isipv6) {
805 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
806 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
807 goto drop;
808 } else {
809 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
810 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
811 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
812 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
813 goto drop;
814 }
815 /*
816 * SYN appears to be valid; create compressed TCP state
817 * for syncache, or perform t/tcp connection.
818 */
819 if (so->so_qlen <= so->so_qlimit) {
820 tcp_dooptions(&to, optp, optlen, 1);
821 if (!syncache_add(&inc, &to, th, &so, m))
822 goto drop;
823 if (so == NULL)
824 /*
825 * Entry added to syncache, mbuf used to
826 * send SYN,ACK packet.
827 */
828 return;
829 /*
830 * Segment passed TAO tests.
831 */
832 inp = sotoinpcb(so);
833 tp = intotcpcb(inp);
834 tp->snd_wnd = tiwin;
835 tp->t_starttime = ticks;
836 tp->t_state = TCPS_ESTABLISHED;
837
838 /*
839 * If there is a FIN, or if there is data and the
840 * connection is local, then delay SYN,ACK(SYN) in
841 * the hope of piggy-backing it on a response
842 * segment. Otherwise must send ACK now in case
843 * the other side is slow starting.
844 */
845 if (DELAY_ACK(tp) &&
846 ((thflags & TH_FIN) ||
847 (tlen != 0 &&
848 ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
849 (!isipv6 && in_localaddr(inp->inp_faddr)))))) {
850 callout_reset(tp->tt_delack, tcp_delacktime,
851 tcp_timer_delack, tp);
852 tp->t_flags |= TF_NEEDSYN;
853 } else
854 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
855
856 tcpstat.tcps_connects++;
857 soisconnected(so);
858 goto trimthenstep6;
859 }
860 goto drop;
861 }
862after_listen:
863
864/* XXX temp debugging */
865 /* should not happen - syncache should pick up these connections */
866 if (tp->t_state == TCPS_LISTEN)
867 panic("tcp_input: TCPS_LISTEN");
868
869 /*
870 * Segment received on connection.
871 * Reset idle time and keep-alive timer.
872 */
873 tp->t_rcvtime = ticks;
874 if (TCPS_HAVEESTABLISHED(tp->t_state))
875 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
876
877 /*
878 * Process options.
879 * XXX this is tradtitional behavior, may need to be cleaned up.
880 */
881 tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
882 if (thflags & TH_SYN) {
883 if (to.to_flags & TOF_SCALE) {
884 tp->t_flags |= TF_RCVD_SCALE;
885 tp->requested_s_scale = to.to_requested_s_scale;
886 }
887 if (to.to_flags & TOF_TS) {
888 tp->t_flags |= TF_RCVD_TSTMP;
889 tp->ts_recent = to.to_tsval;
890 tp->ts_recent_age = ticks;
891 }
892 if (to.to_flags & (TOF_CC|TOF_CCNEW))
893 tp->t_flags |= TF_RCVD_CC;
894 if (to.to_flags & TOF_MSS)
895 tcp_mss(tp, to.to_mss);
896 }
897
898 /*
899 * Header prediction: check for the two common cases
900 * of a uni-directional data xfer. If the packet has
901 * no control flags, is in-sequence, the window didn't
902 * change and we're not retransmitting, it's a
903 * candidate. If the length is zero and the ack moved
904 * forward, we're the sender side of the xfer. Just
905 * free the data acked & wake any higher level process
906 * that was blocked waiting for space. If the length
907 * is non-zero and the ack didn't move, we're the
908 * receiver side. If we're getting packets in-order
909 * (the reassembly queue is empty), add the data to
910 * the socket buffer and note that we need a delayed ack.
911 * Make sure that the hidden state-flags are also off.
912 * Since we check for TCPS_ESTABLISHED above, it can only
913 * be TH_NEEDSYN.
914 */
915 if (tp->t_state == TCPS_ESTABLISHED &&
916 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
917 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
918 ((to.to_flags & TOF_TS) == 0 ||
919 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
920 /*
921 * Using the CC option is compulsory if once started:
922 * the segment is OK if no T/TCP was negotiated or
923 * if the segment has a CC option equal to CCrecv
924 */
925 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
926 ((to.to_flags & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
927 th->th_seq == tp->rcv_nxt &&
928 tiwin && tiwin == tp->snd_wnd &&
929 tp->snd_nxt == tp->snd_max) {
930
931 /*
932 * If last ACK falls within this segment's sequence numbers,
933 * record the timestamp.
934 * NOTE that the test is modified according to the latest
935 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
936 */
937 if ((to.to_flags & TOF_TS) != 0 &&
938 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
939 tp->ts_recent_age = ticks;
940 tp->ts_recent = to.to_tsval;
941 }
942
943 if (tlen == 0) {
944 if (SEQ_GT(th->th_ack, tp->snd_una) &&
945 SEQ_LEQ(th->th_ack, tp->snd_max) &&
946 tp->snd_cwnd >= tp->snd_wnd &&
947 ((!tcp_do_newreno &&
948 tp->t_dupacks < tcprexmtthresh) ||
949 (tcp_do_newreno &&
950 !SEQ_LT(tp->snd_una, tp->snd_recover)))) {
951 /*
952 * this is a pure ack for outstanding data.
953 */
954 ++tcpstat.tcps_predack;
955 /*
956 * "bad retransmit" recovery
957 */
958 if (tp->t_rxtshift == 1 &&
959 ticks < tp->t_badrxtwin) {
960 tp->snd_cwnd = tp->snd_cwnd_prev;
961 tp->snd_ssthresh =
962 tp->snd_ssthresh_prev;
963 tp->snd_high = tp->snd_high_prev;
964 tp->snd_nxt = tp->snd_max;
965 tp->t_badrxtwin = 0;
966 }
967 /*
968 * Recalculate the retransmit timer / rtt.
969 *
970 * Some machines (certain windows boxes)
971 * send broken timestamp replies during the
972 * SYN+ACK phase, ignore timestamps of 0.
973 */
974 if ((to.to_flags & TOF_TS) != 0 &&
975 to.to_tsecr) {
976 tcp_xmit_timer(tp,
977 ticks - to.to_tsecr + 1);
978 } else if (tp->t_rtttime &&
979 SEQ_GT(th->th_ack, tp->t_rtseq)) {
980 tcp_xmit_timer(tp,
981 ticks - tp->t_rtttime);
982 }
983 tcp_xmit_bandwidth_limit(tp, th->th_ack);
984 acked = th->th_ack - tp->snd_una;
985 tcpstat.tcps_rcvackpack++;
986 tcpstat.tcps_rcvackbyte += acked;
987 sbdrop(&so->so_snd, acked);
988 if (SEQ_GT(tp->snd_una, tp->snd_high) &&
989 SEQ_LEQ(th->th_ack, tp->snd_high))
990 tp->snd_high = th->th_ack - 1;
991 tp->snd_una = tp->snd_recover = th->th_ack;
992 tp->t_dupacks = 0;
993 m_freem(m);
994 ND6_HINT(tp); /* some progress has been done */
995
996 /*
997 * If all outstanding data are acked, stop
998 * retransmit timer, otherwise restart timer
999 * using current (possibly backed-off) value.
1000 * If process is waiting for space,
1001 * wakeup/selwakeup/signal. If data
1002 * are ready to send, let tcp_output
1003 * decide between more output or persist.
1004 */
1005 if (tp->snd_una == tp->snd_max)
1006 callout_stop(tp->tt_rexmt);
1007 else if (!callout_active(tp->tt_persist))
1008 callout_reset(tp->tt_rexmt,
1009 tp->t_rxtcur,
1010 tcp_timer_rexmt, tp);
1011
1012 sowwakeup(so);
1013 if (so->so_snd.sb_cc)
1014 (void) tcp_output(tp);
1015 return;
1016 }
1017 } else if (th->th_ack == tp->snd_una &&
1018 LIST_EMPTY(&tp->t_segq) &&
1019 tlen <= sbspace(&so->so_rcv)) {
1020 /*
1021 * this is a pure, in-sequence data packet
1022 * with nothing on the reassembly queue and
1023 * we have enough buffer space to take it.
1024 */
1025 ++tcpstat.tcps_preddat;
1026 tp->rcv_nxt += tlen;
1027 tcpstat.tcps_rcvpack++;
1028 tcpstat.tcps_rcvbyte += tlen;
1029 ND6_HINT(tp); /* some progress has been done */
1030 /*
1031 * Add data to socket buffer.
1032 */
1033 if (so->so_state & SS_CANTRCVMORE) {
1034 m_freem(m);
1035 } else {
1036 m_adj(m, drop_hdrlen); /* delayed header drop */
1037 sbappend(&so->so_rcv, m);
1038 }
1039 sorwakeup(so);
1040 if (DELAY_ACK(tp)) {
1041 callout_reset(tp->tt_delack, tcp_delacktime,
1042 tcp_timer_delack, tp);
1043 } else {
1044 tp->t_flags |= TF_ACKNOW;
1045 tcp_output(tp);
1046 }
1047 return;
1048 }
1049 }
1050
1051 /*
1052 * Calculate amount of space in receive window,
1053 * and then do TCP input processing.
1054 * Receive window is amount of space in rcv queue,
1055 * but not less than advertised window.
1056 */
1057 { int win;
1058
1059 win = sbspace(&so->so_rcv);
1060 if (win < 0)
1061 win = 0;
1062 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1063 }
1064
1065 switch (tp->t_state) {
1066
1067 /*
1068 * If the state is SYN_RECEIVED:
1069 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1070 */
1071 case TCPS_SYN_RECEIVED:
1072 if ((thflags & TH_ACK) &&
1073 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1074 SEQ_GT(th->th_ack, tp->snd_max))) {
1075 rstreason = BANDLIM_RST_OPENPORT;
1076 goto dropwithreset;
1077 }
1078 break;
1079
1080 /*
1081 * If the state is SYN_SENT:
1082 * if seg contains an ACK, but not for our SYN, drop the input.
1083 * if seg contains a RST, then drop the connection.
1084 * if seg does not contain SYN, then drop it.
1085 * Otherwise this is an acceptable SYN segment
1086 * initialize tp->rcv_nxt and tp->irs
1087 * if seg contains ack then advance tp->snd_una
1088 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1089 * arrange for segment to be acked (eventually)
1090 * continue processing rest of data/controls, beginning with URG
1091 */
1092 case TCPS_SYN_SENT:
1093 if ((taop = tcp_gettaocache(&inp->inp_inc)) == NULL) {
1094 taop = &tao_noncached;
1095 bzero(taop, sizeof(*taop));
1096 }
1097
1098 if ((thflags & TH_ACK) &&
1099 (SEQ_LEQ(th->th_ack, tp->iss) ||
1100 SEQ_GT(th->th_ack, tp->snd_max))) {
1101 /*
1102 * If we have a cached CCsent for the remote host,
1103 * hence we haven't just crashed and restarted,
1104 * do not send a RST. This may be a retransmission
1105 * from the other side after our earlier ACK was lost.
1106 * Our new SYN, when it arrives, will serve as the
1107 * needed ACK.
1108 */
1109 if (taop->tao_ccsent != 0)
1110 goto drop;
1111 else {
1112 rstreason = BANDLIM_UNLIMITED;
1113 goto dropwithreset;
1114 }
1115 }
1116 if (thflags & TH_RST) {
1117 if (thflags & TH_ACK)
1118 tp = tcp_drop(tp, ECONNREFUSED);
1119 goto drop;
1120 }
1121 if ((thflags & TH_SYN) == 0)
1122 goto drop;
1123 tp->snd_wnd = th->th_win; /* initial send window */
1124 tp->cc_recv = to.to_cc; /* foreign CC */
1125
1126 tp->irs = th->th_seq;
1127 tcp_rcvseqinit(tp);
1128 if (thflags & TH_ACK) {
1129 /*
1130 * Our SYN was acked. If segment contains CC.ECHO
1131 * option, check it to make sure this segment really
1132 * matches our SYN. If not, just drop it as old
1133 * duplicate, but send an RST if we're still playing
1134 * by the old rules. If no CC.ECHO option, make sure
1135 * we don't get fooled into using T/TCP.
1136 */
1137 if (to.to_flags & TOF_CCECHO) {
1138 if (tp->cc_send != to.to_ccecho) {
1139 if (taop->tao_ccsent != 0)
1140 goto drop;
1141 else {
1142 rstreason = BANDLIM_UNLIMITED;
1143 goto dropwithreset;
1144 }
1145 }
1146 } else
1147 tp->t_flags &= ~TF_RCVD_CC;
1148 tcpstat.tcps_connects++;
1149 soisconnected(so);
1150 /* Do window scaling on this connection? */
1151 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1152 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1153 tp->snd_scale = tp->requested_s_scale;
1154 tp->rcv_scale = tp->request_r_scale;
1155 }
1156 /* Segment is acceptable, update cache if undefined. */
1157 if (taop->tao_ccsent == 0)
1158 taop->tao_ccsent = to.to_ccecho;
1159
1160 tp->rcv_adv += tp->rcv_wnd;
1161 tp->snd_una++; /* SYN is acked */
1162 /*
1163 * If there's data, delay ACK; if there's also a FIN
1164 * ACKNOW will be turned on later.
1165 */
1166 if (DELAY_ACK(tp) && tlen != 0)
1167 callout_reset(tp->tt_delack, tcp_delacktime,
1168 tcp_timer_delack, tp);
1169 else
1170 tp->t_flags |= TF_ACKNOW;
1171 /*
1172 * Received <SYN,ACK> in SYN_SENT[*] state.
1173 * Transitions:
1174 * SYN_SENT --> ESTABLISHED
1175 * SYN_SENT* --> FIN_WAIT_1
1176 */
1177 tp->t_starttime = ticks;
1178 if (tp->t_flags & TF_NEEDFIN) {
1179 tp->t_state = TCPS_FIN_WAIT_1;
1180 tp->t_flags &= ~TF_NEEDFIN;
1181 thflags &= ~TH_SYN;
1182 } else {
1183 tp->t_state = TCPS_ESTABLISHED;
1184 callout_reset(tp->tt_keep, tcp_keepidle,
1185 tcp_timer_keep, tp);
1186 }
1187 } else {
1188 /*
1189 * Received initial SYN in SYN-SENT[*] state =>
1190 * simultaneous open. If segment contains CC option
1191 * and there is a cached CC, apply TAO test.
1192 * If it succeeds, connection is * half-synchronized.
1193 * Otherwise, do 3-way handshake:
1194 * SYN-SENT -> SYN-RECEIVED
1195 * SYN-SENT* -> SYN-RECEIVED*
1196 * If there was no CC option, clear cached CC value.
1197 */
1198 tp->t_flags |= TF_ACKNOW;
1199 callout_stop(tp->tt_rexmt);
1200 if (to.to_flags & TOF_CC) {
1201 if (taop->tao_cc != 0 &&
1202 CC_GT(to.to_cc, taop->tao_cc)) {
1203 /*
1204 * update cache and make transition:
1205 * SYN-SENT -> ESTABLISHED*
1206 * SYN-SENT* -> FIN-WAIT-1*
1207 */
1208 taop->tao_cc = to.to_cc;
1209 tp->t_starttime = ticks;
1210 if (tp->t_flags & TF_NEEDFIN) {
1211 tp->t_state = TCPS_FIN_WAIT_1;
1212 tp->t_flags &= ~TF_NEEDFIN;
1213 } else {
1214 tp->t_state = TCPS_ESTABLISHED;
1215 callout_reset(tp->tt_keep,
1216 tcp_keepidle,
1217 tcp_timer_keep,
1218 tp);
1219 }
1220 tp->t_flags |= TF_NEEDSYN;
1221 } else
1222 tp->t_state = TCPS_SYN_RECEIVED;
1223 } else {
1224 /* CC.NEW or no option => invalidate cache */
1225 taop->tao_cc = 0;
1226 tp->t_state = TCPS_SYN_RECEIVED;
1227 }
1228 }
1229
1230trimthenstep6:
1231 /*
1232 * Advance th->th_seq to correspond to first data byte.
1233 * If data, trim to stay within window,
1234 * dropping FIN if necessary.
1235 */
1236 th->th_seq++;
1237 if (tlen > tp->rcv_wnd) {
1238 todrop = tlen - tp->rcv_wnd;
1239 m_adj(m, -todrop);
1240 tlen = tp->rcv_wnd;
1241 thflags &= ~TH_FIN;
1242 tcpstat.tcps_rcvpackafterwin++;
1243 tcpstat.tcps_rcvbyteafterwin += todrop;
1244 }
1245 tp->snd_wl1 = th->th_seq - 1;
1246 tp->rcv_up = th->th_seq;
1247 /*
1248 * Client side of transaction: already sent SYN and data.
1249 * If the remote host used T/TCP to validate the SYN,
1250 * our data will be ACK'd; if so, enter normal data segment
1251 * processing in the middle of step 5, ack processing.
1252 * Otherwise, goto step 6.
1253 */
1254 if (thflags & TH_ACK)
1255 goto process_ACK;
1256
1257 goto step6;
1258
1259 /*
1260 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1261 * if segment contains a SYN and CC [not CC.NEW] option:
1262 * if state == TIME_WAIT and connection duration > MSL,
1263 * drop packet and send RST;
1264 *
1265 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1266 * ack the FIN (and data) in retransmission queue.
1267 * Complete close and delete TCPCB. Then reprocess
1268 * segment, hoping to find new TCPCB in LISTEN state;
1269 *
1270 * else must be old SYN; drop it.
1271 * else do normal processing.
1272 */
1273 case TCPS_LAST_ACK:
1274 case TCPS_CLOSING:
1275 case TCPS_TIME_WAIT:
1276 if ((thflags & TH_SYN) &&
1277 (to.to_flags & TOF_CC) && tp->cc_recv != 0) {
1278 if (tp->t_state == TCPS_TIME_WAIT &&
1279 (ticks - tp->t_starttime) > tcp_msl) {
1280 rstreason = BANDLIM_UNLIMITED;
1281 goto dropwithreset;
1282 }
1283 if (CC_GT(to.to_cc, tp->cc_recv)) {
1284 tp = tcp_close(tp);
1285 goto findpcb;
1286 }
1287 else
1288 goto drop;
1289 }
1290 break; /* continue normal processing */
1291 }
1292
1293 /*
1294 * States other than LISTEN or SYN_SENT.
1295 * First check the RST flag and sequence number since reset segments
1296 * are exempt from the timestamp and connection count tests. This
1297 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1298 * below which allowed reset segments in half the sequence space
1299 * to fall though and be processed (which gives forged reset
1300 * segments with a random sequence number a 50 percent chance of
1301 * killing a connection).
1302 * Then check timestamp, if present.
1303 * Then check the connection count, if present.
1304 * Then check that at least some bytes of segment are within
1305 * receive window. If segment begins before rcv_nxt,
1306 * drop leading data (and SYN); if nothing left, just ack.
1307 *
1308 *
1309 * If the RST bit is set, check the sequence number to see
1310 * if this is a valid reset segment.
1311 * RFC 793 page 37:
1312 * In all states except SYN-SENT, all reset (RST) segments
1313 * are validated by checking their SEQ-fields. A reset is
1314 * valid if its sequence number is in the window.
1315 * Note: this does not take into account delayed ACKs, so
1316 * we should test against last_ack_sent instead of rcv_nxt.
1317 * The sequence number in the reset segment is normally an
1318 * echo of our outgoing acknowlegement numbers, but some hosts
1319 * send a reset with the sequence number at the rightmost edge
1320 * of our receive window, and we have to handle this case.
1321 * If we have multiple segments in flight, the intial reset
1322 * segment sequence numbers will be to the left of last_ack_sent,
1323 * but they will eventually catch up.
1324 * In any case, it never made sense to trim reset segments to
1325 * fit the receive window since RFC 1122 says:
1326 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1327 *
1328 * A TCP SHOULD allow a received RST segment to include data.
1329 *
1330 * DISCUSSION
1331 * It has been suggested that a RST segment could contain
1332 * ASCII text that encoded and explained the cause of the
1333 * RST. No standard has yet been established for such
1334 * data.
1335 *
1336 * If the reset segment passes the sequence number test examine
1337 * the state:
1338 * SYN_RECEIVED STATE:
1339 * If passive open, return to LISTEN state.
1340 * If active open, inform user that connection was refused.
1341 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1342 * Inform user that connection was reset, and close tcb.
1343 * CLOSING, LAST_ACK STATES:
1344 * Close the tcb.
1345 * TIME_WAIT STATE:
1346 * Drop the segment - see Stevens, vol. 2, p. 964 and
1347 * RFC 1337.
1348 */
1349 if (thflags & TH_RST) {
1350 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent) &&
1351 SEQ_LT(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1352 switch (tp->t_state) {
1353
1354 case TCPS_SYN_RECEIVED:
1355 so->so_error = ECONNREFUSED;
1356 goto close;
1357
1358 case TCPS_ESTABLISHED:
1359 case TCPS_FIN_WAIT_1:
1360 case TCPS_FIN_WAIT_2:
1361 case TCPS_CLOSE_WAIT:
1362 so->so_error = ECONNRESET;
1363 close:
1364 tp->t_state = TCPS_CLOSED;
1365 tcpstat.tcps_drops++;
1366 tp = tcp_close(tp);
1367 break;
1368
1369 case TCPS_CLOSING:
1370 case TCPS_LAST_ACK:
1371 tp = tcp_close(tp);
1372 break;
1373
1374 case TCPS_TIME_WAIT:
1375 break;
1376 }
1377 }
1378 goto drop;
1379 }
1380
1381 /*
1382 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1383 * and it's less than ts_recent, drop it.
1384 */
1385 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1386 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1387
1388 /* Check to see if ts_recent is over 24 days old. */
1389 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1390 /*
1391 * Invalidate ts_recent. If this segment updates
1392 * ts_recent, the age will be reset later and ts_recent
1393 * will get a valid value. If it does not, setting
1394 * ts_recent to zero will at least satisfy the
1395 * requirement that zero be placed in the timestamp
1396 * echo reply when ts_recent isn't valid. The
1397 * age isn't reset until we get a valid ts_recent
1398 * because we don't want out-of-order segments to be
1399 * dropped when ts_recent is old.
1400 */
1401 tp->ts_recent = 0;
1402 } else {
1403 tcpstat.tcps_rcvduppack++;
1404 tcpstat.tcps_rcvdupbyte += tlen;
1405 tcpstat.tcps_pawsdrop++;
1406 if (tlen)
1407 goto dropafterack;
1408 goto drop;
1409 }
1410 }
1411
1412 /*
1413 * T/TCP mechanism
1414 * If T/TCP was negotiated and the segment doesn't have CC,
1415 * or if its CC is wrong then drop the segment.
1416 * RST segments do not have to comply with this.
1417 */
1418 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1419 ((to.to_flags & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1420 goto dropafterack;
1421
1422 /*
1423 * In the SYN-RECEIVED state, validate that the packet belongs to
1424 * this connection before trimming the data to fit the receive
1425 * window. Check the sequence number versus IRS since we know
1426 * the sequence numbers haven't wrapped. This is a partial fix
1427 * for the "LAND" DoS attack.
1428 */
1429 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1430 rstreason = BANDLIM_RST_OPENPORT;
1431 goto dropwithreset;
1432 }
1433
1434 todrop = tp->rcv_nxt - th->th_seq;
1435 if (todrop > 0) {
1436 if (thflags & TH_SYN) {
1437 thflags &= ~TH_SYN;
1438 th->th_seq++;
1439 if (th->th_urp > 1)
1440 th->th_urp--;
1441 else
1442 thflags &= ~TH_URG;
1443 todrop--;
1444 }
1445 /*
1446 * Following if statement from Stevens, vol. 2, p. 960.
1447 */
1448 if (todrop > tlen
1449 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1450 /*
1451 * Any valid FIN must be to the left of the window.
1452 * At this point the FIN must be a duplicate or out
1453 * of sequence; drop it.
1454 */
1455 thflags &= ~TH_FIN;
1456
1457 /*
1458 * Send an ACK to resynchronize and drop any data.
1459 * But keep on processing for RST or ACK.
1460 */
1461 tp->t_flags |= TF_ACKNOW;
1462 todrop = tlen;
1463 tcpstat.tcps_rcvduppack++;
1464 tcpstat.tcps_rcvdupbyte += todrop;
1465 } else {
1466 tcpstat.tcps_rcvpartduppack++;
1467 tcpstat.tcps_rcvpartdupbyte += todrop;
1468 }
1469 drop_hdrlen += todrop; /* drop from the top afterwards */
1470 th->th_seq += todrop;
1471 tlen -= todrop;
1472 if (th->th_urp > todrop)
1473 th->th_urp -= todrop;
1474 else {
1475 thflags &= ~TH_URG;
1476 th->th_urp = 0;
1477 }
1478 }
1479
1480 /*
1481 * If new data are received on a connection after the
1482 * user processes are gone, then RST the other end.
1483 */
1484 if ((so->so_state & SS_NOFDREF) &&
1485 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1486 tp = tcp_close(tp);
1487 tcpstat.tcps_rcvafterclose++;
1488 rstreason = BANDLIM_UNLIMITED;
1489 goto dropwithreset;
1490 }
1491
1492 /*
1493 * If segment ends after window, drop trailing data
1494 * (and PUSH and FIN); if nothing left, just ACK.
1495 */
1496 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1497 if (todrop > 0) {
1498 tcpstat.tcps_rcvpackafterwin++;
1499 if (todrop >= tlen) {
1500 tcpstat.tcps_rcvbyteafterwin += tlen;
1501 /*
1502 * If a new connection request is received
1503 * while in TIME_WAIT, drop the old connection
1504 * and start over if the sequence numbers
1505 * are above the previous ones.
1506 */
1507 if (thflags & TH_SYN &&
1508 tp->t_state == TCPS_TIME_WAIT &&
1509 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1510 tp = tcp_close(tp);
1511 goto findpcb;
1512 }
1513 /*
1514 * If window is closed can only take segments at
1515 * window edge, and have to drop data and PUSH from
1516 * incoming segments. Continue processing, but
1517 * remember to ack. Otherwise, drop segment
1518 * and ack.
1519 */
1520 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1521 tp->t_flags |= TF_ACKNOW;
1522 tcpstat.tcps_rcvwinprobe++;
1523 } else
1524 goto dropafterack;
1525 } else
1526 tcpstat.tcps_rcvbyteafterwin += todrop;
1527 m_adj(m, -todrop);
1528 tlen -= todrop;
1529 thflags &= ~(TH_PUSH|TH_FIN);
1530 }
1531
1532 /*
1533 * If last ACK falls within this segment's sequence numbers,
1534 * record its timestamp.
1535 * NOTE that the test is modified according to the latest
1536 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1537 */
1538 if ((to.to_flags & TOF_TS) != 0 &&
1539 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1540 tp->ts_recent_age = ticks;
1541 tp->ts_recent = to.to_tsval;
1542 }
1543
1544 /*
1545 * If a SYN is in the window, then this is an
1546 * error and we send an RST and drop the connection.
1547 */
1548 if (thflags & TH_SYN) {
1549 tp = tcp_drop(tp, ECONNRESET);
1550 rstreason = BANDLIM_UNLIMITED;
1551 goto dropwithreset;
1552 }
1553
1554 /*
1555 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1556 * flag is on (half-synchronized state), then queue data for
1557 * later processing; else drop segment and return.
1558 */
1559 if ((thflags & TH_ACK) == 0) {
1560 if (tp->t_state == TCPS_SYN_RECEIVED ||
1561 (tp->t_flags & TF_NEEDSYN))
1562 goto step6;
1563 else
1564 goto drop;
1565 }
1566
1567 /*
1568 * Ack processing.
1569 */
1570 switch (tp->t_state) {
1571
1572 /*
1573 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1574 * ESTABLISHED state and continue processing.
1575 * The ACK was checked above.
1576 */
1577 case TCPS_SYN_RECEIVED:
1578
1579 tcpstat.tcps_connects++;
1580 soisconnected(so);
1581 /* Do window scaling? */
1582 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1583 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1584 tp->snd_scale = tp->requested_s_scale;
1585 tp->rcv_scale = tp->request_r_scale;
1586 }
1587 /*
1588 * Upon successful completion of 3-way handshake,
1589 * update cache.CC if it was undefined, pass any queued
1590 * data to the user, and advance state appropriately.
1591 */
1592 if ((taop = tcp_gettaocache(&inp->inp_inc)) != NULL &&
1593 taop->tao_cc == 0)
1594 taop->tao_cc = tp->cc_recv;
1595
1596 /*
1597 * Make transitions:
1598 * SYN-RECEIVED -> ESTABLISHED
1599 * SYN-RECEIVED* -> FIN-WAIT-1
1600 */
1601 tp->t_starttime = ticks;
1602 if (tp->t_flags & TF_NEEDFIN) {
1603 tp->t_state = TCPS_FIN_WAIT_1;
1604 tp->t_flags &= ~TF_NEEDFIN;
1605 } else {
1606 tp->t_state = TCPS_ESTABLISHED;
1607 callout_reset(tp->tt_keep, tcp_keepidle,
1608 tcp_timer_keep, tp);
1609 }
1610 /*
1611 * If segment contains data or ACK, will call tcp_reass()
1612 * later; if not, do so now to pass queued data to user.
1613 */
1614 if (tlen == 0 && (thflags & TH_FIN) == 0)
1615 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1616 (struct mbuf *)0);
1617 tp->snd_wl1 = th->th_seq - 1;
1618 /* fall into ... */
1619
1620 /*
1621 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1622 * ACKs. If the ack is in the range
1623 * tp->snd_una < th->th_ack <= tp->snd_max
1624 * then advance tp->snd_una to th->th_ack and drop
1625 * data from the retransmission queue. If this ACK reflects
1626 * more up to date window information we update our window information.
1627 */
1628 case TCPS_ESTABLISHED:
1629 case TCPS_FIN_WAIT_1:
1630 case TCPS_FIN_WAIT_2:
1631 case TCPS_CLOSE_WAIT:
1632 case TCPS_CLOSING:
1633 case TCPS_LAST_ACK:
1634 case TCPS_TIME_WAIT:
1635
1636 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1637 if (tlen == 0 && tiwin == tp->snd_wnd) {
1638 tcpstat.tcps_rcvdupack++;
1639 /*
1640 * If we have outstanding data (other than
1641 * a window probe), this is a completely
1642 * duplicate ack (ie, window info didn't
1643 * change), the ack is the biggest we've
1644 * seen and we've seen exactly our rexmt
1645 * threshhold of them, assume a packet
1646 * has been dropped and retransmit it.
1647 * Kludge snd_nxt & the congestion
1648 * window so we send only this one
1649 * packet.
1650 *
1651 * We know we're losing at the current
1652 * window size so do congestion avoidance
1653 * (set ssthresh to half the current window
1654 * and pull our congestion window back to
1655 * the new ssthresh).
1656 *
1657 * Dup acks mean that packets have left the
1658 * network (they're now cached at the receiver)
1659 * so bump cwnd by the amount in the receiver
1660 * to keep a constant cwnd packets in the
1661 * network.
1662 */
1663 if (!callout_active(tp->tt_rexmt) ||
1664 th->th_ack != tp->snd_una)
1665 tp->t_dupacks = 0;
1666 else if (++tp->t_dupacks > tcprexmtthresh ||
1667 (tcp_do_newreno &&
1668 SEQ_LT(tp->snd_una,
1669 tp->snd_recover))) {
1670 tp->snd_cwnd += tp->t_maxseg;
1671 (void) tcp_output(tp);
1672 goto drop;
1673 } else if (tp->t_dupacks == tcprexmtthresh) {
1674 tcp_seq onxt = tp->snd_nxt;
1675 u_int win;
1676 if (tcp_do_newreno &&
1677 SEQ_LEQ(th->th_ack, tp->snd_high)) {
1678 tp->t_dupacks = 0;
1679 break;
1680 }
1681 win = min(tp->snd_wnd, tp->snd_cwnd) /
1682 2 / tp->t_maxseg;
1683 if (win < 2)
1684 win = 2;
1685 tp->snd_ssthresh = win * tp->t_maxseg;
1686 tp->snd_recover = tp->snd_max;
1687 callout_stop(tp->tt_rexmt);
1688 tp->t_rtttime = 0;
1689 tp->snd_nxt = th->th_ack;
1690 tp->snd_cwnd = tp->t_maxseg;
1691 (void) tcp_output(tp);
1692 tp->snd_cwnd = tp->snd_ssthresh +
1693 tp->t_maxseg * tp->t_dupacks;
1694 if (SEQ_GT(onxt, tp->snd_nxt))
1695 tp->snd_nxt = onxt;
1696 goto drop;
1697 }
1698 } else
1699 tp->t_dupacks = 0;
1700 break;
1701 }
1702
1703 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1704
1705 /*
1706 * If the congestion window was inflated to account
1707 * for the other side's cached packets, retract it.
1708 */
1709 if (tcp_do_newreno) {
1710 if (SEQ_LT(tp->snd_una, tp->snd_recover)) {
1711 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
1712 tcp_newreno_partial_ack(tp, th);
1713 } else {
1714 /*
1715 * Window inflation should have left us
1716 * with approximately snd_ssthresh
1717 * outstanding data.
1718 * But in case we would be inclined to
1719 * send a burst, better to do it via
1720 * the slow start mechanism.
1721 */
1722 if (SEQ_GT(th->th_ack +
1723 tp->snd_ssthresh,
1724 tp->snd_max))
1725 tp->snd_cwnd = tp->snd_max -
1726 th->th_ack +
1727 tp->t_maxseg;
1728 else
1729 tp->snd_cwnd = tp->snd_ssthresh;
1730 }
1731 }
1732 } else {
1733 if (tp->t_dupacks >= tcprexmtthresh &&
1734 tp->snd_cwnd > tp->snd_ssthresh)
1735 tp->snd_cwnd = tp->snd_ssthresh;
1736 }
1737 tp->t_dupacks = 0;
1738 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1739 tcpstat.tcps_rcvacktoomuch++;
1740 goto dropafterack;
1741 }
1742 /*
1743 * If we reach this point, ACK is not a duplicate,
1744 * i.e., it ACKs something we sent.
1745 */
1746 if (tp->t_flags & TF_NEEDSYN) {
1747 /*
1748 * T/TCP: Connection was half-synchronized, and our
1749 * SYN has been ACK'd (so connection is now fully
1750 * synchronized). Go to non-starred state,
1751 * increment snd_una for ACK of SYN, and check if
1752 * we can do window scaling.
1753 */
1754 tp->t_flags &= ~TF_NEEDSYN;
1755 tp->snd_una++;
1756 /* Do window scaling? */
1757 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1758 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1759 tp->snd_scale = tp->requested_s_scale;
1760 tp->rcv_scale = tp->request_r_scale;
1761 }
1762 }
1763
1764process_ACK:
1765 acked = th->th_ack - tp->snd_una;
1766 tcpstat.tcps_rcvackpack++;
1767 tcpstat.tcps_rcvackbyte += acked;
1768
1769 /*
1770 * If we just performed our first retransmit, and the ACK
1771 * arrives within our recovery window, then it was a mistake
1772 * to do the retransmit in the first place. Recover our
1773 * original cwnd and ssthresh, and proceed to transmit where
1774 * we left off.
1775 */
1776 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
1777 tp->snd_cwnd = tp->snd_cwnd_prev;
1778 tp->snd_ssthresh = tp->snd_ssthresh_prev;
1779 tp->snd_high = tp->snd_high_prev;
1780 tp->snd_nxt = tp->snd_max;
1781 tp->t_badrxtwin = 0; /* XXX probably not required */
1782 }
1783
1784 /*
1785 * If we have a timestamp reply, update smoothed
1786 * round trip time. If no timestamp is present but
1787 * transmit timer is running and timed sequence
1788 * number was acked, update smoothed round trip time.
1789 * Since we now have an rtt measurement, cancel the
1790 * timer backoff (cf., Phil Karn's retransmit alg.).
1791 * Recompute the initial retransmit timer.
1792 *
1793 * Some machines (certain windows boxes) send broken
1794 * timestamp replies during the SYN+ACK phase, ignore
1795 * timestamps of 0.
1796 */
1797 if ((to.to_flags & TOF_TS) != 0 &&
1798 to.to_tsecr) {
1799 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
1800 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
1801 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
1802 }
1803 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1804
1805 /*
1806 * If all outstanding data is acked, stop retransmit
1807 * timer and remember to restart (more output or persist).
1808 * If there is more data to be acked, restart retransmit
1809 * timer, using current (possibly backed-off) value.
1810 */
1811 if (th->th_ack == tp->snd_max) {
1812 callout_stop(tp->tt_rexmt);
1813 needoutput = 1;
1814 } else if (!callout_active(tp->tt_persist))
1815 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
1816 tcp_timer_rexmt, tp);
1817
1818 /*
1819 * If no data (only SYN) was ACK'd,
1820 * skip rest of ACK processing.
1821 */
1822 if (acked == 0)
1823 goto step6;
1824
1825 /*
1826 * When new data is acked, open the congestion window.
1827 * If the window gives us less than ssthresh packets
1828 * in flight, open exponentially (maxseg per packet).
1829 * Otherwise open linearly: maxseg per window
1830 * (maxseg^2 / cwnd per packet).
1831 */
1832 if (!tcp_do_newreno || SEQ_GEQ(tp->snd_una, tp->snd_recover)) {
1833 register u_int cw = tp->snd_cwnd;
1834 register u_int incr = tp->t_maxseg;
1835 if (cw > tp->snd_ssthresh)
1836 incr = incr * incr / cw;
1837 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
1838 }
1839 if (acked > so->so_snd.sb_cc) {
1840 tp->snd_wnd -= so->so_snd.sb_cc;
1841 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1842 ourfinisacked = 1;
1843 } else {
1844 sbdrop(&so->so_snd, acked);
1845 tp->snd_wnd -= acked;
1846 ourfinisacked = 0;
1847 }
1848 sowwakeup(so);
1849 /* detect una wraparound */
1850 if (SEQ_GEQ(tp->snd_una, tp->snd_recover) &&
1851 SEQ_LT(th->th_ack, tp->snd_recover))
1852 tp->snd_recover = th->th_ack;
1853 if (SEQ_GT(tp->snd_una, tp->snd_high) &&
1854 SEQ_LEQ(th->th_ack, tp->snd_high))
1855 tp->snd_high = th->th_ack - 1;
1856 tp->snd_una = th->th_ack;
1857 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1858 tp->snd_nxt = tp->snd_una;
1859
1860 switch (tp->t_state) {
1861
1862 /*
1863 * In FIN_WAIT_1 STATE in addition to the processing
1864 * for the ESTABLISHED state if our FIN is now acknowledged
1865 * then enter FIN_WAIT_2.
1866 */
1867 case TCPS_FIN_WAIT_1:
1868 if (ourfinisacked) {
1869 /*
1870 * If we can't receive any more
1871 * data, then closing user can proceed.
1872 * Starting the timer is contrary to the
1873 * specification, but if we don't get a FIN
1874 * we'll hang forever.
1875 */
1876 if (so->so_state & SS_CANTRCVMORE) {
1877 soisdisconnected(so);
1878 callout_reset(tp->tt_2msl, tcp_maxidle,
1879 tcp_timer_2msl, tp);
1880 }
1881 tp->t_state = TCPS_FIN_WAIT_2;
1882 }
1883 break;
1884
1885 /*
1886 * In CLOSING STATE in addition to the processing for
1887 * the ESTABLISHED state if the ACK acknowledges our FIN
1888 * then enter the TIME-WAIT state, otherwise ignore
1889 * the segment.
1890 */
1891 case TCPS_CLOSING:
1892 if (ourfinisacked) {
1893 tp->t_state = TCPS_TIME_WAIT;
1894 tcp_canceltimers(tp);
1895 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1896 if (tp->cc_recv != 0 &&
1897 (ticks - tp->t_starttime) < tcp_msl)
1898 callout_reset(tp->tt_2msl,
1899 tp->t_rxtcur *
1900 TCPTV_TWTRUNC,
1901 tcp_timer_2msl, tp);
1902 else
1903 callout_reset(tp->tt_2msl, 2 * tcp_msl,
1904 tcp_timer_2msl, tp);
1905 soisdisconnected(so);
1906 }
1907 break;
1908
1909 /*
1910 * In LAST_ACK, we may still be waiting for data to drain
1911 * and/or to be acked, as well as for the ack of our FIN.
1912 * If our FIN is now acknowledged, delete the TCB,
1913 * enter the closed state and return.
1914 */
1915 case TCPS_LAST_ACK:
1916 if (ourfinisacked) {
1917 tp = tcp_close(tp);
1918 goto drop;
1919 }
1920 break;
1921
1922 /*
1923 * In TIME_WAIT state the only thing that should arrive
1924 * is a retransmission of the remote FIN. Acknowledge
1925 * it and restart the finack timer.
1926 */
1927 case TCPS_TIME_WAIT:
1928 callout_reset(tp->tt_2msl, 2 * tcp_msl,
1929 tcp_timer_2msl, tp);
1930 goto dropafterack;
1931 }
1932 }
1933
1934step6:
1935 /*
1936 * Update window information.
1937 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1938 */
1939 if ((thflags & TH_ACK) &&
1940 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1941 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
1942 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
1943 /* keep track of pure window updates */
1944 if (tlen == 0 &&
1945 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1946 tcpstat.tcps_rcvwinupd++;
1947 tp->snd_wnd = tiwin;
1948 tp->snd_wl1 = th->th_seq;
1949 tp->snd_wl2 = th->th_ack;
1950 if (tp->snd_wnd > tp->max_sndwnd)
1951 tp->max_sndwnd = tp->snd_wnd;
1952 needoutput = 1;
1953 }
1954
1955 /*
1956 * Process segments with URG.
1957 */
1958 if ((thflags & TH_URG) && th->th_urp &&
1959 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1960 /*
1961 * This is a kludge, but if we receive and accept
1962 * random urgent pointers, we'll crash in
1963 * soreceive. It's hard to imagine someone
1964 * actually wanting to send this much urgent data.
1965 */
1966 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1967 th->th_urp = 0; /* XXX */
1968 thflags &= ~TH_URG; /* XXX */
1969 goto dodata; /* XXX */
1970 }
1971 /*
1972 * If this segment advances the known urgent pointer,
1973 * then mark the data stream. This should not happen
1974 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1975 * a FIN has been received from the remote side.
1976 * In these states we ignore the URG.
1977 *
1978 * According to RFC961 (Assigned Protocols),
1979 * the urgent pointer points to the last octet
1980 * of urgent data. We continue, however,
1981 * to consider it to indicate the first octet
1982 * of data past the urgent section as the original
1983 * spec states (in one of two places).
1984 */
1985 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1986 tp->rcv_up = th->th_seq + th->th_urp;
1987 so->so_oobmark = so->so_rcv.sb_cc +
1988 (tp->rcv_up - tp->rcv_nxt) - 1;
1989 if (so->so_oobmark == 0)
1990 so->so_state |= SS_RCVATMARK;
1991 sohasoutofband(so);
1992 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1993 }
1994 /*
1995 * Remove out of band data so doesn't get presented to user.
1996 * This can happen independent of advancing the URG pointer,
1997 * but if two URG's are pending at once, some out-of-band
1998 * data may creep in... ick.
1999 */
2000 if (th->th_urp <= (u_long)tlen
2001#ifdef SO_OOBINLINE
2002 && (so->so_options & SO_OOBINLINE) == 0
2003#endif
2004 )
2005 tcp_pulloutofband(so, th, m,
2006 drop_hdrlen); /* hdr drop is delayed */
2007 } else {
2008 /*
2009 * If no out of band data is expected,
2010 * pull receive urgent pointer along
2011 * with the receive window.
2012 */
2013 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2014 tp->rcv_up = tp->rcv_nxt;
2015 }
2016dodata: /* XXX */
2017
2018 /*
2019 * Process the segment text, merging it into the TCP sequencing queue,
2020 * and arranging for acknowledgment of receipt if necessary.
2021 * This process logically involves adjusting tp->rcv_wnd as data
2022 * is presented to the user (this happens in tcp_usrreq.c,
2023 * case PRU_RCVD). If a FIN has already been received on this
2024 * connection then we just ignore the text.
2025 */
2026 if ((tlen || (thflags & TH_FIN)) &&
2027 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2028 m_adj(m, drop_hdrlen); /* delayed header drop */
2029 /*
2030 * Insert segment which includes th into TCP reassembly queue
2031 * with control block tp. Set thflags to whether reassembly now
2032 * includes a segment with FIN. This handles the common case
2033 * inline (segment is the next to be received on an established
2034 * connection, and the queue is empty), avoiding linkage into
2035 * and removal from the queue and repetition of various
2036 * conversions.
2037 * Set DELACK for segments received in order, but ack
2038 * immediately when segments are out of order (so
2039 * fast retransmit can work).
2040 */
2041 if (th->th_seq == tp->rcv_nxt &&
2042 LIST_EMPTY(&tp->t_segq) &&
2043 TCPS_HAVEESTABLISHED(tp->t_state)) {
2044 if (DELAY_ACK(tp))
2045 callout_reset(tp->tt_delack, tcp_delacktime,
2046 tcp_timer_delack, tp);
2047 else
2048 tp->t_flags |= TF_ACKNOW;
2049 tp->rcv_nxt += tlen;
2050 thflags = th->th_flags & TH_FIN;
2051 tcpstat.tcps_rcvpack++;
2052 tcpstat.tcps_rcvbyte += tlen;
2053 ND6_HINT(tp);
2054 if (so->so_state & SS_CANTRCVMORE)
2055 m_freem(m);
2056 else
2057 sbappend(&so->so_rcv, m);
2058 sorwakeup(so);
2059 } else {
2060 thflags = tcp_reass(tp, th, &tlen, m);
2061 tp->t_flags |= TF_ACKNOW;
2062 }
2063
2064 /*
2065 * Note the amount of data that peer has sent into
2066 * our window, in order to estimate the sender's
2067 * buffer size.
2068 */
2069 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2070 } else {
2071 m_freem(m);
2072 thflags &= ~TH_FIN;
2073 }
2074
2075 /*
2076 * If FIN is received ACK the FIN and let the user know
2077 * that the connection is closing.
2078 */
2079 if (thflags & TH_FIN) {
2080 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2081 socantrcvmore(so);
2082 /*
2083 * If connection is half-synchronized
2084 * (ie NEEDSYN flag on) then delay ACK,
2085 * so it may be piggybacked when SYN is sent.
2086 * Otherwise, since we received a FIN then no
2087 * more input can be expected, send ACK now.
2088 */
2089 if (DELAY_ACK(tp) && (tp->t_flags & TF_NEEDSYN))
2090 callout_reset(tp->tt_delack, tcp_delacktime,
2091 tcp_timer_delack, tp);
2092 else
2093 tp->t_flags |= TF_ACKNOW;
2094 tp->rcv_nxt++;
2095 }
2096 switch (tp->t_state) {
2097
2098 /*
2099 * In SYN_RECEIVED and ESTABLISHED STATES
2100 * enter the CLOSE_WAIT state.
2101 */
2102 case TCPS_SYN_RECEIVED:
2103 tp->t_starttime = ticks;
2104 /*FALLTHROUGH*/
2105 case TCPS_ESTABLISHED:
2106 tp->t_state = TCPS_CLOSE_WAIT;
2107 break;
2108
2109 /*
2110 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2111 * enter the CLOSING state.
2112 */
2113 case TCPS_FIN_WAIT_1:
2114 tp->t_state = TCPS_CLOSING;
2115 break;
2116
2117 /*
2118 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2119 * starting the time-wait timer, turning off the other
2120 * standard timers.
2121 */
2122 case TCPS_FIN_WAIT_2:
2123 tp->t_state = TCPS_TIME_WAIT;
2124 tcp_canceltimers(tp);
2125 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2126 if (tp->cc_recv != 0 &&
2127 (ticks - tp->t_starttime) < tcp_msl) {
2128 callout_reset(tp->tt_2msl,
2129 tp->t_rxtcur * TCPTV_TWTRUNC,
2130 tcp_timer_2msl, tp);
2131 /* For transaction client, force ACK now. */
2132 tp->t_flags |= TF_ACKNOW;
2133 }
2134 else
2135 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2136 tcp_timer_2msl, tp);
2137 soisdisconnected(so);
2138 break;
2139
2140 /*
2141 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2142 */
2143 case TCPS_TIME_WAIT:
2144 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2145 tcp_timer_2msl, tp);
2146 break;
2147 }
2148 }
2149#ifdef TCPDEBUG
2150 if (so->so_options & SO_DEBUG)
2151 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2152 &tcp_savetcp, 0);
2153#endif
2154
2155 /*
2156 * Return any desired output.
2157 */
2158 if (needoutput || (tp->t_flags & TF_ACKNOW))
2159 (void) tcp_output(tp);
2160 return;
2161
2162dropafterack:
2163 /*
2164 * Generate an ACK dropping incoming segment if it occupies
2165 * sequence space, where the ACK reflects our state.
2166 *
2167 * We can now skip the test for the RST flag since all
2168 * paths to this code happen after packets containing
2169 * RST have been dropped.
2170 *
2171 * In the SYN-RECEIVED state, don't send an ACK unless the
2172 * segment we received passes the SYN-RECEIVED ACK test.
2173 * If it fails send a RST. This breaks the loop in the
2174 * "LAND" DoS attack, and also prevents an ACK storm
2175 * between two listening ports that have been sent forged
2176 * SYN segments, each with the source address of the other.
2177 */
2178 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2179 (SEQ_GT(tp->snd_una, th->th_ack) ||
2180 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2181 rstreason = BANDLIM_RST_OPENPORT;
2182 goto dropwithreset;
2183 }
2184#ifdef TCPDEBUG
2185 if (so->so_options & SO_DEBUG)
2186 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2187 &tcp_savetcp, 0);
2188#endif
2189 m_freem(m);
2190 tp->t_flags |= TF_ACKNOW;
2191 (void) tcp_output(tp);
2192 return;
2193
2194dropwithreset:
2195 /*
2196 * Generate a RST, dropping incoming segment.
2197 * Make ACK acceptable to originator of segment.
2198 * Don't bother to respond if destination was broadcast/multicast.
2199 */
2200 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2201 goto drop;
2202 if (isipv6) {
2203 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2204 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2205 goto drop;
2206 } else {
2207 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2208 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2209 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2210 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2211 goto drop;
2212 }
2213 /* IPv6 anycast check is done at tcp6_input() */
2214
2215 /*
2216 * Perform bandwidth limiting.
2217 */
2218#ifdef ICMP_BANDLIM
2219 if (badport_bandlim(rstreason) < 0)
2220 goto drop;
2221#endif
2222
2223#ifdef TCPDEBUG
2224 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2225 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2226 &tcp_savetcp, 0);
2227#endif
2228 if (thflags & TH_ACK)
2229 /* mtod() below is safe as long as hdr dropping is delayed */
2230 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2231 TH_RST);
2232 else {
2233 if (thflags & TH_SYN)
2234 tlen++;
2235 /* mtod() below is safe as long as hdr dropping is delayed */
2236 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2237 (tcp_seq)0, TH_RST|TH_ACK);
2238 }
2239 return;
2240
2241drop:
2242 /*
2243 * Drop space held by incoming segment and return.
2244 */
2245#ifdef TCPDEBUG
2246 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2247 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2248 &tcp_savetcp, 0);
2249#endif
2250 m_freem(m);
2251 return;
2252}
2253
2254/*
2255 * Parse TCP options and place in tcpopt.
2256 */
2257static void
2258tcp_dooptions(to, cp, cnt, is_syn)
2259 struct tcpopt *to;
2260 u_char *cp;
2261 int cnt;
2262{
2263 int opt, optlen;
2264
2265 to->to_flags = 0;
2266 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2267 opt = cp[0];
2268 if (opt == TCPOPT_EOL)
2269 break;
2270 if (opt == TCPOPT_NOP)
2271 optlen = 1;
2272 else {
2273 if (cnt < 2)
2274 break;
2275 optlen = cp[1];
2276 if (optlen < 2 || optlen > cnt)
2277 break;
2278 }
2279 switch (opt) {
2280 case TCPOPT_MAXSEG:
2281 if (optlen != TCPOLEN_MAXSEG)
2282 continue;
2283 if (!is_syn)
2284 continue;
2285 to->to_flags |= TOF_MSS;
2286 bcopy((char *)cp + 2,
2287 (char *)&to->to_mss, sizeof(to->to_mss));
2288 to->to_mss = ntohs(to->to_mss);
2289 break;
2290 case TCPOPT_WINDOW:
2291 if (optlen != TCPOLEN_WINDOW)
2292 continue;
2293 if (! is_syn)
2294 continue;
2295 to->to_flags |= TOF_SCALE;
2296 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2297 break;
2298 case TCPOPT_TIMESTAMP:
2299 if (optlen != TCPOLEN_TIMESTAMP)
2300 continue;
2301 to->to_flags |= TOF_TS;
2302 bcopy((char *)cp + 2,
2303 (char *)&to->to_tsval, sizeof(to->to_tsval));
2304 to->to_tsval = ntohl(to->to_tsval);
2305 bcopy((char *)cp + 6,
2306 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2307 to->to_tsecr = ntohl(to->to_tsecr);
2308 break;
2309 case TCPOPT_CC:
2310 if (optlen != TCPOLEN_CC)
2311 continue;
2312 to->to_flags |= TOF_CC;
2313 bcopy((char *)cp + 2,
2314 (char *)&to->to_cc, sizeof(to->to_cc));
2315 to->to_cc = ntohl(to->to_cc);
2316 break;
2317 case TCPOPT_CCNEW:
2318 if (optlen != TCPOLEN_CC)
2319 continue;
2320 if (!is_syn)
2321 continue;
2322 to->to_flags |= TOF_CCNEW;
2323 bcopy((char *)cp + 2,
2324 (char *)&to->to_cc, sizeof(to->to_cc));
2325 to->to_cc = ntohl(to->to_cc);
2326 break;
2327 case TCPOPT_CCECHO:
2328 if (optlen != TCPOLEN_CC)
2329 continue;
2330 if (!is_syn)
2331 continue;
2332 to->to_flags |= TOF_CCECHO;
2333 bcopy((char *)cp + 2,
2334 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2335 to->to_ccecho = ntohl(to->to_ccecho);
2336 break;
2337 default:
2338 continue;
2339 }
2340 }
2341}
2342
2343/*
2344 * Pull out of band byte out of a segment so
2345 * it doesn't appear in the user's data queue.
2346 * It is still reflected in the segment length for
2347 * sequencing purposes.
2348 */
2349static void
2350tcp_pulloutofband(so, th, m, off)
2351 struct socket *so;
2352 struct tcphdr *th;
2353 register struct mbuf *m;
2354 int off; /* delayed to be droped hdrlen */
2355{
2356 int cnt = off + th->th_urp - 1;
2357
2358 while (cnt >= 0) {
2359 if (m->m_len > cnt) {
2360 char *cp = mtod(m, caddr_t) + cnt;
2361 struct tcpcb *tp = sototcpcb(so);
2362
2363 tp->t_iobc = *cp;
2364 tp->t_oobflags |= TCPOOB_HAVEDATA;
2365 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2366 m->m_len--;
2367 if (m->m_flags & M_PKTHDR)
2368 m->m_pkthdr.len--;
2369 return;
2370 }
2371 cnt -= m->m_len;
2372 m = m->m_next;
2373 if (m == 0)
2374 break;
2375 }
2376 panic("tcp_pulloutofband");
2377}
2378
2379/*
2380 * Collect new round-trip time estimate
2381 * and update averages and current timeout.
2382 */
2383static void
2384tcp_xmit_timer(tp, rtt)
2385 register struct tcpcb *tp;
2386 int rtt;
2387{
2388 register int delta;
2389
2390 tcpstat.tcps_rttupdated++;
2391 tp->t_rttupdated++;
2392 if (tp->t_srtt != 0) {
2393 /*
2394 * srtt is stored as fixed point with 5 bits after the
2395 * binary point (i.e., scaled by 8). The following magic
2396 * is equivalent to the smoothing algorithm in rfc793 with
2397 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2398 * point). Adjust rtt to origin 0.
2399 */
2400 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2401 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2402
2403 if ((tp->t_srtt += delta) <= 0)
2404 tp->t_srtt = 1;
2405
2406 /*
2407 * We accumulate a smoothed rtt variance (actually, a
2408 * smoothed mean difference), then set the retransmit
2409 * timer to smoothed rtt + 4 times the smoothed variance.
2410 * rttvar is stored as fixed point with 4 bits after the
2411 * binary point (scaled by 16). The following is
2412 * equivalent to rfc793 smoothing with an alpha of .75
2413 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2414 * rfc793's wired-in beta.
2415 */
2416 if (delta < 0)
2417 delta = -delta;
2418 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2419 if ((tp->t_rttvar += delta) <= 0)
2420 tp->t_rttvar = 1;
2421 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2422 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2423 } else {
2424 /*
2425 * No rtt measurement yet - use the unsmoothed rtt.
2426 * Set the variance to half the rtt (so our first
2427 * retransmit happens at 3*rtt).
2428 */
2429 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2430 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2431 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2432 }
2433 tp->t_rtttime = 0;
2434 tp->t_rxtshift = 0;
2435
2436 /*
2437 * the retransmit should happen at rtt + 4 * rttvar.
2438 * Because of the way we do the smoothing, srtt and rttvar
2439 * will each average +1/2 tick of bias. When we compute
2440 * the retransmit timer, we want 1/2 tick of rounding and
2441 * 1 extra tick because of +-1/2 tick uncertainty in the
2442 * firing of the timer. The bias will give us exactly the
2443 * 1.5 tick we need. But, because the bias is
2444 * statistical, we have to test that we don't drop below
2445 * the minimum feasible timer (which is 2 ticks).
2446 */
2447 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2448 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2449
2450 /*
2451 * We received an ack for a packet that wasn't retransmitted;
2452 * it is probably safe to discard any error indications we've
2453 * received recently. This isn't quite right, but close enough
2454 * for now (a route might have failed after we sent a segment,
2455 * and the return path might not be symmetrical).
2456 */
2457 tp->t_softerror = 0;
2458}
2459
2460/*
2461 * Determine a reasonable value for maxseg size.
2462 * If the route is known, check route for mtu.
2463 * If none, use an mss that can be handled on the outgoing
2464 * interface without forcing IP to fragment; if bigger than
2465 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2466 * to utilize large mbufs. If no route is found, route has no mtu,
2467 * or the destination isn't local, use a default, hopefully conservative
2468 * size (usually 512 or the default IP max size, but no more than the mtu
2469 * of the interface), as we can't discover anything about intervening
2470 * gateways or networks. We also initialize the congestion/slow start
2471 * window to be a single segment if the destination isn't local.
2472 * While looking at the routing entry, we also initialize other path-dependent
2473 * parameters from pre-set or cached values in the routing entry.
2474 *
2475 * Also take into account the space needed for options that we
2476 * send regularly. Make maxseg shorter by that amount to assure
2477 * that we can send maxseg amount of data even when the options
2478 * are present. Store the upper limit of the length of options plus
2479 * data in maxopd.
2480 *
2481 * NOTE that this routine is only called when we process an incoming
2482 * segment, for outgoing segments only tcp_mssopt is called.
2483 *
2484 * In case of T/TCP, we call this routine during implicit connection
2485 * setup as well (offer = -1), to initialize maxseg from the cached
2486 * MSS of our peer.
2487 */
2488void
2489tcp_mss(tp, offer)
2490 struct tcpcb *tp;
2491 int offer;
2492{
2493 register struct rtentry *rt;
2494 struct ifnet *ifp;
2495 register int rtt, mss;
2496 u_long bufsize;
2497 struct inpcb *inp = tp->t_inpcb;
2498 struct socket *so;
2499 struct rmxp_tao *taop;
2500 int origoffer = offer;
2501#ifdef INET6
2502 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2503 size_t min_protoh = isipv6 ?
2504 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2505 sizeof(struct tcpiphdr);
2506#else
2507 const int isipv6 = 0;
2508 const size_t min_protoh = sizeof(struct tcpiphdr);
2509#endif
2510
2511 if (isipv6)
2512 rt = tcp_rtlookup6(&inp->inp_inc);
2513 else
2514 rt = tcp_rtlookup(&inp->inp_inc);
2515 if (rt == NULL) {
2516 tp->t_maxopd = tp->t_maxseg =
2517 isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2518 return;
2519 }
2520 ifp = rt->rt_ifp;
2521 so = inp->inp_socket;
2522
2523 taop = rmx_taop(rt->rt_rmx);
2524 /*
2525 * Offer == -1 means that we didn't receive SYN yet,
2526 * use cached value in that case;
2527 */
2528 if (offer == -1)
2529 offer = taop->tao_mssopt;
2530 /*
2531 * Offer == 0 means that there was no MSS on the SYN segment,
2532 * in this case we use tcp_mssdflt.
2533 */
2534 if (offer == 0)
2535 offer = isipv6 ? tcp_v6mssdflt : tcp_mssdflt;
2536 else
2537 /*
2538 * Sanity check: make sure that maxopd will be large
2539 * enough to allow some data on segments even is the
2540 * all the option space is used (40bytes). Otherwise
2541 * funny things may happen in tcp_output.
2542 */
2543 offer = max(offer, 64);
2544 taop->tao_mssopt = offer;
2545
2546 /*
2547 * While we're here, check if there's an initial rtt
2548 * or rttvar. Convert from the route-table units
2549 * to scaled multiples of the slow timeout timer.
2550 */
2551 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2552 /*
2553 * XXX the lock bit for RTT indicates that the value
2554 * is also a minimum value; this is subject to time.
2555 */
2556 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2557 tp->t_rttmin = rtt / (RTM_RTTUNIT / hz);
2558 tp->t_srtt = rtt / (RTM_RTTUNIT / (hz * TCP_RTT_SCALE));
2559 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
2560 tcpstat.tcps_usedrtt++;
2561 if (rt->rt_rmx.rmx_rttvar) {
2562 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2563 (RTM_RTTUNIT / (hz * TCP_RTTVAR_SCALE));
2564 tcpstat.tcps_usedrttvar++;
2565 } else {
2566 /* default variation is +- 1 rtt */
2567 tp->t_rttvar =
2568 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2569 }
2570 TCPT_RANGESET(tp->t_rxtcur,
2571 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2572 tp->t_rttmin, TCPTV_REXMTMAX);
2573 }
2574 /*
2575 * if there's an mtu associated with the route, use it
2576 * else, use the link mtu.
2577 */
2578 if (rt->rt_rmx.rmx_mtu)
2579 mss = rt->rt_rmx.rmx_mtu - min_protoh;
2580 else {
2581 if (isipv6) {
2582 mss = nd_ifinfo[rt->rt_ifp->if_index].linkmtu -
2583 min_protoh;
2584 if (!in6_localaddr(&inp->in6p_faddr))
2585 mss = min(mss, tcp_v6mssdflt);
2586 } else {
2587 mss = ifp->if_mtu - min_protoh;
2588 if (!in_localaddr(inp->inp_faddr))
2589 mss = min(mss, tcp_mssdflt);
2590 }
2591 }
2592 mss = min(mss, offer);
2593 /*
2594 * maxopd stores the maximum length of data AND options
2595 * in a segment; maxseg is the amount of data in a normal
2596 * segment. We need to store this value (maxopd) apart
2597 * from maxseg, because now every segment carries options
2598 * and thus we normally have somewhat less data in segments.
2599 */
2600 tp->t_maxopd = mss;
2601
2602 /*
2603 * In case of T/TCP, origoffer==-1 indicates, that no segments
2604 * were received yet. In this case we just guess, otherwise
2605 * we do the same as before T/TCP.
2606 */
2607 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2608 (origoffer == -1 ||
2609 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2610 mss -= TCPOLEN_TSTAMP_APPA;
2611 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2612 (origoffer == -1 ||
2613 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2614 mss -= TCPOLEN_CC_APPA;
2615
2616#if (MCLBYTES & (MCLBYTES - 1)) == 0
2617 if (mss > MCLBYTES)
2618 mss &= ~(MCLBYTES-1);
2619#else
2620 if (mss > MCLBYTES)
2621 mss = mss / MCLBYTES * MCLBYTES;
2622#endif
2623 /*
2624 * If there's a pipesize, change the socket buffer
2625 * to that size. Make the socket buffers an integral
2626 * number of mss units; if the mss is larger than
2627 * the socket buffer, decrease the mss.
2628 */
2629#ifdef RTV_SPIPE
2630 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2631#endif
2632 bufsize = so->so_snd.sb_hiwat;
2633 if (bufsize < mss)
2634 mss = bufsize;
2635 else {
2636 bufsize = roundup(bufsize, mss);
2637 if (bufsize > sb_max)
2638 bufsize = sb_max;
2639 if (bufsize > so->so_snd.sb_hiwat)
2640 (void)sbreserve(&so->so_snd, bufsize, so, NULL);
2641 }
2642 tp->t_maxseg = mss;
2643
2644#ifdef RTV_RPIPE
2645 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2646#endif
2647 bufsize = so->so_rcv.sb_hiwat;
2648 if (bufsize > mss) {
2649 bufsize = roundup(bufsize, mss);
2650 if (bufsize > sb_max)
2651 bufsize = sb_max;
2652 if (bufsize > so->so_rcv.sb_hiwat)
2653 (void)sbreserve(&so->so_rcv, bufsize, so, NULL);
2654 }
2655
2656 /*
2657 * Set the slow-start flight size depending on whether this
2658 * is a local network or not.
2659 */
2660 if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
2661 (!isipv6 && in_localaddr(inp->inp_faddr)))
2662 tp->snd_cwnd = mss * ss_fltsz_local;
2663 else
2664 tp->snd_cwnd = mss * ss_fltsz;
2665
2666 if (rt->rt_rmx.rmx_ssthresh) {
2667 /*
2668 * There's some sort of gateway or interface
2669 * buffer limit on the path. Use this to set
2670 * the slow start threshhold, but set the
2671 * threshold to no less than 2*mss.
2672 */
2673 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2674 tcpstat.tcps_usedssthresh++;
2675 }
2676}
2677
2678/*
2679 * Determine the MSS option to send on an outgoing SYN.
2680 */
2681int
2682tcp_mssopt(tp)
2683 struct tcpcb *tp;
2684{
2685 struct rtentry *rt;
2686#ifdef INET6
2687 int isipv6 = ((tp->t_inpcb->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2688 int min_protoh = isipv6 ?
2689 sizeof(struct ip6_hdr) + sizeof(struct tcphdr) :
2690 sizeof(struct tcpiphdr);
2691#else
2692 const int isipv6 = 0;
2693 const size_t min_protoh = sizeof(struct tcpiphdr);
2694#endif
2695
2696 if (isipv6)
2697 rt = tcp_rtlookup6(&tp->t_inpcb->inp_inc);
2698 else
2699 rt = tcp_rtlookup(&tp->t_inpcb->inp_inc);
2700 if (rt == NULL)
2701 return (isipv6 ? tcp_v6mssdflt : tcp_mssdflt);
2702
2703 return (rt->rt_ifp->if_mtu - min_protoh);
2704}
2705
2706
2707/*
2708 * When a partial ack arrives, force the retransmission of the
2709 * next unacknowledged segment. Do not clear tp->t_dupacks.
2710 * By setting snd_nxt to ti_ack, this forces retransmission timer to
2711 * be started again.
2712 */
2713static void
2714tcp_newreno_partial_ack(tp, th)
2715 struct tcpcb *tp;
2716 struct tcphdr *th;
2717{
2718 tcp_seq onxt = tp->snd_nxt;
2719 u_long ocwnd = tp->snd_cwnd;
2720
2721 callout_stop(tp->tt_rexmt);
2722 tp->t_rtttime = 0;
2723 tp->snd_nxt = th->th_ack;
2724 /*
2725 * Set snd_cwnd to one segment beyond acknowledged offset
2726 * (tp->snd_una has not yet been updated when this function is called.)
2727 */
2728 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
2729 tp->t_flags |= TF_ACKNOW;
2730 (void) tcp_output(tp);
2731 tp->snd_cwnd = ocwnd;
2732 if (SEQ_GT(onxt, tp->snd_nxt))
2733 tp->snd_nxt = onxt;
2734 /*
2735 * Partial window deflation. Relies on fact that tp->snd_una
2736 * not updated yet.
2737 */
2738 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_maxseg);
2739}