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