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