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