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