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