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