tcp_input.c revision 1.346 1 /* $NetBSD: tcp_input.c,v 1.346 2016/06/10 13:27:16 ozaki-r 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, 2005, 2006,
74 * 2011 The NetBSD Foundation, Inc.
75 * All rights reserved.
76 *
77 * This code is derived from software contributed to The NetBSD Foundation
78 * by Coyote Point Systems, Inc.
79 * This code is derived from software contributed to The NetBSD Foundation
80 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
81 * Facility, NASA Ames Research Center.
82 * This code is derived from software contributed to The NetBSD Foundation
83 * by Charles M. Hannum.
84 * This code is derived from software contributed to The NetBSD Foundation
85 * by Rui Paulo.
86 *
87 * Redistribution and use in source and binary forms, with or without
88 * modification, are permitted provided that the following conditions
89 * are met:
90 * 1. Redistributions of source code must retain the above copyright
91 * notice, this list of conditions and the following disclaimer.
92 * 2. Redistributions in binary form must reproduce the above copyright
93 * notice, this list of conditions and the following disclaimer in the
94 * documentation and/or other materials provided with the distribution.
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.346 2016/06/10 13:27:16 ozaki-r Exp $");
152
153 #ifdef _KERNEL_OPT
154 #include "opt_inet.h"
155 #include "opt_ipsec.h"
156 #include "opt_inet_csum.h"
157 #include "opt_tcp_debug.h"
158 #endif
159
160 #include <sys/param.h>
161 #include <sys/systm.h>
162 #include <sys/malloc.h>
163 #include <sys/mbuf.h>
164 #include <sys/protosw.h>
165 #include <sys/socket.h>
166 #include <sys/socketvar.h>
167 #include <sys/errno.h>
168 #include <sys/syslog.h>
169 #include <sys/pool.h>
170 #include <sys/domain.h>
171 #include <sys/kernel.h>
172 #ifdef TCP_SIGNATURE
173 #include <sys/md5.h>
174 #endif
175 #include <sys/lwp.h> /* for lwp0 */
176 #include <sys/cprng.h>
177
178 #include <net/if.h>
179 #include <net/if_types.h>
180
181 #include <netinet/in.h>
182 #include <netinet/in_systm.h>
183 #include <netinet/ip.h>
184 #include <netinet/in_pcb.h>
185 #include <netinet/in_var.h>
186 #include <netinet/ip_var.h>
187 #include <netinet/in_offload.h>
188
189 #ifdef INET6
190 #ifndef INET
191 #include <netinet/in.h>
192 #endif
193 #include <netinet/ip6.h>
194 #include <netinet6/ip6_var.h>
195 #include <netinet6/in6_pcb.h>
196 #include <netinet6/ip6_var.h>
197 #include <netinet6/in6_var.h>
198 #include <netinet/icmp6.h>
199 #include <netinet6/nd6.h>
200 #ifdef TCP_SIGNATURE
201 #include <netinet6/scope6_var.h>
202 #endif
203 #endif
204
205 #ifndef INET6
206 /* always need ip6.h for IP6_EXTHDR_GET */
207 #include <netinet/ip6.h>
208 #endif
209
210 #include <netinet/tcp.h>
211 #include <netinet/tcp_fsm.h>
212 #include <netinet/tcp_seq.h>
213 #include <netinet/tcp_timer.h>
214 #include <netinet/tcp_var.h>
215 #include <netinet/tcp_private.h>
216 #include <netinet/tcpip.h>
217 #include <netinet/tcp_congctl.h>
218 #include <netinet/tcp_debug.h>
219
220 #ifdef INET6
221 #include "faith.h"
222 #if defined(NFAITH) && NFAITH > 0
223 #include <net/if_faith.h>
224 #endif
225 #endif /* INET6 */
226
227 #ifdef IPSEC
228 #include <netipsec/ipsec.h>
229 #include <netipsec/ipsec_var.h>
230 #include <netipsec/ipsec_private.h>
231 #include <netipsec/key.h>
232 #ifdef INET6
233 #include <netipsec/ipsec6.h>
234 #endif
235 #endif /* IPSEC*/
236
237 #include <netinet/tcp_vtw.h>
238
239 int tcprexmtthresh = 3;
240 int tcp_log_refused;
241
242 int tcp_do_autorcvbuf = 1;
243 int tcp_autorcvbuf_inc = 16 * 1024;
244 int tcp_autorcvbuf_max = 256 * 1024;
245 int tcp_msl = (TCPTV_MSL / PR_SLOWHZ);
246
247 static int tcp_rst_ppslim_count = 0;
248 static struct timeval tcp_rst_ppslim_last;
249 static int tcp_ackdrop_ppslim_count = 0;
250 static struct timeval tcp_ackdrop_ppslim_last;
251
252 #define TCP_PAWS_IDLE (24U * 24 * 60 * 60 * PR_SLOWHZ)
253
254 /* for modulo comparisons of timestamps */
255 #define TSTMP_LT(a,b) ((int)((a)-(b)) < 0)
256 #define TSTMP_GEQ(a,b) ((int)((a)-(b)) >= 0)
257
258 /*
259 * Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint.
260 */
261 #ifdef INET6
262 static inline void
263 nd6_hint(struct tcpcb *tp)
264 {
265 struct rtentry *rt;
266
267 if (tp != NULL && tp->t_in6pcb != NULL && tp->t_family == AF_INET6 &&
268 (rt = rtcache_validate(&tp->t_in6pcb->in6p_route)) != NULL)
269 nd6_nud_hint(rt);
270 }
271 #else
272 static inline void
273 nd6_hint(struct tcpcb *tp)
274 {
275 }
276 #endif
277
278 /*
279 * Compute ACK transmission behavior. Delay the ACK unless
280 * we have already delayed an ACK (must send an ACK every two segments).
281 * We also ACK immediately if we received a PUSH and the ACK-on-PUSH
282 * option is enabled.
283 */
284 static void
285 tcp_setup_ack(struct tcpcb *tp, const struct tcphdr *th)
286 {
287
288 if (tp->t_flags & TF_DELACK ||
289 (tcp_ack_on_push && th->th_flags & TH_PUSH))
290 tp->t_flags |= TF_ACKNOW;
291 else
292 TCP_SET_DELACK(tp);
293 }
294
295 static void
296 icmp_check(struct tcpcb *tp, const struct tcphdr *th, int acked)
297 {
298
299 /*
300 * If we had a pending ICMP message that refers to data that have
301 * just been acknowledged, disregard the recorded ICMP message.
302 */
303 if ((tp->t_flags & TF_PMTUD_PEND) &&
304 SEQ_GT(th->th_ack, tp->t_pmtud_th_seq))
305 tp->t_flags &= ~TF_PMTUD_PEND;
306
307 /*
308 * Keep track of the largest chunk of data
309 * acknowledged since last PMTU update
310 */
311 if (tp->t_pmtud_mss_acked < acked)
312 tp->t_pmtud_mss_acked = acked;
313 }
314
315 /*
316 * Convert TCP protocol fields to host order for easier processing.
317 */
318 static void
319 tcp_fields_to_host(struct tcphdr *th)
320 {
321
322 NTOHL(th->th_seq);
323 NTOHL(th->th_ack);
324 NTOHS(th->th_win);
325 NTOHS(th->th_urp);
326 }
327
328 /*
329 * ... and reverse the above.
330 */
331 static void
332 tcp_fields_to_net(struct tcphdr *th)
333 {
334
335 HTONL(th->th_seq);
336 HTONL(th->th_ack);
337 HTONS(th->th_win);
338 HTONS(th->th_urp);
339 }
340
341 #ifdef TCP_CSUM_COUNTERS
342 #include <sys/device.h>
343
344 #if defined(INET)
345 extern struct evcnt tcp_hwcsum_ok;
346 extern struct evcnt tcp_hwcsum_bad;
347 extern struct evcnt tcp_hwcsum_data;
348 extern struct evcnt tcp_swcsum;
349 #endif /* defined(INET) */
350 #if defined(INET6)
351 extern struct evcnt tcp6_hwcsum_ok;
352 extern struct evcnt tcp6_hwcsum_bad;
353 extern struct evcnt tcp6_hwcsum_data;
354 extern struct evcnt tcp6_swcsum;
355 #endif /* defined(INET6) */
356
357 #define TCP_CSUM_COUNTER_INCR(ev) (ev)->ev_count++
358
359 #else
360
361 #define TCP_CSUM_COUNTER_INCR(ev) /* nothing */
362
363 #endif /* TCP_CSUM_COUNTERS */
364
365 #ifdef TCP_REASS_COUNTERS
366 #include <sys/device.h>
367
368 extern struct evcnt tcp_reass_;
369 extern struct evcnt tcp_reass_empty;
370 extern struct evcnt tcp_reass_iteration[8];
371 extern struct evcnt tcp_reass_prependfirst;
372 extern struct evcnt tcp_reass_prepend;
373 extern struct evcnt tcp_reass_insert;
374 extern struct evcnt tcp_reass_inserttail;
375 extern struct evcnt tcp_reass_append;
376 extern struct evcnt tcp_reass_appendtail;
377 extern struct evcnt tcp_reass_overlaptail;
378 extern struct evcnt tcp_reass_overlapfront;
379 extern struct evcnt tcp_reass_segdup;
380 extern struct evcnt tcp_reass_fragdup;
381
382 #define TCP_REASS_COUNTER_INCR(ev) (ev)->ev_count++
383
384 #else
385
386 #define TCP_REASS_COUNTER_INCR(ev) /* nothing */
387
388 #endif /* TCP_REASS_COUNTERS */
389
390 static int tcp_reass(struct tcpcb *, const struct tcphdr *, struct mbuf *,
391 int *);
392 static int tcp_dooptions(struct tcpcb *, const u_char *, int,
393 struct tcphdr *, struct mbuf *, int, struct tcp_opt_info *);
394
395 #ifdef INET
396 static void tcp4_log_refused(const struct ip *, const struct tcphdr *);
397 #endif
398 #ifdef INET6
399 static void tcp6_log_refused(const struct ip6_hdr *, const struct tcphdr *);
400 #endif
401
402 #define TRAVERSE(x) while ((x)->m_next) (x) = (x)->m_next
403
404 #if defined(MBUFTRACE)
405 struct mowner tcp_reass_mowner = MOWNER_INIT("tcp", "reass");
406 #endif /* defined(MBUFTRACE) */
407
408 static struct pool tcpipqent_pool;
409
410 void
411 tcpipqent_init(void)
412 {
413
414 pool_init(&tcpipqent_pool, sizeof(struct ipqent), 0, 0, 0, "tcpipqepl",
415 NULL, IPL_VM);
416 }
417
418 struct ipqent *
419 tcpipqent_alloc(void)
420 {
421 struct ipqent *ipqe;
422 int s;
423
424 s = splvm();
425 ipqe = pool_get(&tcpipqent_pool, PR_NOWAIT);
426 splx(s);
427
428 return ipqe;
429 }
430
431 void
432 tcpipqent_free(struct ipqent *ipqe)
433 {
434 int s;
435
436 s = splvm();
437 pool_put(&tcpipqent_pool, ipqe);
438 splx(s);
439 }
440
441 static int
442 tcp_reass(struct tcpcb *tp, const struct tcphdr *th, struct mbuf *m, int *tlen)
443 {
444 struct ipqent *p, *q, *nq, *tiqe = NULL;
445 struct socket *so = NULL;
446 int pkt_flags;
447 tcp_seq pkt_seq;
448 unsigned pkt_len;
449 u_long rcvpartdupbyte = 0;
450 u_long rcvoobyte;
451 #ifdef TCP_REASS_COUNTERS
452 u_int count = 0;
453 #endif
454 uint64_t *tcps;
455
456 if (tp->t_inpcb)
457 so = tp->t_inpcb->inp_socket;
458 #ifdef INET6
459 else if (tp->t_in6pcb)
460 so = tp->t_in6pcb->in6p_socket;
461 #endif
462
463 TCP_REASS_LOCK_CHECK(tp);
464
465 /*
466 * Call with th==0 after become established to
467 * force pre-ESTABLISHED data up to user socket.
468 */
469 if (th == 0)
470 goto present;
471
472 m_claimm(m, &tcp_reass_mowner);
473
474 rcvoobyte = *tlen;
475 /*
476 * Copy these to local variables because the tcpiphdr
477 * gets munged while we are collapsing mbufs.
478 */
479 pkt_seq = th->th_seq;
480 pkt_len = *tlen;
481 pkt_flags = th->th_flags;
482
483 TCP_REASS_COUNTER_INCR(&tcp_reass_);
484
485 if ((p = TAILQ_LAST(&tp->segq, ipqehead)) != NULL) {
486 /*
487 * When we miss a packet, the vast majority of time we get
488 * packets that follow it in order. So optimize for that.
489 */
490 if (pkt_seq == p->ipqe_seq + p->ipqe_len) {
491 p->ipqe_len += pkt_len;
492 p->ipqe_flags |= pkt_flags;
493 m_cat(p->ipre_mlast, m);
494 TRAVERSE(p->ipre_mlast);
495 m = NULL;
496 tiqe = p;
497 TAILQ_REMOVE(&tp->timeq, p, ipqe_timeq);
498 TCP_REASS_COUNTER_INCR(&tcp_reass_appendtail);
499 goto skip_replacement;
500 }
501 /*
502 * While we're here, if the pkt is completely beyond
503 * anything we have, just insert it at the tail.
504 */
505 if (SEQ_GT(pkt_seq, p->ipqe_seq + p->ipqe_len)) {
506 TCP_REASS_COUNTER_INCR(&tcp_reass_inserttail);
507 goto insert_it;
508 }
509 }
510
511 q = TAILQ_FIRST(&tp->segq);
512
513 if (q != NULL) {
514 /*
515 * If this segment immediately precedes the first out-of-order
516 * block, simply slap the segment in front of it and (mostly)
517 * skip the complicated logic.
518 */
519 if (pkt_seq + pkt_len == q->ipqe_seq) {
520 q->ipqe_seq = pkt_seq;
521 q->ipqe_len += pkt_len;
522 q->ipqe_flags |= pkt_flags;
523 m_cat(m, q->ipqe_m);
524 q->ipqe_m = m;
525 q->ipre_mlast = m; /* last mbuf may have changed */
526 TRAVERSE(q->ipre_mlast);
527 tiqe = q;
528 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
529 TCP_REASS_COUNTER_INCR(&tcp_reass_prependfirst);
530 goto skip_replacement;
531 }
532 } else {
533 TCP_REASS_COUNTER_INCR(&tcp_reass_empty);
534 }
535
536 /*
537 * Find a segment which begins after this one does.
538 */
539 for (p = NULL; q != NULL; q = nq) {
540 nq = TAILQ_NEXT(q, ipqe_q);
541 #ifdef TCP_REASS_COUNTERS
542 count++;
543 #endif
544 /*
545 * If the received segment is just right after this
546 * fragment, merge the two together and then check
547 * for further overlaps.
548 */
549 if (q->ipqe_seq + q->ipqe_len == pkt_seq) {
550 #ifdef TCPREASS_DEBUG
551 printf("tcp_reass[%p]: concat %u:%u(%u) to %u:%u(%u)\n",
552 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
553 q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len);
554 #endif
555 pkt_len += q->ipqe_len;
556 pkt_flags |= q->ipqe_flags;
557 pkt_seq = q->ipqe_seq;
558 m_cat(q->ipre_mlast, m);
559 TRAVERSE(q->ipre_mlast);
560 m = q->ipqe_m;
561 TCP_REASS_COUNTER_INCR(&tcp_reass_append);
562 goto free_ipqe;
563 }
564 /*
565 * If the received segment is completely past this
566 * fragment, we need to go the next fragment.
567 */
568 if (SEQ_LT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
569 p = q;
570 continue;
571 }
572 /*
573 * If the fragment is past the received segment,
574 * it (or any following) can't be concatenated.
575 */
576 if (SEQ_GT(q->ipqe_seq, pkt_seq + pkt_len)) {
577 TCP_REASS_COUNTER_INCR(&tcp_reass_insert);
578 break;
579 }
580
581 /*
582 * We've received all the data in this segment before.
583 * mark it as a duplicate and return.
584 */
585 if (SEQ_LEQ(q->ipqe_seq, pkt_seq) &&
586 SEQ_GEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
587 tcps = TCP_STAT_GETREF();
588 tcps[TCP_STAT_RCVDUPPACK]++;
589 tcps[TCP_STAT_RCVDUPBYTE] += pkt_len;
590 TCP_STAT_PUTREF();
591 tcp_new_dsack(tp, pkt_seq, pkt_len);
592 m_freem(m);
593 if (tiqe != NULL) {
594 tcpipqent_free(tiqe);
595 }
596 TCP_REASS_COUNTER_INCR(&tcp_reass_segdup);
597 goto out;
598 }
599 /*
600 * Received segment completely overlaps this fragment
601 * so we drop the fragment (this keeps the temporal
602 * ordering of segments correct).
603 */
604 if (SEQ_GEQ(q->ipqe_seq, pkt_seq) &&
605 SEQ_LEQ(q->ipqe_seq + q->ipqe_len, pkt_seq + pkt_len)) {
606 rcvpartdupbyte += q->ipqe_len;
607 m_freem(q->ipqe_m);
608 TCP_REASS_COUNTER_INCR(&tcp_reass_fragdup);
609 goto free_ipqe;
610 }
611 /*
612 * RX'ed segment extends past the end of the
613 * fragment. Drop the overlapping bytes. Then
614 * merge the fragment and segment then treat as
615 * a longer received packet.
616 */
617 if (SEQ_LT(q->ipqe_seq, pkt_seq) &&
618 SEQ_GT(q->ipqe_seq + q->ipqe_len, pkt_seq)) {
619 int overlap = q->ipqe_seq + q->ipqe_len - pkt_seq;
620 #ifdef TCPREASS_DEBUG
621 printf("tcp_reass[%p]: trim starting %d bytes of %u:%u(%u)\n",
622 tp, overlap,
623 pkt_seq, pkt_seq + pkt_len, pkt_len);
624 #endif
625 m_adj(m, overlap);
626 rcvpartdupbyte += overlap;
627 m_cat(q->ipre_mlast, m);
628 TRAVERSE(q->ipre_mlast);
629 m = q->ipqe_m;
630 pkt_seq = q->ipqe_seq;
631 pkt_len += q->ipqe_len - overlap;
632 rcvoobyte -= overlap;
633 TCP_REASS_COUNTER_INCR(&tcp_reass_overlaptail);
634 goto free_ipqe;
635 }
636 /*
637 * RX'ed segment extends past the front of the
638 * fragment. Drop the overlapping bytes on the
639 * received packet. The packet will then be
640 * contatentated with this fragment a bit later.
641 */
642 if (SEQ_GT(q->ipqe_seq, pkt_seq) &&
643 SEQ_LT(q->ipqe_seq, pkt_seq + pkt_len)) {
644 int overlap = pkt_seq + pkt_len - q->ipqe_seq;
645 #ifdef TCPREASS_DEBUG
646 printf("tcp_reass[%p]: trim trailing %d bytes of %u:%u(%u)\n",
647 tp, overlap,
648 pkt_seq, pkt_seq + pkt_len, pkt_len);
649 #endif
650 m_adj(m, -overlap);
651 pkt_len -= overlap;
652 rcvpartdupbyte += overlap;
653 TCP_REASS_COUNTER_INCR(&tcp_reass_overlapfront);
654 rcvoobyte -= overlap;
655 }
656 /*
657 * If the received segment immediates precedes this
658 * fragment then tack the fragment onto this segment
659 * and reinsert the data.
660 */
661 if (q->ipqe_seq == pkt_seq + pkt_len) {
662 #ifdef TCPREASS_DEBUG
663 printf("tcp_reass[%p]: append %u:%u(%u) to %u:%u(%u)\n",
664 tp, q->ipqe_seq, q->ipqe_seq + q->ipqe_len, q->ipqe_len,
665 pkt_seq, pkt_seq + pkt_len, pkt_len);
666 #endif
667 pkt_len += q->ipqe_len;
668 pkt_flags |= q->ipqe_flags;
669 m_cat(m, q->ipqe_m);
670 TAILQ_REMOVE(&tp->segq, q, ipqe_q);
671 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
672 tp->t_segqlen--;
673 KASSERT(tp->t_segqlen >= 0);
674 KASSERT(tp->t_segqlen != 0 ||
675 (TAILQ_EMPTY(&tp->segq) &&
676 TAILQ_EMPTY(&tp->timeq)));
677 if (tiqe == NULL) {
678 tiqe = q;
679 } else {
680 tcpipqent_free(q);
681 }
682 TCP_REASS_COUNTER_INCR(&tcp_reass_prepend);
683 break;
684 }
685 /*
686 * If the fragment is before the segment, remember it.
687 * When this loop is terminated, p will contain the
688 * pointer to fragment that is right before the received
689 * segment.
690 */
691 if (SEQ_LEQ(q->ipqe_seq, pkt_seq))
692 p = q;
693
694 continue;
695
696 /*
697 * This is a common operation. It also will allow
698 * to save doing a malloc/free in most instances.
699 */
700 free_ipqe:
701 TAILQ_REMOVE(&tp->segq, q, ipqe_q);
702 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
703 tp->t_segqlen--;
704 KASSERT(tp->t_segqlen >= 0);
705 KASSERT(tp->t_segqlen != 0 ||
706 (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
707 if (tiqe == NULL) {
708 tiqe = q;
709 } else {
710 tcpipqent_free(q);
711 }
712 }
713
714 #ifdef TCP_REASS_COUNTERS
715 if (count > 7)
716 TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[0]);
717 else if (count > 0)
718 TCP_REASS_COUNTER_INCR(&tcp_reass_iteration[count]);
719 #endif
720
721 insert_it:
722
723 /*
724 * Allocate a new queue entry since the received segment did not
725 * collapse onto any other out-of-order block; thus we are allocating
726 * a new block. If it had collapsed, tiqe would not be NULL and
727 * we would be reusing it.
728 * XXX If we can't, just drop the packet. XXX
729 */
730 if (tiqe == NULL) {
731 tiqe = tcpipqent_alloc();
732 if (tiqe == NULL) {
733 TCP_STATINC(TCP_STAT_RCVMEMDROP);
734 m_freem(m);
735 goto out;
736 }
737 }
738
739 /*
740 * Update the counters.
741 */
742 tp->t_rcvoopack++;
743 tcps = TCP_STAT_GETREF();
744 tcps[TCP_STAT_RCVOOPACK]++;
745 tcps[TCP_STAT_RCVOOBYTE] += rcvoobyte;
746 if (rcvpartdupbyte) {
747 tcps[TCP_STAT_RCVPARTDUPPACK]++;
748 tcps[TCP_STAT_RCVPARTDUPBYTE] += rcvpartdupbyte;
749 }
750 TCP_STAT_PUTREF();
751
752 /*
753 * Insert the new fragment queue entry into both queues.
754 */
755 tiqe->ipqe_m = m;
756 tiqe->ipre_mlast = m;
757 tiqe->ipqe_seq = pkt_seq;
758 tiqe->ipqe_len = pkt_len;
759 tiqe->ipqe_flags = pkt_flags;
760 if (p == NULL) {
761 TAILQ_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
762 #ifdef TCPREASS_DEBUG
763 if (tiqe->ipqe_seq != tp->rcv_nxt)
764 printf("tcp_reass[%p]: insert %u:%u(%u) at front\n",
765 tp, pkt_seq, pkt_seq + pkt_len, pkt_len);
766 #endif
767 } else {
768 TAILQ_INSERT_AFTER(&tp->segq, p, tiqe, ipqe_q);
769 #ifdef TCPREASS_DEBUG
770 printf("tcp_reass[%p]: insert %u:%u(%u) after %u:%u(%u)\n",
771 tp, pkt_seq, pkt_seq + pkt_len, pkt_len,
772 p->ipqe_seq, p->ipqe_seq + p->ipqe_len, p->ipqe_len);
773 #endif
774 }
775 tp->t_segqlen++;
776
777 skip_replacement:
778
779 TAILQ_INSERT_HEAD(&tp->timeq, tiqe, ipqe_timeq);
780
781 present:
782 /*
783 * Present data to user, advancing rcv_nxt through
784 * completed sequence space.
785 */
786 if (TCPS_HAVEESTABLISHED(tp->t_state) == 0)
787 goto out;
788 q = TAILQ_FIRST(&tp->segq);
789 if (q == NULL || q->ipqe_seq != tp->rcv_nxt)
790 goto out;
791 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_len)
792 goto out;
793
794 tp->rcv_nxt += q->ipqe_len;
795 pkt_flags = q->ipqe_flags & TH_FIN;
796 nd6_hint(tp);
797
798 TAILQ_REMOVE(&tp->segq, q, ipqe_q);
799 TAILQ_REMOVE(&tp->timeq, q, ipqe_timeq);
800 tp->t_segqlen--;
801 KASSERT(tp->t_segqlen >= 0);
802 KASSERT(tp->t_segqlen != 0 ||
803 (TAILQ_EMPTY(&tp->segq) && TAILQ_EMPTY(&tp->timeq)));
804 if (so->so_state & SS_CANTRCVMORE)
805 m_freem(q->ipqe_m);
806 else
807 sbappendstream(&so->so_rcv, q->ipqe_m);
808 tcpipqent_free(q);
809 TCP_REASS_UNLOCK(tp);
810 sorwakeup(so);
811 return (pkt_flags);
812 out:
813 TCP_REASS_UNLOCK(tp);
814 return (0);
815 }
816
817 #ifdef INET6
818 int
819 tcp6_input(struct mbuf **mp, int *offp, int proto)
820 {
821 struct mbuf *m = *mp;
822
823 /*
824 * draft-itojun-ipv6-tcp-to-anycast
825 * better place to put this in?
826 */
827 if (m->m_flags & M_ANYCAST6) {
828 struct ip6_hdr *ip6;
829 if (m->m_len < sizeof(struct ip6_hdr)) {
830 if ((m = m_pullup(m, sizeof(struct ip6_hdr))) == NULL) {
831 TCP_STATINC(TCP_STAT_RCVSHORT);
832 return IPPROTO_DONE;
833 }
834 }
835 ip6 = mtod(m, struct ip6_hdr *);
836 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
837 (char *)&ip6->ip6_dst - (char *)ip6);
838 return IPPROTO_DONE;
839 }
840
841 tcp_input(m, *offp, proto);
842 return IPPROTO_DONE;
843 }
844 #endif
845
846 #ifdef INET
847 static void
848 tcp4_log_refused(const struct ip *ip, const struct tcphdr *th)
849 {
850 char src[INET_ADDRSTRLEN];
851 char dst[INET_ADDRSTRLEN];
852
853 if (ip) {
854 in_print(src, sizeof(src), &ip->ip_src);
855 in_print(dst, sizeof(dst), &ip->ip_dst);
856 }
857 else {
858 strlcpy(src, "(unknown)", sizeof(src));
859 strlcpy(dst, "(unknown)", sizeof(dst));
860 }
861 log(LOG_INFO,
862 "Connection attempt to TCP %s:%d from %s:%d\n",
863 dst, ntohs(th->th_dport),
864 src, ntohs(th->th_sport));
865 }
866 #endif
867
868 #ifdef INET6
869 static void
870 tcp6_log_refused(const struct ip6_hdr *ip6, const struct tcphdr *th)
871 {
872 char src[INET6_ADDRSTRLEN];
873 char dst[INET6_ADDRSTRLEN];
874
875 if (ip6) {
876 in6_print(src, sizeof(src), &ip6->ip6_src);
877 in6_print(dst, sizeof(dst), &ip6->ip6_dst);
878 }
879 else {
880 strlcpy(src, "(unknown v6)", sizeof(src));
881 strlcpy(dst, "(unknown v6)", sizeof(dst));
882 }
883 log(LOG_INFO,
884 "Connection attempt to TCP [%s]:%d from [%s]:%d\n",
885 dst, ntohs(th->th_dport),
886 src, ntohs(th->th_sport));
887 }
888 #endif
889
890 /*
891 * Checksum extended TCP header and data.
892 */
893 int
894 tcp_input_checksum(int af, struct mbuf *m, const struct tcphdr *th,
895 int toff, int off, int tlen)
896 {
897
898 /*
899 * XXX it's better to record and check if this mbuf is
900 * already checked.
901 */
902
903 switch (af) {
904 #ifdef INET
905 case AF_INET:
906 switch (m->m_pkthdr.csum_flags &
907 ((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv4) |
908 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
909 case M_CSUM_TCPv4|M_CSUM_TCP_UDP_BAD:
910 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_bad);
911 goto badcsum;
912
913 case M_CSUM_TCPv4|M_CSUM_DATA: {
914 u_int32_t hw_csum = m->m_pkthdr.csum_data;
915
916 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_data);
917 if (m->m_pkthdr.csum_flags & M_CSUM_NO_PSEUDOHDR) {
918 const struct ip *ip =
919 mtod(m, const struct ip *);
920
921 hw_csum = in_cksum_phdr(ip->ip_src.s_addr,
922 ip->ip_dst.s_addr,
923 htons(hw_csum + tlen + off + IPPROTO_TCP));
924 }
925 if ((hw_csum ^ 0xffff) != 0)
926 goto badcsum;
927 break;
928 }
929
930 case M_CSUM_TCPv4:
931 /* Checksum was okay. */
932 TCP_CSUM_COUNTER_INCR(&tcp_hwcsum_ok);
933 break;
934
935 default:
936 /*
937 * Must compute it ourselves. Maybe skip checksum
938 * on loopback interfaces.
939 */
940 if (__predict_true(!(m->m_pkthdr.rcvif->if_flags &
941 IFF_LOOPBACK) ||
942 tcp_do_loopback_cksum)) {
943 TCP_CSUM_COUNTER_INCR(&tcp_swcsum);
944 if (in4_cksum(m, IPPROTO_TCP, toff,
945 tlen + off) != 0)
946 goto badcsum;
947 }
948 break;
949 }
950 break;
951 #endif /* INET4 */
952
953 #ifdef INET6
954 case AF_INET6:
955 switch (m->m_pkthdr.csum_flags &
956 ((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_TCPv6) |
957 M_CSUM_TCP_UDP_BAD | M_CSUM_DATA)) {
958 case M_CSUM_TCPv6|M_CSUM_TCP_UDP_BAD:
959 TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_bad);
960 goto badcsum;
961
962 #if 0 /* notyet */
963 case M_CSUM_TCPv6|M_CSUM_DATA:
964 #endif
965
966 case M_CSUM_TCPv6:
967 /* Checksum was okay. */
968 TCP_CSUM_COUNTER_INCR(&tcp6_hwcsum_ok);
969 break;
970
971 default:
972 /*
973 * Must compute it ourselves. Maybe skip checksum
974 * on loopback interfaces.
975 */
976 if (__predict_true((m->m_flags & M_LOOP) == 0 ||
977 tcp_do_loopback_cksum)) {
978 TCP_CSUM_COUNTER_INCR(&tcp6_swcsum);
979 if (in6_cksum(m, IPPROTO_TCP, toff,
980 tlen + off) != 0)
981 goto badcsum;
982 }
983 }
984 break;
985 #endif /* INET6 */
986 }
987
988 return 0;
989
990 badcsum:
991 TCP_STATINC(TCP_STAT_RCVBADSUM);
992 return -1;
993 }
994
995 /* When a packet arrives addressed to a vestigial tcpbp, we
996 * nevertheless have to respond to it per the spec.
997 */
998 static void tcp_vtw_input(struct tcphdr *th, vestigial_inpcb_t *vp,
999 struct mbuf *m, int tlen, int multicast)
1000 {
1001 int tiflags;
1002 int todrop;
1003 uint32_t t_flags = 0;
1004 uint64_t *tcps;
1005
1006 tiflags = th->th_flags;
1007 todrop = vp->rcv_nxt - th->th_seq;
1008
1009 if (todrop > 0) {
1010 if (tiflags & TH_SYN) {
1011 tiflags &= ~TH_SYN;
1012 ++th->th_seq;
1013 if (th->th_urp > 1)
1014 --th->th_urp;
1015 else {
1016 tiflags &= ~TH_URG;
1017 th->th_urp = 0;
1018 }
1019 --todrop;
1020 }
1021 if (todrop > tlen ||
1022 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
1023 /*
1024 * Any valid FIN or RST must be to the left of the
1025 * window. At this point the FIN or RST must be a
1026 * duplicate or out of sequence; drop it.
1027 */
1028 if (tiflags & TH_RST)
1029 goto drop;
1030 tiflags &= ~(TH_FIN|TH_RST);
1031 /*
1032 * Send an ACK to resynchronize and drop any data.
1033 * But keep on processing for RST or ACK.
1034 */
1035 t_flags |= TF_ACKNOW;
1036 todrop = tlen;
1037 tcps = TCP_STAT_GETREF();
1038 tcps[TCP_STAT_RCVDUPPACK] += 1;
1039 tcps[TCP_STAT_RCVDUPBYTE] += todrop;
1040 TCP_STAT_PUTREF();
1041 } else if ((tiflags & TH_RST)
1042 && th->th_seq != vp->rcv_nxt) {
1043 /*
1044 * Test for reset before adjusting the sequence
1045 * number for overlapping data.
1046 */
1047 goto dropafterack_ratelim;
1048 } else {
1049 tcps = TCP_STAT_GETREF();
1050 tcps[TCP_STAT_RCVPARTDUPPACK] += 1;
1051 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
1052 TCP_STAT_PUTREF();
1053 }
1054
1055 // tcp_new_dsack(tp, th->th_seq, todrop);
1056 // hdroptlen += todrop; /*drop from head afterwards*/
1057
1058 th->th_seq += todrop;
1059 tlen -= todrop;
1060
1061 if (th->th_urp > todrop)
1062 th->th_urp -= todrop;
1063 else {
1064 tiflags &= ~TH_URG;
1065 th->th_urp = 0;
1066 }
1067 }
1068
1069 /*
1070 * If new data are received on a connection after the
1071 * user processes are gone, then RST the other end.
1072 */
1073 if (tlen) {
1074 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
1075 goto dropwithreset;
1076 }
1077
1078 /*
1079 * If segment ends after window, drop trailing data
1080 * (and PUSH and FIN); if nothing left, just ACK.
1081 */
1082 todrop = (th->th_seq + tlen) - (vp->rcv_nxt+vp->rcv_wnd);
1083
1084 if (todrop > 0) {
1085 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
1086 if (todrop >= tlen) {
1087 /*
1088 * The segment actually starts after the window.
1089 * th->th_seq + tlen - vp->rcv_nxt - vp->rcv_wnd >= tlen
1090 * th->th_seq - vp->rcv_nxt - vp->rcv_wnd >= 0
1091 * th->th_seq >= vp->rcv_nxt + vp->rcv_wnd
1092 */
1093 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
1094 /*
1095 * If a new connection request is received
1096 * while in TIME_WAIT, drop the old connection
1097 * and start over if the sequence numbers
1098 * are above the previous ones.
1099 */
1100 if ((tiflags & TH_SYN)
1101 && SEQ_GT(th->th_seq, vp->rcv_nxt)) {
1102 /* We only support this in the !NOFDREF case, which
1103 * is to say: not here.
1104 */
1105 goto dropwithreset;
1106 }
1107 /*
1108 * If window is closed can only take segments at
1109 * window edge, and have to drop data and PUSH from
1110 * incoming segments. Continue processing, but
1111 * remember to ack. Otherwise, drop segment
1112 * and (if not RST) ack.
1113 */
1114 if (vp->rcv_wnd == 0 && th->th_seq == vp->rcv_nxt) {
1115 t_flags |= TF_ACKNOW;
1116 TCP_STATINC(TCP_STAT_RCVWINPROBE);
1117 } else
1118 goto dropafterack;
1119 } else
1120 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
1121 m_adj(m, -todrop);
1122 tlen -= todrop;
1123 tiflags &= ~(TH_PUSH|TH_FIN);
1124 }
1125
1126 if (tiflags & TH_RST) {
1127 if (th->th_seq != vp->rcv_nxt)
1128 goto dropafterack_ratelim;
1129
1130 vtw_del(vp->ctl, vp->vtw);
1131 goto drop;
1132 }
1133
1134 /*
1135 * If the ACK bit is off we drop the segment and return.
1136 */
1137 if ((tiflags & TH_ACK) == 0) {
1138 if (t_flags & TF_ACKNOW)
1139 goto dropafterack;
1140 else
1141 goto drop;
1142 }
1143
1144 /*
1145 * In TIME_WAIT state the only thing that should arrive
1146 * is a retransmission of the remote FIN. Acknowledge
1147 * it and restart the finack timer.
1148 */
1149 vtw_restart(vp);
1150 goto dropafterack;
1151
1152 dropafterack:
1153 /*
1154 * Generate an ACK dropping incoming segment if it occupies
1155 * sequence space, where the ACK reflects our state.
1156 */
1157 if (tiflags & TH_RST)
1158 goto drop;
1159 goto dropafterack2;
1160
1161 dropafterack_ratelim:
1162 /*
1163 * We may want to rate-limit ACKs against SYN/RST attack.
1164 */
1165 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
1166 tcp_ackdrop_ppslim) == 0) {
1167 /* XXX stat */
1168 goto drop;
1169 }
1170 /* ...fall into dropafterack2... */
1171
1172 dropafterack2:
1173 (void)tcp_respond(0, m, m, th, th->th_seq + tlen, th->th_ack,
1174 TH_ACK);
1175 return;
1176
1177 dropwithreset:
1178 /*
1179 * Generate a RST, dropping incoming segment.
1180 * Make ACK acceptable to originator of segment.
1181 */
1182 if (tiflags & TH_RST)
1183 goto drop;
1184
1185 if (tiflags & TH_ACK)
1186 tcp_respond(0, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
1187 else {
1188 if (tiflags & TH_SYN)
1189 ++tlen;
1190 (void)tcp_respond(0, m, m, th, th->th_seq + tlen, (tcp_seq)0,
1191 TH_RST|TH_ACK);
1192 }
1193 return;
1194 drop:
1195 m_freem(m);
1196 }
1197
1198 /*
1199 * TCP input routine, follows pages 65-76 of RFC 793 very closely.
1200 */
1201 void
1202 tcp_input(struct mbuf *m, ...)
1203 {
1204 struct tcphdr *th;
1205 struct ip *ip;
1206 struct inpcb *inp;
1207 #ifdef INET6
1208 struct ip6_hdr *ip6;
1209 struct in6pcb *in6p;
1210 #endif
1211 u_int8_t *optp = NULL;
1212 int optlen = 0;
1213 int len, tlen, toff, hdroptlen = 0;
1214 struct tcpcb *tp = 0;
1215 int tiflags;
1216 struct socket *so = NULL;
1217 int todrop, acked, ourfinisacked, needoutput = 0;
1218 bool dupseg;
1219 #ifdef TCP_DEBUG
1220 short ostate = 0;
1221 #endif
1222 u_long tiwin;
1223 struct tcp_opt_info opti;
1224 int off, iphlen;
1225 va_list ap;
1226 int af; /* af on the wire */
1227 struct mbuf *tcp_saveti = NULL;
1228 uint32_t ts_rtt;
1229 uint8_t iptos;
1230 uint64_t *tcps;
1231 vestigial_inpcb_t vestige;
1232
1233 vestige.valid = 0;
1234
1235 MCLAIM(m, &tcp_rx_mowner);
1236 va_start(ap, m);
1237 toff = va_arg(ap, int);
1238 (void)va_arg(ap, int); /* ignore value, advance ap */
1239 va_end(ap);
1240
1241 TCP_STATINC(TCP_STAT_RCVTOTAL);
1242
1243 memset(&opti, 0, sizeof(opti));
1244 opti.ts_present = 0;
1245 opti.maxseg = 0;
1246
1247 /*
1248 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
1249 *
1250 * TCP is, by definition, unicast, so we reject all
1251 * multicast outright.
1252 *
1253 * Note, there are additional src/dst address checks in
1254 * the AF-specific code below.
1255 */
1256 if (m->m_flags & (M_BCAST|M_MCAST)) {
1257 /* XXX stat */
1258 goto drop;
1259 }
1260 #ifdef INET6
1261 if (m->m_flags & M_ANYCAST6) {
1262 /* XXX stat */
1263 goto drop;
1264 }
1265 #endif
1266
1267 /*
1268 * Get IP and TCP header.
1269 * Note: IP leaves IP header in first mbuf.
1270 */
1271 ip = mtod(m, struct ip *);
1272 switch (ip->ip_v) {
1273 #ifdef INET
1274 case 4:
1275 #ifdef INET6
1276 ip6 = NULL;
1277 #endif
1278 af = AF_INET;
1279 iphlen = sizeof(struct ip);
1280 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
1281 sizeof(struct tcphdr));
1282 if (th == NULL) {
1283 TCP_STATINC(TCP_STAT_RCVSHORT);
1284 return;
1285 }
1286 /* We do the checksum after PCB lookup... */
1287 len = ntohs(ip->ip_len);
1288 tlen = len - toff;
1289 iptos = ip->ip_tos;
1290 break;
1291 #endif
1292 #ifdef INET6
1293 case 6:
1294 ip = NULL;
1295 iphlen = sizeof(struct ip6_hdr);
1296 af = AF_INET6;
1297 ip6 = mtod(m, struct ip6_hdr *);
1298 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff,
1299 sizeof(struct tcphdr));
1300 if (th == NULL) {
1301 TCP_STATINC(TCP_STAT_RCVSHORT);
1302 return;
1303 }
1304
1305 /* Be proactive about malicious use of IPv4 mapped address */
1306 if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
1307 IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
1308 /* XXX stat */
1309 goto drop;
1310 }
1311
1312 /*
1313 * Be proactive about unspecified IPv6 address in source.
1314 * As we use all-zero to indicate unbounded/unconnected pcb,
1315 * unspecified IPv6 address can be used to confuse us.
1316 *
1317 * Note that packets with unspecified IPv6 destination is
1318 * already dropped in ip6_input.
1319 */
1320 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1321 /* XXX stat */
1322 goto drop;
1323 }
1324
1325 /*
1326 * Make sure destination address is not multicast.
1327 * Source address checked in ip6_input().
1328 */
1329 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1330 /* XXX stat */
1331 goto drop;
1332 }
1333
1334 /* We do the checksum after PCB lookup... */
1335 len = m->m_pkthdr.len;
1336 tlen = len - toff;
1337 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1338 break;
1339 #endif
1340 default:
1341 m_freem(m);
1342 return;
1343 }
1344
1345 KASSERT(TCP_HDR_ALIGNED_P(th));
1346
1347 /*
1348 * Check that TCP offset makes sense,
1349 * pull out TCP options and adjust length. XXX
1350 */
1351 off = th->th_off << 2;
1352 if (off < sizeof (struct tcphdr) || off > tlen) {
1353 TCP_STATINC(TCP_STAT_RCVBADOFF);
1354 goto drop;
1355 }
1356 tlen -= off;
1357
1358 /*
1359 * tcp_input() has been modified to use tlen to mean the TCP data
1360 * length throughout the function. Other functions can use
1361 * m->m_pkthdr.len as the basis for calculating the TCP data length.
1362 * rja
1363 */
1364
1365 if (off > sizeof (struct tcphdr)) {
1366 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
1367 if (th == NULL) {
1368 TCP_STATINC(TCP_STAT_RCVSHORT);
1369 return;
1370 }
1371 /*
1372 * NOTE: ip/ip6 will not be affected by m_pulldown()
1373 * (as they're before toff) and we don't need to update those.
1374 */
1375 KASSERT(TCP_HDR_ALIGNED_P(th));
1376 optlen = off - sizeof (struct tcphdr);
1377 optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1378 /*
1379 * Do quick retrieval of timestamp options ("options
1380 * prediction?"). If timestamp is the only option and it's
1381 * formatted as recommended in RFC 1323 appendix A, we
1382 * quickly get the values now and not bother calling
1383 * tcp_dooptions(), etc.
1384 */
1385 if ((optlen == TCPOLEN_TSTAMP_APPA ||
1386 (optlen > TCPOLEN_TSTAMP_APPA &&
1387 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1388 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1389 (th->th_flags & TH_SYN) == 0) {
1390 opti.ts_present = 1;
1391 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1392 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1393 optp = NULL; /* we've parsed the options */
1394 }
1395 }
1396 tiflags = th->th_flags;
1397
1398 /*
1399 * Checksum extended TCP header and data
1400 */
1401 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1402 goto badcsum;
1403
1404 /*
1405 * Locate pcb for segment.
1406 */
1407 findpcb:
1408 inp = NULL;
1409 #ifdef INET6
1410 in6p = NULL;
1411 #endif
1412 switch (af) {
1413 #ifdef INET
1414 case AF_INET:
1415 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1416 ip->ip_dst, th->th_dport,
1417 &vestige);
1418 if (inp == 0 && !vestige.valid) {
1419 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1420 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst, th->th_dport);
1421 }
1422 #ifdef INET6
1423 if (inp == 0 && !vestige.valid) {
1424 struct in6_addr s, d;
1425
1426 /* mapped addr case */
1427 in6_in_2_v4mapin6(&ip->ip_src, &s);
1428 in6_in_2_v4mapin6(&ip->ip_dst, &d);
1429 in6p = in6_pcblookup_connect(&tcbtable, &s,
1430 th->th_sport, &d, th->th_dport,
1431 0, &vestige);
1432 if (in6p == 0 && !vestige.valid) {
1433 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1434 in6p = in6_pcblookup_bind(&tcbtable, &d,
1435 th->th_dport, 0);
1436 }
1437 }
1438 #endif
1439 #ifndef INET6
1440 if (inp == 0 && !vestige.valid)
1441 #else
1442 if (inp == 0 && in6p == 0 && !vestige.valid)
1443 #endif
1444 {
1445 TCP_STATINC(TCP_STAT_NOPORT);
1446 if (tcp_log_refused &&
1447 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1448 tcp4_log_refused(ip, th);
1449 }
1450 tcp_fields_to_host(th);
1451 goto dropwithreset_ratelim;
1452 }
1453 #if defined(IPSEC)
1454 if (ipsec_used) {
1455 if (inp &&
1456 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0
1457 && ipsec4_in_reject(m, inp)) {
1458 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1459 goto drop;
1460 }
1461 #ifdef INET6
1462 else if (in6p &&
1463 (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0
1464 && ipsec6_in_reject_so(m, in6p->in6p_socket)) {
1465 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1466 goto drop;
1467 }
1468 #endif
1469 }
1470 #endif /*IPSEC*/
1471 break;
1472 #endif /*INET*/
1473 #ifdef INET6
1474 case AF_INET6:
1475 {
1476 int faith;
1477
1478 #if defined(NFAITH) && NFAITH > 0
1479 faith = faithprefix(&ip6->ip6_dst);
1480 #else
1481 faith = 0;
1482 #endif
1483 in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1484 th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
1485 if (!in6p && !vestige.valid) {
1486 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1487 in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1488 th->th_dport, faith);
1489 }
1490 if (!in6p && !vestige.valid) {
1491 TCP_STATINC(TCP_STAT_NOPORT);
1492 if (tcp_log_refused &&
1493 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1494 tcp6_log_refused(ip6, th);
1495 }
1496 tcp_fields_to_host(th);
1497 goto dropwithreset_ratelim;
1498 }
1499 #if defined(IPSEC)
1500 if (ipsec_used && in6p
1501 && (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0
1502 && ipsec6_in_reject(m, in6p)) {
1503 IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
1504 goto drop;
1505 }
1506 #endif /*IPSEC*/
1507 break;
1508 }
1509 #endif
1510 }
1511
1512 /*
1513 * If the state is CLOSED (i.e., TCB does not exist) then
1514 * all data in the incoming segment is discarded.
1515 * If the TCB exists but is in CLOSED state, it is embryonic,
1516 * but should either do a listen or a connect soon.
1517 */
1518 tp = NULL;
1519 so = NULL;
1520 if (inp) {
1521 /* Check the minimum TTL for socket. */
1522 if (ip->ip_ttl < inp->inp_ip_minttl)
1523 goto drop;
1524
1525 tp = intotcpcb(inp);
1526 so = inp->inp_socket;
1527 }
1528 #ifdef INET6
1529 else if (in6p) {
1530 tp = in6totcpcb(in6p);
1531 so = in6p->in6p_socket;
1532 }
1533 #endif
1534 else if (vestige.valid) {
1535 int mc = 0;
1536
1537 /* We do not support the resurrection of vtw tcpcps.
1538 */
1539 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1540 goto badcsum;
1541
1542 switch (af) {
1543 #ifdef INET6
1544 case AF_INET6:
1545 mc = IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst);
1546 break;
1547 #endif
1548
1549 case AF_INET:
1550 mc = (IN_MULTICAST(ip->ip_dst.s_addr)
1551 || in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif));
1552 break;
1553 }
1554
1555 tcp_fields_to_host(th);
1556 tcp_vtw_input(th, &vestige, m, tlen, mc);
1557 m = 0;
1558 goto drop;
1559 }
1560
1561 if (tp == 0) {
1562 tcp_fields_to_host(th);
1563 goto dropwithreset_ratelim;
1564 }
1565 if (tp->t_state == TCPS_CLOSED)
1566 goto drop;
1567
1568 KASSERT(so->so_lock == softnet_lock);
1569 KASSERT(solocked(so));
1570
1571 tcp_fields_to_host(th);
1572
1573 /* Unscale the window into a 32-bit value. */
1574 if ((tiflags & TH_SYN) == 0)
1575 tiwin = th->th_win << tp->snd_scale;
1576 else
1577 tiwin = th->th_win;
1578
1579 #ifdef INET6
1580 /* save packet options if user wanted */
1581 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1582 if (in6p->in6p_options) {
1583 m_freem(in6p->in6p_options);
1584 in6p->in6p_options = 0;
1585 }
1586 KASSERT(ip6 != NULL);
1587 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1588 }
1589 #endif
1590
1591 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
1592 union syn_cache_sa src;
1593 union syn_cache_sa dst;
1594
1595 memset(&src, 0, sizeof(src));
1596 memset(&dst, 0, sizeof(dst));
1597 switch (af) {
1598 #ifdef INET
1599 case AF_INET:
1600 src.sin.sin_len = sizeof(struct sockaddr_in);
1601 src.sin.sin_family = AF_INET;
1602 src.sin.sin_addr = ip->ip_src;
1603 src.sin.sin_port = th->th_sport;
1604
1605 dst.sin.sin_len = sizeof(struct sockaddr_in);
1606 dst.sin.sin_family = AF_INET;
1607 dst.sin.sin_addr = ip->ip_dst;
1608 dst.sin.sin_port = th->th_dport;
1609 break;
1610 #endif
1611 #ifdef INET6
1612 case AF_INET6:
1613 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1614 src.sin6.sin6_family = AF_INET6;
1615 src.sin6.sin6_addr = ip6->ip6_src;
1616 src.sin6.sin6_port = th->th_sport;
1617
1618 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1619 dst.sin6.sin6_family = AF_INET6;
1620 dst.sin6.sin6_addr = ip6->ip6_dst;
1621 dst.sin6.sin6_port = th->th_dport;
1622 break;
1623 #endif /* INET6 */
1624 default:
1625 goto badsyn; /*sanity*/
1626 }
1627
1628 if (so->so_options & SO_DEBUG) {
1629 #ifdef TCP_DEBUG
1630 ostate = tp->t_state;
1631 #endif
1632
1633 tcp_saveti = NULL;
1634 if (iphlen + sizeof(struct tcphdr) > MHLEN)
1635 goto nosave;
1636
1637 if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1638 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1639 if (!tcp_saveti)
1640 goto nosave;
1641 } else {
1642 MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1643 if (!tcp_saveti)
1644 goto nosave;
1645 MCLAIM(m, &tcp_mowner);
1646 tcp_saveti->m_len = iphlen;
1647 m_copydata(m, 0, iphlen,
1648 mtod(tcp_saveti, void *));
1649 }
1650
1651 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1652 m_freem(tcp_saveti);
1653 tcp_saveti = NULL;
1654 } else {
1655 tcp_saveti->m_len += sizeof(struct tcphdr);
1656 memcpy(mtod(tcp_saveti, char *) + iphlen, th,
1657 sizeof(struct tcphdr));
1658 }
1659 nosave:;
1660 }
1661 if (so->so_options & SO_ACCEPTCONN) {
1662 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1663 if (tiflags & TH_RST) {
1664 syn_cache_reset(&src.sa, &dst.sa, th);
1665 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
1666 (TH_ACK|TH_SYN)) {
1667 /*
1668 * Received a SYN,ACK. This should
1669 * never happen while we are in
1670 * LISTEN. Send an RST.
1671 */
1672 goto badsyn;
1673 } else if (tiflags & TH_ACK) {
1674 so = syn_cache_get(&src.sa, &dst.sa,
1675 th, toff, tlen, so, m);
1676 if (so == NULL) {
1677 /*
1678 * We don't have a SYN for
1679 * this ACK; send an RST.
1680 */
1681 goto badsyn;
1682 } else if (so ==
1683 (struct socket *)(-1)) {
1684 /*
1685 * We were unable to create
1686 * the connection. If the
1687 * 3-way handshake was
1688 * completed, and RST has
1689 * been sent to the peer.
1690 * Since the mbuf might be
1691 * in use for the reply,
1692 * do not free it.
1693 */
1694 m = NULL;
1695 } else {
1696 /*
1697 * We have created a
1698 * full-blown connection.
1699 */
1700 tp = NULL;
1701 inp = NULL;
1702 #ifdef INET6
1703 in6p = NULL;
1704 #endif
1705 switch (so->so_proto->pr_domain->dom_family) {
1706 #ifdef INET
1707 case AF_INET:
1708 inp = sotoinpcb(so);
1709 tp = intotcpcb(inp);
1710 break;
1711 #endif
1712 #ifdef INET6
1713 case AF_INET6:
1714 in6p = sotoin6pcb(so);
1715 tp = in6totcpcb(in6p);
1716 break;
1717 #endif
1718 }
1719 if (tp == NULL)
1720 goto badsyn; /*XXX*/
1721 tiwin <<= tp->snd_scale;
1722 goto after_listen;
1723 }
1724 } else {
1725 /*
1726 * None of RST, SYN or ACK was set.
1727 * This is an invalid packet for a
1728 * TCB in LISTEN state. Send a RST.
1729 */
1730 goto badsyn;
1731 }
1732 } else {
1733 /*
1734 * Received a SYN.
1735 *
1736 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1737 */
1738 if (m->m_flags & (M_BCAST|M_MCAST))
1739 goto drop;
1740
1741 switch (af) {
1742 #ifdef INET6
1743 case AF_INET6:
1744 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1745 goto drop;
1746 break;
1747 #endif /* INET6 */
1748 case AF_INET:
1749 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1750 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1751 goto drop;
1752 break;
1753 }
1754
1755 #ifdef INET6
1756 /*
1757 * If deprecated address is forbidden, we do
1758 * not accept SYN to deprecated interface
1759 * address to prevent any new inbound
1760 * connection from getting established.
1761 * When we do not accept SYN, we send a TCP
1762 * RST, with deprecated source address (instead
1763 * of dropping it). We compromise it as it is
1764 * much better for peer to send a RST, and
1765 * RST will be the final packet for the
1766 * exchange.
1767 *
1768 * If we do not forbid deprecated addresses, we
1769 * accept the SYN packet. RFC2462 does not
1770 * suggest dropping SYN in this case.
1771 * If we decipher RFC2462 5.5.4, it says like
1772 * this:
1773 * 1. use of deprecated addr with existing
1774 * communication is okay - "SHOULD continue
1775 * to be used"
1776 * 2. use of it with new communication:
1777 * (2a) "SHOULD NOT be used if alternate
1778 * address with sufficient scope is
1779 * available"
1780 * (2b) nothing mentioned otherwise.
1781 * Here we fall into (2b) case as we have no
1782 * choice in our source address selection - we
1783 * must obey the peer.
1784 *
1785 * The wording in RFC2462 is confusing, and
1786 * there are multiple description text for
1787 * deprecated address handling - worse, they
1788 * are not exactly the same. I believe 5.5.4
1789 * is the best one, so we follow 5.5.4.
1790 */
1791 if (af == AF_INET6 && !ip6_use_deprecated) {
1792 struct in6_ifaddr *ia6;
1793 if ((ia6 = in6ifa_ifpwithaddr(m->m_pkthdr.rcvif,
1794 &ip6->ip6_dst)) &&
1795 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1796 tp = NULL;
1797 goto dropwithreset;
1798 }
1799 }
1800 #endif
1801
1802 #if defined(IPSEC)
1803 if (ipsec_used) {
1804 switch (af) {
1805 #ifdef INET
1806 case AF_INET:
1807 if (!ipsec4_in_reject_so(m, so))
1808 break;
1809 IPSEC_STATINC(
1810 IPSEC_STAT_IN_POLVIO);
1811 tp = NULL;
1812 goto dropwithreset;
1813 #endif
1814 #ifdef INET6
1815 case AF_INET6:
1816 if (!ipsec6_in_reject_so(m, so))
1817 break;
1818 IPSEC6_STATINC(
1819 IPSEC_STAT_IN_POLVIO);
1820 tp = NULL;
1821 goto dropwithreset;
1822 #endif /*INET6*/
1823 }
1824 }
1825 #endif /*IPSEC*/
1826
1827 /*
1828 * LISTEN socket received a SYN
1829 * from itself? This can't possibly
1830 * be valid; drop the packet.
1831 */
1832 if (th->th_sport == th->th_dport) {
1833 int i;
1834
1835 switch (af) {
1836 #ifdef INET
1837 case AF_INET:
1838 i = in_hosteq(ip->ip_src, ip->ip_dst);
1839 break;
1840 #endif
1841 #ifdef INET6
1842 case AF_INET6:
1843 i = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src, &ip6->ip6_dst);
1844 break;
1845 #endif
1846 default:
1847 i = 1;
1848 }
1849 if (i) {
1850 TCP_STATINC(TCP_STAT_BADSYN);
1851 goto drop;
1852 }
1853 }
1854
1855 /*
1856 * SYN looks ok; create compressed TCP
1857 * state for it.
1858 */
1859 if (so->so_qlen <= so->so_qlimit &&
1860 syn_cache_add(&src.sa, &dst.sa, th, tlen,
1861 so, m, optp, optlen, &opti))
1862 m = NULL;
1863 }
1864 goto drop;
1865 }
1866 }
1867
1868 after_listen:
1869 #ifdef DIAGNOSTIC
1870 /*
1871 * Should not happen now that all embryonic connections
1872 * are handled with compressed state.
1873 */
1874 if (tp->t_state == TCPS_LISTEN)
1875 panic("tcp_input: TCPS_LISTEN");
1876 #endif
1877
1878 /*
1879 * Segment received on connection.
1880 * Reset idle time and keep-alive timer.
1881 */
1882 tp->t_rcvtime = tcp_now;
1883 if (TCPS_HAVEESTABLISHED(tp->t_state))
1884 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
1885
1886 /*
1887 * Process options.
1888 */
1889 #ifdef TCP_SIGNATURE
1890 if (optp || (tp->t_flags & TF_SIGNATURE))
1891 #else
1892 if (optp)
1893 #endif
1894 if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1895 goto drop;
1896
1897 if (TCP_SACK_ENABLED(tp)) {
1898 tcp_del_sackholes(tp, th);
1899 }
1900
1901 if (TCP_ECN_ALLOWED(tp)) {
1902 if (tiflags & TH_CWR) {
1903 tp->t_flags &= ~TF_ECN_SND_ECE;
1904 }
1905 switch (iptos & IPTOS_ECN_MASK) {
1906 case IPTOS_ECN_CE:
1907 tp->t_flags |= TF_ECN_SND_ECE;
1908 TCP_STATINC(TCP_STAT_ECN_CE);
1909 break;
1910 case IPTOS_ECN_ECT0:
1911 TCP_STATINC(TCP_STAT_ECN_ECT);
1912 break;
1913 case IPTOS_ECN_ECT1:
1914 /* XXX: ignore for now -- rpaulo */
1915 break;
1916 }
1917 /*
1918 * Congestion experienced.
1919 * Ignore if we are already trying to recover.
1920 */
1921 if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
1922 tp->t_congctl->cong_exp(tp);
1923 }
1924
1925 if (opti.ts_present && opti.ts_ecr) {
1926 /*
1927 * Calculate the RTT from the returned time stamp and the
1928 * connection's time base. If the time stamp is later than
1929 * the current time, or is extremely old, fall back to non-1323
1930 * RTT calculation. Since ts_rtt is unsigned, we can test both
1931 * at the same time.
1932 *
1933 * Note that ts_rtt is in units of slow ticks (500
1934 * ms). Since most earthbound RTTs are < 500 ms,
1935 * observed values will have large quantization noise.
1936 * Our smoothed RTT is then the fraction of observed
1937 * samples that are 1 tick instead of 0 (times 500
1938 * ms).
1939 *
1940 * ts_rtt is increased by 1 to denote a valid sample,
1941 * with 0 indicating an invalid measurement. This
1942 * extra 1 must be removed when ts_rtt is used, or
1943 * else an an erroneous extra 500 ms will result.
1944 */
1945 ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1946 if (ts_rtt > TCP_PAWS_IDLE)
1947 ts_rtt = 0;
1948 } else {
1949 ts_rtt = 0;
1950 }
1951
1952 /*
1953 * Header prediction: check for the two common cases
1954 * of a uni-directional data xfer. If the packet has
1955 * no control flags, is in-sequence, the window didn't
1956 * change and we're not retransmitting, it's a
1957 * candidate. If the length is zero and the ack moved
1958 * forward, we're the sender side of the xfer. Just
1959 * free the data acked & wake any higher level process
1960 * that was blocked waiting for space. If the length
1961 * is non-zero and the ack didn't move, we're the
1962 * receiver side. If we're getting packets in-order
1963 * (the reassembly queue is empty), add the data to
1964 * the socket buffer and note that we need a delayed ack.
1965 */
1966 if (tp->t_state == TCPS_ESTABLISHED &&
1967 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
1968 == TH_ACK &&
1969 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1970 th->th_seq == tp->rcv_nxt &&
1971 tiwin && tiwin == tp->snd_wnd &&
1972 tp->snd_nxt == tp->snd_max) {
1973
1974 /*
1975 * If last ACK falls within this segment's sequence numbers,
1976 * record the timestamp.
1977 * NOTE that the test is modified according to the latest
1978 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
1979 *
1980 * note that we already know
1981 * TSTMP_GEQ(opti.ts_val, tp->ts_recent)
1982 */
1983 if (opti.ts_present &&
1984 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1985 tp->ts_recent_age = tcp_now;
1986 tp->ts_recent = opti.ts_val;
1987 }
1988
1989 if (tlen == 0) {
1990 /* Ack prediction. */
1991 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1992 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1993 tp->snd_cwnd >= tp->snd_wnd &&
1994 tp->t_partialacks < 0) {
1995 /*
1996 * this is a pure ack for outstanding data.
1997 */
1998 if (ts_rtt)
1999 tcp_xmit_timer(tp, ts_rtt - 1);
2000 else if (tp->t_rtttime &&
2001 SEQ_GT(th->th_ack, tp->t_rtseq))
2002 tcp_xmit_timer(tp,
2003 tcp_now - tp->t_rtttime);
2004 acked = th->th_ack - tp->snd_una;
2005 tcps = TCP_STAT_GETREF();
2006 tcps[TCP_STAT_PREDACK]++;
2007 tcps[TCP_STAT_RCVACKPACK]++;
2008 tcps[TCP_STAT_RCVACKBYTE] += acked;
2009 TCP_STAT_PUTREF();
2010 nd6_hint(tp);
2011
2012 if (acked > (tp->t_lastoff - tp->t_inoff))
2013 tp->t_lastm = NULL;
2014 sbdrop(&so->so_snd, acked);
2015 tp->t_lastoff -= acked;
2016
2017 icmp_check(tp, th, acked);
2018
2019 tp->snd_una = th->th_ack;
2020 tp->snd_fack = tp->snd_una;
2021 if (SEQ_LT(tp->snd_high, tp->snd_una))
2022 tp->snd_high = tp->snd_una;
2023 m_freem(m);
2024
2025 /*
2026 * If all outstanding data are acked, stop
2027 * retransmit timer, otherwise restart timer
2028 * using current (possibly backed-off) value.
2029 * If process is waiting for space,
2030 * wakeup/selnotify/signal. If data
2031 * are ready to send, let tcp_output
2032 * decide between more output or persist.
2033 */
2034 if (tp->snd_una == tp->snd_max)
2035 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2036 else if (TCP_TIMER_ISARMED(tp,
2037 TCPT_PERSIST) == 0)
2038 TCP_TIMER_ARM(tp, TCPT_REXMT,
2039 tp->t_rxtcur);
2040
2041 sowwakeup(so);
2042 if (so->so_snd.sb_cc) {
2043 KERNEL_LOCK(1, NULL);
2044 (void) tcp_output(tp);
2045 KERNEL_UNLOCK_ONE(NULL);
2046 }
2047 if (tcp_saveti)
2048 m_freem(tcp_saveti);
2049 return;
2050 }
2051 } else if (th->th_ack == tp->snd_una &&
2052 TAILQ_FIRST(&tp->segq) == NULL &&
2053 tlen <= sbspace(&so->so_rcv)) {
2054 int newsize = 0; /* automatic sockbuf scaling */
2055
2056 /*
2057 * this is a pure, in-sequence data packet
2058 * with nothing on the reassembly queue and
2059 * we have enough buffer space to take it.
2060 */
2061 tp->rcv_nxt += tlen;
2062 tcps = TCP_STAT_GETREF();
2063 tcps[TCP_STAT_PREDDAT]++;
2064 tcps[TCP_STAT_RCVPACK]++;
2065 tcps[TCP_STAT_RCVBYTE] += tlen;
2066 TCP_STAT_PUTREF();
2067 nd6_hint(tp);
2068
2069 /*
2070 * Automatic sizing enables the performance of large buffers
2071 * and most of the efficiency of small ones by only allocating
2072 * space when it is needed.
2073 *
2074 * On the receive side the socket buffer memory is only rarely
2075 * used to any significant extent. This allows us to be much
2076 * more aggressive in scaling the receive socket buffer. For
2077 * the case that the buffer space is actually used to a large
2078 * extent and we run out of kernel memory we can simply drop
2079 * the new segments; TCP on the sender will just retransmit it
2080 * later. Setting the buffer size too big may only consume too
2081 * much kernel memory if the application doesn't read() from
2082 * the socket or packet loss or reordering makes use of the
2083 * reassembly queue.
2084 *
2085 * The criteria to step up the receive buffer one notch are:
2086 * 1. the number of bytes received during the time it takes
2087 * one timestamp to be reflected back to us (the RTT);
2088 * 2. received bytes per RTT is within seven eighth of the
2089 * current socket buffer size;
2090 * 3. receive buffer size has not hit maximal automatic size;
2091 *
2092 * This algorithm does one step per RTT at most and only if
2093 * we receive a bulk stream w/o packet losses or reorderings.
2094 * Shrinking the buffer during idle times is not necessary as
2095 * it doesn't consume any memory when idle.
2096 *
2097 * TODO: Only step up if the application is actually serving
2098 * the buffer to better manage the socket buffer resources.
2099 */
2100 if (tcp_do_autorcvbuf &&
2101 opti.ts_ecr &&
2102 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
2103 if (opti.ts_ecr > tp->rfbuf_ts &&
2104 opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
2105 if (tp->rfbuf_cnt >
2106 (so->so_rcv.sb_hiwat / 8 * 7) &&
2107 so->so_rcv.sb_hiwat <
2108 tcp_autorcvbuf_max) {
2109 newsize =
2110 min(so->so_rcv.sb_hiwat +
2111 tcp_autorcvbuf_inc,
2112 tcp_autorcvbuf_max);
2113 }
2114 /* Start over with next RTT. */
2115 tp->rfbuf_ts = 0;
2116 tp->rfbuf_cnt = 0;
2117 } else
2118 tp->rfbuf_cnt += tlen; /* add up */
2119 }
2120
2121 /*
2122 * Drop TCP, IP headers and TCP options then add data
2123 * to socket buffer.
2124 */
2125 if (so->so_state & SS_CANTRCVMORE)
2126 m_freem(m);
2127 else {
2128 /*
2129 * Set new socket buffer size.
2130 * Give up when limit is reached.
2131 */
2132 if (newsize)
2133 if (!sbreserve(&so->so_rcv,
2134 newsize, so))
2135 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
2136 m_adj(m, toff + off);
2137 sbappendstream(&so->so_rcv, m);
2138 }
2139 sorwakeup(so);
2140 tcp_setup_ack(tp, th);
2141 if (tp->t_flags & TF_ACKNOW) {
2142 KERNEL_LOCK(1, NULL);
2143 (void) tcp_output(tp);
2144 KERNEL_UNLOCK_ONE(NULL);
2145 }
2146 if (tcp_saveti)
2147 m_freem(tcp_saveti);
2148 return;
2149 }
2150 }
2151
2152 /*
2153 * Compute mbuf offset to TCP data segment.
2154 */
2155 hdroptlen = toff + off;
2156
2157 /*
2158 * Calculate amount of space in receive window,
2159 * and then do TCP input processing.
2160 * Receive window is amount of space in rcv queue,
2161 * but not less than advertised window.
2162 */
2163 { int win;
2164
2165 win = sbspace(&so->so_rcv);
2166 if (win < 0)
2167 win = 0;
2168 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
2169 }
2170
2171 /* Reset receive buffer auto scaling when not in bulk receive mode. */
2172 tp->rfbuf_ts = 0;
2173 tp->rfbuf_cnt = 0;
2174
2175 switch (tp->t_state) {
2176 /*
2177 * If the state is SYN_SENT:
2178 * if seg contains an ACK, but not for our SYN, drop the input.
2179 * if seg contains a RST, then drop the connection.
2180 * if seg does not contain SYN, then drop it.
2181 * Otherwise this is an acceptable SYN segment
2182 * initialize tp->rcv_nxt and tp->irs
2183 * if seg contains ack then advance tp->snd_una
2184 * if seg contains a ECE and ECN support is enabled, the stream
2185 * is ECN capable.
2186 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2187 * arrange for segment to be acked (eventually)
2188 * continue processing rest of data/controls, beginning with URG
2189 */
2190 case TCPS_SYN_SENT:
2191 if ((tiflags & TH_ACK) &&
2192 (SEQ_LEQ(th->th_ack, tp->iss) ||
2193 SEQ_GT(th->th_ack, tp->snd_max)))
2194 goto dropwithreset;
2195 if (tiflags & TH_RST) {
2196 if (tiflags & TH_ACK)
2197 tp = tcp_drop(tp, ECONNREFUSED);
2198 goto drop;
2199 }
2200 if ((tiflags & TH_SYN) == 0)
2201 goto drop;
2202 if (tiflags & TH_ACK) {
2203 tp->snd_una = th->th_ack;
2204 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2205 tp->snd_nxt = tp->snd_una;
2206 if (SEQ_LT(tp->snd_high, tp->snd_una))
2207 tp->snd_high = tp->snd_una;
2208 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2209
2210 if ((tiflags & TH_ECE) && tcp_do_ecn) {
2211 tp->t_flags |= TF_ECN_PERMIT;
2212 TCP_STATINC(TCP_STAT_ECN_SHS);
2213 }
2214
2215 }
2216 tp->irs = th->th_seq;
2217 tcp_rcvseqinit(tp);
2218 tp->t_flags |= TF_ACKNOW;
2219 tcp_mss_from_peer(tp, opti.maxseg);
2220
2221 /*
2222 * Initialize the initial congestion window. If we
2223 * had to retransmit the SYN, we must initialize cwnd
2224 * to 1 segment (i.e. the Loss Window).
2225 */
2226 if (tp->t_flags & TF_SYN_REXMT)
2227 tp->snd_cwnd = tp->t_peermss;
2228 else {
2229 int ss = tcp_init_win;
2230 #ifdef INET
2231 if (inp != NULL && in_localaddr(inp->inp_faddr))
2232 ss = tcp_init_win_local;
2233 #endif
2234 #ifdef INET6
2235 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
2236 ss = tcp_init_win_local;
2237 #endif
2238 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
2239 }
2240
2241 tcp_rmx_rtt(tp);
2242 if (tiflags & TH_ACK) {
2243 TCP_STATINC(TCP_STAT_CONNECTS);
2244 /*
2245 * move tcp_established before soisconnected
2246 * because upcall handler can drive tcp_output
2247 * functionality.
2248 * XXX we might call soisconnected at the end of
2249 * all processing
2250 */
2251 tcp_established(tp);
2252 soisconnected(so);
2253 /* Do window scaling on this connection? */
2254 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2255 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2256 tp->snd_scale = tp->requested_s_scale;
2257 tp->rcv_scale = tp->request_r_scale;
2258 }
2259 TCP_REASS_LOCK(tp);
2260 (void) tcp_reass(tp, NULL, NULL, &tlen);
2261 /*
2262 * if we didn't have to retransmit the SYN,
2263 * use its rtt as our initial srtt & rtt var.
2264 */
2265 if (tp->t_rtttime)
2266 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2267 } else
2268 tp->t_state = TCPS_SYN_RECEIVED;
2269
2270 /*
2271 * Advance th->th_seq to correspond to first data byte.
2272 * If data, trim to stay within window,
2273 * dropping FIN if necessary.
2274 */
2275 th->th_seq++;
2276 if (tlen > tp->rcv_wnd) {
2277 todrop = tlen - tp->rcv_wnd;
2278 m_adj(m, -todrop);
2279 tlen = tp->rcv_wnd;
2280 tiflags &= ~TH_FIN;
2281 tcps = TCP_STAT_GETREF();
2282 tcps[TCP_STAT_RCVPACKAFTERWIN]++;
2283 tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
2284 TCP_STAT_PUTREF();
2285 }
2286 tp->snd_wl1 = th->th_seq - 1;
2287 tp->rcv_up = th->th_seq;
2288 goto step6;
2289
2290 /*
2291 * If the state is SYN_RECEIVED:
2292 * If seg contains an ACK, but not for our SYN, drop the input
2293 * and generate an RST. See page 36, rfc793
2294 */
2295 case TCPS_SYN_RECEIVED:
2296 if ((tiflags & TH_ACK) &&
2297 (SEQ_LEQ(th->th_ack, tp->iss) ||
2298 SEQ_GT(th->th_ack, tp->snd_max)))
2299 goto dropwithreset;
2300 break;
2301 }
2302
2303 /*
2304 * States other than LISTEN or SYN_SENT.
2305 * First check timestamp, if present.
2306 * Then check that at least some bytes of segment are within
2307 * receive window. If segment begins before rcv_nxt,
2308 * drop leading data (and SYN); if nothing left, just ack.
2309 *
2310 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2311 * and it's less than ts_recent, drop it.
2312 */
2313 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
2314 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
2315
2316 /* Check to see if ts_recent is over 24 days old. */
2317 if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
2318 /*
2319 * Invalidate ts_recent. If this segment updates
2320 * ts_recent, the age will be reset later and ts_recent
2321 * will get a valid value. If it does not, setting
2322 * ts_recent to zero will at least satisfy the
2323 * requirement that zero be placed in the timestamp
2324 * echo reply when ts_recent isn't valid. The
2325 * age isn't reset until we get a valid ts_recent
2326 * because we don't want out-of-order segments to be
2327 * dropped when ts_recent is old.
2328 */
2329 tp->ts_recent = 0;
2330 } else {
2331 tcps = TCP_STAT_GETREF();
2332 tcps[TCP_STAT_RCVDUPPACK]++;
2333 tcps[TCP_STAT_RCVDUPBYTE] += tlen;
2334 tcps[TCP_STAT_PAWSDROP]++;
2335 TCP_STAT_PUTREF();
2336 tcp_new_dsack(tp, th->th_seq, tlen);
2337 goto dropafterack;
2338 }
2339 }
2340
2341 todrop = tp->rcv_nxt - th->th_seq;
2342 dupseg = false;
2343 if (todrop > 0) {
2344 if (tiflags & TH_SYN) {
2345 tiflags &= ~TH_SYN;
2346 th->th_seq++;
2347 if (th->th_urp > 1)
2348 th->th_urp--;
2349 else {
2350 tiflags &= ~TH_URG;
2351 th->th_urp = 0;
2352 }
2353 todrop--;
2354 }
2355 if (todrop > tlen ||
2356 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
2357 /*
2358 * Any valid FIN or RST must be to the left of the
2359 * window. At this point the FIN or RST must be a
2360 * duplicate or out of sequence; drop it.
2361 */
2362 if (tiflags & TH_RST)
2363 goto drop;
2364 tiflags &= ~(TH_FIN|TH_RST);
2365 /*
2366 * Send an ACK to resynchronize and drop any data.
2367 * But keep on processing for RST or ACK.
2368 */
2369 tp->t_flags |= TF_ACKNOW;
2370 todrop = tlen;
2371 dupseg = true;
2372 tcps = TCP_STAT_GETREF();
2373 tcps[TCP_STAT_RCVDUPPACK]++;
2374 tcps[TCP_STAT_RCVDUPBYTE] += todrop;
2375 TCP_STAT_PUTREF();
2376 } else if ((tiflags & TH_RST) &&
2377 th->th_seq != tp->rcv_nxt) {
2378 /*
2379 * Test for reset before adjusting the sequence
2380 * number for overlapping data.
2381 */
2382 goto dropafterack_ratelim;
2383 } else {
2384 tcps = TCP_STAT_GETREF();
2385 tcps[TCP_STAT_RCVPARTDUPPACK]++;
2386 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
2387 TCP_STAT_PUTREF();
2388 }
2389 tcp_new_dsack(tp, th->th_seq, todrop);
2390 hdroptlen += todrop; /*drop from head afterwards*/
2391 th->th_seq += todrop;
2392 tlen -= todrop;
2393 if (th->th_urp > todrop)
2394 th->th_urp -= todrop;
2395 else {
2396 tiflags &= ~TH_URG;
2397 th->th_urp = 0;
2398 }
2399 }
2400
2401 /*
2402 * If new data are received on a connection after the
2403 * user processes are gone, then RST the other end.
2404 */
2405 if ((so->so_state & SS_NOFDREF) &&
2406 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2407 tp = tcp_close(tp);
2408 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
2409 goto dropwithreset;
2410 }
2411
2412 /*
2413 * If segment ends after window, drop trailing data
2414 * (and PUSH and FIN); if nothing left, just ACK.
2415 */
2416 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
2417 if (todrop > 0) {
2418 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
2419 if (todrop >= tlen) {
2420 /*
2421 * The segment actually starts after the window.
2422 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2423 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2424 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2425 */
2426 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
2427 /*
2428 * If a new connection request is received
2429 * while in TIME_WAIT, drop the old connection
2430 * and start over if the sequence numbers
2431 * are above the previous ones.
2432 *
2433 * NOTE: We will checksum the packet again, and
2434 * so we need to put the header fields back into
2435 * network order!
2436 * XXX This kind of sucks, but we don't expect
2437 * XXX this to happen very often, so maybe it
2438 * XXX doesn't matter so much.
2439 */
2440 if (tiflags & TH_SYN &&
2441 tp->t_state == TCPS_TIME_WAIT &&
2442 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2443 tp = tcp_close(tp);
2444 tcp_fields_to_net(th);
2445 goto findpcb;
2446 }
2447 /*
2448 * If window is closed can only take segments at
2449 * window edge, and have to drop data and PUSH from
2450 * incoming segments. Continue processing, but
2451 * remember to ack. Otherwise, drop segment
2452 * and (if not RST) ack.
2453 */
2454 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2455 tp->t_flags |= TF_ACKNOW;
2456 TCP_STATINC(TCP_STAT_RCVWINPROBE);
2457 } else
2458 goto dropafterack;
2459 } else
2460 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
2461 m_adj(m, -todrop);
2462 tlen -= todrop;
2463 tiflags &= ~(TH_PUSH|TH_FIN);
2464 }
2465
2466 /*
2467 * If last ACK falls within this segment's sequence numbers,
2468 * record the timestamp.
2469 * NOTE:
2470 * 1) That the test incorporates suggestions from the latest
2471 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
2472 * 2) That updating only on newer timestamps interferes with
2473 * our earlier PAWS tests, so this check should be solely
2474 * predicated on the sequence space of this segment.
2475 * 3) That we modify the segment boundary check to be
2476 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2477 * instead of RFC1323's
2478 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2479 * This modified check allows us to overcome RFC1323's
2480 * limitations as described in Stevens TCP/IP Illustrated
2481 * Vol. 2 p.869. In such cases, we can still calculate the
2482 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2483 */
2484 if (opti.ts_present &&
2485 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2486 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2487 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2488 tp->ts_recent_age = tcp_now;
2489 tp->ts_recent = opti.ts_val;
2490 }
2491
2492 /*
2493 * If the RST bit is set examine the state:
2494 * SYN_RECEIVED STATE:
2495 * If passive open, return to LISTEN state.
2496 * If active open, inform user that connection was refused.
2497 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
2498 * Inform user that connection was reset, and close tcb.
2499 * CLOSING, LAST_ACK, TIME_WAIT STATES
2500 * Close the tcb.
2501 */
2502 if (tiflags & TH_RST) {
2503 if (th->th_seq != tp->rcv_nxt)
2504 goto dropafterack_ratelim;
2505
2506 switch (tp->t_state) {
2507 case TCPS_SYN_RECEIVED:
2508 so->so_error = ECONNREFUSED;
2509 goto close;
2510
2511 case TCPS_ESTABLISHED:
2512 case TCPS_FIN_WAIT_1:
2513 case TCPS_FIN_WAIT_2:
2514 case TCPS_CLOSE_WAIT:
2515 so->so_error = ECONNRESET;
2516 close:
2517 tp->t_state = TCPS_CLOSED;
2518 TCP_STATINC(TCP_STAT_DROPS);
2519 tp = tcp_close(tp);
2520 goto drop;
2521
2522 case TCPS_CLOSING:
2523 case TCPS_LAST_ACK:
2524 case TCPS_TIME_WAIT:
2525 tp = tcp_close(tp);
2526 goto drop;
2527 }
2528 }
2529
2530 /*
2531 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2532 * we must be in a synchronized state. RFC791 states (under RST
2533 * generation) that any unacceptable segment (an out-of-order SYN
2534 * qualifies) received in a synchronized state must elicit only an
2535 * empty acknowledgment segment ... and the connection remains in
2536 * the same state.
2537 */
2538 if (tiflags & TH_SYN) {
2539 if (tp->rcv_nxt == th->th_seq) {
2540 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2541 TH_ACK);
2542 if (tcp_saveti)
2543 m_freem(tcp_saveti);
2544 return;
2545 }
2546
2547 goto dropafterack_ratelim;
2548 }
2549
2550 /*
2551 * If the ACK bit is off we drop the segment and return.
2552 */
2553 if ((tiflags & TH_ACK) == 0) {
2554 if (tp->t_flags & TF_ACKNOW)
2555 goto dropafterack;
2556 else
2557 goto drop;
2558 }
2559
2560 /*
2561 * Ack processing.
2562 */
2563 switch (tp->t_state) {
2564
2565 /*
2566 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2567 * ESTABLISHED state and continue processing, otherwise
2568 * send an RST.
2569 */
2570 case TCPS_SYN_RECEIVED:
2571 if (SEQ_GT(tp->snd_una, th->th_ack) ||
2572 SEQ_GT(th->th_ack, tp->snd_max))
2573 goto dropwithreset;
2574 TCP_STATINC(TCP_STAT_CONNECTS);
2575 soisconnected(so);
2576 tcp_established(tp);
2577 /* Do window scaling? */
2578 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2579 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2580 tp->snd_scale = tp->requested_s_scale;
2581 tp->rcv_scale = tp->request_r_scale;
2582 }
2583 TCP_REASS_LOCK(tp);
2584 (void) tcp_reass(tp, NULL, NULL, &tlen);
2585 tp->snd_wl1 = th->th_seq - 1;
2586 /* fall into ... */
2587
2588 /*
2589 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2590 * ACKs. If the ack is in the range
2591 * tp->snd_una < th->th_ack <= tp->snd_max
2592 * then advance tp->snd_una to th->th_ack and drop
2593 * data from the retransmission queue. If this ACK reflects
2594 * more up to date window information we update our window information.
2595 */
2596 case TCPS_ESTABLISHED:
2597 case TCPS_FIN_WAIT_1:
2598 case TCPS_FIN_WAIT_2:
2599 case TCPS_CLOSE_WAIT:
2600 case TCPS_CLOSING:
2601 case TCPS_LAST_ACK:
2602 case TCPS_TIME_WAIT:
2603
2604 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2605 if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2606 TCP_STATINC(TCP_STAT_RCVDUPACK);
2607 /*
2608 * If we have outstanding data (other than
2609 * a window probe), this is a completely
2610 * duplicate ack (ie, window info didn't
2611 * change), the ack is the biggest we've
2612 * seen and we've seen exactly our rexmt
2613 * threshhold of them, assume a packet
2614 * has been dropped and retransmit it.
2615 * Kludge snd_nxt & the congestion
2616 * window so we send only this one
2617 * packet.
2618 */
2619 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2620 th->th_ack != tp->snd_una)
2621 tp->t_dupacks = 0;
2622 else if (tp->t_partialacks < 0 &&
2623 (++tp->t_dupacks == tcprexmtthresh ||
2624 TCP_FACK_FASTRECOV(tp))) {
2625 /*
2626 * Do the fast retransmit, and adjust
2627 * congestion control paramenters.
2628 */
2629 if (tp->t_congctl->fast_retransmit(tp, th)) {
2630 /* False fast retransmit */
2631 break;
2632 } else
2633 goto drop;
2634 } else if (tp->t_dupacks > tcprexmtthresh) {
2635 tp->snd_cwnd += tp->t_segsz;
2636 KERNEL_LOCK(1, NULL);
2637 (void) tcp_output(tp);
2638 KERNEL_UNLOCK_ONE(NULL);
2639 goto drop;
2640 }
2641 } else {
2642 /*
2643 * If the ack appears to be very old, only
2644 * allow data that is in-sequence. This
2645 * makes it somewhat more difficult to insert
2646 * forged data by guessing sequence numbers.
2647 * Sent an ack to try to update the send
2648 * sequence number on the other side.
2649 */
2650 if (tlen && th->th_seq != tp->rcv_nxt &&
2651 SEQ_LT(th->th_ack,
2652 tp->snd_una - tp->max_sndwnd))
2653 goto dropafterack;
2654 }
2655 break;
2656 }
2657 /*
2658 * If the congestion window was inflated to account
2659 * for the other side's cached packets, retract it.
2660 */
2661 tp->t_congctl->fast_retransmit_newack(tp, th);
2662
2663 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2664 TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
2665 goto dropafterack;
2666 }
2667 acked = th->th_ack - tp->snd_una;
2668 tcps = TCP_STAT_GETREF();
2669 tcps[TCP_STAT_RCVACKPACK]++;
2670 tcps[TCP_STAT_RCVACKBYTE] += acked;
2671 TCP_STAT_PUTREF();
2672
2673 /*
2674 * If we have a timestamp reply, update smoothed
2675 * round trip time. If no timestamp is present but
2676 * transmit timer is running and timed sequence
2677 * number was acked, update smoothed round trip time.
2678 * Since we now have an rtt measurement, cancel the
2679 * timer backoff (cf., Phil Karn's retransmit alg.).
2680 * Recompute the initial retransmit timer.
2681 */
2682 if (ts_rtt)
2683 tcp_xmit_timer(tp, ts_rtt - 1);
2684 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2685 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2686
2687 /*
2688 * If all outstanding data is acked, stop retransmit
2689 * timer and remember to restart (more output or persist).
2690 * If there is more data to be acked, restart retransmit
2691 * timer, using current (possibly backed-off) value.
2692 */
2693 if (th->th_ack == tp->snd_max) {
2694 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2695 needoutput = 1;
2696 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2697 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2698
2699 /*
2700 * New data has been acked, adjust the congestion window.
2701 */
2702 tp->t_congctl->newack(tp, th);
2703
2704 nd6_hint(tp);
2705 if (acked > so->so_snd.sb_cc) {
2706 tp->snd_wnd -= so->so_snd.sb_cc;
2707 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2708 ourfinisacked = 1;
2709 } else {
2710 if (acked > (tp->t_lastoff - tp->t_inoff))
2711 tp->t_lastm = NULL;
2712 sbdrop(&so->so_snd, acked);
2713 tp->t_lastoff -= acked;
2714 if (tp->snd_wnd > acked)
2715 tp->snd_wnd -= acked;
2716 else
2717 tp->snd_wnd = 0;
2718 ourfinisacked = 0;
2719 }
2720 sowwakeup(so);
2721
2722 icmp_check(tp, th, acked);
2723
2724 tp->snd_una = th->th_ack;
2725 if (SEQ_GT(tp->snd_una, tp->snd_fack))
2726 tp->snd_fack = tp->snd_una;
2727 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2728 tp->snd_nxt = tp->snd_una;
2729 if (SEQ_LT(tp->snd_high, tp->snd_una))
2730 tp->snd_high = tp->snd_una;
2731
2732 switch (tp->t_state) {
2733
2734 /*
2735 * In FIN_WAIT_1 STATE in addition to the processing
2736 * for the ESTABLISHED state if our FIN is now acknowledged
2737 * then enter FIN_WAIT_2.
2738 */
2739 case TCPS_FIN_WAIT_1:
2740 if (ourfinisacked) {
2741 /*
2742 * If we can't receive any more
2743 * data, then closing user can proceed.
2744 * Starting the timer is contrary to the
2745 * specification, but if we don't get a FIN
2746 * we'll hang forever.
2747 */
2748 if (so->so_state & SS_CANTRCVMORE) {
2749 soisdisconnected(so);
2750 if (tp->t_maxidle > 0)
2751 TCP_TIMER_ARM(tp, TCPT_2MSL,
2752 tp->t_maxidle);
2753 }
2754 tp->t_state = TCPS_FIN_WAIT_2;
2755 }
2756 break;
2757
2758 /*
2759 * In CLOSING STATE in addition to the processing for
2760 * the ESTABLISHED state if the ACK acknowledges our FIN
2761 * then enter the TIME-WAIT state, otherwise ignore
2762 * the segment.
2763 */
2764 case TCPS_CLOSING:
2765 if (ourfinisacked) {
2766 tp->t_state = TCPS_TIME_WAIT;
2767 tcp_canceltimers(tp);
2768 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2769 soisdisconnected(so);
2770 }
2771 break;
2772
2773 /*
2774 * In LAST_ACK, we may still be waiting for data to drain
2775 * and/or to be acked, as well as for the ack of our FIN.
2776 * If our FIN is now acknowledged, delete the TCB,
2777 * enter the closed state and return.
2778 */
2779 case TCPS_LAST_ACK:
2780 if (ourfinisacked) {
2781 tp = tcp_close(tp);
2782 goto drop;
2783 }
2784 break;
2785
2786 /*
2787 * In TIME_WAIT state the only thing that should arrive
2788 * is a retransmission of the remote FIN. Acknowledge
2789 * it and restart the finack timer.
2790 */
2791 case TCPS_TIME_WAIT:
2792 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2793 goto dropafterack;
2794 }
2795 }
2796
2797 step6:
2798 /*
2799 * Update window information.
2800 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2801 */
2802 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2803 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2804 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2805 /* keep track of pure window updates */
2806 if (tlen == 0 &&
2807 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2808 TCP_STATINC(TCP_STAT_RCVWINUPD);
2809 tp->snd_wnd = tiwin;
2810 tp->snd_wl1 = th->th_seq;
2811 tp->snd_wl2 = th->th_ack;
2812 if (tp->snd_wnd > tp->max_sndwnd)
2813 tp->max_sndwnd = tp->snd_wnd;
2814 needoutput = 1;
2815 }
2816
2817 /*
2818 * Process segments with URG.
2819 */
2820 if ((tiflags & TH_URG) && th->th_urp &&
2821 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2822 /*
2823 * This is a kludge, but if we receive and accept
2824 * random urgent pointers, we'll crash in
2825 * soreceive. It's hard to imagine someone
2826 * actually wanting to send this much urgent data.
2827 */
2828 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2829 th->th_urp = 0; /* XXX */
2830 tiflags &= ~TH_URG; /* XXX */
2831 goto dodata; /* XXX */
2832 }
2833 /*
2834 * If this segment advances the known urgent pointer,
2835 * then mark the data stream. This should not happen
2836 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2837 * a FIN has been received from the remote side.
2838 * In these states we ignore the URG.
2839 *
2840 * According to RFC961 (Assigned Protocols),
2841 * the urgent pointer points to the last octet
2842 * of urgent data. We continue, however,
2843 * to consider it to indicate the first octet
2844 * of data past the urgent section as the original
2845 * spec states (in one of two places).
2846 */
2847 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2848 tp->rcv_up = th->th_seq + th->th_urp;
2849 so->so_oobmark = so->so_rcv.sb_cc +
2850 (tp->rcv_up - tp->rcv_nxt) - 1;
2851 if (so->so_oobmark == 0)
2852 so->so_state |= SS_RCVATMARK;
2853 sohasoutofband(so);
2854 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2855 }
2856 /*
2857 * Remove out of band data so doesn't get presented to user.
2858 * This can happen independent of advancing the URG pointer,
2859 * but if two URG's are pending at once, some out-of-band
2860 * data may creep in... ick.
2861 */
2862 if (th->th_urp <= (u_int16_t) tlen
2863 #ifdef SO_OOBINLINE
2864 && (so->so_options & SO_OOBINLINE) == 0
2865 #endif
2866 )
2867 tcp_pulloutofband(so, th, m, hdroptlen);
2868 } else
2869 /*
2870 * If no out of band data is expected,
2871 * pull receive urgent pointer along
2872 * with the receive window.
2873 */
2874 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2875 tp->rcv_up = tp->rcv_nxt;
2876 dodata: /* XXX */
2877
2878 /*
2879 * Process the segment text, merging it into the TCP sequencing queue,
2880 * and arranging for acknowledgement of receipt if necessary.
2881 * This process logically involves adjusting tp->rcv_wnd as data
2882 * is presented to the user (this happens in tcp_usrreq.c,
2883 * tcp_rcvd()). If a FIN has already been received on this
2884 * connection then we just ignore the text.
2885 */
2886 if ((tlen || (tiflags & TH_FIN)) &&
2887 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2888 /*
2889 * Insert segment ti into reassembly queue of tcp with
2890 * control block tp. Return TH_FIN if reassembly now includes
2891 * a segment with FIN. The macro form does the common case
2892 * inline (segment is the next to be received on an
2893 * established connection, and the queue is empty),
2894 * avoiding linkage into and removal from the queue and
2895 * repetition of various conversions.
2896 * Set DELACK for segments received in order, but ack
2897 * immediately when segments are out of order
2898 * (so fast retransmit can work).
2899 */
2900 /* NOTE: this was TCP_REASS() macro, but used only once */
2901 TCP_REASS_LOCK(tp);
2902 if (th->th_seq == tp->rcv_nxt &&
2903 TAILQ_FIRST(&tp->segq) == NULL &&
2904 tp->t_state == TCPS_ESTABLISHED) {
2905 tcp_setup_ack(tp, th);
2906 tp->rcv_nxt += tlen;
2907 tiflags = th->th_flags & TH_FIN;
2908 tcps = TCP_STAT_GETREF();
2909 tcps[TCP_STAT_RCVPACK]++;
2910 tcps[TCP_STAT_RCVBYTE] += tlen;
2911 TCP_STAT_PUTREF();
2912 nd6_hint(tp);
2913 if (so->so_state & SS_CANTRCVMORE)
2914 m_freem(m);
2915 else {
2916 m_adj(m, hdroptlen);
2917 sbappendstream(&(so)->so_rcv, m);
2918 }
2919 TCP_REASS_UNLOCK(tp);
2920 sorwakeup(so);
2921 } else {
2922 m_adj(m, hdroptlen);
2923 tiflags = tcp_reass(tp, th, m, &tlen);
2924 tp->t_flags |= TF_ACKNOW;
2925 }
2926
2927 /*
2928 * Note the amount of data that peer has sent into
2929 * our window, in order to estimate the sender's
2930 * buffer size.
2931 */
2932 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2933 } else {
2934 m_freem(m);
2935 m = NULL;
2936 tiflags &= ~TH_FIN;
2937 }
2938
2939 /*
2940 * If FIN is received ACK the FIN and let the user know
2941 * that the connection is closing. Ignore a FIN received before
2942 * the connection is fully established.
2943 */
2944 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2945 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2946 socantrcvmore(so);
2947 tp->t_flags |= TF_ACKNOW;
2948 tp->rcv_nxt++;
2949 }
2950 switch (tp->t_state) {
2951
2952 /*
2953 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2954 */
2955 case TCPS_ESTABLISHED:
2956 tp->t_state = TCPS_CLOSE_WAIT;
2957 break;
2958
2959 /*
2960 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2961 * enter the CLOSING state.
2962 */
2963 case TCPS_FIN_WAIT_1:
2964 tp->t_state = TCPS_CLOSING;
2965 break;
2966
2967 /*
2968 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2969 * starting the time-wait timer, turning off the other
2970 * standard timers.
2971 */
2972 case TCPS_FIN_WAIT_2:
2973 tp->t_state = TCPS_TIME_WAIT;
2974 tcp_canceltimers(tp);
2975 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2976 soisdisconnected(so);
2977 break;
2978
2979 /*
2980 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2981 */
2982 case TCPS_TIME_WAIT:
2983 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2984 break;
2985 }
2986 }
2987 #ifdef TCP_DEBUG
2988 if (so->so_options & SO_DEBUG)
2989 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2990 #endif
2991
2992 /*
2993 * Return any desired output.
2994 */
2995 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2996 KERNEL_LOCK(1, NULL);
2997 (void) tcp_output(tp);
2998 KERNEL_UNLOCK_ONE(NULL);
2999 }
3000 if (tcp_saveti)
3001 m_freem(tcp_saveti);
3002
3003 if (tp->t_state == TCPS_TIME_WAIT
3004 && (so->so_state & SS_NOFDREF)
3005 && (tp->t_inpcb || af != AF_INET)
3006 && (tp->t_in6pcb || af != AF_INET6)
3007 && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
3008 && TAILQ_EMPTY(&tp->segq)
3009 && vtw_add(af, tp)) {
3010 ;
3011 }
3012 return;
3013
3014 badsyn:
3015 /*
3016 * Received a bad SYN. Increment counters and dropwithreset.
3017 */
3018 TCP_STATINC(TCP_STAT_BADSYN);
3019 tp = NULL;
3020 goto dropwithreset;
3021
3022 dropafterack:
3023 /*
3024 * Generate an ACK dropping incoming segment if it occupies
3025 * sequence space, where the ACK reflects our state.
3026 */
3027 if (tiflags & TH_RST)
3028 goto drop;
3029 goto dropafterack2;
3030
3031 dropafterack_ratelim:
3032 /*
3033 * We may want to rate-limit ACKs against SYN/RST attack.
3034 */
3035 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
3036 tcp_ackdrop_ppslim) == 0) {
3037 /* XXX stat */
3038 goto drop;
3039 }
3040 /* ...fall into dropafterack2... */
3041
3042 dropafterack2:
3043 m_freem(m);
3044 tp->t_flags |= TF_ACKNOW;
3045 KERNEL_LOCK(1, NULL);
3046 (void) tcp_output(tp);
3047 KERNEL_UNLOCK_ONE(NULL);
3048 if (tcp_saveti)
3049 m_freem(tcp_saveti);
3050 return;
3051
3052 dropwithreset_ratelim:
3053 /*
3054 * We may want to rate-limit RSTs in certain situations,
3055 * particularly if we are sending an RST in response to
3056 * an attempt to connect to or otherwise communicate with
3057 * a port for which we have no socket.
3058 */
3059 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
3060 tcp_rst_ppslim) == 0) {
3061 /* XXX stat */
3062 goto drop;
3063 }
3064 /* ...fall into dropwithreset... */
3065
3066 dropwithreset:
3067 /*
3068 * Generate a RST, dropping incoming segment.
3069 * Make ACK acceptable to originator of segment.
3070 */
3071 if (tiflags & TH_RST)
3072 goto drop;
3073
3074 switch (af) {
3075 #ifdef INET6
3076 case AF_INET6:
3077 /* For following calls to tcp_respond */
3078 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
3079 goto drop;
3080 break;
3081 #endif /* INET6 */
3082 case AF_INET:
3083 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
3084 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
3085 goto drop;
3086 }
3087
3088 if (tiflags & TH_ACK)
3089 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3090 else {
3091 if (tiflags & TH_SYN)
3092 tlen++;
3093 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
3094 TH_RST|TH_ACK);
3095 }
3096 if (tcp_saveti)
3097 m_freem(tcp_saveti);
3098 return;
3099
3100 badcsum:
3101 drop:
3102 /*
3103 * Drop space held by incoming segment and return.
3104 */
3105 if (tp) {
3106 if (tp->t_inpcb)
3107 so = tp->t_inpcb->inp_socket;
3108 #ifdef INET6
3109 else if (tp->t_in6pcb)
3110 so = tp->t_in6pcb->in6p_socket;
3111 #endif
3112 else
3113 so = NULL;
3114 #ifdef TCP_DEBUG
3115 if (so && (so->so_options & SO_DEBUG) != 0)
3116 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
3117 #endif
3118 }
3119 if (tcp_saveti)
3120 m_freem(tcp_saveti);
3121 m_freem(m);
3122 return;
3123 }
3124
3125 #ifdef TCP_SIGNATURE
3126 int
3127 tcp_signature_apply(void *fstate, void *data, u_int len)
3128 {
3129
3130 MD5Update(fstate, (u_char *)data, len);
3131 return (0);
3132 }
3133
3134 struct secasvar *
3135 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
3136 {
3137 struct ip *ip;
3138 struct ip6_hdr *ip6;
3139
3140 ip = mtod(m, struct ip *);
3141 switch (ip->ip_v) {
3142 case 4:
3143 ip = mtod(m, struct ip *);
3144 ip6 = NULL;
3145 break;
3146 case 6:
3147 ip = NULL;
3148 ip6 = mtod(m, struct ip6_hdr *);
3149 break;
3150 default:
3151 return (NULL);
3152 }
3153
3154 #ifdef IPSEC
3155 if (ipsec_used) {
3156 union sockaddr_union dst;
3157 /* Extract the destination from the IP header in the mbuf. */
3158 memset(&dst, 0, sizeof(union sockaddr_union));
3159 if (ip != NULL) {
3160 dst.sa.sa_len = sizeof(struct sockaddr_in);
3161 dst.sa.sa_family = AF_INET;
3162 dst.sin.sin_addr = ip->ip_dst;
3163 } else {
3164 dst.sa.sa_len = sizeof(struct sockaddr_in6);
3165 dst.sa.sa_family = AF_INET6;
3166 dst.sin6.sin6_addr = ip6->ip6_dst;
3167 }
3168
3169 /*
3170 * Look up an SADB entry which matches the address of the peer.
3171 */
3172 return KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0);
3173 }
3174 return NULL;
3175 #else
3176 if (ip)
3177 return key_allocsa(AF_INET, (void *)&ip->ip_src,
3178 (void *)&ip->ip_dst, IPPROTO_TCP,
3179 htonl(TCP_SIG_SPI), 0, 0);
3180 else
3181 return key_allocsa(AF_INET6, (void *)&ip6->ip6_src,
3182 (void *)&ip6->ip6_dst, IPPROTO_TCP,
3183 htonl(TCP_SIG_SPI), 0, 0);
3184 #endif
3185 }
3186
3187 int
3188 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
3189 struct secasvar *sav, char *sig)
3190 {
3191 MD5_CTX ctx;
3192 struct ip *ip;
3193 struct ipovly *ipovly;
3194 #ifdef INET6
3195 struct ip6_hdr *ip6;
3196 struct ip6_hdr_pseudo ip6pseudo;
3197 #endif /* INET6 */
3198 struct ippseudo ippseudo;
3199 struct tcphdr th0;
3200 int l, tcphdrlen;
3201
3202 if (sav == NULL)
3203 return (-1);
3204
3205 tcphdrlen = th->th_off * 4;
3206
3207 switch (mtod(m, struct ip *)->ip_v) {
3208 case 4:
3209 MD5Init(&ctx);
3210 ip = mtod(m, struct ip *);
3211 memset(&ippseudo, 0, sizeof(ippseudo));
3212 ipovly = (struct ipovly *)ip;
3213 ippseudo.ippseudo_src = ipovly->ih_src;
3214 ippseudo.ippseudo_dst = ipovly->ih_dst;
3215 ippseudo.ippseudo_pad = 0;
3216 ippseudo.ippseudo_p = IPPROTO_TCP;
3217 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
3218 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
3219 break;
3220 #if INET6
3221 case 6:
3222 MD5Init(&ctx);
3223 ip6 = mtod(m, struct ip6_hdr *);
3224 memset(&ip6pseudo, 0, sizeof(ip6pseudo));
3225 ip6pseudo.ip6ph_src = ip6->ip6_src;
3226 in6_clearscope(&ip6pseudo.ip6ph_src);
3227 ip6pseudo.ip6ph_dst = ip6->ip6_dst;
3228 in6_clearscope(&ip6pseudo.ip6ph_dst);
3229 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
3230 ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
3231 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
3232 break;
3233 #endif /* INET6 */
3234 default:
3235 return (-1);
3236 }
3237
3238 th0 = *th;
3239 th0.th_sum = 0;
3240 MD5Update(&ctx, (char *)&th0, sizeof(th0));
3241
3242 l = m->m_pkthdr.len - thoff - tcphdrlen;
3243 if (l > 0)
3244 m_apply(m, thoff + tcphdrlen,
3245 m->m_pkthdr.len - thoff - tcphdrlen,
3246 tcp_signature_apply, &ctx);
3247
3248 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3249 MD5Final(sig, &ctx);
3250
3251 return (0);
3252 }
3253 #endif
3254
3255 /*
3256 * tcp_dooptions: parse and process tcp options.
3257 *
3258 * returns -1 if this segment should be dropped. (eg. wrong signature)
3259 * otherwise returns 0.
3260 */
3261
3262 static int
3263 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt,
3264 struct tcphdr *th,
3265 struct mbuf *m, int toff, struct tcp_opt_info *oi)
3266 {
3267 u_int16_t mss;
3268 int opt, optlen = 0;
3269 #ifdef TCP_SIGNATURE
3270 void *sigp = NULL;
3271 char sigbuf[TCP_SIGLEN];
3272 struct secasvar *sav = NULL;
3273 #endif
3274
3275 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
3276 opt = cp[0];
3277 if (opt == TCPOPT_EOL)
3278 break;
3279 if (opt == TCPOPT_NOP)
3280 optlen = 1;
3281 else {
3282 if (cnt < 2)
3283 break;
3284 optlen = cp[1];
3285 if (optlen < 2 || optlen > cnt)
3286 break;
3287 }
3288 switch (opt) {
3289
3290 default:
3291 continue;
3292
3293 case TCPOPT_MAXSEG:
3294 if (optlen != TCPOLEN_MAXSEG)
3295 continue;
3296 if (!(th->th_flags & TH_SYN))
3297 continue;
3298 if (TCPS_HAVERCVDSYN(tp->t_state))
3299 continue;
3300 bcopy(cp + 2, &mss, sizeof(mss));
3301 oi->maxseg = ntohs(mss);
3302 break;
3303
3304 case TCPOPT_WINDOW:
3305 if (optlen != TCPOLEN_WINDOW)
3306 continue;
3307 if (!(th->th_flags & TH_SYN))
3308 continue;
3309 if (TCPS_HAVERCVDSYN(tp->t_state))
3310 continue;
3311 tp->t_flags |= TF_RCVD_SCALE;
3312 tp->requested_s_scale = cp[2];
3313 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
3314 char buf[INET6_ADDRSTRLEN];
3315 struct ip *ip = mtod(m, struct ip *);
3316 #ifdef INET6
3317 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
3318 #endif
3319 if (ip)
3320 in_print(buf, sizeof(buf),
3321 &ip->ip_src);
3322 #ifdef INET6
3323 else if (ip6)
3324 in6_print(buf, sizeof(buf),
3325 &ip6->ip6_src);
3326 #endif
3327 else
3328 strlcpy(buf, "(unknown)", sizeof(buf));
3329 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
3330 "assuming %d\n",
3331 tp->requested_s_scale, buf,
3332 TCP_MAX_WINSHIFT);
3333 tp->requested_s_scale = TCP_MAX_WINSHIFT;
3334 }
3335 break;
3336
3337 case TCPOPT_TIMESTAMP:
3338 if (optlen != TCPOLEN_TIMESTAMP)
3339 continue;
3340 oi->ts_present = 1;
3341 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
3342 NTOHL(oi->ts_val);
3343 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
3344 NTOHL(oi->ts_ecr);
3345
3346 if (!(th->th_flags & TH_SYN))
3347 continue;
3348 if (TCPS_HAVERCVDSYN(tp->t_state))
3349 continue;
3350 /*
3351 * A timestamp received in a SYN makes
3352 * it ok to send timestamp requests and replies.
3353 */
3354 tp->t_flags |= TF_RCVD_TSTMP;
3355 tp->ts_recent = oi->ts_val;
3356 tp->ts_recent_age = tcp_now;
3357 break;
3358
3359 case TCPOPT_SACK_PERMITTED:
3360 if (optlen != TCPOLEN_SACK_PERMITTED)
3361 continue;
3362 if (!(th->th_flags & TH_SYN))
3363 continue;
3364 if (TCPS_HAVERCVDSYN(tp->t_state))
3365 continue;
3366 if (tcp_do_sack) {
3367 tp->t_flags |= TF_SACK_PERMIT;
3368 tp->t_flags |= TF_WILL_SACK;
3369 }
3370 break;
3371
3372 case TCPOPT_SACK:
3373 tcp_sack_option(tp, th, cp, optlen);
3374 break;
3375 #ifdef TCP_SIGNATURE
3376 case TCPOPT_SIGNATURE:
3377 if (optlen != TCPOLEN_SIGNATURE)
3378 continue;
3379 if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN))
3380 return (-1);
3381
3382 sigp = sigbuf;
3383 memcpy(sigbuf, cp + 2, TCP_SIGLEN);
3384 tp->t_flags |= TF_SIGNATURE;
3385 break;
3386 #endif
3387 }
3388 }
3389
3390 #ifndef TCP_SIGNATURE
3391 return 0;
3392 #else
3393 if (tp->t_flags & TF_SIGNATURE) {
3394
3395 sav = tcp_signature_getsav(m, th);
3396
3397 if (sav == NULL && tp->t_state == TCPS_LISTEN)
3398 return (-1);
3399 }
3400
3401 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE))
3402 goto out;
3403
3404 if (sigp) {
3405 char sig[TCP_SIGLEN];
3406
3407 tcp_fields_to_net(th);
3408 if (tcp_signature(m, th, toff, sav, sig) < 0) {
3409 tcp_fields_to_host(th);
3410 goto out;
3411 }
3412 tcp_fields_to_host(th);
3413
3414 if (memcmp(sig, sigp, TCP_SIGLEN)) {
3415 TCP_STATINC(TCP_STAT_BADSIG);
3416 goto out;
3417 } else
3418 TCP_STATINC(TCP_STAT_GOODSIG);
3419
3420 key_sa_recordxfer(sav, m);
3421 KEY_FREESAV(&sav);
3422 }
3423 return 0;
3424 out:
3425 if (sav != NULL)
3426 KEY_FREESAV(&sav);
3427 return -1;
3428 #endif
3429 }
3430
3431 /*
3432 * Pull out of band byte out of a segment so
3433 * it doesn't appear in the user's data queue.
3434 * It is still reflected in the segment length for
3435 * sequencing purposes.
3436 */
3437 void
3438 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3439 struct mbuf *m, int off)
3440 {
3441 int cnt = off + th->th_urp - 1;
3442
3443 while (cnt >= 0) {
3444 if (m->m_len > cnt) {
3445 char *cp = mtod(m, char *) + cnt;
3446 struct tcpcb *tp = sototcpcb(so);
3447
3448 tp->t_iobc = *cp;
3449 tp->t_oobflags |= TCPOOB_HAVEDATA;
3450 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3451 m->m_len--;
3452 return;
3453 }
3454 cnt -= m->m_len;
3455 m = m->m_next;
3456 if (m == 0)
3457 break;
3458 }
3459 panic("tcp_pulloutofband");
3460 }
3461
3462 /*
3463 * Collect new round-trip time estimate
3464 * and update averages and current timeout.
3465 *
3466 * rtt is in units of slow ticks (typically 500 ms) -- essentially the
3467 * difference of two timestamps.
3468 */
3469 void
3470 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3471 {
3472 int32_t delta;
3473
3474 TCP_STATINC(TCP_STAT_RTTUPDATED);
3475 if (tp->t_srtt != 0) {
3476 /*
3477 * Compute the amount to add to srtt for smoothing,
3478 * *alpha, or 2^(-TCP_RTT_SHIFT). Because
3479 * srtt is stored in 1/32 slow ticks, we conceptually
3480 * shift left 5 bits, subtract srtt to get the
3481 * diference, and then shift right by TCP_RTT_SHIFT
3482 * (3) to obtain 1/8 of the difference.
3483 */
3484 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3485 /*
3486 * This can never happen, because delta's lowest
3487 * possible value is 1/8 of t_srtt. But if it does,
3488 * set srtt to some reasonable value, here chosen
3489 * as 1/8 tick.
3490 */
3491 if ((tp->t_srtt += delta) <= 0)
3492 tp->t_srtt = 1 << 2;
3493 /*
3494 * RFC2988 requires that rttvar be updated first.
3495 * This code is compliant because "delta" is the old
3496 * srtt minus the new observation (scaled).
3497 *
3498 * RFC2988 says:
3499 * rttvar = (1-beta) * rttvar + beta * |srtt-observed|
3500 *
3501 * delta is in units of 1/32 ticks, and has then been
3502 * divided by 8. This is equivalent to being in 1/16s
3503 * units and divided by 4. Subtract from it 1/4 of
3504 * the existing rttvar to form the (signed) amount to
3505 * adjust.
3506 */
3507 if (delta < 0)
3508 delta = -delta;
3509 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3510 /*
3511 * As with srtt, this should never happen. There is
3512 * no support in RFC2988 for this operation. But 1/4s
3513 * as rttvar when faced with something arguably wrong
3514 * is ok.
3515 */
3516 if ((tp->t_rttvar += delta) <= 0)
3517 tp->t_rttvar = 1 << 2;
3518
3519 /*
3520 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
3521 * Problem is: it doesn't work. Disabled by defaulting
3522 * tcp_rttlocal to 0; see corresponding code in
3523 * tcp_subr that selects local vs remote in a different way.
3524 *
3525 * The static branch prediction hint here should be removed
3526 * when the rtt estimator is fixed and the rtt_enable code
3527 * is turned back on.
3528 */
3529 if (__predict_false(tcp_rttlocal) && tcp_msl_enable
3530 && tp->t_srtt > tcp_msl_remote_threshold
3531 && tp->t_msl < tcp_msl_remote) {
3532 tp->t_msl = tcp_msl_remote;
3533 }
3534 } else {
3535 /*
3536 * This is the first measurement. Per RFC2988, 2.2,
3537 * set rtt=R and srtt=R/2.
3538 * For srtt, storage representation is 1/32 ticks,
3539 * so shift left by 5.
3540 * For rttvar, storage representation is 1/16 ticks,
3541 * So shift left by 4, but then right by 1 to halve.
3542 */
3543 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3544 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3545 }
3546 tp->t_rtttime = 0;
3547 tp->t_rxtshift = 0;
3548
3549 /*
3550 * the retransmit should happen at rtt + 4 * rttvar.
3551 * Because of the way we do the smoothing, srtt and rttvar
3552 * will each average +1/2 tick of bias. When we compute
3553 * the retransmit timer, we want 1/2 tick of rounding and
3554 * 1 extra tick because of +-1/2 tick uncertainty in the
3555 * firing of the timer. The bias will give us exactly the
3556 * 1.5 tick we need. But, because the bias is
3557 * statistical, we have to test that we don't drop below
3558 * the minimum feasible timer (which is 2 ticks).
3559 */
3560 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3561 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3562
3563 /*
3564 * We received an ack for a packet that wasn't retransmitted;
3565 * it is probably safe to discard any error indications we've
3566 * received recently. This isn't quite right, but close enough
3567 * for now (a route might have failed after we sent a segment,
3568 * and the return path might not be symmetrical).
3569 */
3570 tp->t_softerror = 0;
3571 }
3572
3573
3574 /*
3575 * TCP compressed state engine. Currently used to hold compressed
3576 * state for SYN_RECEIVED.
3577 */
3578
3579 u_long syn_cache_count;
3580 u_int32_t syn_hash1, syn_hash2;
3581
3582 #define SYN_HASH(sa, sp, dp) \
3583 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3584 ((u_int32_t)(sp)))^syn_hash2)))
3585 #ifndef INET6
3586 #define SYN_HASHALL(hash, src, dst) \
3587 do { \
3588 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3589 ((const struct sockaddr_in *)(src))->sin_port, \
3590 ((const struct sockaddr_in *)(dst))->sin_port); \
3591 } while (/*CONSTCOND*/ 0)
3592 #else
3593 #define SYN_HASH6(sa, sp, dp) \
3594 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3595 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3596 & 0x7fffffff)
3597
3598 #define SYN_HASHALL(hash, src, dst) \
3599 do { \
3600 switch ((src)->sa_family) { \
3601 case AF_INET: \
3602 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3603 ((const struct sockaddr_in *)(src))->sin_port, \
3604 ((const struct sockaddr_in *)(dst))->sin_port); \
3605 break; \
3606 case AF_INET6: \
3607 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3608 ((const struct sockaddr_in6 *)(src))->sin6_port, \
3609 ((const struct sockaddr_in6 *)(dst))->sin6_port); \
3610 break; \
3611 default: \
3612 hash = 0; \
3613 } \
3614 } while (/*CONSTCOND*/0)
3615 #endif /* INET6 */
3616
3617 static struct pool syn_cache_pool;
3618
3619 /*
3620 * We don't estimate RTT with SYNs, so each packet starts with the default
3621 * RTT and each timer step has a fixed timeout value.
3622 */
3623 #define SYN_CACHE_TIMER_ARM(sc) \
3624 do { \
3625 TCPT_RANGESET((sc)->sc_rxtcur, \
3626 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \
3627 TCPTV_REXMTMAX); \
3628 callout_reset(&(sc)->sc_timer, \
3629 (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc)); \
3630 } while (/*CONSTCOND*/0)
3631
3632 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase)
3633
3634 static inline void
3635 syn_cache_rm(struct syn_cache *sc)
3636 {
3637 TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket,
3638 sc, sc_bucketq);
3639 sc->sc_tp = NULL;
3640 LIST_REMOVE(sc, sc_tpq);
3641 tcp_syn_cache[sc->sc_bucketidx].sch_length--;
3642 callout_stop(&sc->sc_timer);
3643 syn_cache_count--;
3644 }
3645
3646 static inline void
3647 syn_cache_put(struct syn_cache *sc)
3648 {
3649 if (sc->sc_ipopts)
3650 (void) m_free(sc->sc_ipopts);
3651 rtcache_free(&sc->sc_route);
3652 sc->sc_flags |= SCF_DEAD;
3653 if (!callout_invoking(&sc->sc_timer))
3654 callout_schedule(&(sc)->sc_timer, 1);
3655 }
3656
3657 void
3658 syn_cache_init(void)
3659 {
3660 int i;
3661
3662 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
3663 "synpl", NULL, IPL_SOFTNET);
3664
3665 /* Initialize the hash buckets. */
3666 for (i = 0; i < tcp_syn_cache_size; i++)
3667 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3668 }
3669
3670 void
3671 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3672 {
3673 struct syn_cache_head *scp;
3674 struct syn_cache *sc2;
3675 int s;
3676
3677 /*
3678 * If there are no entries in the hash table, reinitialize
3679 * the hash secrets.
3680 */
3681 if (syn_cache_count == 0) {
3682 syn_hash1 = cprng_fast32();
3683 syn_hash2 = cprng_fast32();
3684 }
3685
3686 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3687 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3688 scp = &tcp_syn_cache[sc->sc_bucketidx];
3689
3690 /*
3691 * Make sure that we don't overflow the per-bucket
3692 * limit or the total cache size limit.
3693 */
3694 s = splsoftnet();
3695 if (scp->sch_length >= tcp_syn_bucket_limit) {
3696 TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW);
3697 /*
3698 * The bucket is full. Toss the oldest element in the
3699 * bucket. This will be the first entry in the bucket.
3700 */
3701 sc2 = TAILQ_FIRST(&scp->sch_bucket);
3702 #ifdef DIAGNOSTIC
3703 /*
3704 * This should never happen; we should always find an
3705 * entry in our bucket.
3706 */
3707 if (sc2 == NULL)
3708 panic("syn_cache_insert: bucketoverflow: impossible");
3709 #endif
3710 syn_cache_rm(sc2);
3711 syn_cache_put(sc2); /* calls pool_put but see spl above */
3712 } else if (syn_cache_count >= tcp_syn_cache_limit) {
3713 struct syn_cache_head *scp2, *sce;
3714
3715 TCP_STATINC(TCP_STAT_SC_OVERFLOWED);
3716 /*
3717 * The cache is full. Toss the oldest entry in the
3718 * first non-empty bucket we can find.
3719 *
3720 * XXX We would really like to toss the oldest
3721 * entry in the cache, but we hope that this
3722 * condition doesn't happen very often.
3723 */
3724 scp2 = scp;
3725 if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3726 sce = &tcp_syn_cache[tcp_syn_cache_size];
3727 for (++scp2; scp2 != scp; scp2++) {
3728 if (scp2 >= sce)
3729 scp2 = &tcp_syn_cache[0];
3730 if (! TAILQ_EMPTY(&scp2->sch_bucket))
3731 break;
3732 }
3733 #ifdef DIAGNOSTIC
3734 /*
3735 * This should never happen; we should always find a
3736 * non-empty bucket.
3737 */
3738 if (scp2 == scp)
3739 panic("syn_cache_insert: cacheoverflow: "
3740 "impossible");
3741 #endif
3742 }
3743 sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3744 syn_cache_rm(sc2);
3745 syn_cache_put(sc2); /* calls pool_put but see spl above */
3746 }
3747
3748 /*
3749 * Initialize the entry's timer.
3750 */
3751 sc->sc_rxttot = 0;
3752 sc->sc_rxtshift = 0;
3753 SYN_CACHE_TIMER_ARM(sc);
3754
3755 /* Link it from tcpcb entry */
3756 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3757
3758 /* Put it into the bucket. */
3759 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3760 scp->sch_length++;
3761 syn_cache_count++;
3762
3763 TCP_STATINC(TCP_STAT_SC_ADDED);
3764 splx(s);
3765 }
3766
3767 /*
3768 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3769 * If we have retransmitted an entry the maximum number of times, expire
3770 * that entry.
3771 */
3772 void
3773 syn_cache_timer(void *arg)
3774 {
3775 struct syn_cache *sc = arg;
3776
3777 mutex_enter(softnet_lock);
3778 KERNEL_LOCK(1, NULL);
3779 callout_ack(&sc->sc_timer);
3780
3781 if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3782 TCP_STATINC(TCP_STAT_SC_DELAYED_FREE);
3783 callout_destroy(&sc->sc_timer);
3784 pool_put(&syn_cache_pool, sc);
3785 KERNEL_UNLOCK_ONE(NULL);
3786 mutex_exit(softnet_lock);
3787 return;
3788 }
3789
3790 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3791 /* Drop it -- too many retransmissions. */
3792 goto dropit;
3793 }
3794
3795 /*
3796 * Compute the total amount of time this entry has
3797 * been on a queue. If this entry has been on longer
3798 * than the keep alive timer would allow, expire it.
3799 */
3800 sc->sc_rxttot += sc->sc_rxtcur;
3801 if (sc->sc_rxttot >= tcp_keepinit)
3802 goto dropit;
3803
3804 TCP_STATINC(TCP_STAT_SC_RETRANSMITTED);
3805 (void) syn_cache_respond(sc, NULL);
3806
3807 /* Advance the timer back-off. */
3808 sc->sc_rxtshift++;
3809 SYN_CACHE_TIMER_ARM(sc);
3810
3811 KERNEL_UNLOCK_ONE(NULL);
3812 mutex_exit(softnet_lock);
3813 return;
3814
3815 dropit:
3816 TCP_STATINC(TCP_STAT_SC_TIMED_OUT);
3817 syn_cache_rm(sc);
3818 if (sc->sc_ipopts)
3819 (void) m_free(sc->sc_ipopts);
3820 rtcache_free(&sc->sc_route);
3821 callout_destroy(&sc->sc_timer);
3822 pool_put(&syn_cache_pool, sc);
3823 KERNEL_UNLOCK_ONE(NULL);
3824 mutex_exit(softnet_lock);
3825 }
3826
3827 /*
3828 * Remove syn cache created by the specified tcb entry,
3829 * because this does not make sense to keep them
3830 * (if there's no tcb entry, syn cache entry will never be used)
3831 */
3832 void
3833 syn_cache_cleanup(struct tcpcb *tp)
3834 {
3835 struct syn_cache *sc, *nsc;
3836 int s;
3837
3838 s = splsoftnet();
3839
3840 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3841 nsc = LIST_NEXT(sc, sc_tpq);
3842
3843 #ifdef DIAGNOSTIC
3844 if (sc->sc_tp != tp)
3845 panic("invalid sc_tp in syn_cache_cleanup");
3846 #endif
3847 syn_cache_rm(sc);
3848 syn_cache_put(sc); /* calls pool_put but see spl above */
3849 }
3850 /* just for safety */
3851 LIST_INIT(&tp->t_sc);
3852
3853 splx(s);
3854 }
3855
3856 /*
3857 * Find an entry in the syn cache.
3858 */
3859 struct syn_cache *
3860 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3861 struct syn_cache_head **headp)
3862 {
3863 struct syn_cache *sc;
3864 struct syn_cache_head *scp;
3865 u_int32_t hash;
3866 int s;
3867
3868 SYN_HASHALL(hash, src, dst);
3869
3870 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3871 *headp = scp;
3872 s = splsoftnet();
3873 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3874 sc = TAILQ_NEXT(sc, sc_bucketq)) {
3875 if (sc->sc_hash != hash)
3876 continue;
3877 if (!memcmp(&sc->sc_src, src, src->sa_len) &&
3878 !memcmp(&sc->sc_dst, dst, dst->sa_len)) {
3879 splx(s);
3880 return (sc);
3881 }
3882 }
3883 splx(s);
3884 return (NULL);
3885 }
3886
3887 /*
3888 * This function gets called when we receive an ACK for a
3889 * socket in the LISTEN state. We look up the connection
3890 * in the syn cache, and if its there, we pull it out of
3891 * the cache and turn it into a full-blown connection in
3892 * the SYN-RECEIVED state.
3893 *
3894 * The return values may not be immediately obvious, and their effects
3895 * can be subtle, so here they are:
3896 *
3897 * NULL SYN was not found in cache; caller should drop the
3898 * packet and send an RST.
3899 *
3900 * -1 We were unable to create the new connection, and are
3901 * aborting it. An ACK,RST is being sent to the peer
3902 * (unless we got screwey sequence numbners; see below),
3903 * because the 3-way handshake has been completed. Caller
3904 * should not free the mbuf, since we may be using it. If
3905 * we are not, we will free it.
3906 *
3907 * Otherwise, the return value is a pointer to the new socket
3908 * associated with the connection.
3909 */
3910 struct socket *
3911 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3912 struct tcphdr *th, unsigned int hlen, unsigned int tlen,
3913 struct socket *so, struct mbuf *m)
3914 {
3915 struct syn_cache *sc;
3916 struct syn_cache_head *scp;
3917 struct inpcb *inp = NULL;
3918 #ifdef INET6
3919 struct in6pcb *in6p = NULL;
3920 #endif
3921 struct tcpcb *tp = 0;
3922 int s;
3923 struct socket *oso;
3924
3925 s = splsoftnet();
3926 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3927 splx(s);
3928 return (NULL);
3929 }
3930
3931 /*
3932 * Verify the sequence and ack numbers. Try getting the correct
3933 * response again.
3934 */
3935 if ((th->th_ack != sc->sc_iss + 1) ||
3936 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3937 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3938 (void) syn_cache_respond(sc, m);
3939 splx(s);
3940 return ((struct socket *)(-1));
3941 }
3942
3943 /* Remove this cache entry */
3944 syn_cache_rm(sc);
3945 splx(s);
3946
3947 /*
3948 * Ok, create the full blown connection, and set things up
3949 * as they would have been set up if we had created the
3950 * connection when the SYN arrived. If we can't create
3951 * the connection, abort it.
3952 */
3953 /*
3954 * inp still has the OLD in_pcb stuff, set the
3955 * v6-related flags on the new guy, too. This is
3956 * done particularly for the case where an AF_INET6
3957 * socket is bound only to a port, and a v4 connection
3958 * comes in on that port.
3959 * we also copy the flowinfo from the original pcb
3960 * to the new one.
3961 */
3962 oso = so;
3963 so = sonewconn(so, true);
3964 if (so == NULL)
3965 goto resetandabort;
3966
3967 switch (so->so_proto->pr_domain->dom_family) {
3968 #ifdef INET
3969 case AF_INET:
3970 inp = sotoinpcb(so);
3971 break;
3972 #endif
3973 #ifdef INET6
3974 case AF_INET6:
3975 in6p = sotoin6pcb(so);
3976 break;
3977 #endif
3978 }
3979 switch (src->sa_family) {
3980 #ifdef INET
3981 case AF_INET:
3982 if (inp) {
3983 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3984 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3985 inp->inp_options = ip_srcroute();
3986 in_pcbstate(inp, INP_BOUND);
3987 if (inp->inp_options == NULL) {
3988 inp->inp_options = sc->sc_ipopts;
3989 sc->sc_ipopts = NULL;
3990 }
3991 }
3992 #ifdef INET6
3993 else if (in6p) {
3994 /* IPv4 packet to AF_INET6 socket */
3995 memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr));
3996 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3997 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3998 &in6p->in6p_laddr.s6_addr32[3],
3999 sizeof(((struct sockaddr_in *)dst)->sin_addr));
4000 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
4001 in6totcpcb(in6p)->t_family = AF_INET;
4002 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
4003 in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
4004 else
4005 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
4006 in6_pcbstate(in6p, IN6P_BOUND);
4007 }
4008 #endif
4009 break;
4010 #endif
4011 #ifdef INET6
4012 case AF_INET6:
4013 if (in6p) {
4014 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
4015 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
4016 in6_pcbstate(in6p, IN6P_BOUND);
4017 }
4018 break;
4019 #endif
4020 }
4021 #ifdef INET6
4022 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
4023 struct in6pcb *oin6p = sotoin6pcb(oso);
4024 /* inherit socket options from the listening socket */
4025 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
4026 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
4027 m_freem(in6p->in6p_options);
4028 in6p->in6p_options = 0;
4029 }
4030 ip6_savecontrol(in6p, &in6p->in6p_options,
4031 mtod(m, struct ip6_hdr *), m);
4032 }
4033 #endif
4034
4035 #if defined(IPSEC)
4036 if (ipsec_used) {
4037 /*
4038 * we make a copy of policy, instead of sharing the policy, for
4039 * better behavior in terms of SA lookup and dead SA removal.
4040 */
4041 if (inp) {
4042 /* copy old policy into new socket's */
4043 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp,
4044 inp->inp_sp))
4045 printf("tcp_input: could not copy policy\n");
4046 }
4047 #ifdef INET6
4048 else if (in6p) {
4049 /* copy old policy into new socket's */
4050 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
4051 in6p->in6p_sp))
4052 printf("tcp_input: could not copy policy\n");
4053 }
4054 #endif
4055 }
4056 #endif
4057
4058 /*
4059 * Give the new socket our cached route reference.
4060 */
4061 if (inp) {
4062 rtcache_copy(&inp->inp_route, &sc->sc_route);
4063 rtcache_free(&sc->sc_route);
4064 }
4065 #ifdef INET6
4066 else {
4067 rtcache_copy(&in6p->in6p_route, &sc->sc_route);
4068 rtcache_free(&sc->sc_route);
4069 }
4070 #endif
4071
4072 if (inp) {
4073 struct sockaddr_in sin;
4074 memcpy(&sin, src, src->sa_len);
4075 if (in_pcbconnect(inp, &sin, &lwp0)) {
4076 goto resetandabort;
4077 }
4078 }
4079 #ifdef INET6
4080 else if (in6p) {
4081 struct sockaddr_in6 sin6;
4082 memcpy(&sin6, src, src->sa_len);
4083 if (src->sa_family == AF_INET) {
4084 /* IPv4 packet to AF_INET6 socket */
4085 in6_sin_2_v4mapsin6((struct sockaddr_in *)src, &sin6);
4086 }
4087 if (in6_pcbconnect(in6p, &sin6, NULL)) {
4088 goto resetandabort;
4089 }
4090 }
4091 #endif
4092 else {
4093 goto resetandabort;
4094 }
4095
4096 if (inp)
4097 tp = intotcpcb(inp);
4098 #ifdef INET6
4099 else if (in6p)
4100 tp = in6totcpcb(in6p);
4101 #endif
4102 else
4103 tp = NULL;
4104 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
4105 if (sc->sc_request_r_scale != 15) {
4106 tp->requested_s_scale = sc->sc_requested_s_scale;
4107 tp->request_r_scale = sc->sc_request_r_scale;
4108 tp->snd_scale = sc->sc_requested_s_scale;
4109 tp->rcv_scale = sc->sc_request_r_scale;
4110 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
4111 }
4112 if (sc->sc_flags & SCF_TIMESTAMP)
4113 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
4114 tp->ts_timebase = sc->sc_timebase;
4115
4116 tp->t_template = tcp_template(tp);
4117 if (tp->t_template == 0) {
4118 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
4119 so = NULL;
4120 m_freem(m);
4121 goto abort;
4122 }
4123
4124 tp->iss = sc->sc_iss;
4125 tp->irs = sc->sc_irs;
4126 tcp_sendseqinit(tp);
4127 tcp_rcvseqinit(tp);
4128 tp->t_state = TCPS_SYN_RECEIVED;
4129 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit);
4130 TCP_STATINC(TCP_STAT_ACCEPTS);
4131
4132 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
4133 tp->t_flags |= TF_WILL_SACK;
4134
4135 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
4136 tp->t_flags |= TF_ECN_PERMIT;
4137
4138 #ifdef TCP_SIGNATURE
4139 if (sc->sc_flags & SCF_SIGNATURE)
4140 tp->t_flags |= TF_SIGNATURE;
4141 #endif
4142
4143 /* Initialize tp->t_ourmss before we deal with the peer's! */
4144 tp->t_ourmss = sc->sc_ourmaxseg;
4145 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
4146
4147 /*
4148 * Initialize the initial congestion window. If we
4149 * had to retransmit the SYN,ACK, we must initialize cwnd
4150 * to 1 segment (i.e. the Loss Window).
4151 */
4152 if (sc->sc_rxtshift)
4153 tp->snd_cwnd = tp->t_peermss;
4154 else {
4155 int ss = tcp_init_win;
4156 #ifdef INET
4157 if (inp != NULL && in_localaddr(inp->inp_faddr))
4158 ss = tcp_init_win_local;
4159 #endif
4160 #ifdef INET6
4161 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
4162 ss = tcp_init_win_local;
4163 #endif
4164 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
4165 }
4166
4167 tcp_rmx_rtt(tp);
4168 tp->snd_wl1 = sc->sc_irs;
4169 tp->rcv_up = sc->sc_irs + 1;
4170
4171 /*
4172 * This is what whould have happened in tcp_output() when
4173 * the SYN,ACK was sent.
4174 */
4175 tp->snd_up = tp->snd_una;
4176 tp->snd_max = tp->snd_nxt = tp->iss+1;
4177 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
4178 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
4179 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
4180 tp->last_ack_sent = tp->rcv_nxt;
4181 tp->t_partialacks = -1;
4182 tp->t_dupacks = 0;
4183
4184 TCP_STATINC(TCP_STAT_SC_COMPLETED);
4185 s = splsoftnet();
4186 syn_cache_put(sc);
4187 splx(s);
4188 return (so);
4189
4190 resetandabort:
4191 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
4192 abort:
4193 if (so != NULL) {
4194 (void) soqremque(so, 1);
4195 (void) soabort(so);
4196 mutex_enter(softnet_lock);
4197 }
4198 s = splsoftnet();
4199 syn_cache_put(sc);
4200 splx(s);
4201 TCP_STATINC(TCP_STAT_SC_ABORTED);
4202 return ((struct socket *)(-1));
4203 }
4204
4205 /*
4206 * This function is called when we get a RST for a
4207 * non-existent connection, so that we can see if the
4208 * connection is in the syn cache. If it is, zap it.
4209 */
4210
4211 void
4212 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
4213 {
4214 struct syn_cache *sc;
4215 struct syn_cache_head *scp;
4216 int s = splsoftnet();
4217
4218 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4219 splx(s);
4220 return;
4221 }
4222 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
4223 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
4224 splx(s);
4225 return;
4226 }
4227 syn_cache_rm(sc);
4228 TCP_STATINC(TCP_STAT_SC_RESET);
4229 syn_cache_put(sc); /* calls pool_put but see spl above */
4230 splx(s);
4231 }
4232
4233 void
4234 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
4235 struct tcphdr *th)
4236 {
4237 struct syn_cache *sc;
4238 struct syn_cache_head *scp;
4239 int s;
4240
4241 s = splsoftnet();
4242 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4243 splx(s);
4244 return;
4245 }
4246 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
4247 if (ntohl (th->th_seq) != sc->sc_iss) {
4248 splx(s);
4249 return;
4250 }
4251
4252 /*
4253 * If we've retransmitted 3 times and this is our second error,
4254 * we remove the entry. Otherwise, we allow it to continue on.
4255 * This prevents us from incorrectly nuking an entry during a
4256 * spurious network outage.
4257 *
4258 * See tcp_notify().
4259 */
4260 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
4261 sc->sc_flags |= SCF_UNREACH;
4262 splx(s);
4263 return;
4264 }
4265
4266 syn_cache_rm(sc);
4267 TCP_STATINC(TCP_STAT_SC_UNREACH);
4268 syn_cache_put(sc); /* calls pool_put but see spl above */
4269 splx(s);
4270 }
4271
4272 /*
4273 * Given a LISTEN socket and an inbound SYN request, add
4274 * this to the syn cache, and send back a segment:
4275 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
4276 * to the source.
4277 *
4278 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
4279 * Doing so would require that we hold onto the data and deliver it
4280 * to the application. However, if we are the target of a SYN-flood
4281 * DoS attack, an attacker could send data which would eventually
4282 * consume all available buffer space if it were ACKed. By not ACKing
4283 * the data, we avoid this DoS scenario.
4284 */
4285
4286 int
4287 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
4288 unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
4289 int optlen, struct tcp_opt_info *oi)
4290 {
4291 struct tcpcb tb, *tp;
4292 long win;
4293 struct syn_cache *sc;
4294 struct syn_cache_head *scp;
4295 struct mbuf *ipopts;
4296 struct tcp_opt_info opti;
4297 int s;
4298
4299 tp = sototcpcb(so);
4300
4301 memset(&opti, 0, sizeof(opti));
4302
4303 /*
4304 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
4305 *
4306 * Note this check is performed in tcp_input() very early on.
4307 */
4308
4309 /*
4310 * Initialize some local state.
4311 */
4312 win = sbspace(&so->so_rcv);
4313 if (win > TCP_MAXWIN)
4314 win = TCP_MAXWIN;
4315
4316 switch (src->sa_family) {
4317 #ifdef INET
4318 case AF_INET:
4319 /*
4320 * Remember the IP options, if any.
4321 */
4322 ipopts = ip_srcroute();
4323 break;
4324 #endif
4325 default:
4326 ipopts = NULL;
4327 }
4328
4329 #ifdef TCP_SIGNATURE
4330 if (optp || (tp->t_flags & TF_SIGNATURE))
4331 #else
4332 if (optp)
4333 #endif
4334 {
4335 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
4336 #ifdef TCP_SIGNATURE
4337 tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
4338 #endif
4339 tb.t_state = TCPS_LISTEN;
4340 if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
4341 sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
4342 return (0);
4343 } else
4344 tb.t_flags = 0;
4345
4346 /*
4347 * See if we already have an entry for this connection.
4348 * If we do, resend the SYN,ACK. We do not count this
4349 * as a retransmission (XXX though maybe we should).
4350 */
4351 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
4352 TCP_STATINC(TCP_STAT_SC_DUPESYN);
4353 if (ipopts) {
4354 /*
4355 * If we were remembering a previous source route,
4356 * forget it and use the new one we've been given.
4357 */
4358 if (sc->sc_ipopts)
4359 (void) m_free(sc->sc_ipopts);
4360 sc->sc_ipopts = ipopts;
4361 }
4362 sc->sc_timestamp = tb.ts_recent;
4363 if (syn_cache_respond(sc, m) == 0) {
4364 uint64_t *tcps = TCP_STAT_GETREF();
4365 tcps[TCP_STAT_SNDACKS]++;
4366 tcps[TCP_STAT_SNDTOTAL]++;
4367 TCP_STAT_PUTREF();
4368 }
4369 return (1);
4370 }
4371
4372 s = splsoftnet();
4373 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
4374 splx(s);
4375 if (sc == NULL) {
4376 if (ipopts)
4377 (void) m_free(ipopts);
4378 return (0);
4379 }
4380
4381 /*
4382 * Fill in the cache, and put the necessary IP and TCP
4383 * options into the reply.
4384 */
4385 memset(sc, 0, sizeof(struct syn_cache));
4386 callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
4387 bcopy(src, &sc->sc_src, src->sa_len);
4388 bcopy(dst, &sc->sc_dst, dst->sa_len);
4389 sc->sc_flags = 0;
4390 sc->sc_ipopts = ipopts;
4391 sc->sc_irs = th->th_seq;
4392 switch (src->sa_family) {
4393 #ifdef INET
4394 case AF_INET:
4395 {
4396 struct sockaddr_in *srcin = (void *) src;
4397 struct sockaddr_in *dstin = (void *) dst;
4398
4399 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
4400 &srcin->sin_addr, dstin->sin_port,
4401 srcin->sin_port, sizeof(dstin->sin_addr), 0);
4402 break;
4403 }
4404 #endif /* INET */
4405 #ifdef INET6
4406 case AF_INET6:
4407 {
4408 struct sockaddr_in6 *srcin6 = (void *) src;
4409 struct sockaddr_in6 *dstin6 = (void *) dst;
4410
4411 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
4412 &srcin6->sin6_addr, dstin6->sin6_port,
4413 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
4414 break;
4415 }
4416 #endif /* INET6 */
4417 }
4418 sc->sc_peermaxseg = oi->maxseg;
4419 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
4420 m->m_pkthdr.rcvif : NULL,
4421 sc->sc_src.sa.sa_family);
4422 sc->sc_win = win;
4423 sc->sc_timebase = tcp_now - 1; /* see tcp_newtcpcb() */
4424 sc->sc_timestamp = tb.ts_recent;
4425 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
4426 (TF_REQ_TSTMP|TF_RCVD_TSTMP))
4427 sc->sc_flags |= SCF_TIMESTAMP;
4428 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
4429 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
4430 sc->sc_requested_s_scale = tb.requested_s_scale;
4431 sc->sc_request_r_scale = 0;
4432 /*
4433 * Pick the smallest possible scaling factor that
4434 * will still allow us to scale up to sb_max.
4435 *
4436 * We do this because there are broken firewalls that
4437 * will corrupt the window scale option, leading to
4438 * the other endpoint believing that our advertised
4439 * window is unscaled. At scale factors larger than
4440 * 5 the unscaled window will drop below 1500 bytes,
4441 * leading to serious problems when traversing these
4442 * broken firewalls.
4443 *
4444 * With the default sbmax of 256K, a scale factor
4445 * of 3 will be chosen by this algorithm. Those who
4446 * choose a larger sbmax should watch out
4447 * for the compatiblity problems mentioned above.
4448 *
4449 * RFC1323: The Window field in a SYN (i.e., a <SYN>
4450 * or <SYN,ACK>) segment itself is never scaled.
4451 */
4452 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
4453 (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max)
4454 sc->sc_request_r_scale++;
4455 } else {
4456 sc->sc_requested_s_scale = 15;
4457 sc->sc_request_r_scale = 15;
4458 }
4459 if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
4460 sc->sc_flags |= SCF_SACK_PERMIT;
4461
4462 /*
4463 * ECN setup packet recieved.
4464 */
4465 if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn)
4466 sc->sc_flags |= SCF_ECN_PERMIT;
4467
4468 #ifdef TCP_SIGNATURE
4469 if (tb.t_flags & TF_SIGNATURE)
4470 sc->sc_flags |= SCF_SIGNATURE;
4471 #endif
4472 sc->sc_tp = tp;
4473 if (syn_cache_respond(sc, m) == 0) {
4474 uint64_t *tcps = TCP_STAT_GETREF();
4475 tcps[TCP_STAT_SNDACKS]++;
4476 tcps[TCP_STAT_SNDTOTAL]++;
4477 TCP_STAT_PUTREF();
4478 syn_cache_insert(sc, tp);
4479 } else {
4480 s = splsoftnet();
4481 /*
4482 * syn_cache_put() will try to schedule the timer, so
4483 * we need to initialize it
4484 */
4485 SYN_CACHE_TIMER_ARM(sc);
4486 syn_cache_put(sc);
4487 splx(s);
4488 TCP_STATINC(TCP_STAT_SC_DROPPED);
4489 }
4490 return (1);
4491 }
4492
4493 /*
4494 * syn_cache_respond: (re)send SYN+ACK.
4495 *
4496 * returns 0 on success. otherwise returns an errno, typically ENOBUFS.
4497 */
4498
4499 int
4500 syn_cache_respond(struct syn_cache *sc, struct mbuf *m)
4501 {
4502 #ifdef INET6
4503 struct rtentry *rt;
4504 #endif
4505 struct route *ro;
4506 u_int8_t *optp;
4507 int optlen, error;
4508 u_int16_t tlen;
4509 struct ip *ip = NULL;
4510 #ifdef INET6
4511 struct ip6_hdr *ip6 = NULL;
4512 #endif
4513 struct tcpcb *tp = NULL;
4514 struct tcphdr *th;
4515 u_int hlen;
4516 struct socket *so;
4517
4518 ro = &sc->sc_route;
4519 switch (sc->sc_src.sa.sa_family) {
4520 case AF_INET:
4521 hlen = sizeof(struct ip);
4522 break;
4523 #ifdef INET6
4524 case AF_INET6:
4525 hlen = sizeof(struct ip6_hdr);
4526 break;
4527 #endif
4528 default:
4529 if (m)
4530 m_freem(m);
4531 return (EAFNOSUPPORT);
4532 }
4533
4534 /* Compute the size of the TCP options. */
4535 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
4536 ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) +
4537 #ifdef TCP_SIGNATURE
4538 ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
4539 #endif
4540 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
4541
4542 tlen = hlen + sizeof(struct tcphdr) + optlen;
4543
4544 /*
4545 * Create the IP+TCP header from scratch.
4546 */
4547 if (m)
4548 m_freem(m);
4549 #ifdef DIAGNOSTIC
4550 if (max_linkhdr + tlen > MCLBYTES)
4551 return (ENOBUFS);
4552 #endif
4553 MGETHDR(m, M_DONTWAIT, MT_DATA);
4554 if (m && (max_linkhdr + tlen) > MHLEN) {
4555 MCLGET(m, M_DONTWAIT);
4556 if ((m->m_flags & M_EXT) == 0) {
4557 m_freem(m);
4558 m = NULL;
4559 }
4560 }
4561 if (m == NULL)
4562 return (ENOBUFS);
4563 MCLAIM(m, &tcp_tx_mowner);
4564
4565 /* Fixup the mbuf. */
4566 m->m_data += max_linkhdr;
4567 m->m_len = m->m_pkthdr.len = tlen;
4568 if (sc->sc_tp) {
4569 tp = sc->sc_tp;
4570 if (tp->t_inpcb)
4571 so = tp->t_inpcb->inp_socket;
4572 #ifdef INET6
4573 else if (tp->t_in6pcb)
4574 so = tp->t_in6pcb->in6p_socket;
4575 #endif
4576 else
4577 so = NULL;
4578 } else
4579 so = NULL;
4580 m_reset_rcvif(m);
4581 memset(mtod(m, u_char *), 0, tlen);
4582
4583 switch (sc->sc_src.sa.sa_family) {
4584 case AF_INET:
4585 ip = mtod(m, struct ip *);
4586 ip->ip_v = 4;
4587 ip->ip_dst = sc->sc_src.sin.sin_addr;
4588 ip->ip_src = sc->sc_dst.sin.sin_addr;
4589 ip->ip_p = IPPROTO_TCP;
4590 th = (struct tcphdr *)(ip + 1);
4591 th->th_dport = sc->sc_src.sin.sin_port;
4592 th->th_sport = sc->sc_dst.sin.sin_port;
4593 break;
4594 #ifdef INET6
4595 case AF_INET6:
4596 ip6 = mtod(m, struct ip6_hdr *);
4597 ip6->ip6_vfc = IPV6_VERSION;
4598 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4599 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4600 ip6->ip6_nxt = IPPROTO_TCP;
4601 /* ip6_plen will be updated in ip6_output() */
4602 th = (struct tcphdr *)(ip6 + 1);
4603 th->th_dport = sc->sc_src.sin6.sin6_port;
4604 th->th_sport = sc->sc_dst.sin6.sin6_port;
4605 break;
4606 #endif
4607 default:
4608 th = NULL;
4609 }
4610
4611 th->th_seq = htonl(sc->sc_iss);
4612 th->th_ack = htonl(sc->sc_irs + 1);
4613 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4614 th->th_flags = TH_SYN|TH_ACK;
4615 th->th_win = htons(sc->sc_win);
4616 /* th_sum already 0 */
4617 /* th_urp already 0 */
4618
4619 /* Tack on the TCP options. */
4620 optp = (u_int8_t *)(th + 1);
4621 *optp++ = TCPOPT_MAXSEG;
4622 *optp++ = 4;
4623 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4624 *optp++ = sc->sc_ourmaxseg & 0xff;
4625
4626 if (sc->sc_request_r_scale != 15) {
4627 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4628 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4629 sc->sc_request_r_scale);
4630 optp += 4;
4631 }
4632
4633 if (sc->sc_flags & SCF_TIMESTAMP) {
4634 u_int32_t *lp = (u_int32_t *)(optp);
4635 /* Form timestamp option as shown in appendix A of RFC 1323. */
4636 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
4637 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4638 *lp = htonl(sc->sc_timestamp);
4639 optp += TCPOLEN_TSTAMP_APPA;
4640 }
4641
4642 if (sc->sc_flags & SCF_SACK_PERMIT) {
4643 u_int8_t *p = optp;
4644
4645 /* Let the peer know that we will SACK. */
4646 p[0] = TCPOPT_SACK_PERMITTED;
4647 p[1] = 2;
4648 p[2] = TCPOPT_NOP;
4649 p[3] = TCPOPT_NOP;
4650 optp += 4;
4651 }
4652
4653 /*
4654 * Send ECN SYN-ACK setup packet.
4655 * Routes can be asymetric, so, even if we receive a packet
4656 * with ECE and CWR set, we must not assume no one will block
4657 * the ECE packet we are about to send.
4658 */
4659 if ((sc->sc_flags & SCF_ECN_PERMIT) && tp &&
4660 SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
4661 th->th_flags |= TH_ECE;
4662 TCP_STATINC(TCP_STAT_ECN_SHS);
4663
4664 /*
4665 * draft-ietf-tcpm-ecnsyn-00.txt
4666 *
4667 * "[...] a TCP node MAY respond to an ECN-setup
4668 * SYN packet by setting ECT in the responding
4669 * ECN-setup SYN/ACK packet, indicating to routers
4670 * that the SYN/ACK packet is ECN-Capable.
4671 * This allows a congested router along the path
4672 * to mark the packet instead of dropping the
4673 * packet as an indication of congestion."
4674 *
4675 * "[...] There can be a great benefit in setting
4676 * an ECN-capable codepoint in SYN/ACK packets [...]
4677 * Congestion is most likely to occur in
4678 * the server-to-client direction. As a result,
4679 * setting an ECN-capable codepoint in SYN/ACK
4680 * packets can reduce the occurence of three-second
4681 * retransmit timeouts resulting from the drop
4682 * of SYN/ACK packets."
4683 *
4684 * Page 4 and 6, January 2006.
4685 */
4686
4687 switch (sc->sc_src.sa.sa_family) {
4688 #ifdef INET
4689 case AF_INET:
4690 ip->ip_tos |= IPTOS_ECN_ECT0;
4691 break;
4692 #endif
4693 #ifdef INET6
4694 case AF_INET6:
4695 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
4696 break;
4697 #endif
4698 }
4699 TCP_STATINC(TCP_STAT_ECN_ECT);
4700 }
4701
4702 #ifdef TCP_SIGNATURE
4703 if (sc->sc_flags & SCF_SIGNATURE) {
4704 struct secasvar *sav;
4705 u_int8_t *sigp;
4706
4707 sav = tcp_signature_getsav(m, th);
4708
4709 if (sav == NULL) {
4710 if (m)
4711 m_freem(m);
4712 return (EPERM);
4713 }
4714
4715 *optp++ = TCPOPT_SIGNATURE;
4716 *optp++ = TCPOLEN_SIGNATURE;
4717 sigp = optp;
4718 memset(optp, 0, TCP_SIGLEN);
4719 optp += TCP_SIGLEN;
4720 *optp++ = TCPOPT_NOP;
4721 *optp++ = TCPOPT_EOL;
4722
4723 (void)tcp_signature(m, th, hlen, sav, sigp);
4724
4725 key_sa_recordxfer(sav, m);
4726 KEY_FREESAV(&sav);
4727 }
4728 #endif
4729
4730 /* Compute the packet's checksum. */
4731 switch (sc->sc_src.sa.sa_family) {
4732 case AF_INET:
4733 ip->ip_len = htons(tlen - hlen);
4734 th->th_sum = 0;
4735 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4736 break;
4737 #ifdef INET6
4738 case AF_INET6:
4739 ip6->ip6_plen = htons(tlen - hlen);
4740 th->th_sum = 0;
4741 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4742 break;
4743 #endif
4744 }
4745
4746 /*
4747 * Fill in some straggling IP bits. Note the stack expects
4748 * ip_len to be in host order, for convenience.
4749 */
4750 switch (sc->sc_src.sa.sa_family) {
4751 #ifdef INET
4752 case AF_INET:
4753 ip->ip_len = htons(tlen);
4754 ip->ip_ttl = ip_defttl;
4755 /* XXX tos? */
4756 break;
4757 #endif
4758 #ifdef INET6
4759 case AF_INET6:
4760 ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4761 ip6->ip6_vfc |= IPV6_VERSION;
4762 ip6->ip6_plen = htons(tlen - hlen);
4763 /* ip6_hlim will be initialized afterwards */
4764 /* XXX flowlabel? */
4765 break;
4766 #endif
4767 }
4768
4769 /* XXX use IPsec policy on listening socket, on SYN ACK */
4770 tp = sc->sc_tp;
4771
4772 switch (sc->sc_src.sa.sa_family) {
4773 #ifdef INET
4774 case AF_INET:
4775 error = ip_output(m, sc->sc_ipopts, ro,
4776 (ip_mtudisc ? IP_MTUDISC : 0),
4777 NULL, so);
4778 break;
4779 #endif
4780 #ifdef INET6
4781 case AF_INET6:
4782 ip6->ip6_hlim = in6_selecthlim(NULL,
4783 (rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp : NULL);
4784
4785 error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL, so, NULL);
4786 break;
4787 #endif
4788 default:
4789 error = EAFNOSUPPORT;
4790 break;
4791 }
4792 return (error);
4793 }
4794