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