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