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