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