tcp_input.c revision 1.97 1 /* $NetBSD: tcp_input.c,v 1.97 1999/12/08 16:22:20 itojun 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_adj(m, toff + off);
1161 sbappend(&so->so_rcv, m);
1162 sorwakeup(so);
1163 TCP_SETUP_ACK(tp, th);
1164 if (tp->t_flags & TF_ACKNOW)
1165 (void) tcp_output(tp);
1166 if (tcp_saveti)
1167 m_freem(tcp_saveti);
1168 return;
1169 }
1170 }
1171
1172 /*
1173 * Compute mbuf offset to TCP data segment.
1174 */
1175 hdroptlen = toff + off;
1176
1177 /*
1178 * Calculate amount of space in receive window,
1179 * and then do TCP input processing.
1180 * Receive window is amount of space in rcv queue,
1181 * but not less than advertised window.
1182 */
1183 { int win;
1184
1185 win = sbspace(&so->so_rcv);
1186 if (win < 0)
1187 win = 0;
1188 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1189 }
1190
1191 switch (tp->t_state) {
1192
1193 /*
1194 * If the state is SYN_SENT:
1195 * if seg contains an ACK, but not for our SYN, drop the input.
1196 * if seg contains a RST, then drop the connection.
1197 * if seg does not contain SYN, then drop it.
1198 * Otherwise this is an acceptable SYN segment
1199 * initialize tp->rcv_nxt and tp->irs
1200 * if seg contains ack then advance tp->snd_una
1201 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1202 * arrange for segment to be acked (eventually)
1203 * continue processing rest of data/controls, beginning with URG
1204 */
1205 case TCPS_SYN_SENT:
1206 if ((tiflags & TH_ACK) &&
1207 (SEQ_LEQ(th->th_ack, tp->iss) ||
1208 SEQ_GT(th->th_ack, tp->snd_max)))
1209 goto dropwithreset;
1210 if (tiflags & TH_RST) {
1211 if (tiflags & TH_ACK)
1212 tp = tcp_drop(tp, ECONNREFUSED);
1213 goto drop;
1214 }
1215 if ((tiflags & TH_SYN) == 0)
1216 goto drop;
1217 if (tiflags & TH_ACK) {
1218 tp->snd_una = tp->snd_recover = th->th_ack;
1219 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1220 tp->snd_nxt = tp->snd_una;
1221 }
1222 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1223 tp->irs = th->th_seq;
1224 tcp_rcvseqinit(tp);
1225 tp->t_flags |= TF_ACKNOW;
1226 tcp_mss_from_peer(tp, opti.maxseg);
1227
1228 /*
1229 * Initialize the initial congestion window. If we
1230 * had to retransmit the SYN, we must initialize cwnd
1231 * to 1 segment (i.e. the Loss Window).
1232 */
1233 if (tp->t_flags & TF_SYN_REXMT)
1234 tp->snd_cwnd = tp->t_peermss;
1235 else
1236 tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win,
1237 tp->t_peermss);
1238
1239 tcp_rmx_rtt(tp);
1240 if (tiflags & TH_ACK && SEQ_GT(tp->snd_una, tp->iss)) {
1241 tcpstat.tcps_connects++;
1242 soisconnected(so);
1243 tcp_established(tp);
1244 /* Do window scaling on this connection? */
1245 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1246 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1247 tp->snd_scale = tp->requested_s_scale;
1248 tp->rcv_scale = tp->request_r_scale;
1249 }
1250 TCP_REASS_LOCK(tp);
1251 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1252 TCP_REASS_UNLOCK(tp);
1253 /*
1254 * if we didn't have to retransmit the SYN,
1255 * use its rtt as our initial srtt & rtt var.
1256 */
1257 if (tp->t_rtt)
1258 tcp_xmit_timer(tp, tp->t_rtt);
1259 } else
1260 tp->t_state = TCPS_SYN_RECEIVED;
1261
1262 /*
1263 * Advance th->th_seq to correspond to first data byte.
1264 * If data, trim to stay within window,
1265 * dropping FIN if necessary.
1266 */
1267 th->th_seq++;
1268 if (tlen > tp->rcv_wnd) {
1269 todrop = tlen - tp->rcv_wnd;
1270 m_adj(m, -todrop);
1271 tlen = tp->rcv_wnd;
1272 tiflags &= ~TH_FIN;
1273 tcpstat.tcps_rcvpackafterwin++;
1274 tcpstat.tcps_rcvbyteafterwin += todrop;
1275 }
1276 tp->snd_wl1 = th->th_seq - 1;
1277 tp->rcv_up = th->th_seq;
1278 goto step6;
1279
1280 /*
1281 * If the state is SYN_RECEIVED:
1282 * If seg contains an ACK, but not for our SYN, drop the input
1283 * and generate an RST. See page 36, rfc793
1284 */
1285 case TCPS_SYN_RECEIVED:
1286 if ((tiflags & TH_ACK) &&
1287 (SEQ_LEQ(th->th_ack, tp->iss) ||
1288 SEQ_GT(th->th_ack, tp->snd_max)))
1289 goto dropwithreset;
1290 break;
1291 }
1292
1293 /*
1294 * States other than LISTEN or SYN_SENT.
1295 * First check timestamp, if present.
1296 * Then check that at least some bytes of segment are within
1297 * receive window. If segment begins before rcv_nxt,
1298 * drop leading data (and SYN); if nothing left, just ack.
1299 *
1300 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1301 * and it's less than ts_recent, drop it.
1302 */
1303 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
1304 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
1305
1306 /* Check to see if ts_recent is over 24 days old. */
1307 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1308 /*
1309 * Invalidate ts_recent. If this segment updates
1310 * ts_recent, the age will be reset later and ts_recent
1311 * will get a valid value. If it does not, setting
1312 * ts_recent to zero will at least satisfy the
1313 * requirement that zero be placed in the timestamp
1314 * echo reply when ts_recent isn't valid. The
1315 * age isn't reset until we get a valid ts_recent
1316 * because we don't want out-of-order segments to be
1317 * dropped when ts_recent is old.
1318 */
1319 tp->ts_recent = 0;
1320 } else {
1321 tcpstat.tcps_rcvduppack++;
1322 tcpstat.tcps_rcvdupbyte += tlen;
1323 tcpstat.tcps_pawsdrop++;
1324 goto dropafterack;
1325 }
1326 }
1327
1328 todrop = tp->rcv_nxt - th->th_seq;
1329 if (todrop > 0) {
1330 if (tiflags & TH_SYN) {
1331 tiflags &= ~TH_SYN;
1332 th->th_seq++;
1333 if (th->th_urp > 1)
1334 th->th_urp--;
1335 else {
1336 tiflags &= ~TH_URG;
1337 th->th_urp = 0;
1338 }
1339 todrop--;
1340 }
1341 if (todrop > tlen ||
1342 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1343 /*
1344 * Any valid FIN must be to the left of the window.
1345 * At this point the FIN must be a duplicate or
1346 * out of sequence; drop it.
1347 */
1348 tiflags &= ~TH_FIN;
1349 /*
1350 * Send an ACK to resynchronize and drop any data.
1351 * But keep on processing for RST or ACK.
1352 */
1353 tp->t_flags |= TF_ACKNOW;
1354 todrop = tlen;
1355 tcpstat.tcps_rcvdupbyte += todrop;
1356 tcpstat.tcps_rcvduppack++;
1357 } else {
1358 tcpstat.tcps_rcvpartduppack++;
1359 tcpstat.tcps_rcvpartdupbyte += todrop;
1360 }
1361 hdroptlen += todrop; /*drop from head afterwards*/
1362 th->th_seq += todrop;
1363 tlen -= todrop;
1364 if (th->th_urp > todrop)
1365 th->th_urp -= todrop;
1366 else {
1367 tiflags &= ~TH_URG;
1368 th->th_urp = 0;
1369 }
1370 }
1371
1372 /*
1373 * If new data are received on a connection after the
1374 * user processes are gone, then RST the other end.
1375 */
1376 if ((so->so_state & SS_NOFDREF) &&
1377 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1378 tp = tcp_close(tp);
1379 tcpstat.tcps_rcvafterclose++;
1380 goto dropwithreset;
1381 }
1382
1383 /*
1384 * If segment ends after window, drop trailing data
1385 * (and PUSH and FIN); if nothing left, just ACK.
1386 */
1387 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
1388 if (todrop > 0) {
1389 tcpstat.tcps_rcvpackafterwin++;
1390 if (todrop >= tlen) {
1391 tcpstat.tcps_rcvbyteafterwin += tlen;
1392 /*
1393 * If a new connection request is received
1394 * while in TIME_WAIT, drop the old connection
1395 * and start over if the sequence numbers
1396 * are above the previous ones.
1397 */
1398 if (tiflags & TH_SYN &&
1399 tp->t_state == TCPS_TIME_WAIT &&
1400 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1401 iss = tcp_new_iss(tp, sizeof(struct tcpcb),
1402 tp->snd_nxt);
1403 tp = tcp_close(tp);
1404 goto findpcb;
1405 }
1406 /*
1407 * If window is closed can only take segments at
1408 * window edge, and have to drop data and PUSH from
1409 * incoming segments. Continue processing, but
1410 * remember to ack. Otherwise, drop segment
1411 * and ack.
1412 */
1413 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1414 tp->t_flags |= TF_ACKNOW;
1415 tcpstat.tcps_rcvwinprobe++;
1416 } else
1417 goto dropafterack;
1418 } else
1419 tcpstat.tcps_rcvbyteafterwin += todrop;
1420 m_adj(m, -todrop);
1421 tlen -= todrop;
1422 tiflags &= ~(TH_PUSH|TH_FIN);
1423 }
1424
1425 /*
1426 * If last ACK falls within this segment's sequence numbers,
1427 * and the timestamp is newer, record it.
1428 */
1429 if (opti.ts_present && TSTMP_GEQ(opti.ts_val, tp->ts_recent) &&
1430 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1431 SEQ_LT(tp->last_ack_sent, th->th_seq + tlen +
1432 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
1433 tp->ts_recent_age = tcp_now;
1434 tp->ts_recent = opti.ts_val;
1435 }
1436
1437 /*
1438 * If the RST bit is set examine the state:
1439 * SYN_RECEIVED STATE:
1440 * If passive open, return to LISTEN state.
1441 * If active open, inform user that connection was refused.
1442 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1443 * Inform user that connection was reset, and close tcb.
1444 * CLOSING, LAST_ACK, TIME_WAIT STATES
1445 * Close the tcb.
1446 */
1447 if (tiflags&TH_RST) switch (tp->t_state) {
1448
1449 case TCPS_SYN_RECEIVED:
1450 so->so_error = ECONNREFUSED;
1451 goto close;
1452
1453 case TCPS_ESTABLISHED:
1454 case TCPS_FIN_WAIT_1:
1455 case TCPS_FIN_WAIT_2:
1456 case TCPS_CLOSE_WAIT:
1457 so->so_error = ECONNRESET;
1458 close:
1459 tp->t_state = TCPS_CLOSED;
1460 tcpstat.tcps_drops++;
1461 tp = tcp_close(tp);
1462 goto drop;
1463
1464 case TCPS_CLOSING:
1465 case TCPS_LAST_ACK:
1466 case TCPS_TIME_WAIT:
1467 tp = tcp_close(tp);
1468 goto drop;
1469 }
1470
1471 /*
1472 * If a SYN is in the window, then this is an
1473 * error and we send an RST and drop the connection.
1474 */
1475 if (tiflags & TH_SYN) {
1476 tp = tcp_drop(tp, ECONNRESET);
1477 goto dropwithreset;
1478 }
1479
1480 /*
1481 * If the ACK bit is off we drop the segment and return.
1482 */
1483 if ((tiflags & TH_ACK) == 0) {
1484 if (tp->t_flags & TF_ACKNOW)
1485 goto dropafterack;
1486 else
1487 goto drop;
1488 }
1489
1490 /*
1491 * Ack processing.
1492 */
1493 switch (tp->t_state) {
1494
1495 /*
1496 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
1497 * ESTABLISHED state and continue processing, otherwise
1498 * send an RST.
1499 */
1500 case TCPS_SYN_RECEIVED:
1501 if (SEQ_GT(tp->snd_una, th->th_ack) ||
1502 SEQ_GT(th->th_ack, tp->snd_max))
1503 goto dropwithreset;
1504 tcpstat.tcps_connects++;
1505 soisconnected(so);
1506 tcp_established(tp);
1507 /* Do window scaling? */
1508 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1509 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1510 tp->snd_scale = tp->requested_s_scale;
1511 tp->rcv_scale = tp->request_r_scale;
1512 }
1513 TCP_REASS_LOCK(tp);
1514 (void) tcp_reass(tp, NULL, (struct mbuf *)0, &tlen);
1515 TCP_REASS_UNLOCK(tp);
1516 tp->snd_wl1 = th->th_seq - 1;
1517 /* fall into ... */
1518
1519 /*
1520 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1521 * ACKs. If the ack is in the range
1522 * tp->snd_una < th->th_ack <= tp->snd_max
1523 * then advance tp->snd_una to th->th_ack and drop
1524 * data from the retransmission queue. If this ACK reflects
1525 * more up to date window information we update our window information.
1526 */
1527 case TCPS_ESTABLISHED:
1528 case TCPS_FIN_WAIT_1:
1529 case TCPS_FIN_WAIT_2:
1530 case TCPS_CLOSE_WAIT:
1531 case TCPS_CLOSING:
1532 case TCPS_LAST_ACK:
1533 case TCPS_TIME_WAIT:
1534
1535 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1536 if (tlen == 0 && tiwin == tp->snd_wnd) {
1537 tcpstat.tcps_rcvdupack++;
1538 /*
1539 * If we have outstanding data (other than
1540 * a window probe), this is a completely
1541 * duplicate ack (ie, window info didn't
1542 * change), the ack is the biggest we've
1543 * seen and we've seen exactly our rexmt
1544 * threshhold of them, assume a packet
1545 * has been dropped and retransmit it.
1546 * Kludge snd_nxt & the congestion
1547 * window so we send only this one
1548 * packet.
1549 *
1550 * We know we're losing at the current
1551 * window size so do congestion avoidance
1552 * (set ssthresh to half the current window
1553 * and pull our congestion window back to
1554 * the new ssthresh).
1555 *
1556 * Dup acks mean that packets have left the
1557 * network (they're now cached at the receiver)
1558 * so bump cwnd by the amount in the receiver
1559 * to keep a constant cwnd packets in the
1560 * network.
1561 */
1562 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
1563 th->th_ack != tp->snd_una)
1564 tp->t_dupacks = 0;
1565 else if (++tp->t_dupacks == tcprexmtthresh) {
1566 tcp_seq onxt = tp->snd_nxt;
1567 u_int win =
1568 min(tp->snd_wnd, tp->snd_cwnd) /
1569 2 / tp->t_segsz;
1570 if (tcp_do_newreno && SEQ_LT(th->th_ack,
1571 tp->snd_recover)) {
1572 /*
1573 * False fast retransmit after
1574 * timeout. Do not cut window.
1575 */
1576 tp->snd_cwnd += tp->t_segsz;
1577 tp->t_dupacks = 0;
1578 (void) tcp_output(tp);
1579 goto drop;
1580 }
1581
1582 if (win < 2)
1583 win = 2;
1584 tp->snd_ssthresh = win * tp->t_segsz;
1585 tp->snd_recover = tp->snd_max;
1586 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1587 tp->t_rtt = 0;
1588 tp->snd_nxt = th->th_ack;
1589 tp->snd_cwnd = tp->t_segsz;
1590 (void) tcp_output(tp);
1591 tp->snd_cwnd = tp->snd_ssthresh +
1592 tp->t_segsz * tp->t_dupacks;
1593 if (SEQ_GT(onxt, tp->snd_nxt))
1594 tp->snd_nxt = onxt;
1595 goto drop;
1596 } else if (tp->t_dupacks > tcprexmtthresh) {
1597 tp->snd_cwnd += tp->t_segsz;
1598 (void) tcp_output(tp);
1599 goto drop;
1600 }
1601 } else
1602 tp->t_dupacks = 0;
1603 break;
1604 }
1605 /*
1606 * If the congestion window was inflated to account
1607 * for the other side's cached packets, retract it.
1608 */
1609 if (tcp_do_newreno == 0) {
1610 if (tp->t_dupacks >= tcprexmtthresh &&
1611 tp->snd_cwnd > tp->snd_ssthresh)
1612 tp->snd_cwnd = tp->snd_ssthresh;
1613 tp->t_dupacks = 0;
1614 } else if (tp->t_dupacks >= tcprexmtthresh &&
1615 tcp_newreno(tp, th) == 0) {
1616 tp->snd_cwnd = tp->snd_ssthresh;
1617 /*
1618 * Window inflation should have left us with approx.
1619 * snd_ssthresh outstanding data. But in case we
1620 * would be inclined to send a burst, better to do
1621 * it via the slow start mechanism.
1622 */
1623 if (SEQ_SUB(tp->snd_max, th->th_ack) < tp->snd_ssthresh)
1624 tp->snd_cwnd = SEQ_SUB(tp->snd_max, th->th_ack)
1625 + tp->t_segsz;
1626 tp->t_dupacks = 0;
1627 }
1628 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1629 tcpstat.tcps_rcvacktoomuch++;
1630 goto dropafterack;
1631 }
1632 acked = th->th_ack - tp->snd_una;
1633 tcpstat.tcps_rcvackpack++;
1634 tcpstat.tcps_rcvackbyte += acked;
1635
1636 /*
1637 * If we have a timestamp reply, update smoothed
1638 * round trip time. If no timestamp is present but
1639 * transmit timer is running and timed sequence
1640 * number was acked, update smoothed round trip time.
1641 * Since we now have an rtt measurement, cancel the
1642 * timer backoff (cf., Phil Karn's retransmit alg.).
1643 * Recompute the initial retransmit timer.
1644 */
1645 if (opti.ts_present && opti.ts_ecr)
1646 tcp_xmit_timer(tp, tcp_now - opti.ts_ecr + 1);
1647 else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
1648 tcp_xmit_timer(tp,tp->t_rtt);
1649
1650 /*
1651 * If all outstanding data is acked, stop retransmit
1652 * timer and remember to restart (more output or persist).
1653 * If there is more data to be acked, restart retransmit
1654 * timer, using current (possibly backed-off) value.
1655 */
1656 if (th->th_ack == tp->snd_max) {
1657 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1658 needoutput = 1;
1659 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
1660 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
1661 /*
1662 * When new data is acked, open the congestion window.
1663 * If the window gives us less than ssthresh packets
1664 * in flight, open exponentially (segsz per packet).
1665 * Otherwise open linearly: segsz per window
1666 * (segsz^2 / cwnd per packet), plus a constant
1667 * fraction of a packet (segsz/8) to help larger windows
1668 * open quickly enough.
1669 */
1670 {
1671 register u_int cw = tp->snd_cwnd;
1672 register u_int incr = tp->t_segsz;
1673
1674 if (cw > tp->snd_ssthresh)
1675 incr = incr * incr / cw;
1676 if (tcp_do_newreno == 0 || SEQ_GEQ(th->th_ack, tp->snd_recover))
1677 tp->snd_cwnd = min(cw + incr,
1678 TCP_MAXWIN << tp->snd_scale);
1679 }
1680 if (acked > so->so_snd.sb_cc) {
1681 tp->snd_wnd -= so->so_snd.sb_cc;
1682 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1683 ourfinisacked = 1;
1684 } else {
1685 sbdrop(&so->so_snd, acked);
1686 tp->snd_wnd -= acked;
1687 ourfinisacked = 0;
1688 }
1689 sowwakeup(so);
1690 /*
1691 * We want snd_recover to track snd_una to
1692 * avoid sequence wraparound problems for
1693 * very large transfers.
1694 */
1695 tp->snd_una = tp->snd_recover = th->th_ack;
1696 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1697 tp->snd_nxt = tp->snd_una;
1698
1699 switch (tp->t_state) {
1700
1701 /*
1702 * In FIN_WAIT_1 STATE in addition to the processing
1703 * for the ESTABLISHED state if our FIN is now acknowledged
1704 * then enter FIN_WAIT_2.
1705 */
1706 case TCPS_FIN_WAIT_1:
1707 if (ourfinisacked) {
1708 /*
1709 * If we can't receive any more
1710 * data, then closing user can proceed.
1711 * Starting the timer is contrary to the
1712 * specification, but if we don't get a FIN
1713 * we'll hang forever.
1714 */
1715 if (so->so_state & SS_CANTRCVMORE) {
1716 soisdisconnected(so);
1717 if (tcp_maxidle > 0)
1718 TCP_TIMER_ARM(tp, TCPT_2MSL,
1719 tcp_maxidle);
1720 }
1721 tp->t_state = TCPS_FIN_WAIT_2;
1722 }
1723 break;
1724
1725 /*
1726 * In CLOSING STATE in addition to the processing for
1727 * the ESTABLISHED state if the ACK acknowledges our FIN
1728 * then enter the TIME-WAIT state, otherwise ignore
1729 * the segment.
1730 */
1731 case TCPS_CLOSING:
1732 if (ourfinisacked) {
1733 tp->t_state = TCPS_TIME_WAIT;
1734 tcp_canceltimers(tp);
1735 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1736 soisdisconnected(so);
1737 }
1738 break;
1739
1740 /*
1741 * In LAST_ACK, we may still be waiting for data to drain
1742 * and/or to be acked, as well as for the ack of our FIN.
1743 * If our FIN is now acknowledged, delete the TCB,
1744 * enter the closed state and return.
1745 */
1746 case TCPS_LAST_ACK:
1747 if (ourfinisacked) {
1748 tp = tcp_close(tp);
1749 goto drop;
1750 }
1751 break;
1752
1753 /*
1754 * In TIME_WAIT state the only thing that should arrive
1755 * is a retransmission of the remote FIN. Acknowledge
1756 * it and restart the finack timer.
1757 */
1758 case TCPS_TIME_WAIT:
1759 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1760 goto dropafterack;
1761 }
1762 }
1763
1764 step6:
1765 /*
1766 * Update window information.
1767 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1768 */
1769 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
1770 (tp->snd_wl1 == th->th_seq && SEQ_LT(tp->snd_wl2, th->th_ack)) ||
1771 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))) {
1772 /* keep track of pure window updates */
1773 if (tlen == 0 &&
1774 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
1775 tcpstat.tcps_rcvwinupd++;
1776 tp->snd_wnd = tiwin;
1777 tp->snd_wl1 = th->th_seq;
1778 tp->snd_wl2 = th->th_ack;
1779 if (tp->snd_wnd > tp->max_sndwnd)
1780 tp->max_sndwnd = tp->snd_wnd;
1781 needoutput = 1;
1782 }
1783
1784 /*
1785 * Process segments with URG.
1786 */
1787 if ((tiflags & TH_URG) && th->th_urp &&
1788 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1789 /*
1790 * This is a kludge, but if we receive and accept
1791 * random urgent pointers, we'll crash in
1792 * soreceive. It's hard to imagine someone
1793 * actually wanting to send this much urgent data.
1794 */
1795 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
1796 th->th_urp = 0; /* XXX */
1797 tiflags &= ~TH_URG; /* XXX */
1798 goto dodata; /* XXX */
1799 }
1800 /*
1801 * If this segment advances the known urgent pointer,
1802 * then mark the data stream. This should not happen
1803 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1804 * a FIN has been received from the remote side.
1805 * In these states we ignore the URG.
1806 *
1807 * According to RFC961 (Assigned Protocols),
1808 * the urgent pointer points to the last octet
1809 * of urgent data. We continue, however,
1810 * to consider it to indicate the first octet
1811 * of data past the urgent section as the original
1812 * spec states (in one of two places).
1813 */
1814 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
1815 tp->rcv_up = th->th_seq + th->th_urp;
1816 so->so_oobmark = so->so_rcv.sb_cc +
1817 (tp->rcv_up - tp->rcv_nxt) - 1;
1818 if (so->so_oobmark == 0)
1819 so->so_state |= SS_RCVATMARK;
1820 sohasoutofband(so);
1821 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1822 }
1823 /*
1824 * Remove out of band data so doesn't get presented to user.
1825 * This can happen independent of advancing the URG pointer,
1826 * but if two URG's are pending at once, some out-of-band
1827 * data may creep in... ick.
1828 */
1829 if (th->th_urp <= (u_int16_t) tlen
1830 #ifdef SO_OOBINLINE
1831 && (so->so_options & SO_OOBINLINE) == 0
1832 #endif
1833 )
1834 tcp_pulloutofband(so, th, m, hdroptlen);
1835 } else
1836 /*
1837 * If no out of band data is expected,
1838 * pull receive urgent pointer along
1839 * with the receive window.
1840 */
1841 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1842 tp->rcv_up = tp->rcv_nxt;
1843 dodata: /* XXX */
1844
1845 /*
1846 * Process the segment text, merging it into the TCP sequencing queue,
1847 * and arranging for acknowledgement of receipt if necessary.
1848 * This process logically involves adjusting tp->rcv_wnd as data
1849 * is presented to the user (this happens in tcp_usrreq.c,
1850 * case PRU_RCVD). If a FIN has already been received on this
1851 * connection then we just ignore the text.
1852 */
1853 if ((tlen || (tiflags & TH_FIN)) &&
1854 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1855 /*
1856 * Insert segment ti into reassembly queue of tcp with
1857 * control block tp. Return TH_FIN if reassembly now includes
1858 * a segment with FIN. The macro form does the common case
1859 * inline (segment is the next to be received on an
1860 * established connection, and the queue is empty),
1861 * avoiding linkage into and removal from the queue and
1862 * repetition of various conversions.
1863 * Set DELACK for segments received in order, but ack
1864 * immediately when segments are out of order
1865 * (so fast retransmit can work).
1866 */
1867 /* NOTE: this was TCP_REASS() macro, but used only once */
1868 TCP_REASS_LOCK(tp);
1869 if (th->th_seq == tp->rcv_nxt &&
1870 tp->segq.lh_first == NULL &&
1871 tp->t_state == TCPS_ESTABLISHED) {
1872 TCP_SETUP_ACK(tp, th);
1873 tp->rcv_nxt += tlen;
1874 tiflags = th->th_flags & TH_FIN;
1875 tcpstat.tcps_rcvpack++;
1876 tcpstat.tcps_rcvbyte += tlen;
1877 m_adj(m, hdroptlen);
1878 sbappend(&(so)->so_rcv, m);
1879 sorwakeup(so);
1880 } else {
1881 m_adj(m, hdroptlen);
1882 tiflags = tcp_reass(tp, th, m, &tlen);
1883 tp->t_flags |= TF_ACKNOW;
1884 }
1885 TCP_REASS_UNLOCK(tp);
1886
1887 /*
1888 * Note the amount of data that peer has sent into
1889 * our window, in order to estimate the sender's
1890 * buffer size.
1891 */
1892 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1893 } else {
1894 m_freem(m);
1895 m = NULL;
1896 tiflags &= ~TH_FIN;
1897 }
1898
1899 /*
1900 * If FIN is received ACK the FIN and let the user know
1901 * that the connection is closing. Ignore a FIN received before
1902 * the connection is fully established.
1903 */
1904 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
1905 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1906 socantrcvmore(so);
1907 tp->t_flags |= TF_ACKNOW;
1908 tp->rcv_nxt++;
1909 }
1910 switch (tp->t_state) {
1911
1912 /*
1913 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
1914 */
1915 case TCPS_ESTABLISHED:
1916 tp->t_state = TCPS_CLOSE_WAIT;
1917 break;
1918
1919 /*
1920 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1921 * enter the CLOSING state.
1922 */
1923 case TCPS_FIN_WAIT_1:
1924 tp->t_state = TCPS_CLOSING;
1925 break;
1926
1927 /*
1928 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1929 * starting the time-wait timer, turning off the other
1930 * standard timers.
1931 */
1932 case TCPS_FIN_WAIT_2:
1933 tp->t_state = TCPS_TIME_WAIT;
1934 tcp_canceltimers(tp);
1935 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1936 soisdisconnected(so);
1937 break;
1938
1939 /*
1940 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1941 */
1942 case TCPS_TIME_WAIT:
1943 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
1944 break;
1945 }
1946 }
1947 if (so->so_options & SO_DEBUG) {
1948 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
1949 }
1950
1951 /*
1952 * Return any desired output.
1953 */
1954 if (needoutput || (tp->t_flags & TF_ACKNOW))
1955 (void) tcp_output(tp);
1956 if (tcp_saveti)
1957 m_freem(tcp_saveti);
1958 return;
1959
1960 badsyn:
1961 /*
1962 * Received a bad SYN. Increment counters and dropwithreset.
1963 */
1964 tcpstat.tcps_badsyn++;
1965 tp = NULL;
1966 goto dropwithreset;
1967
1968 dropafterack:
1969 /*
1970 * Generate an ACK dropping incoming segment if it occupies
1971 * sequence space, where the ACK reflects our state.
1972 */
1973 if (tiflags & TH_RST)
1974 goto drop;
1975 m_freem(m);
1976 tp->t_flags |= TF_ACKNOW;
1977 (void) tcp_output(tp);
1978 if (tcp_saveti)
1979 m_freem(tcp_saveti);
1980 return;
1981
1982 dropwithreset:
1983 /*
1984 * Generate a RST, dropping incoming segment.
1985 * Make ACK acceptable to originator of segment.
1986 * Don't bother to respond if destination was broadcast/multicast.
1987 */
1988 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
1989 goto drop;
1990 if (ip && IN_MULTICAST(ip->ip_dst.s_addr))
1991 goto drop;
1992 #ifdef INET6
1993 if (m->m_flags & M_ANYCAST6)
1994 goto drop;
1995 else if (ip6 && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1996 goto drop;
1997 #endif
1998 {
1999 /*
2000 * need to recover version # field, which was overwritten on
2001 * ip_cksum computation.
2002 */
2003 struct ip *sip;
2004 sip = mtod(m, struct ip *);
2005 switch (af) {
2006 case AF_INET:
2007 sip->ip_v = 4;
2008 break;
2009 #ifdef INET6
2010 case AF_INET6:
2011 sip->ip_v = 6;
2012 break;
2013 #endif
2014 }
2015 }
2016 if (tiflags & TH_ACK)
2017 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2018 else {
2019 if (tiflags & TH_SYN)
2020 tlen++;
2021 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2022 TH_RST|TH_ACK);
2023 }
2024 if (tcp_saveti)
2025 m_freem(tcp_saveti);
2026 return;
2027
2028 drop:
2029 /*
2030 * Drop space held by incoming segment and return.
2031 */
2032 if (tp) {
2033 if (tp->t_inpcb)
2034 so = tp->t_inpcb->inp_socket;
2035 #ifdef INET6
2036 else if (tp->t_in6pcb)
2037 so = tp->t_in6pcb->in6p_socket;
2038 #endif
2039 else
2040 so = NULL;
2041 if (so && (so->so_options & SO_DEBUG) != 0)
2042 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2043 }
2044 if (tcp_saveti)
2045 m_freem(tcp_saveti);
2046 m_freem(m);
2047 return;
2048 }
2049
2050 void
2051 tcp_dooptions(tp, cp, cnt, th, oi)
2052 struct tcpcb *tp;
2053 u_char *cp;
2054 int cnt;
2055 struct tcphdr *th;
2056 struct tcp_opt_info *oi;
2057 {
2058 u_int16_t mss;
2059 int opt, optlen;
2060
2061 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2062 opt = cp[0];
2063 if (opt == TCPOPT_EOL)
2064 break;
2065 if (opt == TCPOPT_NOP)
2066 optlen = 1;
2067 else {
2068 optlen = cp[1];
2069 if (optlen <= 0)
2070 break;
2071 }
2072 switch (opt) {
2073
2074 default:
2075 continue;
2076
2077 case TCPOPT_MAXSEG:
2078 if (optlen != TCPOLEN_MAXSEG)
2079 continue;
2080 if (!(th->th_flags & TH_SYN))
2081 continue;
2082 bcopy(cp + 2, &mss, sizeof(mss));
2083 oi->maxseg = ntohs(mss);
2084 break;
2085
2086 case TCPOPT_WINDOW:
2087 if (optlen != TCPOLEN_WINDOW)
2088 continue;
2089 if (!(th->th_flags & TH_SYN))
2090 continue;
2091 tp->t_flags |= TF_RCVD_SCALE;
2092 tp->requested_s_scale = cp[2];
2093 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2094 #if 0 /*XXX*/
2095 char *p;
2096
2097 if (ip)
2098 p = ntohl(ip->ip_src);
2099 #ifdef INET6
2100 else if (ip6)
2101 p = ip6_sprintf(&ip6->ip6_src);
2102 #endif
2103 else
2104 p = "(unknown)";
2105 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2106 "assuming %d\n",
2107 tp->requested_s_scale, p,
2108 TCP_MAX_WINSHIFT);
2109 #else
2110 log(LOG_ERR, "TCP: invalid wscale %d, "
2111 "assuming %d\n",
2112 tp->requested_s_scale,
2113 TCP_MAX_WINSHIFT);
2114 #endif
2115 tp->requested_s_scale = TCP_MAX_WINSHIFT;
2116 }
2117 break;
2118
2119 case TCPOPT_TIMESTAMP:
2120 if (optlen != TCPOLEN_TIMESTAMP)
2121 continue;
2122 oi->ts_present = 1;
2123 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2124 NTOHL(oi->ts_val);
2125 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2126 NTOHL(oi->ts_ecr);
2127
2128 /*
2129 * A timestamp received in a SYN makes
2130 * it ok to send timestamp requests and replies.
2131 */
2132 if (th->th_flags & TH_SYN) {
2133 tp->t_flags |= TF_RCVD_TSTMP;
2134 tp->ts_recent = oi->ts_val;
2135 tp->ts_recent_age = tcp_now;
2136 }
2137 break;
2138 case TCPOPT_SACK_PERMITTED:
2139 if (optlen != TCPOLEN_SACK_PERMITTED)
2140 continue;
2141 if (!(th->th_flags & TH_SYN))
2142 continue;
2143 tp->t_flags &= ~TF_CANT_TXSACK;
2144 break;
2145
2146 case TCPOPT_SACK:
2147 if (tp->t_flags & TF_IGNR_RXSACK)
2148 continue;
2149 if (optlen % 8 != 2 || optlen < 10)
2150 continue;
2151 cp += 2;
2152 optlen -= 2;
2153 for (; optlen > 0; cp -= 8, optlen -= 8) {
2154 tcp_seq lwe, rwe;
2155 bcopy((char *)cp, (char *) &lwe, sizeof(lwe));
2156 NTOHL(lwe);
2157 bcopy((char *)cp, (char *) &rwe, sizeof(rwe));
2158 NTOHL(rwe);
2159 /* tcp_mark_sacked(tp, lwe, rwe); */
2160 }
2161 break;
2162 }
2163 }
2164 }
2165
2166 /*
2167 * Pull out of band byte out of a segment so
2168 * it doesn't appear in the user's data queue.
2169 * It is still reflected in the segment length for
2170 * sequencing purposes.
2171 */
2172 void
2173 tcp_pulloutofband(so, th, m, off)
2174 struct socket *so;
2175 struct tcphdr *th;
2176 register struct mbuf *m;
2177 int off;
2178 {
2179 int cnt = off + th->th_urp - 1;
2180
2181 while (cnt >= 0) {
2182 if (m->m_len > cnt) {
2183 char *cp = mtod(m, caddr_t) + cnt;
2184 struct tcpcb *tp = sototcpcb(so);
2185
2186 tp->t_iobc = *cp;
2187 tp->t_oobflags |= TCPOOB_HAVEDATA;
2188 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2189 m->m_len--;
2190 return;
2191 }
2192 cnt -= m->m_len;
2193 m = m->m_next;
2194 if (m == 0)
2195 break;
2196 }
2197 panic("tcp_pulloutofband");
2198 }
2199
2200 /*
2201 * Collect new round-trip time estimate
2202 * and update averages and current timeout.
2203 */
2204 void
2205 tcp_xmit_timer(tp, rtt)
2206 register struct tcpcb *tp;
2207 short rtt;
2208 {
2209 register short delta;
2210 short rttmin;
2211
2212 tcpstat.tcps_rttupdated++;
2213 --rtt;
2214 if (tp->t_srtt != 0) {
2215 /*
2216 * srtt is stored as fixed point with 3 bits after the
2217 * binary point (i.e., scaled by 8). The following magic
2218 * is equivalent to the smoothing algorithm in rfc793 with
2219 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2220 * point). Adjust rtt to origin 0.
2221 */
2222 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
2223 if ((tp->t_srtt += delta) <= 0)
2224 tp->t_srtt = 1 << 2;
2225 /*
2226 * We accumulate a smoothed rtt variance (actually, a
2227 * smoothed mean difference), then set the retransmit
2228 * timer to smoothed rtt + 4 times the smoothed variance.
2229 * rttvar is stored as fixed point with 2 bits after the
2230 * binary point (scaled by 4). The following is
2231 * equivalent to rfc793 smoothing with an alpha of .75
2232 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2233 * rfc793's wired-in beta.
2234 */
2235 if (delta < 0)
2236 delta = -delta;
2237 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
2238 if ((tp->t_rttvar += delta) <= 0)
2239 tp->t_rttvar = 1 << 2;
2240 } else {
2241 /*
2242 * No rtt measurement yet - use the unsmoothed rtt.
2243 * Set the variance to half the rtt (so our first
2244 * retransmit happens at 3*rtt).
2245 */
2246 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
2247 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
2248 }
2249 tp->t_rtt = 0;
2250 tp->t_rxtshift = 0;
2251
2252 /*
2253 * the retransmit should happen at rtt + 4 * rttvar.
2254 * Because of the way we do the smoothing, srtt and rttvar
2255 * will each average +1/2 tick of bias. When we compute
2256 * the retransmit timer, we want 1/2 tick of rounding and
2257 * 1 extra tick because of +-1/2 tick uncertainty in the
2258 * firing of the timer. The bias will give us exactly the
2259 * 1.5 tick we need. But, because the bias is
2260 * statistical, we have to test that we don't drop below
2261 * the minimum feasible timer (which is 2 ticks).
2262 */
2263 if (tp->t_rttmin > rtt + 2)
2264 rttmin = tp->t_rttmin;
2265 else
2266 rttmin = rtt + 2;
2267 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp), rttmin, TCPTV_REXMTMAX);
2268
2269 /*
2270 * We received an ack for a packet that wasn't retransmitted;
2271 * it is probably safe to discard any error indications we've
2272 * received recently. This isn't quite right, but close enough
2273 * for now (a route might have failed after we sent a segment,
2274 * and the return path might not be symmetrical).
2275 */
2276 tp->t_softerror = 0;
2277 }
2278
2279 /*
2280 * Checks for partial ack. If partial ack arrives, force the retransmission
2281 * of the next unacknowledged segment, do not clear tp->t_dupacks, and return
2282 * 1. By setting snd_nxt to th_ack, this forces retransmission timer to
2283 * be started again. If the ack advances at least to tp->snd_recover, return 0.
2284 */
2285 int
2286 tcp_newreno(tp, th)
2287 struct tcpcb *tp;
2288 struct tcphdr *th;
2289 {
2290 tcp_seq onxt = tp->snd_nxt;
2291 u_long ocwnd = tp->snd_cwnd;
2292
2293 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2294 /*
2295 * snd_una has not yet been updated and the socket's send
2296 * buffer has not yet drained off the ACK'd data, so we
2297 * have to leave snd_una as it was to get the correct data
2298 * offset in tcp_output().
2299 */
2300 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2301 tp->t_rtt = 0;
2302 tp->snd_nxt = th->th_ack;
2303 /*
2304 * Set snd_cwnd to one segment beyond ACK'd offset. snd_una
2305 * is not yet updated when we're called.
2306 */
2307 tp->snd_cwnd = tp->t_segsz + (th->th_ack - tp->snd_una);
2308 (void) tcp_output(tp);
2309 tp->snd_cwnd = ocwnd;
2310 if (SEQ_GT(onxt, tp->snd_nxt))
2311 tp->snd_nxt = onxt;
2312 /*
2313 * Partial window deflation. Relies on fact that tp->snd_una
2314 * not updated yet.
2315 */
2316 tp->snd_cwnd -= (th->th_ack - tp->snd_una - tp->t_segsz);
2317 return 1;
2318 }
2319 return 0;
2320 }
2321
2322
2323 /*
2324 * TCP compressed state engine. Currently used to hold compressed
2325 * state for SYN_RECEIVED.
2326 */
2327
2328 u_long syn_cache_count;
2329 u_int32_t syn_hash1, syn_hash2;
2330
2331 #define SYN_HASH(sa, sp, dp) \
2332 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
2333 ((u_int32_t)(sp)))^syn_hash2)))
2334 #ifndef INET6
2335 #define SYN_HASHALL(hash, src, dst) \
2336 do { \
2337 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2338 ((struct sockaddr_in *)(src))->sin_port, \
2339 ((struct sockaddr_in *)(dst))->sin_port); \
2340 } while (0)
2341 #else
2342 #define SYN_HASH6(sa, sp, dp) \
2343 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
2344 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
2345 & 0x7fffffff)
2346
2347 #define SYN_HASHALL(hash, src, dst) \
2348 do { \
2349 switch ((src)->sa_family) { \
2350 case AF_INET: \
2351 hash = SYN_HASH(&((struct sockaddr_in *)(src))->sin_addr, \
2352 ((struct sockaddr_in *)(src))->sin_port, \
2353 ((struct sockaddr_in *)(dst))->sin_port); \
2354 break; \
2355 case AF_INET6: \
2356 hash = SYN_HASH6(&((struct sockaddr_in6 *)(src))->sin6_addr, \
2357 ((struct sockaddr_in6 *)(src))->sin6_port, \
2358 ((struct sockaddr_in6 *)(dst))->sin6_port); \
2359 break; \
2360 default: \
2361 hash = 0; \
2362 } \
2363 } while (0)
2364 #endif /* INET6 */
2365
2366 #define SYN_CACHE_RM(sc) \
2367 do { \
2368 LIST_REMOVE((sc), sc_bucketq); \
2369 (sc)->sc_tp = NULL; \
2370 LIST_REMOVE((sc), sc_tpq); \
2371 tcp_syn_cache[(sc)->sc_bucketidx].sch_length--; \
2372 TAILQ_REMOVE(&tcp_syn_cache_timeq[(sc)->sc_rxtshift], (sc), sc_timeq); \
2373 syn_cache_count--; \
2374 } while (0)
2375
2376 #define SYN_CACHE_PUT(sc) \
2377 do { \
2378 if ((sc)->sc_ipopts) \
2379 (void) m_free((sc)->sc_ipopts); \
2380 if ((sc)->sc_route4.ro_rt != NULL) \
2381 RTFREE((sc)->sc_route4.ro_rt); \
2382 pool_put(&syn_cache_pool, (sc)); \
2383 } while (0)
2384
2385 struct pool syn_cache_pool;
2386
2387 /*
2388 * We don't estimate RTT with SYNs, so each packet starts with the default
2389 * RTT and each timer queue has a fixed timeout value. This allows us to
2390 * optimize the timer queues somewhat.
2391 */
2392 #define SYN_CACHE_TIMER_ARM(sc) \
2393 do { \
2394 TCPT_RANGESET((sc)->sc_rxtcur, \
2395 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \
2396 TCPTV_REXMTMAX); \
2397 PRT_SLOW_ARM((sc)->sc_rexmt, (sc)->sc_rxtcur); \
2398 } while (0)
2399
2400 TAILQ_HEAD(, syn_cache) tcp_syn_cache_timeq[TCP_MAXRXTSHIFT + 1];
2401
2402 void
2403 syn_cache_init()
2404 {
2405 int i;
2406
2407 /* Initialize the hash buckets. */
2408 for (i = 0; i < tcp_syn_cache_size; i++)
2409 LIST_INIT(&tcp_syn_cache[i].sch_bucket);
2410
2411 /* Initialize the timer queues. */
2412 for (i = 0; i <= TCP_MAXRXTSHIFT; i++)
2413 TAILQ_INIT(&tcp_syn_cache_timeq[i]);
2414
2415 /* Initialize the syn cache pool. */
2416 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
2417 "synpl", 0, NULL, NULL, M_PCB);
2418 }
2419
2420 void
2421 syn_cache_insert(sc, tp)
2422 struct syn_cache *sc;
2423 struct tcpcb *tp;
2424 {
2425 struct syn_cache_head *scp;
2426 struct syn_cache *sc2;
2427 int s, i;
2428
2429 /*
2430 * If there are no entries in the hash table, reinitialize
2431 * the hash secrets.
2432 */
2433 if (syn_cache_count == 0) {
2434 struct timeval tv;
2435 microtime(&tv);
2436 syn_hash1 = random() ^ (u_long)≻
2437 syn_hash2 = random() ^ tv.tv_usec;
2438 }
2439
2440 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
2441 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
2442 scp = &tcp_syn_cache[sc->sc_bucketidx];
2443
2444 /*
2445 * Make sure that we don't overflow the per-bucket
2446 * limit or the total cache size limit.
2447 */
2448 s = splsoftnet();
2449 if (scp->sch_length >= tcp_syn_bucket_limit) {
2450 tcpstat.tcps_sc_bucketoverflow++;
2451 /*
2452 * The bucket is full. Toss the oldest element in the
2453 * bucket. This will be the entry with our bucket
2454 * index closest to the front of the timer queue with
2455 * the largest timeout value.
2456 *
2457 * Note: This timer queue traversal may be expensive, so
2458 * we hope that this doesn't happen very often. It is
2459 * much more likely that we'll overflow the entire
2460 * cache, which is much easier to handle; see below.
2461 */
2462 for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2463 for (sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2464 sc2 != NULL;
2465 sc2 = TAILQ_NEXT(sc2, sc_timeq)) {
2466 if (sc2->sc_bucketidx == sc->sc_bucketidx) {
2467 SYN_CACHE_RM(sc2);
2468 SYN_CACHE_PUT(sc2);
2469 goto insert; /* 2 level break */
2470 }
2471 }
2472 }
2473 #ifdef DIAGNOSTIC
2474 /*
2475 * This should never happen; we should always find an
2476 * entry in our bucket.
2477 */
2478 panic("syn_cache_insert: bucketoverflow: impossible");
2479 #endif
2480 } else if (syn_cache_count >= tcp_syn_cache_limit) {
2481 tcpstat.tcps_sc_overflowed++;
2482 /*
2483 * The cache is full. Toss the oldest entry in the
2484 * entire cache. This is the front entry in the
2485 * first non-empty timer queue with the largest
2486 * timeout value.
2487 */
2488 for (i = TCP_MAXRXTSHIFT; i >= 0; i--) {
2489 sc2 = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2490 if (sc2 == NULL)
2491 continue;
2492 SYN_CACHE_RM(sc2);
2493 SYN_CACHE_PUT(sc2);
2494 goto insert; /* symmetry with above */
2495 }
2496 #ifdef DIAGNOSTIC
2497 /*
2498 * This should never happen; we should always find an
2499 * entry in the cache.
2500 */
2501 panic("syn_cache_insert: cache overflow: impossible");
2502 #endif
2503 }
2504
2505 insert:
2506 /*
2507 * Initialize the entry's timer.
2508 */
2509 sc->sc_rxttot = 0;
2510 sc->sc_rxtshift = 0;
2511 SYN_CACHE_TIMER_ARM(sc);
2512 TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift], sc, sc_timeq);
2513
2514 /* Link it from tcpcb entry */
2515 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
2516
2517 /* Put it into the bucket. */
2518 LIST_INSERT_HEAD(&scp->sch_bucket, sc, sc_bucketq);
2519 scp->sch_length++;
2520 syn_cache_count++;
2521
2522 tcpstat.tcps_sc_added++;
2523 splx(s);
2524 }
2525
2526 /*
2527 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
2528 * If we have retransmitted an entry the maximum number of times, expire
2529 * that entry.
2530 */
2531 void
2532 syn_cache_timer()
2533 {
2534 struct syn_cache *sc, *nsc;
2535 int i, s;
2536
2537 s = splsoftnet();
2538
2539 /*
2540 * First, get all the entries that need to be retransmitted, or
2541 * must be expired due to exceeding the initial keepalive time.
2542 */
2543 for (i = 0; i < TCP_MAXRXTSHIFT; i++) {
2544 for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[i]);
2545 sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2546 sc = nsc) {
2547 nsc = TAILQ_NEXT(sc, sc_timeq);
2548
2549 /*
2550 * Compute the total amount of time this entry has
2551 * been on a queue. If this entry has been on longer
2552 * than the keep alive timer would allow, expire it.
2553 */
2554 sc->sc_rxttot += sc->sc_rxtcur;
2555 if (sc->sc_rxttot >= TCPTV_KEEP_INIT) {
2556 tcpstat.tcps_sc_timed_out++;
2557 SYN_CACHE_RM(sc);
2558 SYN_CACHE_PUT(sc);
2559 continue;
2560 }
2561
2562 tcpstat.tcps_sc_retransmitted++;
2563 (void) syn_cache_respond(sc, NULL);
2564
2565 /* Advance this entry onto the next timer queue. */
2566 TAILQ_REMOVE(&tcp_syn_cache_timeq[i], sc, sc_timeq);
2567 sc->sc_rxtshift = i + 1;
2568 SYN_CACHE_TIMER_ARM(sc);
2569 TAILQ_INSERT_TAIL(&tcp_syn_cache_timeq[sc->sc_rxtshift],
2570 sc, sc_timeq);
2571 }
2572 }
2573
2574 /*
2575 * Now get all the entries that are expired due to too many
2576 * retransmissions.
2577 */
2578 for (sc = TAILQ_FIRST(&tcp_syn_cache_timeq[TCP_MAXRXTSHIFT]);
2579 sc != NULL && PRT_SLOW_ISEXPIRED(sc->sc_rexmt);
2580 sc = nsc) {
2581 nsc = TAILQ_NEXT(sc, sc_timeq);
2582 tcpstat.tcps_sc_timed_out++;
2583 SYN_CACHE_RM(sc);
2584 SYN_CACHE_PUT(sc);
2585 }
2586 splx(s);
2587 }
2588
2589 /*
2590 * Remove syn cache created by the specified tcb entry,
2591 * because this does not make sense to keep them
2592 * (if there's no tcb entry, syn cache entry will never be used)
2593 */
2594 void
2595 syn_cache_cleanup(tp)
2596 struct tcpcb *tp;
2597 {
2598 struct syn_cache *sc, *nsc;
2599 int s;
2600
2601 s = splsoftnet();
2602
2603 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
2604 nsc = LIST_NEXT(sc, sc_tpq);
2605
2606 #ifdef DIAGNOSTIC
2607 if (sc->sc_tp != tp)
2608 panic("invalid sc_tp in syn_cache_cleanup");
2609 #endif
2610 SYN_CACHE_RM(sc);
2611 SYN_CACHE_PUT(sc);
2612 }
2613 /* just for safety */
2614 LIST_INIT(&tp->t_sc);
2615
2616 splx(s);
2617 }
2618
2619 /*
2620 * Find an entry in the syn cache.
2621 */
2622 struct syn_cache *
2623 syn_cache_lookup(src, dst, headp)
2624 struct sockaddr *src;
2625 struct sockaddr *dst;
2626 struct syn_cache_head **headp;
2627 {
2628 struct syn_cache *sc;
2629 struct syn_cache_head *scp;
2630 u_int32_t hash;
2631 int s;
2632
2633 SYN_HASHALL(hash, src, dst);
2634
2635 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
2636 *headp = scp;
2637 s = splsoftnet();
2638 for (sc = LIST_FIRST(&scp->sch_bucket); sc != NULL;
2639 sc = LIST_NEXT(sc, sc_bucketq)) {
2640 if (sc->sc_hash != hash)
2641 continue;
2642 if (!bcmp(&sc->sc_src, src, src->sa_len) &&
2643 !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
2644 splx(s);
2645 return (sc);
2646 }
2647 }
2648 splx(s);
2649 return (NULL);
2650 }
2651
2652 /*
2653 * This function gets called when we receive an ACK for a
2654 * socket in the LISTEN state. We look up the connection
2655 * in the syn cache, and if its there, we pull it out of
2656 * the cache and turn it into a full-blown connection in
2657 * the SYN-RECEIVED state.
2658 *
2659 * The return values may not be immediately obvious, and their effects
2660 * can be subtle, so here they are:
2661 *
2662 * NULL SYN was not found in cache; caller should drop the
2663 * packet and send an RST.
2664 *
2665 * -1 We were unable to create the new connection, and are
2666 * aborting it. An ACK,RST is being sent to the peer
2667 * (unless we got screwey sequence numbners; see below),
2668 * because the 3-way handshake has been completed. Caller
2669 * should not free the mbuf, since we may be using it. If
2670 * we are not, we will free it.
2671 *
2672 * Otherwise, the return value is a pointer to the new socket
2673 * associated with the connection.
2674 */
2675 struct socket *
2676 syn_cache_get(src, dst, th, hlen, tlen, so, m)
2677 struct sockaddr *src;
2678 struct sockaddr *dst;
2679 struct tcphdr *th;
2680 unsigned int hlen, tlen;
2681 struct socket *so;
2682 struct mbuf *m;
2683 {
2684 struct syn_cache *sc;
2685 struct syn_cache_head *scp;
2686 register struct inpcb *inp = NULL;
2687 #ifdef INET6
2688 register struct in6pcb *in6p = NULL;
2689 #endif
2690 register struct tcpcb *tp = 0;
2691 struct mbuf *am;
2692 int s;
2693 struct socket *oso;
2694
2695 s = splsoftnet();
2696 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2697 splx(s);
2698 return (NULL);
2699 }
2700
2701 /*
2702 * Verify the sequence and ack numbers. Try getting the correct
2703 * response again.
2704 */
2705 if ((th->th_ack != sc->sc_iss + 1) ||
2706 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
2707 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
2708 (void) syn_cache_respond(sc, m);
2709 splx(s);
2710 return ((struct socket *)(-1));
2711 }
2712
2713 /* Remove this cache entry */
2714 SYN_CACHE_RM(sc);
2715 splx(s);
2716
2717 /*
2718 * Ok, create the full blown connection, and set things up
2719 * as they would have been set up if we had created the
2720 * connection when the SYN arrived. If we can't create
2721 * the connection, abort it.
2722 */
2723 /*
2724 * inp still has the OLD in_pcb stuff, set the
2725 * v6-related flags on the new guy, too. This is
2726 * done particularly for the case where an AF_INET6
2727 * socket is bound only to a port, and a v4 connection
2728 * comes in on that port.
2729 * we also copy the flowinfo from the original pcb
2730 * to the new one.
2731 */
2732 {
2733 struct inpcb *parentinpcb;
2734
2735 parentinpcb = (struct inpcb *)so->so_pcb;
2736
2737 oso = so;
2738 so = sonewconn(so, SS_ISCONNECTED);
2739 if (so == NULL)
2740 goto resetandabort;
2741
2742 switch (so->so_proto->pr_domain->dom_family) {
2743 case AF_INET:
2744 inp = sotoinpcb(so);
2745 break;
2746 #ifdef INET6
2747 case AF_INET6:
2748 in6p = sotoin6pcb(so);
2749 #if 0 /*def INET6*/
2750 inp->inp_flags |= (parentinpcb->inp_flags &
2751 (INP_IPV6 | INP_IPV6_UNDEC | INP_IPV6_MAPPED));
2752 if ((inp->inp_flags & INP_IPV6) &&
2753 !(inp->inp_flags & INP_IPV6_MAPPED)) {
2754 inp->inp_ipv6.ip6_hlim = parentinpcb->inp_ipv6.ip6_hlim;
2755 inp->inp_ipv6.ip6_vfc = parentinpcb->inp_ipv6.ip6_vfc;
2756 }
2757 #endif
2758 break;
2759 #endif
2760 }
2761 }
2762 switch (src->sa_family) {
2763 case AF_INET:
2764 if (inp) {
2765 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
2766 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
2767 inp->inp_options = ip_srcroute();
2768 in_pcbstate(inp, INP_BOUND);
2769 if (inp->inp_options == NULL) {
2770 inp->inp_options = sc->sc_ipopts;
2771 sc->sc_ipopts = NULL;
2772 }
2773 }
2774 #ifdef INET6
2775 else if (in6p) {
2776 /* IPv4 packet to AF_INET6 socket */
2777 bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
2778 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
2779 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
2780 &in6p->in6p_laddr.s6_addr32[3],
2781 sizeof(((struct sockaddr_in *)dst)->sin_addr));
2782 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
2783 in6totcpcb(in6p)->t_family = AF_INET;
2784 }
2785 #endif
2786 break;
2787 #ifdef INET6
2788 case AF_INET6:
2789 if (in6p) {
2790 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
2791 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
2792 #if 0
2793 in6p->in6p_flowinfo = ip6->ip6_flow & IPV6_FLOWINFO_MASK;
2794 /*inp->inp_options = ip6_srcroute();*/ /* soon. */
2795 #endif
2796 }
2797 break;
2798 #endif
2799 }
2800 #ifdef INET6
2801 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
2802 struct in6pcb *oin6p = sotoin6pcb(oso);
2803 /* inherit socket options from the listening socket */
2804 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
2805 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
2806 m_freem(in6p->in6p_options);
2807 in6p->in6p_options = 0;
2808 }
2809 ip6_savecontrol(in6p, &in6p->in6p_options,
2810 mtod(m, struct ip6_hdr *), m);
2811 }
2812 #endif
2813
2814 #ifdef IPSEC
2815 {
2816 struct secpolicy *sp;
2817 if (inp) {
2818 sp = ipsec_copy_policy(sotoinpcb(oso)->inp_sp);
2819 if (sp) {
2820 key_freesp(inp->inp_sp);
2821 inp->inp_sp = sp;
2822 } else
2823 printf("tcp_input: could not copy policy\n");
2824 }
2825 #ifdef INET6
2826 else if (in6p) {
2827 sp = ipsec_copy_policy(sotoin6pcb(oso)->in6p_sp);
2828 if (sp) {
2829 key_freesp(in6p->in6p_sp);
2830 in6p->in6p_sp = sp;
2831 } else
2832 printf("tcp_input: could not copy policy\n");
2833 }
2834 #endif
2835 }
2836 #endif
2837
2838 /*
2839 * Give the new socket our cached route reference.
2840 */
2841 if (inp)
2842 inp->inp_route = sc->sc_route4; /* struct assignment */
2843 #ifdef INET6
2844 else
2845 in6p->in6p_route = sc->sc_route6;
2846 #endif
2847 sc->sc_route4.ro_rt = NULL;
2848
2849 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
2850 if (am == NULL)
2851 goto resetandabort;
2852 am->m_len = src->sa_len;
2853 bcopy(src, mtod(am, caddr_t), src->sa_len);
2854 if (inp) {
2855 if (in_pcbconnect(inp, am)) {
2856 (void) m_free(am);
2857 goto resetandabort;
2858 }
2859 }
2860 #ifdef INET6
2861 else if (in6p) {
2862 if (src->sa_family == AF_INET) {
2863 /* IPv4 packet to AF_INET6 socket */
2864 struct sockaddr_in6 *sin6;
2865 sin6 = mtod(am, struct sockaddr_in6 *);
2866 am->m_len = sizeof(*sin6);
2867 bzero(sin6, sizeof(*sin6));
2868 sin6->sin6_family = AF_INET6;
2869 sin6->sin6_len = sizeof(*sin6);
2870 sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
2871 sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
2872 bcopy(&((struct sockaddr_in *)src)->sin_addr,
2873 &sin6->sin6_addr.s6_addr32[3],
2874 sizeof(sin6->sin6_addr.s6_addr32[3]));
2875 }
2876 if (in6_pcbconnect(in6p, am)) {
2877 (void) m_free(am);
2878 goto resetandabort;
2879 }
2880 }
2881 #endif
2882 else {
2883 (void) m_free(am);
2884 goto resetandabort;
2885 }
2886 (void) m_free(am);
2887
2888 if (inp)
2889 tp = intotcpcb(inp);
2890 #ifdef INET6
2891 else if (in6p)
2892 tp = in6totcpcb(in6p);
2893 #endif
2894 else
2895 tp = NULL;
2896 if (sc->sc_request_r_scale != 15) {
2897 tp->requested_s_scale = sc->sc_requested_s_scale;
2898 tp->request_r_scale = sc->sc_request_r_scale;
2899 tp->snd_scale = sc->sc_requested_s_scale;
2900 tp->rcv_scale = sc->sc_request_r_scale;
2901 tp->t_flags |= TF_RCVD_SCALE;
2902 }
2903 if (sc->sc_flags & SCF_TIMESTAMP)
2904 tp->t_flags |= TF_RCVD_TSTMP;
2905
2906 tp->t_template = tcp_template(tp);
2907 if (tp->t_template == 0) {
2908 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
2909 so = NULL;
2910 m_freem(m);
2911 goto abort;
2912 }
2913
2914 tp->iss = sc->sc_iss;
2915 tp->irs = sc->sc_irs;
2916 tcp_sendseqinit(tp);
2917 tcp_rcvseqinit(tp);
2918 tp->t_state = TCPS_SYN_RECEIVED;
2919 TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
2920 tcpstat.tcps_accepts++;
2921
2922 /* Initialize tp->t_ourmss before we deal with the peer's! */
2923 tp->t_ourmss = sc->sc_ourmaxseg;
2924 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
2925
2926 /*
2927 * Initialize the initial congestion window. If we
2928 * had to retransmit the SYN,ACK, we must initialize cwnd
2929 * to 1 segment (i.e. the Loss Window).
2930 */
2931 if (sc->sc_rxtshift)
2932 tp->snd_cwnd = tp->t_peermss;
2933 else
2934 tp->snd_cwnd = TCP_INITIAL_WINDOW(tcp_init_win, tp->t_peermss);
2935
2936 tcp_rmx_rtt(tp);
2937 tp->snd_wl1 = sc->sc_irs;
2938 tp->rcv_up = sc->sc_irs + 1;
2939
2940 /*
2941 * This is what whould have happened in tcp_ouput() when
2942 * the SYN,ACK was sent.
2943 */
2944 tp->snd_up = tp->snd_una;
2945 tp->snd_max = tp->snd_nxt = tp->iss+1;
2946 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2947 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
2948 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
2949 tp->last_ack_sent = tp->rcv_nxt;
2950
2951 tcpstat.tcps_sc_completed++;
2952 SYN_CACHE_PUT(sc);
2953 return (so);
2954
2955 resetandabort:
2956 (void) tcp_respond(NULL, m, m, th,
2957 th->th_seq + tlen, (tcp_seq)0, TH_RST|TH_ACK);
2958 abort:
2959 if (so != NULL)
2960 (void) soabort(so);
2961 SYN_CACHE_PUT(sc);
2962 tcpstat.tcps_sc_aborted++;
2963 return ((struct socket *)(-1));
2964 }
2965
2966 /*
2967 * This function is called when we get a RST for a
2968 * non-existant connection, so that we can see if the
2969 * connection is in the syn cache. If it is, zap it.
2970 */
2971
2972 void
2973 syn_cache_reset(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 = splsoftnet();
2981
2982 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
2983 splx(s);
2984 return;
2985 }
2986 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
2987 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
2988 splx(s);
2989 return;
2990 }
2991 SYN_CACHE_RM(sc);
2992 splx(s);
2993 tcpstat.tcps_sc_reset++;
2994 SYN_CACHE_PUT(sc);
2995 }
2996
2997 void
2998 syn_cache_unreach(src, dst, th)
2999 struct sockaddr *src;
3000 struct sockaddr *dst;
3001 struct tcphdr *th;
3002 {
3003 struct syn_cache *sc;
3004 struct syn_cache_head *scp;
3005 int s;
3006
3007 s = splsoftnet();
3008 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3009 splx(s);
3010 return;
3011 }
3012 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
3013 if (ntohl (th->th_seq) != sc->sc_iss) {
3014 splx(s);
3015 return;
3016 }
3017
3018 /*
3019 * If we've rertransmitted 3 times and this is our second error,
3020 * we remove the entry. Otherwise, we allow it to continue on.
3021 * This prevents us from incorrectly nuking an entry during a
3022 * spurious network outage.
3023 *
3024 * See tcp_notify().
3025 */
3026 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
3027 sc->sc_flags |= SCF_UNREACH;
3028 splx(s);
3029 return;
3030 }
3031
3032 SYN_CACHE_RM(sc);
3033 splx(s);
3034 tcpstat.tcps_sc_unreach++;
3035 SYN_CACHE_PUT(sc);
3036 }
3037
3038 /*
3039 * Given a LISTEN socket and an inbound SYN request, add
3040 * this to the syn cache, and send back a segment:
3041 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3042 * to the source.
3043 *
3044 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3045 * Doing so would require that we hold onto the data and deliver it
3046 * to the application. However, if we are the target of a SYN-flood
3047 * DoS attack, an attacker could send data which would eventually
3048 * consume all available buffer space if it were ACKed. By not ACKing
3049 * the data, we avoid this DoS scenario.
3050 */
3051
3052 int
3053 syn_cache_add(src, dst, th, hlen, so, m, optp, optlen, oi)
3054 struct sockaddr *src;
3055 struct sockaddr *dst;
3056 struct tcphdr *th;
3057 unsigned int hlen;
3058 struct socket *so;
3059 struct mbuf *m;
3060 u_char *optp;
3061 int optlen;
3062 struct tcp_opt_info *oi;
3063 {
3064 struct tcpcb tb, *tp;
3065 long win;
3066 struct syn_cache *sc;
3067 struct syn_cache_head *scp;
3068 struct mbuf *ipopts;
3069
3070 tp = sototcpcb(so);
3071
3072 /*
3073 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3074 * in_broadcast() should never return true on a received
3075 * packet with M_BCAST not set.
3076 */
3077 if (m->m_flags & (M_BCAST|M_MCAST))
3078 return 0;
3079 #ifdef INET6
3080 if (m->m_flags & M_ANYCAST6)
3081 return 0;
3082 #endif
3083
3084 switch (src->sa_family) {
3085 case AF_INET:
3086 if (IN_MULTICAST(((struct sockaddr_in *)src)->sin_addr.s_addr)
3087 || IN_MULTICAST(((struct sockaddr_in *)dst)->sin_addr.s_addr))
3088 return 0;
3089 break;
3090 #ifdef INET6
3091 case AF_INET6:
3092 if (IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)src)->sin6_addr)
3093 || IN6_IS_ADDR_MULTICAST(&((struct sockaddr_in6 *)dst)->sin6_addr))
3094 return 0;
3095 break;
3096 #endif
3097 default:
3098 return 0;
3099 }
3100
3101 /*
3102 * Initialize some local state.
3103 */
3104 win = sbspace(&so->so_rcv);
3105 if (win > TCP_MAXWIN)
3106 win = TCP_MAXWIN;
3107
3108 if (src->sa_family == AF_INET) {
3109 /*
3110 * Remember the IP options, if any.
3111 */
3112 ipopts = ip_srcroute();
3113 } else
3114 ipopts = NULL;
3115
3116 if (optp) {
3117 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
3118 tcp_dooptions(&tb, optp, optlen, th, oi);
3119 } else
3120 tb.t_flags = 0;
3121
3122 /*
3123 * See if we already have an entry for this connection.
3124 * If we do, resend the SYN,ACK. We do not count this
3125 * as a retransmission (XXX though maybe we should).
3126 */
3127 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
3128 tcpstat.tcps_sc_dupesyn++;
3129 if (ipopts) {
3130 /*
3131 * If we were remembering a previous source route,
3132 * forget it and use the new one we've been given.
3133 */
3134 if (sc->sc_ipopts)
3135 (void) m_free(sc->sc_ipopts);
3136 sc->sc_ipopts = ipopts;
3137 }
3138 sc->sc_timestamp = tb.ts_recent;
3139 if (syn_cache_respond(sc, m) == 0) {
3140 tcpstat.tcps_sndacks++;
3141 tcpstat.tcps_sndtotal++;
3142 }
3143 return (1);
3144 }
3145
3146 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
3147 if (sc == NULL) {
3148 if (ipopts)
3149 (void) m_free(ipopts);
3150 return (0);
3151 }
3152
3153 /*
3154 * Fill in the cache, and put the necessary IP and TCP
3155 * options into the reply.
3156 */
3157 bzero(sc, sizeof(struct syn_cache));
3158 bcopy(src, &sc->sc_src, src->sa_len);
3159 bcopy(dst, &sc->sc_dst, dst->sa_len);
3160 sc->sc_flags = 0;
3161 sc->sc_ipopts = ipopts;
3162 sc->sc_irs = th->th_seq;
3163 sc->sc_iss = tcp_new_iss(sc, sizeof(struct syn_cache), 0);
3164 sc->sc_peermaxseg = oi->maxseg;
3165 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
3166 m->m_pkthdr.rcvif : NULL,
3167 sc->sc_src.sa.sa_family);
3168 sc->sc_win = win;
3169 sc->sc_timestamp = tb.ts_recent;
3170 if (tcp_do_rfc1323 && (tb.t_flags & TF_RCVD_TSTMP))
3171 sc->sc_flags |= SCF_TIMESTAMP;
3172 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
3173 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
3174 sc->sc_requested_s_scale = tb.requested_s_scale;
3175 sc->sc_request_r_scale = 0;
3176 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
3177 TCP_MAXWIN << sc->sc_request_r_scale <
3178 so->so_rcv.sb_hiwat)
3179 sc->sc_request_r_scale++;
3180 } else {
3181 sc->sc_requested_s_scale = 15;
3182 sc->sc_request_r_scale = 15;
3183 }
3184 sc->sc_tp = tp;
3185 if (syn_cache_respond(sc, m) == 0) {
3186 syn_cache_insert(sc, tp);
3187 tcpstat.tcps_sndacks++;
3188 tcpstat.tcps_sndtotal++;
3189 } else {
3190 SYN_CACHE_PUT(sc);
3191 tcpstat.tcps_sc_dropped++;
3192 }
3193 return (1);
3194 }
3195
3196 int
3197 syn_cache_respond(sc, m)
3198 struct syn_cache *sc;
3199 struct mbuf *m;
3200 {
3201 struct route *ro;
3202 struct rtentry *rt;
3203 u_int8_t *optp;
3204 int optlen, error;
3205 u_int16_t tlen;
3206 struct ip *ip = NULL;
3207 #ifdef INET6
3208 struct ip6_hdr *ip6 = NULL;
3209 #endif
3210 struct tcphdr *th;
3211 u_int hlen;
3212
3213 switch (sc->sc_src.sa.sa_family) {
3214 case AF_INET:
3215 hlen = sizeof(struct ip);
3216 ro = &sc->sc_route4;
3217 break;
3218 #ifdef INET6
3219 case AF_INET6:
3220 hlen = sizeof(struct ip6_hdr);
3221 ro = (struct route *)&sc->sc_route6;
3222 break;
3223 #endif
3224 default:
3225 if (m)
3226 m_freem(m);
3227 return EAFNOSUPPORT;
3228 }
3229
3230 /* Compute the size of the TCP options. */
3231 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
3232 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
3233
3234 tlen = hlen + sizeof(struct tcphdr) + optlen;
3235
3236 /*
3237 * Create the IP+TCP header from scratch. Reuse the received mbuf
3238 * if possible.
3239 */
3240 if (m != NULL) {
3241 m_freem(m->m_next);
3242 m->m_next = NULL;
3243 MRESETDATA(m);
3244 } else {
3245 MGETHDR(m, M_DONTWAIT, MT_DATA);
3246 if (m == NULL)
3247 return (ENOBUFS);
3248 }
3249
3250 /* Fixup the mbuf. */
3251 m->m_data += max_linkhdr;
3252 m->m_len = m->m_pkthdr.len = tlen;
3253 #ifdef IPSEC
3254 if (sc->sc_tp) {
3255 struct tcpcb *tp;
3256 struct socket *so;
3257
3258 tp = sc->sc_tp;
3259 if (tp->t_inpcb)
3260 so = tp->t_inpcb->inp_socket;
3261 #ifdef INET6
3262 else if (tp->t_in6pcb)
3263 so = tp->t_in6pcb->in6p_socket;
3264 #endif
3265 else
3266 so = NULL;
3267 /* use IPsec policy on listening socket, on SYN ACK */
3268 m->m_pkthdr.rcvif = (struct ifnet *)so;
3269 }
3270 #else
3271 m->m_pkthdr.rcvif = NULL;
3272 #endif
3273 memset(mtod(m, u_char *), 0, tlen);
3274
3275 switch (sc->sc_src.sa.sa_family) {
3276 case AF_INET:
3277 ip = mtod(m, struct ip *);
3278 ip->ip_dst = sc->sc_src.sin.sin_addr;
3279 ip->ip_src = sc->sc_dst.sin.sin_addr;
3280 ip->ip_p = IPPROTO_TCP;
3281 th = (struct tcphdr *)(ip + 1);
3282 th->th_dport = sc->sc_src.sin.sin_port;
3283 th->th_sport = sc->sc_dst.sin.sin_port;
3284 break;
3285 #ifdef INET6
3286 case AF_INET6:
3287 ip6 = mtod(m, struct ip6_hdr *);
3288 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
3289 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
3290 ip6->ip6_nxt = IPPROTO_TCP;
3291 /* ip6_plen will be updated in ip6_output() */
3292 th = (struct tcphdr *)(ip6 + 1);
3293 th->th_dport = sc->sc_src.sin6.sin6_port;
3294 th->th_sport = sc->sc_dst.sin6.sin6_port;
3295 break;
3296 #endif
3297 default:
3298 th = NULL;
3299 }
3300
3301 th->th_seq = htonl(sc->sc_iss);
3302 th->th_ack = htonl(sc->sc_irs + 1);
3303 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
3304 th->th_flags = TH_SYN|TH_ACK;
3305 th->th_win = htons(sc->sc_win);
3306 /* th_sum already 0 */
3307 /* th_urp already 0 */
3308
3309 /* Tack on the TCP options. */
3310 optp = (u_int8_t *)(th + 1);
3311 *optp++ = TCPOPT_MAXSEG;
3312 *optp++ = 4;
3313 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
3314 *optp++ = sc->sc_ourmaxseg & 0xff;
3315
3316 if (sc->sc_request_r_scale != 15) {
3317 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
3318 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
3319 sc->sc_request_r_scale);
3320 optp += 4;
3321 }
3322
3323 if (sc->sc_flags & SCF_TIMESTAMP) {
3324 u_int32_t *lp = (u_int32_t *)(optp);
3325 /* Form timestamp option as shown in appendix A of RFC 1323. */
3326 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
3327 *lp++ = htonl(tcp_now);
3328 *lp = htonl(sc->sc_timestamp);
3329 optp += TCPOLEN_TSTAMP_APPA;
3330 }
3331
3332 /* Compute the packet's checksum. */
3333 switch (sc->sc_src.sa.sa_family) {
3334 case AF_INET:
3335 ip->ip_len = htons(tlen - hlen);
3336 th->th_sum = 0;
3337 th->th_sum = in_cksum(m, tlen);
3338 break;
3339 #ifdef INET6
3340 case AF_INET6:
3341 ip6->ip6_plen = htons(tlen - hlen);
3342 th->th_sum = 0;
3343 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
3344 break;
3345 #endif
3346 }
3347
3348 /*
3349 * Fill in some straggling IP bits. Note the stack expects
3350 * ip_len to be in host order, for convenience.
3351 */
3352 switch (sc->sc_src.sa.sa_family) {
3353 case AF_INET:
3354 ip->ip_len = tlen;
3355 ip->ip_ttl = ip_defttl;
3356 /* XXX tos? */
3357 break;
3358 #ifdef INET6
3359 case AF_INET6:
3360 ip6->ip6_vfc = IPV6_VERSION;
3361 ip6->ip6_plen = htons(tlen - hlen);
3362 ip6->ip6_hlim = ip6_defhlim;
3363 /* XXX flowlabel? */
3364 break;
3365 #endif
3366 }
3367
3368 /*
3369 * If we're doing Path MTU discovery, we need to set DF unless
3370 * the route's MTU is locked. If we don't yet know the route,
3371 * look it up now. We will copy this reference to the inpcb
3372 * when we finish creating the connection.
3373 */
3374 if ((rt = ro->ro_rt) == NULL || (rt->rt_flags & RTF_UP) == 0) {
3375 if (ro->ro_rt != NULL) {
3376 RTFREE(ro->ro_rt);
3377 ro->ro_rt = NULL;
3378 }
3379 bcopy(&sc->sc_src, &ro->ro_dst, sc->sc_src.sa.sa_len);
3380 rtalloc(ro);
3381 if ((rt = ro->ro_rt) == NULL) {
3382 m_freem(m);
3383 switch (sc->sc_src.sa.sa_family) {
3384 case AF_INET:
3385 ipstat.ips_noroute++;
3386 break;
3387 #ifdef INET6
3388 case AF_INET6:
3389 ip6stat.ip6s_noroute++;
3390 break;
3391 #endif
3392 }
3393 return (EHOSTUNREACH);
3394 }
3395 }
3396
3397 switch (sc->sc_src.sa.sa_family) {
3398 case AF_INET:
3399 if (ip_mtudisc != 0 && (rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
3400 ip->ip_off |= IP_DF;
3401
3402 /* ...and send it off! */
3403 error = ip_output(m, sc->sc_ipopts, ro, 0, NULL);
3404 break;
3405 #ifdef INET6
3406 case AF_INET6:
3407 error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro,
3408 0, NULL);
3409 break;
3410 #endif
3411 default:
3412 error = EAFNOSUPPORT;
3413 break;
3414 }
3415 return (error);
3416 }
3417