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