tcp_input.c revision 1.377 1 /* $NetBSD: tcp_input.c,v 1.377 2018/02/12 08:08:28 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.377 2018/02/12 08:08:28 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)
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 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1298 in_broadcast(ip->ip_dst, m_get_rcvif_NOMPSAFE(m)))
1299 goto drop;
1300
1301 /* We do the checksum after PCB lookup... */
1302 len = ntohs(ip->ip_len);
1303 tlen = len - toff;
1304 iptos = ip->ip_tos;
1305 break;
1306 #endif
1307 #ifdef INET6
1308 case 6:
1309 ip = NULL;
1310 iphlen = sizeof(struct ip6_hdr);
1311 af = AF_INET6;
1312 ip6 = mtod(m, struct ip6_hdr *);
1313
1314 /*
1315 * Be proactive about unspecified IPv6 address in source.
1316 * As we use all-zero to indicate unbounded/unconnected pcb,
1317 * unspecified IPv6 address can be used to confuse us.
1318 *
1319 * Note that packets with unspecified IPv6 destination is
1320 * already dropped in ip6_input.
1321 */
1322 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1323 /* XXX stat */
1324 goto drop;
1325 }
1326
1327 /*
1328 * Make sure destination address is not multicast.
1329 * Source address checked in ip6_input().
1330 */
1331 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1332 /* XXX stat */
1333 goto drop;
1334 }
1335
1336 /* We do the checksum after PCB lookup... */
1337 len = m->m_pkthdr.len;
1338 tlen = len - toff;
1339 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1340 break;
1341 #endif
1342 default:
1343 m_freem(m);
1344 return;
1345 }
1346
1347 /*
1348 * Enforce alignment requirements that are violated in
1349 * some cases, see kern/50766 for details.
1350 */
1351 if (TCP_HDR_ALIGNED_P(th) == 0) {
1352 m = m_copyup(m, toff + sizeof(struct tcphdr), 0);
1353 if (m == NULL) {
1354 TCP_STATINC(TCP_STAT_RCVSHORT);
1355 return;
1356 }
1357 ip = mtod(m, struct ip *);
1358 #ifdef INET6
1359 ip6 = mtod(m, struct ip6_hdr *);
1360 #endif
1361 th = (struct tcphdr *)(mtod(m, char *) + toff);
1362 }
1363 KASSERT(TCP_HDR_ALIGNED_P(th));
1364
1365 /*
1366 * Check that TCP offset makes sense, pull out TCP options and
1367 * adjust length.
1368 */
1369 off = th->th_off << 2;
1370 if (off < sizeof(struct tcphdr) || off > tlen) {
1371 TCP_STATINC(TCP_STAT_RCVBADOFF);
1372 goto drop;
1373 }
1374 tlen -= off;
1375
1376 if (off > sizeof(struct tcphdr)) {
1377 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
1378 if (th == NULL) {
1379 TCP_STATINC(TCP_STAT_RCVSHORT);
1380 return;
1381 }
1382 KASSERT(TCP_HDR_ALIGNED_P(th));
1383 optlen = off - sizeof(struct tcphdr);
1384 optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1385 /*
1386 * Do quick retrieval of timestamp options ("options
1387 * prediction?"). If timestamp is the only option and it's
1388 * formatted as recommended in RFC 1323 appendix A, we
1389 * quickly get the values now and not bother calling
1390 * tcp_dooptions(), etc.
1391 */
1392 if ((optlen == TCPOLEN_TSTAMP_APPA ||
1393 (optlen > TCPOLEN_TSTAMP_APPA &&
1394 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1395 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1396 (th->th_flags & TH_SYN) == 0) {
1397 opti.ts_present = 1;
1398 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1399 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1400 optp = NULL; /* we've parsed the options */
1401 }
1402 }
1403 tiflags = th->th_flags;
1404
1405 /*
1406 * Checksum extended TCP header and data
1407 */
1408 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1409 goto badcsum;
1410
1411 /*
1412 * Locate pcb for segment.
1413 */
1414 findpcb:
1415 inp = NULL;
1416 #ifdef INET6
1417 in6p = NULL;
1418 #endif
1419 switch (af) {
1420 #ifdef INET
1421 case AF_INET:
1422 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1423 ip->ip_dst, th->th_dport, &vestige);
1424 if (inp == NULL && !vestige.valid) {
1425 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1426 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst,
1427 th->th_dport);
1428 }
1429 #ifdef INET6
1430 if (inp == NULL && !vestige.valid) {
1431 struct in6_addr s, d;
1432
1433 /* mapped addr case */
1434 in6_in_2_v4mapin6(&ip->ip_src, &s);
1435 in6_in_2_v4mapin6(&ip->ip_dst, &d);
1436 in6p = in6_pcblookup_connect(&tcbtable, &s,
1437 th->th_sport, &d, th->th_dport, 0, &vestige);
1438 if (in6p == 0 && !vestige.valid) {
1439 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1440 in6p = in6_pcblookup_bind(&tcbtable, &d,
1441 th->th_dport, 0);
1442 }
1443 }
1444 #endif
1445 #ifndef INET6
1446 if (inp == NULL && !vestige.valid)
1447 #else
1448 if (inp == NULL && in6p == NULL && !vestige.valid)
1449 #endif
1450 {
1451 TCP_STATINC(TCP_STAT_NOPORT);
1452 if (tcp_log_refused &&
1453 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1454 tcp4_log_refused(ip, th);
1455 }
1456 tcp_fields_to_host(th);
1457 goto dropwithreset_ratelim;
1458 }
1459 #if defined(IPSEC)
1460 if (ipsec_used) {
1461 if (inp &&
1462 (inp->inp_socket->so_options & SO_ACCEPTCONN) == 0
1463 && ipsec4_in_reject(m, inp)) {
1464 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1465 goto drop;
1466 }
1467 #ifdef INET6
1468 else if (in6p &&
1469 (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0
1470 && ipsec6_in_reject(m, in6p)) {
1471 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1472 goto drop;
1473 }
1474 #endif
1475 }
1476 #endif /*IPSEC*/
1477 break;
1478 #endif /*INET*/
1479 #ifdef INET6
1480 case AF_INET6:
1481 {
1482 int faith;
1483
1484 #if defined(NFAITH) && NFAITH > 0
1485 faith = faithprefix(&ip6->ip6_dst);
1486 #else
1487 faith = 0;
1488 #endif
1489 in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1490 th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
1491 if (!in6p && !vestige.valid) {
1492 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1493 in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1494 th->th_dport, faith);
1495 }
1496 if (!in6p && !vestige.valid) {
1497 TCP_STATINC(TCP_STAT_NOPORT);
1498 if (tcp_log_refused &&
1499 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1500 tcp6_log_refused(ip6, th);
1501 }
1502 tcp_fields_to_host(th);
1503 goto dropwithreset_ratelim;
1504 }
1505 #if defined(IPSEC)
1506 if (ipsec_used && in6p &&
1507 (in6p->in6p_socket->so_options & SO_ACCEPTCONN) == 0 &&
1508 ipsec6_in_reject(m, in6p)) {
1509 IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
1510 goto drop;
1511 }
1512 #endif /*IPSEC*/
1513 break;
1514 }
1515 #endif
1516 }
1517
1518 /*
1519 * If the state is CLOSED (i.e., TCB does not exist) then
1520 * all data in the incoming segment is discarded.
1521 * If the TCB exists but is in CLOSED state, it is embryonic,
1522 * but should either do a listen or a connect soon.
1523 */
1524 tp = NULL;
1525 so = NULL;
1526 if (inp) {
1527 /* Check the minimum TTL for socket. */
1528 if (ip->ip_ttl < inp->inp_ip_minttl)
1529 goto drop;
1530
1531 tp = intotcpcb(inp);
1532 so = inp->inp_socket;
1533 }
1534 #ifdef INET6
1535 else if (in6p) {
1536 tp = in6totcpcb(in6p);
1537 so = in6p->in6p_socket;
1538 }
1539 #endif
1540 else if (vestige.valid) {
1541 /* We do not support the resurrection of vtw tcpcps. */
1542 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1543 goto badcsum;
1544
1545 tcp_fields_to_host(th);
1546 tcp_vtw_input(th, &vestige, m, tlen);
1547 m = NULL;
1548 goto drop;
1549 }
1550
1551 if (tp == NULL) {
1552 tcp_fields_to_host(th);
1553 goto dropwithreset_ratelim;
1554 }
1555 if (tp->t_state == TCPS_CLOSED)
1556 goto drop;
1557
1558 KASSERT(so->so_lock == softnet_lock);
1559 KASSERT(solocked(so));
1560
1561 tcp_fields_to_host(th);
1562
1563 /* Unscale the window into a 32-bit value. */
1564 if ((tiflags & TH_SYN) == 0)
1565 tiwin = th->th_win << tp->snd_scale;
1566 else
1567 tiwin = th->th_win;
1568
1569 #ifdef INET6
1570 /* save packet options if user wanted */
1571 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1572 if (in6p->in6p_options) {
1573 m_freem(in6p->in6p_options);
1574 in6p->in6p_options = NULL;
1575 }
1576 KASSERT(ip6 != NULL);
1577 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1578 }
1579 #endif
1580
1581 if (so->so_options & SO_DEBUG) {
1582 #ifdef TCP_DEBUG
1583 ostate = tp->t_state;
1584 #endif
1585
1586 tcp_saveti = NULL;
1587 if (iphlen + sizeof(struct tcphdr) > MHLEN)
1588 goto nosave;
1589
1590 if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1591 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1592 if (tcp_saveti == NULL)
1593 goto nosave;
1594 } else {
1595 MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1596 if (tcp_saveti == NULL)
1597 goto nosave;
1598 MCLAIM(m, &tcp_mowner);
1599 tcp_saveti->m_len = iphlen;
1600 m_copydata(m, 0, iphlen,
1601 mtod(tcp_saveti, void *));
1602 }
1603
1604 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1605 m_freem(tcp_saveti);
1606 tcp_saveti = NULL;
1607 } else {
1608 tcp_saveti->m_len += sizeof(struct tcphdr);
1609 memcpy(mtod(tcp_saveti, char *) + iphlen, th,
1610 sizeof(struct tcphdr));
1611 }
1612 nosave:;
1613 }
1614
1615 if (so->so_options & SO_ACCEPTCONN) {
1616 union syn_cache_sa src;
1617 union syn_cache_sa dst;
1618
1619 memset(&src, 0, sizeof(src));
1620 memset(&dst, 0, sizeof(dst));
1621 switch (af) {
1622 #ifdef INET
1623 case AF_INET:
1624 src.sin.sin_len = sizeof(struct sockaddr_in);
1625 src.sin.sin_family = AF_INET;
1626 src.sin.sin_addr = ip->ip_src;
1627 src.sin.sin_port = th->th_sport;
1628
1629 dst.sin.sin_len = sizeof(struct sockaddr_in);
1630 dst.sin.sin_family = AF_INET;
1631 dst.sin.sin_addr = ip->ip_dst;
1632 dst.sin.sin_port = th->th_dport;
1633 break;
1634 #endif
1635 #ifdef INET6
1636 case AF_INET6:
1637 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1638 src.sin6.sin6_family = AF_INET6;
1639 src.sin6.sin6_addr = ip6->ip6_src;
1640 src.sin6.sin6_port = th->th_sport;
1641
1642 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1643 dst.sin6.sin6_family = AF_INET6;
1644 dst.sin6.sin6_addr = ip6->ip6_dst;
1645 dst.sin6.sin6_port = th->th_dport;
1646 break;
1647 #endif /* INET6 */
1648 }
1649
1650 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1651 if (tiflags & TH_RST) {
1652 syn_cache_reset(&src.sa, &dst.sa, th);
1653 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
1654 (TH_ACK|TH_SYN)) {
1655 /*
1656 * Received a SYN,ACK. This should never
1657 * happen while we are in LISTEN. Send an RST.
1658 */
1659 goto badsyn;
1660 } else if (tiflags & TH_ACK) {
1661 so = syn_cache_get(&src.sa, &dst.sa,
1662 th, toff, tlen, so, m);
1663 if (so == NULL) {
1664 /*
1665 * We don't have a SYN for this ACK;
1666 * send an RST.
1667 */
1668 goto badsyn;
1669 } else if (so == (struct socket *)(-1)) {
1670 /*
1671 * We were unable to create the
1672 * connection. If the 3-way handshake
1673 * was completed, and RST has been
1674 * sent to the peer. Since the mbuf
1675 * might be in use for the reply, do
1676 * not free it.
1677 */
1678 m = NULL;
1679 } else {
1680 /*
1681 * We have created a full-blown
1682 * connection.
1683 */
1684 tp = NULL;
1685 inp = NULL;
1686 #ifdef INET6
1687 in6p = NULL;
1688 #endif
1689 switch (so->so_proto->pr_domain->dom_family) {
1690 #ifdef INET
1691 case AF_INET:
1692 inp = sotoinpcb(so);
1693 tp = intotcpcb(inp);
1694 break;
1695 #endif
1696 #ifdef INET6
1697 case AF_INET6:
1698 in6p = sotoin6pcb(so);
1699 tp = in6totcpcb(in6p);
1700 break;
1701 #endif
1702 }
1703 if (tp == NULL)
1704 goto badsyn; /*XXX*/
1705 tiwin <<= tp->snd_scale;
1706 goto after_listen;
1707 }
1708 } else {
1709 /*
1710 * None of RST, SYN or ACK was set.
1711 * This is an invalid packet for a
1712 * TCB in LISTEN state. Send a RST.
1713 */
1714 goto badsyn;
1715 }
1716 } else {
1717 /*
1718 * Received a SYN.
1719 */
1720
1721 #ifdef INET6
1722 /*
1723 * If deprecated address is forbidden, we do
1724 * not accept SYN to deprecated interface
1725 * address to prevent any new inbound
1726 * connection from getting established.
1727 * When we do not accept SYN, we send a TCP
1728 * RST, with deprecated source address (instead
1729 * of dropping it). We compromise it as it is
1730 * much better for peer to send a RST, and
1731 * RST will be the final packet for the
1732 * exchange.
1733 *
1734 * If we do not forbid deprecated addresses, we
1735 * accept the SYN packet. RFC2462 does not
1736 * suggest dropping SYN in this case.
1737 * If we decipher RFC2462 5.5.4, it says like
1738 * this:
1739 * 1. use of deprecated addr with existing
1740 * communication is okay - "SHOULD continue
1741 * to be used"
1742 * 2. use of it with new communication:
1743 * (2a) "SHOULD NOT be used if alternate
1744 * address with sufficient scope is
1745 * available"
1746 * (2b) nothing mentioned otherwise.
1747 * Here we fall into (2b) case as we have no
1748 * choice in our source address selection - we
1749 * must obey the peer.
1750 *
1751 * The wording in RFC2462 is confusing, and
1752 * there are multiple description text for
1753 * deprecated address handling - worse, they
1754 * are not exactly the same. I believe 5.5.4
1755 * is the best one, so we follow 5.5.4.
1756 */
1757 if (af == AF_INET6 && !ip6_use_deprecated) {
1758 struct in6_ifaddr *ia6;
1759 int s;
1760 struct ifnet *rcvif = m_get_rcvif(m, &s);
1761 if (rcvif == NULL)
1762 goto dropwithreset; /* XXX */
1763 if ((ia6 = in6ifa_ifpwithaddr(rcvif,
1764 &ip6->ip6_dst)) &&
1765 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1766 tp = NULL;
1767 m_put_rcvif(rcvif, &s);
1768 goto dropwithreset;
1769 }
1770 m_put_rcvif(rcvif, &s);
1771 }
1772 #endif
1773
1774 #if defined(IPSEC)
1775 if (ipsec_used) {
1776 switch (af) {
1777 #ifdef INET
1778 case AF_INET:
1779 /*
1780 * inp can be NULL when receiving an
1781 * IPv4 packet on an IPv4-mapped IPv6
1782 * address.
1783 */
1784 KASSERT(inp == NULL ||
1785 sotoinpcb(so) == inp);
1786 if (!ipsec4_in_reject(m, inp))
1787 break;
1788 IPSEC_STATINC(IPSEC_STAT_IN_POLVIO);
1789 tp = NULL;
1790 goto dropwithreset;
1791 #endif
1792 #ifdef INET6
1793 case AF_INET6:
1794 KASSERT(sotoin6pcb(so) == in6p);
1795 if (!ipsec6_in_reject(m, in6p))
1796 break;
1797 IPSEC6_STATINC(IPSEC_STAT_IN_POLVIO);
1798 tp = NULL;
1799 goto dropwithreset;
1800 #endif /*INET6*/
1801 }
1802 }
1803 #endif /*IPSEC*/
1804
1805 /*
1806 * LISTEN socket received a SYN from itself? This
1807 * can't possibly be valid; drop the packet.
1808 */
1809 if (th->th_sport == th->th_dport) {
1810 int eq = 0;
1811
1812 switch (af) {
1813 #ifdef INET
1814 case AF_INET:
1815 eq = in_hosteq(ip->ip_src, ip->ip_dst);
1816 break;
1817 #endif
1818 #ifdef INET6
1819 case AF_INET6:
1820 eq = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src,
1821 &ip6->ip6_dst);
1822 break;
1823 #endif
1824 }
1825 if (eq) {
1826 TCP_STATINC(TCP_STAT_BADSYN);
1827 goto drop;
1828 }
1829 }
1830
1831 /*
1832 * SYN looks ok; create compressed TCP
1833 * state for it.
1834 */
1835 if (so->so_qlen <= so->so_qlimit &&
1836 syn_cache_add(&src.sa, &dst.sa, th, tlen,
1837 so, m, optp, optlen, &opti))
1838 m = NULL;
1839 }
1840
1841 goto drop;
1842 }
1843
1844 after_listen:
1845 /*
1846 * Should not happen now that all embryonic connections
1847 * are handled with compressed state.
1848 */
1849 KASSERT(tp->t_state != TCPS_LISTEN);
1850
1851 /*
1852 * Segment received on connection.
1853 * Reset idle time and keep-alive timer.
1854 */
1855 tp->t_rcvtime = tcp_now;
1856 if (TCPS_HAVEESTABLISHED(tp->t_state))
1857 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
1858
1859 /*
1860 * Process options.
1861 */
1862 #ifdef TCP_SIGNATURE
1863 if (optp || (tp->t_flags & TF_SIGNATURE))
1864 #else
1865 if (optp)
1866 #endif
1867 if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1868 goto drop;
1869
1870 if (TCP_SACK_ENABLED(tp)) {
1871 tcp_del_sackholes(tp, th);
1872 }
1873
1874 if (TCP_ECN_ALLOWED(tp)) {
1875 if (tiflags & TH_CWR) {
1876 tp->t_flags &= ~TF_ECN_SND_ECE;
1877 }
1878 switch (iptos & IPTOS_ECN_MASK) {
1879 case IPTOS_ECN_CE:
1880 tp->t_flags |= TF_ECN_SND_ECE;
1881 TCP_STATINC(TCP_STAT_ECN_CE);
1882 break;
1883 case IPTOS_ECN_ECT0:
1884 TCP_STATINC(TCP_STAT_ECN_ECT);
1885 break;
1886 case IPTOS_ECN_ECT1:
1887 /* XXX: ignore for now -- rpaulo */
1888 break;
1889 }
1890 /*
1891 * Congestion experienced.
1892 * Ignore if we are already trying to recover.
1893 */
1894 if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
1895 tp->t_congctl->cong_exp(tp);
1896 }
1897
1898 if (opti.ts_present && opti.ts_ecr) {
1899 /*
1900 * Calculate the RTT from the returned time stamp and the
1901 * connection's time base. If the time stamp is later than
1902 * the current time, or is extremely old, fall back to non-1323
1903 * RTT calculation. Since ts_rtt is unsigned, we can test both
1904 * at the same time.
1905 *
1906 * Note that ts_rtt is in units of slow ticks (500
1907 * ms). Since most earthbound RTTs are < 500 ms,
1908 * observed values will have large quantization noise.
1909 * Our smoothed RTT is then the fraction of observed
1910 * samples that are 1 tick instead of 0 (times 500
1911 * ms).
1912 *
1913 * ts_rtt is increased by 1 to denote a valid sample,
1914 * with 0 indicating an invalid measurement. This
1915 * extra 1 must be removed when ts_rtt is used, or
1916 * else an an erroneous extra 500 ms will result.
1917 */
1918 ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1919 if (ts_rtt > TCP_PAWS_IDLE)
1920 ts_rtt = 0;
1921 } else {
1922 ts_rtt = 0;
1923 }
1924
1925 /*
1926 * Header prediction: check for the two common cases
1927 * of a uni-directional data xfer. If the packet has
1928 * no control flags, is in-sequence, the window didn't
1929 * change and we're not retransmitting, it's a
1930 * candidate. If the length is zero and the ack moved
1931 * forward, we're the sender side of the xfer. Just
1932 * free the data acked & wake any higher level process
1933 * that was blocked waiting for space. If the length
1934 * is non-zero and the ack didn't move, we're the
1935 * receiver side. If we're getting packets in-order
1936 * (the reassembly queue is empty), add the data to
1937 * the socket buffer and note that we need a delayed ack.
1938 */
1939 if (tp->t_state == TCPS_ESTABLISHED &&
1940 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
1941 == TH_ACK &&
1942 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1943 th->th_seq == tp->rcv_nxt &&
1944 tiwin && tiwin == tp->snd_wnd &&
1945 tp->snd_nxt == tp->snd_max) {
1946
1947 /*
1948 * If last ACK falls within this segment's sequence numbers,
1949 * record the timestamp.
1950 * NOTE that the test is modified according to the latest
1951 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
1952 *
1953 * note that we already know
1954 * TSTMP_GEQ(opti.ts_val, tp->ts_recent)
1955 */
1956 if (opti.ts_present &&
1957 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1958 tp->ts_recent_age = tcp_now;
1959 tp->ts_recent = opti.ts_val;
1960 }
1961
1962 if (tlen == 0) {
1963 /* Ack prediction. */
1964 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1965 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1966 tp->snd_cwnd >= tp->snd_wnd &&
1967 tp->t_partialacks < 0) {
1968 /*
1969 * this is a pure ack for outstanding data.
1970 */
1971 if (ts_rtt)
1972 tcp_xmit_timer(tp, ts_rtt - 1);
1973 else if (tp->t_rtttime &&
1974 SEQ_GT(th->th_ack, tp->t_rtseq))
1975 tcp_xmit_timer(tp,
1976 tcp_now - tp->t_rtttime);
1977 acked = th->th_ack - tp->snd_una;
1978 tcps = TCP_STAT_GETREF();
1979 tcps[TCP_STAT_PREDACK]++;
1980 tcps[TCP_STAT_RCVACKPACK]++;
1981 tcps[TCP_STAT_RCVACKBYTE] += acked;
1982 TCP_STAT_PUTREF();
1983 nd6_hint(tp);
1984
1985 if (acked > (tp->t_lastoff - tp->t_inoff))
1986 tp->t_lastm = NULL;
1987 sbdrop(&so->so_snd, acked);
1988 tp->t_lastoff -= acked;
1989
1990 icmp_check(tp, th, acked);
1991
1992 tp->snd_una = th->th_ack;
1993 tp->snd_fack = tp->snd_una;
1994 if (SEQ_LT(tp->snd_high, tp->snd_una))
1995 tp->snd_high = tp->snd_una;
1996 m_freem(m);
1997
1998 /*
1999 * If all outstanding data are acked, stop
2000 * retransmit timer, otherwise restart timer
2001 * using current (possibly backed-off) value.
2002 * If process is waiting for space,
2003 * wakeup/selnotify/signal. If data
2004 * are ready to send, let tcp_output
2005 * decide between more output or persist.
2006 */
2007 if (tp->snd_una == tp->snd_max)
2008 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2009 else if (TCP_TIMER_ISARMED(tp,
2010 TCPT_PERSIST) == 0)
2011 TCP_TIMER_ARM(tp, TCPT_REXMT,
2012 tp->t_rxtcur);
2013
2014 sowwakeup(so);
2015 if (so->so_snd.sb_cc) {
2016 KERNEL_LOCK(1, NULL);
2017 (void) tcp_output(tp);
2018 KERNEL_UNLOCK_ONE(NULL);
2019 }
2020 if (tcp_saveti)
2021 m_freem(tcp_saveti);
2022 return;
2023 }
2024 } else if (th->th_ack == tp->snd_una &&
2025 TAILQ_FIRST(&tp->segq) == NULL &&
2026 tlen <= sbspace(&so->so_rcv)) {
2027 int newsize = 0; /* automatic sockbuf scaling */
2028
2029 /*
2030 * this is a pure, in-sequence data packet
2031 * with nothing on the reassembly queue and
2032 * we have enough buffer space to take it.
2033 */
2034 tp->rcv_nxt += tlen;
2035 tcps = TCP_STAT_GETREF();
2036 tcps[TCP_STAT_PREDDAT]++;
2037 tcps[TCP_STAT_RCVPACK]++;
2038 tcps[TCP_STAT_RCVBYTE] += tlen;
2039 TCP_STAT_PUTREF();
2040 nd6_hint(tp);
2041
2042 /*
2043 * Automatic sizing enables the performance of large buffers
2044 * and most of the efficiency of small ones by only allocating
2045 * space when it is needed.
2046 *
2047 * On the receive side the socket buffer memory is only rarely
2048 * used to any significant extent. This allows us to be much
2049 * more aggressive in scaling the receive socket buffer. For
2050 * the case that the buffer space is actually used to a large
2051 * extent and we run out of kernel memory we can simply drop
2052 * the new segments; TCP on the sender will just retransmit it
2053 * later. Setting the buffer size too big may only consume too
2054 * much kernel memory if the application doesn't read() from
2055 * the socket or packet loss or reordering makes use of the
2056 * reassembly queue.
2057 *
2058 * The criteria to step up the receive buffer one notch are:
2059 * 1. the number of bytes received during the time it takes
2060 * one timestamp to be reflected back to us (the RTT);
2061 * 2. received bytes per RTT is within seven eighth of the
2062 * current socket buffer size;
2063 * 3. receive buffer size has not hit maximal automatic size;
2064 *
2065 * This algorithm does one step per RTT at most and only if
2066 * we receive a bulk stream w/o packet losses or reorderings.
2067 * Shrinking the buffer during idle times is not necessary as
2068 * it doesn't consume any memory when idle.
2069 *
2070 * TODO: Only step up if the application is actually serving
2071 * the buffer to better manage the socket buffer resources.
2072 */
2073 if (tcp_do_autorcvbuf &&
2074 opti.ts_ecr &&
2075 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
2076 if (opti.ts_ecr > tp->rfbuf_ts &&
2077 opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
2078 if (tp->rfbuf_cnt >
2079 (so->so_rcv.sb_hiwat / 8 * 7) &&
2080 so->so_rcv.sb_hiwat <
2081 tcp_autorcvbuf_max) {
2082 newsize =
2083 min(so->so_rcv.sb_hiwat +
2084 tcp_autorcvbuf_inc,
2085 tcp_autorcvbuf_max);
2086 }
2087 /* Start over with next RTT. */
2088 tp->rfbuf_ts = 0;
2089 tp->rfbuf_cnt = 0;
2090 } else
2091 tp->rfbuf_cnt += tlen; /* add up */
2092 }
2093
2094 /*
2095 * Drop TCP, IP headers and TCP options then add data
2096 * to socket buffer.
2097 */
2098 if (so->so_state & SS_CANTRCVMORE)
2099 m_freem(m);
2100 else {
2101 /*
2102 * Set new socket buffer size.
2103 * Give up when limit is reached.
2104 */
2105 if (newsize)
2106 if (!sbreserve(&so->so_rcv,
2107 newsize, so))
2108 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
2109 m_adj(m, toff + off);
2110 sbappendstream(&so->so_rcv, m);
2111 }
2112 sorwakeup(so);
2113 tcp_setup_ack(tp, th);
2114 if (tp->t_flags & TF_ACKNOW) {
2115 KERNEL_LOCK(1, NULL);
2116 (void) tcp_output(tp);
2117 KERNEL_UNLOCK_ONE(NULL);
2118 }
2119 if (tcp_saveti)
2120 m_freem(tcp_saveti);
2121 return;
2122 }
2123 }
2124
2125 /*
2126 * Compute mbuf offset to TCP data segment.
2127 */
2128 hdroptlen = toff + off;
2129
2130 /*
2131 * Calculate amount of space in receive window,
2132 * and then do TCP input processing.
2133 * Receive window is amount of space in rcv queue,
2134 * but not less than advertised window.
2135 */
2136 { int win;
2137
2138 win = sbspace(&so->so_rcv);
2139 if (win < 0)
2140 win = 0;
2141 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
2142 }
2143
2144 /* Reset receive buffer auto scaling when not in bulk receive mode. */
2145 tp->rfbuf_ts = 0;
2146 tp->rfbuf_cnt = 0;
2147
2148 switch (tp->t_state) {
2149 /*
2150 * If the state is SYN_SENT:
2151 * if seg contains an ACK, but not for our SYN, drop the input.
2152 * if seg contains a RST, then drop the connection.
2153 * if seg does not contain SYN, then drop it.
2154 * Otherwise this is an acceptable SYN segment
2155 * initialize tp->rcv_nxt and tp->irs
2156 * if seg contains ack then advance tp->snd_una
2157 * if seg contains a ECE and ECN support is enabled, the stream
2158 * is ECN capable.
2159 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2160 * arrange for segment to be acked (eventually)
2161 * continue processing rest of data/controls, beginning with URG
2162 */
2163 case TCPS_SYN_SENT:
2164 if ((tiflags & TH_ACK) &&
2165 (SEQ_LEQ(th->th_ack, tp->iss) ||
2166 SEQ_GT(th->th_ack, tp->snd_max)))
2167 goto dropwithreset;
2168 if (tiflags & TH_RST) {
2169 if (tiflags & TH_ACK)
2170 tp = tcp_drop(tp, ECONNREFUSED);
2171 goto drop;
2172 }
2173 if ((tiflags & TH_SYN) == 0)
2174 goto drop;
2175 if (tiflags & TH_ACK) {
2176 tp->snd_una = th->th_ack;
2177 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2178 tp->snd_nxt = tp->snd_una;
2179 if (SEQ_LT(tp->snd_high, tp->snd_una))
2180 tp->snd_high = tp->snd_una;
2181 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2182
2183 if ((tiflags & TH_ECE) && tcp_do_ecn) {
2184 tp->t_flags |= TF_ECN_PERMIT;
2185 TCP_STATINC(TCP_STAT_ECN_SHS);
2186 }
2187
2188 }
2189 tp->irs = th->th_seq;
2190 tcp_rcvseqinit(tp);
2191 tp->t_flags |= TF_ACKNOW;
2192 tcp_mss_from_peer(tp, opti.maxseg);
2193
2194 /*
2195 * Initialize the initial congestion window. If we
2196 * had to retransmit the SYN, we must initialize cwnd
2197 * to 1 segment (i.e. the Loss Window).
2198 */
2199 if (tp->t_flags & TF_SYN_REXMT)
2200 tp->snd_cwnd = tp->t_peermss;
2201 else {
2202 int ss = tcp_init_win;
2203 #ifdef INET
2204 if (inp != NULL && in_localaddr(inp->inp_faddr))
2205 ss = tcp_init_win_local;
2206 #endif
2207 #ifdef INET6
2208 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
2209 ss = tcp_init_win_local;
2210 #endif
2211 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
2212 }
2213
2214 tcp_rmx_rtt(tp);
2215 if (tiflags & TH_ACK) {
2216 TCP_STATINC(TCP_STAT_CONNECTS);
2217 /*
2218 * move tcp_established before soisconnected
2219 * because upcall handler can drive tcp_output
2220 * functionality.
2221 * XXX we might call soisconnected at the end of
2222 * all processing
2223 */
2224 tcp_established(tp);
2225 soisconnected(so);
2226 /* Do window scaling on this connection? */
2227 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2228 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2229 tp->snd_scale = tp->requested_s_scale;
2230 tp->rcv_scale = tp->request_r_scale;
2231 }
2232 TCP_REASS_LOCK(tp);
2233 (void) tcp_reass(tp, NULL, NULL, &tlen);
2234 /*
2235 * if we didn't have to retransmit the SYN,
2236 * use its rtt as our initial srtt & rtt var.
2237 */
2238 if (tp->t_rtttime)
2239 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2240 } else
2241 tp->t_state = TCPS_SYN_RECEIVED;
2242
2243 /*
2244 * Advance th->th_seq to correspond to first data byte.
2245 * If data, trim to stay within window,
2246 * dropping FIN if necessary.
2247 */
2248 th->th_seq++;
2249 if (tlen > tp->rcv_wnd) {
2250 todrop = tlen - tp->rcv_wnd;
2251 m_adj(m, -todrop);
2252 tlen = tp->rcv_wnd;
2253 tiflags &= ~TH_FIN;
2254 tcps = TCP_STAT_GETREF();
2255 tcps[TCP_STAT_RCVPACKAFTERWIN]++;
2256 tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
2257 TCP_STAT_PUTREF();
2258 }
2259 tp->snd_wl1 = th->th_seq - 1;
2260 tp->rcv_up = th->th_seq;
2261 goto step6;
2262
2263 /*
2264 * If the state is SYN_RECEIVED:
2265 * If seg contains an ACK, but not for our SYN, drop the input
2266 * and generate an RST. See page 36, rfc793
2267 */
2268 case TCPS_SYN_RECEIVED:
2269 if ((tiflags & TH_ACK) &&
2270 (SEQ_LEQ(th->th_ack, tp->iss) ||
2271 SEQ_GT(th->th_ack, tp->snd_max)))
2272 goto dropwithreset;
2273 break;
2274 }
2275
2276 /*
2277 * States other than LISTEN or SYN_SENT.
2278 * First check timestamp, if present.
2279 * Then check that at least some bytes of segment are within
2280 * receive window. If segment begins before rcv_nxt,
2281 * drop leading data (and SYN); if nothing left, just ack.
2282 *
2283 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2284 * and it's less than ts_recent, drop it.
2285 */
2286 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
2287 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
2288
2289 /* Check to see if ts_recent is over 24 days old. */
2290 if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
2291 /*
2292 * Invalidate ts_recent. If this segment updates
2293 * ts_recent, the age will be reset later and ts_recent
2294 * will get a valid value. If it does not, setting
2295 * ts_recent to zero will at least satisfy the
2296 * requirement that zero be placed in the timestamp
2297 * echo reply when ts_recent isn't valid. The
2298 * age isn't reset until we get a valid ts_recent
2299 * because we don't want out-of-order segments to be
2300 * dropped when ts_recent is old.
2301 */
2302 tp->ts_recent = 0;
2303 } else {
2304 tcps = TCP_STAT_GETREF();
2305 tcps[TCP_STAT_RCVDUPPACK]++;
2306 tcps[TCP_STAT_RCVDUPBYTE] += tlen;
2307 tcps[TCP_STAT_PAWSDROP]++;
2308 TCP_STAT_PUTREF();
2309 tcp_new_dsack(tp, th->th_seq, tlen);
2310 goto dropafterack;
2311 }
2312 }
2313
2314 todrop = tp->rcv_nxt - th->th_seq;
2315 dupseg = false;
2316 if (todrop > 0) {
2317 if (tiflags & TH_SYN) {
2318 tiflags &= ~TH_SYN;
2319 th->th_seq++;
2320 if (th->th_urp > 1)
2321 th->th_urp--;
2322 else {
2323 tiflags &= ~TH_URG;
2324 th->th_urp = 0;
2325 }
2326 todrop--;
2327 }
2328 if (todrop > tlen ||
2329 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
2330 /*
2331 * Any valid FIN or RST must be to the left of the
2332 * window. At this point the FIN or RST must be a
2333 * duplicate or out of sequence; drop it.
2334 */
2335 if (tiflags & TH_RST)
2336 goto drop;
2337 tiflags &= ~(TH_FIN|TH_RST);
2338 /*
2339 * Send an ACK to resynchronize and drop any data.
2340 * But keep on processing for RST or ACK.
2341 */
2342 tp->t_flags |= TF_ACKNOW;
2343 todrop = tlen;
2344 dupseg = true;
2345 tcps = TCP_STAT_GETREF();
2346 tcps[TCP_STAT_RCVDUPPACK]++;
2347 tcps[TCP_STAT_RCVDUPBYTE] += todrop;
2348 TCP_STAT_PUTREF();
2349 } else if ((tiflags & TH_RST) &&
2350 th->th_seq != tp->rcv_nxt) {
2351 /*
2352 * Test for reset before adjusting the sequence
2353 * number for overlapping data.
2354 */
2355 goto dropafterack_ratelim;
2356 } else {
2357 tcps = TCP_STAT_GETREF();
2358 tcps[TCP_STAT_RCVPARTDUPPACK]++;
2359 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
2360 TCP_STAT_PUTREF();
2361 }
2362 tcp_new_dsack(tp, th->th_seq, todrop);
2363 hdroptlen += todrop; /*drop from head afterwards*/
2364 th->th_seq += todrop;
2365 tlen -= todrop;
2366 if (th->th_urp > todrop)
2367 th->th_urp -= todrop;
2368 else {
2369 tiflags &= ~TH_URG;
2370 th->th_urp = 0;
2371 }
2372 }
2373
2374 /*
2375 * If new data are received on a connection after the
2376 * user processes are gone, then RST the other end.
2377 */
2378 if ((so->so_state & SS_NOFDREF) &&
2379 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2380 tp = tcp_close(tp);
2381 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
2382 goto dropwithreset;
2383 }
2384
2385 /*
2386 * If segment ends after window, drop trailing data
2387 * (and PUSH and FIN); if nothing left, just ACK.
2388 */
2389 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
2390 if (todrop > 0) {
2391 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
2392 if (todrop >= tlen) {
2393 /*
2394 * The segment actually starts after the window.
2395 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2396 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2397 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2398 */
2399 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
2400 /*
2401 * If a new connection request is received
2402 * while in TIME_WAIT, drop the old connection
2403 * and start over if the sequence numbers
2404 * are above the previous ones.
2405 *
2406 * NOTE: We will checksum the packet again, and
2407 * so we need to put the header fields back into
2408 * network order!
2409 * XXX This kind of sucks, but we don't expect
2410 * XXX this to happen very often, so maybe it
2411 * XXX doesn't matter so much.
2412 */
2413 if (tiflags & TH_SYN &&
2414 tp->t_state == TCPS_TIME_WAIT &&
2415 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2416 tp = tcp_close(tp);
2417 tcp_fields_to_net(th);
2418 goto findpcb;
2419 }
2420 /*
2421 * If window is closed can only take segments at
2422 * window edge, and have to drop data and PUSH from
2423 * incoming segments. Continue processing, but
2424 * remember to ack. Otherwise, drop segment
2425 * and (if not RST) ack.
2426 */
2427 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2428 tp->t_flags |= TF_ACKNOW;
2429 TCP_STATINC(TCP_STAT_RCVWINPROBE);
2430 } else
2431 goto dropafterack;
2432 } else
2433 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
2434 m_adj(m, -todrop);
2435 tlen -= todrop;
2436 tiflags &= ~(TH_PUSH|TH_FIN);
2437 }
2438
2439 /*
2440 * If last ACK falls within this segment's sequence numbers,
2441 * record the timestamp.
2442 * NOTE:
2443 * 1) That the test incorporates suggestions from the latest
2444 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
2445 * 2) That updating only on newer timestamps interferes with
2446 * our earlier PAWS tests, so this check should be solely
2447 * predicated on the sequence space of this segment.
2448 * 3) That we modify the segment boundary check to be
2449 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2450 * instead of RFC1323's
2451 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2452 * This modified check allows us to overcome RFC1323's
2453 * limitations as described in Stevens TCP/IP Illustrated
2454 * Vol. 2 p.869. In such cases, we can still calculate the
2455 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2456 */
2457 if (opti.ts_present &&
2458 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2459 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2460 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2461 tp->ts_recent_age = tcp_now;
2462 tp->ts_recent = opti.ts_val;
2463 }
2464
2465 /*
2466 * If the RST bit is set examine the state:
2467 * SYN_RECEIVED STATE:
2468 * If passive open, return to LISTEN state.
2469 * If active open, inform user that connection was refused.
2470 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
2471 * Inform user that connection was reset, and close tcb.
2472 * CLOSING, LAST_ACK, TIME_WAIT STATES
2473 * Close the tcb.
2474 */
2475 if (tiflags & TH_RST) {
2476 if (th->th_seq != tp->rcv_nxt)
2477 goto dropafterack_ratelim;
2478
2479 switch (tp->t_state) {
2480 case TCPS_SYN_RECEIVED:
2481 so->so_error = ECONNREFUSED;
2482 goto close;
2483
2484 case TCPS_ESTABLISHED:
2485 case TCPS_FIN_WAIT_1:
2486 case TCPS_FIN_WAIT_2:
2487 case TCPS_CLOSE_WAIT:
2488 so->so_error = ECONNRESET;
2489 close:
2490 tp->t_state = TCPS_CLOSED;
2491 TCP_STATINC(TCP_STAT_DROPS);
2492 tp = tcp_close(tp);
2493 goto drop;
2494
2495 case TCPS_CLOSING:
2496 case TCPS_LAST_ACK:
2497 case TCPS_TIME_WAIT:
2498 tp = tcp_close(tp);
2499 goto drop;
2500 }
2501 }
2502
2503 /*
2504 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2505 * we must be in a synchronized state. RFC791 states (under RST
2506 * generation) that any unacceptable segment (an out-of-order SYN
2507 * qualifies) received in a synchronized state must elicit only an
2508 * empty acknowledgment segment ... and the connection remains in
2509 * the same state.
2510 */
2511 if (tiflags & TH_SYN) {
2512 if (tp->rcv_nxt == th->th_seq) {
2513 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2514 TH_ACK);
2515 if (tcp_saveti)
2516 m_freem(tcp_saveti);
2517 return;
2518 }
2519
2520 goto dropafterack_ratelim;
2521 }
2522
2523 /*
2524 * If the ACK bit is off we drop the segment and return.
2525 */
2526 if ((tiflags & TH_ACK) == 0) {
2527 if (tp->t_flags & TF_ACKNOW)
2528 goto dropafterack;
2529 else
2530 goto drop;
2531 }
2532
2533 /*
2534 * Ack processing.
2535 */
2536 switch (tp->t_state) {
2537
2538 /*
2539 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2540 * ESTABLISHED state and continue processing, otherwise
2541 * send an RST.
2542 */
2543 case TCPS_SYN_RECEIVED:
2544 if (SEQ_GT(tp->snd_una, th->th_ack) ||
2545 SEQ_GT(th->th_ack, tp->snd_max))
2546 goto dropwithreset;
2547 TCP_STATINC(TCP_STAT_CONNECTS);
2548 soisconnected(so);
2549 tcp_established(tp);
2550 /* Do window scaling? */
2551 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2552 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2553 tp->snd_scale = tp->requested_s_scale;
2554 tp->rcv_scale = tp->request_r_scale;
2555 }
2556 TCP_REASS_LOCK(tp);
2557 (void) tcp_reass(tp, NULL, NULL, &tlen);
2558 tp->snd_wl1 = th->th_seq - 1;
2559 /* fall into ... */
2560
2561 /*
2562 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2563 * ACKs. If the ack is in the range
2564 * tp->snd_una < th->th_ack <= tp->snd_max
2565 * then advance tp->snd_una to th->th_ack and drop
2566 * data from the retransmission queue. If this ACK reflects
2567 * more up to date window information we update our window information.
2568 */
2569 case TCPS_ESTABLISHED:
2570 case TCPS_FIN_WAIT_1:
2571 case TCPS_FIN_WAIT_2:
2572 case TCPS_CLOSE_WAIT:
2573 case TCPS_CLOSING:
2574 case TCPS_LAST_ACK:
2575 case TCPS_TIME_WAIT:
2576
2577 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2578 if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2579 TCP_STATINC(TCP_STAT_RCVDUPACK);
2580 /*
2581 * If we have outstanding data (other than
2582 * a window probe), this is a completely
2583 * duplicate ack (ie, window info didn't
2584 * change), the ack is the biggest we've
2585 * seen and we've seen exactly our rexmt
2586 * threshhold of them, assume a packet
2587 * has been dropped and retransmit it.
2588 * Kludge snd_nxt & the congestion
2589 * window so we send only this one
2590 * packet.
2591 */
2592 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2593 th->th_ack != tp->snd_una)
2594 tp->t_dupacks = 0;
2595 else if (tp->t_partialacks < 0 &&
2596 (++tp->t_dupacks == tcprexmtthresh ||
2597 TCP_FACK_FASTRECOV(tp))) {
2598 /*
2599 * Do the fast retransmit, and adjust
2600 * congestion control paramenters.
2601 */
2602 if (tp->t_congctl->fast_retransmit(tp, th)) {
2603 /* False fast retransmit */
2604 break;
2605 } else
2606 goto drop;
2607 } else if (tp->t_dupacks > tcprexmtthresh) {
2608 tp->snd_cwnd += tp->t_segsz;
2609 KERNEL_LOCK(1, NULL);
2610 (void) tcp_output(tp);
2611 KERNEL_UNLOCK_ONE(NULL);
2612 goto drop;
2613 }
2614 } else {
2615 /*
2616 * If the ack appears to be very old, only
2617 * allow data that is in-sequence. This
2618 * makes it somewhat more difficult to insert
2619 * forged data by guessing sequence numbers.
2620 * Sent an ack to try to update the send
2621 * sequence number on the other side.
2622 */
2623 if (tlen && th->th_seq != tp->rcv_nxt &&
2624 SEQ_LT(th->th_ack,
2625 tp->snd_una - tp->max_sndwnd))
2626 goto dropafterack;
2627 }
2628 break;
2629 }
2630 /*
2631 * If the congestion window was inflated to account
2632 * for the other side's cached packets, retract it.
2633 */
2634 tp->t_congctl->fast_retransmit_newack(tp, th);
2635
2636 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2637 TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
2638 goto dropafterack;
2639 }
2640 acked = th->th_ack - tp->snd_una;
2641 tcps = TCP_STAT_GETREF();
2642 tcps[TCP_STAT_RCVACKPACK]++;
2643 tcps[TCP_STAT_RCVACKBYTE] += acked;
2644 TCP_STAT_PUTREF();
2645
2646 /*
2647 * If we have a timestamp reply, update smoothed
2648 * round trip time. If no timestamp is present but
2649 * transmit timer is running and timed sequence
2650 * number was acked, update smoothed round trip time.
2651 * Since we now have an rtt measurement, cancel the
2652 * timer backoff (cf., Phil Karn's retransmit alg.).
2653 * Recompute the initial retransmit timer.
2654 */
2655 if (ts_rtt)
2656 tcp_xmit_timer(tp, ts_rtt - 1);
2657 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2658 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2659
2660 /*
2661 * If all outstanding data is acked, stop retransmit
2662 * timer and remember to restart (more output or persist).
2663 * If there is more data to be acked, restart retransmit
2664 * timer, using current (possibly backed-off) value.
2665 */
2666 if (th->th_ack == tp->snd_max) {
2667 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2668 needoutput = 1;
2669 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2670 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2671
2672 /*
2673 * New data has been acked, adjust the congestion window.
2674 */
2675 tp->t_congctl->newack(tp, th);
2676
2677 nd6_hint(tp);
2678 if (acked > so->so_snd.sb_cc) {
2679 tp->snd_wnd -= so->so_snd.sb_cc;
2680 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2681 ourfinisacked = 1;
2682 } else {
2683 if (acked > (tp->t_lastoff - tp->t_inoff))
2684 tp->t_lastm = NULL;
2685 sbdrop(&so->so_snd, acked);
2686 tp->t_lastoff -= acked;
2687 if (tp->snd_wnd > acked)
2688 tp->snd_wnd -= acked;
2689 else
2690 tp->snd_wnd = 0;
2691 ourfinisacked = 0;
2692 }
2693 sowwakeup(so);
2694
2695 icmp_check(tp, th, acked);
2696
2697 tp->snd_una = th->th_ack;
2698 if (SEQ_GT(tp->snd_una, tp->snd_fack))
2699 tp->snd_fack = tp->snd_una;
2700 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2701 tp->snd_nxt = tp->snd_una;
2702 if (SEQ_LT(tp->snd_high, tp->snd_una))
2703 tp->snd_high = tp->snd_una;
2704
2705 switch (tp->t_state) {
2706
2707 /*
2708 * In FIN_WAIT_1 STATE in addition to the processing
2709 * for the ESTABLISHED state if our FIN is now acknowledged
2710 * then enter FIN_WAIT_2.
2711 */
2712 case TCPS_FIN_WAIT_1:
2713 if (ourfinisacked) {
2714 /*
2715 * If we can't receive any more
2716 * data, then closing user can proceed.
2717 * Starting the timer is contrary to the
2718 * specification, but if we don't get a FIN
2719 * we'll hang forever.
2720 */
2721 if (so->so_state & SS_CANTRCVMORE) {
2722 soisdisconnected(so);
2723 if (tp->t_maxidle > 0)
2724 TCP_TIMER_ARM(tp, TCPT_2MSL,
2725 tp->t_maxidle);
2726 }
2727 tp->t_state = TCPS_FIN_WAIT_2;
2728 }
2729 break;
2730
2731 /*
2732 * In CLOSING STATE in addition to the processing for
2733 * the ESTABLISHED state if the ACK acknowledges our FIN
2734 * then enter the TIME-WAIT state, otherwise ignore
2735 * the segment.
2736 */
2737 case TCPS_CLOSING:
2738 if (ourfinisacked) {
2739 tp->t_state = TCPS_TIME_WAIT;
2740 tcp_canceltimers(tp);
2741 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2742 soisdisconnected(so);
2743 }
2744 break;
2745
2746 /*
2747 * In LAST_ACK, we may still be waiting for data to drain
2748 * and/or to be acked, as well as for the ack of our FIN.
2749 * If our FIN is now acknowledged, delete the TCB,
2750 * enter the closed state and return.
2751 */
2752 case TCPS_LAST_ACK:
2753 if (ourfinisacked) {
2754 tp = tcp_close(tp);
2755 goto drop;
2756 }
2757 break;
2758
2759 /*
2760 * In TIME_WAIT state the only thing that should arrive
2761 * is a retransmission of the remote FIN. Acknowledge
2762 * it and restart the finack timer.
2763 */
2764 case TCPS_TIME_WAIT:
2765 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2766 goto dropafterack;
2767 }
2768 }
2769
2770 step6:
2771 /*
2772 * Update window information.
2773 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2774 */
2775 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2776 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2777 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2778 /* keep track of pure window updates */
2779 if (tlen == 0 &&
2780 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2781 TCP_STATINC(TCP_STAT_RCVWINUPD);
2782 tp->snd_wnd = tiwin;
2783 tp->snd_wl1 = th->th_seq;
2784 tp->snd_wl2 = th->th_ack;
2785 if (tp->snd_wnd > tp->max_sndwnd)
2786 tp->max_sndwnd = tp->snd_wnd;
2787 needoutput = 1;
2788 }
2789
2790 /*
2791 * Process segments with URG.
2792 */
2793 if ((tiflags & TH_URG) && th->th_urp &&
2794 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2795 /*
2796 * This is a kludge, but if we receive and accept
2797 * random urgent pointers, we'll crash in
2798 * soreceive. It's hard to imagine someone
2799 * actually wanting to send this much urgent data.
2800 */
2801 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2802 th->th_urp = 0; /* XXX */
2803 tiflags &= ~TH_URG; /* XXX */
2804 goto dodata; /* XXX */
2805 }
2806 /*
2807 * If this segment advances the known urgent pointer,
2808 * then mark the data stream. This should not happen
2809 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2810 * a FIN has been received from the remote side.
2811 * In these states we ignore the URG.
2812 *
2813 * According to RFC961 (Assigned Protocols),
2814 * the urgent pointer points to the last octet
2815 * of urgent data. We continue, however,
2816 * to consider it to indicate the first octet
2817 * of data past the urgent section as the original
2818 * spec states (in one of two places).
2819 */
2820 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2821 tp->rcv_up = th->th_seq + th->th_urp;
2822 so->so_oobmark = so->so_rcv.sb_cc +
2823 (tp->rcv_up - tp->rcv_nxt) - 1;
2824 if (so->so_oobmark == 0)
2825 so->so_state |= SS_RCVATMARK;
2826 sohasoutofband(so);
2827 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2828 }
2829 /*
2830 * Remove out of band data so doesn't get presented to user.
2831 * This can happen independent of advancing the URG pointer,
2832 * but if two URG's are pending at once, some out-of-band
2833 * data may creep in... ick.
2834 */
2835 if (th->th_urp <= (u_int16_t) tlen
2836 #ifdef SO_OOBINLINE
2837 && (so->so_options & SO_OOBINLINE) == 0
2838 #endif
2839 )
2840 tcp_pulloutofband(so, th, m, hdroptlen);
2841 } else
2842 /*
2843 * If no out of band data is expected,
2844 * pull receive urgent pointer along
2845 * with the receive window.
2846 */
2847 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2848 tp->rcv_up = tp->rcv_nxt;
2849 dodata: /* XXX */
2850
2851 /*
2852 * Process the segment text, merging it into the TCP sequencing queue,
2853 * and arranging for acknowledgement of receipt if necessary.
2854 * This process logically involves adjusting tp->rcv_wnd as data
2855 * is presented to the user (this happens in tcp_usrreq.c,
2856 * tcp_rcvd()). If a FIN has already been received on this
2857 * connection then we just ignore the text.
2858 */
2859 if ((tlen || (tiflags & TH_FIN)) &&
2860 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2861 /*
2862 * Insert segment ti into reassembly queue of tcp with
2863 * control block tp. Return TH_FIN if reassembly now includes
2864 * a segment with FIN. The macro form does the common case
2865 * inline (segment is the next to be received on an
2866 * established connection, and the queue is empty),
2867 * avoiding linkage into and removal from the queue and
2868 * repetition of various conversions.
2869 * Set DELACK for segments received in order, but ack
2870 * immediately when segments are out of order
2871 * (so fast retransmit can work).
2872 */
2873 /* NOTE: this was TCP_REASS() macro, but used only once */
2874 TCP_REASS_LOCK(tp);
2875 if (th->th_seq == tp->rcv_nxt &&
2876 TAILQ_FIRST(&tp->segq) == NULL &&
2877 tp->t_state == TCPS_ESTABLISHED) {
2878 tcp_setup_ack(tp, th);
2879 tp->rcv_nxt += tlen;
2880 tiflags = th->th_flags & TH_FIN;
2881 tcps = TCP_STAT_GETREF();
2882 tcps[TCP_STAT_RCVPACK]++;
2883 tcps[TCP_STAT_RCVBYTE] += tlen;
2884 TCP_STAT_PUTREF();
2885 nd6_hint(tp);
2886 if (so->so_state & SS_CANTRCVMORE)
2887 m_freem(m);
2888 else {
2889 m_adj(m, hdroptlen);
2890 sbappendstream(&(so)->so_rcv, m);
2891 }
2892 TCP_REASS_UNLOCK(tp);
2893 sorwakeup(so);
2894 } else {
2895 m_adj(m, hdroptlen);
2896 tiflags = tcp_reass(tp, th, m, &tlen);
2897 tp->t_flags |= TF_ACKNOW;
2898 }
2899
2900 /*
2901 * Note the amount of data that peer has sent into
2902 * our window, in order to estimate the sender's
2903 * buffer size.
2904 */
2905 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2906 } else {
2907 m_freem(m);
2908 m = NULL;
2909 tiflags &= ~TH_FIN;
2910 }
2911
2912 /*
2913 * If FIN is received ACK the FIN and let the user know
2914 * that the connection is closing. Ignore a FIN received before
2915 * the connection is fully established.
2916 */
2917 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2918 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2919 socantrcvmore(so);
2920 tp->t_flags |= TF_ACKNOW;
2921 tp->rcv_nxt++;
2922 }
2923 switch (tp->t_state) {
2924
2925 /*
2926 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2927 */
2928 case TCPS_ESTABLISHED:
2929 tp->t_state = TCPS_CLOSE_WAIT;
2930 break;
2931
2932 /*
2933 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2934 * enter the CLOSING state.
2935 */
2936 case TCPS_FIN_WAIT_1:
2937 tp->t_state = TCPS_CLOSING;
2938 break;
2939
2940 /*
2941 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2942 * starting the time-wait timer, turning off the other
2943 * standard timers.
2944 */
2945 case TCPS_FIN_WAIT_2:
2946 tp->t_state = TCPS_TIME_WAIT;
2947 tcp_canceltimers(tp);
2948 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2949 soisdisconnected(so);
2950 break;
2951
2952 /*
2953 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2954 */
2955 case TCPS_TIME_WAIT:
2956 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2957 break;
2958 }
2959 }
2960 #ifdef TCP_DEBUG
2961 if (so->so_options & SO_DEBUG)
2962 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2963 #endif
2964
2965 /*
2966 * Return any desired output.
2967 */
2968 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2969 KERNEL_LOCK(1, NULL);
2970 (void) tcp_output(tp);
2971 KERNEL_UNLOCK_ONE(NULL);
2972 }
2973 if (tcp_saveti)
2974 m_freem(tcp_saveti);
2975
2976 if (tp->t_state == TCPS_TIME_WAIT
2977 && (so->so_state & SS_NOFDREF)
2978 && (tp->t_inpcb || af != AF_INET)
2979 && (tp->t_in6pcb || af != AF_INET6)
2980 && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
2981 && TAILQ_EMPTY(&tp->segq)
2982 && vtw_add(af, tp)) {
2983 ;
2984 }
2985 return;
2986
2987 badsyn:
2988 /*
2989 * Received a bad SYN. Increment counters and dropwithreset.
2990 */
2991 TCP_STATINC(TCP_STAT_BADSYN);
2992 tp = NULL;
2993 goto dropwithreset;
2994
2995 dropafterack:
2996 /*
2997 * Generate an ACK dropping incoming segment if it occupies
2998 * sequence space, where the ACK reflects our state.
2999 */
3000 if (tiflags & TH_RST)
3001 goto drop;
3002 goto dropafterack2;
3003
3004 dropafterack_ratelim:
3005 /*
3006 * We may want to rate-limit ACKs against SYN/RST attack.
3007 */
3008 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
3009 tcp_ackdrop_ppslim) == 0) {
3010 /* XXX stat */
3011 goto drop;
3012 }
3013 /* ...fall into dropafterack2... */
3014
3015 dropafterack2:
3016 m_freem(m);
3017 tp->t_flags |= TF_ACKNOW;
3018 KERNEL_LOCK(1, NULL);
3019 (void) tcp_output(tp);
3020 KERNEL_UNLOCK_ONE(NULL);
3021 if (tcp_saveti)
3022 m_freem(tcp_saveti);
3023 return;
3024
3025 dropwithreset_ratelim:
3026 /*
3027 * We may want to rate-limit RSTs in certain situations,
3028 * particularly if we are sending an RST in response to
3029 * an attempt to connect to or otherwise communicate with
3030 * a port for which we have no socket.
3031 */
3032 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
3033 tcp_rst_ppslim) == 0) {
3034 /* XXX stat */
3035 goto drop;
3036 }
3037 /* ...fall into dropwithreset... */
3038
3039 dropwithreset:
3040 /*
3041 * Generate a RST, dropping incoming segment.
3042 * Make ACK acceptable to originator of segment.
3043 */
3044 if (tiflags & TH_RST)
3045 goto drop;
3046 if (tiflags & TH_ACK) {
3047 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3048 } else {
3049 if (tiflags & TH_SYN)
3050 tlen++;
3051 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
3052 TH_RST|TH_ACK);
3053 }
3054 if (tcp_saveti)
3055 m_freem(tcp_saveti);
3056 return;
3057
3058 badcsum:
3059 drop:
3060 /*
3061 * Drop space held by incoming segment and return.
3062 */
3063 if (tp) {
3064 if (tp->t_inpcb)
3065 so = tp->t_inpcb->inp_socket;
3066 #ifdef INET6
3067 else if (tp->t_in6pcb)
3068 so = tp->t_in6pcb->in6p_socket;
3069 #endif
3070 else
3071 so = NULL;
3072 #ifdef TCP_DEBUG
3073 if (so && (so->so_options & SO_DEBUG) != 0)
3074 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
3075 #endif
3076 }
3077 if (tcp_saveti)
3078 m_freem(tcp_saveti);
3079 m_freem(m);
3080 return;
3081 }
3082
3083 #ifdef TCP_SIGNATURE
3084 int
3085 tcp_signature_apply(void *fstate, void *data, u_int len)
3086 {
3087
3088 MD5Update(fstate, (u_char *)data, len);
3089 return (0);
3090 }
3091
3092 struct secasvar *
3093 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
3094 {
3095 struct ip *ip;
3096 struct ip6_hdr *ip6;
3097
3098 ip = mtod(m, struct ip *);
3099 switch (ip->ip_v) {
3100 case 4:
3101 ip = mtod(m, struct ip *);
3102 ip6 = NULL;
3103 break;
3104 case 6:
3105 ip = NULL;
3106 ip6 = mtod(m, struct ip6_hdr *);
3107 break;
3108 default:
3109 return (NULL);
3110 }
3111
3112 #ifdef IPSEC
3113 union sockaddr_union dst;
3114
3115 /* Extract the destination from the IP header in the mbuf. */
3116 memset(&dst, 0, sizeof(union sockaddr_union));
3117 if (ip != NULL) {
3118 dst.sa.sa_len = sizeof(struct sockaddr_in);
3119 dst.sa.sa_family = AF_INET;
3120 dst.sin.sin_addr = ip->ip_dst;
3121 } else {
3122 dst.sa.sa_len = sizeof(struct sockaddr_in6);
3123 dst.sa.sa_family = AF_INET6;
3124 dst.sin6.sin6_addr = ip6->ip6_dst;
3125 }
3126
3127 /*
3128 * Look up an SADB entry which matches the address of the peer.
3129 */
3130 return KEY_LOOKUP_SA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0);
3131 #else
3132 return NULL;
3133 #endif
3134 }
3135
3136 int
3137 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
3138 struct secasvar *sav, char *sig)
3139 {
3140 MD5_CTX ctx;
3141 struct ip *ip;
3142 struct ipovly *ipovly;
3143 #ifdef INET6
3144 struct ip6_hdr *ip6;
3145 struct ip6_hdr_pseudo ip6pseudo;
3146 #endif /* INET6 */
3147 struct ippseudo ippseudo;
3148 struct tcphdr th0;
3149 int l, tcphdrlen;
3150
3151 if (sav == NULL)
3152 return (-1);
3153
3154 tcphdrlen = th->th_off * 4;
3155
3156 switch (mtod(m, struct ip *)->ip_v) {
3157 case 4:
3158 MD5Init(&ctx);
3159 ip = mtod(m, struct ip *);
3160 memset(&ippseudo, 0, sizeof(ippseudo));
3161 ipovly = (struct ipovly *)ip;
3162 ippseudo.ippseudo_src = ipovly->ih_src;
3163 ippseudo.ippseudo_dst = ipovly->ih_dst;
3164 ippseudo.ippseudo_pad = 0;
3165 ippseudo.ippseudo_p = IPPROTO_TCP;
3166 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
3167 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
3168 break;
3169 #if INET6
3170 case 6:
3171 MD5Init(&ctx);
3172 ip6 = mtod(m, struct ip6_hdr *);
3173 memset(&ip6pseudo, 0, sizeof(ip6pseudo));
3174 ip6pseudo.ip6ph_src = ip6->ip6_src;
3175 in6_clearscope(&ip6pseudo.ip6ph_src);
3176 ip6pseudo.ip6ph_dst = ip6->ip6_dst;
3177 in6_clearscope(&ip6pseudo.ip6ph_dst);
3178 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
3179 ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
3180 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
3181 break;
3182 #endif /* INET6 */
3183 default:
3184 return (-1);
3185 }
3186
3187 th0 = *th;
3188 th0.th_sum = 0;
3189 MD5Update(&ctx, (char *)&th0, sizeof(th0));
3190
3191 l = m->m_pkthdr.len - thoff - tcphdrlen;
3192 if (l > 0)
3193 m_apply(m, thoff + tcphdrlen,
3194 m->m_pkthdr.len - thoff - tcphdrlen,
3195 tcp_signature_apply, &ctx);
3196
3197 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3198 MD5Final(sig, &ctx);
3199
3200 return (0);
3201 }
3202 #endif
3203
3204 /*
3205 * tcp_dooptions: parse and process tcp options.
3206 *
3207 * returns -1 if this segment should be dropped. (eg. wrong signature)
3208 * otherwise returns 0.
3209 */
3210
3211 static int
3212 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt, struct tcphdr *th,
3213 struct mbuf *m, int toff, struct tcp_opt_info *oi)
3214 {
3215 u_int16_t mss;
3216 int opt, optlen = 0;
3217 #ifdef TCP_SIGNATURE
3218 void *sigp = NULL;
3219 char sigbuf[TCP_SIGLEN];
3220 struct secasvar *sav = NULL;
3221 #endif
3222
3223 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
3224 opt = cp[0];
3225 if (opt == TCPOPT_EOL)
3226 break;
3227 if (opt == TCPOPT_NOP)
3228 optlen = 1;
3229 else {
3230 if (cnt < 2)
3231 break;
3232 optlen = cp[1];
3233 if (optlen < 2 || optlen > cnt)
3234 break;
3235 }
3236 switch (opt) {
3237
3238 default:
3239 continue;
3240
3241 case TCPOPT_MAXSEG:
3242 if (optlen != TCPOLEN_MAXSEG)
3243 continue;
3244 if (!(th->th_flags & TH_SYN))
3245 continue;
3246 if (TCPS_HAVERCVDSYN(tp->t_state))
3247 continue;
3248 bcopy(cp + 2, &mss, sizeof(mss));
3249 oi->maxseg = ntohs(mss);
3250 break;
3251
3252 case TCPOPT_WINDOW:
3253 if (optlen != TCPOLEN_WINDOW)
3254 continue;
3255 if (!(th->th_flags & TH_SYN))
3256 continue;
3257 if (TCPS_HAVERCVDSYN(tp->t_state))
3258 continue;
3259 tp->t_flags |= TF_RCVD_SCALE;
3260 tp->requested_s_scale = cp[2];
3261 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
3262 char buf[INET6_ADDRSTRLEN];
3263 struct ip *ip = mtod(m, struct ip *);
3264 #ifdef INET6
3265 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
3266 #endif
3267 if (ip)
3268 in_print(buf, sizeof(buf),
3269 &ip->ip_src);
3270 #ifdef INET6
3271 else if (ip6)
3272 in6_print(buf, sizeof(buf),
3273 &ip6->ip6_src);
3274 #endif
3275 else
3276 strlcpy(buf, "(unknown)", sizeof(buf));
3277 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
3278 "assuming %d\n",
3279 tp->requested_s_scale, buf,
3280 TCP_MAX_WINSHIFT);
3281 tp->requested_s_scale = TCP_MAX_WINSHIFT;
3282 }
3283 break;
3284
3285 case TCPOPT_TIMESTAMP:
3286 if (optlen != TCPOLEN_TIMESTAMP)
3287 continue;
3288 oi->ts_present = 1;
3289 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
3290 NTOHL(oi->ts_val);
3291 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
3292 NTOHL(oi->ts_ecr);
3293
3294 if (!(th->th_flags & TH_SYN))
3295 continue;
3296 if (TCPS_HAVERCVDSYN(tp->t_state))
3297 continue;
3298 /*
3299 * A timestamp received in a SYN makes
3300 * it ok to send timestamp requests and replies.
3301 */
3302 tp->t_flags |= TF_RCVD_TSTMP;
3303 tp->ts_recent = oi->ts_val;
3304 tp->ts_recent_age = tcp_now;
3305 break;
3306
3307 case TCPOPT_SACK_PERMITTED:
3308 if (optlen != TCPOLEN_SACK_PERMITTED)
3309 continue;
3310 if (!(th->th_flags & TH_SYN))
3311 continue;
3312 if (TCPS_HAVERCVDSYN(tp->t_state))
3313 continue;
3314 if (tcp_do_sack) {
3315 tp->t_flags |= TF_SACK_PERMIT;
3316 tp->t_flags |= TF_WILL_SACK;
3317 }
3318 break;
3319
3320 case TCPOPT_SACK:
3321 tcp_sack_option(tp, th, cp, optlen);
3322 break;
3323 #ifdef TCP_SIGNATURE
3324 case TCPOPT_SIGNATURE:
3325 if (optlen != TCPOLEN_SIGNATURE)
3326 continue;
3327 if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN))
3328 return (-1);
3329
3330 sigp = sigbuf;
3331 memcpy(sigbuf, cp + 2, TCP_SIGLEN);
3332 tp->t_flags |= TF_SIGNATURE;
3333 break;
3334 #endif
3335 }
3336 }
3337
3338 #ifndef TCP_SIGNATURE
3339 return 0;
3340 #else
3341 if (tp->t_flags & TF_SIGNATURE) {
3342
3343 sav = tcp_signature_getsav(m, th);
3344
3345 if (sav == NULL && tp->t_state == TCPS_LISTEN)
3346 return (-1);
3347 }
3348
3349 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE))
3350 goto out;
3351
3352 if (sigp) {
3353 char sig[TCP_SIGLEN];
3354
3355 tcp_fields_to_net(th);
3356 if (tcp_signature(m, th, toff, sav, sig) < 0) {
3357 tcp_fields_to_host(th);
3358 goto out;
3359 }
3360 tcp_fields_to_host(th);
3361
3362 if (memcmp(sig, sigp, TCP_SIGLEN)) {
3363 TCP_STATINC(TCP_STAT_BADSIG);
3364 goto out;
3365 } else
3366 TCP_STATINC(TCP_STAT_GOODSIG);
3367
3368 key_sa_recordxfer(sav, m);
3369 KEY_SA_UNREF(&sav);
3370 }
3371 return 0;
3372 out:
3373 if (sav != NULL)
3374 KEY_SA_UNREF(&sav);
3375 return -1;
3376 #endif
3377 }
3378
3379 /*
3380 * Pull out of band byte out of a segment so
3381 * it doesn't appear in the user's data queue.
3382 * It is still reflected in the segment length for
3383 * sequencing purposes.
3384 */
3385 void
3386 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3387 struct mbuf *m, int off)
3388 {
3389 int cnt = off + th->th_urp - 1;
3390
3391 while (cnt >= 0) {
3392 if (m->m_len > cnt) {
3393 char *cp = mtod(m, char *) + cnt;
3394 struct tcpcb *tp = sototcpcb(so);
3395
3396 tp->t_iobc = *cp;
3397 tp->t_oobflags |= TCPOOB_HAVEDATA;
3398 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3399 m->m_len--;
3400 return;
3401 }
3402 cnt -= m->m_len;
3403 m = m->m_next;
3404 if (m == 0)
3405 break;
3406 }
3407 panic("tcp_pulloutofband");
3408 }
3409
3410 /*
3411 * Collect new round-trip time estimate
3412 * and update averages and current timeout.
3413 *
3414 * rtt is in units of slow ticks (typically 500 ms) -- essentially the
3415 * difference of two timestamps.
3416 */
3417 void
3418 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3419 {
3420 int32_t delta;
3421
3422 TCP_STATINC(TCP_STAT_RTTUPDATED);
3423 if (tp->t_srtt != 0) {
3424 /*
3425 * Compute the amount to add to srtt for smoothing,
3426 * *alpha, or 2^(-TCP_RTT_SHIFT). Because
3427 * srtt is stored in 1/32 slow ticks, we conceptually
3428 * shift left 5 bits, subtract srtt to get the
3429 * diference, and then shift right by TCP_RTT_SHIFT
3430 * (3) to obtain 1/8 of the difference.
3431 */
3432 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3433 /*
3434 * This can never happen, because delta's lowest
3435 * possible value is 1/8 of t_srtt. But if it does,
3436 * set srtt to some reasonable value, here chosen
3437 * as 1/8 tick.
3438 */
3439 if ((tp->t_srtt += delta) <= 0)
3440 tp->t_srtt = 1 << 2;
3441 /*
3442 * RFC2988 requires that rttvar be updated first.
3443 * This code is compliant because "delta" is the old
3444 * srtt minus the new observation (scaled).
3445 *
3446 * RFC2988 says:
3447 * rttvar = (1-beta) * rttvar + beta * |srtt-observed|
3448 *
3449 * delta is in units of 1/32 ticks, and has then been
3450 * divided by 8. This is equivalent to being in 1/16s
3451 * units and divided by 4. Subtract from it 1/4 of
3452 * the existing rttvar to form the (signed) amount to
3453 * adjust.
3454 */
3455 if (delta < 0)
3456 delta = -delta;
3457 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3458 /*
3459 * As with srtt, this should never happen. There is
3460 * no support in RFC2988 for this operation. But 1/4s
3461 * as rttvar when faced with something arguably wrong
3462 * is ok.
3463 */
3464 if ((tp->t_rttvar += delta) <= 0)
3465 tp->t_rttvar = 1 << 2;
3466
3467 /*
3468 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
3469 * Problem is: it doesn't work. Disabled by defaulting
3470 * tcp_rttlocal to 0; see corresponding code in
3471 * tcp_subr that selects local vs remote in a different way.
3472 *
3473 * The static branch prediction hint here should be removed
3474 * when the rtt estimator is fixed and the rtt_enable code
3475 * is turned back on.
3476 */
3477 if (__predict_false(tcp_rttlocal) && tcp_msl_enable
3478 && tp->t_srtt > tcp_msl_remote_threshold
3479 && tp->t_msl < tcp_msl_remote) {
3480 tp->t_msl = tcp_msl_remote;
3481 }
3482 } else {
3483 /*
3484 * This is the first measurement. Per RFC2988, 2.2,
3485 * set rtt=R and srtt=R/2.
3486 * For srtt, storage representation is 1/32 ticks,
3487 * so shift left by 5.
3488 * For rttvar, storage representation is 1/16 ticks,
3489 * So shift left by 4, but then right by 1 to halve.
3490 */
3491 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3492 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3493 }
3494 tp->t_rtttime = 0;
3495 tp->t_rxtshift = 0;
3496
3497 /*
3498 * the retransmit should happen at rtt + 4 * rttvar.
3499 * Because of the way we do the smoothing, srtt and rttvar
3500 * will each average +1/2 tick of bias. When we compute
3501 * the retransmit timer, we want 1/2 tick of rounding and
3502 * 1 extra tick because of +-1/2 tick uncertainty in the
3503 * firing of the timer. The bias will give us exactly the
3504 * 1.5 tick we need. But, because the bias is
3505 * statistical, we have to test that we don't drop below
3506 * the minimum feasible timer (which is 2 ticks).
3507 */
3508 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3509 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3510
3511 /*
3512 * We received an ack for a packet that wasn't retransmitted;
3513 * it is probably safe to discard any error indications we've
3514 * received recently. This isn't quite right, but close enough
3515 * for now (a route might have failed after we sent a segment,
3516 * and the return path might not be symmetrical).
3517 */
3518 tp->t_softerror = 0;
3519 }
3520
3521
3522 /*
3523 * TCP compressed state engine. Currently used to hold compressed
3524 * state for SYN_RECEIVED.
3525 */
3526
3527 u_long syn_cache_count;
3528 u_int32_t syn_hash1, syn_hash2;
3529
3530 #define SYN_HASH(sa, sp, dp) \
3531 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3532 ((u_int32_t)(sp)))^syn_hash2)))
3533 #ifndef INET6
3534 #define SYN_HASHALL(hash, src, dst) \
3535 do { \
3536 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3537 ((const struct sockaddr_in *)(src))->sin_port, \
3538 ((const struct sockaddr_in *)(dst))->sin_port); \
3539 } while (/*CONSTCOND*/ 0)
3540 #else
3541 #define SYN_HASH6(sa, sp, dp) \
3542 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3543 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3544 & 0x7fffffff)
3545
3546 #define SYN_HASHALL(hash, src, dst) \
3547 do { \
3548 switch ((src)->sa_family) { \
3549 case AF_INET: \
3550 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3551 ((const struct sockaddr_in *)(src))->sin_port, \
3552 ((const struct sockaddr_in *)(dst))->sin_port); \
3553 break; \
3554 case AF_INET6: \
3555 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3556 ((const struct sockaddr_in6 *)(src))->sin6_port, \
3557 ((const struct sockaddr_in6 *)(dst))->sin6_port); \
3558 break; \
3559 default: \
3560 hash = 0; \
3561 } \
3562 } while (/*CONSTCOND*/0)
3563 #endif /* INET6 */
3564
3565 static struct pool syn_cache_pool;
3566
3567 /*
3568 * We don't estimate RTT with SYNs, so each packet starts with the default
3569 * RTT and each timer step has a fixed timeout value.
3570 */
3571 static inline void
3572 syn_cache_timer_arm(struct syn_cache *sc)
3573 {
3574
3575 TCPT_RANGESET(sc->sc_rxtcur,
3576 TCPTV_SRTTDFLT * tcp_backoff[sc->sc_rxtshift], TCPTV_MIN,
3577 TCPTV_REXMTMAX);
3578 callout_reset(&sc->sc_timer,
3579 sc->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, sc);
3580 }
3581
3582 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase)
3583
3584 static inline void
3585 syn_cache_rm(struct syn_cache *sc)
3586 {
3587 TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket,
3588 sc, sc_bucketq);
3589 sc->sc_tp = NULL;
3590 LIST_REMOVE(sc, sc_tpq);
3591 tcp_syn_cache[sc->sc_bucketidx].sch_length--;
3592 callout_stop(&sc->sc_timer);
3593 syn_cache_count--;
3594 }
3595
3596 static inline void
3597 syn_cache_put(struct syn_cache *sc)
3598 {
3599 if (sc->sc_ipopts)
3600 (void) m_free(sc->sc_ipopts);
3601 rtcache_free(&sc->sc_route);
3602 sc->sc_flags |= SCF_DEAD;
3603 if (!callout_invoking(&sc->sc_timer))
3604 callout_schedule(&(sc)->sc_timer, 1);
3605 }
3606
3607 void
3608 syn_cache_init(void)
3609 {
3610 int i;
3611
3612 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
3613 "synpl", NULL, IPL_SOFTNET);
3614
3615 /* Initialize the hash buckets. */
3616 for (i = 0; i < tcp_syn_cache_size; i++)
3617 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3618 }
3619
3620 void
3621 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3622 {
3623 struct syn_cache_head *scp;
3624 struct syn_cache *sc2;
3625 int s;
3626
3627 /*
3628 * If there are no entries in the hash table, reinitialize
3629 * the hash secrets.
3630 */
3631 if (syn_cache_count == 0) {
3632 syn_hash1 = cprng_fast32();
3633 syn_hash2 = cprng_fast32();
3634 }
3635
3636 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3637 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3638 scp = &tcp_syn_cache[sc->sc_bucketidx];
3639
3640 /*
3641 * Make sure that we don't overflow the per-bucket
3642 * limit or the total cache size limit.
3643 */
3644 s = splsoftnet();
3645 if (scp->sch_length >= tcp_syn_bucket_limit) {
3646 TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW);
3647 /*
3648 * The bucket is full. Toss the oldest element in the
3649 * bucket. This will be the first entry in the bucket.
3650 */
3651 sc2 = TAILQ_FIRST(&scp->sch_bucket);
3652 #ifdef DIAGNOSTIC
3653 /*
3654 * This should never happen; we should always find an
3655 * entry in our bucket.
3656 */
3657 if (sc2 == NULL)
3658 panic("syn_cache_insert: bucketoverflow: impossible");
3659 #endif
3660 syn_cache_rm(sc2);
3661 syn_cache_put(sc2); /* calls pool_put but see spl above */
3662 } else if (syn_cache_count >= tcp_syn_cache_limit) {
3663 struct syn_cache_head *scp2, *sce;
3664
3665 TCP_STATINC(TCP_STAT_SC_OVERFLOWED);
3666 /*
3667 * The cache is full. Toss the oldest entry in the
3668 * first non-empty bucket we can find.
3669 *
3670 * XXX We would really like to toss the oldest
3671 * entry in the cache, but we hope that this
3672 * condition doesn't happen very often.
3673 */
3674 scp2 = scp;
3675 if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3676 sce = &tcp_syn_cache[tcp_syn_cache_size];
3677 for (++scp2; scp2 != scp; scp2++) {
3678 if (scp2 >= sce)
3679 scp2 = &tcp_syn_cache[0];
3680 if (! TAILQ_EMPTY(&scp2->sch_bucket))
3681 break;
3682 }
3683 #ifdef DIAGNOSTIC
3684 /*
3685 * This should never happen; we should always find a
3686 * non-empty bucket.
3687 */
3688 if (scp2 == scp)
3689 panic("syn_cache_insert: cacheoverflow: "
3690 "impossible");
3691 #endif
3692 }
3693 sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3694 syn_cache_rm(sc2);
3695 syn_cache_put(sc2); /* calls pool_put but see spl above */
3696 }
3697
3698 /*
3699 * Initialize the entry's timer.
3700 */
3701 sc->sc_rxttot = 0;
3702 sc->sc_rxtshift = 0;
3703 syn_cache_timer_arm(sc);
3704
3705 /* Link it from tcpcb entry */
3706 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3707
3708 /* Put it into the bucket. */
3709 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3710 scp->sch_length++;
3711 syn_cache_count++;
3712
3713 TCP_STATINC(TCP_STAT_SC_ADDED);
3714 splx(s);
3715 }
3716
3717 /*
3718 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3719 * If we have retransmitted an entry the maximum number of times, expire
3720 * that entry.
3721 */
3722 static void
3723 syn_cache_timer(void *arg)
3724 {
3725 struct syn_cache *sc = arg;
3726
3727 mutex_enter(softnet_lock);
3728 KERNEL_LOCK(1, NULL);
3729
3730 callout_ack(&sc->sc_timer);
3731
3732 if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3733 TCP_STATINC(TCP_STAT_SC_DELAYED_FREE);
3734 goto free;
3735 }
3736
3737 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3738 /* Drop it -- too many retransmissions. */
3739 goto dropit;
3740 }
3741
3742 /*
3743 * Compute the total amount of time this entry has
3744 * been on a queue. If this entry has been on longer
3745 * than the keep alive timer would allow, expire it.
3746 */
3747 sc->sc_rxttot += sc->sc_rxtcur;
3748 if (sc->sc_rxttot >= tcp_keepinit)
3749 goto dropit;
3750
3751 TCP_STATINC(TCP_STAT_SC_RETRANSMITTED);
3752 (void)syn_cache_respond(sc);
3753
3754 /* Advance the timer back-off. */
3755 sc->sc_rxtshift++;
3756 syn_cache_timer_arm(sc);
3757
3758 goto out;
3759
3760 dropit:
3761 TCP_STATINC(TCP_STAT_SC_TIMED_OUT);
3762 syn_cache_rm(sc);
3763 if (sc->sc_ipopts)
3764 (void) m_free(sc->sc_ipopts);
3765 rtcache_free(&sc->sc_route);
3766
3767 free:
3768 callout_destroy(&sc->sc_timer);
3769 pool_put(&syn_cache_pool, sc);
3770
3771 out:
3772 KERNEL_UNLOCK_ONE(NULL);
3773 mutex_exit(softnet_lock);
3774 }
3775
3776 /*
3777 * Remove syn cache created by the specified tcb entry,
3778 * because this does not make sense to keep them
3779 * (if there's no tcb entry, syn cache entry will never be used)
3780 */
3781 void
3782 syn_cache_cleanup(struct tcpcb *tp)
3783 {
3784 struct syn_cache *sc, *nsc;
3785 int s;
3786
3787 s = splsoftnet();
3788
3789 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3790 nsc = LIST_NEXT(sc, sc_tpq);
3791
3792 #ifdef DIAGNOSTIC
3793 if (sc->sc_tp != tp)
3794 panic("invalid sc_tp in syn_cache_cleanup");
3795 #endif
3796 syn_cache_rm(sc);
3797 syn_cache_put(sc); /* calls pool_put but see spl above */
3798 }
3799 /* just for safety */
3800 LIST_INIT(&tp->t_sc);
3801
3802 splx(s);
3803 }
3804
3805 /*
3806 * Find an entry in the syn cache.
3807 */
3808 struct syn_cache *
3809 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3810 struct syn_cache_head **headp)
3811 {
3812 struct syn_cache *sc;
3813 struct syn_cache_head *scp;
3814 u_int32_t hash;
3815 int s;
3816
3817 SYN_HASHALL(hash, src, dst);
3818
3819 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3820 *headp = scp;
3821 s = splsoftnet();
3822 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3823 sc = TAILQ_NEXT(sc, sc_bucketq)) {
3824 if (sc->sc_hash != hash)
3825 continue;
3826 if (!memcmp(&sc->sc_src, src, src->sa_len) &&
3827 !memcmp(&sc->sc_dst, dst, dst->sa_len)) {
3828 splx(s);
3829 return (sc);
3830 }
3831 }
3832 splx(s);
3833 return (NULL);
3834 }
3835
3836 /*
3837 * This function gets called when we receive an ACK for a
3838 * socket in the LISTEN state. We look up the connection
3839 * in the syn cache, and if its there, we pull it out of
3840 * the cache and turn it into a full-blown connection in
3841 * the SYN-RECEIVED state.
3842 *
3843 * The return values may not be immediately obvious, and their effects
3844 * can be subtle, so here they are:
3845 *
3846 * NULL SYN was not found in cache; caller should drop the
3847 * packet and send an RST.
3848 *
3849 * -1 We were unable to create the new connection, and are
3850 * aborting it. An ACK,RST is being sent to the peer
3851 * (unless we got screwey sequence numbners; see below),
3852 * because the 3-way handshake has been completed. Caller
3853 * should not free the mbuf, since we may be using it. If
3854 * we are not, we will free it.
3855 *
3856 * Otherwise, the return value is a pointer to the new socket
3857 * associated with the connection.
3858 */
3859 struct socket *
3860 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3861 struct tcphdr *th, unsigned int hlen, unsigned int tlen,
3862 struct socket *so, struct mbuf *m)
3863 {
3864 struct syn_cache *sc;
3865 struct syn_cache_head *scp;
3866 struct inpcb *inp = NULL;
3867 #ifdef INET6
3868 struct in6pcb *in6p = NULL;
3869 #endif
3870 struct tcpcb *tp = 0;
3871 int s;
3872 struct socket *oso;
3873
3874 s = splsoftnet();
3875 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3876 splx(s);
3877 return (NULL);
3878 }
3879
3880 /*
3881 * Verify the sequence and ack numbers. Try getting the correct
3882 * response again.
3883 */
3884 if ((th->th_ack != sc->sc_iss + 1) ||
3885 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3886 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3887 m_freem(m);
3888 (void)syn_cache_respond(sc);
3889 splx(s);
3890 return ((struct socket *)(-1));
3891 }
3892
3893 /* Remove this cache entry */
3894 syn_cache_rm(sc);
3895 splx(s);
3896
3897 /*
3898 * Ok, create the full blown connection, and set things up
3899 * as they would have been set up if we had created the
3900 * connection when the SYN arrived. If we can't create
3901 * the connection, abort it.
3902 */
3903 /*
3904 * inp still has the OLD in_pcb stuff, set the
3905 * v6-related flags on the new guy, too. This is
3906 * done particularly for the case where an AF_INET6
3907 * socket is bound only to a port, and a v4 connection
3908 * comes in on that port.
3909 * we also copy the flowinfo from the original pcb
3910 * to the new one.
3911 */
3912 oso = so;
3913 so = sonewconn(so, true);
3914 if (so == NULL)
3915 goto resetandabort;
3916
3917 switch (so->so_proto->pr_domain->dom_family) {
3918 #ifdef INET
3919 case AF_INET:
3920 inp = sotoinpcb(so);
3921 break;
3922 #endif
3923 #ifdef INET6
3924 case AF_INET6:
3925 in6p = sotoin6pcb(so);
3926 break;
3927 #endif
3928 }
3929 switch (src->sa_family) {
3930 #ifdef INET
3931 case AF_INET:
3932 if (inp) {
3933 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3934 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3935 inp->inp_options = ip_srcroute(m);
3936 in_pcbstate(inp, INP_BOUND);
3937 if (inp->inp_options == NULL) {
3938 inp->inp_options = sc->sc_ipopts;
3939 sc->sc_ipopts = NULL;
3940 }
3941 }
3942 #ifdef INET6
3943 else if (in6p) {
3944 /* IPv4 packet to AF_INET6 socket */
3945 memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr));
3946 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3947 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3948 &in6p->in6p_laddr.s6_addr32[3],
3949 sizeof(((struct sockaddr_in *)dst)->sin_addr));
3950 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
3951 in6totcpcb(in6p)->t_family = AF_INET;
3952 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
3953 in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
3954 else
3955 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
3956 in6_pcbstate(in6p, IN6P_BOUND);
3957 }
3958 #endif
3959 break;
3960 #endif
3961 #ifdef INET6
3962 case AF_INET6:
3963 if (in6p) {
3964 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
3965 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
3966 in6_pcbstate(in6p, IN6P_BOUND);
3967 }
3968 break;
3969 #endif
3970 }
3971 #ifdef INET6
3972 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
3973 struct in6pcb *oin6p = sotoin6pcb(oso);
3974 /* inherit socket options from the listening socket */
3975 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
3976 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
3977 m_freem(in6p->in6p_options);
3978 in6p->in6p_options = 0;
3979 }
3980 ip6_savecontrol(in6p, &in6p->in6p_options,
3981 mtod(m, struct ip6_hdr *), m);
3982 }
3983 #endif
3984
3985 #if defined(IPSEC)
3986 if (ipsec_used) {
3987 /*
3988 * we make a copy of policy, instead of sharing the policy, for
3989 * better behavior in terms of SA lookup and dead SA removal.
3990 */
3991 if (inp) {
3992 /* copy old policy into new socket's */
3993 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp,
3994 inp->inp_sp))
3995 printf("tcp_input: could not copy policy\n");
3996 }
3997 #ifdef INET6
3998 else if (in6p) {
3999 /* copy old policy into new socket's */
4000 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
4001 in6p->in6p_sp))
4002 printf("tcp_input: could not copy policy\n");
4003 }
4004 #endif
4005 }
4006 #endif
4007
4008 /*
4009 * Give the new socket our cached route reference.
4010 */
4011 if (inp) {
4012 rtcache_copy(&inp->inp_route, &sc->sc_route);
4013 rtcache_free(&sc->sc_route);
4014 }
4015 #ifdef INET6
4016 else {
4017 rtcache_copy(&in6p->in6p_route, &sc->sc_route);
4018 rtcache_free(&sc->sc_route);
4019 }
4020 #endif
4021
4022 if (inp) {
4023 struct sockaddr_in sin;
4024 memcpy(&sin, src, src->sa_len);
4025 if (in_pcbconnect(inp, &sin, &lwp0)) {
4026 goto resetandabort;
4027 }
4028 }
4029 #ifdef INET6
4030 else if (in6p) {
4031 struct sockaddr_in6 sin6;
4032 memcpy(&sin6, src, src->sa_len);
4033 if (src->sa_family == AF_INET) {
4034 /* IPv4 packet to AF_INET6 socket */
4035 in6_sin_2_v4mapsin6((struct sockaddr_in *)src, &sin6);
4036 }
4037 if (in6_pcbconnect(in6p, &sin6, NULL)) {
4038 goto resetandabort;
4039 }
4040 }
4041 #endif
4042 else {
4043 goto resetandabort;
4044 }
4045
4046 if (inp)
4047 tp = intotcpcb(inp);
4048 #ifdef INET6
4049 else if (in6p)
4050 tp = in6totcpcb(in6p);
4051 #endif
4052 else
4053 tp = NULL;
4054 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
4055 if (sc->sc_request_r_scale != 15) {
4056 tp->requested_s_scale = sc->sc_requested_s_scale;
4057 tp->request_r_scale = sc->sc_request_r_scale;
4058 tp->snd_scale = sc->sc_requested_s_scale;
4059 tp->rcv_scale = sc->sc_request_r_scale;
4060 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
4061 }
4062 if (sc->sc_flags & SCF_TIMESTAMP)
4063 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
4064 tp->ts_timebase = sc->sc_timebase;
4065
4066 tp->t_template = tcp_template(tp);
4067 if (tp->t_template == 0) {
4068 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
4069 so = NULL;
4070 m_freem(m);
4071 goto abort;
4072 }
4073
4074 tp->iss = sc->sc_iss;
4075 tp->irs = sc->sc_irs;
4076 tcp_sendseqinit(tp);
4077 tcp_rcvseqinit(tp);
4078 tp->t_state = TCPS_SYN_RECEIVED;
4079 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit);
4080 TCP_STATINC(TCP_STAT_ACCEPTS);
4081
4082 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
4083 tp->t_flags |= TF_WILL_SACK;
4084
4085 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
4086 tp->t_flags |= TF_ECN_PERMIT;
4087
4088 #ifdef TCP_SIGNATURE
4089 if (sc->sc_flags & SCF_SIGNATURE)
4090 tp->t_flags |= TF_SIGNATURE;
4091 #endif
4092
4093 /* Initialize tp->t_ourmss before we deal with the peer's! */
4094 tp->t_ourmss = sc->sc_ourmaxseg;
4095 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
4096
4097 /*
4098 * Initialize the initial congestion window. If we
4099 * had to retransmit the SYN,ACK, we must initialize cwnd
4100 * to 1 segment (i.e. the Loss Window).
4101 */
4102 if (sc->sc_rxtshift)
4103 tp->snd_cwnd = tp->t_peermss;
4104 else {
4105 int ss = tcp_init_win;
4106 #ifdef INET
4107 if (inp != NULL && in_localaddr(inp->inp_faddr))
4108 ss = tcp_init_win_local;
4109 #endif
4110 #ifdef INET6
4111 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
4112 ss = tcp_init_win_local;
4113 #endif
4114 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
4115 }
4116
4117 tcp_rmx_rtt(tp);
4118 tp->snd_wl1 = sc->sc_irs;
4119 tp->rcv_up = sc->sc_irs + 1;
4120
4121 /*
4122 * This is what whould have happened in tcp_output() when
4123 * the SYN,ACK was sent.
4124 */
4125 tp->snd_up = tp->snd_una;
4126 tp->snd_max = tp->snd_nxt = tp->iss+1;
4127 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
4128 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
4129 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
4130 tp->last_ack_sent = tp->rcv_nxt;
4131 tp->t_partialacks = -1;
4132 tp->t_dupacks = 0;
4133
4134 TCP_STATINC(TCP_STAT_SC_COMPLETED);
4135 s = splsoftnet();
4136 syn_cache_put(sc);
4137 splx(s);
4138 return (so);
4139
4140 resetandabort:
4141 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
4142 abort:
4143 if (so != NULL) {
4144 (void) soqremque(so, 1);
4145 (void) soabort(so);
4146 mutex_enter(softnet_lock);
4147 }
4148 s = splsoftnet();
4149 syn_cache_put(sc);
4150 splx(s);
4151 TCP_STATINC(TCP_STAT_SC_ABORTED);
4152 return ((struct socket *)(-1));
4153 }
4154
4155 /*
4156 * This function is called when we get a RST for a
4157 * non-existent connection, so that we can see if the
4158 * connection is in the syn cache. If it is, zap it.
4159 */
4160
4161 void
4162 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
4163 {
4164 struct syn_cache *sc;
4165 struct syn_cache_head *scp;
4166 int s = splsoftnet();
4167
4168 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4169 splx(s);
4170 return;
4171 }
4172 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
4173 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
4174 splx(s);
4175 return;
4176 }
4177 syn_cache_rm(sc);
4178 TCP_STATINC(TCP_STAT_SC_RESET);
4179 syn_cache_put(sc); /* calls pool_put but see spl above */
4180 splx(s);
4181 }
4182
4183 void
4184 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
4185 struct tcphdr *th)
4186 {
4187 struct syn_cache *sc;
4188 struct syn_cache_head *scp;
4189 int s;
4190
4191 s = splsoftnet();
4192 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4193 splx(s);
4194 return;
4195 }
4196 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
4197 if (ntohl (th->th_seq) != sc->sc_iss) {
4198 splx(s);
4199 return;
4200 }
4201
4202 /*
4203 * If we've retransmitted 3 times and this is our second error,
4204 * we remove the entry. Otherwise, we allow it to continue on.
4205 * This prevents us from incorrectly nuking an entry during a
4206 * spurious network outage.
4207 *
4208 * See tcp_notify().
4209 */
4210 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
4211 sc->sc_flags |= SCF_UNREACH;
4212 splx(s);
4213 return;
4214 }
4215
4216 syn_cache_rm(sc);
4217 TCP_STATINC(TCP_STAT_SC_UNREACH);
4218 syn_cache_put(sc); /* calls pool_put but see spl above */
4219 splx(s);
4220 }
4221
4222 /*
4223 * Given a LISTEN socket and an inbound SYN request, add
4224 * this to the syn cache, and send back a segment:
4225 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
4226 * to the source.
4227 *
4228 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
4229 * Doing so would require that we hold onto the data and deliver it
4230 * to the application. However, if we are the target of a SYN-flood
4231 * DoS attack, an attacker could send data which would eventually
4232 * consume all available buffer space if it were ACKed. By not ACKing
4233 * the data, we avoid this DoS scenario.
4234 */
4235 int
4236 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
4237 unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
4238 int optlen, struct tcp_opt_info *oi)
4239 {
4240 struct tcpcb tb, *tp;
4241 long win;
4242 struct syn_cache *sc;
4243 struct syn_cache_head *scp;
4244 struct mbuf *ipopts;
4245 struct tcp_opt_info opti;
4246 int s;
4247
4248 tp = sototcpcb(so);
4249
4250 memset(&opti, 0, sizeof(opti));
4251
4252 /*
4253 * Initialize some local state.
4254 */
4255 win = sbspace(&so->so_rcv);
4256 if (win > TCP_MAXWIN)
4257 win = TCP_MAXWIN;
4258
4259 #ifdef TCP_SIGNATURE
4260 if (optp || (tp->t_flags & TF_SIGNATURE))
4261 #else
4262 if (optp)
4263 #endif
4264 {
4265 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
4266 #ifdef TCP_SIGNATURE
4267 tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
4268 #endif
4269 tb.t_state = TCPS_LISTEN;
4270 if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
4271 sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
4272 return 0;
4273 } else
4274 tb.t_flags = 0;
4275
4276 switch (src->sa_family) {
4277 #ifdef INET
4278 case AF_INET:
4279 /*
4280 * Remember the IP options, if any.
4281 */
4282 ipopts = ip_srcroute(m);
4283 break;
4284 #endif
4285 default:
4286 ipopts = NULL;
4287 }
4288
4289 /*
4290 * See if we already have an entry for this connection.
4291 * If we do, resend the SYN,ACK. We do not count this
4292 * as a retransmission (XXX though maybe we should).
4293 */
4294 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
4295 TCP_STATINC(TCP_STAT_SC_DUPESYN);
4296 if (ipopts) {
4297 /*
4298 * If we were remembering a previous source route,
4299 * forget it and use the new one we've been given.
4300 */
4301 if (sc->sc_ipopts)
4302 (void)m_free(sc->sc_ipopts);
4303 sc->sc_ipopts = ipopts;
4304 }
4305 sc->sc_timestamp = tb.ts_recent;
4306 m_freem(m);
4307 if (syn_cache_respond(sc) == 0) {
4308 uint64_t *tcps = TCP_STAT_GETREF();
4309 tcps[TCP_STAT_SNDACKS]++;
4310 tcps[TCP_STAT_SNDTOTAL]++;
4311 TCP_STAT_PUTREF();
4312 }
4313 return 1;
4314 }
4315
4316 s = splsoftnet();
4317 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
4318 splx(s);
4319 if (sc == NULL) {
4320 if (ipopts)
4321 (void)m_free(ipopts);
4322 return 0;
4323 }
4324
4325 /*
4326 * Fill in the cache, and put the necessary IP and TCP
4327 * options into the reply.
4328 */
4329 memset(sc, 0, sizeof(struct syn_cache));
4330 callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
4331 bcopy(src, &sc->sc_src, src->sa_len);
4332 bcopy(dst, &sc->sc_dst, dst->sa_len);
4333 sc->sc_flags = 0;
4334 sc->sc_ipopts = ipopts;
4335 sc->sc_irs = th->th_seq;
4336 switch (src->sa_family) {
4337 #ifdef INET
4338 case AF_INET:
4339 {
4340 struct sockaddr_in *srcin = (void *)src;
4341 struct sockaddr_in *dstin = (void *)dst;
4342
4343 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
4344 &srcin->sin_addr, dstin->sin_port,
4345 srcin->sin_port, sizeof(dstin->sin_addr), 0);
4346 break;
4347 }
4348 #endif /* INET */
4349 #ifdef INET6
4350 case AF_INET6:
4351 {
4352 struct sockaddr_in6 *srcin6 = (void *)src;
4353 struct sockaddr_in6 *dstin6 = (void *)dst;
4354
4355 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
4356 &srcin6->sin6_addr, dstin6->sin6_port,
4357 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
4358 break;
4359 }
4360 #endif /* INET6 */
4361 }
4362 sc->sc_peermaxseg = oi->maxseg;
4363 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
4364 m_get_rcvif_NOMPSAFE(m) : NULL, sc->sc_src.sa.sa_family);
4365 sc->sc_win = win;
4366 sc->sc_timebase = tcp_now - 1; /* see tcp_newtcpcb() */
4367 sc->sc_timestamp = tb.ts_recent;
4368 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
4369 (TF_REQ_TSTMP|TF_RCVD_TSTMP))
4370 sc->sc_flags |= SCF_TIMESTAMP;
4371 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
4372 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
4373 sc->sc_requested_s_scale = tb.requested_s_scale;
4374 sc->sc_request_r_scale = 0;
4375 /*
4376 * Pick the smallest possible scaling factor that
4377 * will still allow us to scale up to sb_max.
4378 *
4379 * We do this because there are broken firewalls that
4380 * will corrupt the window scale option, leading to
4381 * the other endpoint believing that our advertised
4382 * window is unscaled. At scale factors larger than
4383 * 5 the unscaled window will drop below 1500 bytes,
4384 * leading to serious problems when traversing these
4385 * broken firewalls.
4386 *
4387 * With the default sbmax of 256K, a scale factor
4388 * of 3 will be chosen by this algorithm. Those who
4389 * choose a larger sbmax should watch out
4390 * for the compatiblity problems mentioned above.
4391 *
4392 * RFC1323: The Window field in a SYN (i.e., a <SYN>
4393 * or <SYN,ACK>) segment itself is never scaled.
4394 */
4395 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
4396 (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max)
4397 sc->sc_request_r_scale++;
4398 } else {
4399 sc->sc_requested_s_scale = 15;
4400 sc->sc_request_r_scale = 15;
4401 }
4402 if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
4403 sc->sc_flags |= SCF_SACK_PERMIT;
4404
4405 /*
4406 * ECN setup packet received.
4407 */
4408 if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn)
4409 sc->sc_flags |= SCF_ECN_PERMIT;
4410
4411 #ifdef TCP_SIGNATURE
4412 if (tb.t_flags & TF_SIGNATURE)
4413 sc->sc_flags |= SCF_SIGNATURE;
4414 #endif
4415 sc->sc_tp = tp;
4416 m_freem(m);
4417 if (syn_cache_respond(sc) == 0) {
4418 uint64_t *tcps = TCP_STAT_GETREF();
4419 tcps[TCP_STAT_SNDACKS]++;
4420 tcps[TCP_STAT_SNDTOTAL]++;
4421 TCP_STAT_PUTREF();
4422 syn_cache_insert(sc, tp);
4423 } else {
4424 s = splsoftnet();
4425 /*
4426 * syn_cache_put() will try to schedule the timer, so
4427 * we need to initialize it
4428 */
4429 syn_cache_timer_arm(sc);
4430 syn_cache_put(sc);
4431 splx(s);
4432 TCP_STATINC(TCP_STAT_SC_DROPPED);
4433 }
4434 return 1;
4435 }
4436
4437 /*
4438 * syn_cache_respond: (re)send SYN+ACK.
4439 *
4440 * returns 0 on success. otherwise returns an errno, typically ENOBUFS.
4441 */
4442
4443 int
4444 syn_cache_respond(struct syn_cache *sc)
4445 {
4446 #ifdef INET6
4447 struct rtentry *rt = NULL;
4448 #endif
4449 struct route *ro;
4450 u_int8_t *optp;
4451 int optlen, error;
4452 u_int16_t tlen;
4453 struct ip *ip = NULL;
4454 #ifdef INET6
4455 struct ip6_hdr *ip6 = NULL;
4456 #endif
4457 struct tcpcb *tp = NULL;
4458 struct tcphdr *th;
4459 struct mbuf *m;
4460 u_int hlen;
4461 #ifdef TCP_SIGNATURE
4462 struct secasvar *sav = NULL;
4463 u_int8_t *sigp = NULL;
4464 #endif
4465
4466 ro = &sc->sc_route;
4467 switch (sc->sc_src.sa.sa_family) {
4468 case AF_INET:
4469 hlen = sizeof(struct ip);
4470 break;
4471 #ifdef INET6
4472 case AF_INET6:
4473 hlen = sizeof(struct ip6_hdr);
4474 break;
4475 #endif
4476 default:
4477 return (EAFNOSUPPORT);
4478 }
4479
4480 /* worst case scanario, since we don't know the option size yet */
4481 tlen = hlen + sizeof(struct tcphdr) + MAX_TCPOPTLEN;
4482
4483 /*
4484 * Create the IP+TCP header from scratch.
4485 */
4486 #ifdef DIAGNOSTIC
4487 if (max_linkhdr + tlen > MCLBYTES)
4488 return ENOBUFS;
4489 #endif
4490
4491 MGETHDR(m, M_DONTWAIT, MT_DATA);
4492 if (m && (max_linkhdr + tlen) > MHLEN) {
4493 MCLGET(m, M_DONTWAIT);
4494 if ((m->m_flags & M_EXT) == 0) {
4495 m_freem(m);
4496 m = NULL;
4497 }
4498 }
4499 if (m == NULL)
4500 return ENOBUFS;
4501 MCLAIM(m, &tcp_tx_mowner);
4502
4503 /* Fixup the mbuf. */
4504 m->m_data += max_linkhdr;
4505 if (sc->sc_tp)
4506 tp = sc->sc_tp;
4507 m_reset_rcvif(m);
4508 memset(mtod(m, u_char *), 0, tlen);
4509
4510 switch (sc->sc_src.sa.sa_family) {
4511 case AF_INET:
4512 ip = mtod(m, struct ip *);
4513 ip->ip_v = 4;
4514 ip->ip_dst = sc->sc_src.sin.sin_addr;
4515 ip->ip_src = sc->sc_dst.sin.sin_addr;
4516 ip->ip_p = IPPROTO_TCP;
4517 th = (struct tcphdr *)(ip + 1);
4518 th->th_dport = sc->sc_src.sin.sin_port;
4519 th->th_sport = sc->sc_dst.sin.sin_port;
4520 break;
4521 #ifdef INET6
4522 case AF_INET6:
4523 ip6 = mtod(m, struct ip6_hdr *);
4524 ip6->ip6_vfc = IPV6_VERSION;
4525 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4526 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4527 ip6->ip6_nxt = IPPROTO_TCP;
4528 /* ip6_plen will be updated in ip6_output() */
4529 th = (struct tcphdr *)(ip6 + 1);
4530 th->th_dport = sc->sc_src.sin6.sin6_port;
4531 th->th_sport = sc->sc_dst.sin6.sin6_port;
4532 break;
4533 #endif
4534 default:
4535 return ENOBUFS;
4536 }
4537
4538 th->th_seq = htonl(sc->sc_iss);
4539 th->th_ack = htonl(sc->sc_irs + 1);
4540 th->th_flags = TH_SYN|TH_ACK;
4541 th->th_win = htons(sc->sc_win);
4542 /* th_x2, th_sum, th_urp already 0 from memset */
4543
4544 /* Tack on the TCP options. */
4545 optp = (u_int8_t *)(th + 1);
4546 optlen = 0;
4547 *optp++ = TCPOPT_MAXSEG;
4548 *optp++ = TCPOLEN_MAXSEG;
4549 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4550 *optp++ = sc->sc_ourmaxseg & 0xff;
4551 optlen += TCPOLEN_MAXSEG;
4552
4553 if (sc->sc_request_r_scale != 15) {
4554 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4555 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4556 sc->sc_request_r_scale);
4557 optp += TCPOLEN_WINDOW + TCPOLEN_NOP;
4558 optlen += TCPOLEN_WINDOW + TCPOLEN_NOP;
4559 }
4560
4561 if (sc->sc_flags & SCF_SACK_PERMIT) {
4562 /* Let the peer know that we will SACK. */
4563 *optp++ = TCPOPT_SACK_PERMITTED;
4564 *optp++ = TCPOLEN_SACK_PERMITTED;
4565 optlen += TCPOLEN_SACK_PERMITTED;
4566 }
4567
4568 if (sc->sc_flags & SCF_TIMESTAMP) {
4569 while (optlen % 4 != 2) {
4570 optlen += TCPOLEN_NOP;
4571 *optp++ = TCPOPT_NOP;
4572 }
4573 *optp++ = TCPOPT_TIMESTAMP;
4574 *optp++ = TCPOLEN_TIMESTAMP;
4575 u_int32_t *lp = (u_int32_t *)(optp);
4576 /* Form timestamp option as shown in appendix A of RFC 1323. */
4577 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4578 *lp = htonl(sc->sc_timestamp);
4579 optp += TCPOLEN_TIMESTAMP - 2;
4580 optlen += TCPOLEN_TIMESTAMP;
4581 }
4582
4583 #ifdef TCP_SIGNATURE
4584 if (sc->sc_flags & SCF_SIGNATURE) {
4585
4586 sav = tcp_signature_getsav(m, th);
4587
4588 if (sav == NULL) {
4589 if (m)
4590 m_freem(m);
4591 return (EPERM);
4592 }
4593
4594 *optp++ = TCPOPT_SIGNATURE;
4595 *optp++ = TCPOLEN_SIGNATURE;
4596 sigp = optp;
4597 memset(optp, 0, TCP_SIGLEN);
4598 optp += TCP_SIGLEN;
4599 optlen += TCPOLEN_SIGNATURE;
4600
4601 }
4602 #endif
4603 /* Terminate and pad TCP options to a 4 byte boundary. */
4604 if (optlen % 4) {
4605 optlen += TCPOLEN_EOL;
4606 *optp++ = TCPOPT_EOL;
4607 }
4608 /*
4609 * According to RFC 793 (STD0007):
4610 * "The content of the header beyond the End-of-Option option
4611 * must be header padding (i.e., zero)."
4612 * and later: "The padding is composed of zeros."
4613 */
4614 while (optlen % 4) {
4615 optlen += TCPOLEN_PAD;
4616 *optp++ = TCPOPT_PAD;
4617 }
4618
4619 /* compute the actual values now that we've added the options */
4620 tlen = hlen + sizeof(struct tcphdr) + optlen;
4621 m->m_len = m->m_pkthdr.len = tlen;
4622 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4623
4624 #ifdef TCP_SIGNATURE
4625 if (sav) {
4626 (void)tcp_signature(m, th, hlen, sav, sigp);
4627 key_sa_recordxfer(sav, m);
4628 KEY_SA_UNREF(&sav);
4629 }
4630 #endif
4631
4632 /*
4633 * Send ECN SYN-ACK setup packet.
4634 * Routes can be asymetric, so, even if we receive a packet
4635 * with ECE and CWR set, we must not assume no one will block
4636 * the ECE packet we are about to send.
4637 */
4638 if ((sc->sc_flags & SCF_ECN_PERMIT) && tp &&
4639 SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
4640 th->th_flags |= TH_ECE;
4641 TCP_STATINC(TCP_STAT_ECN_SHS);
4642
4643 /*
4644 * draft-ietf-tcpm-ecnsyn-00.txt
4645 *
4646 * "[...] a TCP node MAY respond to an ECN-setup
4647 * SYN packet by setting ECT in the responding
4648 * ECN-setup SYN/ACK packet, indicating to routers
4649 * that the SYN/ACK packet is ECN-Capable.
4650 * This allows a congested router along the path
4651 * to mark the packet instead of dropping the
4652 * packet as an indication of congestion."
4653 *
4654 * "[...] There can be a great benefit in setting
4655 * an ECN-capable codepoint in SYN/ACK packets [...]
4656 * Congestion is most likely to occur in
4657 * the server-to-client direction. As a result,
4658 * setting an ECN-capable codepoint in SYN/ACK
4659 * packets can reduce the occurence of three-second
4660 * retransmit timeouts resulting from the drop
4661 * of SYN/ACK packets."
4662 *
4663 * Page 4 and 6, January 2006.
4664 */
4665
4666 switch (sc->sc_src.sa.sa_family) {
4667 #ifdef INET
4668 case AF_INET:
4669 ip->ip_tos |= IPTOS_ECN_ECT0;
4670 break;
4671 #endif
4672 #ifdef INET6
4673 case AF_INET6:
4674 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
4675 break;
4676 #endif
4677 }
4678 TCP_STATINC(TCP_STAT_ECN_ECT);
4679 }
4680
4681
4682 /* Compute the packet's checksum. */
4683 switch (sc->sc_src.sa.sa_family) {
4684 case AF_INET:
4685 ip->ip_len = htons(tlen - hlen);
4686 th->th_sum = 0;
4687 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4688 break;
4689 #ifdef INET6
4690 case AF_INET6:
4691 ip6->ip6_plen = htons(tlen - hlen);
4692 th->th_sum = 0;
4693 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4694 break;
4695 #endif
4696 }
4697
4698 /*
4699 * Fill in some straggling IP bits. Note the stack expects
4700 * ip_len to be in host order, for convenience.
4701 */
4702 switch (sc->sc_src.sa.sa_family) {
4703 #ifdef INET
4704 case AF_INET:
4705 ip->ip_len = htons(tlen);
4706 ip->ip_ttl = ip_defttl;
4707 /* XXX tos? */
4708 break;
4709 #endif
4710 #ifdef INET6
4711 case AF_INET6:
4712 ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4713 ip6->ip6_vfc |= IPV6_VERSION;
4714 ip6->ip6_plen = htons(tlen - hlen);
4715 /* ip6_hlim will be initialized afterwards */
4716 /* XXX flowlabel? */
4717 break;
4718 #endif
4719 }
4720
4721 /* XXX use IPsec policy on listening socket, on SYN ACK */
4722 tp = sc->sc_tp;
4723
4724 switch (sc->sc_src.sa.sa_family) {
4725 #ifdef INET
4726 case AF_INET:
4727 error = ip_output(m, sc->sc_ipopts, ro,
4728 (ip_mtudisc ? IP_MTUDISC : 0),
4729 NULL, tp ? tp->t_inpcb : NULL);
4730 break;
4731 #endif
4732 #ifdef INET6
4733 case AF_INET6:
4734 ip6->ip6_hlim = in6_selecthlim(NULL,
4735 (rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp : NULL);
4736 rtcache_unref(rt, ro);
4737
4738 error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL,
4739 tp ? tp->t_in6pcb : NULL, NULL);
4740 break;
4741 #endif
4742 default:
4743 error = EAFNOSUPPORT;
4744 break;
4745 }
4746 return (error);
4747 }
4748