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