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