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