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