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 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
30 * $FreeBSD: releng/6.4/sys/netinet/tcp_input.c 182971 2008-09-12 19:36:37Z bz $
31 */
32
33 #include "opt_ipfw.h" /* for ipfw_fwd */
34 #include "opt_inet.h"
35 #include "opt_inet6.h"
36 #include "opt_ipsec.h"
37 #include "opt_mac.h"
38 #include "opt_tcpdebug.h"
39 #include "opt_tcp_input.h"
40 #include "opt_tcp_sack.h"
41
42 #include <sys/param.h>
43 #include <sys/kernel.h>
44 #include <sys/mac.h>
45 #include <sys/malloc.h>
46 #include <sys/mbuf.h>
47 #include <sys/proc.h> /* for proc0 declaration */
48 #include <sys/protosw.h>
49 #include <sys/signalvar.h>
50 #include <sys/socket.h>
51 #include <sys/socketvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/syslog.h>
54 #include <sys/systm.h>
55
56 #include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
57
58 #include <vm/uma.h>
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 static const int tcprexmtthresh = 3;
101
102 struct tcpstat tcpstat;
103 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
104 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
105
106 static int log_in_vain = 0;
107 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
108 &log_in_vain, 0, "Log all incoming TCP connections");
109
110 static int blackhole = 0;
111 SYSCTL_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
112 &blackhole, 0, "Do not send RST when dropping refused connections");
113
114 int tcp_delack_enabled = 1;
115 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
116 &tcp_delack_enabled, 0,
117 "Delay ACK to try and piggyback it onto a data packet");
118
119 #ifdef TCP_DROP_SYNFIN
120 static int drop_synfin = 0;
121 SYSCTL_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
122 &drop_synfin, 0, "Drop TCP packets with SYN+FIN set");
123 #endif
124
125 static int tcp_do_rfc3042 = 1;
126 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
127 &tcp_do_rfc3042, 0, "Enable RFC 3042 (Limited Transmit)");
128
129 static int tcp_do_rfc3390 = 1;
130 SYSCTL_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
131 &tcp_do_rfc3390, 0,
132 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
133
134 static int tcp_insecure_rst = 0;
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
136 &tcp_insecure_rst, 0,
137 "Follow the old (insecure) criteria for accepting RST packets.");
138
139 SYSCTL_NODE(_net_inet_tcp, OID_AUTO, reass, CTLFLAG_RW, 0,
140 "TCP Segment Reassembly Queue");
141
142 static int tcp_reass_maxseg = 0;
143 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxsegments, CTLFLAG_RDTUN,
144 &tcp_reass_maxseg, 0,
145 "Global maximum number of TCP Segments in Reassembly Queue");
146
147 int tcp_reass_qsize = 0;
148 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, cursegments, CTLFLAG_RD,
149 &tcp_reass_qsize, 0,
150 "Global number of TCP Segments currently in Reassembly Queue");
151
152 static int tcp_reass_maxqlen = 48;
153 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, maxqlen, CTLFLAG_RW,
154 &tcp_reass_maxqlen, 0,
155 "Maximum number of TCP Segments per individual Reassembly Queue");
156
157 static int tcp_reass_overflows = 0;
158 SYSCTL_INT(_net_inet_tcp_reass, OID_AUTO, overflows, CTLFLAG_RD,
159 &tcp_reass_overflows, 0,
160 "Global number of TCP Segment Reassembly Queue Overflows");
161
162 struct inpcbhead tcb;
163 #define tcb6 tcb /* for KAME src sync over BSD*'s */
164 struct inpcbinfo tcbinfo;
165 struct mtx *tcbinfo_mtx;
166
167 static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
168
169 static void tcp_pulloutofband(struct socket *,
170 struct tcphdr *, struct mbuf *, int);
171 static int tcp_reass(struct tcpcb *, struct tcphdr *, int *,
172 struct mbuf *);
173 static void tcp_xmit_timer(struct tcpcb *, int);
174 static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
175 static int tcp_timewait(struct tcptw *, struct tcpopt *,
176 struct tcphdr *, struct mbuf *, int);
177
178 /* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
179 #ifdef INET6
180 #define ND6_HINT(tp) \
181 do { \
182 if ((tp) && (tp)->t_inpcb && \
183 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
184 nd6_nud_hint(NULL, NULL, 0); \
185 } while (0)
186 #else
187 #define ND6_HINT(tp)
188 #endif
189
190 /*
191 * Indicate whether this ack should be delayed. We can delay the ack if
192 * - there is no delayed ack timer in progress and
193 * - our last ack wasn't a 0-sized window. We never want to delay
194 * the ack that opens up a 0-sized window and
195 * - delayed acks are enabled or
196 * - this is a half-synchronized T/TCP connection.
197 */
198 #define DELAY_ACK(tp) \
199 ((!callout_active(tp->tt_delack) && \
200 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
201 (tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
202
203 /* Initialize TCP reassembly queue */
204 static void
205 tcp_reass_zone_change(void *tag)
206 {
207
208 tcp_reass_maxseg = nmbclusters / 16;
209 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
210 }
211
212 uma_zone_t tcp_reass_zone;
213 void
214 tcp_reass_init()
215 {
216 tcp_reass_maxseg = nmbclusters / 16;
217 TUNABLE_INT_FETCH("net.inet.tcp.reass.maxsegments",
218 &tcp_reass_maxseg);
219 tcp_reass_zone = uma_zcreate("tcpreass", sizeof (struct tseg_qent),
220 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
221 uma_zone_set_max(tcp_reass_zone, tcp_reass_maxseg);
222 EVENTHANDLER_REGISTER(nmbclusters_change,
223 tcp_reass_zone_change, NULL, EVENTHANDLER_PRI_ANY);
224 }
225
226 static int
227 tcp_reass(tp, th, tlenp, m)
228 register struct tcpcb *tp;
229 register struct tcphdr *th;
230 int *tlenp;
231 struct mbuf *m;
232 {
233 struct tseg_qent *q;
234 struct tseg_qent *p = NULL;
235 struct tseg_qent *nq;
236 struct tseg_qent *te = NULL;
237 struct socket *so = tp->t_inpcb->inp_socket;
238 int flags;
239
240 INP_LOCK_ASSERT(tp->t_inpcb);
241
242 /*
243 * XXX: tcp_reass() is rather inefficient with its data structures
244 * and should be rewritten (see NetBSD for optimizations). While
245 * doing that it should move to its own file tcp_reass.c.
246 */
247
248 /*
249 * Call with th==NULL after become established to
250 * force pre-ESTABLISHED data up to user socket.
251 */
252 if (th == NULL)
253 goto present;
254
255 /*
256 * Limit the number of segments in the reassembly queue to prevent
257 * holding on to too many segments (and thus running out of mbufs).
258 * Make sure to let the missing segment through which caused this
259 * queue. Always keep one global queue entry spare to be able to
260 * process the missing segment.
261 */
262 if (th->th_seq != tp->rcv_nxt &&
263 (tcp_reass_qsize + 1 >= tcp_reass_maxseg ||
264 tp->t_segqlen >= tcp_reass_maxqlen)) {
265 tcp_reass_overflows++;
266 tcpstat.tcps_rcvmemdrop++;
267 m_freem(m);
268 *tlenp = 0;
269 return (0);
270 }
271
272 /*
273 * Allocate a new queue entry. If we can't, or hit the zone limit
274 * just drop the pkt.
275 */
276 te = uma_zalloc(tcp_reass_zone, M_NOWAIT);
277 if (te == NULL) {
278 tcpstat.tcps_rcvmemdrop++;
279 m_freem(m);
280 *tlenp = 0;
281 return (0);
282 }
283 tp->t_segqlen++;
284 tcp_reass_qsize++;
285
286 /*
287 * Find a segment which begins after this one does.
288 */
289 LIST_FOREACH(q, &tp->t_segq, tqe_q) {
290 if (SEQ_GT(q->tqe_th->th_seq, th->th_seq))
291 break;
292 p = q;
293 }
294
295 /*
296 * If there is a preceding segment, it may provide some of
297 * our data already. If so, drop the data from the incoming
298 * segment. If it provides all of our data, drop us.
299 */
300 if (p != NULL) {
301 register int i;
302 /* conversion to int (in i) handles seq wraparound */
303 i = p->tqe_th->th_seq + p->tqe_len - th->th_seq;
304 if (i > 0) {
305 if (i >= *tlenp) {
306 tcpstat.tcps_rcvduppack++;
307 tcpstat.tcps_rcvdupbyte += *tlenp;
308 m_freem(m);
309 uma_zfree(tcp_reass_zone, te);
310 tp->t_segqlen--;
311 tcp_reass_qsize--;
312 /*
313 * Try to present any queued data
314 * at the left window edge to the user.
315 * This is needed after the 3-WHS
316 * completes.
317 */
318 goto present; /* ??? */
319 }
320 m_adj(m, i);
321 *tlenp -= i;
322 th->th_seq += i;
323 }
324 }
325 tcpstat.tcps_rcvoopack++;
326 tcpstat.tcps_rcvoobyte += *tlenp;
327
328 /*
329 * While we overlap succeeding segments trim them or,
330 * if they are completely covered, dequeue them.
331 */
332 while (q) {
333 register int i = (th->th_seq + *tlenp) - q->tqe_th->th_seq;
334 if (i <= 0)
335 break;
336 if (i < q->tqe_len) {
337 q->tqe_th->th_seq += i;
338 q->tqe_len -= i;
339 m_adj(q->tqe_m, i);
340 break;
341 }
342
343 nq = LIST_NEXT(q, tqe_q);
344 LIST_REMOVE(q, tqe_q);
345 m_freem(q->tqe_m);
346 uma_zfree(tcp_reass_zone, q);
347 tp->t_segqlen--;
348 tcp_reass_qsize--;
349 q = nq;
350 }
351
352 /* Insert the new segment queue entry into place. */
353 te->tqe_m = m;
354 te->tqe_th = th;
355 te->tqe_len = *tlenp;
356
357 if (p == NULL) {
358 LIST_INSERT_HEAD(&tp->t_segq, te, tqe_q);
359 } else {
360 LIST_INSERT_AFTER(p, te, tqe_q);
361 }
362
363 present:
364 /*
365 * Present data to user, advancing rcv_nxt through
366 * completed sequence space.
367 */
368 if (!TCPS_HAVEESTABLISHED(tp->t_state))
369 return (0);
370 q = LIST_FIRST(&tp->t_segq);
371 if (!q || q->tqe_th->th_seq != tp->rcv_nxt)
372 return (0);
373 SOCKBUF_LOCK(&so->so_rcv);
374 do {
375 tp->rcv_nxt += q->tqe_len;
376 flags = q->tqe_th->th_flags & TH_FIN;
377 nq = LIST_NEXT(q, tqe_q);
378 LIST_REMOVE(q, tqe_q);
379 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
380 m_freem(q->tqe_m);
381 else
382 sbappendstream_locked(&so->so_rcv, q->tqe_m);
383 uma_zfree(tcp_reass_zone, q);
384 tp->t_segqlen--;
385 tcp_reass_qsize--;
386 q = nq;
387 } while (q && q->tqe_th->th_seq == tp->rcv_nxt);
388 ND6_HINT(tp);
389 sorwakeup_locked(so);
390 return (flags);
391 }
392
393 /*
394 * TCP input routine, follows pages 65-76 of the
395 * protocol specification dated September, 1981 very closely.
396 */
397 #ifdef INET6
398 int
399 tcp6_input(mp, offp, proto)
400 struct mbuf **mp;
401 int *offp, proto;
402 {
403 register struct mbuf *m = *mp;
404 struct in6_ifaddr *ia6;
405
406 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
407
408 /*
409 * draft-itojun-ipv6-tcp-to-anycast
410 * better place to put this in?
411 */
412 ia6 = ip6_getdstifaddr(m);
413 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
414 struct ip6_hdr *ip6;
415
416 ip6 = mtod(m, struct ip6_hdr *);
417 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
418 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
419 return IPPROTO_DONE;
420 }
421
422 tcp_input(m, *offp);
423 return IPPROTO_DONE;
424 }
425 #endif
426
427 void
428 tcp_input(m, off0)
429 register struct mbuf *m;
430 int off0;
431 {
432 register struct tcphdr *th;
433 register struct ip *ip = NULL;
434 register struct ipovly *ipov;
435 register struct inpcb *inp = NULL;
436 u_char *optp = NULL;
437 int optlen = 0;
438 int len, tlen, off;
439 int drop_hdrlen;
440 register struct tcpcb *tp = 0;
441 register int thflags;
442 struct socket *so = 0;
443 int todrop, acked, ourfinisacked, needoutput = 0;
444 u_long tiwin;
445 struct tcpopt to; /* options in this segment */
446 int headlocked = 0;
447 #ifdef IPFIREWALL_FORWARD
448 struct m_tag *fwd_tag;
449 #endif
450 int rstreason; /* For badport_bandlim accounting purposes */
451
452 struct ip6_hdr *ip6 = NULL;
453 #ifdef INET6
454 int isipv6;
455 #else
456 const int isipv6 = 0;
457 #endif
458
459 #ifdef TCPDEBUG
460 /*
461 * The size of tcp_saveipgen must be the size of the max ip header,
462 * now IPv6.
463 */
464 u_char tcp_saveipgen[40];
465 struct tcphdr tcp_savetcp;
466 short ostate = 0;
467 #endif
468
469 #ifdef INET6
470 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
471 #endif
472 bzero((char *)&to, sizeof(to));
473
474 tcpstat.tcps_rcvtotal++;
475
476 if (isipv6) {
477 #ifdef INET6
478 /* IP6_EXTHDR_CHECK() is already done at tcp6_input() */
479 ip6 = mtod(m, struct ip6_hdr *);
480 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
481 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
482 tcpstat.tcps_rcvbadsum++;
483 goto drop;
484 }
485 th = (struct tcphdr *)((caddr_t)ip6 + off0);
486
487 /*
488 * Be proactive about unspecified IPv6 address in source.
489 * As we use all-zero to indicate unbounded/unconnected pcb,
490 * unspecified IPv6 address can be used to confuse us.
491 *
492 * Note that packets with unspecified IPv6 destination is
493 * already dropped in ip6_input.
494 */
495 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
496 /* XXX stat */
497 goto drop;
498 }
499 #else
500 th = NULL; /* XXX: avoid compiler warning */
501 #endif
502 } else {
503 /*
504 * Get IP and TCP header together in first mbuf.
505 * Note: IP leaves IP header in first mbuf.
506 */
507 if (off0 > sizeof (struct ip)) {
508 ip_stripoptions(m, (struct mbuf *)0);
509 off0 = sizeof(struct ip);
510 }
511 if (m->m_len < sizeof (struct tcpiphdr)) {
512 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
513 tcpstat.tcps_rcvshort++;
514 return;
515 }
516 }
517 ip = mtod(m, struct ip *);
518 ipov = (struct ipovly *)ip;
519 th = (struct tcphdr *)((caddr_t)ip + off0);
520 tlen = ip->ip_len;
521
522 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
523 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
524 th->th_sum = m->m_pkthdr.csum_data;
525 else
526 th->th_sum = in_pseudo(ip->ip_src.s_addr,
527 ip->ip_dst.s_addr,
528 htonl(m->m_pkthdr.csum_data +
529 ip->ip_len +
530 IPPROTO_TCP));
531 th->th_sum ^= 0xffff;
532 #ifdef TCPDEBUG
533 ipov->ih_len = (u_short)tlen;
534 ipov->ih_len = htons(ipov->ih_len);
535 #endif
536 } else {
537 /*
538 * Checksum extended TCP header and data.
539 */
540 len = sizeof (struct ip) + tlen;
541 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
542 ipov->ih_len = (u_short)tlen;
543 ipov->ih_len = htons(ipov->ih_len);
544 th->th_sum = in_cksum(m, len);
545 }
546 if (th->th_sum) {
547 tcpstat.tcps_rcvbadsum++;
548 goto drop;
549 }
550 #ifdef INET6
551 /* Re-initialization for later version check */
552 ip->ip_v = IPVERSION;
553 #endif
554 }
555
556 /*
557 * Check that TCP offset makes sense,
558 * pull out TCP options and adjust length. XXX
559 */
560 off = th->th_off << 2;
561 if (off < sizeof (struct tcphdr) || off > tlen) {
562 tcpstat.tcps_rcvbadoff++;
563 goto drop;
564 }
565 tlen -= off; /* tlen is used instead of ti->ti_len */
566 if (off > sizeof (struct tcphdr)) {
567 if (isipv6) {
568 #ifdef INET6
569 IP6_EXTHDR_CHECK(m, off0, off, );
570 ip6 = mtod(m, struct ip6_hdr *);
571 th = (struct tcphdr *)((caddr_t)ip6 + off0);
572 #endif
573 } else {
574 if (m->m_len < sizeof(struct ip) + off) {
575 if ((m = m_pullup(m, sizeof (struct ip) + off))
576 == 0) {
577 tcpstat.tcps_rcvshort++;
578 return;
579 }
580 ip = mtod(m, struct ip *);
581 ipov = (struct ipovly *)ip;
582 th = (struct tcphdr *)((caddr_t)ip + off0);
583 }
584 }
585 optlen = off - sizeof (struct tcphdr);
586 optp = (u_char *)(th + 1);
587 }
588 thflags = th->th_flags;
589
590 #ifdef TCP_DROP_SYNFIN
591 /*
592 * If the drop_synfin option is enabled, drop all packets with
593 * both the SYN and FIN bits set. This prevents e.g. nmap from
594 * identifying the TCP/IP stack.
595 *
596 * This is a violation of the TCP specification.
597 */
598 if (drop_synfin && (thflags & (TH_SYN|TH_FIN)) == (TH_SYN|TH_FIN))
599 goto drop;
600 #endif
601
602 /*
603 * Convert TCP protocol specific fields to host format.
604 */
605 th->th_seq = ntohl(th->th_seq);
606 th->th_ack = ntohl(th->th_ack);
607 th->th_win = ntohs(th->th_win);
608 th->th_urp = ntohs(th->th_urp);
609
610 /*
611 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options,
612 * until after ip6_savecontrol() is called and before other functions
613 * which don't want those proto headers.
614 * Because ip6_savecontrol() is going to parse the mbuf to
615 * search for data to be passed up to user-land, it wants mbuf
616 * parameters to be unchanged.
617 * XXX: the call of ip6_savecontrol() has been obsoleted based on
618 * latest version of the advanced API (20020110).
619 */
620 drop_hdrlen = off0 + off;
621
622 /*
623 * Locate pcb for segment.
624 */
625 INP_INFO_WLOCK(&tcbinfo);
626 headlocked = 1;
627 findpcb:
628 KASSERT(headlocked, ("tcp_input: findpcb: head not locked"));
629 #ifdef IPFIREWALL_FORWARD
630 /* Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain. */
631 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
632
633 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
634 struct sockaddr_in *next_hop;
635
636 next_hop = (struct sockaddr_in *)(fwd_tag+1);
637 /*
638 * Transparently forwarded. Pretend to be the destination.
639 * already got one like this?
640 */
641 inp = in_pcblookup_hash(&tcbinfo,
642 ip->ip_src, th->th_sport,
643 ip->ip_dst, th->th_dport,
644 0, m->m_pkthdr.rcvif);
645 if (!inp) {
646 /* It's new. Try to find the ambushing socket. */
647 inp = in_pcblookup_hash(&tcbinfo,
648 ip->ip_src, th->th_sport,
649 next_hop->sin_addr,
650 next_hop->sin_port ?
651 ntohs(next_hop->sin_port) :
652 th->th_dport,
653 1, m->m_pkthdr.rcvif);
654 }
655 /* Remove the tag from the packet. We don't need it anymore. */
656 m_tag_delete(m, fwd_tag);
657 } else {
658 #endif /* IPFIREWALL_FORWARD */
659 if (isipv6) {
660 #ifdef INET6
661 inp = in6_pcblookup_hash(&tcbinfo,
662 &ip6->ip6_src, th->th_sport,
663 &ip6->ip6_dst, th->th_dport,
664 1, m->m_pkthdr.rcvif);
665 #endif
666 } else
667 inp = in_pcblookup_hash(&tcbinfo,
668 ip->ip_src, th->th_sport,
669 ip->ip_dst, th->th_dport,
670 1, m->m_pkthdr.rcvif);
671 #ifdef IPFIREWALL_FORWARD
672 }
673 #endif /* IPFIREWALL_FORWARD */
674
675 #if defined(IPSEC) || defined(FAST_IPSEC)
676 #ifdef INET6
677 if (isipv6) {
678 if (inp != NULL && ipsec6_in_reject(m, inp)) {
679 #ifdef IPSEC
680 ipsec6stat.in_polvio++;
681 #endif
682 goto drop;
683 }
684 } else
685 #endif /* INET6 */
686 if (inp != NULL && ipsec4_in_reject(m, inp)) {
687 #ifdef IPSEC
688 ipsecstat.in_polvio++;
689 #endif
690 goto drop;
691 }
692 #endif /*IPSEC || FAST_IPSEC*/
693
694 /*
695 * If the state is CLOSED (i.e., TCB does not exist) then
696 * all data in the incoming segment is discarded.
697 * If the TCB exists but is in CLOSED state, it is embryonic,
698 * but should either do a listen or a connect soon.
699 */
700 if (inp == NULL) {
701 if (log_in_vain) {
702 #ifdef INET6
703 char dbuf[INET6_ADDRSTRLEN+2], sbuf[INET6_ADDRSTRLEN+2];
704 #else
705 char dbuf[4*sizeof "123"], sbuf[4*sizeof "123"];
706 #endif
707
708 if (isipv6) {
709 #ifdef INET6
710 strcpy(dbuf, "[");
711 strcpy(sbuf, "[");
712 strcat(dbuf, ip6_sprintf(&ip6->ip6_dst));
713 strcat(sbuf, ip6_sprintf(&ip6->ip6_src));
714 strcat(dbuf, "]");
715 strcat(sbuf, "]");
716 #endif
717 } else {
718 strcpy(dbuf, inet_ntoa(ip->ip_dst));
719 strcpy(sbuf, inet_ntoa(ip->ip_src));
720 }
721 switch (log_in_vain) {
722 case 1:
723 if ((thflags & TH_SYN) == 0)
724 break;
725 /* FALLTHROUGH */
726 case 2:
727 log(LOG_INFO,
728 "Connection attempt to TCP %s:%d "
729 "from %s:%d flags:0x%02x\n",
730 dbuf, ntohs(th->th_dport), sbuf,
731 ntohs(th->th_sport), thflags);
732 break;
733 default:
734 break;
735 }
736 }
737 if (blackhole) {
738 switch (blackhole) {
739 case 1:
740 if (thflags & TH_SYN)
741 goto drop;
742 break;
743 case 2:
744 goto drop;
745 default:
746 goto drop;
747 }
748 }
749 rstreason = BANDLIM_RST_CLOSEDPORT;
750 goto dropwithreset;
751 }
752 INP_LOCK(inp);
753
754 /* Check the minimum TTL for socket. */
755 if (inp->inp_ip_minttl != 0) {
756 #ifdef INET6
757 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
758 goto drop;
759 else
760 #endif
761 if (inp->inp_ip_minttl > ip->ip_ttl)
762 goto drop;
763 }
764
765 if (inp->inp_vflag & INP_TIMEWAIT) {
766 /*
767 * The only option of relevance is TOF_CC, and only if
768 * present in a SYN segment. See tcp_timewait().
769 */
770 if (thflags & TH_SYN)
771 tcp_dooptions(&to, optp, optlen, 1);
772 if (tcp_timewait((struct tcptw *)inp->inp_ppcb,
773 &to, th, m, tlen))
774 goto findpcb;
775 /*
776 * tcp_timewait unlocks inp.
777 */
778 INP_INFO_WUNLOCK(&tcbinfo);
779 return;
780 }
781 tp = intotcpcb(inp);
782 if (tp == 0) {
783 INP_UNLOCK(inp);
784 rstreason = BANDLIM_RST_CLOSEDPORT;
785 goto dropwithreset;
786 }
787 if (tp->t_state == TCPS_CLOSED)
788 goto drop;
789
790 /* Unscale the window into a 32-bit value. */
791 if ((thflags & TH_SYN) == 0)
792 tiwin = th->th_win << tp->snd_scale;
793 else
794 tiwin = th->th_win;
795
796 #ifdef MAC
797 INP_LOCK_ASSERT(inp);
798 if (mac_check_inpcb_deliver(inp, m))
799 goto drop;
800 #endif
801 so = inp->inp_socket;
802 KASSERT(so != NULL, ("tcp_input: so == NULL"));
803 #ifdef TCPDEBUG
804 if (so->so_options & SO_DEBUG) {
805 ostate = tp->t_state;
806 if (isipv6)
807 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
808 else
809 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
810 tcp_savetcp = *th;
811 }
812 #endif
813 if (so->so_options & SO_ACCEPTCONN) {
814 struct in_conninfo inc;
815
816 #ifdef INET6
817 inc.inc_isipv6 = isipv6;
818 #endif
819 if (isipv6) {
820 inc.inc6_faddr = ip6->ip6_src;
821 inc.inc6_laddr = ip6->ip6_dst;
822 } else {
823 inc.inc_faddr = ip->ip_src;
824 inc.inc_laddr = ip->ip_dst;
825 }
826 inc.inc_fport = th->th_sport;
827 inc.inc_lport = th->th_dport;
828
829 /*
830 * If the state is LISTEN then ignore segment if it contains
831 * a RST. If the segment contains an ACK then it is bad and
832 * send a RST. If it does not contain a SYN then it is not
833 * interesting; drop it.
834 *
835 * If the state is SYN_RECEIVED (syncache) and seg contains
836 * an ACK, but not for our SYN/ACK, send a RST. If the seg
837 * contains a RST, check the sequence number to see if it
838 * is a valid reset segment.
839 */
840 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
841 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
842 if (!syncache_expand(&inc, th, &so, m)) {
843 /*
844 * No syncache entry, or ACK was not
845 * for our SYN/ACK. Send a RST.
846 */
847 tcpstat.tcps_badsyn++;
848 rstreason = BANDLIM_RST_OPENPORT;
849 goto dropwithreset;
850 }
851 if (so == NULL) {
852 /*
853 * Could not complete 3-way handshake,
854 * connection is being closed down, and
855 * syncache will free mbuf.
856 */
857 INP_UNLOCK(inp);
858 INP_INFO_WUNLOCK(&tcbinfo);
859 return;
860 }
861 /*
862 * Socket is created in state SYN_RECEIVED.
863 * Continue processing segment.
864 */
865 INP_UNLOCK(inp);
866 inp = sotoinpcb(so);
867 INP_LOCK(inp);
868 tp = intotcpcb(inp);
869 /*
870 * This is what would have happened in
871 * tcp_output() when the SYN,ACK was sent.
872 */
873 tp->snd_up = tp->snd_una;
874 tp->snd_max = tp->snd_nxt = tp->iss + 1;
875 tp->last_ack_sent = tp->rcv_nxt;
876 /*
877 * RFC1323: The window in SYN & SYN/ACK
878 * segments is never scaled.
879 */
880 tp->snd_wnd = tiwin; /* unscaled */
881 goto after_listen;
882 }
883 if (thflags & TH_RST) {
884 syncache_chkrst(&inc, th);
885 goto drop;
886 }
887 if (thflags & TH_ACK) {
888 syncache_badack(&inc);
889 tcpstat.tcps_badsyn++;
890 rstreason = BANDLIM_RST_OPENPORT;
891 goto dropwithreset;
892 }
893 goto drop;
894 }
895
896 /*
897 * Segment's flags are (SYN) or (SYN|FIN).
898 */
899 #ifdef INET6
900 /*
901 * If deprecated address is forbidden,
902 * we do not accept SYN to deprecated interface
903 * address to prevent any new inbound connection from
904 * getting established.
905 * When we do not accept SYN, we send a TCP RST,
906 * with deprecated source address (instead of dropping
907 * it). We compromise it as it is much better for peer
908 * to send a RST, and RST will be the final packet
909 * for the exchange.
910 *
911 * If we do not forbid deprecated addresses, we accept
912 * the SYN packet. RFC2462 does not suggest dropping
913 * SYN in this case.
914 * If we decipher RFC2462 5.5.4, it says like this:
915 * 1. use of deprecated addr with existing
916 * communication is okay - "SHOULD continue to be
917 * used"
918 * 2. use of it with new communication:
919 * (2a) "SHOULD NOT be used if alternate address
920 * with sufficient scope is available"
921 * (2b) nothing mentioned otherwise.
922 * Here we fall into (2b) case as we have no choice in
923 * our source address selection - we must obey the peer.
924 *
925 * The wording in RFC2462 is confusing, and there are
926 * multiple description text for deprecated address
927 * handling - worse, they are not exactly the same.
928 * I believe 5.5.4 is the best one, so we follow 5.5.4.
929 */
930 if (isipv6 && !ip6_use_deprecated) {
931 struct in6_ifaddr *ia6;
932
933 if ((ia6 = ip6_getdstifaddr(m)) &&
934 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
935 INP_UNLOCK(inp);
936 tp = NULL;
937 rstreason = BANDLIM_RST_OPENPORT;
938 goto dropwithreset;
939 }
940 }
941 #endif
942 /*
943 * If it is from this socket, drop it, it must be forged.
944 * Don't bother responding if the destination was a broadcast.
945 */
946 if (th->th_dport == th->th_sport) {
947 if (isipv6) {
948 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
949 &ip6->ip6_src))
950 goto drop;
951 } else {
952 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
953 goto drop;
954 }
955 }
956 /*
957 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
958 *
959 * Note that it is quite possible to receive unicast
960 * link-layer packets with a broadcast IP address. Use
961 * in_broadcast() to find them.
962 */
963 if (m->m_flags & (M_BCAST|M_MCAST))
964 goto drop;
965 if (isipv6) {
966 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
967 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
968 goto drop;
969 } else {
970 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
971 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
972 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
973 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
974 goto drop;
975 }
976 /*
977 * SYN appears to be valid; create compressed TCP state
978 * for syncache, or perform t/tcp connection.
979 */
980 if (so->so_qlen <= so->so_qlimit) {
981 #ifdef TCPDEBUG
982 if (so->so_options & SO_DEBUG)
983 tcp_trace(TA_INPUT, ostate, tp,
984 (void *)tcp_saveipgen, &tcp_savetcp, 0);
985 #endif
986 tcp_dooptions(&to, optp, optlen, 1);
987 if (!syncache_add(&inc, &to, th, &so, m))
988 goto drop;
989 if (so == NULL) {
990 /*
991 * Entry added to syncache, mbuf used to
992 * send SYN,ACK packet.
993 */
994 KASSERT(headlocked, ("headlocked"));
995 INP_UNLOCK(inp);
996 INP_INFO_WUNLOCK(&tcbinfo);
997 return;
998 }
999 /*
1000 * Segment passed TAO tests.
1001 */
1002 INP_UNLOCK(inp);
1003 inp = sotoinpcb(so);
1004 INP_LOCK(inp);
1005 tp = intotcpcb(inp);
1006 tp->snd_wnd = tiwin;
1007 tp->t_starttime = ticks;
1008 tp->t_state = TCPS_ESTABLISHED;
1009
1010 /*
1011 * T/TCP logic:
1012 * If there is a FIN or if there is data, then
1013 * delay SYN,ACK(SYN) in the hope of piggy-backing
1014 * it on a response segment. Otherwise must send
1015 * ACK now in case the other side is slow starting.
1016 */
1017 if (thflags & TH_FIN || tlen != 0)
1018 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
1019 else
1020 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1021 tcpstat.tcps_connects++;
1022 soisconnected(so);
1023 goto trimthenstep6;
1024 }
1025 goto drop;
1026 }
1027 after_listen:
1028 KASSERT(headlocked, ("tcp_input: after_listen: head not locked"));
1029 INP_LOCK_ASSERT(inp);
1030
1031 /* Syncache takes care of sockets in the listen state. */
1032 KASSERT(tp->t_state != TCPS_LISTEN, ("tcp_input: TCPS_LISTEN"));
1033
1034 /*
1035 * This is the second part of the MSS DoS prevention code (after
1036 * minmss on the sending side) and it deals with too many too small
1037 * tcp packets in a too short timeframe (1 second).
1038 *
1039 * For every full second we count the number of received packets
1040 * and bytes. If we get a lot of packets per second for this connection
1041 * (tcp_minmssoverload) we take a closer look at it and compute the
1042 * average packet size for the past second. If that is less than
1043 * tcp_minmss we get too many packets with very small payload which
1044 * is not good and burdens our system (and every packet generates
1045 * a wakeup to the process connected to our socket). We can reasonable
1046 * expect this to be small packet DoS attack to exhaust our CPU
1047 * cycles.
1048 *
1049 * Care has to be taken for the minimum packet overload value. This
1050 * value defines the minimum number of packets per second before we
1051 * start to worry. This must not be too low to avoid killing for
1052 * example interactive connections with many small packets like
1053 * telnet or SSH.
1054 *
1055 * Setting either tcp_minmssoverload or tcp_minmss to "" disables
1056 * this check.
1057 *
1058 * Account for packet if payload packet, skip over ACK, etc.
1059 */
1060 if (tcp_minmss && tcp_minmssoverload &&
1061 tp->t_state == TCPS_ESTABLISHED && tlen > 0) {
1062 if ((unsigned int)(tp->rcv_second - ticks) < hz) {
1063 tp->rcv_pps++;
1064 tp->rcv_byps += tlen + off;
1065 if (tp->rcv_pps > tcp_minmssoverload) {
1066 if ((tp->rcv_byps / tp->rcv_pps) < tcp_minmss) {
1067 printf("too many small tcp packets from "
1068 "%s:%u, av. %lubyte/packet, "
1069 "dropping connection\n",
1070 #ifdef INET6
1071 isipv6 ?
1072 ip6_sprintf(&inp->inp_inc.inc6_faddr) :
1073 #endif
1074 inet_ntoa(inp->inp_inc.inc_faddr),
1075 inp->inp_inc.inc_fport,
1076 tp->rcv_byps / tp->rcv_pps);
1077 KASSERT(headlocked, ("tcp_input: "
1078 "after_listen: tcp_drop: head "
1079 "not locked"));
1080 tp = tcp_drop(tp, ECONNRESET);
1081 tcpstat.tcps_minmssdrops++;
1082 goto drop;
1083 }
1084 }
1085 } else {
1086 tp->rcv_second = ticks + hz;
1087 tp->rcv_pps = 1;
1088 tp->rcv_byps = tlen + off;
1089 }
1090 }
1091
1092 /*
1093 * Segment received on connection.
1094 * Reset idle time and keep-alive timer.
1095 */
1096 tp->t_rcvtime = ticks;
1097 if (TCPS_HAVEESTABLISHED(tp->t_state))
1098 callout_reset(tp->tt_keep, tcp_keepidle, tcp_timer_keep, tp);
1099
1100 /*
1101 * Process options only when we get SYN/ACK back. The SYN case
1102 * for incoming connections is handled in tcp_syncache.
1103 * XXX this is traditional behavior, may need to be cleaned up.
1104 */
1105 tcp_dooptions(&to, optp, optlen, thflags & TH_SYN);
1106 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1107 if (to.to_flags & TOF_SCALE) {
1108 tp->t_flags |= TF_RCVD_SCALE;
1109 tp->requested_s_scale = to.to_requested_s_scale;
1110 }
1111 if (to.to_flags & TOF_TS) {
1112 tp->t_flags |= TF_RCVD_TSTMP;
1113 tp->ts_recent = to.to_tsval;
1114 tp->ts_recent_age = ticks;
1115 }
1116 tp->snd_wnd = th->th_win; /* initial send window */
1117 if (to.to_flags & TOF_MSS)
1118 tcp_mss(tp, to.to_mss);
1119 if (tp->sack_enable) {
1120 if (!(to.to_flags & TOF_SACK))
1121 tp->sack_enable = 0;
1122 else
1123 tp->t_flags |= TF_SACK_PERMIT;
1124 }
1125
1126 }
1127
1128 /*
1129 * Header prediction: check for the two common cases
1130 * of a uni-directional data xfer. If the packet has
1131 * no control flags, is in-sequence, the window didn't
1132 * change and we're not retransmitting, it's a
1133 * candidate. If the length is zero and the ack moved
1134 * forward, we're the sender side of the xfer. Just
1135 * free the data acked & wake any higher level process
1136 * that was blocked waiting for space. If the length
1137 * is non-zero and the ack didn't move, we're the
1138 * receiver side. If we're getting packets in-order
1139 * (the reassembly queue is empty), add the data to
1140 * the socket buffer and note that we need a delayed ack.
1141 * Make sure that the hidden state-flags are also off.
1142 * Since we check for TCPS_ESTABLISHED above, it can only
1143 * be TH_NEEDSYN.
1144 */
1145 if (tp->t_state == TCPS_ESTABLISHED &&
1146 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1147 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1148 ((to.to_flags & TOF_TS) == 0 ||
1149 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
1150 th->th_seq == tp->rcv_nxt && tiwin && tiwin == tp->snd_wnd &&
1151 tp->snd_nxt == tp->snd_max) {
1152
1153 /*
1154 * If last ACK falls within this segment's sequence numbers,
1155 * record the timestamp.
1156 * NOTE that the test is modified according to the latest
1157 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1158 */
1159 if ((to.to_flags & TOF_TS) != 0 &&
1160 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1161 tp->ts_recent_age = ticks;
1162 tp->ts_recent = to.to_tsval;
1163 }
1164
1165 if (tlen == 0) {
1166 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1167 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1168 tp->snd_cwnd >= tp->snd_wnd &&
1169 ((!tcp_do_newreno && !tp->sack_enable &&
1170 tp->t_dupacks < tcprexmtthresh) ||
1171 ((tcp_do_newreno || tp->sack_enable) &&
1172 !IN_FASTRECOVERY(tp) && to.to_nsacks == 0 &&
1173 TAILQ_EMPTY(&tp->snd_holes)))) {
1174 KASSERT(headlocked, ("headlocked"));
1175 INP_INFO_WUNLOCK(&tcbinfo);
1176 headlocked = 0;
1177 /*
1178 * this is a pure ack for outstanding data.
1179 */
1180 ++tcpstat.tcps_predack;
1181 /*
1182 * "bad retransmit" recovery
1183 */
1184 if (tp->t_rxtshift == 1 &&
1185 ticks < tp->t_badrxtwin) {
1186 ++tcpstat.tcps_sndrexmitbad;
1187 tp->snd_cwnd = tp->snd_cwnd_prev;
1188 tp->snd_ssthresh =
1189 tp->snd_ssthresh_prev;
1190 tp->snd_recover = tp->snd_recover_prev;
1191 if (tp->t_flags & TF_WASFRECOVERY)
1192 ENTER_FASTRECOVERY(tp);
1193 tp->snd_nxt = tp->snd_max;
1194 tp->t_badrxtwin = 0;
1195 }
1196
1197 /*
1198 * Recalculate the transmit timer / rtt.
1199 *
1200 * Some boxes send broken timestamp replies
1201 * during the SYN+ACK phase, ignore
1202 * timestamps of 0 or we could calculate a
1203 * huge RTT and blow up the retransmit timer.
1204 */
1205 if ((to.to_flags & TOF_TS) != 0 &&
1206 to.to_tsecr) {
1207 if (!tp->t_rttlow ||
1208 tp->t_rttlow > ticks - to.to_tsecr)
1209 tp->t_rttlow = ticks - to.to_tsecr;
1210 tcp_xmit_timer(tp,
1211 ticks - to.to_tsecr + 1);
1212 } else if (tp->t_rtttime &&
1213 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1214 if (!tp->t_rttlow ||
1215 tp->t_rttlow > ticks - tp->t_rtttime)
1216 tp->t_rttlow = ticks - tp->t_rtttime;
1217 tcp_xmit_timer(tp,
1218 ticks - tp->t_rtttime);
1219 }
1220 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1221 acked = th->th_ack - tp->snd_una;
1222 tcpstat.tcps_rcvackpack++;
1223 tcpstat.tcps_rcvackbyte += acked;
1224 sbdrop(&so->so_snd, acked);
1225 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1226 SEQ_LEQ(th->th_ack, tp->snd_recover))
1227 tp->snd_recover = th->th_ack - 1;
1228 tp->snd_una = th->th_ack;
1229 /*
1230 * pull snd_wl2 up to prevent seq wrap relative
1231 * to th_ack.
1232 */
1233 tp->snd_wl2 = th->th_ack;
1234 tp->t_dupacks = 0;
1235 m_freem(m);
1236 ND6_HINT(tp); /* some progress has been done */
1237
1238 /*
1239 * If all outstanding data are acked, stop
1240 * retransmit timer, otherwise restart timer
1241 * using current (possibly backed-off) value.
1242 * If process is waiting for space,
1243 * wakeup/selwakeup/signal. If data
1244 * are ready to send, let tcp_output
1245 * decide between more output or persist.
1246
1247 #ifdef TCPDEBUG
1248 if (so->so_options & SO_DEBUG)
1249 tcp_trace(TA_INPUT, ostate, tp,
1250 (void *)tcp_saveipgen,
1251 &tcp_savetcp, 0);
1252 #endif
1253 */
1254 if (tp->snd_una == tp->snd_max)
1255 callout_stop(tp->tt_rexmt);
1256 else if (!callout_active(tp->tt_persist))
1257 callout_reset(tp->tt_rexmt,
1258 tp->t_rxtcur,
1259 tcp_timer_rexmt, tp);
1260
1261 sowwakeup(so);
1262 if (so->so_snd.sb_cc)
1263 (void) tcp_output(tp);
1264 goto check_delack;
1265 }
1266 } else if (th->th_ack == tp->snd_una &&
1267 LIST_EMPTY(&tp->t_segq) &&
1268 tlen <= sbspace(&so->so_rcv)) {
1269 KASSERT(headlocked, ("headlocked"));
1270 INP_INFO_WUNLOCK(&tcbinfo);
1271 headlocked = 0;
1272 /*
1273 * this is a pure, in-sequence data packet
1274 * with nothing on the reassembly queue and
1275 * we have enough buffer space to take it.
1276 */
1277 /* Clean receiver SACK report if present */
1278 if (tp->sack_enable && tp->rcv_numsacks)
1279 tcp_clean_sackreport(tp);
1280 ++tcpstat.tcps_preddat;
1281 tp->rcv_nxt += tlen;
1282 /*
1283 * Pull snd_wl1 up to prevent seq wrap relative to
1284 * th_seq.
1285 */
1286 tp->snd_wl1 = th->th_seq;
1287 /*
1288 * Pull rcv_up up to prevent seq wrap relative to
1289 * rcv_nxt.
1290 */
1291 tp->rcv_up = tp->rcv_nxt;
1292 tcpstat.tcps_rcvpack++;
1293 tcpstat.tcps_rcvbyte += tlen;
1294 ND6_HINT(tp); /* some progress has been done */
1295 /*
1296 #ifdef TCPDEBUG
1297 if (so->so_options & SO_DEBUG)
1298 tcp_trace(TA_INPUT, ostate, tp,
1299 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1300 #endif
1301 * Add data to socket buffer.
1302 */
1303 SOCKBUF_LOCK(&so->so_rcv);
1304 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1305 m_freem(m);
1306 } else {
1307 m_adj(m, drop_hdrlen); /* delayed header drop */
1308 sbappendstream_locked(&so->so_rcv, m);
1309 }
1310 sorwakeup_locked(so);
1311 if (DELAY_ACK(tp)) {
1312 tp->t_flags |= TF_DELACK;
1313 } else {
1314 tp->t_flags |= TF_ACKNOW;
1315 tcp_output(tp);
1316 }
1317 goto check_delack;
1318 }
1319 }
1320
1321 /*
1322 * Calculate amount of space in receive window,
1323 * and then do TCP input processing.
1324 * Receive window is amount of space in rcv queue,
1325 * but not less than advertised window.
1326 */
1327 { int win;
1328
1329 win = sbspace(&so->so_rcv);
1330 if (win < 0)
1331 win = 0;
1332 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1333 }
1334
1335 switch (tp->t_state) {
1336
1337 /*
1338 * If the state is SYN_RECEIVED:
1339 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1340 */
1341 case TCPS_SYN_RECEIVED:
1342 if ((thflags & TH_ACK) &&
1343 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1344 SEQ_GT(th->th_ack, tp->snd_max))) {
1345 rstreason = BANDLIM_RST_OPENPORT;
1346 goto dropwithreset;
1347 }
1348 break;
1349
1350 /*
1351 * If the state is SYN_SENT:
1352 * if seg contains an ACK, but not for our SYN, drop the input.
1353 * if seg contains a RST, then drop the connection.
1354 * if seg does not contain SYN, then drop it.
1355 * Otherwise this is an acceptable SYN segment
1356 * initialize tp->rcv_nxt and tp->irs
1357 * if seg contains ack then advance tp->snd_una
1358 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1359 * arrange for segment to be acked (eventually)
1360 * continue processing rest of data/controls, beginning with URG
1361 */
1362 case TCPS_SYN_SENT:
1363 if ((thflags & TH_ACK) &&
1364 (SEQ_LEQ(th->th_ack, tp->iss) ||
1365 SEQ_GT(th->th_ack, tp->snd_max))) {
1366 rstreason = BANDLIM_UNLIMITED;
1367 goto dropwithreset;
1368 }
1369 if (thflags & TH_RST) {
1370 if (thflags & TH_ACK) {
1371 KASSERT(headlocked, ("tcp_input: after_listen"
1372 ": tcp_drop.2: head not locked"));
1373 tp = tcp_drop(tp, ECONNREFUSED);
1374 }
1375 goto drop;
1376 }
1377 if ((thflags & TH_SYN) == 0)
1378 goto drop;
1379
1380 tp->irs = th->th_seq;
1381 tcp_rcvseqinit(tp);
1382 if (thflags & TH_ACK) {
1383 tcpstat.tcps_connects++;
1384 soisconnected(so);
1385 #ifdef MAC
1386 SOCK_LOCK(so);
1387 mac_set_socket_peer_from_mbuf(m, so);
1388 SOCK_UNLOCK(so);
1389 #endif
1390 /* Do window scaling on this connection? */
1391 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1392 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1393 tp->snd_scale = tp->requested_s_scale;
1394 tp->rcv_scale = tp->request_r_scale;
1395 }
1396 tp->rcv_adv += tp->rcv_wnd;
1397 tp->snd_una++; /* SYN is acked */
1398 /*
1399 * If there's data, delay ACK; if there's also a FIN
1400 * ACKNOW will be turned on later.
1401 */
1402 if (DELAY_ACK(tp) && tlen != 0)
1403 callout_reset(tp->tt_delack, tcp_delacktime,
1404 tcp_timer_delack, tp);
1405 else
1406 tp->t_flags |= TF_ACKNOW;
1407 /*
1408 * Received <SYN,ACK> in SYN_SENT[*] state.
1409 * Transitions:
1410 * SYN_SENT --> ESTABLISHED
1411 * SYN_SENT* --> FIN_WAIT_1
1412 */
1413 tp->t_starttime = ticks;
1414 if (tp->t_flags & TF_NEEDFIN) {
1415 tp->t_state = TCPS_FIN_WAIT_1;
1416 tp->t_flags &= ~TF_NEEDFIN;
1417 thflags &= ~TH_SYN;
1418 } else {
1419 tp->t_state = TCPS_ESTABLISHED;
1420 callout_reset(tp->tt_keep, tcp_keepidle,
1421 tcp_timer_keep, tp);
1422 }
1423 } else {
1424 /*
1425 * Received initial SYN in SYN-SENT[*] state =>
1426 * simultaneous open. If segment contains CC option
1427 * and there is a cached CC, apply TAO test.
1428 * If it succeeds, connection is * half-synchronized.
1429 * Otherwise, do 3-way handshake:
1430 * SYN-SENT -> SYN-RECEIVED
1431 * SYN-SENT* -> SYN-RECEIVED*
1432 * If there was no CC option, clear cached CC value.
1433 */
1434 tp->t_flags |= TF_ACKNOW;
1435 callout_stop(tp->tt_rexmt);
1436 tp->t_state = TCPS_SYN_RECEIVED;
1437 }
1438
1439 trimthenstep6:
1440 KASSERT(headlocked, ("tcp_input: trimthenstep6: head not "
1441 "locked"));
1442 INP_LOCK_ASSERT(inp);
1443
1444 /*
1445 * Advance th->th_seq to correspond to first data byte.
1446 * If data, trim to stay within window,
1447 * dropping FIN if necessary.
1448 */
1449 th->th_seq++;
1450 if (tlen > tp->rcv_wnd) {
1451 todrop = tlen - tp->rcv_wnd;
1452 m_adj(m, -todrop);
1453 tlen = tp->rcv_wnd;
1454 thflags &= ~TH_FIN;
1455 tcpstat.tcps_rcvpackafterwin++;
1456 tcpstat.tcps_rcvbyteafterwin += todrop;
1457 }
1458 tp->snd_wl1 = th->th_seq - 1;
1459 tp->rcv_up = th->th_seq;
1460 /*
1461 * Client side of transaction: already sent SYN and data.
1462 * If the remote host used T/TCP to validate the SYN,
1463 * our data will be ACK'd; if so, enter normal data segment
1464 * processing in the middle of step 5, ack processing.
1465 * Otherwise, goto step 6.
1466 */
1467 if (thflags & TH_ACK)
1468 goto process_ACK;
1469
1470 goto step6;
1471
1472 /*
1473 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1474 * do normal processing.
1475 *
1476 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1477 */
1478 case TCPS_LAST_ACK:
1479 case TCPS_CLOSING:
1480 case TCPS_TIME_WAIT:
1481 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1482 break; /* continue normal processing */
1483 }
1484
1485 /*
1486 * States other than LISTEN or SYN_SENT.
1487 * First check the RST flag and sequence number since reset segments
1488 * are exempt from the timestamp and connection count tests. This
1489 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1490 * below which allowed reset segments in half the sequence space
1491 * to fall though and be processed (which gives forged reset
1492 * segments with a random sequence number a 50 percent chance of
1493 * killing a connection).
1494 * Then check timestamp, if present.
1495 * Then check the connection count, if present.
1496 * Then check that at least some bytes of segment are within
1497 * receive window. If segment begins before rcv_nxt,
1498 * drop leading data (and SYN); if nothing left, just ack.
1499 *
1500 *
1501 * If the RST bit is set, check the sequence number to see
1502 * if this is a valid reset segment.
1503 * RFC 793 page 37:
1504 * In all states except SYN-SENT, all reset (RST) segments
1505 * are validated by checking their SEQ-fields. A reset is
1506 * valid if its sequence number is in the window.
1507 * Note: this does not take into account delayed ACKs, so
1508 * we should test against last_ack_sent instead of rcv_nxt.
1509 * The sequence number in the reset segment is normally an
1510 * echo of our outgoing acknowlegement numbers, but some hosts
1511 * send a reset with the sequence number at the rightmost edge
1512 * of our receive window, and we have to handle this case.
1513 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1514 * that brute force RST attacks are possible. To combat this,
1515 * we use a much stricter check while in the ESTABLISHED state,
1516 * only accepting RSTs where the sequence number is equal to
1517 * last_ack_sent. In all other states (the states in which a
1518 * RST is more likely), the more permissive check is used.
1519 * If we have multiple segments in flight, the intial reset
1520 * segment sequence numbers will be to the left of last_ack_sent,
1521 * but they will eventually catch up.
1522 * In any case, it never made sense to trim reset segments to
1523 * fit the receive window since RFC 1122 says:
1524 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1525 *
1526 * A TCP SHOULD allow a received RST segment to include data.
1527 *
1528 * DISCUSSION
1529 * It has been suggested that a RST segment could contain
1530 * ASCII text that encoded and explained the cause of the
1531 * RST. No standard has yet been established for such
1532 * data.
1533 *
1534 * If the reset segment passes the sequence number test examine
1535 * the state:
1536 * SYN_RECEIVED STATE:
1537 * If passive open, return to LISTEN state.
1538 * If active open, inform user that connection was refused.
1539 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1540 * Inform user that connection was reset, and close tcb.
1541 * CLOSING, LAST_ACK STATES:
1542 * Close the tcb.
1543 * TIME_WAIT STATE:
1544 * Drop the segment - see Stevens, vol. 2, p. 964 and
1545 * RFC 1337.
1546 */
1547 if (thflags & TH_RST) {
1548 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1549 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1550 switch (tp->t_state) {
1551
1552 case TCPS_SYN_RECEIVED:
1553 so->so_error = ECONNREFUSED;
1554 goto close;
1555
1556 case TCPS_ESTABLISHED:
1557 if (tcp_insecure_rst == 0 &&
1558 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1559 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1560 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1561 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1562 tcpstat.tcps_badrst++;
1563 goto drop;
1564 }
1565 case TCPS_FIN_WAIT_1:
1566 case TCPS_FIN_WAIT_2:
1567 case TCPS_CLOSE_WAIT:
1568 so->so_error = ECONNRESET;
1569 close:
1570 tp->t_state = TCPS_CLOSED;
1571 tcpstat.tcps_drops++;
1572 KASSERT(headlocked, ("tcp_input: "
1573 "trimthenstep6: tcp_close: head not "
1574 "locked"));
1575 tp = tcp_close(tp);
1576 break;
1577
1578 case TCPS_CLOSING:
1579 case TCPS_LAST_ACK:
1580 KASSERT(headlocked, ("trimthenstep6: "
1581 "tcp_close.2: head not locked"));
1582 tp = tcp_close(tp);
1583 break;
1584
1585 case TCPS_TIME_WAIT:
1586 KASSERT(tp->t_state != TCPS_TIME_WAIT,
1587 ("timewait"));
1588 break;
1589 }
1590 }
1591 goto drop;
1592 }
1593
1594 /*
1595 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1596 * and it's less than ts_recent, drop it.
1597 */
1598 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1599 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1600
1601 /* Check to see if ts_recent is over 24 days old. */
1602 if ((int)(ticks - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1603 /*
1604 * Invalidate ts_recent. If this segment updates
1605 * ts_recent, the age will be reset later and ts_recent
1606 * will get a valid value. If it does not, setting
1607 * ts_recent to zero will at least satisfy the
1608 * requirement that zero be placed in the timestamp
1609 * echo reply when ts_recent isn't valid. The
1610 * age isn't reset until we get a valid ts_recent
1611 * because we don't want out-of-order segments to be
1612 * dropped when ts_recent is old.
1613 */
1614 tp->ts_recent = 0;
1615 } else {
1616 tcpstat.tcps_rcvduppack++;
1617 tcpstat.tcps_rcvdupbyte += tlen;
1618 tcpstat.tcps_pawsdrop++;
1619 if (tlen)
1620 goto dropafterack;
1621 goto drop;
1622 }
1623 }
1624
1625 /*
1626 * In the SYN-RECEIVED state, validate that the packet belongs to
1627 * this connection before trimming the data to fit the receive
1628 * window. Check the sequence number versus IRS since we know
1629 * the sequence numbers haven't wrapped. This is a partial fix
1630 * for the "LAND" DoS attack.
1631 */
1632 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1633 rstreason = BANDLIM_RST_OPENPORT;
1634 goto dropwithreset;
1635 }
1636
1637 todrop = tp->rcv_nxt - th->th_seq;
1638 if (todrop > 0) {
1639 if (thflags & TH_SYN) {
1640 thflags &= ~TH_SYN;
1641 th->th_seq++;
1642 if (th->th_urp > 1)
1643 th->th_urp--;
1644 else
1645 thflags &= ~TH_URG;
1646 todrop--;
1647 }
1648 /*
1649 * Following if statement from Stevens, vol. 2, p. 960.
1650 */
1651 if (todrop > tlen
1652 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1653 /*
1654 * Any valid FIN must be to the left of the window.
1655 * At this point the FIN must be a duplicate or out
1656 * of sequence; drop it.
1657 */
1658 thflags &= ~TH_FIN;
1659
1660 /*
1661 * Send an ACK to resynchronize and drop any data.
1662 * But keep on processing for RST or ACK.
1663 */
1664 tp->t_flags |= TF_ACKNOW;
1665 todrop = tlen;
1666 tcpstat.tcps_rcvduppack++;
1667 tcpstat.tcps_rcvdupbyte += todrop;
1668 } else {
1669 tcpstat.tcps_rcvpartduppack++;
1670 tcpstat.tcps_rcvpartdupbyte += todrop;
1671 }
1672 drop_hdrlen += todrop; /* drop from the top afterwards */
1673 th->th_seq += todrop;
1674 tlen -= todrop;
1675 if (th->th_urp > todrop)
1676 th->th_urp -= todrop;
1677 else {
1678 thflags &= ~TH_URG;
1679 th->th_urp = 0;
1680 }
1681 }
1682
1683 /*
1684 * If new data are received on a connection after the
1685 * user processes are gone, then RST the other end.
1686 */
1687 if ((so->so_state & SS_NOFDREF) &&
1688 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1689 KASSERT(headlocked, ("trimthenstep6: tcp_close.3: head not "
1690 "locked"));
1691 tp = tcp_close(tp);
1692 tcpstat.tcps_rcvafterclose++;
1693 rstreason = BANDLIM_UNLIMITED;
1694 goto dropwithreset;
1695 }
1696
1697 /*
1698 * If segment ends after window, drop trailing data
1699 * (and PUSH and FIN); if nothing left, just ACK.
1700 */
1701 todrop = (th->th_seq+tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1702 if (todrop > 0) {
1703 tcpstat.tcps_rcvpackafterwin++;
1704 if (todrop >= tlen) {
1705 tcpstat.tcps_rcvbyteafterwin += tlen;
1706 /*
1707 * If a new connection request is received
1708 * while in TIME_WAIT, drop the old connection
1709 * and start over if the sequence numbers
1710 * are above the previous ones.
1711 */
1712 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1713 if (thflags & TH_SYN &&
1714 tp->t_state == TCPS_TIME_WAIT &&
1715 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1716 KASSERT(headlocked, ("trimthenstep6: "
1717 "tcp_close.4: head not locked"));
1718 tp = tcp_close(tp);
1719 goto findpcb;
1720 }
1721 /*
1722 * If window is closed can only take segments at
1723 * window edge, and have to drop data and PUSH from
1724 * incoming segments. Continue processing, but
1725 * remember to ack. Otherwise, drop segment
1726 * and ack.
1727 */
1728 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1729 tp->t_flags |= TF_ACKNOW;
1730 tcpstat.tcps_rcvwinprobe++;
1731 } else
1732 goto dropafterack;
1733 } else
1734 tcpstat.tcps_rcvbyteafterwin += todrop;
1735 m_adj(m, -todrop);
1736 tlen -= todrop;
1737 thflags &= ~(TH_PUSH|TH_FIN);
1738 }
1739
1740 /*
1741 * If last ACK falls within this segment's sequence numbers,
1742 * record its timestamp.
1743 * NOTE:
1744 * 1) That the test incorporates suggestions from the latest
1745 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1746 * 2) That updating only on newer timestamps interferes with
1747 * our earlier PAWS tests, so this check should be solely
1748 * predicated on the sequence space of this segment.
1749 * 3) That we modify the segment boundary check to be
1750 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1751 * instead of RFC1323's
1752 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1753 * This modified check allows us to overcome RFC1323's
1754 * limitations as described in Stevens TCP/IP Illustrated
1755 * Vol. 2 p.869. In such cases, we can still calculate the
1756 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1757 */
1758 if ((to.to_flags & TOF_TS) != 0 &&
1759 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1760 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1761 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1762 tp->ts_recent_age = ticks;
1763 tp->ts_recent = to.to_tsval;
1764 }
1765
1766 /*
1767 * If a SYN is in the window, then this is an
1768 * error and we send an RST and drop the connection.
1769 */
1770 if (thflags & TH_SYN) {
1771 KASSERT(headlocked, ("tcp_input: tcp_drop: trimthenstep6: "
1772 "head not locked"));
1773 tp = tcp_drop(tp, ECONNRESET);
1774 rstreason = BANDLIM_UNLIMITED;
1775 goto drop;
1776 }
1777
1778 /*
1779 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1780 * flag is on (half-synchronized state), then queue data for
1781 * later processing; else drop segment and return.
1782 */
1783 if ((thflags & TH_ACK) == 0) {
1784 if (tp->t_state == TCPS_SYN_RECEIVED ||
1785 (tp->t_flags & TF_NEEDSYN))
1786 goto step6;
1787 else if (tp->t_flags & TF_ACKNOW)
1788 goto dropafterack;
1789 else
1790 goto drop;
1791 }
1792
1793 /*
1794 * Ack processing.
1795 */
1796 switch (tp->t_state) {
1797
1798 /*
1799 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1800 * ESTABLISHED state and continue processing.
1801 * The ACK was checked above.
1802 */
1803 case TCPS_SYN_RECEIVED:
1804
1805 tcpstat.tcps_connects++;
1806 soisconnected(so);
1807 /* Do window scaling? */
1808 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1809 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1810 tp->snd_scale = tp->requested_s_scale;
1811 tp->rcv_scale = tp->request_r_scale;
1812 }
1813 /*
1814 * Make transitions:
1815 * SYN-RECEIVED -> ESTABLISHED
1816 * SYN-RECEIVED* -> FIN-WAIT-1
1817 */
1818 tp->t_starttime = ticks;
1819 if (tp->t_flags & TF_NEEDFIN) {
1820 tp->t_state = TCPS_FIN_WAIT_1;
1821 tp->t_flags &= ~TF_NEEDFIN;
1822 } else {
1823 tp->t_state = TCPS_ESTABLISHED;
1824 callout_reset(tp->tt_keep, tcp_keepidle,
1825 tcp_timer_keep, tp);
1826 }
1827 /*
1828 * If segment contains data or ACK, will call tcp_reass()
1829 * later; if not, do so now to pass queued data to user.
1830 */
1831 if (tlen == 0 && (thflags & TH_FIN) == 0)
1832 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1833 (struct mbuf *)0);
1834 tp->snd_wl1 = th->th_seq - 1;
1835 /* FALLTHROUGH */
1836
1837 /*
1838 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1839 * ACKs. If the ack is in the range
1840 * tp->snd_una < th->th_ack <= tp->snd_max
1841 * then advance tp->snd_una to th->th_ack and drop
1842 * data from the retransmission queue. If this ACK reflects
1843 * more up to date window information we update our window information.
1844 */
1845 case TCPS_ESTABLISHED:
1846 case TCPS_FIN_WAIT_1:
1847 case TCPS_FIN_WAIT_2:
1848 case TCPS_CLOSE_WAIT:
1849 case TCPS_CLOSING:
1850 case TCPS_LAST_ACK:
1851 case TCPS_TIME_WAIT:
1852 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
1853 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1854 tcpstat.tcps_rcvacktoomuch++;
1855 goto dropafterack;
1856 }
1857 if (tp->sack_enable &&
1858 (to.to_nsacks > 0 || !TAILQ_EMPTY(&tp->snd_holes)))
1859 tcp_sack_doack(tp, &to, th->th_ack);
1860 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1861 if (tlen == 0 && tiwin == tp->snd_wnd) {
1862 tcpstat.tcps_rcvdupack++;
1863 /*
1864 * If we have outstanding data (other than
1865 * a window probe), this is a completely
1866 * duplicate ack (ie, window info didn't
1867 * change), the ack is the biggest we've
1868 * seen and we've seen exactly our rexmt
1869 * threshhold of them, assume a packet
1870 * has been dropped and retransmit it.
1871 * Kludge snd_nxt & the congestion
1872 * window so we send only this one
1873 * packet.
1874 *
1875 * We know we're losing at the current
1876 * window size so do congestion avoidance
1877 * (set ssthresh to half the current window
1878 * and pull our congestion window back to
1879 * the new ssthresh).
1880 *
1881 * Dup acks mean that packets have left the
1882 * network (they're now cached at the receiver)
1883 * so bump cwnd by the amount in the receiver
1884 * to keep a constant cwnd packets in the
1885 * network.
1886 */
1887 if (!callout_active(tp->tt_rexmt) ||
1888 th->th_ack != tp->snd_una)
1889 tp->t_dupacks = 0;
1890 else if (++tp->t_dupacks > tcprexmtthresh ||
1891 ((tcp_do_newreno || tp->sack_enable) &&
1892 IN_FASTRECOVERY(tp))) {
1893 if (tp->sack_enable && IN_FASTRECOVERY(tp)) {
1894 int awnd;
1895
1896 /*
1897 * Compute the amount of data in flight first.
1898 * We can inject new data into the pipe iff
1899 * we have less than 1/2 the original window's
1900 * worth of data in flight.
1901 */
1902 awnd = (tp->snd_nxt - tp->snd_fack) +
1903 tp->sackhint.sack_bytes_rexmit;
1904 if (awnd < tp->snd_ssthresh) {
1905 tp->snd_cwnd += tp->t_maxseg;
1906 if (tp->snd_cwnd > tp->snd_ssthresh)
1907 tp->snd_cwnd = tp->snd_ssthresh;
1908 }
1909 } else
1910 tp->snd_cwnd += tp->t_maxseg;
1911 (void) tcp_output(tp);
1912 goto drop;
1913 } else if (tp->t_dupacks == tcprexmtthresh) {
1914 tcp_seq onxt = tp->snd_nxt;
1915 u_int win;
1916
1917 /*
1918 * If we're doing sack, check to
1919 * see if we're already in sack
1920 * recovery. If we're not doing sack,
1921 * check to see if we're in newreno
1922 * recovery.
1923 */
1924 if (tp->sack_enable) {
1925 if (IN_FASTRECOVERY(tp)) {
1926 tp->t_dupacks = 0;
1927 break;
1928 }
1929 } else if (tcp_do_newreno) {
1930 if (SEQ_LEQ(th->th_ack,
1931 tp->snd_recover)) {
1932 tp->t_dupacks = 0;
1933 break;
1934 }
1935 }
1936 win = min(tp->snd_wnd, tp->snd_cwnd) /
1937 2 / tp->t_maxseg;
1938 if (win < 2)
1939 win = 2;
1940 tp->snd_ssthresh = win * tp->t_maxseg;
1941 ENTER_FASTRECOVERY(tp);
1942 tp->snd_recover = tp->snd_max;
1943 callout_stop(tp->tt_rexmt);
1944 tp->t_rtttime = 0;
1945 if (tp->sack_enable) {
1946 tcpstat.tcps_sack_recovery_episode++;
1947 tp->sack_newdata = tp->snd_nxt;
1948 tp->snd_cwnd = tp->t_maxseg;
1949 (void) tcp_output(tp);
1950 goto drop;
1951 }
1952 tp->snd_nxt = th->th_ack;
1953 tp->snd_cwnd = tp->t_maxseg;
1954 (void) tcp_output(tp);
1955 KASSERT(tp->snd_limited <= 2,
1956 ("tp->snd_limited too big"));
1957 tp->snd_cwnd = tp->snd_ssthresh +
1958 tp->t_maxseg *
1959 (tp->t_dupacks - tp->snd_limited);
1960 if (SEQ_GT(onxt, tp->snd_nxt))
1961 tp->snd_nxt = onxt;
1962 goto drop;
1963 } else if (tcp_do_rfc3042) {
1964 u_long oldcwnd = tp->snd_cwnd;
1965 tcp_seq oldsndmax = tp->snd_max;
1966 u_int sent;
1967
1968 KASSERT(tp->t_dupacks == 1 ||
1969 tp->t_dupacks == 2,
1970 ("dupacks not 1 or 2"));
1971 if (tp->t_dupacks == 1)
1972 tp->snd_limited = 0;
1973 tp->snd_cwnd =
1974 (tp->snd_nxt - tp->snd_una) +
1975 (tp->t_dupacks - tp->snd_limited) *
1976 tp->t_maxseg;
1977 (void) tcp_output(tp);
1978 sent = tp->snd_max - oldsndmax;
1979 if (sent > tp->t_maxseg) {
1980 KASSERT((tp->t_dupacks == 2 &&
1981 tp->snd_limited == 0) ||
1982 (sent == tp->t_maxseg + 1 &&
1983 tp->t_flags & TF_SENTFIN),
1984 ("sent too much"));
1985 tp->snd_limited = 2;
1986 } else if (sent > 0)
1987 ++tp->snd_limited;
1988 tp->snd_cwnd = oldcwnd;
1989 goto drop;
1990 }
1991 } else
1992 tp->t_dupacks = 0;
1993 break;
1994 }
1995
1996 KASSERT(SEQ_GT(th->th_ack, tp->snd_una), ("th_ack <= snd_una"));
1997
1998 /*
1999 * If the congestion window was inflated to account
2000 * for the other side's cached packets, retract it.
2001 */
2002 if (tcp_do_newreno || tp->sack_enable) {
2003 if (IN_FASTRECOVERY(tp)) {
2004 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2005 if (tp->sack_enable)
2006 tcp_sack_partialack(tp, th);
2007 else
2008 tcp_newreno_partial_ack(tp, th);
2009 } else {
2010 /*
2011 * Out of fast recovery.
2012 * Window inflation should have left us
2013 * with approximately snd_ssthresh
2014 * outstanding data.
2015 * But in case we would be inclined to
2016 * send a burst, better to do it via
2017 * the slow start mechanism.
2018 */
2019 if (SEQ_GT(th->th_ack +
2020 tp->snd_ssthresh,
2021 tp->snd_max))
2022 tp->snd_cwnd = tp->snd_max -
2023 th->th_ack +
2024 tp->t_maxseg;
2025 else
2026 tp->snd_cwnd = tp->snd_ssthresh;
2027 }
2028 }
2029 } else {
2030 if (tp->t_dupacks >= tcprexmtthresh &&
2031 tp->snd_cwnd > tp->snd_ssthresh)
2032 tp->snd_cwnd = tp->snd_ssthresh;
2033 }
2034 tp->t_dupacks = 0;
2035 /*
2036 * If we reach this point, ACK is not a duplicate,
2037 * i.e., it ACKs something we sent.
2038 */
2039 if (tp->t_flags & TF_NEEDSYN) {
2040 /*
2041 * T/TCP: Connection was half-synchronized, and our
2042 * SYN has been ACK'd (so connection is now fully
2043 * synchronized). Go to non-starred state,
2044 * increment snd_una for ACK of SYN, and check if
2045 * we can do window scaling.
2046 */
2047 tp->t_flags &= ~TF_NEEDSYN;
2048 tp->snd_una++;
2049 /* Do window scaling? */
2050 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2051 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2052 tp->snd_scale = tp->requested_s_scale;
2053 tp->rcv_scale = tp->request_r_scale;
2054 }
2055 }
2056
2057 process_ACK:
2058 KASSERT(headlocked, ("tcp_input: process_ACK: head not "
2059 "locked"));
2060 INP_LOCK_ASSERT(inp);
2061
2062 acked = th->th_ack - tp->snd_una;
2063 tcpstat.tcps_rcvackpack++;
2064 tcpstat.tcps_rcvackbyte += acked;
2065
2066 /*
2067 * If we just performed our first retransmit, and the ACK
2068 * arrives within our recovery window, then it was a mistake
2069 * to do the retransmit in the first place. Recover our
2070 * original cwnd and ssthresh, and proceed to transmit where
2071 * we left off.
2072 */
2073 if (tp->t_rxtshift == 1 && ticks < tp->t_badrxtwin) {
2074 ++tcpstat.tcps_sndrexmitbad;
2075 tp->snd_cwnd = tp->snd_cwnd_prev;
2076 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2077 tp->snd_recover = tp->snd_recover_prev;
2078 if (tp->t_flags & TF_WASFRECOVERY)
2079 ENTER_FASTRECOVERY(tp);
2080 tp->snd_nxt = tp->snd_max;
2081 tp->t_badrxtwin = 0; /* XXX probably not required */
2082 }
2083
2084 /*
2085 * If we have a timestamp reply, update smoothed
2086 * round trip time. If no timestamp is present but
2087 * transmit timer is running and timed sequence
2088 * number was acked, update smoothed round trip time.
2089 * Since we now have an rtt measurement, cancel the
2090 * timer backoff (cf., Phil Karn's retransmit alg.).
2091 * Recompute the initial retransmit timer.
2092 *
2093 * Some boxes send broken timestamp replies
2094 * during the SYN+ACK phase, ignore
2095 * timestamps of 0 or we could calculate a
2096 * huge RTT and blow up the retransmit timer.
2097 */
2098 if ((to.to_flags & TOF_TS) != 0 &&
2099 to.to_tsecr) {
2100 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2101 tp->t_rttlow = ticks - to.to_tsecr;
2102 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2103 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2104 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2105 tp->t_rttlow = ticks - tp->t_rtttime;
2106 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2107 }
2108 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2109
2110 /*
2111 * If all outstanding data is acked, stop retransmit
2112 * timer and remember to restart (more output or persist).
2113 * If there is more data to be acked, restart retransmit
2114 * timer, using current (possibly backed-off) value.
2115 */
2116 if (th->th_ack == tp->snd_max) {
2117 callout_stop(tp->tt_rexmt);
2118 needoutput = 1;
2119 } else if (!callout_active(tp->tt_persist))
2120 callout_reset(tp->tt_rexmt, tp->t_rxtcur,
2121 tcp_timer_rexmt, tp);
2122
2123 /*
2124 * If no data (only SYN) was ACK'd,
2125 * skip rest of ACK processing.
2126 */
2127 if (acked == 0)
2128 goto step6;
2129
2130 /*
2131 * When new data is acked, open the congestion window.
2132 * If the window gives us less than ssthresh packets
2133 * in flight, open exponentially (maxseg per packet).
2134 * Otherwise open linearly: maxseg per window
2135 * (maxseg^2 / cwnd per packet).
2136 * If cwnd > maxseg^2, fix the cwnd increment at 1 byte
2137 * to avoid capping cwnd (as suggested in RFC2581).
2138 */
2139 if ((!tcp_do_newreno && !tp->sack_enable) ||
2140 !IN_FASTRECOVERY(tp)) {
2141 register u_int cw = tp->snd_cwnd;
2142 register u_int incr = tp->t_maxseg;
2143 if (cw > tp->snd_ssthresh)
2144 incr = max((incr * incr / cw), 1);
2145 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2146 }
2147 SOCKBUF_LOCK(&so->so_snd);
2148 if (acked > so->so_snd.sb_cc) {
2149 tp->snd_wnd -= so->so_snd.sb_cc;
2150 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2151 ourfinisacked = 1;
2152 } else {
2153 sbdrop_locked(&so->so_snd, acked);
2154 tp->snd_wnd -= acked;
2155 ourfinisacked = 0;
2156 }
2157 sowwakeup_locked(so);
2158 /* detect una wraparound */
2159 if ((tcp_do_newreno || tp->sack_enable) &&
2160 !IN_FASTRECOVERY(tp) &&
2161 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2162 SEQ_LEQ(th->th_ack, tp->snd_recover))
2163 tp->snd_recover = th->th_ack - 1;
2164 if ((tcp_do_newreno || tp->sack_enable) &&
2165 IN_FASTRECOVERY(tp) &&
2166 SEQ_GEQ(th->th_ack, tp->snd_recover))
2167 EXIT_FASTRECOVERY(tp);
2168 tp->snd_una = th->th_ack;
2169 if (tp->sack_enable) {
2170 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2171 tp->snd_recover = tp->snd_una;
2172 }
2173 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2174 tp->snd_nxt = tp->snd_una;
2175
2176 switch (tp->t_state) {
2177
2178 /*
2179 * In FIN_WAIT_1 STATE in addition to the processing
2180 * for the ESTABLISHED state if our FIN is now acknowledged
2181 * then enter FIN_WAIT_2.
2182 */
2183 case TCPS_FIN_WAIT_1:
2184 if (ourfinisacked) {
2185 /*
2186 * If we can't receive any more
2187 * data, then closing user can proceed.
2188 * Starting the timer is contrary to the
2189 * specification, but if we don't get a FIN
2190 * we'll hang forever.
2191 */
2192 /* XXXjl
2193 * we should release the tp also, and use a
2194 * compressed state.
2195 */
2196 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2197 soisdisconnected(so);
2198 callout_reset(tp->tt_2msl, tcp_maxidle,
2199 tcp_timer_2msl, tp);
2200 }
2201 tp->t_state = TCPS_FIN_WAIT_2;
2202 }
2203 break;
2204
2205 /*
2206 * In CLOSING STATE in addition to the processing for
2207 * the ESTABLISHED state if the ACK acknowledges our FIN
2208 * then enter the TIME-WAIT state, otherwise ignore
2209 * the segment.
2210 */
2211 case TCPS_CLOSING:
2212 if (ourfinisacked) {
2213 KASSERT(headlocked, ("tcp_input: process_ACK: "
2214 "head not locked"));
2215 tcp_twstart(tp);
2216 INP_INFO_WUNLOCK(&tcbinfo);
2217 m_freem(m);
2218 return;
2219 }
2220 break;
2221
2222 /*
2223 * In LAST_ACK, we may still be waiting for data to drain
2224 * and/or to be acked, as well as for the ack of our FIN.
2225 * If our FIN is now acknowledged, delete the TCB,
2226 * enter the closed state and return.
2227 */
2228 case TCPS_LAST_ACK:
2229 if (ourfinisacked) {
2230 KASSERT(headlocked, ("tcp_input: process_ACK:"
2231 " tcp_close: head not locked"));
2232 tp = tcp_close(tp);
2233 goto drop;
2234 }
2235 break;
2236
2237 /*
2238 * In TIME_WAIT state the only thing that should arrive
2239 * is a retransmission of the remote FIN. Acknowledge
2240 * it and restart the finack timer.
2241 */
2242 case TCPS_TIME_WAIT:
2243 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2244 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2245 tcp_timer_2msl, tp);
2246 goto dropafterack;
2247 }
2248 }
2249
2250 step6:
2251 KASSERT(headlocked, ("tcp_input: step6: head not locked"));
2252 INP_LOCK_ASSERT(inp);
2253
2254 /*
2255 * Update window information.
2256 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2257 */
2258 if ((thflags & TH_ACK) &&
2259 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2260 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2261 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2262 /* keep track of pure window updates */
2263 if (tlen == 0 &&
2264 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2265 tcpstat.tcps_rcvwinupd++;
2266 tp->snd_wnd = tiwin;
2267 tp->snd_wl1 = th->th_seq;
2268 tp->snd_wl2 = th->th_ack;
2269 if (tp->snd_wnd > tp->max_sndwnd)
2270 tp->max_sndwnd = tp->snd_wnd;
2271 needoutput = 1;
2272 }
2273
2274 /*
2275 * Process segments with URG.
2276 */
2277 if ((thflags & TH_URG) && th->th_urp &&
2278 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2279 /*
2280 * This is a kludge, but if we receive and accept
2281 * random urgent pointers, we'll crash in
2282 * soreceive. It's hard to imagine someone
2283 * actually wanting to send this much urgent data.
2284 */
2285 SOCKBUF_LOCK(&so->so_rcv);
2286 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2287 th->th_urp = 0; /* XXX */
2288 thflags &= ~TH_URG; /* XXX */
2289 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2290 goto dodata; /* XXX */
2291 }
2292 /*
2293 * If this segment advances the known urgent pointer,
2294 * then mark the data stream. This should not happen
2295 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2296 * a FIN has been received from the remote side.
2297 * In these states we ignore the URG.
2298 *
2299 * According to RFC961 (Assigned Protocols),
2300 * the urgent pointer points to the last octet
2301 * of urgent data. We continue, however,
2302 * to consider it to indicate the first octet
2303 * of data past the urgent section as the original
2304 * spec states (in one of two places).
2305 */
2306 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2307 tp->rcv_up = th->th_seq + th->th_urp;
2308 so->so_oobmark = so->so_rcv.sb_cc +
2309 (tp->rcv_up - tp->rcv_nxt) - 1;
2310 if (so->so_oobmark == 0)
2311 so->so_rcv.sb_state |= SBS_RCVATMARK;
2312 sohasoutofband(so);
2313 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2314 }
2315 SOCKBUF_UNLOCK(&so->so_rcv);
2316 /*
2317 * Remove out of band data so doesn't get presented to user.
2318 * This can happen independent of advancing the URG pointer,
2319 * but if two URG's are pending at once, some out-of-band
2320 * data may creep in... ick.
2321 */
2322 if (th->th_urp <= (u_long)tlen &&
2323 !(so->so_options & SO_OOBINLINE)) {
2324 /* hdr drop is delayed */
2325 tcp_pulloutofband(so, th, m, drop_hdrlen);
2326 }
2327 } else {
2328 /*
2329 * If no out of band data is expected,
2330 * pull receive urgent pointer along
2331 * with the receive window.
2332 */
2333 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2334 tp->rcv_up = tp->rcv_nxt;
2335 }
2336 dodata: /* XXX */
2337 KASSERT(headlocked, ("tcp_input: dodata: head not locked"));
2338 INP_LOCK_ASSERT(inp);
2339
2340 /*
2341 * Process the segment text, merging it into the TCP sequencing queue,
2342 * and arranging for acknowledgment of receipt if necessary.
2343 * This process logically involves adjusting tp->rcv_wnd as data
2344 * is presented to the user (this happens in tcp_usrreq.c,
2345 * case PRU_RCVD). If a FIN has already been received on this
2346 * connection then we just ignore the text.
2347 */
2348 if ((tlen || (thflags & TH_FIN)) &&
2349 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2350 tcp_seq save_start = th->th_seq;
2351 tcp_seq save_end = th->th_seq + tlen;
2352 m_adj(m, drop_hdrlen); /* delayed header drop */
2353 /*
2354 * Insert segment which includes th into TCP reassembly queue
2355 * with control block tp. Set thflags to whether reassembly now
2356 * includes a segment with FIN. This handles the common case
2357 * inline (segment is the next to be received on an established
2358 * connection, and the queue is empty), avoiding linkage into
2359 * and removal from the queue and repetition of various
2360 * conversions.
2361 * Set DELACK for segments received in order, but ack
2362 * immediately when segments are out of order (so
2363 * fast retransmit can work).
2364 */
2365 if (th->th_seq == tp->rcv_nxt &&
2366 LIST_EMPTY(&tp->t_segq) &&
2367 TCPS_HAVEESTABLISHED(tp->t_state)) {
2368 if (DELAY_ACK(tp))
2369 tp->t_flags |= TF_DELACK;
2370 else
2371 tp->t_flags |= TF_ACKNOW;
2372 tp->rcv_nxt += tlen;
2373 thflags = th->th_flags & TH_FIN;
2374 tcpstat.tcps_rcvpack++;
2375 tcpstat.tcps_rcvbyte += tlen;
2376 ND6_HINT(tp);
2377 SOCKBUF_LOCK(&so->so_rcv);
2378 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2379 m_freem(m);
2380 else
2381 sbappendstream_locked(&so->so_rcv, m);
2382 sorwakeup_locked(so);
2383 } else {
2384 thflags = tcp_reass(tp, th, &tlen, m);
2385 tp->t_flags |= TF_ACKNOW;
2386 }
2387 if (tlen > 0 && tp->sack_enable)
2388 tcp_update_sack_list(tp, save_start, save_end);
2389 /*
2390 * Note the amount of data that peer has sent into
2391 * our window, in order to estimate the sender's
2392 * buffer size.
2393 */
2394 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2395 } else {
2396 m_freem(m);
2397 thflags &= ~TH_FIN;
2398 }
2399
2400 /*
2401 * If FIN is received ACK the FIN and let the user know
2402 * that the connection is closing.
2403 */
2404 if (thflags & TH_FIN) {
2405 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2406 socantrcvmore(so);
2407 /*
2408 * If connection is half-synchronized
2409 * (ie NEEDSYN flag on) then delay ACK,
2410 * so it may be piggybacked when SYN is sent.
2411 * Otherwise, since we received a FIN then no
2412 * more input can be expected, send ACK now.
2413 */
2414 if (tp->t_flags & TF_NEEDSYN)
2415 tp->t_flags |= TF_DELACK;
2416 else
2417 tp->t_flags |= TF_ACKNOW;
2418 tp->rcv_nxt++;
2419 }
2420 switch (tp->t_state) {
2421
2422 /*
2423 * In SYN_RECEIVED and ESTABLISHED STATES
2424 * enter the CLOSE_WAIT state.
2425 */
2426 case TCPS_SYN_RECEIVED:
2427 tp->t_starttime = ticks;
2428 /*FALLTHROUGH*/
2429 case TCPS_ESTABLISHED:
2430 tp->t_state = TCPS_CLOSE_WAIT;
2431 break;
2432
2433 /*
2434 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2435 * enter the CLOSING state.
2436 */
2437 case TCPS_FIN_WAIT_1:
2438 tp->t_state = TCPS_CLOSING;
2439 break;
2440
2441 /*
2442 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2443 * starting the time-wait timer, turning off the other
2444 * standard timers.
2445 */
2446 case TCPS_FIN_WAIT_2:
2447 KASSERT(headlocked == 1, ("tcp_input: dodata: "
2448 "TCP_FIN_WAIT_2: head not locked"));
2449 tcp_twstart(tp);
2450 INP_INFO_WUNLOCK(&tcbinfo);
2451 return;
2452
2453 /*
2454 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2455 */
2456 case TCPS_TIME_WAIT:
2457 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("timewait"));
2458 callout_reset(tp->tt_2msl, 2 * tcp_msl,
2459 tcp_timer_2msl, tp);
2460 break;
2461 }
2462 }
2463 INP_INFO_WUNLOCK(&tcbinfo);
2464 headlocked = 0;
2465 #ifdef TCPDEBUG
2466 if (so->so_options & SO_DEBUG)
2467 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2468 &tcp_savetcp, 0);
2469 #endif
2470
2471 /*
2472 * Return any desired output.
2473 */
2474 if (needoutput || (tp->t_flags & TF_ACKNOW))
2475 (void) tcp_output(tp);
2476
2477 check_delack:
2478 KASSERT(headlocked == 0, ("tcp_input: check_delack: head locked"));
2479 INP_LOCK_ASSERT(inp);
2480 if (tp->t_flags & TF_DELACK) {
2481 tp->t_flags &= ~TF_DELACK;
2482 callout_reset(tp->tt_delack, tcp_delacktime,
2483 tcp_timer_delack, tp);
2484 }
2485 INP_UNLOCK(inp);
2486 return;
2487
2488 dropafterack:
2489 KASSERT(headlocked, ("tcp_input: dropafterack: head not locked"));
2490 /*
2491 * Generate an ACK dropping incoming segment if it occupies
2492 * sequence space, where the ACK reflects our state.
2493 *
2494 * We can now skip the test for the RST flag since all
2495 * paths to this code happen after packets containing
2496 * RST have been dropped.
2497 *
2498 * In the SYN-RECEIVED state, don't send an ACK unless the
2499 * segment we received passes the SYN-RECEIVED ACK test.
2500 * If it fails send a RST. This breaks the loop in the
2501 * "LAND" DoS attack, and also prevents an ACK storm
2502 * between two listening ports that have been sent forged
2503 * SYN segments, each with the source address of the other.
2504 */
2505 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2506 (SEQ_GT(tp->snd_una, th->th_ack) ||
2507 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2508 rstreason = BANDLIM_RST_OPENPORT;
2509 goto dropwithreset;
2510 }
2511 #ifdef TCPDEBUG
2512 if (so->so_options & SO_DEBUG)
2513 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2514 &tcp_savetcp, 0);
2515 #endif
2516 KASSERT(headlocked, ("headlocked should be 1"));
2517 INP_INFO_WUNLOCK(&tcbinfo);
2518 tp->t_flags |= TF_ACKNOW;
2519 (void) tcp_output(tp);
2520 INP_UNLOCK(inp);
2521 m_freem(m);
2522 return;
2523
2524 dropwithreset:
2525 KASSERT(headlocked, ("tcp_input: dropwithreset: head not locked"));
2526 /*
2527 * Generate a RST, dropping incoming segment.
2528 * Make ACK acceptable to originator of segment.
2529 * Don't bother to respond if destination was broadcast/multicast.
2530 */
2531 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2532 goto drop;
2533 if (isipv6) {
2534 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2535 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2536 goto drop;
2537 } else {
2538 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2539 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2540 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2541 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2542 goto drop;
2543 }
2544 /* IPv6 anycast check is done at tcp6_input() */
2545
2546 /*
2547 * Perform bandwidth limiting.
2548 */
2549 if (badport_bandlim(rstreason) < 0)
2550 goto drop;
2551
2552 #ifdef TCPDEBUG
2553 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2554 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2555 &tcp_savetcp, 0);
2556 #endif
2557
2558 if (thflags & TH_ACK)
2559 /* mtod() below is safe as long as hdr dropping is delayed */
2560 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0, th->th_ack,
2561 TH_RST);
2562 else {
2563 if (thflags & TH_SYN)
2564 tlen++;
2565 /* mtod() below is safe as long as hdr dropping is delayed */
2566 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2567 (tcp_seq)0, TH_RST|TH_ACK);
2568 }
2569
2570 if (tp != NULL)
2571 INP_UNLOCK(inp);
2572 if (headlocked)
2573 INP_INFO_WUNLOCK(&tcbinfo);
2574 return;
2575
2576 drop:
2577 /*
2578 * Drop space held by incoming segment and return.
2579 */
2580 #ifdef TCPDEBUG
2581 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2582 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2583 &tcp_savetcp, 0);
2584 #endif
2585 if (tp != NULL)
2586 INP_UNLOCK(inp);
2587 if (headlocked)
2588 INP_INFO_WUNLOCK(&tcbinfo);
2589 m_freem(m);
2590 return;
2591 }
2592
2593 /*
2594 * Parse TCP options and place in tcpopt.
2595 */
2596 static void
2597 tcp_dooptions(to, cp, cnt, is_syn)
2598 struct tcpopt *to;
2599 u_char *cp;
2600 int cnt;
2601 int is_syn;
2602 {
2603 int opt, optlen;
2604
2605 to->to_flags = 0;
2606 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2607 opt = cp[0];
2608 if (opt == TCPOPT_EOL)
2609 break;
2610 if (opt == TCPOPT_NOP)
2611 optlen = 1;
2612 else {
2613 if (cnt < 2)
2614 break;
2615 optlen = cp[1];
2616 if (optlen < 2 || optlen > cnt)
2617 break;
2618 }
2619 switch (opt) {
2620 case TCPOPT_MAXSEG:
2621 if (optlen != TCPOLEN_MAXSEG)
2622 continue;
2623 if (!is_syn)
2624 continue;
2625 to->to_flags |= TOF_MSS;
2626 bcopy((char *)cp + 2,
2627 (char *)&to->to_mss, sizeof(to->to_mss));
2628 to->to_mss = ntohs(to->to_mss);
2629 break;
2630 case TCPOPT_WINDOW:
2631 if (optlen != TCPOLEN_WINDOW)
2632 continue;
2633 if (! is_syn)
2634 continue;
2635 to->to_flags |= TOF_SCALE;
2636 to->to_requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2637 break;
2638 case TCPOPT_TIMESTAMP:
2639 if (optlen != TCPOLEN_TIMESTAMP)
2640 continue;
2641 to->to_flags |= TOF_TS;
2642 bcopy((char *)cp + 2,
2643 (char *)&to->to_tsval, sizeof(to->to_tsval));
2644 to->to_tsval = ntohl(to->to_tsval);
2645 bcopy((char *)cp + 6,
2646 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2647 to->to_tsecr = ntohl(to->to_tsecr);
2648 /*
2649 * If echoed timestamp is later than the current time,
2650 * fall back to non RFC1323 RTT calculation.
2651 */
2652 if ((to->to_tsecr != 0) && TSTMP_GT(to->to_tsecr, ticks))
2653 to->to_tsecr = 0;
2654 break;
2655 #ifdef TCP_SIGNATURE
2656 /*
2657 * XXX In order to reply to a host which has set the
2658 * TCP_SIGNATURE option in its initial SYN, we have to
2659 * record the fact that the option was observed here
2660 * for the syncache code to perform the correct response.
2661 */
2662 case TCPOPT_SIGNATURE:
2663 if (optlen != TCPOLEN_SIGNATURE)
2664 continue;
2665 to->to_flags |= (TOF_SIGNATURE | TOF_SIGLEN);
2666 break;
2667 #endif
2668 case TCPOPT_SACK_PERMITTED:
2669 if (!tcp_do_sack ||
2670 optlen != TCPOLEN_SACK_PERMITTED)
2671 continue;
2672 if (is_syn) {
2673 /* MUST only be set on SYN */
2674 to->to_flags |= TOF_SACK;
2675 }
2676 break;
2677 case TCPOPT_SACK:
2678 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2679 continue;
2680 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2681 to->to_sacks = cp + 2;
2682 tcpstat.tcps_sack_rcv_blocks++;
2683 break;
2684 default:
2685 continue;
2686 }
2687 }
2688 }
2689
2690 /*
2691 * Pull out of band byte out of a segment so
2692 * it doesn't appear in the user's data queue.
2693 * It is still reflected in the segment length for
2694 * sequencing purposes.
2695 */
2696 static void
2697 tcp_pulloutofband(so, th, m, off)
2698 struct socket *so;
2699 struct tcphdr *th;
2700 register struct mbuf *m;
2701 int off; /* delayed to be droped hdrlen */
2702 {
2703 int cnt = off + th->th_urp - 1;
2704
2705 while (cnt >= 0) {
2706 if (m->m_len > cnt) {
2707 char *cp = mtod(m, caddr_t) + cnt;
2708 struct tcpcb *tp = sototcpcb(so);
2709
2710 tp->t_iobc = *cp;
2711 tp->t_oobflags |= TCPOOB_HAVEDATA;
2712 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2713 m->m_len--;
2714 if (m->m_flags & M_PKTHDR)
2715 m->m_pkthdr.len--;
2716 return;
2717 }
2718 cnt -= m->m_len;
2719 m = m->m_next;
2720 if (m == 0)
2721 break;
2722 }
2723 panic("tcp_pulloutofband");
2724 }
2725
2726 /*
2727 * Collect new round-trip time estimate
2728 * and update averages and current timeout.
2729 */
2730 static void
2731 tcp_xmit_timer(tp, rtt)
2732 register struct tcpcb *tp;
2733 int rtt;
2734 {
2735 register int delta;
2736
2737 INP_LOCK_ASSERT(tp->t_inpcb);
2738
2739 tcpstat.tcps_rttupdated++;
2740 tp->t_rttupdated++;
2741 if (tp->t_srtt != 0) {
2742 /*
2743 * srtt is stored as fixed point with 5 bits after the
2744 * binary point (i.e., scaled by 8). The following magic
2745 * is equivalent to the smoothing algorithm in rfc793 with
2746 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2747 * point). Adjust rtt to origin 0.
2748 */
2749 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2750 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2751
2752 if ((tp->t_srtt += delta) <= 0)
2753 tp->t_srtt = 1;
2754
2755 /*
2756 * We accumulate a smoothed rtt variance (actually, a
2757 * smoothed mean difference), then set the retransmit
2758 * timer to smoothed rtt + 4 times the smoothed variance.
2759 * rttvar is stored as fixed point with 4 bits after the
2760 * binary point (scaled by 16). The following is
2761 * equivalent to rfc793 smoothing with an alpha of .75
2762 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2763 * rfc793's wired-in beta.
2764 */
2765 if (delta < 0)
2766 delta = -delta;
2767 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2768 if ((tp->t_rttvar += delta) <= 0)
2769 tp->t_rttvar = 1;
2770 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
2771 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2772 } else {
2773 /*
2774 * No rtt measurement yet - use the unsmoothed rtt.
2775 * Set the variance to half the rtt (so our first
2776 * retransmit happens at 3*rtt).
2777 */
2778 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2779 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2780 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
2781 }
2782 tp->t_rtttime = 0;
2783 tp->t_rxtshift = 0;
2784
2785 /*
2786 * the retransmit should happen at rtt + 4 * rttvar.
2787 * Because of the way we do the smoothing, srtt and rttvar
2788 * will each average +1/2 tick of bias. When we compute
2789 * the retransmit timer, we want 1/2 tick of rounding and
2790 * 1 extra tick because of +-1/2 tick uncertainty in the
2791 * firing of the timer. The bias will give us exactly the
2792 * 1.5 tick we need. But, because the bias is
2793 * statistical, we have to test that we don't drop below
2794 * the minimum feasible timer (which is 2 ticks).
2795 */
2796 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2797 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2798
2799 /*
2800 * We received an ack for a packet that wasn't retransmitted;
2801 * it is probably safe to discard any error indications we've
2802 * received recently. This isn't quite right, but close enough
2803 * for now (a route might have failed after we sent a segment,
2804 * and the return path might not be symmetrical).
2805 */
2806 tp->t_softerror = 0;
2807 }
2808
2809 /*
2810 * Determine a reasonable value for maxseg size.
2811 * If the route is known, check route for mtu.
2812 * If none, use an mss that can be handled on the outgoing
2813 * interface without forcing IP to fragment; if bigger than
2814 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2815 * to utilize large mbufs. If no route is found, route has no mtu,
2816 * or the destination isn't local, use a default, hopefully conservative
2817 * size (usually 512 or the default IP max size, but no more than the mtu
2818 * of the interface), as we can't discover anything about intervening
2819 * gateways or networks. We also initialize the congestion/slow start
2820 * window to be a single segment if the destination isn't local.
2821 * While looking at the routing entry, we also initialize other path-dependent
2822 * parameters from pre-set or cached values in the routing entry.
2823 *
2824 * Also take into account the space needed for options that we
2825 * send regularly. Make maxseg shorter by that amount to assure
2826 * that we can send maxseg amount of data even when the options
2827 * are present. Store the upper limit of the length of options plus
2828 * data in maxopd.
2829 *
2830 *
2831 * In case of T/TCP, we call this routine during implicit connection
2832 * setup as well (offer = -1), to initialize maxseg from the cached
2833 * MSS of our peer.
2834 *
2835 * NOTE that this routine is only called when we process an incoming
2836 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
2837 */
2838 void
2839 tcp_mss(tp, offer)
2840 struct tcpcb *tp;
2841 int offer;
2842 {
2843 int rtt, mss;
2844 u_long bufsize;
2845 u_long maxmtu;
2846 struct inpcb *inp = tp->t_inpcb;
2847 struct socket *so;
2848 struct hc_metrics_lite metrics;
2849 int origoffer = offer;
2850 #ifdef INET6
2851 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
2852 size_t min_protoh = isipv6 ?
2853 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
2854 sizeof (struct tcpiphdr);
2855 #else
2856 const size_t min_protoh = sizeof(struct tcpiphdr);
2857 #endif
2858
2859 /* initialize */
2860 #ifdef INET6
2861 if (isipv6) {
2862 maxmtu = tcp_maxmtu6(&inp->inp_inc);
2863 tp->t_maxopd = tp->t_maxseg = tcp_v6mssdflt;
2864 } else
2865 #endif
2866 {
2867 maxmtu = tcp_maxmtu(&inp->inp_inc);
2868 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2869 }
2870 so = inp->inp_socket;
2871
2872 /*
2873 * no route to sender, stay with default mss and return
2874 */
2875 if (maxmtu == 0)
2876 return;
2877
2878 /* what have we got? */
2879 switch (offer) {
2880 case 0:
2881 /*
2882 * Offer == 0 means that there was no MSS on the SYN
2883 * segment, in this case we use tcp_mssdflt.
2884 */
2885 offer =
2886 #ifdef INET6
2887 isipv6 ? tcp_v6mssdflt :
2888 #endif
2889 tcp_mssdflt;
2890 break;
2891
2892 case -1:
2893 /*
2894 * Offer == -1 means that we didn't receive SYN yet.
2895 */
2896 /* FALLTHROUGH */
2897
2898 default:
2899 /*
2900 * Prevent DoS attack with too small MSS. Round up
2901 * to at least minmss.
2902 */
2903 offer = max(offer, tcp_minmss);
2904 /*
2905 * Sanity check: make sure that maxopd will be large
2906 * enough to allow some data on segments even if the
2907 * all the option space is used (40bytes). Otherwise
2908 * funny things may happen in tcp_output.
2909 */
2910 offer = max(offer, 64);
2911 }
2912
2913 /*
2914 * rmx information is now retrieved from tcp_hostcache
2915 */
2916 tcp_hc_get(&inp->inp_inc, &metrics);
2917
2918 /*
2919 * if there's a discovered mtu int tcp hostcache, use it
2920 * else, use the link mtu.
2921 */
2922 if (metrics.rmx_mtu)
2923 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
2924 else {
2925 #ifdef INET6
2926 if (isipv6) {
2927 mss = maxmtu - min_protoh;
2928 if (!path_mtu_discovery &&
2929 !in6_localaddr(&inp->in6p_faddr))
2930 mss = min(mss, tcp_v6mssdflt);
2931 } else
2932 #endif
2933 {
2934 mss = maxmtu - min_protoh;
2935 if (!path_mtu_discovery &&
2936 !in_localaddr(inp->inp_faddr))
2937 mss = min(mss, tcp_mssdflt);
2938 }
2939 }
2940 mss = min(mss, offer);
2941
2942 /*
2943 * maxopd stores the maximum length of data AND options
2944 * in a segment; maxseg is the amount of data in a normal
2945 * segment. We need to store this value (maxopd) apart
2946 * from maxseg, because now every segment carries options
2947 * and thus we normally have somewhat less data in segments.
2948 */
2949 tp->t_maxopd = mss;
2950
2951 /*
2952 * origoffer==-1 indicates, that no segments were received yet.
2953 * In this case we just guess.
2954 */
2955 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2956 (origoffer == -1 ||
2957 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2958 mss -= TCPOLEN_TSTAMP_APPA;
2959 tp->t_maxseg = mss;
2960
2961 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2962 if (mss > MCLBYTES)
2963 mss &= ~(MCLBYTES-1);
2964 #else
2965 if (mss > MCLBYTES)
2966 mss = mss / MCLBYTES * MCLBYTES;
2967 #endif
2968 tp->t_maxseg = mss;
2969
2970 /*
2971 * If there's a pipesize, change the socket buffer to that size,
2972 * don't change if sb_hiwat is different than default (then it
2973 * has been changed on purpose with setsockopt).
2974 * Make the socket buffers an integral number of mss units;
2975 * if the mss is larger than the socket buffer, decrease the mss.
2976 */
2977 SOCKBUF_LOCK(&so->so_snd);
2978 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
2979 bufsize = metrics.rmx_sendpipe;
2980 else
2981 bufsize = so->so_snd.sb_hiwat;
2982 if (bufsize < mss)
2983 mss = bufsize;
2984 else {
2985 bufsize = roundup(bufsize, mss);
2986 if (bufsize > sb_max)
2987 bufsize = sb_max;
2988 if (bufsize > so->so_snd.sb_hiwat)
2989 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
2990 }
2991 SOCKBUF_UNLOCK(&so->so_snd);
2992 tp->t_maxseg = mss;
2993
2994 SOCKBUF_LOCK(&so->so_rcv);
2995 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
2996 bufsize = metrics.rmx_recvpipe;
2997 else
2998 bufsize = so->so_rcv.sb_hiwat;
2999 if (bufsize > mss) {
3000 bufsize = roundup(bufsize, mss);
3001 if (bufsize > sb_max)
3002 bufsize = sb_max;
3003 if (bufsize > so->so_rcv.sb_hiwat)
3004 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3005 }
3006 SOCKBUF_UNLOCK(&so->so_rcv);
3007 /*
3008 * While we're here, check the others too
3009 */
3010 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3011 tp->t_srtt = rtt;
3012 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3013 tcpstat.tcps_usedrtt++;
3014 if (metrics.rmx_rttvar) {
3015 tp->t_rttvar = metrics.rmx_rttvar;
3016 tcpstat.tcps_usedrttvar++;
3017 } else {
3018 /* default variation is +- 1 rtt */
3019 tp->t_rttvar =
3020 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3021 }
3022 TCPT_RANGESET(tp->t_rxtcur,
3023 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3024 tp->t_rttmin, TCPTV_REXMTMAX);
3025 }
3026 if (metrics.rmx_ssthresh) {
3027 /*
3028 * There's some sort of gateway or interface
3029 * buffer limit on the path. Use this to set
3030 * the slow start threshhold, but set the
3031 * threshold to no less than 2*mss.
3032 */
3033 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3034 tcpstat.tcps_usedssthresh++;
3035 }
3036 if (metrics.rmx_bandwidth)
3037 tp->snd_bandwidth = metrics.rmx_bandwidth;
3038
3039 /*
3040 * Set the slow-start flight size depending on whether this
3041 * is a local network or not.
3042 *
3043 * Extend this so we cache the cwnd too and retrieve it here.
3044 * Make cwnd even bigger than RFC3390 suggests but only if we
3045 * have previous experience with the remote host. Be careful
3046 * not make cwnd bigger than remote receive window or our own
3047 * send socket buffer. Maybe put some additional upper bound
3048 * on the retrieved cwnd. Should do incremental updates to
3049 * hostcache when cwnd collapses so next connection doesn't
3050 * overloads the path again.
3051 *
3052 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3053 * We currently check only in syncache_socket for that.
3054 */
3055 #define TCP_METRICS_CWND
3056 #ifdef TCP_METRICS_CWND
3057 if (metrics.rmx_cwnd)
3058 tp->snd_cwnd = max(mss,
3059 min(metrics.rmx_cwnd / 2,
3060 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3061 else
3062 #endif
3063 if (tcp_do_rfc3390)
3064 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3065 #ifdef INET6
3066 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3067 (!isipv6 && in_localaddr(inp->inp_faddr)))
3068 #else
3069 else if (in_localaddr(inp->inp_faddr))
3070 #endif
3071 tp->snd_cwnd = mss * ss_fltsz_local;
3072 else
3073 tp->snd_cwnd = mss * ss_fltsz;
3074 }
3075
3076 /*
3077 * Determine the MSS option to send on an outgoing SYN.
3078 */
3079 int
3080 tcp_mssopt(inc)
3081 struct in_conninfo *inc;
3082 {
3083 int mss = 0;
3084 u_long maxmtu = 0;
3085 u_long thcmtu = 0;
3086 size_t min_protoh;
3087 #ifdef INET6
3088 int isipv6 = inc->inc_isipv6 ? 1 : 0;
3089 #endif
3090
3091 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3092
3093 #ifdef INET6
3094 if (isipv6) {
3095 mss = tcp_v6mssdflt;
3096 maxmtu = tcp_maxmtu6(inc);
3097 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3098 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3099 } else
3100 #endif
3101 {
3102 mss = tcp_mssdflt;
3103 maxmtu = tcp_maxmtu(inc);
3104 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3105 min_protoh = sizeof(struct tcpiphdr);
3106 }
3107 if (maxmtu && thcmtu)
3108 mss = min(maxmtu, thcmtu) - min_protoh;
3109 else if (maxmtu || thcmtu)
3110 mss = max(maxmtu, thcmtu) - min_protoh;
3111
3112 return (mss);
3113 }
3114
3115
3116 /*
3117 * On a partial ack arrives, force the retransmission of the
3118 * next unacknowledged segment. Do not clear tp->t_dupacks.
3119 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3120 * be started again.
3121 */
3122 static void
3123 tcp_newreno_partial_ack(tp, th)
3124 struct tcpcb *tp;
3125 struct tcphdr *th;
3126 {
3127 tcp_seq onxt = tp->snd_nxt;
3128 u_long ocwnd = tp->snd_cwnd;
3129
3130 callout_stop(tp->tt_rexmt);
3131 tp->t_rtttime = 0;
3132 tp->snd_nxt = th->th_ack;
3133 /*
3134 * Set snd_cwnd to one segment beyond acknowledged offset.
3135 * (tp->snd_una has not yet been updated when this function is called.)
3136 */
3137 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3138 tp->t_flags |= TF_ACKNOW;
3139 (void) tcp_output(tp);
3140 tp->snd_cwnd = ocwnd;
3141 if (SEQ_GT(onxt, tp->snd_nxt))
3142 tp->snd_nxt = onxt;
3143 /*
3144 * Partial window deflation. Relies on fact that tp->snd_una
3145 * not updated yet.
3146 */
3147 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3148 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3149 else
3150 tp->snd_cwnd = 0;
3151 tp->snd_cwnd += tp->t_maxseg;
3152 }
3153
3154 /*
3155 * Returns 1 if the TIME_WAIT state was killed and we should start over,
3156 * looking for a pcb in the listen state. Returns 0 otherwise.
3157 */
3158 static int
3159 tcp_timewait(tw, to, th, m, tlen)
3160 struct tcptw *tw;
3161 struct tcpopt *to;
3162 struct tcphdr *th;
3163 struct mbuf *m;
3164 int tlen;
3165 {
3166 int thflags;
3167 tcp_seq seq;
3168 #ifdef INET6
3169 int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
3170 #else
3171 const int isipv6 = 0;
3172 #endif
3173
3174 /* tcbinfo lock required for tcp_twclose(), tcp_timer_2msl_reset(). */
3175 INP_INFO_WLOCK_ASSERT(&tcbinfo);
3176 INP_LOCK_ASSERT(tw->tw_inpcb);
3177
3178 thflags = th->th_flags;
3179
3180 /*
3181 * NOTE: for FIN_WAIT_2 (to be added later),
3182 * must validate sequence number before accepting RST
3183 */
3184
3185 /*
3186 * If the segment contains RST:
3187 * Drop the segment - see Stevens, vol. 2, p. 964 and
3188 * RFC 1337.
3189 */
3190 if (thflags & TH_RST)
3191 goto drop;
3192
3193 #if 0
3194 /* PAWS not needed at the moment */
3195 /*
3196 * RFC 1323 PAWS: If we have a timestamp reply on this segment
3197 * and it's less than ts_recent, drop it.
3198 */
3199 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
3200 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
3201 if ((thflags & TH_ACK) == 0)
3202 goto drop;
3203 goto ack;
3204 }
3205 /*
3206 * ts_recent is never updated because we never accept new segments.
3207 */
3208 #endif
3209
3210 /*
3211 * If a new connection request is received
3212 * while in TIME_WAIT, drop the old connection
3213 * and start over if the sequence numbers
3214 * are above the previous ones.
3215 */
3216 if ((thflags & TH_SYN) && SEQ_GT(th->th_seq, tw->rcv_nxt)) {
3217 tcp_twclose(tw, 0);
3218 return (1);
3219 }
3220
3221 /*
3222 * Drop the the segment if it does not contain an ACK.
3223 */
3224 if ((thflags & TH_ACK) == 0)
3225 goto drop;
3226
3227 /*
3228 * Reset the 2MSL timer if this is a duplicate FIN.
3229 */
3230 if (thflags & TH_FIN) {
3231 seq = th->th_seq + tlen + (thflags & TH_SYN ? 1 : 0);
3232 if (seq + 1 == tw->rcv_nxt)
3233 tcp_timer_2msl_reset(tw, 1);
3234 }
3235
3236 /*
3237 * Acknowledge the segment if it has data or is not a duplicate ACK.
3238 */
3239 if (thflags != TH_ACK || tlen != 0 ||
3240 th->th_seq != tw->rcv_nxt || th->th_ack != tw->snd_nxt)
3241 tcp_twrespond(tw, TH_ACK);
3242 goto drop;
3243
3244 /*
3245 * Generate a RST, dropping incoming segment.
3246 * Make ACK acceptable to originator of segment.
3247 * Don't bother to respond if destination was broadcast/multicast.
3248 */
3249 if (m->m_flags & (M_BCAST|M_MCAST))
3250 goto drop;
3251 if (isipv6) {
3252 struct ip6_hdr *ip6;
3253
3254 /* IPv6 anycast check is done at tcp6_input() */
3255 ip6 = mtod(m, struct ip6_hdr *);
3256 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
3257 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
3258 goto drop;
3259 } else {
3260 struct ip *ip;
3261
3262 ip = mtod(m, struct ip *);
3263 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
3264 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
3265 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
3266 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3267 goto drop;
3268 }
3269 if (thflags & TH_ACK) {
3270 tcp_respond(NULL,
3271 mtod(m, void *), th, m, 0, th->th_ack, TH_RST);
3272 } else {
3273 seq = th->th_seq + (thflags & TH_SYN ? 1 : 0);
3274 tcp_respond(NULL,
3275 mtod(m, void *), th, m, seq, 0, TH_RST|TH_ACK);
3276 }
3277 INP_UNLOCK(tw->tw_inpcb);
3278 return (0);
3279
3280 drop:
3281 INP_UNLOCK(tw->tw_inpcb);
3282 m_freem(m);
3283 return (0);
3284 }
Cache object: 53abb63001b840bbaeb8755c18f5f953
|