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