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