tcp_input.c revision 1.92 1 /* $NetBSD: tcp_input.c,v 1.92 1999/08/23 14:14:30 christos Exp $ */
2
3 /*
4 %%% portions-copyright-nrl-95
5 Portions of this software are Copyright 1995-1998 by Randall Atkinson,
6 Ronald Lee, Daniel McDonald, Bao Phan, and Chris Winters. All Rights
7 Reserved. All rights under this copyright have been assigned to the US
8 Naval Research Laboratory (NRL). The NRL Copyright Notice and License
9 Agreement Version 1.1 (January 17, 1995) applies to these portions of the
10 software.
11 You should have received a copy of the license with this software. If you
12 didn't get a copy, you may request one from <license (at) ipv6.nrl.navy.mil>.
13
14 */
15
16 /*
17 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
18 * All rights reserved.
19 *
20 * Redistribution and use in source and binary forms, with or without
21 * modification, are permitted provided that the following conditions
22 * are met:
23 * 1. Redistributions of source code must retain the above copyright
24 * notice, this list of conditions and the following disclaimer.
25 * 2. Redistributions in binary form must reproduce the above copyright
26 * notice, this list of conditions and the following disclaimer in the
27 * documentation and/or other materials provided with the distribution.
28 * 3. Neither the name of the project nor the names of its contributors
29 * may be used to endorse or promote products derived from this software
30 * without specific prior written permission.
31 *
32 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
33 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
34 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
35 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
36 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
37 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
38 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
39 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
40 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
41 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 * SUCH DAMAGE.
43 */
44
45 /*-
46 * Copyright (c) 1997, 1998, 1999 The NetBSD Foundation, Inc.
47 * All rights reserved.
48 *
49 * This code is derived from software contributed to The NetBSD Foundation
50 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
51 * Facility, NASA Ames Research Center.
52 *
53 * Redistribution and use in source and binary forms, with or without
54 * modification, are permitted provided that the following conditions
55 * are met:
56 * 1. Redistributions of source code must retain the above copyright
57 * notice, this list of conditions and the following disclaimer.
58 * 2. Redistributions in binary form must reproduce the above copyright
59 * notice, this list of conditions and the following disclaimer in the
60 * documentation and/or other materials provided with the distribution.
61 * 3. All advertising materials mentioning features or use of this software
62 * must display the following acknowledgement:
63 * This product includes software developed by the NetBSD
64 * Foundation, Inc. and its contributors.
65 * 4. Neither the name of The NetBSD Foundation nor the names of its
66 * contributors may be used to endorse or promote products derived
67 * from this software without specific prior written permission.
68 *
69 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
70 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
71 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
72 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
73 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
74 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
75 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
76 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
77 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
78 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
79 * POSSIBILITY OF SUCH DAMAGE.
80 */
81
82 /*
83 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
84 * The Regents of the University of California. All rights reserved.
85 *
86 * Redistribution and use in source and binary forms, with or without
87 * modification, are permitted provided that the following conditions
88 * are met:
89 * 1. Redistributions of source code must retain the above copyright
90 * notice, this list of conditions and the following disclaimer.
91 * 2. Redistributions in binary form must reproduce the above copyright
92 * notice, this list of conditions and the following disclaimer in the
93 * documentation and/or other materials provided with the distribution.
94 * 3. All advertising materials mentioning features or use of this software
95 * must display the following acknowledgement:
96 * This product includes software developed by the University of
97 * California, Berkeley and its contributors.
98 * 4. Neither the name of the University nor the names of its contributors
99 * may be used to endorse or promote products derived from this software
100 * without specific prior written permission.
101 *
102 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
103 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
104 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
105 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
106 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
107 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
108 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
109 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
110 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
111 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
112 * SUCH DAMAGE.
113 *
114 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
115 */
116
117 /*
118 * TODO list for SYN cache stuff:
119 *
120 * Find room for a "state" field, which is needed to keep a
121 * compressed state for TIME_WAIT TCBs. It's been noted already
122 * that this is fairly important for very high-volume web and
123 * mail servers, which use a large number of short-lived
124 * connections.
125 */
126
127 #include "opt_inet.h"
128 #include "opt_ipsec.h"
129
130 #include <sys/param.h>
131 #include <sys/systm.h>
132 #include <sys/malloc.h>
133 #include <sys/mbuf.h>
134 #include <sys/protosw.h>
135 #include <sys/socket.h>
136 #include <sys/socketvar.h>
137 #include <sys/errno.h>
138 #include <sys/syslog.h>
139 #include <sys/pool.h>
140 #include <sys/domain.h>
141
142 #include <net/if.h>
143 #include <net/route.h>
144 #include <net/if_types.h>
145
146 #include <netinet/in.h>
147 #include <netinet/in_systm.h>
148 #include <netinet/ip.h>
149 #include <netinet/in_pcb.h>
150 #include <netinet/ip_var.h>
151
152 #ifdef INET6
153 #ifndef INET
154 #include <netinet/in.h>
155 #endif
156 #include <netinet/ip6.h>
157 #include <netinet6/in6_pcb.h>
158 #include <netinet6/ip6_var.h>
159 #include <netinet6/in6_var.h>
160 #include <netinet/icmp6.h>
161 #endif
162
163 #include <netinet/tcp.h>
164 #include <netinet/tcp_fsm.h>
165 #include <netinet/tcp_seq.h>
166 #include <netinet/tcp_timer.h>
167 #include <netinet/tcp_var.h>
168 #include <netinet/tcpip.h>
169 #include <netinet/tcp_debug.h>
170
171 #include <machine/stdarg.h>
172
173 #ifdef IPSEC
174 #include <netinet6/ipsec.h>
175 #include <netkey/key.h>
176 #include <netkey/key_debug.h>
177 #endif /*IPSEC*/
178 #ifdef INET6
179 #include "faith.h"
180 #endif
181
182 int tcprexmtthresh = 3;
183 int tcp_log_refused;
184
185 #define TCP_PAWS_IDLE (24 * 24 * 60 * 60 * PR_SLOWHZ)
186
187 /* for modulo comparisons of timestamps */
188 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
189 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
190
191 /*
192 * Macro to compute ACK transmission behavior. Delay the ACK unless
193 * we have already delayed an ACK (must send an ACK every two segments).
194 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
195 * option is enabled.
196 */
197 #define TCP_SETUP_ACK(tp, th) \
198 do { \
199 if ((tp)->t_flags & TF_DELACK || \
200 (tcp_ack_on_push && (th)->th_flags & TH_PUSH)) \
201 tp->t_flags |= TF_ACKNOW; \
202 else \
203 TCP_SET_DELACK(tp); \
204 } while (0)
205
206 int
207 tcp_reass(tp, th, m, tlen)
208 register struct tcpcb *tp;
209 register struct tcphdr *th;
210 struct mbuf *m;
211 int *tlen;
212 {
213 register struct ipqent *p, *q, *nq, *tiqe = NULL;
214 struct socket *so = NULL;
215 int pkt_flags;
216 tcp_seq pkt_seq;
217 unsigned pkt_len;
218 u_long rcvpartdupbyte = 0;
219 u_long rcvoobyte;
220
221 if (tp->t_inpcb)
222 so = tp->t_inpcb->inp_socket;
223 #ifdef INET6
224 else if (tp->t_in6pcb)
225 so = tp->t_in6pcb->in6p_socket;
226 #endif
227
228 TCP_REASS_LOCK_CHECK(tp);
229
230 /*
231 * Call with th==0 after become established to
232 * force pre-ESTABLISHED data up to user socket.
233 */
234 if (th == 0)
235 goto present;
236
237 rcvoobyte = *tlen;
238 /*
239 * Copy these to local variables because the tcpiphdr
240 * gets munged while we are collapsing mbufs.
241 */
242 pkt_seq = th->th_seq;
243 pkt_len = *tlen;
244 pkt_flags = th->th_flags;
245 /*
246 * Find a segment which begins after this one does.
247 */
248 for (p = NULL, q = tp->segq.lh_first; q != NULL; q = nq) {
249 nq = q->ipqe_q.le_next;
250 /*
251 * If the received segment is just right after this
252 * fragment, merge the two together and then check
253 * for further overlaps.
254 */
255 if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
256 #ifdef TCPREASS_DEBUG
257 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
258 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
259 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
260 #endif
261 pkt_len += q->ipqe_len;
262 pkt_flags |= q->ipqe_flags;
263 pkt_seq = q->ipqe_seq;
264 m_cat(q->ipqe_m, m);
265 m = q->ipqe_m;
266 goto free_ipqe;
267 }
268 /*
269 * If the received segment is completely past this
270 * fragment, we need to go the next fragment.
271 */
272 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
273 p = q;
274 continue;
275 }
276 /*
277 * If the fragment is past the received segment,
278 * it (or any following) can't be concatenated.
279 */
280 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len))
281 break;
282 /*
283 * We've received all the data in this segment before.
284 * mark it as a duplicate and return.
285 */
286 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
287 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
288 tcpstat.tcps_rcvduppack++;
289 tcpstat.tcps_rcvdupbyte += pkt_len;
290 m_freem(m);
291 if (tiqe != NULL)
292 pool_put(&ipqent_pool, tiqe);
293 return (0);
294 }
295 /*
296 * Received segment completely overlaps this fragment
297 * so we drop the fragment (this keeps the temporal
298 * ordering of segments correct).
299 */
300 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
301 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
302 rcvpartdupbyte += q->ipqe_len;
303 m_freem(q->ipqe_m);
304 goto free_ipqe;
305 }
306 /*
307 * RX'ed segment extends past the end of the
308 * fragment. Drop the overlapping bytes. Then
309 * merge the fragment and segment then treat as
310 * a longer received packet.
311 */
312 if (SEQ_LT(q->ipqe_seq, pkt_seq)
313 && SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
314 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
315 #ifdef TCPREASS_DEBUG
316 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
317 tp, overlap,
318 pkt_seq, pkt_seq + pkt_len, pkt_len);
319 #endif
320 m_adj(m, overlap);
321 rcvpartdupbyte += overlap;
322 m_cat(q->ipqe_m, m);
323 m = q->ipqe_m;
324 pkt_seq = q->ipqe_seq;
325 pkt_len += q->ipqe_len - overlap;
326 rcvoobyte -= overlap;
327 goto free_ipqe;
328 }
329 /*
330 * RX'ed segment extends past the front of the
331 * fragment. Drop the overlapping bytes on the
332 * received packet. The packet will then be
333 * contatentated with this fragment a bit later.
334 */
335 if (SEQ_GT(q->ipqe_seq, pkt_seq)
336 && SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) {
337 int overlap = pkt_seq + pkt_len - q->ipqe_seq;
338 #ifdef TCPREASS_DEBUG
339 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
340 tp, overlap,
341 pkt_seq, pkt_seq + pkt_len, pkt_len);
342 #endif
343 m_adj(m, -overlap);
344 pkt_len -= overlap;
345 rcvpartdupbyte += overlap;
346 rcvoobyte -= overlap;
347 }
348 /*
349 * If the received segment immediates precedes this
350 * fragment then tack the fragment onto this segment
351 * and reinsert the data.
352 */
353 if (q->ipqe_seq == pkt_seq + pkt_len) {
354 #ifdef TCPREASS_DEBUG
355 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
356 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
357 pkt_seq, pkt_seq + pkt_len, pkt_len);
358 #endif
359 pkt_len += q->ipqe_len;
360 pkt_flags |= q->ipqe_flags;
361 m_cat(m, q->ipqe_m);
362 LIST_REMOVE(q, ipqe_q);
363 LIST_REMOVE(q, ipqe_timeq);
364 if (tiqe == NULL) {
365 tiqe = q;
366 } else {
367 pool_put(&ipqent_pool, q);
368 }
369 break;
370 }
371 /*
372 * If the fragment is before the segment, remember it.
373 * When this loop is terminated, p will contain the
374 * pointer to fragment that is right before the received
375 * segment.
376 */
377 if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
378 p = q;
379
380 continue;
381
382 /*
383 * This is a common operation. It also will allow
384 * to save doing a malloc/free in most instances.
385 */
386 free_ipqe:
387 LIST_REMOVE(q, ipqe_q);
388 LIST_REMOVE(q, ipqe_timeq);
389 if (tiqe == NULL) {
390 tiqe = q;
391 } else {
392 pool_put(&ipqent_pool, q);
393 }
394 }
395
396 /*
397 * Allocate a new queue entry since the received segment did not
398 * collapse onto any other out-of-order block; thus we are allocating
399 * a new block. If it had collapsed, tiqe would not be NULL and
400 * we would be reusing it.
401 * XXX If we can't, just drop the packet. XXX
402 */
403 if (tiqe == NULL) {
404 tiqe = pool_get(&ipqent_pool, PR_NOWAIT);
405 if (tiqe == NULL) {
406 tcpstat.tcps_rcvmemdrop++;
407 m_freem(m);
408 return (0);
409 }
410 }
411
412 /*
413 * Update the counters.
414 */
415 tcpstat.tcps_rcvoopack++;
416 tcpstat.tcps_rcvoobyte += rcvoobyte;
417 if (rcvpartdupbyte) {
418 tcpstat.tcps_rcvpartduppack++;
419 tcpstat.tcps_rcvpartdupbyte += rcvpartdupbyte;
420 }
421
422 /*
423 * Insert the new fragment queue entry into both queues.
424 */
425 tiqe->ipqe_m = m;
426 tiqe->ipqe_seq = pkt_seq;
427 tiqe->ipqe_len = pkt_len;
428 tiqe->ipqe_flags = pkt_flags;
429 if (p == NULL) {
430 LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
431 #ifdef TCPREASS_DEBUG
432 if (tiqe->ipqe_seq != tp->rcv_nxt)
433 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
434 tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
435 #endif
436 } else {
437 LIST_INSERT_AFTER(p, tiqe, ipqe_q);
438 #ifdef TCPREASS_DEBUG
439 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
440 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
441 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
442 #endif
443 }
444
445 LIST_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
446
447 present:
448 /*
449 * Present data to user, advancing rcv_nxt through
450 * completed sequence space.
451 */
452 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
453 return (0);
454 q = tp->segq.lh_first;
455 if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
456 return (0);
457 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
458 return (0);
459
460 tp->rcv_nxt += q->ipqe_len;
461 pkt_flags = q->ipqe_flags & TH_FIN;
462
463 LIST_REMOVE(q, ipqe_q);
464 LIST_REMOVE(q, ipqe_timeq);
465 if (so->so_state & SS_CANTRCVMORE)
466 m_freem(q->ipqe_m);
467 else
468 sbappend(&so->so_rcv, q->ipqe_m);
469 pool_put(&ipqent_pool, q);
470 sorwakeup(so);
471 return (pkt_flags);
472 }
473
474 #if defined(INET6) && !defined(TCP6)
475 int
476 tcp6_input(mp, offp, proto)
477 struct mbuf **mp;
478 int *offp, proto;
479 {
480 struct mbuf *m = *mp;
481
482 #if defined(NFAITH) && 0 < NFAITH
483 if (m->m_pkthdr.rcvif) {
484 if (m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
485 /* XXX send icmp6 host/port unreach? */
486 m_freem(m);
487 return IPPROTO_DONE;
488 }
489 }
490 #endif
491
492 /*
493 * draft-itojun-ipv6-tcp-to-anycast
494 * better place to put this in?
495 */
496 if (m->m_flags & M_ANYCAST6) {
497 if (m->m_len >= sizeof(struct ip6_hdr)) {
498 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
499 icmp6_error(m, ICMP6_DST_UNREACH,
500 ICMP6_DST_UNREACH_ADDR,
501 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
502 } else
503 m_freem(m);
504 return IPPROTO_DONE;
505 }
506
507 tcp_input(m, *offp, proto);
508 return IPPROTO_DONE;
509 }
510 #endif
511
512 /*
513 * TCP input routine, follows pages 65-76 of the
514 * protocol specification dated September, 1981 very closely.
515 */
516 void
517 #if __STDC__
518 tcp_input(struct mbuf *m, ...)
519 #else
520 tcp_input(m, va_alist)
521 register struct mbuf *m;
522 #endif
523 {
524 int proto;
525 register struct tcphdr *th;
526 struct ip *ip;
527 register struct inpcb *inp;
528 #ifdef INET6
529 struct ip6_hdr *ip6;
530 register struct in6pcb *in6p;
531 #endif
532 caddr_t optp = NULL;
533 int optlen = 0;
534 int len, tlen, toff, hdroptlen = 0;
535 register struct tcpcb *tp = 0;
536 register int tiflags;
537 struct socket *so = NULL;
538 int todrop, acked, ourfinisacked, needoutput = 0;
539 short ostate = 0;
540 int iss = 0;
541 u_long tiwin;
542 struct tcp_opt_info opti;
543 int off, iphlen;
544 va_list ap;
545 int af; /* af on the wire */
546 struct mbuf *tcp_saveti = NULL;
547
548 va_start(ap, m);
549 toff = va_arg(ap, int);
550 proto = va_arg(ap, int);
551 va_end(ap);
552
553 tcpstat.tcps_rcvtotal++;
554
555 bzero(&opti, sizeof(opti));
556 opti.ts_present = 0;
557 opti.maxseg = 0;
558
559 /*
560 * Get IP and TCP header together in first mbuf.
561 * Note: IP leaves IP header in first mbuf.
562 */
563 ip = mtod(m, struct ip *);
564 #ifdef INET6
565 ip6 = NULL;
566 #endif
567 switch (ip->ip_v) {
568 case 4:
569 af = AF_INET;
570 iphlen = sizeof(struct ip);
571 /* would like to get rid of this... */
572 if (toff > sizeof (struct ip)) {
573 ip_stripoptions(m, (struct mbuf *)0);
574 toff = sizeof(struct ip);
575 }
576 if (m->m_len < toff + sizeof (struct tcphdr)) {
577 if ((m = m_pullup(m, toff + sizeof (struct tcphdr))) == 0) {
578 tcpstat.tcps_rcvshort++;
579 return;
580 }
581 }
582 ip = mtod(m, struct ip *);
583 th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
584
585 /*
586 * Checksum extended TCP header and data.
587 */
588 len = ip->ip_len;
589 tlen = len - toff;
590 {
591 struct ipovly *ipov;
592 ipov = (struct ipovly *)ip;
593 bzero(ipov->ih_x1, sizeof ipov->ih_x1);
594 ipov->ih_len = htons(tlen);
595 }
596 if (in_cksum(m, len) != 0) {
597 tcpstat.tcps_rcvbadsum++;
598 goto drop;
599 }
600 break;
601 #ifdef INET6
602 case 6:
603 ip = NULL;
604 iphlen = sizeof(struct ip6_hdr);
605 af = AF_INET6;
606 if (m->m_len < toff + sizeof(struct tcphdr)) {
607 m = m_pullup(m, toff + sizeof(struct tcphdr)); /*XXX*/
608 if (m == NULL) {
609 tcpstat.tcps_rcvshort++;
610 return;
611 }
612 }
613 ip6 = mtod(m, struct ip6_hdr *);
614 th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
615
616 /*
617 * Checksum extended TCP header and data.
618 */
619 len = m->m_pkthdr.len;
620 tlen = len - toff;
621 if (in6_cksum(m, IPPROTO_TCP, toff, tlen)) {
622 tcpstat.tcps_rcvbadsum++;
623 goto drop;
624 }
625 break;
626 #endif
627 default:
628 m_freem(m);
629 return;
630 }
631
632 /*
633 * Check that TCP offset makes sense,
634 * pull out TCP options and adjust length. XXX
635 */
636 off = th->th_off << 2;
637 if (off < sizeof (struct tcphdr) || off > tlen) {
638 tcpstat.tcps_rcvbadoff++;
639 goto drop;
640 }
641 tlen -= off;
642
643 /*
644 * tcp_input() has been modified to use tlen to mean the TCP data
645 * length throughout the function. Other functions can use
646 * m->m_pkthdr.len as the basis for calculating the TCP data length.
647 * rja
648 */
649
650 if (off > sizeof (struct tcphdr)) {
651 if (m->m_len < toff + off) {
652 if ((m = m_pullup(m, toff + off)) == 0) {
653 tcpstat.tcps_rcvshort++;
654 return;
655 }
656 switch (af) {
657 case AF_INET:
658 ip = mtod(m, struct ip *);
659 break;
660 #ifdef INET6
661 case AF_INET6:
662 ip6 = mtod(m, struct ip6_hdr *);
663 break;
664 #endif
665 }
666 th = (struct tcphdr *)(mtod(m, caddr_t) + toff);
667 }
668 optlen = off - sizeof (struct tcphdr);
669 optp = mtod(m, caddr_t) + toff + sizeof (struct tcphdr);
670 /*
671 * Do quick retrieval of timestamp options ("options
672 * prediction?"). If timestamp is the only option and it's
673 * formatted as recommended in RFC 1323 appendix A, we
674 * quickly get the values now and not bother calling
675 * tcp_dooptions(), etc.
676 */
677 if ((optlen == TCPOLEN_TSTAMP_APPA ||
678 (optlen > TCPOLEN_TSTAMP_APPA &&
679 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
680 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
681 (th->th_flags & TH_SYN) == 0) {
682 opti.ts_present = 1;
683 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
684 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
685 optp = NULL; /* we've parsed the options */
686 }
687 }
688 tiflags = th->th_flags;
689
690 /*
691 * Convert TCP protocol specific fields to host format.
692 */
693 NTOHL(th->th_seq);
694 NTOHL(th->th_ack);
695 NTOHS(th->th_win);
696 NTOHS(th->th_urp);
697
698 /*
699 * Locate pcb for segment.
700 */
701 findpcb:
702 inp = NULL;
703 #ifdef INET6
704 in6p = NULL;
705 #endif
706 switch (af) {
707 case AF_INET:
708 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
709 ip->ip_dst, th->th_dport);
710 if (inp == 0) {
711 ++tcpstat.tcps_pcbhashmiss;
712 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
713 }
714 #if defined(INET6) && !defined(TCP6)
715 if (inp == 0) {
716 struct in6_addr s, d;
717
718 /* mapped addr case */
719 bzero(&s, sizeof(s));
720 s.s6_addr16[5] = htons(0xffff);
721 bcopy(&ip->ip_src, &s.s6_addr32[3], sizeof(ip->ip_src));
722 bzero(&d, sizeof(d));
723 d.s6_addr16[5] = htons(0xffff);
724 bcopy(&ip->ip_dst, &d.s6_addr32[3], sizeof(ip->ip_dst));
725 in6p = in6_pcblookup_connect(&tcb6, &s, th->th_sport,
726 &d, th->th_dport, 0);
727 if (in6p == 0) {
728 ++tcpstat.tcps_pcbhashmiss;
729 in6p = in6_pcblookup_bind(&tcb6, &d,
730 th->th_dport, 0);
731 }
732 }
733 #endif
734 #ifndef INET6
735 if (inp == 0)
736 #else
737 if (inp == 0 && in6p == 0)
738 #endif
739 {
740 ++tcpstat.tcps_noport;
741 if (tcp_log_refused && (tiflags & TH_SYN)) {
742 #ifndef INET6
743 char src[4*sizeof "123"];
744 char dst[4*sizeof "123"];
745 #else
746 char src[INET6_ADDRSTRLEN];
747 char dst[INET6_ADDRSTRLEN];
748 #endif
749 if (ip) {
750 strcpy(src, inet_ntoa(ip->ip_src));
751 strcpy(dst, inet_ntoa(ip->ip_dst));
752 }
753 #ifdef INET6
754 else if (ip6) {
755 strcpy(src, ip6_sprintf(&ip6->ip6_src));
756 strcpy(dst, ip6_sprintf(&ip6->ip6_dst));
757 }
758 #endif
759 else {
760 strcpy(src, "(unknown)");
761 strcpy(dst, "(unknown)");
762 }
763 log(LOG_INFO,
764 "Connection attempt to TCP %s:%d from %s:%d\n",
765 dst, ntohs(th->th_dport),
766 src, ntohs(th->th_sport));
767 }
768 goto dropwithreset;
769 }
770 #ifdef IPSEC
771 if (inp && ipsec4_in_reject(m, inp)) {
772 ipsecstat.in_polvio++;
773 goto drop;
774 }
775 #ifdef INET6
776 else if (in6p && ipsec4_in_reject_so(m, in6p->in6p_socket)) {
777 ipsecstat.in_polvio++;
778 goto drop;
779 }
780 #endif
781 #endif /*IPSEC*/
782 break;
783 #if defined(INET6) && !defined(TCP6)
784 case AF_INET6:
785 {
786 int faith;
787
788 #if defined(NFAITH) && NFAITH > 0
789 if (m->m_pkthdr.rcvif
790 && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
791 faith = 1;
792 } else
793 faith = 0;
794 #else
795 faith = 0;
796 #endif
797 in6p = in6_pcblookup_connect(&tcb6, &ip6->ip6_src, th->th_sport,
798 &ip6->ip6_dst, th->th_dport, faith);
799 if (in6p == NULL) {
800 ++tcpstat.tcps_pcbhashmiss;
801 in6p = in6_pcblookup_bind(&tcb6, &ip6->ip6_dst,
802 th->th_dport, faith);
803 }
804 if (in6p == NULL) {
805 ++tcpstat.tcps_noport;
806 goto dropwithreset;
807 }
808 #ifdef IPSEC
809 if (ipsec6_in_reject(m, in6p)) {
810 ipsec6stat.in_polvio++;
811 goto drop;
812 }
813 #endif /*IPSEC*/
814 break;
815 }
816 #endif
817 }
818
819 /*
820 * If the state is CLOSED (i.e., TCB does not exist) then
821 * all data in the incoming segment is discarded.
822 * If the TCB exists but is in CLOSED state, it is embryonic,
823 * but should either do a listen or a connect soon.
824 */
825 tp = NULL;
826 so = NULL;
827 if (inp) {
828 tp = intotcpcb(inp);
829 so = inp->inp_socket;
830 }
831 #ifdef INET6
832 else if (in6p) {
833 tp = in6totcpcb(in6p);
834 so = in6p->in6p_socket;
835 }
836 #endif
837 if (tp == 0) {
838 goto dropwithreset;
839 }
840 if (tp->t_state == TCPS_CLOSED)
841 goto drop;
842
843 /* Unscale the window into a 32-bit value. */
844 if ((tiflags & TH_SYN) == 0)
845 tiwin = th->th_win << tp->snd_scale;
846 else
847 tiwin = th->th_win;
848
849 #ifdef INET6
850 /* save packet options if user wanted */
851 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
852 if (in6p->in6p_options) {
853 m_freem(in6p->in6p_options);
854 in6p->in6p_options = 0;
855 }
856 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
857 }
858 #endif
859
860 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
861 union syn_cache_sa src;
862 union syn_cache_sa dst;
863
864 bzero(&src, sizeof(src));
865 bzero(&dst, sizeof(dst));
866 switch (af) {
867 case AF_INET:
868 src.sin.sin_len = sizeof(struct sockaddr_in);
869 src.sin.sin_family = AF_INET;
870 src.sin.sin_addr = ip->ip_src;
871 src.sin.sin_port = th->th_sport;
872
873 dst.sin.sin_len = sizeof(struct sockaddr_in);
874 dst.sin.sin_family = AF_INET;
875 dst.sin.sin_addr = ip->ip_dst;
876 dst.sin.sin_port = th->th_dport;
877 break;
878 #ifdef INET6
879 case AF_INET6:
880 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
881 src.sin6.sin6_family = AF_INET6;
882 src.sin6.sin6_addr = ip6->ip6_src;
883 src.sin6.sin6_port = th->th_sport;
884
885 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
886 dst.sin6.sin6_family = AF_INET6;
887 dst.sin6.sin6_addr = ip6->ip6_dst;
888 dst.sin6.sin6_port = th->th_dport;
889 break;
890 #endif /* INET6 */
891 default:
892 goto badsyn; /*sanity*/
893 }
894
895 if (so->so_options & SO_DEBUG) {
896 ostate = tp->t_state;
897 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
898 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
899 m_freem(tcp_saveti);
900 tcp_saveti = NULL;
901 } else {
902 tcp_saveti->m_len += sizeof(struct tcphdr);
903 bcopy(th, mtod(tcp_saveti, caddr_t) + iphlen,
904 sizeof(struct tcphdr));
905 }
906 if (tcp_saveti) {
907 /*
908 * need to recover version # field, which was
909 * overwritten on ip_cksum computation.
910 */
911 struct ip *sip;
912 sip = mtod(tcp_saveti, struct ip *);
913 switch (af) {
914 case AF_INET:
915 sip->ip_v = 4;
916 break;
917 #ifdef INET6
918 case AF_INET6:
919 sip->ip_v = 6;
920 break;
921 #endif
922 }
923 }
924 }
925 if (so->so_options & SO_ACCEPTCONN) {
926 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
927 if (tiflags & TH_RST) {
928 syn_cache_reset(&src.sa, &dst.sa, th);
929 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
930 (TH_ACK|TH_SYN)) {
931 /*
932 * Received a SYN,ACK. This should
933 * never happen while we are in
934 * LISTEN. Send an RST.
935 */
936 goto badsyn;
937 } else if (tiflags & TH_ACK) {
938 so = syn_cache_get(&src.sa, &dst.sa,
939 th, toff, tlen, so, m);
940 if (so == NULL) {
941 /*
942 * We don't have a SYN for
943 * this ACK; send an RST.
944 */
945 goto badsyn;
946 } else if (so ==
947 (struct socket *)(-1)) {
948 /*
949 * We were unable to create
950 * the connection. If the
951 * 3-way handshake was
952 * completed, and RST has
953 * been sent to the peer.
954 * Since the mbuf might be
955 * in use for the reply,
956 * do not free it.
957 */
958 m = NULL;
959 } else {
960 /*
961 * We have created a
962 * full-blown connection.
963 */
964 tp = NULL;
965 inp = NULL;
966 #ifdef INET6
967 in6p = NULL;
968 #endif
969 switch (so->so_proto->pr_domain->dom_family) {
970 case AF_INET:
971 inp = sotoinpcb(so);
972 tp = intotcpcb(inp);
973 break;
974 #ifdef INET6
975 case AF_INET6:
976 in6p = sotoin6pcb(so);
977 tp = in6totcpcb(in6p);
978 break;
979 #endif
980 }
981 if (tp == NULL)
982 goto badsyn; /*XXX*/
983 tiwin <<= tp->snd_scale;
984 goto after_listen;
985 }
986 } else {
987 /*
988 * None of RST, SYN or ACK was set.
989 * This is an invalid packet for a
990 * TCB in LISTEN state. Send a RST.
991 */
992 goto badsyn;
993 }
994 } else {
995 /*
996 * Received a SYN.
997 */
998
999 /*
1000 * LISTEN socket received a SYN
1001 * from itself? This can't possibly
1002 * be valid; drop the packet.
1003 */
1004 if (th->th_sport == th->th_dport) {
1005 int i;
1006
1007 switch (af) {
1008 case AF_INET:
1009 i = in_hosteq(ip->ip_src, ip->ip_dst);
1010 break;
1011 #ifdef INET6
1012 case AF_INET6:
1013 i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1014 break;
1015 #endif
1016 default:
1017 i = 1;
1018 }
1019 if (i) {
1020 tcpstat.tcps_badsyn++;
1021 goto drop;
1022 }
1023 }
1024
1025 /*
1026 * SYN looks ok; create compressed TCP
1027 * state for it.
1028 */
1029 if (so->so_qlen <= so->so_qlimit &&
1030 syn_cache_add(&src.sa, &dst.sa, th, tlen,
1031 so, m, optp, optlen, &opti))
1032 m = NULL;
1033 }
1034 goto drop;
1035 }
1036 }
1037
1038 after_listen:
1039 #ifdef DIAGNOSTIC
1040 /*
1041 * Should not happen now that all embryonic connections
1042 * are handled with compressed state.
1043 */
1044 if (tp->t_state == TCPS_LISTEN)
1045 panic("tcp_input: TCPS_LISTEN");
1046 #endif
1047
1048 /*
1049 * Segment received on connection.
1050 * Reset idle time and keep-alive timer.
1051 */
1052 tp->t_idle = 0;
1053 if (TCPS_HAVEESTABLISHED(tp->t_state))
1054 TCP_TIMER_ARM(tp, TCPT_KEEP, tcp_keepidle);
1055
1056 /*
1057 * Process options.
1058 */
1059 if (optp)
1060 tcp_dooptions(tp, optp, optlen, th, &opti);
1061
1062 /*
1063 * Header prediction: check for the two common cases
1064 * of a uni-directional data xfer. If the packet has
1065 * no control flags, is in-sequence, the window didn't
1066 * change and we're not retransmitting, it's a
1067 * candidate. If the length is zero and the ack moved
1068 * forward, we're the sender side of the xfer. Just
1069 * free the data acked & wake any higher level process
1070 * that was blocked waiting for space. If the length
1071 * is non-zero and the ack didn't move, we're the
1072 * receiver side. If we're getting packets in-order
1073 * (the reassembly queue is empty), add the data to
1074 * the socket buffer and note that we need a delayed ack.
1075 */
1076 if (tp->t_state == TCPS_ESTABLISHED &&
1077 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1078 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1079 th->th_seq == tp->rcv_nxt &&
1080 tiwin && tiwin == tp->snd_wnd &&
1081 tp->snd_nxt == tp->snd_max) {
1082
1083 /*
1084 * If last ACK falls within this segment's sequence numbers,
1085 * record the timestamp.
1086 */
1087 if (opti.ts_present &&
1088 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1089 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen)) {
1090 tp->ts_recent_age = tcp_now;
1091 tp->ts_recent = opti.ts_val;
1092 }
1093
1094 if (tlen == 0) {
1095 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1096 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1097 tp->snd_cwnd >= tp->snd_wnd &&
1098 tp->t_dupacks < tcprexmtthresh) {
1099 /*
1100 * this is a pure ack for outstanding data.
1101 */
1102 ++tcpstat.tcps_predack;
1103 if (opti.ts_present && opti.ts_ecr)
1104 tcp_xmit_timer(tp,
1105 tcp_now - opti.ts_ecr + 1);
1106 else if (tp->t_rtt &&
1107 SEQ_GT(th->th_ack, tp->t_rtseq))
1108 tcp_xmit_timer(tp, tp->t_rtt);
1109 acked = th->th_ack - tp->snd_una;
1110 tcpstat.tcps_rcvackpack++;
1111 tcpstat.tcps_rcvackbyte += acked;
1112 sbdrop(&so->so_snd, acked);
1113 /*
1114 * We want snd_recover to track snd_una to
1115 * avoid sequence wraparound problems for
1116 * very large transfers.
1117 */
1118 tp->snd_una = tp->snd_recover = th->th_ack;
1119 m_freem(m);
1120
1121 /*
1122 * If all outstanding data are acked, stop
1123 * retransmit timer, otherwise restart timer
1124 * using current (possibly backed-off) value.
1125 * If process is waiting for space,
1126 * wakeup/selwakeup/signal. If data
1127 * are ready to send, let tcp_output
1128 * decide between more output or persist.
1129 */
1130 if (tp->snd_una == tp->snd_max)
1131 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1132 else if (TCP_TIMER_ISARMED(tp,
1133 TCPT_PERSIST) == 0)
1134 TCP_TIMER_ARM(tp, TCPT_REXMT,
1135 tp->t_rxtcur);
1136
1137 sowwakeup(so);
1138 if (so->so_snd.sb_cc)
1139 (void) tcp_output(tp);
1140 if (tcp_saveti)
1141 m_freem(tcp_saveti);
1142 return;
1143 }
1144 } else if (th->th_ack == tp->snd_una &&
1145 tp->segq.lh_first == NULL &&
1146 tlen <= sbspace(&so->so_rcv)) {
1147 /*
1148 * this is a pure, in-sequence data packet
1149 * with nothing on the reassembly queue and
1150 * we have enough buffer space to take it.
1151 */
1152 ++tcpstat.tcps_preddat;
1153 tp->rcv_nxt += tlen;
1154 tcpstat.tcps_rcvpack++;
1155 tcpstat.tcps_rcvbyte += tlen;
1156 /*
1157 * Drop TCP, IP headers and TCP options then add data
1158 * to socket buffer.
1159 */
1160 m->m_data += toff + off;
1161 m->m_len -= (toff + off);
1162 sbappend(&so->so_rcv, m);
1163 sorwakeup(so);
1164 TCP_SETUP_ACK(tp, th);
1165 if (tp->t_flags & TF_ACKNOW)
1166 (void) tcp_output(tp);
1167 if (tcp_saveti)
1168 m_freem(tcp_saveti);
1169 return;
1170 }
1171 }
1172
1173 /*
1174 * Drop TCP, IP headers and TCP options.
1175 */
1176 hdroptlen = toff + off;
1177 m->m_data += hdroptlen;
1178 m->m_len -= hdroptlen;
1179
1180 /*
1181 * Calculate amount of space in receive window,
1182 * and then do TCP input processing.
1183 * Receive window is amount of space in rcv queue,
1184 * but not less than advertised window.
1185 */
1186 { int win;
1187
1188 win = sbspace(&so->so_rcv);
1189 if (win < 0)
1190 win = 0;
1191 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1192 }
1193
1194 switch (tp->t_state) {
1195
1196 /*
1197 * If the state is SYN_SENT:
1198 * if seg contains an ACK, but not for our SYN, drop the input.
1199 * if seg contains a RST, then drop the connection.
1200 * if seg does not contain SYN, then drop it.
1201 * Otherwise this is an acceptable SYN segment
1202 * initialize tp->rcv_nxt and tp->irs
1203 * if seg contains ack then advance tp->snd_una
1204 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1205 * arrange for segment to be acked (eventually)
1206 * continue processing rest of data/controls, beginning with URG
1207 */
1208 case TCPS_SYN_SENT:
1209 if ((tiflags & TH_ACK) &&
1210 (SEQ_LEQ(th->th_ack, tp->iss) ||
1211 SEQ_GT(th->th_ack, tp->snd_max)))
1212 goto dropwithreset;
1213 if (tiflags & TH_RST) {
1214 if (tiflags & TH_ACK)
1215 tp = tcp_drop(tp, ECONNREFUSED);
1216 goto drop;
1217 }
1218 if ((tiflags & TH_SYN) == 0)
1219 goto drop;
1220 if (tiflags & TH_ACK) {
1221 tp->snd_una = tp->snd_recover = th->th_ack;
1222 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1223 tp->snd_nxt = tp->snd_una;
1224 }
1225 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1226 tp->irs = th->th_seq;
1227 tcp_rcvseqinit(tp);
1228 tp->t_flags |= TF_ACKNOW;
1229 tcp_mss_from_peer(tp, opti.maxseg);
1230
1231 /*
1232 * Initialize the initial congestion window. If we
1233 * had to retransmit the SYN, we must initialize cwnd
1234 * to 1 segment (i.e. the Loss Window).
1235 */
1236 if (tp->t_flags & TF_SYN_REXMT)
1237 tp->snd_cwnd = tp->t_peermss;
1238 else
1239 tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win,
1240 tp->t_peermss);
1241
1242 tcp_rmx_rtt(tp);
1243 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
1244 tcpstat.tcps_connects++;
1245 soisconnected(so);
1246 tcp_established(tp);
1247 /* Do window scaling on this connection? */
1248 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1249 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1250 tp->snd_scale = tp->requested_s_scale;
1251 tp->rcv_scale = tp->request_r_scale;
1252 }
1253 TCP_REASS_LOCK(tp);
1254 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1255 TCP_REASS_UNLOCK(tp);
1256 /*
1257 * if we didn't have to retransmit the SYN,
1258 * use its rtt as our initial srtt & rtt var.
1259 */
1260 if (tp->t_rtt)
1261 tcp_xmit_timer(tp, tp->t_rtt);
1262 } else
1263 tp->t_state = TCPS_SYN_RECEIVED;
1264
1265 /*
1266 * Advance th->th_seq to correspond to first data byte.
1267 * If data, trim to stay within window,
1268 * dropping FIN if necessary.
1269 */
1270 th->th_seq++;
1271 if (tlen > tp->rcv_wnd) {
1272 todrop = tlen - tp->rcv_wnd;
1273 m_adj(m, -todrop);
1274 tlen = tp->rcv_wnd;
1275 tiflags &= ~TH_FIN;
1276 tcpstat.tcps_rcvpackafterwin++;
1277 tcpstat.tcps_rcvbyteafterwin += todrop;
1278 }
1279 tp->snd_wl1 = th->th_seq - 1;
1280 tp->rcv_up = th->th_seq;
1281 goto step6;
1282
1283 /*
1284 * If the state is SYN_RECEIVED:
1285 * If seg contains an ACK, but not for our SYN, drop the input
1286 * and generate an RST. See page 36, rfc793
1287 */
1288 case TCPS_SYN_RECEIVED:
1289 if ((tiflags & TH_ACK) &&
1290 (SEQ_LEQ(th->th_ack, tp->iss) ||
1291 SEQ_GT(th->th_ack, tp->snd_max)))
1292 goto dropwithreset;
1293 break;
1294 }
1295
1296 /*
1297 * States other than LISTEN or SYN_SENT.
1298 * First check timestamp, if present.
1299 * Then check that at least some bytes of segment are within
1300 * receive window. If segment begins before rcv_nxt,
1301 * drop leading data (and SYN); if nothing left, just ack.
1302 *
1303 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1304 * and it's less than ts_recent, drop it.
1305 */
1306 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1307 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
1308
1309 /* Check to see if ts_recent is over 24 days old. */
1310 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1311 /*
1312 * Invalidate ts_recent. If this segment updates
1313 * ts_recent, the age will be reset later and ts_recent
1314 * will get a valid value. If it does not, setting
1315 * ts_recent to zero will at least satisfy the
1316 * requirement that zero be placed in the timestamp
1317 * echo reply when ts_recent isn't valid. The
1318 * age isn't reset until we get a valid ts_recent
1319 * because we don't want out-of-order segments to be
1320 * dropped when ts_recent is old.
1321 */
1322 tp->ts_recent = 0;
1323 } else {
1324 tcpstat.tcps_rcvduppack++;
1325 tcpstat.tcps_rcvdupbyte += tlen;
1326 tcpstat.tcps_pawsdrop++;
1327 goto dropafterack;
1328 }
1329 }
1330
1331 todrop = tp->rcv_nxt - th->th_seq;
1332 if (todrop > 0) {
1333 if (tiflags & TH_SYN) {
1334 tiflags &= ~TH_SYN;
1335 th->th_seq++;
1336 if (th->th_urp > 1)
1337 th->th_urp--;
1338 else {
1339 tiflags &= ~TH_URG;
1340 th->th_urp = 0;
1341 }
1342 todrop--;
1343 }
1344 if (todrop > tlen ||
1345 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1346 /*
1347 * Any valid FIN must be to the left of the window.
1348 * At this point the FIN must be a duplicate or
1349 * out of sequence; drop it.
1350 */
1351 tiflags &= ~TH_FIN;
1352 /*
1353 * Send an ACK to resynchronize and drop any data.
1354 * But keep on processing for RST or ACK.
1355 */
1356 tp->t_flags |= TF_ACKNOW;
1357 todrop = tlen;
1358 tcpstat.tcps_rcvdupbyte += todrop;
1359 tcpstat.tcps_rcvduppack++;
1360 } else {
1361 tcpstat.tcps_rcvpartduppack++;
1362 tcpstat.tcps_rcvpartdupbyte += todrop;
1363 }
1364 m_adj(m, todrop);
1365 th->th_seq += todrop;
1366 tlen -= todrop;
1367 if (th->th_urp > todrop)
1368 th->th_urp -= todrop;
1369 else {
1370 tiflags &= ~TH_URG;
1371 th->th_urp = 0;
1372 }
1373 }
1374
1375 /*
1376 * If new data are received on a connection after the
1377 * user processes are gone, then RST the other end.
1378 */
1379 if ((so->so_state & SS_NOFDREF) &&
1380 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1381 tp = tcp_close(tp);
1382 tcpstat.tcps_rcvafterclose++;
1383 goto dropwithreset;
1384 }
1385
1386 /*
1387 * If segment ends after window, drop trailing data
1388 * (and PUSH and FIN); if nothing left, just ACK.
1389 */
1390 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1391 if (todrop > 0) {
1392 tcpstat.tcps_rcvpackafterwin++;
1393 if (todrop >= tlen) {
1394 tcpstat.tcps_rcvbyteafterwin += tlen;
1395 /*
1396 * If a new connection request is received
1397 * while in TIME_WAIT, drop the old connection
1398 * and start over if the sequence numbers
1399 * are above the previous ones.
1400 */
1401 if (tiflags & TH_SYN &&
1402 tp->t_state == TCPS_TIME_WAIT &&
1403 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1404 iss = tcp_new_iss(tp, sizeof(struct tcpcb),
1405 tp->snd_nxt);
1406 tp = tcp_close(tp);
1407 /*
1408 * We have already advanced the mbuf
1409 * pointers past the IP+TCP headers and
1410 * options. Restore those pointers before
1411 * attempting to use the TCP header again.
1412 */
1413 m->m_data -= hdroptlen;
1414 m->m_len += hdroptlen;
1415 hdroptlen = 0;
1416 goto findpcb;
1417 }
1418 /*
1419 * If window is closed can only take segments at
1420 * window edge, and have to drop data and PUSH from
1421 * incoming segments. Continue processing, but
1422 * remember to ack. Otherwise, drop segment
1423 * and ack.
1424 */
1425 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1426 tp->t_flags |= TF_ACKNOW;
1427 tcpstat.tcps_rcvwinprobe++;
1428 } else
1429 goto dropafterack;
1430 } else
1431 tcpstat.tcps_rcvbyteafterwin += todrop;
1432 m_adj(m, -todrop);
1433 tlen -= todrop;
1434 tiflags &= ~(TH_PUSH|TH_FIN);
1435 }
1436
1437 /*
1438 * If last ACK falls within this segment's sequence numbers,
1439 * and the timestamp is newer, record it.
1440 */
1441 if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
1442 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1443 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
1444 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1445 tp->ts_recent_age = tcp_now;
1446 tp->ts_recent = opti.ts_val;
1447 }
1448
1449 /*
1450 * If the RST bit is set examine the state:
1451 * SYN_RECEIVED STATE:
1452 * If passive open, return to LISTEN state.
1453 * If active open, inform user that connection was refused.
1454 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1455 * Inform user that connection was reset, and close tcb.
1456 * CLOSING, LAST_ACK, TIME_WAIT STATES
1457 * Close the tcb.
1458 */
1459 if (tiflags&TH_RST) switch (tp->t_state) {
1460
1461 case TCPS_SYN_RECEIVED:
1462 so->so_error = ECONNREFUSED;
1463 goto close;
1464
1465 case TCPS_ESTABLISHED:
1466 case TCPS_FIN_WAIT_1:
1467 case TCPS_FIN_WAIT_2:
1468 case TCPS_CLOSE_WAIT:
1469 so->so_error = ECONNRESET;
1470 close:
1471 tp->t_state = TCPS_CLOSED;
1472 tcpstat.tcps_drops++;
1473 tp = tcp_close(tp);
1474 goto drop;
1475
1476 case TCPS_CLOSING:
1477 case TCPS_LAST_ACK:
1478 case TCPS_TIME_WAIT:
1479 tp = tcp_close(tp);
1480 goto drop;
1481 }
1482
1483 /*
1484 * If a SYN is in the window, then this is an
1485 * error and we send an RST and drop the connection.
1486 */
1487 if (tiflags & TH_SYN) {
1488 tp = tcp_drop(tp, ECONNRESET);
1489 goto dropwithreset;
1490 }
1491
1492 /*
1493 * If the ACK bit is off we drop the segment and return.
1494 */
1495 if ((tiflags & TH_ACK) == 0) {
1496 if (tp->t_flags & TF_ACKNOW)
1497 goto dropafterack;
1498 else
1499 goto drop;
1500 }
1501
1502 /*
1503 * Ack processing.
1504 */
1505 switch (tp->t_state) {
1506
1507 /*
1508 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
1509 * ESTABLISHED state and continue processing, otherwise
1510 * send an RST.
1511 */
1512 case TCPS_SYN_RECEIVED:
1513 if (SEQ_GT(tp->snd_una, th->th_ack) ||
1514 SEQ_GT(th->th_ack, tp->snd_max))
1515 goto dropwithreset;
1516 tcpstat.tcps_connects++;
1517 soisconnected(so);
1518 tcp_established(tp);
1519 /* Do window scaling? */
1520 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1521 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1522 tp->snd_scale = tp->requested_s_scale;
1523 tp->rcv_scale = tp->request_r_scale;
1524 }
1525 TCP_REASS_LOCK(tp);
1526 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1527 TCP_REASS_UNLOCK(tp);
1528 tp->snd_wl1 = th->th_seq - 1;
1529 /* fall into ... */
1530
1531 /*
1532 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1533 * ACKs. If the ack is in the range
1534 * tp->snd_una < th->th_ack <= tp->snd_max
1535 * then advance tp->snd_una to th->th_ack and drop
1536 * data from the retransmission queue. If this ACK reflects
1537 * more up to date window information we update our window information.
1538 */
1539 case TCPS_ESTABLISHED:
1540 case TCPS_FIN_WAIT_1:
1541 case TCPS_FIN_WAIT_2:
1542 case TCPS_CLOSE_WAIT:
1543 case TCPS_CLOSING:
1544 case TCPS_LAST_ACK:
1545 case TCPS_TIME_WAIT:
1546
1547 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1548 if (tlen == 0 && tiwin == tp->snd_wnd) {
1549 tcpstat.tcps_rcvdupack++;
1550 /*
1551 * If we have outstanding data (other than
1552 * a window probe), this is a completely
1553 * duplicate ack (ie, window info didn't
1554 * change), the ack is the biggest we've
1555 * seen and we've seen exactly our rexmt
1556 * threshhold of them, assume a packet
1557 * has been dropped and retransmit it.
1558 * Kludge snd_nxt & the congestion
1559 * window so we send only this one
1560 * packet.
1561 *
1562 * We know we're losing at the current
1563 * window size so do congestion avoidance
1564 * (set ssthresh to half the current window
1565 * and pull our congestion window back to
1566 * the new ssthresh).
1567 *
1568 * Dup acks mean that packets have left the
1569 * network (they're now cached at the receiver)
1570 * so bump cwnd by the amount in the receiver
1571 * to keep a constant cwnd packets in the
1572 * network.
1573 */
1574 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
1575 th->th_ack != tp->snd_una)
1576 tp->t_dupacks = 0;
1577 else if (++tp->t_dupacks == tcprexmtthresh) {
1578 tcp_seq onxt = tp->snd_nxt;
1579 u_int win =
1580 min(tp->snd_wnd, tp->snd_cwnd) /
1581 2 / tp->t_segsz;
1582 if (SEQ_LT(th->th_ack,
1583 tp->snd_recover)) {
1584 /*
1585 * False fast retransmit after
1586 * timeout. Do not cut window.
1587 */
1588 tp->snd_cwnd += tp->t_segsz;
1589 tp->t_dupacks = 0;
1590 (void) tcp_output(tp);
1591 goto drop;
1592 }
1593
1594 if (win < 2)
1595 win = 2;
1596 tp->snd_ssthresh = win * tp->t_segsz;
1597 tp->snd_recover = tp->snd_max;
1598 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1599 tp->t_rtt = 0;
1600 tp->snd_nxt = th->th_ack;
1601 tp->snd_cwnd = tp->t_segsz;
1602 (void) tcp_output(tp);
1603 tp->snd_cwnd = tp->snd_ssthresh +
1604 tp->t_segsz * tp->t_dupacks;
1605 if (SEQ_GT(onxt, tp->snd_nxt))
1606 tp->snd_nxt = onxt;
1607 goto drop;
1608 } else if (tp->t_dupacks > tcprexmtthresh) {
1609 tp->snd_cwnd += tp->t_segsz;
1610 (void) tcp_output(tp);
1611 goto drop;
1612 }
1613 } else
1614 tp->t_dupacks = 0;
1615 break;
1616 }
1617 /*
1618 * If the congestion window was inflated to account
1619 * for the other side's cached packets, retract it.
1620 */
1621 if (!tcp_do_newreno) {
1622 if (tp->t_dupacks >= tcprexmtthresh &&
1623 tp->snd_cwnd > tp->snd_ssthresh)
1624 tp->snd_cwnd = tp->snd_ssthresh;
1625 tp->t_dupacks = 0;
1626 } else if (tp->t_dupacks >= tcprexmtthresh
1627 && !tcp_newreno(tp, th)) {
1628 tp->snd_cwnd = tp->snd_ssthresh;
1629 /*
1630 * Window inflation should have left us with approx.
1631 * snd_ssthresh outstanding data. But in case we
1632 * would be inclined to send a burst, better to do
1633 * it via the slow start mechanism.
1634 */
1635 if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
1636 tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
1637 + tp->t_segsz;
1638 tp->t_dupacks = 0;
1639 }
1640 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1641 tcpstat.tcps_rcvacktoomuch++;
1642 goto dropafterack;
1643 }
1644 acked = th->th_ack - tp->snd_una;
1645 tcpstat.tcps_rcvackpack++;
1646 tcpstat.tcps_rcvackbyte += acked;
1647
1648 /*
1649 * If we have a timestamp reply, update smoothed
1650 * round trip time. If no timestamp is present but
1651 * transmit timer is running and timed sequence
1652 * number was acked, update smoothed round trip time.
1653 * Since we now have an rtt measurement, cancel the
1654 * timer backoff (cf., Phil Karn's retransmit alg.).
1655 * Recompute the initial retransmit timer.
1656 */
1657 if (opti.ts_present && opti.ts_ecr)
1658 tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
1659 else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
1660 tcp_xmit_timer(tp,tp->t_rtt);
1661
1662 /*
1663 * If all outstanding data is acked, stop retransmit
1664 * timer and remember to restart (more output or persist).
1665 * If there is more data to be acked, restart retransmit
1666 * timer, using current (possibly backed-off) value.
1667 */
1668 if (th->th_ack == tp->snd_max) {
1669 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1670 needoutput = 1;
1671 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
1672 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1673 /*
1674 * When new data is acked, open the congestion window.
1675 * If the window gives us less than ssthresh packets
1676 * in flight, open exponentially (segsz per packet).
1677 * Otherwise open linearly: segsz per window
1678 * (segsz^2 / cwnd per packet), plus a constant
1679 * fraction of a packet (segsz/8) to help larger windows
1680 * open quickly enough.
1681 */
1682 {
1683 register u_int cw = tp->snd_cwnd;
1684 register u_int incr = tp->t_segsz;
1685
1686 if (cw > tp->snd_ssthresh)
1687 incr = incr * incr / cw;
1688 if (!tcp_do_newreno || SEQ_GEQ(th->th_ack, tp->snd_recover))
1689 tp->snd_cwnd = min(cw + incr,TCP_MAXWIN<<tp->snd_scale);
1690 }
1691 if (acked > so->so_snd.sb_cc) {
1692 tp->snd_wnd -= so->so_snd.sb_cc;
1693 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1694 ourfinisacked = 1;
1695 } else {
1696 sbdrop(&so->so_snd, acked);
1697 tp->snd_wnd -= acked;
1698 ourfinisacked = 0;
1699 }
1700 sowwakeup(so);
1701 /*
1702 * We want snd_recover to track snd_una to
1703 * avoid sequence wraparound problems for
1704 * very large transfers.
1705 */
1706 tp->snd_una = tp->snd_recover = th->th_ack;
1707 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1708 tp->snd_nxt = tp->snd_una;
1709
1710 switch (tp->t_state) {
1711
1712 /*
1713 * In FIN_WAIT_1 STATE in addition to the processing
1714 * for the ESTABLISHED state if our FIN is now acknowledged
1715 * then enter FIN_WAIT_2.
1716 */
1717 case TCPS_FIN_WAIT_1:
1718 if (ourfinisacked) {
1719 /*
1720 * If we can't receive any more
1721 * data, then closing user can proceed.
1722 * Starting the timer is contrary to the
1723 * specification, but if we don't get a FIN
1724 * we'll hang forever.
1725 */
1726 if (so->so_state & SS_CANTRCVMORE) {
1727 soisdisconnected(so);
1728 if (tcp_maxidle > 0)
1729 TCP_TIMER_ARM(tp, TCPT_2MSL,
1730 tcp_maxidle);
1731 }
1732 tp->t_state = TCPS_FIN_WAIT_2;
1733 }
1734 break;
1735
1736 /*
1737 * In CLOSING STATE in addition to the processing for
1738 * the ESTABLISHED state if the ACK acknowledges our FIN
1739 * then enter the TIME-WAIT state, otherwise ignore
1740 * the segment.
1741 */
1742 case TCPS_CLOSING:
1743 if (ourfinisacked) {
1744 tp->t_state = TCPS_TIME_WAIT;
1745 tcp_canceltimers(tp);
1746 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1747 soisdisconnected(so);
1748 }
1749 break;
1750
1751 /*
1752 * In LAST_ACK, we may still be waiting for data to drain
1753 * and/or to be acked, as well as for the ack of our FIN.
1754 * If our FIN is now acknowledged, delete the TCB,
1755 * enter the closed state and return.
1756 */
1757 case TCPS_LAST_ACK:
1758 if (ourfinisacked) {
1759 tp = tcp_close(tp);
1760 goto drop;
1761 }
1762 break;
1763
1764 /*
1765 * In TIME_WAIT state the only thing that should arrive
1766 * is a retransmission of the remote FIN. Acknowledge
1767 * it and restart the finack timer.
1768 */
1769 case TCPS_TIME_WAIT:
1770 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1771 goto dropafterack;
1772 }
1773 }
1774
1775 step6:
1776 /*
1777 * Update window information.
1778 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1779 */
1780 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1781 (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
1782 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
1783 /* keep track of pure window updates */
1784 if (tlen == 0 &&
1785 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1786 tcpstat.tcps_rcvwinupd++;
1787 tp->snd_wnd = tiwin;
1788 tp->snd_wl1 = th->th_seq;
1789 tp->snd_wl2 = th->th_ack;
1790 if (tp->snd_wnd > tp->max_sndwnd)
1791 tp->max_sndwnd = tp->snd_wnd;
1792 needoutput = 1;
1793 }
1794
1795 /*
1796 * Process segments with URG.
1797 */
1798 if ((tiflags & TH_URG) && th->th_urp &&
1799 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1800 /*
1801 * This is a kludge, but if we receive and accept
1802 * random urgent pointers, we'll crash in
1803 * soreceive. It's hard to imagine someone
1804 * actually wanting to send this much urgent data.
1805 */
1806 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1807 th->th_urp = 0; /* XXX */
1808 tiflags &= ~TH_URG; /* XXX */
1809 goto dodata; /* XXX */
1810 }
1811 /*
1812 * If this segment advances the known urgent pointer,
1813 * then mark the data stream. This should not happen
1814 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1815 * a FIN has been received from the remote side.
1816 * In these states we ignore the URG.
1817 *
1818 * According to RFC961 (Assigned Protocols),
1819 * the urgent pointer points to the last octet
1820 * of urgent data. We continue, however,
1821 * to consider it to indicate the first octet
1822 * of data past the urgent section as the original
1823 * spec states (in one of two places).
1824 */
1825 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1826 tp->rcv_up = th->th_seq + th->th_urp;
1827 so->so_oobmark = so->so_rcv.sb_cc +
1828 (tp->rcv_up - tp->rcv_nxt) - 1;
1829 if (so->so_oobmark == 0)
1830 so->so_state |= SS_RCVATMARK;
1831 sohasoutofband(so);
1832 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1833 }
1834 /*
1835 * Remove out of band data so doesn't get presented to user.
1836 * This can happen independent of advancing the URG pointer,
1837 * but if two URG's are pending at once, some out-of-band
1838 * data may creep in... ick.
1839 */
1840 if (th->th_urp <= (u_int16_t) tlen
1841 #ifdef SO_OOBINLINE
1842 && (so->so_options & SO_OOBINLINE) == 0
1843 #endif
1844 )
1845 tcp_pulloutofband(so, th, m);
1846 } else
1847 /*
1848 * If no out of band data is expected,
1849 * pull receive urgent pointer along
1850 * with the receive window.
1851 */
1852 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1853 tp->rcv_up = tp->rcv_nxt;
1854 dodata: /* XXX */
1855
1856 /*
1857 * Process the segment text, merging it into the TCP sequencing queue,
1858 * and arranging for acknowledgment of receipt if necessary.
1859 * This process logically involves adjusting tp->rcv_wnd as data
1860 * is presented to the user (this happens in tcp_usrreq.c,
1861 * case PRU_RCVD). If a FIN has already been received on this
1862 * connection then we just ignore the text.
1863 */
1864 if ((tlen || (tiflags & TH_FIN)) &&
1865 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1866 /*
1867 * Insert segment ti into reassembly queue of tcp with
1868 * control block tp. Return TH_FIN if reassembly now includes
1869 * a segment with FIN. The macro form does the common case
1870 * inline (segment is the next to be received on an
1871 * established connection, and the queue is empty),
1872 * avoiding linkage into and removal from the queue and
1873 * repetition of various conversions.
1874 * Set DELACK for segments received in order, but ack
1875 * immediately when segments are out of order
1876 * (so fast retransmit can work).
1877 */
1878 /* NOTE: this was TCP_REASS() macro, but used only once */
1879 TCP_REASS_LOCK(tp);
1880 if (th->th_seq == tp->rcv_nxt &&
1881 tp->segq.lh_first == NULL &&
1882 tp->t_state == TCPS_ESTABLISHED) {
1883 TCP_SETUP_ACK(tp, th);
1884 tp->rcv_nxt += tlen;
1885 tiflags = th->th_flags & TH_FIN;
1886 tcpstat.tcps_rcvpack++;\
1887 tcpstat.tcps_rcvbyte += tlen;\
1888 sbappend(&(so)->so_rcv, m);
1889 sorwakeup(so);
1890 } else {
1891 tiflags = tcp_reass(tp, th, m, &tlen);
1892 tp->t_flags |= TF_ACKNOW;
1893 }
1894 TCP_REASS_UNLOCK(tp);
1895
1896 /*
1897 * Note the amount of data that peer has sent into
1898 * our window, in order to estimate the sender's
1899 * buffer size.
1900 */
1901 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1902 } else {
1903 m_freem(m);
1904 m = NULL;
1905 tiflags &= ~TH_FIN;
1906 }
1907
1908 /*
1909 * If FIN is received ACK the FIN and let the user know
1910 * that the connection is closing. Ignore a FIN received before
1911 * the connection is fully established.
1912 */
1913 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
1914 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1915 socantrcvmore(so);
1916 tp->t_flags |= TF_ACKNOW;
1917 tp->rcv_nxt++;
1918 }
1919 switch (tp->t_state) {
1920
1921 /*
1922 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
1923 */
1924 case TCPS_ESTABLISHED:
1925 tp->t_state = TCPS_CLOSE_WAIT;
1926 break;
1927
1928 /*
1929 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1930 * enter the CLOSING state.
1931 */
1932 case TCPS_FIN_WAIT_1:
1933 tp->t_state = TCPS_CLOSING;
1934 break;
1935
1936 /*
1937 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1938 * starting the time-wait timer, turning off the other
1939 * standard timers.
1940 */
1941 case TCPS_FIN_WAIT_2:
1942 tp->t_state = TCPS_TIME_WAIT;
1943 tcp_canceltimers(tp);
1944 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1945 soisdisconnected(so);
1946 break;
1947
1948 /*
1949 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1950 */
1951 case TCPS_TIME_WAIT:
1952 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1953 break;
1954 }
1955 }
1956 if (so->so_options & SO_DEBUG) {
1957 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
1958 }
1959
1960 /*
1961 * Return any desired output.
1962 */
1963 if (needoutput || (tp->t_flags & TF_ACKNOW))
1964 (void) tcp_output(tp);
1965 if (tcp_saveti)
1966 m_freem(tcp_saveti);
1967 return;
1968
1969 badsyn:
1970 /*
1971 * Received a bad SYN. Increment counters and dropwithreset.
1972 */
1973 tcpstat.tcps_badsyn++;
1974 tp = NULL;
1975 goto dropwithreset;
1976
1977 dropafterack:
1978 /*
1979 * Generate an ACK dropping incoming segment if it occupies
1980 * sequence space, where the ACK reflects our state.
1981 */
1982 if (tiflags & TH_RST)
1983 goto drop;
1984 m_freem(m);
1985 tp->t_flags |= TF_ACKNOW;
1986 (void) tcp_output(tp);
1987 if (tcp_saveti)
1988 m_freem(tcp_saveti);
1989 return;
1990
1991 dropwithreset:
1992 /*
1993 * Generate a RST, dropping incoming segment.
1994 * Make ACK acceptable to originator of segment.
1995 * Don't bother to respond if destination was broadcast/multicast.
1996 */
1997 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
1998 goto drop;
1999 if (ip && IN_MULTICAST(ip->ip_dst.s_addr))
2000 goto drop;
2001 #ifdef INET6
2002 if (m->m_flags & M_ANYCAST6)
2003 goto drop;
2004 else if (ip6 && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2005 goto drop;
2006 #endif
2007 /* recover the header if dropped. */
2008 m->m_data -= hdroptlen;
2009 m->m_len += hdroptlen;
2010 {
2011 /*
2012 * need to recover version # field, which was overwritten on
2013 * ip_cksum computation.
2014 */
2015 struct ip *sip;
2016 sip = mtod(m, struct ip *);
2017 switch (af) {
2018 case AF_INET:
2019 sip->ip_v = 4;
2020 break;
2021 #ifdef INET6
2022 case AF_INET6:
2023 sip->ip_v = 6;
2024 break;
2025 #endif
2026 }
2027 }
2028 if (tiflags & TH_ACK)
2029 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2030 else {
2031 if (tiflags & TH_SYN)
2032 tlen++;
2033 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2034 TH_RST|TH_ACK);
2035 }
2036 if (tcp_saveti)
2037 m_freem(tcp_saveti);
2038 return;
2039
2040 drop:
2041 /*
2042 * Drop space held by incoming segment and return.
2043 */
2044 if (tp) {
2045 if (tp->t_inpcb)
2046 so = tp->t_inpcb->inp_socket;
2047 #ifdef INET6
2048 else if (tp->t_in6pcb)
2049 so = tp->t_in6pcb->in6p_socket;
2050 #endif
2051 else
2052 so = NULL;
2053 if (so && (so->so_options & SO_DEBUG) != 0)
2054 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2055 }
2056 if (tcp_saveti)
2057 m_freem(tcp_saveti);
2058 m_freem(m);
2059 return;
2060 }
2061
2062 void
2063 tcp_dooptions(tp, cp, cnt, th, oi)
2064 struct tcpcb *tp;
2065 u_char *cp;
2066 int cnt;
2067 struct tcphdr *th;
2068 struct tcp_opt_info *oi;
2069 {
2070 u_int16_t mss;
2071 int opt, optlen;
2072
2073 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2074 opt = cp[0];
2075 if (opt == TCPOPT_EOL)
2076 break;
2077 if (opt == TCPOPT_NOP)
2078 optlen = 1;
2079 else {
2080 optlen = cp[1];
2081 if (optlen <= 0)
2082 break;
2083 }
2084 switch (opt) {
2085
2086 default:
2087 continue;
2088
2089 case TCPOPT_MAXSEG:
2090 if (optlen != TCPOLEN_MAXSEG)
2091 continue;
2092 if (!(th->th_flags & TH_SYN))
2093 continue;
2094 bcopy(cp + 2, &mss, sizeof(mss));
2095 oi->maxseg = ntohs(mss);
2096 break;
2097
2098 case TCPOPT_WINDOW:
2099 if (optlen != TCPOLEN_WINDOW)
2100 continue;
2101 if (!(th->th_flags & TH_SYN))
2102 continue;
2103 tp->t_flags |= TF_RCVD_SCALE;
2104 tp->requested_s_scale = cp[2];
2105 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2106 #if 0 /*XXX*/
2107 char *p;
2108
2109 if (ip)
2110 p = ntohl(ip->ip_src);
2111 #ifdef INET6
2112 else if (ip6)
2113 p = ip6_sprintf(&ip6->ip6_src);
2114 #endif
2115 else
2116 p = "(unknown)";
2117 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2118 "assuming %d\n",
2119 tp->requested_s_scale, p,
2120 TCP_MAX_WINSHIFT);
2121 #else
2122 log(LOG_ERR, "TCP: invalid wscale %d, "
2123 "assuming %d\n",
2124 tp->requested_s_scale,
2125 TCP_MAX_WINSHIFT);
2126 #endif
2127 tp->requested_s_scale = TCP_MAX_WINSHIFT;
2128 }
2129 break;
2130
2131 case TCPOPT_TIMESTAMP:
2132 if (optlen != TCPOLEN_TIMESTAMP)
2133 continue;
2134 oi->ts_present = 1;
2135 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2136 NTOHL(oi->ts_val);
2137 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2138 NTOHL(oi->ts_ecr);
2139
2140 /*
2141 * A timestamp received in a SYN makes
2142 * it ok to send timestamp requests and replies.
2143 */
2144 if (th->th_flags & TH_SYN) {
2145 tp->t_flags |= TF_RCVD_TSTMP;
2146 tp->ts_recent = oi->ts_val;
2147 tp->ts_recent_age = tcp_now;
2148 }
2149 break;
2150 case TCPOPT_SACK_PERMITTED:
2151 if (optlen != TCPOLEN_SACK_PERMITTED)
2152 continue;
2153 if (!(th->th_flags & TH_SYN))
2154 continue;
2155 tp->t_flags &= ~TF_CANT_TXSACK;
2156 break;
2157
2158 case TCPOPT_SACK:
2159 if (tp->t_flags & TF_IGNR_RXSACK)
2160 continue;
2161 if (optlen % 8 != 2 || optlen < 10)
2162 continue;
2163 cp += 2;
2164 optlen -= 2;
2165 for (; optlen > 0; cp -= 8, optlen -= 8) {
2166 tcp_seq lwe, rwe;
2167 bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
2168 NTOHL(lwe);
2169 bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
2170 NTOHL(rwe);
2171 /* tcp_mark_sacked(tp, lwe, rwe); */
2172 }
2173 break;
2174 }
2175 }
2176 }
2177
2178 /*
2179 * Pull out of band byte out of a segment so
2180 * it doesn't appear in the user's data queue.
2181 * It is still reflected in the segment length for
2182 * sequencing purposes.
2183 */
2184 void
2185 tcp_pulloutofband(so, th, m)
2186 struct socket *so;
2187 struct tcphdr *th;
2188 register struct mbuf *m;
2189 {
2190 int cnt = th->th_urp - 1;
2191
2192 while (cnt >= 0) {
2193 if (m->m_len > cnt) {
2194 char *cp = mtod(m, caddr_t) + cnt;
2195 struct tcpcb *tp = sototcpcb(so);
2196
2197 tp->t_iobc = *cp;
2198 tp->t_oobflags |= TCPOOB_HAVEDATA;
2199 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2200 m->m_len--;
2201 return;
2202 }
2203 cnt -= m->m_len;
2204 m = m->m_next;
2205 if (m == 0)
2206 break;
2207 }
2208 panic("tcp_pulloutofband");
2209 }
2210
2211 /*
2212 * Collect new round-trip time estimate
2213 * and update averages and current timeout.
2214 */
2215 void
2216 tcp_xmit_timer(tp, rtt)
2217 register struct tcpcb *tp;
2218 short rtt;
2219 {
2220 register short delta;
2221 short rttmin;
2222
2223 tcpstat.tcps_rttupdated++;
2224 --rtt;
2225 if (tp->t_srtt != 0) {
2226 /*
2227 * srtt is stored as fixed point with 3 bits after the
2228 * binary point (i.e., scaled by 8). The following magic
2229 * is equivalent to the smoothing algorithm in rfc793 with
2230 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2231 * point). Adjust rtt to origin 0.
2232 */
2233 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2234 if ((tp->t_srtt += delta) <= 0)
2235 tp->t_srtt = 1 << 2;
2236 /*
2237 * We accumulate a smoothed rtt variance (actually, a
2238 * smoothed mean difference), then set the retransmit
2239 * timer to smoothed rtt + 4 times the smoothed variance.
2240 * rttvar is stored as fixed point with 2 bits after the
2241 * binary point (scaled by 4). The following is
2242 * equivalent to rfc793 smoothing with an alpha of .75
2243 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2244 * rfc793's wired-in beta.
2245 */
2246 if (delta < 0)
2247 delta = -delta;
2248 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2249 if ((tp->t_rttvar += delta) <= 0)
2250 tp->t_rttvar = 1 << 2;
2251 } else {
2252 /*
2253 * No rtt measurement yet - use the unsmoothed rtt.
2254 * Set the variance to half the rtt (so our first
2255 * retransmit happens at 3*rtt).
2256 */
2257 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
2258 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
2259 }
2260 tp->t_rtt = 0;
2261 tp->t_rxtshift = 0;
2262
2263 /*
2264 * the retransmit should happen at rtt + 4 * rttvar.
2265 * Because of the way we do the smoothing, srtt and rttvar
2266 * will each average +1/2 tick of bias. When we compute
2267 * the retransmit timer, we want 1/2 tick of rounding and
2268 * 1 extra tick because of +-1/2 tick uncertainty in the
2269 * firing of the timer. The bias will give us exactly the
2270 * 1.5 tick we need. But, because the bias is
2271 * statistical, we have to test that we don't drop below
2272 * the minimum feasible timer (which is 2 ticks).
2273 */
2274 if (tp->t_rttmin > rtt + 2)
2275 rttmin = tp->t_rttmin;
2276 else
2277 rttmin = rtt + 2;
2278 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
2279
2280 /*
2281 * We received an ack for a packet that wasn't retransmitted;
2282 * it is probably safe to discard any error indications we've
2283 * received recently. This isn't quite right, but close enough
2284 * for now (a route might have failed after we sent a segment,
2285 * and the return path might not be symmetrical).
2286 */
2287 tp->t_softerror = 0;
2288 }
2289
2290 /*
2291 * Checks for partial ack. If partial ack arrives, force the retransmission
2292 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
2293 * 1. By setting snd_nxt to th_ack, this forces retransmission timer to
2294 * be started again. If the ack advances at least to tp->snd_recover, return 0.
2295 */
2296 int
2297 tcp_newreno(tp, th)
2298 struct tcpcb *tp;
2299 struct tcphdr *th;
2300 {
2301 tcp_seq onxt = tp->snd_nxt;
2302 u_long ocwnd = tp->snd_cwnd;
2303
2304 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2305 /*
2306 * snd_una has not yet been updated and the socket's send
2307 * buffer has not yet drained off the ACK'd data, so we
2308 * have to leave snd_una as it was to get the correct data
2309 * offset in tcp_output().
2310 */
2311 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2312 tp->t_rtt = 0;
2313 tp->snd_nxt = th->th_ack;
2314 /*
2315 * Set snd_cwnd to one segment beyond ACK'd offset. snd_una
2316 * is not yet updated when we're called.
2317 */
2318 tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
2319 (void) tcp_output(tp);
2320 tp->snd_cwnd = ocwnd;
2321 if (SEQ_GT(onxt, tp->snd_nxt))
2322 tp->snd_nxt = onxt;
2323 /*
2324 * Partial window deflation. Relies on fact that tp->snd_una
2325 * not updated yet.
2326 */
2327 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
2328 return 1;
2329 }
2330 return 0;
2331 }
2332
2333
2334 /*
2335 * TCP compressed state engine. Currently used to hold compressed
2336 * state for SYN_RECEIVED.
2337 */
2338
2339 u_long syn_cache_count;
2340 u_int32_t syn_hash1, syn_hash2;
2341
2342 #define SYN_HASH(sa, sp, dp) \
2343 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
2344 ((u_int32_t)(sp)))^syn_hash2)))
2345 #ifndef INET6
2346 #define SYN_HASHALL(hash, src, dst) \
2347 do { \
2348 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2349 ((struct sockaddr_in *)(src))->sin_port, \
2350 ((struct sockaddr_in *)(dst))->sin_port); \
2351 } while (0)
2352 #else
2353 #define SYN_HASH6(sa, sp, dp) \
2354 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
2355 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
2356 & 0x7fffffff)
2357
2358 #define SYN_HASHALL(hash, src, dst) \
2359 do { \
2360 switch ((src)->sa_family) { \
2361 case AF_INET: \
2362 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2363 ((struct sockaddr_in *)(src))->sin_port, \
2364 ((struct sockaddr_in *)(dst))->sin_port); \
2365 break; \
2366 case AF_INET6: \
2367 hash = SYN_HASH6(&((struct sockaddr_in6 *)(src))->sin6_addr, \
2368 ((struct sockaddr_in6 *)(src))->sin6_port, \
2369 ((struct sockaddr_in6 *)(dst))->sin6_port); \
2370 break; \
2371 default: \
2372 hash = 0; \
2373 } \
2374 } while (0)
2375 #endif /* INET6 */
2376
2377 #define SYN_CACHE_RM(sc) \
2378 do { \
2379 LIST_REMOVE((sc), sc_bucketq); \
2380 tcp_syn_cache[(sc)->sc_bucketidx].sch_length--; \
2381 TAILQ_REMOVE(&tcp_syn_cache_timeq[(sc)->sc_rxtshift], (sc), sc_timeq); \
2382 syn_cache_count--; \
2383 } while (0)
2384
2385 #define SYN_CACHE_PUT(sc) \
2386 do { \
2387 if ((sc)->sc_ipopts) \
2388 (void) m_free((sc)->sc_ipopts); \
2389 if ((sc)->sc_route4.ro_rt != NULL) \
2390 RTFREE((sc)->sc_route4.ro_rt); \
2391 pool_put(&syn_cache_pool, (sc)); \
2392 } while (0)
2393
2394 struct pool syn_cache_pool;
2395
2396 /*
2397 * We don't estimate RTT with SYNs, so each packet starts with the default
2398 * RTT and each timer queue has a fixed timeout value. This allows us to
2399 * optimize the timer queues somewhat.
2400 */
2401 #define SYN_CACHE_TIMER_ARM(sc) \
2402 do { \
2403 TCPT_RANGESET((sc)->sc_rxtcur, \
2404 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \
2405 TCPTV_REXMTMAX); \
2406 PRT_SLOW_ARM((sc)->sc_rexmt, (sc)->sc_rxtcur); \
2407 } while (0)
2408
2409 TAILQ_HEAD(, syn_cache) tcp_syn_cache_timeq[TCP_MAXRXTSHIFT + 1];
2410
2411 void
2412 syn_cache_init()
2413 {
2414 int i;
2415
2416 /* Initialize the hash buckets. */
2417 for (i = 0; i < tcp_syn_cache_size; i++)
2418 LIST_INIT(&tcp_syn_cache[i].sch_bucket);
2419
2420 /* Initialize the timer queues. */
2421 for (i = 0; i <= TCP_MAXRXTSHIFT; i++)
2422 TAILQ_INIT(&tcp_syn_cache_timeq[i]);
2423
2424 /* Initialize the syn cache pool. */
2425 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
2426 "synpl", 0, NULL, NULL, M_PCB);
2427 }
2428
2429 void
2430 syn_cache_insert(sc)
2431 struct syn_cache *sc;
2432 {
2433 struct syn_cache_head *scp;
2434 struct syn_cache *sc2;
2435 int s, i;
2436
2437 /*
2438 * If there are no entries in the hash table, reinitialize
2439 * the hash secrets.
2440 */
2441 if (syn_cache_count == 0) {
2442 struct timeval tv;
2443 microtime(&tv);
2444 syn_hash1 = random() ^ (u_long)≻
2445 syn_hash2 = random() ^ tv.tv_usec;
2446 }
2447
2448 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
2449 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
2450 scp = &tcp_syn_cache[sc->sc_bucketidx];
2451
2452 /*
2453 * Make sure that we don't overflow the per-bucket
2454 * limit or the total cache size limit.
2455 */
2456 s = splsoftnet();
2457 if (scp->sch_length >= tcp_syn_bucket_limit) {
2458 tcpstat.tcps_sc_bucketoverflow++;
2459 /*
2460 * The bucket is full. Toss the oldest element in the
2461 * bucket. This will be the entry with our bucket
2462 * index closest to the front of the timer queue with
2463 * the largest timeout value.
2464 *
2465 * Note: This timer queue traversal may be expensive, so
2466 * we hope that this doesn't happen very often. It is
2467 * much more likely that we'll overflow the entire
2468 * cache, which is much easier to handle; see below.
2469 */
2470 for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2471 for (sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2472 sc2 != NULL;
2473 sc2 = TAILQ_NEXT(sc2, sc_timeq)) {
2474 if (sc2->sc_bucketidx == sc->sc_bucketidx) {
2475 SYN_CACHE_RM(sc2);
2476 SYN_CACHE_PUT(sc2);
2477 goto insert; /* 2 level break */
2478 }
2479 }
2480 }
2481 #ifdef DIAGNOSTIC
2482 /*
2483 * This should never happen; we should always find an
2484 * entry in our bucket.
2485 */
2486 panic("syn_cache_insert: bucketoverflow: impossible");
2487 #endif
2488 } else if (syn_cache_count >= tcp_syn_cache_limit) {
2489 tcpstat.tcps_sc_overflowed++;
2490 /*
2491 * The cache is full. Toss the oldest entry in the
2492 * entire cache. This is the front entry in the
2493 * first non-empty timer queue with the largest
2494 * timeout value.
2495 */
2496 for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2497 sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2498 if (sc2 == NULL)
2499 continue;
2500 SYN_CACHE_RM(sc2);
2501 SYN_CACHE_PUT(sc2);
2502 goto insert; /* symmetry with above */
2503 }
2504 #ifdef DIAGNOSTIC
2505 /*
2506 * This should never happen; we should always find an
2507 * entry in the cache.
2508 */
2509 panic("syn_cache_insert: cache overflow: impossible");
2510 #endif
2511 }
2512
2513 insert:
2514 /*
2515 * Initialize the entry's timer.
2516 */
2517 sc->sc_rxttot = 0;
2518 sc->sc_rxtshift = 0;
2519 SYN_CACHE_TIMER_ARM(sc);
2520 TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift], sc, sc_timeq);
2521
2522 /* Put it into the bucket. */
2523 LIST_INSERT_HEAD(&scp->sch_bucket, sc, sc_bucketq);
2524 scp->sch_length++;
2525 syn_cache_count++;
2526
2527 tcpstat.tcps_sc_added++;
2528 splx(s);
2529 }
2530
2531 /*
2532 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
2533 * If we have retransmitted an entry the maximum number of times, expire
2534 * that entry.
2535 */
2536 void
2537 syn_cache_timer()
2538 {
2539 struct syn_cache *sc, *nsc;
2540 int i, s;
2541
2542 s = splsoftnet();
2543
2544 /*
2545 * First, get all the entries that need to be retransmitted, or
2546 * must be expired due to exceeding the initial keepalive time.
2547 */
2548 for (i = 0; i < TCP_MAXRXTSHIFT; i++) {
2549 for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2550 sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2551 sc = nsc) {
2552 nsc = TAILQ_NEXT(sc, sc_timeq);
2553
2554 /*
2555 * Compute the total amount of time this entry has
2556 * been on a queue. If this entry has been on longer
2557 * than the keep alive timer would allow, expire it.
2558 */
2559 sc->sc_rxttot += sc->sc_rxtcur;
2560 if (sc->sc_rxttot >= TCPTV_KEEP_INIT) {
2561 tcpstat.tcps_sc_timed_out++;
2562 SYN_CACHE_RM(sc);
2563 SYN_CACHE_PUT(sc);
2564 continue;
2565 }
2566
2567 tcpstat.tcps_sc_retransmitted++;
2568 (void) syn_cache_respond(sc, NULL);
2569
2570 /* Advance this entry onto the next timer queue. */
2571 TAILQ_REMOVE(&tcp_syn_cache_timeq[i], sc, sc_timeq);
2572 sc->sc_rxtshift = i + 1;
2573 SYN_CACHE_TIMER_ARM(sc);
2574 TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift],
2575 sc, sc_timeq);
2576 }
2577 }
2578
2579 /*
2580 * Now get all the entries that are expired due to too many
2581 * retransmissions.
2582 */
2583 for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[TCP_MAXRXTSHIFT]);
2584 sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2585 sc = nsc) {
2586 nsc = TAILQ_NEXT(sc, sc_timeq);
2587 tcpstat.tcps_sc_timed_out++;
2588 SYN_CACHE_RM(sc);
2589 SYN_CACHE_PUT(sc);
2590 }
2591 splx(s);
2592 }
2593
2594 /*
2595 * Find an entry in the syn cache.
2596 */
2597 struct syn_cache *
2598 syn_cache_lookup(src, dst, headp)
2599 struct sockaddr *src;
2600 struct sockaddr *dst;
2601 struct syn_cache_head **headp;
2602 {
2603 struct syn_cache *sc;
2604 struct syn_cache_head *scp;
2605 u_int32_t hash;
2606 int s;
2607
2608 SYN_HASHALL(hash, src, dst);
2609
2610 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
2611 *headp = scp;
2612 s = splsoftnet();
2613 for (sc = LIST_FIRST(&scp->sch_bucket); sc != NULL;
2614 sc = LIST_NEXT(sc, sc_bucketq)) {
2615 if (sc->sc_hash != hash)
2616 continue;
2617 if (!bcmp(&sc->sc_src, src, src->sa_len) &&
2618 !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
2619 splx(s);
2620 return (sc);
2621 }
2622 }
2623 splx(s);
2624 return (NULL);
2625 }
2626
2627 /*
2628 * This function gets called when we receive an ACK for a
2629 * socket in the LISTEN state. We look up the connection
2630 * in the syn cache, and if its there, we pull it out of
2631 * the cache and turn it into a full-blown connection in
2632 * the SYN-RECEIVED state.
2633 *
2634 * The return values may not be immediately obvious, and their effects
2635 * can be subtle, so here they are:
2636 *
2637 * NULL SYN was not found in cache; caller should drop the
2638 * packet and send an RST.
2639 *
2640 * -1 We were unable to create the new connection, and are
2641 * aborting it. An ACK,RST is being sent to the peer
2642 * (unless we got screwey sequence numbners; see below),
2643 * because the 3-way handshake has been completed. Caller
2644 * should not free the mbuf, since we may be using it. If
2645 * we are not, we will free it.
2646 *
2647 * Otherwise, the return value is a pointer to the new socket
2648 * associated with the connection.
2649 */
2650 struct socket *
2651 syn_cache_get(src, dst, th, hlen, tlen, so, m)
2652 struct sockaddr *src;
2653 struct sockaddr *dst;
2654 struct tcphdr *th;
2655 unsigned int hlen, tlen;
2656 struct socket *so;
2657 struct mbuf *m;
2658 {
2659 struct syn_cache *sc;
2660 struct syn_cache_head *scp;
2661 register struct inpcb *inp = NULL;
2662 #ifdef INET6
2663 register struct in6pcb *in6p = NULL;
2664 #endif
2665 register struct tcpcb *tp = 0;
2666 struct mbuf *am;
2667 int s;
2668 struct socket *oso;
2669
2670 s = splsoftnet();
2671 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2672 splx(s);
2673 return (NULL);
2674 }
2675
2676 /*
2677 * Verify the sequence and ack numbers. Try getting the correct
2678 * response again.
2679 */
2680 if ((th->th_ack != sc->sc_iss + 1) ||
2681 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
2682 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
2683 (void) syn_cache_respond(sc, m);
2684 splx(s);
2685 return ((struct socket *)(-1));
2686 }
2687
2688 /* Remove this cache entry */
2689 SYN_CACHE_RM(sc);
2690 splx(s);
2691
2692 /*
2693 * Ok, create the full blown connection, and set things up
2694 * as they would have been set up if we had created the
2695 * connection when the SYN arrived. If we can't create
2696 * the connection, abort it.
2697 */
2698 /*
2699 * inp still has the OLD in_pcb stuff, set the
2700 * v6-related flags on the new guy, too. This is
2701 * done particularly for the case where an AF_INET6
2702 * socket is bound only to a port, and a v4 connection
2703 * comes in on that port.
2704 * we also copy the flowinfo from the original pcb
2705 * to the new one.
2706 */
2707 {
2708 struct inpcb *parentinpcb;
2709
2710 parentinpcb = (struct inpcb *)so->so_pcb;
2711
2712 oso = so;
2713 so = sonewconn(so, SS_ISCONNECTED);
2714 if (so == NULL)
2715 goto resetandabort;
2716
2717 switch (so->so_proto->pr_domain->dom_family) {
2718 case AF_INET:
2719 inp = sotoinpcb(so);
2720 break;
2721 #ifdef INET6
2722 case AF_INET6:
2723 in6p = sotoin6pcb(so);
2724 #if 0 /*def INET6*/
2725 inp->inp_flags |= (parentinpcb->inp_flags &
2726 (INP_IPV6 | INP_IPV6_UNDEC | INP_IPV6_MAPPED));
2727 if ((inp->inp_flags & INP_IPV6) &&
2728 !(inp->inp_flags & INP_IPV6_MAPPED)) {
2729 inp->inp_ipv6.ip6_hlim = parentinpcb->inp_ipv6.ip6_hlim;
2730 inp->inp_ipv6.ip6_vfc = parentinpcb->inp_ipv6.ip6_vfc;
2731 }
2732 #endif
2733 break;
2734 #endif
2735 }
2736 }
2737 switch (src->sa_family) {
2738 case AF_INET:
2739 if (inp) {
2740 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
2741 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
2742 inp->inp_options = ip_srcroute();
2743 in_pcbstate(inp, INP_BOUND);
2744 if (inp->inp_options == NULL) {
2745 inp->inp_options = sc->sc_ipopts;
2746 sc->sc_ipopts = NULL;
2747 }
2748 }
2749 #ifdef INET6
2750 else if (in6p) {
2751 /* IPv4 packet to AF_INET6 socket */
2752 bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
2753 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
2754 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
2755 &in6p->in6p_laddr.s6_addr32[3],
2756 sizeof(((struct sockaddr_in *)dst)->sin_addr));
2757 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
2758 in6totcpcb(in6p)->t_family = AF_INET;
2759 }
2760 #endif
2761 break;
2762 #ifdef INET6
2763 case AF_INET6:
2764 if (in6p) {
2765 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
2766 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
2767 #if 0
2768 in6p->in6p_flowinfo = ip6->ip6_flow & IPV6_FLOWINFO_MASK;
2769 /*inp->inp_options = ip6_srcroute();*/ /* soon. */
2770 #endif
2771 }
2772 break;
2773 #endif
2774 }
2775 #ifdef INET6
2776 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
2777 struct in6pcb *oin6p = sotoin6pcb(oso);
2778 /* inherit socket options from the listening socket */
2779 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
2780 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
2781 m_freem(in6p->in6p_options);
2782 in6p->in6p_options = 0;
2783 }
2784 ip6_savecontrol(in6p, &in6p->in6p_options,
2785 mtod(m, struct ip6_hdr *), m);
2786 }
2787 #endif
2788
2789 #ifdef IPSEC
2790 {
2791 struct secpolicy *sp;
2792 if (inp) {
2793 sp = ipsec_copy_policy(sotoinpcb(oso)->inp_sp);
2794 if (sp) {
2795 key_freesp(inp->inp_sp);
2796 inp->inp_sp = sp;
2797 } else
2798 printf("tcp_input: could not copy policy\n");
2799 }
2800 #ifdef INET6
2801 else if (in6p) {
2802 sp = ipsec_copy_policy(sotoin6pcb(oso)->in6p_sp);
2803 if (sp) {
2804 key_freesp(in6p->in6p_sp);
2805 in6p->in6p_sp = sp;
2806 } else
2807 printf("tcp_input: could not copy policy\n");
2808 }
2809 #endif
2810 }
2811 #endif
2812
2813 /*
2814 * Give the new socket our cached route reference.
2815 */
2816 if (inp)
2817 inp->inp_route = sc->sc_route4; /* struct assignment */
2818 #ifdef INET6
2819 else
2820 in6p->in6p_route = sc->sc_route6;
2821 #endif
2822 sc->sc_route4.ro_rt = NULL;
2823
2824 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
2825 if (am == NULL)
2826 goto resetandabort;
2827 am->m_len = src->sa_len;
2828 bcopy(src, mtod(am, caddr_t), src->sa_len);
2829 if (inp) {
2830 if (in_pcbconnect(inp, am)) {
2831 (void) m_free(am);
2832 goto resetandabort;
2833 }
2834 }
2835 #ifdef INET6
2836 else if (in6p) {
2837 if (src->sa_family == AF_INET) {
2838 /* IPv4 packet to AF_INET6 socket */
2839 struct sockaddr_in6 *sin6;
2840 sin6 = mtod(am, struct sockaddr_in6 *);
2841 am->m_len = sizeof(*sin6);
2842 bzero(sin6, sizeof(*sin6));
2843 sin6->sin6_family = AF_INET6;
2844 sin6->sin6_len = sizeof(*sin6);
2845 sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
2846 sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
2847 bcopy(&((struct sockaddr_in *)src)->sin_addr,
2848 &sin6->sin6_addr.s6_addr32[3],
2849 sizeof(sin6->sin6_addr.s6_addr32[3]));
2850 }
2851 if (in6_pcbconnect(in6p, am)) {
2852 (void) m_free(am);
2853 goto resetandabort;
2854 }
2855 }
2856 #endif
2857 else {
2858 (void) m_free(am);
2859 goto resetandabort;
2860 }
2861 (void) m_free(am);
2862
2863 if (inp)
2864 tp = intotcpcb(inp);
2865 #ifdef INET6
2866 else if (in6p)
2867 tp = in6totcpcb(in6p);
2868 #endif
2869 else
2870 tp = NULL;
2871 if (sc->sc_request_r_scale != 15) {
2872 tp->requested_s_scale = sc->sc_requested_s_scale;
2873 tp->request_r_scale = sc->sc_request_r_scale;
2874 tp->snd_scale = sc->sc_requested_s_scale;
2875 tp->rcv_scale = sc->sc_request_r_scale;
2876 tp->t_flags |= TF_RCVD_SCALE;
2877 }
2878 if (sc->sc_flags & SCF_TIMESTAMP)
2879 tp->t_flags |= TF_RCVD_TSTMP;
2880
2881 tp->t_template = tcp_template(tp);
2882 if (tp->t_template == 0) {
2883 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
2884 so = NULL;
2885 m_freem(m);
2886 goto abort;
2887 }
2888
2889 tp->iss = sc->sc_iss;
2890 tp->irs = sc->sc_irs;
2891 tcp_sendseqinit(tp);
2892 tcp_rcvseqinit(tp);
2893 tp->t_state = TCPS_SYN_RECEIVED;
2894 TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
2895 tcpstat.tcps_accepts++;
2896
2897 /* Initialize tp->t_ourmss before we deal with the peer's! */
2898 tp->t_ourmss = sc->sc_ourmaxseg;
2899 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
2900
2901 /*
2902 * Initialize the initial congestion window. If we
2903 * had to retransmit the SYN,ACK, we must initialize cwnd
2904 * to 1 segment (i.e. the Loss Window).
2905 */
2906 if (sc->sc_rxtshift)
2907 tp->snd_cwnd = tp->t_peermss;
2908 else
2909 tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win, tp->t_peermss);
2910
2911 tcp_rmx_rtt(tp);
2912 tp->snd_wl1 = sc->sc_irs;
2913 tp->rcv_up = sc->sc_irs + 1;
2914
2915 /*
2916 * This is what whould have happened in tcp_ouput() when
2917 * the SYN,ACK was sent.
2918 */
2919 tp->snd_up = tp->snd_una;
2920 tp->snd_max = tp->snd_nxt = tp->iss+1;
2921 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2922 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
2923 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
2924 tp->last_ack_sent = tp->rcv_nxt;
2925
2926 tcpstat.tcps_sc_completed++;
2927 SYN_CACHE_PUT(sc);
2928 return (so);
2929
2930 resetandabort:
2931 (void) tcp_respond(NULL, m, m, th,
2932 th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
2933 abort:
2934 if (so != NULL)
2935 (void) soabort(so);
2936 SYN_CACHE_PUT(sc);
2937 tcpstat.tcps_sc_aborted++;
2938 return ((struct socket *)(-1));
2939 }
2940
2941 /*
2942 * This function is called when we get a RST for a
2943 * non-existant connection, so that we can see if the
2944 * connection is in the syn cache. If it is, zap it.
2945 */
2946
2947 void
2948 syn_cache_reset(src, dst, th)
2949 struct sockaddr *src;
2950 struct sockaddr *dst;
2951 struct tcphdr *th;
2952 {
2953 struct syn_cache *sc;
2954 struct syn_cache_head *scp;
2955 int s = splsoftnet();
2956
2957 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2958 splx(s);
2959 return;
2960 }
2961 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
2962 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
2963 splx(s);
2964 return;
2965 }
2966 SYN_CACHE_RM(sc);
2967 splx(s);
2968 tcpstat.tcps_sc_reset++;
2969 SYN_CACHE_PUT(sc);
2970 }
2971
2972 void
2973 syn_cache_unreach(src, dst, th)
2974 struct sockaddr *src;
2975 struct sockaddr *dst;
2976 struct tcphdr *th;
2977 {
2978 struct syn_cache *sc;
2979 struct syn_cache_head *scp;
2980 int s;
2981
2982 s = splsoftnet();
2983 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2984 splx(s);
2985 return;
2986 }
2987 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
2988 if (ntohl (th->th_seq) != sc->sc_iss) {
2989 splx(s);
2990 return;
2991 }
2992
2993 /*
2994 * If we've rertransmitted 3 times and this is our second error,
2995 * we remove the entry. Otherwise, we allow it to continue on.
2996 * This prevents us from incorrectly nuking an entry during a
2997 * spurious network outage.
2998 *
2999 * See tcp_notify().
3000 */
3001 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
3002 sc->sc_flags |= SCF_UNREACH;
3003 splx(s);
3004 return;
3005 }
3006
3007 SYN_CACHE_RM(sc);
3008 splx(s);
3009 tcpstat.tcps_sc_unreach++;
3010 SYN_CACHE_PUT(sc);
3011 }
3012
3013 /*
3014 * Given a LISTEN socket and an inbound SYN request, add
3015 * this to the syn cache, and send back a segment:
3016 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3017 * to the source.
3018 *
3019 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3020 * Doing so would require that we hold onto the data and deliver it
3021 * to the application. However, if we are the target of a SYN-flood
3022 * DoS attack, an attacker could send data which would eventually
3023 * consume all available buffer space if it were ACKed. By not ACKing
3024 * the data, we avoid this DoS scenario.
3025 */
3026
3027 int
3028 syn_cache_add(src, dst, th, hlen, so, m, optp, optlen, oi)
3029 struct sockaddr *src;
3030 struct sockaddr *dst;
3031 struct tcphdr *th;
3032 unsigned int hlen;
3033 struct socket *so;
3034 struct mbuf *m;
3035 u_char *optp;
3036 int optlen;
3037 struct tcp_opt_info *oi;
3038 {
3039 struct tcpcb tb, *tp;
3040 long win;
3041 struct syn_cache *sc;
3042 struct syn_cache_head *scp;
3043 struct mbuf *ipopts;
3044 #ifdef IPSEC
3045 size_t ipsechdrsiz;
3046 #endif
3047
3048 tp = sototcpcb(so);
3049
3050 /*
3051 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3052 * in_broadcast() should never return true on a received
3053 * packet with M_BCAST not set.
3054 */
3055 if (m->m_flags & (M_BCAST|M_MCAST))
3056 return 0;
3057 #ifdef INET6
3058 if (m->m_flags & M_ANYCAST6)
3059 return 0;
3060 #endif
3061
3062 switch (src->sa_family) {
3063 case AF_INET:
3064 if (IN_MULTICAST(((struct sockaddr_in *)src)->sin_addr.s_addr)
3065 || IN_MULTICAST(((struct sockaddr_in *)dst)->sin_addr.s_addr))
3066 return 0;
3067 #ifdef IPSEC
3068 ipsechdrsiz = ipsec4_hdrsiz_tcp(tp);
3069 #endif
3070 break;
3071 #ifdef INET6
3072 case AF_INET6:
3073 if (IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)src)->sin6_addr)
3074 || IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)dst)->sin6_addr))
3075 return 0;
3076 #if defined(IPSEC) && !defined(TCP6)
3077 ipsechdrsiz = ipsec6_hdrsiz_tcp(tp);
3078 #endif
3079 break;
3080 #endif
3081 }
3082
3083 /*
3084 * Initialize some local state.
3085 */
3086 win = sbspace(&so->so_rcv);
3087 if (win > TCP_MAXWIN)
3088 win = TCP_MAXWIN;
3089
3090 if (src->sa_family == AF_INET) {
3091 /*
3092 * Remember the IP options, if any.
3093 */
3094 ipopts = ip_srcroute();
3095 } else
3096 ipopts = NULL;
3097
3098 if (optp) {
3099 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
3100 tcp_dooptions(&tb, optp, optlen, th, oi);
3101 } else
3102 tb.t_flags = 0;
3103
3104 /*
3105 * See if we already have an entry for this connection.
3106 * If we do, resend the SYN,ACK. We do not count this
3107 * as a retransmission (XXX though maybe we should).
3108 */
3109 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
3110 tcpstat.tcps_sc_dupesyn++;
3111 if (ipopts) {
3112 /*
3113 * If we were remembering a previous source route,
3114 * forget it and use the new one we've been given.
3115 */
3116 if (sc->sc_ipopts)
3117 (void) m_free(sc->sc_ipopts);
3118 sc->sc_ipopts = ipopts;
3119 }
3120 sc->sc_timestamp = tb.ts_recent;
3121 if (syn_cache_respond(sc, m) == 0) {
3122 tcpstat.tcps_sndacks++;
3123 tcpstat.tcps_sndtotal++;
3124 }
3125 return (1);
3126 }
3127
3128 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
3129 if (sc == NULL) {
3130 if (ipopts)
3131 (void) m_free(ipopts);
3132 return (0);
3133 }
3134
3135 /*
3136 * Fill in the cache, and put the necessary IP and TCP
3137 * options into the reply.
3138 */
3139 bzero(sc, sizeof(struct syn_cache));
3140 bcopy(src, &sc->sc_src, src->sa_len);
3141 bcopy(dst, &sc->sc_dst, dst->sa_len);
3142 sc->sc_flags = 0;
3143 sc->sc_ipopts = ipopts;
3144 sc->sc_irs = th->th_seq;
3145 sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
3146 sc->sc_peermaxseg = oi->maxseg;
3147 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
3148 m->m_pkthdr.rcvif : NULL);
3149 #ifdef IPSEC
3150 if (ipsechdrsiz < sc->sc_ourmaxseg)
3151 sc->sc_ourmaxseg -= ipsechdrsiz;
3152 #endif
3153 sc->sc_win = win;
3154 sc->sc_timestamp = tb.ts_recent;
3155 if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
3156 sc->sc_flags |= SCF_TIMESTAMP;
3157 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
3158 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
3159 sc->sc_requested_s_scale = tb.requested_s_scale;
3160 sc->sc_request_r_scale = 0;
3161 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
3162 TCP_MAXWIN << sc->sc_request_r_scale <
3163 so->so_rcv.sb_hiwat)
3164 sc->sc_request_r_scale++;
3165 } else {
3166 sc->sc_requested_s_scale = 15;
3167 sc->sc_request_r_scale = 15;
3168 }
3169 sc->sc_so = so;
3170 if (syn_cache_respond(sc, m) == 0) {
3171 syn_cache_insert(sc);
3172 tcpstat.tcps_sndacks++;
3173 tcpstat.tcps_sndtotal++;
3174 } else {
3175 SYN_CACHE_PUT(sc);
3176 tcpstat.tcps_sc_dropped++;
3177 }
3178 return (1);
3179 }
3180
3181 int
3182 syn_cache_respond(sc, m)
3183 struct syn_cache *sc;
3184 struct mbuf *m;
3185 {
3186 struct route *ro = &sc->sc_route4;
3187 struct rtentry *rt;
3188 u_int8_t *optp;
3189 int optlen, error;
3190 u_int16_t tlen;
3191 struct ip *ip = NULL;
3192 #ifdef INET6
3193 struct ip6_hdr *ip6 = NULL;
3194 #endif
3195 struct tcphdr *th;
3196 u_int hlen;
3197
3198 switch (sc->sc_src.sa.sa_family) {
3199 case AF_INET:
3200 hlen = sizeof(struct ip);
3201 break;
3202 #ifdef INET6
3203 case AF_INET6:
3204 hlen = sizeof(struct ip6_hdr);
3205 break;
3206 #endif
3207 default:
3208 if (m)
3209 m_freem(m);
3210 return EAFNOSUPPORT;
3211 }
3212
3213 /* Compute the size of the TCP options. */
3214 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
3215 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
3216
3217 tlen = hlen + sizeof(struct tcphdr) + optlen;
3218
3219 /*
3220 * Create the IP+TCP header from scratch. Reuse the received mbuf
3221 * if possible.
3222 */
3223 if (m != NULL) {
3224 m_freem(m->m_next);
3225 m->m_next = NULL;
3226 MRESETDATA(m);
3227 } else {
3228 MGETHDR(m, M_DONTWAIT, MT_DATA);
3229 if (m == NULL)
3230 return (ENOBUFS);
3231 }
3232
3233 /* Fixup the mbuf. */
3234 m->m_data += max_linkhdr;
3235 m->m_len = m->m_pkthdr.len = tlen;
3236 #ifdef IPSEC
3237 /* use IPsec policy on listening socket, on SYN ACK */
3238 m->m_pkthdr.rcvif = (struct ifnet *)sc->sc_so;
3239 #else
3240 m->m_pkthdr.rcvif = NULL;
3241 #endif
3242 memset(mtod(m, u_char *), 0, tlen);
3243
3244 switch (sc->sc_src.sa.sa_family) {
3245 case AF_INET:
3246 ip = mtod(m, struct ip *);
3247 ip->ip_dst = sc->sc_src.sin.sin_addr;
3248 ip->ip_src = sc->sc_dst.sin.sin_addr;
3249 ip->ip_p = IPPROTO_TCP;
3250 th = (struct tcphdr *)(ip + 1);
3251 th->th_dport = sc->sc_src.sin.sin_port;
3252 th->th_sport = sc->sc_dst.sin.sin_port;
3253 break;
3254 #ifdef INET6
3255 case AF_INET6:
3256 ip6 = mtod(m, struct ip6_hdr *);
3257 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
3258 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
3259 ip6->ip6_nxt = IPPROTO_TCP;
3260 /* ip6_plen will be updated in ip6_output() */
3261 th = (struct tcphdr *)(ip6 + 1);
3262 th->th_dport = sc->sc_src.sin6.sin6_port;
3263 th->th_sport = sc->sc_dst.sin6.sin6_port;
3264 break;
3265 #endif
3266 default:
3267 th = NULL;
3268 }
3269
3270 th->th_seq = htonl(sc->sc_iss);
3271 th->th_ack = htonl(sc->sc_irs + 1);
3272 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
3273 th->th_flags = TH_SYN|TH_ACK;
3274 th->th_win = htons(sc->sc_win);
3275 /* th_sum already 0 */
3276 /* th_urp already 0 */
3277
3278 /* Tack on the TCP options. */
3279 optp = (u_int8_t *)(th + 1);
3280 *optp++ = TCPOPT_MAXSEG;
3281 *optp++ = 4;
3282 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
3283 *optp++ = sc->sc_ourmaxseg & 0xff;
3284
3285 if (sc->sc_request_r_scale != 15) {
3286 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
3287 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
3288 sc->sc_request_r_scale);
3289 optp += 4;
3290 }
3291
3292 if (sc->sc_flags & SCF_TIMESTAMP) {
3293 u_int32_t *lp = (u_int32_t *)(optp);
3294 /* Form timestamp option as shown in appendix A of RFC 1323. */
3295 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
3296 *lp++ = htonl(tcp_now);
3297 *lp = htonl(sc->sc_timestamp);
3298 optp += TCPOLEN_TSTAMP_APPA;
3299 }
3300
3301 /* Compute the packet's checksum. */
3302 switch (sc->sc_src.sa.sa_family) {
3303 case AF_INET:
3304 ip->ip_len = htons(tlen - hlen);
3305 th->th_sum = 0;
3306 th->th_sum = in_cksum(m, tlen);
3307 break;
3308 #ifdef INET6
3309 case AF_INET6:
3310 ip6->ip6_plen = htons(tlen - hlen);
3311 th->th_sum = 0;
3312 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
3313 break;
3314 #endif
3315 }
3316
3317 /*
3318 * Fill in some straggling IP bits. Note the stack expects
3319 * ip_len to be in host order, for convenience.
3320 */
3321 switch (sc->sc_src.sa.sa_family) {
3322 case AF_INET:
3323 ip->ip_len = tlen;
3324 ip->ip_ttl = ip_defttl;
3325 /* XXX tos? */
3326 break;
3327 #ifdef INET6
3328 case AF_INET6:
3329 ip6->ip6_vfc = IPV6_VERSION;
3330 ip6->ip6_plen = htons(tlen - hlen);
3331 ip6->ip6_hlim = ip6_defhlim;
3332 /* XXX flowlabel? */
3333 break;
3334 #endif
3335 }
3336
3337 /*
3338 * If we're doing Path MTU discovery, we need to set DF unless
3339 * the route's MTU is locked. If we don't yet know the route,
3340 * look it up now. We will copy this reference to the inpcb
3341 * when we finish creating the connection.
3342 */
3343 if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
3344 if (ro->ro_rt != NULL) {
3345 RTFREE(ro->ro_rt);
3346 ro->ro_rt = NULL;
3347 }
3348 bcopy(&sc->sc_src, &ro->ro_dst, sc->sc_src.sa.sa_len);
3349 rtalloc(ro);
3350 if ((rt = ro->ro_rt) == NULL) {
3351 m_freem(m);
3352 switch (sc->sc_src.sa.sa_family) {
3353 case AF_INET:
3354 ipstat.ips_noroute++;
3355 break;
3356 #ifdef INET6
3357 case AF_INET6:
3358 ip6stat.ip6s_noroute++;
3359 break;
3360 #endif
3361 }
3362 return (EHOSTUNREACH);
3363 }
3364 }
3365
3366 switch (sc->sc_src.sa.sa_family) {
3367 case AF_INET:
3368 if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
3369 ip->ip_off |= IP_DF;
3370
3371 /* ...and send it off! */
3372 error = ip_output(m, sc->sc_ipopts, ro, 0, NULL);
3373 break;
3374 #ifdef INET6
3375 case AF_INET6:
3376 error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro,
3377 0, NULL);
3378 break;
3379 #endif
3380 default:
3381 error = EAFNOSUPPORT;
3382 break;
3383 }
3384 return (error);
3385 }
3386