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