tcp_input.c revision 1.386 1 /* $NetBSD: tcp_input.c,v 1.386 2018/03/22 21:19:28 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.386 2018/03/22 21:19:28 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 * Do quick retrieval of timestamp options ("options
1386 * prediction?"). If timestamp is the only option and it's
1387 * formatted as recommended in RFC 1323 appendix A, we
1388 * quickly get the values now and not bother calling
1389 * tcp_dooptions(), etc.
1390 */
1391 if ((optlen == TCPOLEN_TSTAMP_APPA ||
1392 (optlen > TCPOLEN_TSTAMP_APPA &&
1393 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1394 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1395 (th->th_flags & TH_SYN) == 0) {
1396 opti.ts_present = 1;
1397 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1398 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1399 optp = NULL; /* we've parsed the options */
1400 }
1401 }
1402 tiflags = th->th_flags;
1403
1404 /*
1405 * Checksum extended TCP header and data
1406 */
1407 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1408 goto badcsum;
1409
1410 /*
1411 * Locate pcb for segment.
1412 */
1413 findpcb:
1414 inp = NULL;
1415 #ifdef INET6
1416 in6p = NULL;
1417 #endif
1418 switch (af) {
1419 #ifdef INET
1420 case AF_INET:
1421 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1422 ip->ip_dst, th->th_dport, &vestige);
1423 if (inp == NULL && !vestige.valid) {
1424 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1425 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst,
1426 th->th_dport);
1427 }
1428 #ifdef INET6
1429 if (inp == NULL && !vestige.valid) {
1430 struct in6_addr s, d;
1431
1432 /* mapped addr case */
1433 in6_in_2_v4mapin6(&ip->ip_src, &s);
1434 in6_in_2_v4mapin6(&ip->ip_dst, &d);
1435 in6p = in6_pcblookup_connect(&tcbtable, &s,
1436 th->th_sport, &d, th->th_dport, 0, &vestige);
1437 if (in6p == 0 && !vestige.valid) {
1438 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1439 in6p = in6_pcblookup_bind(&tcbtable, &d,
1440 th->th_dport, 0);
1441 }
1442 }
1443 #endif
1444 #ifndef INET6
1445 if (inp == NULL && !vestige.valid)
1446 #else
1447 if (inp == NULL && in6p == NULL && !vestige.valid)
1448 #endif
1449 {
1450 TCP_STATINC(TCP_STAT_NOPORT);
1451 if (tcp_log_refused &&
1452 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1453 tcp4_log_refused(ip, th);
1454 }
1455 tcp_fields_to_host(th);
1456 goto dropwithreset_ratelim;
1457 }
1458 #if defined(IPSEC)
1459 if (ipsec_used) {
1460 if (inp && ipsec_in_reject(m, inp)) {
1461 goto drop;
1462 }
1463 #ifdef INET6
1464 else if (in6p && ipsec_in_reject(m, in6p)) {
1465 goto drop;
1466 }
1467 #endif
1468 }
1469 #endif /*IPSEC*/
1470 break;
1471 #endif /*INET*/
1472 #ifdef INET6
1473 case AF_INET6:
1474 {
1475 int faith;
1476
1477 #if defined(NFAITH) && NFAITH > 0
1478 faith = faithprefix(&ip6->ip6_dst);
1479 #else
1480 faith = 0;
1481 #endif
1482 in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1483 th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
1484 if (!in6p && !vestige.valid) {
1485 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1486 in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1487 th->th_dport, faith);
1488 }
1489 if (!in6p && !vestige.valid) {
1490 TCP_STATINC(TCP_STAT_NOPORT);
1491 if (tcp_log_refused &&
1492 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1493 tcp6_log_refused(ip6, th);
1494 }
1495 tcp_fields_to_host(th);
1496 goto dropwithreset_ratelim;
1497 }
1498 #if defined(IPSEC)
1499 if (ipsec_used && in6p && ipsec_in_reject(m, in6p)) {
1500 goto drop;
1501 }
1502 #endif
1503 break;
1504 }
1505 #endif
1506 }
1507
1508 tcp_fields_to_host(th);
1509
1510 /*
1511 * If the state is CLOSED (i.e., TCB does not exist) then
1512 * all data in the incoming segment is discarded.
1513 * If the TCB exists but is in CLOSED state, it is embryonic,
1514 * but should either do a listen or a connect soon.
1515 */
1516 tp = NULL;
1517 so = NULL;
1518 if (inp) {
1519 /* Check the minimum TTL for socket. */
1520 if (ip->ip_ttl < inp->inp_ip_minttl)
1521 goto drop;
1522
1523 tp = intotcpcb(inp);
1524 so = inp->inp_socket;
1525 }
1526 #ifdef INET6
1527 else if (in6p) {
1528 tp = in6totcpcb(in6p);
1529 so = in6p->in6p_socket;
1530 }
1531 #endif
1532 else if (vestige.valid) {
1533 /* We do not support the resurrection of vtw tcpcps. */
1534 tcp_vtw_input(th, &vestige, m, tlen);
1535 m = NULL;
1536 goto drop;
1537 }
1538
1539 if (tp == NULL)
1540 goto dropwithreset_ratelim;
1541 if (tp->t_state == TCPS_CLOSED)
1542 goto drop;
1543
1544 KASSERT(so->so_lock == softnet_lock);
1545 KASSERT(solocked(so));
1546
1547 /* Unscale the window into a 32-bit value. */
1548 if ((tiflags & TH_SYN) == 0)
1549 tiwin = th->th_win << tp->snd_scale;
1550 else
1551 tiwin = th->th_win;
1552
1553 #ifdef INET6
1554 /* save packet options if user wanted */
1555 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1556 if (in6p->in6p_options) {
1557 m_freem(in6p->in6p_options);
1558 in6p->in6p_options = NULL;
1559 }
1560 KASSERT(ip6 != NULL);
1561 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1562 }
1563 #endif
1564
1565 if (so->so_options & SO_DEBUG) {
1566 #ifdef TCP_DEBUG
1567 ostate = tp->t_state;
1568 #endif
1569
1570 tcp_saveti = NULL;
1571 if (iphlen + sizeof(struct tcphdr) > MHLEN)
1572 goto nosave;
1573
1574 if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1575 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1576 if (tcp_saveti == NULL)
1577 goto nosave;
1578 } else {
1579 MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1580 if (tcp_saveti == NULL)
1581 goto nosave;
1582 MCLAIM(m, &tcp_mowner);
1583 tcp_saveti->m_len = iphlen;
1584 m_copydata(m, 0, iphlen,
1585 mtod(tcp_saveti, void *));
1586 }
1587
1588 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1589 m_freem(tcp_saveti);
1590 tcp_saveti = NULL;
1591 } else {
1592 tcp_saveti->m_len += sizeof(struct tcphdr);
1593 memcpy(mtod(tcp_saveti, char *) + iphlen, th,
1594 sizeof(struct tcphdr));
1595 }
1596 nosave:;
1597 }
1598
1599 if (so->so_options & SO_ACCEPTCONN) {
1600 union syn_cache_sa src;
1601 union syn_cache_sa dst;
1602
1603 KASSERT(tp->t_state == TCPS_LISTEN);
1604
1605 memset(&src, 0, sizeof(src));
1606 memset(&dst, 0, sizeof(dst));
1607 switch (af) {
1608 #ifdef INET
1609 case AF_INET:
1610 src.sin.sin_len = sizeof(struct sockaddr_in);
1611 src.sin.sin_family = AF_INET;
1612 src.sin.sin_addr = ip->ip_src;
1613 src.sin.sin_port = th->th_sport;
1614
1615 dst.sin.sin_len = sizeof(struct sockaddr_in);
1616 dst.sin.sin_family = AF_INET;
1617 dst.sin.sin_addr = ip->ip_dst;
1618 dst.sin.sin_port = th->th_dport;
1619 break;
1620 #endif
1621 #ifdef INET6
1622 case AF_INET6:
1623 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1624 src.sin6.sin6_family = AF_INET6;
1625 src.sin6.sin6_addr = ip6->ip6_src;
1626 src.sin6.sin6_port = th->th_sport;
1627
1628 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1629 dst.sin6.sin6_family = AF_INET6;
1630 dst.sin6.sin6_addr = ip6->ip6_dst;
1631 dst.sin6.sin6_port = th->th_dport;
1632 break;
1633 #endif
1634 }
1635
1636 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1637 if (tiflags & TH_RST) {
1638 syn_cache_reset(&src.sa, &dst.sa, th);
1639 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
1640 (TH_ACK|TH_SYN)) {
1641 /*
1642 * Received a SYN,ACK. This should never
1643 * happen while we are in LISTEN. Send an RST.
1644 */
1645 goto badsyn;
1646 } else if (tiflags & TH_ACK) {
1647 so = syn_cache_get(&src.sa, &dst.sa,
1648 th, toff, tlen, so, m);
1649 if (so == NULL) {
1650 /*
1651 * We don't have a SYN for this ACK;
1652 * send an RST.
1653 */
1654 goto badsyn;
1655 } else if (so == (struct socket *)(-1)) {
1656 /*
1657 * We were unable to create the
1658 * connection. If the 3-way handshake
1659 * was completed, and RST has been
1660 * sent to the peer. Since the mbuf
1661 * might be in use for the reply, do
1662 * not free it.
1663 */
1664 m = NULL;
1665 } else {
1666 /*
1667 * We have created a full-blown
1668 * connection.
1669 */
1670 tp = NULL;
1671 inp = NULL;
1672 #ifdef INET6
1673 in6p = NULL;
1674 #endif
1675 switch (so->so_proto->pr_domain->dom_family) {
1676 #ifdef INET
1677 case AF_INET:
1678 inp = sotoinpcb(so);
1679 tp = intotcpcb(inp);
1680 break;
1681 #endif
1682 #ifdef INET6
1683 case AF_INET6:
1684 in6p = sotoin6pcb(so);
1685 tp = in6totcpcb(in6p);
1686 break;
1687 #endif
1688 }
1689 if (tp == NULL)
1690 goto badsyn; /*XXX*/
1691 tiwin <<= tp->snd_scale;
1692 goto after_listen;
1693 }
1694 } else {
1695 /*
1696 * None of RST, SYN or ACK was set.
1697 * This is an invalid packet for a
1698 * TCB in LISTEN state. Send a RST.
1699 */
1700 goto badsyn;
1701 }
1702 } else {
1703 /*
1704 * Received a SYN.
1705 */
1706
1707 #ifdef INET6
1708 /*
1709 * If deprecated address is forbidden, we do
1710 * not accept SYN to deprecated interface
1711 * address to prevent any new inbound
1712 * connection from getting established.
1713 * When we do not accept SYN, we send a TCP
1714 * RST, with deprecated source address (instead
1715 * of dropping it). We compromise it as it is
1716 * much better for peer to send a RST, and
1717 * RST will be the final packet for the
1718 * exchange.
1719 *
1720 * If we do not forbid deprecated addresses, we
1721 * accept the SYN packet. RFC2462 does not
1722 * suggest dropping SYN in this case.
1723 * If we decipher RFC2462 5.5.4, it says like
1724 * this:
1725 * 1. use of deprecated addr with existing
1726 * communication is okay - "SHOULD continue
1727 * to be used"
1728 * 2. use of it with new communication:
1729 * (2a) "SHOULD NOT be used if alternate
1730 * address with sufficient scope is
1731 * available"
1732 * (2b) nothing mentioned otherwise.
1733 * Here we fall into (2b) case as we have no
1734 * choice in our source address selection - we
1735 * must obey the peer.
1736 *
1737 * The wording in RFC2462 is confusing, and
1738 * there are multiple description text for
1739 * deprecated address handling - worse, they
1740 * are not exactly the same. I believe 5.5.4
1741 * is the best one, so we follow 5.5.4.
1742 */
1743 if (af == AF_INET6 && !ip6_use_deprecated) {
1744 struct in6_ifaddr *ia6;
1745 int s;
1746 struct ifnet *rcvif = m_get_rcvif(m, &s);
1747 if (rcvif == NULL)
1748 goto dropwithreset; /* XXX */
1749 if ((ia6 = in6ifa_ifpwithaddr(rcvif,
1750 &ip6->ip6_dst)) &&
1751 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1752 tp = NULL;
1753 m_put_rcvif(rcvif, &s);
1754 goto dropwithreset;
1755 }
1756 m_put_rcvif(rcvif, &s);
1757 }
1758 #endif
1759
1760 /*
1761 * LISTEN socket received a SYN from itself? This
1762 * can't possibly be valid; drop the packet.
1763 */
1764 if (th->th_sport == th->th_dport) {
1765 int eq = 0;
1766
1767 switch (af) {
1768 #ifdef INET
1769 case AF_INET:
1770 eq = in_hosteq(ip->ip_src, ip->ip_dst);
1771 break;
1772 #endif
1773 #ifdef INET6
1774 case AF_INET6:
1775 eq = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src,
1776 &ip6->ip6_dst);
1777 break;
1778 #endif
1779 }
1780 if (eq) {
1781 TCP_STATINC(TCP_STAT_BADSYN);
1782 goto drop;
1783 }
1784 }
1785
1786 /*
1787 * SYN looks ok; create compressed TCP
1788 * state for it.
1789 */
1790 if (so->so_qlen <= so->so_qlimit &&
1791 syn_cache_add(&src.sa, &dst.sa, th, tlen,
1792 so, m, optp, optlen, &opti))
1793 m = NULL;
1794 }
1795
1796 goto drop;
1797 }
1798
1799 after_listen:
1800 /*
1801 * From here on, we're dealing with !LISTEN.
1802 */
1803 KASSERT(tp->t_state != TCPS_LISTEN);
1804
1805 /*
1806 * Segment received on connection.
1807 * Reset idle time and keep-alive timer.
1808 */
1809 tp->t_rcvtime = tcp_now;
1810 if (TCPS_HAVEESTABLISHED(tp->t_state))
1811 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
1812
1813 /*
1814 * Process options.
1815 */
1816 #ifdef TCP_SIGNATURE
1817 if (optp || (tp->t_flags & TF_SIGNATURE))
1818 #else
1819 if (optp)
1820 #endif
1821 if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1822 goto drop;
1823
1824 if (TCP_SACK_ENABLED(tp)) {
1825 tcp_del_sackholes(tp, th);
1826 }
1827
1828 if (TCP_ECN_ALLOWED(tp)) {
1829 if (tiflags & TH_CWR) {
1830 tp->t_flags &= ~TF_ECN_SND_ECE;
1831 }
1832 switch (iptos & IPTOS_ECN_MASK) {
1833 case IPTOS_ECN_CE:
1834 tp->t_flags |= TF_ECN_SND_ECE;
1835 TCP_STATINC(TCP_STAT_ECN_CE);
1836 break;
1837 case IPTOS_ECN_ECT0:
1838 TCP_STATINC(TCP_STAT_ECN_ECT);
1839 break;
1840 case IPTOS_ECN_ECT1:
1841 /* XXX: ignore for now -- rpaulo */
1842 break;
1843 }
1844 /*
1845 * Congestion experienced.
1846 * Ignore if we are already trying to recover.
1847 */
1848 if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
1849 tp->t_congctl->cong_exp(tp);
1850 }
1851
1852 if (opti.ts_present && opti.ts_ecr) {
1853 /*
1854 * Calculate the RTT from the returned time stamp and the
1855 * connection's time base. If the time stamp is later than
1856 * the current time, or is extremely old, fall back to non-1323
1857 * RTT calculation. Since ts_rtt is unsigned, we can test both
1858 * at the same time.
1859 *
1860 * Note that ts_rtt is in units of slow ticks (500
1861 * ms). Since most earthbound RTTs are < 500 ms,
1862 * observed values will have large quantization noise.
1863 * Our smoothed RTT is then the fraction of observed
1864 * samples that are 1 tick instead of 0 (times 500
1865 * ms).
1866 *
1867 * ts_rtt is increased by 1 to denote a valid sample,
1868 * with 0 indicating an invalid measurement. This
1869 * extra 1 must be removed when ts_rtt is used, or
1870 * else an an erroneous extra 500 ms will result.
1871 */
1872 ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1873 if (ts_rtt > TCP_PAWS_IDLE)
1874 ts_rtt = 0;
1875 } else {
1876 ts_rtt = 0;
1877 }
1878
1879 /*
1880 * Header prediction: check for the two common cases
1881 * of a uni-directional data xfer. If the packet has
1882 * no control flags, is in-sequence, the window didn't
1883 * change and we're not retransmitting, it's a
1884 * candidate. If the length is zero and the ack moved
1885 * forward, we're the sender side of the xfer. Just
1886 * free the data acked & wake any higher level process
1887 * that was blocked waiting for space. If the length
1888 * is non-zero and the ack didn't move, we're the
1889 * receiver side. If we're getting packets in-order
1890 * (the reassembly queue is empty), add the data to
1891 * the socket buffer and note that we need a delayed ack.
1892 */
1893 if (tp->t_state == TCPS_ESTABLISHED &&
1894 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
1895 == TH_ACK &&
1896 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1897 th->th_seq == tp->rcv_nxt &&
1898 tiwin && tiwin == tp->snd_wnd &&
1899 tp->snd_nxt == tp->snd_max) {
1900
1901 /*
1902 * If last ACK falls within this segment's sequence numbers,
1903 * record the timestamp.
1904 * NOTE that the test is modified according to the latest
1905 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
1906 *
1907 * note that we already know
1908 * TSTMP_GEQ(opti.ts_val, tp->ts_recent)
1909 */
1910 if (opti.ts_present &&
1911 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1912 tp->ts_recent_age = tcp_now;
1913 tp->ts_recent = opti.ts_val;
1914 }
1915
1916 if (tlen == 0) {
1917 /* Ack prediction. */
1918 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1919 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1920 tp->snd_cwnd >= tp->snd_wnd &&
1921 tp->t_partialacks < 0) {
1922 /*
1923 * this is a pure ack for outstanding data.
1924 */
1925 if (ts_rtt)
1926 tcp_xmit_timer(tp, ts_rtt - 1);
1927 else if (tp->t_rtttime &&
1928 SEQ_GT(th->th_ack, tp->t_rtseq))
1929 tcp_xmit_timer(tp,
1930 tcp_now - tp->t_rtttime);
1931 acked = th->th_ack - tp->snd_una;
1932 tcps = TCP_STAT_GETREF();
1933 tcps[TCP_STAT_PREDACK]++;
1934 tcps[TCP_STAT_RCVACKPACK]++;
1935 tcps[TCP_STAT_RCVACKBYTE] += acked;
1936 TCP_STAT_PUTREF();
1937 nd6_hint(tp);
1938
1939 if (acked > (tp->t_lastoff - tp->t_inoff))
1940 tp->t_lastm = NULL;
1941 sbdrop(&so->so_snd, acked);
1942 tp->t_lastoff -= acked;
1943
1944 icmp_check(tp, th, acked);
1945
1946 tp->snd_una = th->th_ack;
1947 tp->snd_fack = tp->snd_una;
1948 if (SEQ_LT(tp->snd_high, tp->snd_una))
1949 tp->snd_high = tp->snd_una;
1950 m_freem(m);
1951
1952 /*
1953 * If all outstanding data are acked, stop
1954 * retransmit timer, otherwise restart timer
1955 * using current (possibly backed-off) value.
1956 * If process is waiting for space,
1957 * wakeup/selnotify/signal. If data
1958 * are ready to send, let tcp_output
1959 * decide between more output or persist.
1960 */
1961 if (tp->snd_una == tp->snd_max)
1962 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1963 else if (TCP_TIMER_ISARMED(tp,
1964 TCPT_PERSIST) == 0)
1965 TCP_TIMER_ARM(tp, TCPT_REXMT,
1966 tp->t_rxtcur);
1967
1968 sowwakeup(so);
1969 if (so->so_snd.sb_cc) {
1970 KERNEL_LOCK(1, NULL);
1971 (void) tcp_output(tp);
1972 KERNEL_UNLOCK_ONE(NULL);
1973 }
1974 if (tcp_saveti)
1975 m_freem(tcp_saveti);
1976 return;
1977 }
1978 } else if (th->th_ack == tp->snd_una &&
1979 TAILQ_FIRST(&tp->segq) == NULL &&
1980 tlen <= sbspace(&so->so_rcv)) {
1981 int newsize = 0; /* automatic sockbuf scaling */
1982
1983 /*
1984 * this is a pure, in-sequence data packet
1985 * with nothing on the reassembly queue and
1986 * we have enough buffer space to take it.
1987 */
1988 tp->rcv_nxt += tlen;
1989 tcps = TCP_STAT_GETREF();
1990 tcps[TCP_STAT_PREDDAT]++;
1991 tcps[TCP_STAT_RCVPACK]++;
1992 tcps[TCP_STAT_RCVBYTE] += tlen;
1993 TCP_STAT_PUTREF();
1994 nd6_hint(tp);
1995
1996 /*
1997 * Automatic sizing enables the performance of large buffers
1998 * and most of the efficiency of small ones by only allocating
1999 * space when it is needed.
2000 *
2001 * On the receive side the socket buffer memory is only rarely
2002 * used to any significant extent. This allows us to be much
2003 * more aggressive in scaling the receive socket buffer. For
2004 * the case that the buffer space is actually used to a large
2005 * extent and we run out of kernel memory we can simply drop
2006 * the new segments; TCP on the sender will just retransmit it
2007 * later. Setting the buffer size too big may only consume too
2008 * much kernel memory if the application doesn't read() from
2009 * the socket or packet loss or reordering makes use of the
2010 * reassembly queue.
2011 *
2012 * The criteria to step up the receive buffer one notch are:
2013 * 1. the number of bytes received during the time it takes
2014 * one timestamp to be reflected back to us (the RTT);
2015 * 2. received bytes per RTT is within seven eighth of the
2016 * current socket buffer size;
2017 * 3. receive buffer size has not hit maximal automatic size;
2018 *
2019 * This algorithm does one step per RTT at most and only if
2020 * we receive a bulk stream w/o packet losses or reorderings.
2021 * Shrinking the buffer during idle times is not necessary as
2022 * it doesn't consume any memory when idle.
2023 *
2024 * TODO: Only step up if the application is actually serving
2025 * the buffer to better manage the socket buffer resources.
2026 */
2027 if (tcp_do_autorcvbuf &&
2028 opti.ts_ecr &&
2029 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
2030 if (opti.ts_ecr > tp->rfbuf_ts &&
2031 opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
2032 if (tp->rfbuf_cnt >
2033 (so->so_rcv.sb_hiwat / 8 * 7) &&
2034 so->so_rcv.sb_hiwat <
2035 tcp_autorcvbuf_max) {
2036 newsize =
2037 min(so->so_rcv.sb_hiwat +
2038 tcp_autorcvbuf_inc,
2039 tcp_autorcvbuf_max);
2040 }
2041 /* Start over with next RTT. */
2042 tp->rfbuf_ts = 0;
2043 tp->rfbuf_cnt = 0;
2044 } else
2045 tp->rfbuf_cnt += tlen; /* add up */
2046 }
2047
2048 /*
2049 * Drop TCP, IP headers and TCP options then add data
2050 * to socket buffer.
2051 */
2052 if (so->so_state & SS_CANTRCVMORE)
2053 m_freem(m);
2054 else {
2055 /*
2056 * Set new socket buffer size.
2057 * Give up when limit is reached.
2058 */
2059 if (newsize)
2060 if (!sbreserve(&so->so_rcv,
2061 newsize, so))
2062 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
2063 m_adj(m, toff + off);
2064 sbappendstream(&so->so_rcv, m);
2065 }
2066 sorwakeup(so);
2067 tcp_setup_ack(tp, th);
2068 if (tp->t_flags & TF_ACKNOW) {
2069 KERNEL_LOCK(1, NULL);
2070 (void) tcp_output(tp);
2071 KERNEL_UNLOCK_ONE(NULL);
2072 }
2073 if (tcp_saveti)
2074 m_freem(tcp_saveti);
2075 return;
2076 }
2077 }
2078
2079 /*
2080 * Compute mbuf offset to TCP data segment.
2081 */
2082 hdroptlen = toff + off;
2083
2084 /*
2085 * Calculate amount of space in receive window. Receive window is
2086 * amount of space in rcv queue, but not less than advertised
2087 * window.
2088 */
2089 {
2090 int win;
2091 win = sbspace(&so->so_rcv);
2092 if (win < 0)
2093 win = 0;
2094 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
2095 }
2096
2097 /* Reset receive buffer auto scaling when not in bulk receive mode. */
2098 tp->rfbuf_ts = 0;
2099 tp->rfbuf_cnt = 0;
2100
2101 switch (tp->t_state) {
2102 /*
2103 * If the state is SYN_SENT:
2104 * if seg contains an ACK, but not for our SYN, drop the input.
2105 * if seg contains a RST, then drop the connection.
2106 * if seg does not contain SYN, then drop it.
2107 * Otherwise this is an acceptable SYN segment
2108 * initialize tp->rcv_nxt and tp->irs
2109 * if seg contains ack then advance tp->snd_una
2110 * if seg contains a ECE and ECN support is enabled, the stream
2111 * is ECN capable.
2112 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2113 * arrange for segment to be acked (eventually)
2114 * continue processing rest of data/controls, beginning with URG
2115 */
2116 case TCPS_SYN_SENT:
2117 if ((tiflags & TH_ACK) &&
2118 (SEQ_LEQ(th->th_ack, tp->iss) ||
2119 SEQ_GT(th->th_ack, tp->snd_max)))
2120 goto dropwithreset;
2121 if (tiflags & TH_RST) {
2122 if (tiflags & TH_ACK)
2123 tp = tcp_drop(tp, ECONNREFUSED);
2124 goto drop;
2125 }
2126 if ((tiflags & TH_SYN) == 0)
2127 goto drop;
2128 if (tiflags & TH_ACK) {
2129 tp->snd_una = th->th_ack;
2130 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2131 tp->snd_nxt = tp->snd_una;
2132 if (SEQ_LT(tp->snd_high, tp->snd_una))
2133 tp->snd_high = tp->snd_una;
2134 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2135
2136 if ((tiflags & TH_ECE) && tcp_do_ecn) {
2137 tp->t_flags |= TF_ECN_PERMIT;
2138 TCP_STATINC(TCP_STAT_ECN_SHS);
2139 }
2140
2141 }
2142 tp->irs = th->th_seq;
2143 tcp_rcvseqinit(tp);
2144 tp->t_flags |= TF_ACKNOW;
2145 tcp_mss_from_peer(tp, opti.maxseg);
2146
2147 /*
2148 * Initialize the initial congestion window. If we
2149 * had to retransmit the SYN, we must initialize cwnd
2150 * to 1 segment (i.e. the Loss Window).
2151 */
2152 if (tp->t_flags & TF_SYN_REXMT)
2153 tp->snd_cwnd = tp->t_peermss;
2154 else {
2155 int ss = tcp_init_win;
2156 #ifdef INET
2157 if (inp != NULL && in_localaddr(inp->inp_faddr))
2158 ss = tcp_init_win_local;
2159 #endif
2160 #ifdef INET6
2161 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
2162 ss = tcp_init_win_local;
2163 #endif
2164 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
2165 }
2166
2167 tcp_rmx_rtt(tp);
2168 if (tiflags & TH_ACK) {
2169 TCP_STATINC(TCP_STAT_CONNECTS);
2170 /*
2171 * move tcp_established before soisconnected
2172 * because upcall handler can drive tcp_output
2173 * functionality.
2174 * XXX we might call soisconnected at the end of
2175 * all processing
2176 */
2177 tcp_established(tp);
2178 soisconnected(so);
2179 /* Do window scaling on this connection? */
2180 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2181 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2182 tp->snd_scale = tp->requested_s_scale;
2183 tp->rcv_scale = tp->request_r_scale;
2184 }
2185 TCP_REASS_LOCK(tp);
2186 (void)tcp_reass(tp, NULL, NULL, tlen);
2187 /*
2188 * if we didn't have to retransmit the SYN,
2189 * use its rtt as our initial srtt & rtt var.
2190 */
2191 if (tp->t_rtttime)
2192 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2193 } else
2194 tp->t_state = TCPS_SYN_RECEIVED;
2195
2196 /*
2197 * Advance th->th_seq to correspond to first data byte.
2198 * If data, trim to stay within window,
2199 * dropping FIN if necessary.
2200 */
2201 th->th_seq++;
2202 if (tlen > tp->rcv_wnd) {
2203 todrop = tlen - tp->rcv_wnd;
2204 m_adj(m, -todrop);
2205 tlen = tp->rcv_wnd;
2206 tiflags &= ~TH_FIN;
2207 tcps = TCP_STAT_GETREF();
2208 tcps[TCP_STAT_RCVPACKAFTERWIN]++;
2209 tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
2210 TCP_STAT_PUTREF();
2211 }
2212 tp->snd_wl1 = th->th_seq - 1;
2213 tp->rcv_up = th->th_seq;
2214 goto step6;
2215
2216 /*
2217 * If the state is SYN_RECEIVED:
2218 * If seg contains an ACK, but not for our SYN, drop the input
2219 * and generate an RST. See page 36, rfc793
2220 */
2221 case TCPS_SYN_RECEIVED:
2222 if ((tiflags & TH_ACK) &&
2223 (SEQ_LEQ(th->th_ack, tp->iss) ||
2224 SEQ_GT(th->th_ack, tp->snd_max)))
2225 goto dropwithreset;
2226 break;
2227 }
2228
2229 /*
2230 * From here on, we're dealing with !LISTEN and !SYN_SENT.
2231 */
2232 KASSERT(tp->t_state != TCPS_LISTEN &&
2233 tp->t_state != TCPS_SYN_SENT);
2234
2235 /*
2236 * First check timestamp, if present.
2237 * Then check that at least some bytes of segment are within
2238 * receive window. If segment begins before rcv_nxt,
2239 * drop leading data (and SYN); if nothing left, just ack.
2240 *
2241 * RFC 1323 PAWS: If we have a timestamp reply on this segment
2242 * and it's less than ts_recent, drop it.
2243 */
2244 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
2245 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
2246 /* Check to see if ts_recent is over 24 days old. */
2247 if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
2248 /*
2249 * Invalidate ts_recent. If this segment updates
2250 * ts_recent, the age will be reset later and ts_recent
2251 * will get a valid value. If it does not, setting
2252 * ts_recent to zero will at least satisfy the
2253 * requirement that zero be placed in the timestamp
2254 * echo reply when ts_recent isn't valid. The
2255 * age isn't reset until we get a valid ts_recent
2256 * because we don't want out-of-order segments to be
2257 * dropped when ts_recent is old.
2258 */
2259 tp->ts_recent = 0;
2260 } else {
2261 tcps = TCP_STAT_GETREF();
2262 tcps[TCP_STAT_RCVDUPPACK]++;
2263 tcps[TCP_STAT_RCVDUPBYTE] += tlen;
2264 tcps[TCP_STAT_PAWSDROP]++;
2265 TCP_STAT_PUTREF();
2266 tcp_new_dsack(tp, th->th_seq, tlen);
2267 goto dropafterack;
2268 }
2269 }
2270
2271 todrop = tp->rcv_nxt - th->th_seq;
2272 dupseg = false;
2273 if (todrop > 0) {
2274 if (tiflags & TH_SYN) {
2275 tiflags &= ~TH_SYN;
2276 th->th_seq++;
2277 if (th->th_urp > 1)
2278 th->th_urp--;
2279 else {
2280 tiflags &= ~TH_URG;
2281 th->th_urp = 0;
2282 }
2283 todrop--;
2284 }
2285 if (todrop > tlen ||
2286 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
2287 /*
2288 * Any valid FIN or RST must be to the left of the
2289 * window. At this point the FIN or RST must be a
2290 * duplicate or out of sequence; drop it.
2291 */
2292 if (tiflags & TH_RST)
2293 goto drop;
2294 tiflags &= ~(TH_FIN|TH_RST);
2295 /*
2296 * Send an ACK to resynchronize and drop any data.
2297 * But keep on processing for RST or ACK.
2298 */
2299 tp->t_flags |= TF_ACKNOW;
2300 todrop = tlen;
2301 dupseg = true;
2302 tcps = TCP_STAT_GETREF();
2303 tcps[TCP_STAT_RCVDUPPACK]++;
2304 tcps[TCP_STAT_RCVDUPBYTE] += todrop;
2305 TCP_STAT_PUTREF();
2306 } else if ((tiflags & TH_RST) &&
2307 th->th_seq != tp->rcv_nxt) {
2308 /*
2309 * Test for reset before adjusting the sequence
2310 * number for overlapping data.
2311 */
2312 goto dropafterack_ratelim;
2313 } else {
2314 tcps = TCP_STAT_GETREF();
2315 tcps[TCP_STAT_RCVPARTDUPPACK]++;
2316 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
2317 TCP_STAT_PUTREF();
2318 }
2319 tcp_new_dsack(tp, th->th_seq, todrop);
2320 hdroptlen += todrop; /*drop from head afterwards*/
2321 th->th_seq += todrop;
2322 tlen -= todrop;
2323 if (th->th_urp > todrop)
2324 th->th_urp -= todrop;
2325 else {
2326 tiflags &= ~TH_URG;
2327 th->th_urp = 0;
2328 }
2329 }
2330
2331 /*
2332 * If new data are received on a connection after the
2333 * user processes are gone, then RST the other end.
2334 */
2335 if ((so->so_state & SS_NOFDREF) &&
2336 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2337 tp = tcp_close(tp);
2338 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
2339 goto dropwithreset;
2340 }
2341
2342 /*
2343 * If segment ends after window, drop trailing data
2344 * (and PUSH and FIN); if nothing left, just ACK.
2345 */
2346 todrop = (th->th_seq + tlen) - (tp->rcv_nxt+tp->rcv_wnd);
2347 if (todrop > 0) {
2348 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
2349 if (todrop >= tlen) {
2350 /*
2351 * The segment actually starts after the window.
2352 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2353 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2354 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2355 */
2356 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
2357 /*
2358 * If a new connection request is received
2359 * while in TIME_WAIT, drop the old connection
2360 * and start over if the sequence numbers
2361 * are above the previous ones.
2362 *
2363 * NOTE: We will checksum the packet again, and
2364 * so we need to put the header fields back into
2365 * network order!
2366 * XXX This kind of sucks, but we don't expect
2367 * XXX this to happen very often, so maybe it
2368 * XXX doesn't matter so much.
2369 */
2370 if (tiflags & TH_SYN &&
2371 tp->t_state == TCPS_TIME_WAIT &&
2372 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2373 tp = tcp_close(tp);
2374 tcp_fields_to_net(th);
2375 goto findpcb;
2376 }
2377 /*
2378 * If window is closed can only take segments at
2379 * window edge, and have to drop data and PUSH from
2380 * incoming segments. Continue processing, but
2381 * remember to ack. Otherwise, drop segment
2382 * and (if not RST) ack.
2383 */
2384 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2385 tp->t_flags |= TF_ACKNOW;
2386 TCP_STATINC(TCP_STAT_RCVWINPROBE);
2387 } else
2388 goto dropafterack;
2389 } else
2390 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
2391 m_adj(m, -todrop);
2392 tlen -= todrop;
2393 tiflags &= ~(TH_PUSH|TH_FIN);
2394 }
2395
2396 /*
2397 * If last ACK falls within this segment's sequence numbers,
2398 * record the timestamp.
2399 * NOTE:
2400 * 1) That the test incorporates suggestions from the latest
2401 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
2402 * 2) That updating only on newer timestamps interferes with
2403 * our earlier PAWS tests, so this check should be solely
2404 * predicated on the sequence space of this segment.
2405 * 3) That we modify the segment boundary check to be
2406 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2407 * instead of RFC1323's
2408 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2409 * This modified check allows us to overcome RFC1323's
2410 * limitations as described in Stevens TCP/IP Illustrated
2411 * Vol. 2 p.869. In such cases, we can still calculate the
2412 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2413 */
2414 if (opti.ts_present &&
2415 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2416 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2417 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2418 tp->ts_recent_age = tcp_now;
2419 tp->ts_recent = opti.ts_val;
2420 }
2421
2422 /*
2423 * If the RST bit is set examine the state:
2424 * RECEIVED state:
2425 * If passive open, return to LISTEN state.
2426 * If active open, inform user that connection was refused.
2427 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT states:
2428 * Inform user that connection was reset, and close tcb.
2429 * CLOSING, LAST_ACK, TIME_WAIT states:
2430 * Close the tcb.
2431 */
2432 if (tiflags & TH_RST) {
2433 if (th->th_seq != tp->rcv_nxt)
2434 goto dropafterack_ratelim;
2435
2436 switch (tp->t_state) {
2437 case TCPS_SYN_RECEIVED:
2438 so->so_error = ECONNREFUSED;
2439 goto close;
2440
2441 case TCPS_ESTABLISHED:
2442 case TCPS_FIN_WAIT_1:
2443 case TCPS_FIN_WAIT_2:
2444 case TCPS_CLOSE_WAIT:
2445 so->so_error = ECONNRESET;
2446 close:
2447 tp->t_state = TCPS_CLOSED;
2448 TCP_STATINC(TCP_STAT_DROPS);
2449 tp = tcp_close(tp);
2450 goto drop;
2451
2452 case TCPS_CLOSING:
2453 case TCPS_LAST_ACK:
2454 case TCPS_TIME_WAIT:
2455 tp = tcp_close(tp);
2456 goto drop;
2457 }
2458 }
2459
2460 /*
2461 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2462 * we must be in a synchronized state. RFC791 states (under RST
2463 * generation) that any unacceptable segment (an out-of-order SYN
2464 * qualifies) received in a synchronized state must elicit only an
2465 * empty acknowledgment segment ... and the connection remains in
2466 * the same state.
2467 */
2468 if (tiflags & TH_SYN) {
2469 if (tp->rcv_nxt == th->th_seq) {
2470 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2471 TH_ACK);
2472 if (tcp_saveti)
2473 m_freem(tcp_saveti);
2474 return;
2475 }
2476
2477 goto dropafterack_ratelim;
2478 }
2479
2480 /*
2481 * If the ACK bit is off we drop the segment and return.
2482 */
2483 if ((tiflags & TH_ACK) == 0) {
2484 if (tp->t_flags & TF_ACKNOW)
2485 goto dropafterack;
2486 else
2487 goto drop;
2488 }
2489
2490 /*
2491 * Ack processing.
2492 */
2493 switch (tp->t_state) {
2494
2495 /*
2496 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2497 * ESTABLISHED state and continue processing, otherwise
2498 * send an RST.
2499 */
2500 case TCPS_SYN_RECEIVED:
2501 if (SEQ_GT(tp->snd_una, th->th_ack) ||
2502 SEQ_GT(th->th_ack, tp->snd_max))
2503 goto dropwithreset;
2504 TCP_STATINC(TCP_STAT_CONNECTS);
2505 soisconnected(so);
2506 tcp_established(tp);
2507 /* Do window scaling? */
2508 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2509 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2510 tp->snd_scale = tp->requested_s_scale;
2511 tp->rcv_scale = tp->request_r_scale;
2512 }
2513 TCP_REASS_LOCK(tp);
2514 (void)tcp_reass(tp, NULL, NULL, tlen);
2515 tp->snd_wl1 = th->th_seq - 1;
2516 /* fall into ... */
2517
2518 /*
2519 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2520 * ACKs. If the ack is in the range
2521 * tp->snd_una < th->th_ack <= tp->snd_max
2522 * then advance tp->snd_una to th->th_ack and drop
2523 * data from the retransmission queue. If this ACK reflects
2524 * more up to date window information we update our window information.
2525 */
2526 case TCPS_ESTABLISHED:
2527 case TCPS_FIN_WAIT_1:
2528 case TCPS_FIN_WAIT_2:
2529 case TCPS_CLOSE_WAIT:
2530 case TCPS_CLOSING:
2531 case TCPS_LAST_ACK:
2532 case TCPS_TIME_WAIT:
2533
2534 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2535 if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2536 TCP_STATINC(TCP_STAT_RCVDUPACK);
2537 /*
2538 * If we have outstanding data (other than
2539 * a window probe), this is a completely
2540 * duplicate ack (ie, window info didn't
2541 * change), the ack is the biggest we've
2542 * seen and we've seen exactly our rexmt
2543 * threshhold of them, assume a packet
2544 * has been dropped and retransmit it.
2545 * Kludge snd_nxt & the congestion
2546 * window so we send only this one
2547 * packet.
2548 */
2549 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2550 th->th_ack != tp->snd_una)
2551 tp->t_dupacks = 0;
2552 else if (tp->t_partialacks < 0 &&
2553 (++tp->t_dupacks == tcprexmtthresh ||
2554 TCP_FACK_FASTRECOV(tp))) {
2555 /*
2556 * Do the fast retransmit, and adjust
2557 * congestion control paramenters.
2558 */
2559 if (tp->t_congctl->fast_retransmit(tp, th)) {
2560 /* False fast retransmit */
2561 break;
2562 } else
2563 goto drop;
2564 } else if (tp->t_dupacks > tcprexmtthresh) {
2565 tp->snd_cwnd += tp->t_segsz;
2566 KERNEL_LOCK(1, NULL);
2567 (void) tcp_output(tp);
2568 KERNEL_UNLOCK_ONE(NULL);
2569 goto drop;
2570 }
2571 } else {
2572 /*
2573 * If the ack appears to be very old, only
2574 * allow data that is in-sequence. This
2575 * makes it somewhat more difficult to insert
2576 * forged data by guessing sequence numbers.
2577 * Sent an ack to try to update the send
2578 * sequence number on the other side.
2579 */
2580 if (tlen && th->th_seq != tp->rcv_nxt &&
2581 SEQ_LT(th->th_ack,
2582 tp->snd_una - tp->max_sndwnd))
2583 goto dropafterack;
2584 }
2585 break;
2586 }
2587 /*
2588 * If the congestion window was inflated to account
2589 * for the other side's cached packets, retract it.
2590 */
2591 tp->t_congctl->fast_retransmit_newack(tp, th);
2592
2593 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2594 TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
2595 goto dropafterack;
2596 }
2597 acked = th->th_ack - tp->snd_una;
2598 tcps = TCP_STAT_GETREF();
2599 tcps[TCP_STAT_RCVACKPACK]++;
2600 tcps[TCP_STAT_RCVACKBYTE] += acked;
2601 TCP_STAT_PUTREF();
2602
2603 /*
2604 * If we have a timestamp reply, update smoothed
2605 * round trip time. If no timestamp is present but
2606 * transmit timer is running and timed sequence
2607 * number was acked, update smoothed round trip time.
2608 * Since we now have an rtt measurement, cancel the
2609 * timer backoff (cf., Phil Karn's retransmit alg.).
2610 * Recompute the initial retransmit timer.
2611 */
2612 if (ts_rtt)
2613 tcp_xmit_timer(tp, ts_rtt - 1);
2614 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2615 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2616
2617 /*
2618 * If all outstanding data is acked, stop retransmit
2619 * timer and remember to restart (more output or persist).
2620 * If there is more data to be acked, restart retransmit
2621 * timer, using current (possibly backed-off) value.
2622 */
2623 if (th->th_ack == tp->snd_max) {
2624 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2625 needoutput = 1;
2626 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2627 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2628
2629 /*
2630 * New data has been acked, adjust the congestion window.
2631 */
2632 tp->t_congctl->newack(tp, th);
2633
2634 nd6_hint(tp);
2635 if (acked > so->so_snd.sb_cc) {
2636 tp->snd_wnd -= so->so_snd.sb_cc;
2637 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2638 ourfinisacked = 1;
2639 } else {
2640 if (acked > (tp->t_lastoff - tp->t_inoff))
2641 tp->t_lastm = NULL;
2642 sbdrop(&so->so_snd, acked);
2643 tp->t_lastoff -= acked;
2644 if (tp->snd_wnd > acked)
2645 tp->snd_wnd -= acked;
2646 else
2647 tp->snd_wnd = 0;
2648 ourfinisacked = 0;
2649 }
2650 sowwakeup(so);
2651
2652 icmp_check(tp, th, acked);
2653
2654 tp->snd_una = th->th_ack;
2655 if (SEQ_GT(tp->snd_una, tp->snd_fack))
2656 tp->snd_fack = tp->snd_una;
2657 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2658 tp->snd_nxt = tp->snd_una;
2659 if (SEQ_LT(tp->snd_high, tp->snd_una))
2660 tp->snd_high = tp->snd_una;
2661
2662 switch (tp->t_state) {
2663
2664 /*
2665 * In FIN_WAIT_1 STATE in addition to the processing
2666 * for the ESTABLISHED state if our FIN is now acknowledged
2667 * then enter FIN_WAIT_2.
2668 */
2669 case TCPS_FIN_WAIT_1:
2670 if (ourfinisacked) {
2671 /*
2672 * If we can't receive any more
2673 * data, then closing user can proceed.
2674 * Starting the timer is contrary to the
2675 * specification, but if we don't get a FIN
2676 * we'll hang forever.
2677 */
2678 if (so->so_state & SS_CANTRCVMORE) {
2679 soisdisconnected(so);
2680 if (tp->t_maxidle > 0)
2681 TCP_TIMER_ARM(tp, TCPT_2MSL,
2682 tp->t_maxidle);
2683 }
2684 tp->t_state = TCPS_FIN_WAIT_2;
2685 }
2686 break;
2687
2688 /*
2689 * In CLOSING STATE in addition to the processing for
2690 * the ESTABLISHED state if the ACK acknowledges our FIN
2691 * then enter the TIME-WAIT state, otherwise ignore
2692 * the segment.
2693 */
2694 case TCPS_CLOSING:
2695 if (ourfinisacked) {
2696 tp->t_state = TCPS_TIME_WAIT;
2697 tcp_canceltimers(tp);
2698 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2699 soisdisconnected(so);
2700 }
2701 break;
2702
2703 /*
2704 * In LAST_ACK, we may still be waiting for data to drain
2705 * and/or to be acked, as well as for the ack of our FIN.
2706 * If our FIN is now acknowledged, delete the TCB,
2707 * enter the closed state and return.
2708 */
2709 case TCPS_LAST_ACK:
2710 if (ourfinisacked) {
2711 tp = tcp_close(tp);
2712 goto drop;
2713 }
2714 break;
2715
2716 /*
2717 * In TIME_WAIT state the only thing that should arrive
2718 * is a retransmission of the remote FIN. Acknowledge
2719 * it and restart the finack timer.
2720 */
2721 case TCPS_TIME_WAIT:
2722 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2723 goto dropafterack;
2724 }
2725 }
2726
2727 step6:
2728 /*
2729 * Update window information.
2730 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2731 */
2732 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2733 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2734 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2735 /* keep track of pure window updates */
2736 if (tlen == 0 &&
2737 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2738 TCP_STATINC(TCP_STAT_RCVWINUPD);
2739 tp->snd_wnd = tiwin;
2740 tp->snd_wl1 = th->th_seq;
2741 tp->snd_wl2 = th->th_ack;
2742 if (tp->snd_wnd > tp->max_sndwnd)
2743 tp->max_sndwnd = tp->snd_wnd;
2744 needoutput = 1;
2745 }
2746
2747 /*
2748 * Process segments with URG.
2749 */
2750 if ((tiflags & TH_URG) && th->th_urp &&
2751 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2752 /*
2753 * This is a kludge, but if we receive and accept
2754 * random urgent pointers, we'll crash in
2755 * soreceive. It's hard to imagine someone
2756 * actually wanting to send this much urgent data.
2757 */
2758 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2759 th->th_urp = 0; /* XXX */
2760 tiflags &= ~TH_URG; /* XXX */
2761 goto dodata; /* XXX */
2762 }
2763 /*
2764 * If this segment advances the known urgent pointer,
2765 * then mark the data stream. This should not happen
2766 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2767 * a FIN has been received from the remote side.
2768 * In these states we ignore the URG.
2769 *
2770 * According to RFC961 (Assigned Protocols),
2771 * the urgent pointer points to the last octet
2772 * of urgent data. We continue, however,
2773 * to consider it to indicate the first octet
2774 * of data past the urgent section as the original
2775 * spec states (in one of two places).
2776 */
2777 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2778 tp->rcv_up = th->th_seq + th->th_urp;
2779 so->so_oobmark = so->so_rcv.sb_cc +
2780 (tp->rcv_up - tp->rcv_nxt) - 1;
2781 if (so->so_oobmark == 0)
2782 so->so_state |= SS_RCVATMARK;
2783 sohasoutofband(so);
2784 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2785 }
2786 /*
2787 * Remove out of band data so doesn't get presented to user.
2788 * This can happen independent of advancing the URG pointer,
2789 * but if two URG's are pending at once, some out-of-band
2790 * data may creep in... ick.
2791 */
2792 if (th->th_urp <= (u_int16_t)tlen &&
2793 (so->so_options & SO_OOBINLINE) == 0)
2794 tcp_pulloutofband(so, th, m, hdroptlen);
2795 } else
2796 /*
2797 * If no out of band data is expected,
2798 * pull receive urgent pointer along
2799 * with the receive window.
2800 */
2801 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2802 tp->rcv_up = tp->rcv_nxt;
2803 dodata: /* XXX */
2804
2805 /*
2806 * Process the segment text, merging it into the TCP sequencing queue,
2807 * and arranging for acknowledgement of receipt if necessary.
2808 * This process logically involves adjusting tp->rcv_wnd as data
2809 * is presented to the user (this happens in tcp_usrreq.c,
2810 * tcp_rcvd()). If a FIN has already been received on this
2811 * connection then we just ignore the text.
2812 */
2813 if ((tlen || (tiflags & TH_FIN)) &&
2814 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2815 /*
2816 * Insert segment ti into reassembly queue of tcp with
2817 * control block tp. Return TH_FIN if reassembly now includes
2818 * a segment with FIN. The macro form does the common case
2819 * inline (segment is the next to be received on an
2820 * established connection, and the queue is empty),
2821 * avoiding linkage into and removal from the queue and
2822 * repetition of various conversions.
2823 * Set DELACK for segments received in order, but ack
2824 * immediately when segments are out of order
2825 * (so fast retransmit can work).
2826 */
2827 /* NOTE: this was TCP_REASS() macro, but used only once */
2828 TCP_REASS_LOCK(tp);
2829 if (th->th_seq == tp->rcv_nxt &&
2830 TAILQ_FIRST(&tp->segq) == NULL &&
2831 tp->t_state == TCPS_ESTABLISHED) {
2832 tcp_setup_ack(tp, th);
2833 tp->rcv_nxt += tlen;
2834 tiflags = th->th_flags & TH_FIN;
2835 tcps = TCP_STAT_GETREF();
2836 tcps[TCP_STAT_RCVPACK]++;
2837 tcps[TCP_STAT_RCVBYTE] += tlen;
2838 TCP_STAT_PUTREF();
2839 nd6_hint(tp);
2840 if (so->so_state & SS_CANTRCVMORE)
2841 m_freem(m);
2842 else {
2843 m_adj(m, hdroptlen);
2844 sbappendstream(&(so)->so_rcv, m);
2845 }
2846 TCP_REASS_UNLOCK(tp);
2847 sorwakeup(so);
2848 } else {
2849 m_adj(m, hdroptlen);
2850 tiflags = tcp_reass(tp, th, m, tlen);
2851 tp->t_flags |= TF_ACKNOW;
2852 }
2853
2854 /*
2855 * Note the amount of data that peer has sent into
2856 * our window, in order to estimate the sender's
2857 * buffer size.
2858 */
2859 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2860 } else {
2861 m_freem(m);
2862 m = NULL;
2863 tiflags &= ~TH_FIN;
2864 }
2865
2866 /*
2867 * If FIN is received ACK the FIN and let the user know
2868 * that the connection is closing. Ignore a FIN received before
2869 * the connection is fully established.
2870 */
2871 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2872 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2873 socantrcvmore(so);
2874 tp->t_flags |= TF_ACKNOW;
2875 tp->rcv_nxt++;
2876 }
2877 switch (tp->t_state) {
2878
2879 /*
2880 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2881 */
2882 case TCPS_ESTABLISHED:
2883 tp->t_state = TCPS_CLOSE_WAIT;
2884 break;
2885
2886 /*
2887 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2888 * enter the CLOSING state.
2889 */
2890 case TCPS_FIN_WAIT_1:
2891 tp->t_state = TCPS_CLOSING;
2892 break;
2893
2894 /*
2895 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2896 * starting the time-wait timer, turning off the other
2897 * standard timers.
2898 */
2899 case TCPS_FIN_WAIT_2:
2900 tp->t_state = TCPS_TIME_WAIT;
2901 tcp_canceltimers(tp);
2902 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2903 soisdisconnected(so);
2904 break;
2905
2906 /*
2907 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2908 */
2909 case TCPS_TIME_WAIT:
2910 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2911 break;
2912 }
2913 }
2914 #ifdef TCP_DEBUG
2915 if (so->so_options & SO_DEBUG)
2916 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2917 #endif
2918
2919 /*
2920 * Return any desired output.
2921 */
2922 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2923 KERNEL_LOCK(1, NULL);
2924 (void) tcp_output(tp);
2925 KERNEL_UNLOCK_ONE(NULL);
2926 }
2927 if (tcp_saveti)
2928 m_freem(tcp_saveti);
2929
2930 if (tp->t_state == TCPS_TIME_WAIT
2931 && (so->so_state & SS_NOFDREF)
2932 && (tp->t_inpcb || af != AF_INET)
2933 && (tp->t_in6pcb || af != AF_INET6)
2934 && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
2935 && TAILQ_EMPTY(&tp->segq)
2936 && vtw_add(af, tp)) {
2937 ;
2938 }
2939 return;
2940
2941 badsyn:
2942 /*
2943 * Received a bad SYN. Increment counters and dropwithreset.
2944 */
2945 TCP_STATINC(TCP_STAT_BADSYN);
2946 tp = NULL;
2947 goto dropwithreset;
2948
2949 dropafterack:
2950 /*
2951 * Generate an ACK dropping incoming segment if it occupies
2952 * sequence space, where the ACK reflects our state.
2953 */
2954 if (tiflags & TH_RST)
2955 goto drop;
2956 goto dropafterack2;
2957
2958 dropafterack_ratelim:
2959 /*
2960 * We may want to rate-limit ACKs against SYN/RST attack.
2961 */
2962 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
2963 tcp_ackdrop_ppslim) == 0) {
2964 /* XXX stat */
2965 goto drop;
2966 }
2967 /* ...fall into dropafterack2... */
2968
2969 dropafterack2:
2970 m_freem(m);
2971 tp->t_flags |= TF_ACKNOW;
2972 KERNEL_LOCK(1, NULL);
2973 (void) tcp_output(tp);
2974 KERNEL_UNLOCK_ONE(NULL);
2975 if (tcp_saveti)
2976 m_freem(tcp_saveti);
2977 return;
2978
2979 dropwithreset_ratelim:
2980 /*
2981 * We may want to rate-limit RSTs in certain situations,
2982 * particularly if we are sending an RST in response to
2983 * an attempt to connect to or otherwise communicate with
2984 * a port for which we have no socket.
2985 */
2986 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2987 tcp_rst_ppslim) == 0) {
2988 /* XXX stat */
2989 goto drop;
2990 }
2991 /* ...fall into dropwithreset... */
2992
2993 dropwithreset:
2994 /*
2995 * Generate a RST, dropping incoming segment.
2996 * Make ACK acceptable to originator of segment.
2997 */
2998 if (tiflags & TH_RST)
2999 goto drop;
3000 if (tiflags & TH_ACK) {
3001 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3002 } else {
3003 if (tiflags & TH_SYN)
3004 tlen++;
3005 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
3006 TH_RST|TH_ACK);
3007 }
3008 if (tcp_saveti)
3009 m_freem(tcp_saveti);
3010 return;
3011
3012 badcsum:
3013 drop:
3014 /*
3015 * Drop space held by incoming segment and return.
3016 */
3017 if (tp) {
3018 if (tp->t_inpcb)
3019 so = tp->t_inpcb->inp_socket;
3020 #ifdef INET6
3021 else if (tp->t_in6pcb)
3022 so = tp->t_in6pcb->in6p_socket;
3023 #endif
3024 else
3025 so = NULL;
3026 #ifdef TCP_DEBUG
3027 if (so && (so->so_options & SO_DEBUG) != 0)
3028 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
3029 #endif
3030 }
3031 if (tcp_saveti)
3032 m_freem(tcp_saveti);
3033 m_freem(m);
3034 return;
3035 }
3036
3037 #ifdef TCP_SIGNATURE
3038 int
3039 tcp_signature_apply(void *fstate, void *data, u_int len)
3040 {
3041
3042 MD5Update(fstate, (u_char *)data, len);
3043 return (0);
3044 }
3045
3046 struct secasvar *
3047 tcp_signature_getsav(struct mbuf *m)
3048 {
3049 struct ip *ip;
3050 struct ip6_hdr *ip6;
3051
3052 ip = mtod(m, struct ip *);
3053 switch (ip->ip_v) {
3054 case 4:
3055 ip = mtod(m, struct ip *);
3056 ip6 = NULL;
3057 break;
3058 case 6:
3059 ip = NULL;
3060 ip6 = mtod(m, struct ip6_hdr *);
3061 break;
3062 default:
3063 return (NULL);
3064 }
3065
3066 #ifdef IPSEC
3067 union sockaddr_union dst;
3068
3069 /* Extract the destination from the IP header in the mbuf. */
3070 memset(&dst, 0, sizeof(union sockaddr_union));
3071 if (ip != NULL) {
3072 dst.sa.sa_len = sizeof(struct sockaddr_in);
3073 dst.sa.sa_family = AF_INET;
3074 dst.sin.sin_addr = ip->ip_dst;
3075 } else {
3076 dst.sa.sa_len = sizeof(struct sockaddr_in6);
3077 dst.sa.sa_family = AF_INET6;
3078 dst.sin6.sin6_addr = ip6->ip6_dst;
3079 }
3080
3081 /*
3082 * Look up an SADB entry which matches the address of the peer.
3083 */
3084 return KEY_LOOKUP_SA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0);
3085 #else
3086 return NULL;
3087 #endif
3088 }
3089
3090 int
3091 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
3092 struct secasvar *sav, char *sig)
3093 {
3094 MD5_CTX ctx;
3095 struct ip *ip;
3096 struct ipovly *ipovly;
3097 #ifdef INET6
3098 struct ip6_hdr *ip6;
3099 struct ip6_hdr_pseudo ip6pseudo;
3100 #endif /* INET6 */
3101 struct ippseudo ippseudo;
3102 struct tcphdr th0;
3103 int l, tcphdrlen;
3104
3105 if (sav == NULL)
3106 return (-1);
3107
3108 tcphdrlen = th->th_off * 4;
3109
3110 switch (mtod(m, struct ip *)->ip_v) {
3111 case 4:
3112 MD5Init(&ctx);
3113 ip = mtod(m, struct ip *);
3114 memset(&ippseudo, 0, sizeof(ippseudo));
3115 ipovly = (struct ipovly *)ip;
3116 ippseudo.ippseudo_src = ipovly->ih_src;
3117 ippseudo.ippseudo_dst = ipovly->ih_dst;
3118 ippseudo.ippseudo_pad = 0;
3119 ippseudo.ippseudo_p = IPPROTO_TCP;
3120 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
3121 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
3122 break;
3123 #if INET6
3124 case 6:
3125 MD5Init(&ctx);
3126 ip6 = mtod(m, struct ip6_hdr *);
3127 memset(&ip6pseudo, 0, sizeof(ip6pseudo));
3128 ip6pseudo.ip6ph_src = ip6->ip6_src;
3129 in6_clearscope(&ip6pseudo.ip6ph_src);
3130 ip6pseudo.ip6ph_dst = ip6->ip6_dst;
3131 in6_clearscope(&ip6pseudo.ip6ph_dst);
3132 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
3133 ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
3134 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
3135 break;
3136 #endif /* INET6 */
3137 default:
3138 return (-1);
3139 }
3140
3141 th0 = *th;
3142 th0.th_sum = 0;
3143 MD5Update(&ctx, (char *)&th0, sizeof(th0));
3144
3145 l = m->m_pkthdr.len - thoff - tcphdrlen;
3146 if (l > 0)
3147 m_apply(m, thoff + tcphdrlen,
3148 m->m_pkthdr.len - thoff - tcphdrlen,
3149 tcp_signature_apply, &ctx);
3150
3151 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3152 MD5Final(sig, &ctx);
3153
3154 return (0);
3155 }
3156 #endif
3157
3158 /*
3159 * tcp_dooptions: parse and process tcp options.
3160 *
3161 * returns -1 if this segment should be dropped. (eg. wrong signature)
3162 * otherwise returns 0.
3163 */
3164
3165 static int
3166 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt, struct tcphdr *th,
3167 struct mbuf *m, int toff, struct tcp_opt_info *oi)
3168 {
3169 u_int16_t mss;
3170 int opt, optlen = 0;
3171 #ifdef TCP_SIGNATURE
3172 void *sigp = NULL;
3173 char sigbuf[TCP_SIGLEN];
3174 struct secasvar *sav = NULL;
3175 #endif
3176
3177 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
3178 opt = cp[0];
3179 if (opt == TCPOPT_EOL)
3180 break;
3181 if (opt == TCPOPT_NOP)
3182 optlen = 1;
3183 else {
3184 if (cnt < 2)
3185 break;
3186 optlen = cp[1];
3187 if (optlen < 2 || optlen > cnt)
3188 break;
3189 }
3190 switch (opt) {
3191
3192 default:
3193 continue;
3194
3195 case TCPOPT_MAXSEG:
3196 if (optlen != TCPOLEN_MAXSEG)
3197 continue;
3198 if (!(th->th_flags & TH_SYN))
3199 continue;
3200 if (TCPS_HAVERCVDSYN(tp->t_state))
3201 continue;
3202 bcopy(cp + 2, &mss, sizeof(mss));
3203 oi->maxseg = ntohs(mss);
3204 break;
3205
3206 case TCPOPT_WINDOW:
3207 if (optlen != TCPOLEN_WINDOW)
3208 continue;
3209 if (!(th->th_flags & TH_SYN))
3210 continue;
3211 if (TCPS_HAVERCVDSYN(tp->t_state))
3212 continue;
3213 tp->t_flags |= TF_RCVD_SCALE;
3214 tp->requested_s_scale = cp[2];
3215 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
3216 char buf[INET6_ADDRSTRLEN];
3217 struct ip *ip = mtod(m, struct ip *);
3218 #ifdef INET6
3219 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
3220 #endif
3221 if (ip)
3222 in_print(buf, sizeof(buf),
3223 &ip->ip_src);
3224 #ifdef INET6
3225 else if (ip6)
3226 in6_print(buf, sizeof(buf),
3227 &ip6->ip6_src);
3228 #endif
3229 else
3230 strlcpy(buf, "(unknown)", sizeof(buf));
3231 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
3232 "assuming %d\n",
3233 tp->requested_s_scale, buf,
3234 TCP_MAX_WINSHIFT);
3235 tp->requested_s_scale = TCP_MAX_WINSHIFT;
3236 }
3237 break;
3238
3239 case TCPOPT_TIMESTAMP:
3240 if (optlen != TCPOLEN_TIMESTAMP)
3241 continue;
3242 oi->ts_present = 1;
3243 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
3244 NTOHL(oi->ts_val);
3245 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
3246 NTOHL(oi->ts_ecr);
3247
3248 if (!(th->th_flags & TH_SYN))
3249 continue;
3250 if (TCPS_HAVERCVDSYN(tp->t_state))
3251 continue;
3252 /*
3253 * A timestamp received in a SYN makes
3254 * it ok to send timestamp requests and replies.
3255 */
3256 tp->t_flags |= TF_RCVD_TSTMP;
3257 tp->ts_recent = oi->ts_val;
3258 tp->ts_recent_age = tcp_now;
3259 break;
3260
3261 case TCPOPT_SACK_PERMITTED:
3262 if (optlen != TCPOLEN_SACK_PERMITTED)
3263 continue;
3264 if (!(th->th_flags & TH_SYN))
3265 continue;
3266 if (TCPS_HAVERCVDSYN(tp->t_state))
3267 continue;
3268 if (tcp_do_sack) {
3269 tp->t_flags |= TF_SACK_PERMIT;
3270 tp->t_flags |= TF_WILL_SACK;
3271 }
3272 break;
3273
3274 case TCPOPT_SACK:
3275 tcp_sack_option(tp, th, cp, optlen);
3276 break;
3277 #ifdef TCP_SIGNATURE
3278 case TCPOPT_SIGNATURE:
3279 if (optlen != TCPOLEN_SIGNATURE)
3280 continue;
3281 if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN))
3282 return (-1);
3283
3284 sigp = sigbuf;
3285 memcpy(sigbuf, cp + 2, TCP_SIGLEN);
3286 tp->t_flags |= TF_SIGNATURE;
3287 break;
3288 #endif
3289 }
3290 }
3291
3292 #ifndef TCP_SIGNATURE
3293 return 0;
3294 #else
3295 if (tp->t_flags & TF_SIGNATURE) {
3296 sav = tcp_signature_getsav(m);
3297 if (sav == NULL && tp->t_state == TCPS_LISTEN)
3298 return (-1);
3299 }
3300
3301 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE))
3302 goto out;
3303
3304 if (sigp) {
3305 char sig[TCP_SIGLEN];
3306
3307 tcp_fields_to_net(th);
3308 if (tcp_signature(m, th, toff, sav, sig) < 0) {
3309 tcp_fields_to_host(th);
3310 goto out;
3311 }
3312 tcp_fields_to_host(th);
3313
3314 if (memcmp(sig, sigp, TCP_SIGLEN)) {
3315 TCP_STATINC(TCP_STAT_BADSIG);
3316 goto out;
3317 } else
3318 TCP_STATINC(TCP_STAT_GOODSIG);
3319
3320 key_sa_recordxfer(sav, m);
3321 KEY_SA_UNREF(&sav);
3322 }
3323 return 0;
3324 out:
3325 if (sav != NULL)
3326 KEY_SA_UNREF(&sav);
3327 return -1;
3328 #endif
3329 }
3330
3331 /*
3332 * Pull out of band byte out of a segment so
3333 * it doesn't appear in the user's data queue.
3334 * It is still reflected in the segment length for
3335 * sequencing purposes.
3336 */
3337 void
3338 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3339 struct mbuf *m, int off)
3340 {
3341 int cnt = off + th->th_urp - 1;
3342
3343 while (cnt >= 0) {
3344 if (m->m_len > cnt) {
3345 char *cp = mtod(m, char *) + cnt;
3346 struct tcpcb *tp = sototcpcb(so);
3347
3348 tp->t_iobc = *cp;
3349 tp->t_oobflags |= TCPOOB_HAVEDATA;
3350 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3351 m->m_len--;
3352 return;
3353 }
3354 cnt -= m->m_len;
3355 m = m->m_next;
3356 if (m == 0)
3357 break;
3358 }
3359 panic("tcp_pulloutofband");
3360 }
3361
3362 /*
3363 * Collect new round-trip time estimate
3364 * and update averages and current timeout.
3365 *
3366 * rtt is in units of slow ticks (typically 500 ms) -- essentially the
3367 * difference of two timestamps.
3368 */
3369 void
3370 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3371 {
3372 int32_t delta;
3373
3374 TCP_STATINC(TCP_STAT_RTTUPDATED);
3375 if (tp->t_srtt != 0) {
3376 /*
3377 * Compute the amount to add to srtt for smoothing,
3378 * *alpha, or 2^(-TCP_RTT_SHIFT). Because
3379 * srtt is stored in 1/32 slow ticks, we conceptually
3380 * shift left 5 bits, subtract srtt to get the
3381 * diference, and then shift right by TCP_RTT_SHIFT
3382 * (3) to obtain 1/8 of the difference.
3383 */
3384 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3385 /*
3386 * This can never happen, because delta's lowest
3387 * possible value is 1/8 of t_srtt. But if it does,
3388 * set srtt to some reasonable value, here chosen
3389 * as 1/8 tick.
3390 */
3391 if ((tp->t_srtt += delta) <= 0)
3392 tp->t_srtt = 1 << 2;
3393 /*
3394 * RFC2988 requires that rttvar be updated first.
3395 * This code is compliant because "delta" is the old
3396 * srtt minus the new observation (scaled).
3397 *
3398 * RFC2988 says:
3399 * rttvar = (1-beta) * rttvar + beta * |srtt-observed|
3400 *
3401 * delta is in units of 1/32 ticks, and has then been
3402 * divided by 8. This is equivalent to being in 1/16s
3403 * units and divided by 4. Subtract from it 1/4 of
3404 * the existing rttvar to form the (signed) amount to
3405 * adjust.
3406 */
3407 if (delta < 0)
3408 delta = -delta;
3409 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3410 /*
3411 * As with srtt, this should never happen. There is
3412 * no support in RFC2988 for this operation. But 1/4s
3413 * as rttvar when faced with something arguably wrong
3414 * is ok.
3415 */
3416 if ((tp->t_rttvar += delta) <= 0)
3417 tp->t_rttvar = 1 << 2;
3418
3419 /*
3420 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
3421 * Problem is: it doesn't work. Disabled by defaulting
3422 * tcp_rttlocal to 0; see corresponding code in
3423 * tcp_subr that selects local vs remote in a different way.
3424 *
3425 * The static branch prediction hint here should be removed
3426 * when the rtt estimator is fixed and the rtt_enable code
3427 * is turned back on.
3428 */
3429 if (__predict_false(tcp_rttlocal) && tcp_msl_enable
3430 && tp->t_srtt > tcp_msl_remote_threshold
3431 && tp->t_msl < tcp_msl_remote) {
3432 tp->t_msl = tcp_msl_remote;
3433 }
3434 } else {
3435 /*
3436 * This is the first measurement. Per RFC2988, 2.2,
3437 * set rtt=R and srtt=R/2.
3438 * For srtt, storage representation is 1/32 ticks,
3439 * so shift left by 5.
3440 * For rttvar, storage representation is 1/16 ticks,
3441 * So shift left by 4, but then right by 1 to halve.
3442 */
3443 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3444 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3445 }
3446 tp->t_rtttime = 0;
3447 tp->t_rxtshift = 0;
3448
3449 /*
3450 * the retransmit should happen at rtt + 4 * rttvar.
3451 * Because of the way we do the smoothing, srtt and rttvar
3452 * will each average +1/2 tick of bias. When we compute
3453 * the retransmit timer, we want 1/2 tick of rounding and
3454 * 1 extra tick because of +-1/2 tick uncertainty in the
3455 * firing of the timer. The bias will give us exactly the
3456 * 1.5 tick we need. But, because the bias is
3457 * statistical, we have to test that we don't drop below
3458 * the minimum feasible timer (which is 2 ticks).
3459 */
3460 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3461 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3462
3463 /*
3464 * We received an ack for a packet that wasn't retransmitted;
3465 * it is probably safe to discard any error indications we've
3466 * received recently. This isn't quite right, but close enough
3467 * for now (a route might have failed after we sent a segment,
3468 * and the return path might not be symmetrical).
3469 */
3470 tp->t_softerror = 0;
3471 }
3472
3473
3474 /*
3475 * TCP compressed state engine. Currently used to hold compressed
3476 * state for SYN_RECEIVED.
3477 */
3478
3479 u_long syn_cache_count;
3480 u_int32_t syn_hash1, syn_hash2;
3481
3482 #define SYN_HASH(sa, sp, dp) \
3483 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3484 ((u_int32_t)(sp)))^syn_hash2)))
3485 #ifndef INET6
3486 #define SYN_HASHALL(hash, src, dst) \
3487 do { \
3488 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3489 ((const struct sockaddr_in *)(src))->sin_port, \
3490 ((const struct sockaddr_in *)(dst))->sin_port); \
3491 } while (/*CONSTCOND*/ 0)
3492 #else
3493 #define SYN_HASH6(sa, sp, dp) \
3494 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3495 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3496 & 0x7fffffff)
3497
3498 #define SYN_HASHALL(hash, src, dst) \
3499 do { \
3500 switch ((src)->sa_family) { \
3501 case AF_INET: \
3502 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3503 ((const struct sockaddr_in *)(src))->sin_port, \
3504 ((const struct sockaddr_in *)(dst))->sin_port); \
3505 break; \
3506 case AF_INET6: \
3507 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3508 ((const struct sockaddr_in6 *)(src))->sin6_port, \
3509 ((const struct sockaddr_in6 *)(dst))->sin6_port); \
3510 break; \
3511 default: \
3512 hash = 0; \
3513 } \
3514 } while (/*CONSTCOND*/0)
3515 #endif /* INET6 */
3516
3517 static struct pool syn_cache_pool;
3518
3519 /*
3520 * We don't estimate RTT with SYNs, so each packet starts with the default
3521 * RTT and each timer step has a fixed timeout value.
3522 */
3523 static inline void
3524 syn_cache_timer_arm(struct syn_cache *sc)
3525 {
3526
3527 TCPT_RANGESET(sc->sc_rxtcur,
3528 TCPTV_SRTTDFLT * tcp_backoff[sc->sc_rxtshift], TCPTV_MIN,
3529 TCPTV_REXMTMAX);
3530 callout_reset(&sc->sc_timer,
3531 sc->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, sc);
3532 }
3533
3534 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase)
3535
3536 static inline void
3537 syn_cache_rm(struct syn_cache *sc)
3538 {
3539 TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket,
3540 sc, sc_bucketq);
3541 sc->sc_tp = NULL;
3542 LIST_REMOVE(sc, sc_tpq);
3543 tcp_syn_cache[sc->sc_bucketidx].sch_length--;
3544 callout_stop(&sc->sc_timer);
3545 syn_cache_count--;
3546 }
3547
3548 static inline void
3549 syn_cache_put(struct syn_cache *sc)
3550 {
3551 if (sc->sc_ipopts)
3552 (void) m_free(sc->sc_ipopts);
3553 rtcache_free(&sc->sc_route);
3554 sc->sc_flags |= SCF_DEAD;
3555 if (!callout_invoking(&sc->sc_timer))
3556 callout_schedule(&(sc)->sc_timer, 1);
3557 }
3558
3559 void
3560 syn_cache_init(void)
3561 {
3562 int i;
3563
3564 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
3565 "synpl", NULL, IPL_SOFTNET);
3566
3567 /* Initialize the hash buckets. */
3568 for (i = 0; i < tcp_syn_cache_size; i++)
3569 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3570 }
3571
3572 void
3573 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3574 {
3575 struct syn_cache_head *scp;
3576 struct syn_cache *sc2;
3577 int s;
3578
3579 /*
3580 * If there are no entries in the hash table, reinitialize
3581 * the hash secrets.
3582 */
3583 if (syn_cache_count == 0) {
3584 syn_hash1 = cprng_fast32();
3585 syn_hash2 = cprng_fast32();
3586 }
3587
3588 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3589 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3590 scp = &tcp_syn_cache[sc->sc_bucketidx];
3591
3592 /*
3593 * Make sure that we don't overflow the per-bucket
3594 * limit or the total cache size limit.
3595 */
3596 s = splsoftnet();
3597 if (scp->sch_length >= tcp_syn_bucket_limit) {
3598 TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW);
3599 /*
3600 * The bucket is full. Toss the oldest element in the
3601 * bucket. This will be the first entry in the bucket.
3602 */
3603 sc2 = TAILQ_FIRST(&scp->sch_bucket);
3604 #ifdef DIAGNOSTIC
3605 /*
3606 * This should never happen; we should always find an
3607 * entry in our bucket.
3608 */
3609 if (sc2 == NULL)
3610 panic("syn_cache_insert: bucketoverflow: impossible");
3611 #endif
3612 syn_cache_rm(sc2);
3613 syn_cache_put(sc2); /* calls pool_put but see spl above */
3614 } else if (syn_cache_count >= tcp_syn_cache_limit) {
3615 struct syn_cache_head *scp2, *sce;
3616
3617 TCP_STATINC(TCP_STAT_SC_OVERFLOWED);
3618 /*
3619 * The cache is full. Toss the oldest entry in the
3620 * first non-empty bucket we can find.
3621 *
3622 * XXX We would really like to toss the oldest
3623 * entry in the cache, but we hope that this
3624 * condition doesn't happen very often.
3625 */
3626 scp2 = scp;
3627 if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3628 sce = &tcp_syn_cache[tcp_syn_cache_size];
3629 for (++scp2; scp2 != scp; scp2++) {
3630 if (scp2 >= sce)
3631 scp2 = &tcp_syn_cache[0];
3632 if (! TAILQ_EMPTY(&scp2->sch_bucket))
3633 break;
3634 }
3635 #ifdef DIAGNOSTIC
3636 /*
3637 * This should never happen; we should always find a
3638 * non-empty bucket.
3639 */
3640 if (scp2 == scp)
3641 panic("syn_cache_insert: cacheoverflow: "
3642 "impossible");
3643 #endif
3644 }
3645 sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3646 syn_cache_rm(sc2);
3647 syn_cache_put(sc2); /* calls pool_put but see spl above */
3648 }
3649
3650 /*
3651 * Initialize the entry's timer.
3652 */
3653 sc->sc_rxttot = 0;
3654 sc->sc_rxtshift = 0;
3655 syn_cache_timer_arm(sc);
3656
3657 /* Link it from tcpcb entry */
3658 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3659
3660 /* Put it into the bucket. */
3661 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3662 scp->sch_length++;
3663 syn_cache_count++;
3664
3665 TCP_STATINC(TCP_STAT_SC_ADDED);
3666 splx(s);
3667 }
3668
3669 /*
3670 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3671 * If we have retransmitted an entry the maximum number of times, expire
3672 * that entry.
3673 */
3674 static void
3675 syn_cache_timer(void *arg)
3676 {
3677 struct syn_cache *sc = arg;
3678
3679 mutex_enter(softnet_lock);
3680 KERNEL_LOCK(1, NULL);
3681
3682 callout_ack(&sc->sc_timer);
3683
3684 if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3685 TCP_STATINC(TCP_STAT_SC_DELAYED_FREE);
3686 goto free;
3687 }
3688
3689 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3690 /* Drop it -- too many retransmissions. */
3691 goto dropit;
3692 }
3693
3694 /*
3695 * Compute the total amount of time this entry has
3696 * been on a queue. If this entry has been on longer
3697 * than the keep alive timer would allow, expire it.
3698 */
3699 sc->sc_rxttot += sc->sc_rxtcur;
3700 if (sc->sc_rxttot >= tcp_keepinit)
3701 goto dropit;
3702
3703 TCP_STATINC(TCP_STAT_SC_RETRANSMITTED);
3704 (void)syn_cache_respond(sc);
3705
3706 /* Advance the timer back-off. */
3707 sc->sc_rxtshift++;
3708 syn_cache_timer_arm(sc);
3709
3710 goto out;
3711
3712 dropit:
3713 TCP_STATINC(TCP_STAT_SC_TIMED_OUT);
3714 syn_cache_rm(sc);
3715 if (sc->sc_ipopts)
3716 (void) m_free(sc->sc_ipopts);
3717 rtcache_free(&sc->sc_route);
3718
3719 free:
3720 callout_destroy(&sc->sc_timer);
3721 pool_put(&syn_cache_pool, sc);
3722
3723 out:
3724 KERNEL_UNLOCK_ONE(NULL);
3725 mutex_exit(softnet_lock);
3726 }
3727
3728 /*
3729 * Remove syn cache created by the specified tcb entry,
3730 * because this does not make sense to keep them
3731 * (if there's no tcb entry, syn cache entry will never be used)
3732 */
3733 void
3734 syn_cache_cleanup(struct tcpcb *tp)
3735 {
3736 struct syn_cache *sc, *nsc;
3737 int s;
3738
3739 s = splsoftnet();
3740
3741 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3742 nsc = LIST_NEXT(sc, sc_tpq);
3743
3744 #ifdef DIAGNOSTIC
3745 if (sc->sc_tp != tp)
3746 panic("invalid sc_tp in syn_cache_cleanup");
3747 #endif
3748 syn_cache_rm(sc);
3749 syn_cache_put(sc); /* calls pool_put but see spl above */
3750 }
3751 /* just for safety */
3752 LIST_INIT(&tp->t_sc);
3753
3754 splx(s);
3755 }
3756
3757 /*
3758 * Find an entry in the syn cache.
3759 */
3760 struct syn_cache *
3761 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3762 struct syn_cache_head **headp)
3763 {
3764 struct syn_cache *sc;
3765 struct syn_cache_head *scp;
3766 u_int32_t hash;
3767 int s;
3768
3769 SYN_HASHALL(hash, src, dst);
3770
3771 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3772 *headp = scp;
3773 s = splsoftnet();
3774 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3775 sc = TAILQ_NEXT(sc, sc_bucketq)) {
3776 if (sc->sc_hash != hash)
3777 continue;
3778 if (!memcmp(&sc->sc_src, src, src->sa_len) &&
3779 !memcmp(&sc->sc_dst, dst, dst->sa_len)) {
3780 splx(s);
3781 return (sc);
3782 }
3783 }
3784 splx(s);
3785 return (NULL);
3786 }
3787
3788 /*
3789 * This function gets called when we receive an ACK for a
3790 * socket in the LISTEN state. We look up the connection
3791 * in the syn cache, and if its there, we pull it out of
3792 * the cache and turn it into a full-blown connection in
3793 * the SYN-RECEIVED state.
3794 *
3795 * The return values may not be immediately obvious, and their effects
3796 * can be subtle, so here they are:
3797 *
3798 * NULL SYN was not found in cache; caller should drop the
3799 * packet and send an RST.
3800 *
3801 * -1 We were unable to create the new connection, and are
3802 * aborting it. An ACK,RST is being sent to the peer
3803 * (unless we got screwey sequence numbners; see below),
3804 * because the 3-way handshake has been completed. Caller
3805 * should not free the mbuf, since we may be using it. If
3806 * we are not, we will free it.
3807 *
3808 * Otherwise, the return value is a pointer to the new socket
3809 * associated with the connection.
3810 */
3811 struct socket *
3812 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3813 struct tcphdr *th, unsigned int hlen, unsigned int tlen,
3814 struct socket *so, struct mbuf *m)
3815 {
3816 struct syn_cache *sc;
3817 struct syn_cache_head *scp;
3818 struct inpcb *inp = NULL;
3819 #ifdef INET6
3820 struct in6pcb *in6p = NULL;
3821 #endif
3822 struct tcpcb *tp = 0;
3823 int s;
3824 struct socket *oso;
3825
3826 s = splsoftnet();
3827 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3828 splx(s);
3829 return (NULL);
3830 }
3831
3832 /*
3833 * Verify the sequence and ack numbers. Try getting the correct
3834 * response again.
3835 */
3836 if ((th->th_ack != sc->sc_iss + 1) ||
3837 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3838 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3839 m_freem(m);
3840 (void)syn_cache_respond(sc);
3841 splx(s);
3842 return ((struct socket *)(-1));
3843 }
3844
3845 /* Remove this cache entry */
3846 syn_cache_rm(sc);
3847 splx(s);
3848
3849 /*
3850 * Ok, create the full blown connection, and set things up
3851 * as they would have been set up if we had created the
3852 * connection when the SYN arrived. If we can't create
3853 * the connection, abort it.
3854 */
3855 /*
3856 * inp still has the OLD in_pcb stuff, set the
3857 * v6-related flags on the new guy, too. This is
3858 * done particularly for the case where an AF_INET6
3859 * socket is bound only to a port, and a v4 connection
3860 * comes in on that port.
3861 * we also copy the flowinfo from the original pcb
3862 * to the new one.
3863 */
3864 oso = so;
3865 so = sonewconn(so, true);
3866 if (so == NULL)
3867 goto resetandabort;
3868
3869 switch (so->so_proto->pr_domain->dom_family) {
3870 #ifdef INET
3871 case AF_INET:
3872 inp = sotoinpcb(so);
3873 break;
3874 #endif
3875 #ifdef INET6
3876 case AF_INET6:
3877 in6p = sotoin6pcb(so);
3878 break;
3879 #endif
3880 }
3881 switch (src->sa_family) {
3882 #ifdef INET
3883 case AF_INET:
3884 if (inp) {
3885 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3886 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3887 inp->inp_options = ip_srcroute(m);
3888 in_pcbstate(inp, INP_BOUND);
3889 if (inp->inp_options == NULL) {
3890 inp->inp_options = sc->sc_ipopts;
3891 sc->sc_ipopts = NULL;
3892 }
3893 }
3894 #ifdef INET6
3895 else if (in6p) {
3896 /* IPv4 packet to AF_INET6 socket */
3897 memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr));
3898 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3899 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3900 &in6p->in6p_laddr.s6_addr32[3],
3901 sizeof(((struct sockaddr_in *)dst)->sin_addr));
3902 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
3903 in6totcpcb(in6p)->t_family = AF_INET;
3904 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
3905 in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
3906 else
3907 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
3908 in6_pcbstate(in6p, IN6P_BOUND);
3909 }
3910 #endif
3911 break;
3912 #endif
3913 #ifdef INET6
3914 case AF_INET6:
3915 if (in6p) {
3916 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
3917 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
3918 in6_pcbstate(in6p, IN6P_BOUND);
3919 }
3920 break;
3921 #endif
3922 }
3923 #ifdef INET6
3924 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
3925 struct in6pcb *oin6p = sotoin6pcb(oso);
3926 /* inherit socket options from the listening socket */
3927 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
3928 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
3929 m_freem(in6p->in6p_options);
3930 in6p->in6p_options = 0;
3931 }
3932 ip6_savecontrol(in6p, &in6p->in6p_options,
3933 mtod(m, struct ip6_hdr *), m);
3934 }
3935 #endif
3936
3937 #if defined(IPSEC)
3938 if (ipsec_used) {
3939 /*
3940 * we make a copy of policy, instead of sharing the policy, for
3941 * better behavior in terms of SA lookup and dead SA removal.
3942 */
3943 if (inp) {
3944 /* copy old policy into new socket's */
3945 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp,
3946 inp->inp_sp))
3947 printf("tcp_input: could not copy policy\n");
3948 }
3949 #ifdef INET6
3950 else if (in6p) {
3951 /* copy old policy into new socket's */
3952 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
3953 in6p->in6p_sp))
3954 printf("tcp_input: could not copy policy\n");
3955 }
3956 #endif
3957 }
3958 #endif
3959
3960 /*
3961 * Give the new socket our cached route reference.
3962 */
3963 if (inp) {
3964 rtcache_copy(&inp->inp_route, &sc->sc_route);
3965 rtcache_free(&sc->sc_route);
3966 }
3967 #ifdef INET6
3968 else {
3969 rtcache_copy(&in6p->in6p_route, &sc->sc_route);
3970 rtcache_free(&sc->sc_route);
3971 }
3972 #endif
3973
3974 if (inp) {
3975 struct sockaddr_in sin;
3976 memcpy(&sin, src, src->sa_len);
3977 if (in_pcbconnect(inp, &sin, &lwp0)) {
3978 goto resetandabort;
3979 }
3980 }
3981 #ifdef INET6
3982 else if (in6p) {
3983 struct sockaddr_in6 sin6;
3984 memcpy(&sin6, src, src->sa_len);
3985 if (src->sa_family == AF_INET) {
3986 /* IPv4 packet to AF_INET6 socket */
3987 in6_sin_2_v4mapsin6((struct sockaddr_in *)src, &sin6);
3988 }
3989 if (in6_pcbconnect(in6p, &sin6, NULL)) {
3990 goto resetandabort;
3991 }
3992 }
3993 #endif
3994 else {
3995 goto resetandabort;
3996 }
3997
3998 if (inp)
3999 tp = intotcpcb(inp);
4000 #ifdef INET6
4001 else if (in6p)
4002 tp = in6totcpcb(in6p);
4003 #endif
4004 else
4005 tp = NULL;
4006 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
4007 if (sc->sc_request_r_scale != 15) {
4008 tp->requested_s_scale = sc->sc_requested_s_scale;
4009 tp->request_r_scale = sc->sc_request_r_scale;
4010 tp->snd_scale = sc->sc_requested_s_scale;
4011 tp->rcv_scale = sc->sc_request_r_scale;
4012 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
4013 }
4014 if (sc->sc_flags & SCF_TIMESTAMP)
4015 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
4016 tp->ts_timebase = sc->sc_timebase;
4017
4018 tp->t_template = tcp_template(tp);
4019 if (tp->t_template == 0) {
4020 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
4021 so = NULL;
4022 m_freem(m);
4023 goto abort;
4024 }
4025
4026 tp->iss = sc->sc_iss;
4027 tp->irs = sc->sc_irs;
4028 tcp_sendseqinit(tp);
4029 tcp_rcvseqinit(tp);
4030 tp->t_state = TCPS_SYN_RECEIVED;
4031 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit);
4032 TCP_STATINC(TCP_STAT_ACCEPTS);
4033
4034 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
4035 tp->t_flags |= TF_WILL_SACK;
4036
4037 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
4038 tp->t_flags |= TF_ECN_PERMIT;
4039
4040 #ifdef TCP_SIGNATURE
4041 if (sc->sc_flags & SCF_SIGNATURE)
4042 tp->t_flags |= TF_SIGNATURE;
4043 #endif
4044
4045 /* Initialize tp->t_ourmss before we deal with the peer's! */
4046 tp->t_ourmss = sc->sc_ourmaxseg;
4047 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
4048
4049 /*
4050 * Initialize the initial congestion window. If we
4051 * had to retransmit the SYN,ACK, we must initialize cwnd
4052 * to 1 segment (i.e. the Loss Window).
4053 */
4054 if (sc->sc_rxtshift)
4055 tp->snd_cwnd = tp->t_peermss;
4056 else {
4057 int ss = tcp_init_win;
4058 #ifdef INET
4059 if (inp != NULL && in_localaddr(inp->inp_faddr))
4060 ss = tcp_init_win_local;
4061 #endif
4062 #ifdef INET6
4063 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
4064 ss = tcp_init_win_local;
4065 #endif
4066 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
4067 }
4068
4069 tcp_rmx_rtt(tp);
4070 tp->snd_wl1 = sc->sc_irs;
4071 tp->rcv_up = sc->sc_irs + 1;
4072
4073 /*
4074 * This is what whould have happened in tcp_output() when
4075 * the SYN,ACK was sent.
4076 */
4077 tp->snd_up = tp->snd_una;
4078 tp->snd_max = tp->snd_nxt = tp->iss+1;
4079 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
4080 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
4081 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
4082 tp->last_ack_sent = tp->rcv_nxt;
4083 tp->t_partialacks = -1;
4084 tp->t_dupacks = 0;
4085
4086 TCP_STATINC(TCP_STAT_SC_COMPLETED);
4087 s = splsoftnet();
4088 syn_cache_put(sc);
4089 splx(s);
4090 return (so);
4091
4092 resetandabort:
4093 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
4094 abort:
4095 if (so != NULL) {
4096 (void) soqremque(so, 1);
4097 (void) soabort(so);
4098 mutex_enter(softnet_lock);
4099 }
4100 s = splsoftnet();
4101 syn_cache_put(sc);
4102 splx(s);
4103 TCP_STATINC(TCP_STAT_SC_ABORTED);
4104 return ((struct socket *)(-1));
4105 }
4106
4107 /*
4108 * This function is called when we get a RST for a
4109 * non-existent connection, so that we can see if the
4110 * connection is in the syn cache. If it is, zap it.
4111 */
4112
4113 void
4114 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
4115 {
4116 struct syn_cache *sc;
4117 struct syn_cache_head *scp;
4118 int s = splsoftnet();
4119
4120 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4121 splx(s);
4122 return;
4123 }
4124 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
4125 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
4126 splx(s);
4127 return;
4128 }
4129 syn_cache_rm(sc);
4130 TCP_STATINC(TCP_STAT_SC_RESET);
4131 syn_cache_put(sc); /* calls pool_put but see spl above */
4132 splx(s);
4133 }
4134
4135 void
4136 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
4137 struct tcphdr *th)
4138 {
4139 struct syn_cache *sc;
4140 struct syn_cache_head *scp;
4141 int s;
4142
4143 s = splsoftnet();
4144 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4145 splx(s);
4146 return;
4147 }
4148 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
4149 if (ntohl (th->th_seq) != sc->sc_iss) {
4150 splx(s);
4151 return;
4152 }
4153
4154 /*
4155 * If we've retransmitted 3 times and this is our second error,
4156 * we remove the entry. Otherwise, we allow it to continue on.
4157 * This prevents us from incorrectly nuking an entry during a
4158 * spurious network outage.
4159 *
4160 * See tcp_notify().
4161 */
4162 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
4163 sc->sc_flags |= SCF_UNREACH;
4164 splx(s);
4165 return;
4166 }
4167
4168 syn_cache_rm(sc);
4169 TCP_STATINC(TCP_STAT_SC_UNREACH);
4170 syn_cache_put(sc); /* calls pool_put but see spl above */
4171 splx(s);
4172 }
4173
4174 /*
4175 * Given a LISTEN socket and an inbound SYN request, add
4176 * this to the syn cache, and send back a segment:
4177 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
4178 * to the source.
4179 *
4180 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
4181 * Doing so would require that we hold onto the data and deliver it
4182 * to the application. However, if we are the target of a SYN-flood
4183 * DoS attack, an attacker could send data which would eventually
4184 * consume all available buffer space if it were ACKed. By not ACKing
4185 * the data, we avoid this DoS scenario.
4186 */
4187 int
4188 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
4189 unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
4190 int optlen, struct tcp_opt_info *oi)
4191 {
4192 struct tcpcb tb, *tp;
4193 long win;
4194 struct syn_cache *sc;
4195 struct syn_cache_head *scp;
4196 struct mbuf *ipopts;
4197 struct tcp_opt_info opti;
4198 int s;
4199
4200 tp = sototcpcb(so);
4201
4202 memset(&opti, 0, sizeof(opti));
4203
4204 /*
4205 * Initialize some local state.
4206 */
4207 win = sbspace(&so->so_rcv);
4208 if (win > TCP_MAXWIN)
4209 win = TCP_MAXWIN;
4210
4211 #ifdef TCP_SIGNATURE
4212 if (optp || (tp->t_flags & TF_SIGNATURE))
4213 #else
4214 if (optp)
4215 #endif
4216 {
4217 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
4218 #ifdef TCP_SIGNATURE
4219 tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
4220 #endif
4221 tb.t_state = TCPS_LISTEN;
4222 if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
4223 sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
4224 return 0;
4225 } else
4226 tb.t_flags = 0;
4227
4228 switch (src->sa_family) {
4229 #ifdef INET
4230 case AF_INET:
4231 /*
4232 * Remember the IP options, if any.
4233 */
4234 ipopts = ip_srcroute(m);
4235 break;
4236 #endif
4237 default:
4238 ipopts = NULL;
4239 }
4240
4241 /*
4242 * See if we already have an entry for this connection.
4243 * If we do, resend the SYN,ACK. We do not count this
4244 * as a retransmission (XXX though maybe we should).
4245 */
4246 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
4247 TCP_STATINC(TCP_STAT_SC_DUPESYN);
4248 if (ipopts) {
4249 /*
4250 * If we were remembering a previous source route,
4251 * forget it and use the new one we've been given.
4252 */
4253 if (sc->sc_ipopts)
4254 (void)m_free(sc->sc_ipopts);
4255 sc->sc_ipopts = ipopts;
4256 }
4257 sc->sc_timestamp = tb.ts_recent;
4258 m_freem(m);
4259 if (syn_cache_respond(sc) == 0) {
4260 uint64_t *tcps = TCP_STAT_GETREF();
4261 tcps[TCP_STAT_SNDACKS]++;
4262 tcps[TCP_STAT_SNDTOTAL]++;
4263 TCP_STAT_PUTREF();
4264 }
4265 return 1;
4266 }
4267
4268 s = splsoftnet();
4269 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
4270 splx(s);
4271 if (sc == NULL) {
4272 if (ipopts)
4273 (void)m_free(ipopts);
4274 return 0;
4275 }
4276
4277 /*
4278 * Fill in the cache, and put the necessary IP and TCP
4279 * options into the reply.
4280 */
4281 memset(sc, 0, sizeof(struct syn_cache));
4282 callout_init(&sc->sc_timer, CALLOUT_MPSAFE);
4283 bcopy(src, &sc->sc_src, src->sa_len);
4284 bcopy(dst, &sc->sc_dst, dst->sa_len);
4285 sc->sc_flags = 0;
4286 sc->sc_ipopts = ipopts;
4287 sc->sc_irs = th->th_seq;
4288 switch (src->sa_family) {
4289 #ifdef INET
4290 case AF_INET:
4291 {
4292 struct sockaddr_in *srcin = (void *)src;
4293 struct sockaddr_in *dstin = (void *)dst;
4294
4295 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
4296 &srcin->sin_addr, dstin->sin_port,
4297 srcin->sin_port, sizeof(dstin->sin_addr), 0);
4298 break;
4299 }
4300 #endif /* INET */
4301 #ifdef INET6
4302 case AF_INET6:
4303 {
4304 struct sockaddr_in6 *srcin6 = (void *)src;
4305 struct sockaddr_in6 *dstin6 = (void *)dst;
4306
4307 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
4308 &srcin6->sin6_addr, dstin6->sin6_port,
4309 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
4310 break;
4311 }
4312 #endif /* INET6 */
4313 }
4314 sc->sc_peermaxseg = oi->maxseg;
4315 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
4316 m_get_rcvif_NOMPSAFE(m) : NULL, sc->sc_src.sa.sa_family);
4317 sc->sc_win = win;
4318 sc->sc_timebase = tcp_now - 1; /* see tcp_newtcpcb() */
4319 sc->sc_timestamp = tb.ts_recent;
4320 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
4321 (TF_REQ_TSTMP|TF_RCVD_TSTMP))
4322 sc->sc_flags |= SCF_TIMESTAMP;
4323 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
4324 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
4325 sc->sc_requested_s_scale = tb.requested_s_scale;
4326 sc->sc_request_r_scale = 0;
4327 /*
4328 * Pick the smallest possible scaling factor that
4329 * will still allow us to scale up to sb_max.
4330 *
4331 * We do this because there are broken firewalls that
4332 * will corrupt the window scale option, leading to
4333 * the other endpoint believing that our advertised
4334 * window is unscaled. At scale factors larger than
4335 * 5 the unscaled window will drop below 1500 bytes,
4336 * leading to serious problems when traversing these
4337 * broken firewalls.
4338 *
4339 * With the default sbmax of 256K, a scale factor
4340 * of 3 will be chosen by this algorithm. Those who
4341 * choose a larger sbmax should watch out
4342 * for the compatiblity problems mentioned above.
4343 *
4344 * RFC1323: The Window field in a SYN (i.e., a <SYN>
4345 * or <SYN,ACK>) segment itself is never scaled.
4346 */
4347 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
4348 (TCP_MAXWIN << sc->sc_request_r_scale) < sb_max)
4349 sc->sc_request_r_scale++;
4350 } else {
4351 sc->sc_requested_s_scale = 15;
4352 sc->sc_request_r_scale = 15;
4353 }
4354 if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
4355 sc->sc_flags |= SCF_SACK_PERMIT;
4356
4357 /*
4358 * ECN setup packet received.
4359 */
4360 if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn)
4361 sc->sc_flags |= SCF_ECN_PERMIT;
4362
4363 #ifdef TCP_SIGNATURE
4364 if (tb.t_flags & TF_SIGNATURE)
4365 sc->sc_flags |= SCF_SIGNATURE;
4366 #endif
4367 sc->sc_tp = tp;
4368 m_freem(m);
4369 if (syn_cache_respond(sc) == 0) {
4370 uint64_t *tcps = TCP_STAT_GETREF();
4371 tcps[TCP_STAT_SNDACKS]++;
4372 tcps[TCP_STAT_SNDTOTAL]++;
4373 TCP_STAT_PUTREF();
4374 syn_cache_insert(sc, tp);
4375 } else {
4376 s = splsoftnet();
4377 /*
4378 * syn_cache_put() will try to schedule the timer, so
4379 * we need to initialize it
4380 */
4381 syn_cache_timer_arm(sc);
4382 syn_cache_put(sc);
4383 splx(s);
4384 TCP_STATINC(TCP_STAT_SC_DROPPED);
4385 }
4386 return 1;
4387 }
4388
4389 /*
4390 * syn_cache_respond: (re)send SYN+ACK.
4391 *
4392 * returns 0 on success. otherwise returns an errno, typically ENOBUFS.
4393 */
4394
4395 int
4396 syn_cache_respond(struct syn_cache *sc)
4397 {
4398 #ifdef INET6
4399 struct rtentry *rt = NULL;
4400 #endif
4401 struct route *ro;
4402 u_int8_t *optp;
4403 int optlen, error;
4404 u_int16_t tlen;
4405 struct ip *ip = NULL;
4406 #ifdef INET6
4407 struct ip6_hdr *ip6 = NULL;
4408 #endif
4409 struct tcpcb *tp = NULL;
4410 struct tcphdr *th;
4411 struct mbuf *m;
4412 u_int hlen;
4413 #ifdef TCP_SIGNATURE
4414 struct secasvar *sav = NULL;
4415 u_int8_t *sigp = NULL;
4416 #endif
4417
4418 ro = &sc->sc_route;
4419 switch (sc->sc_src.sa.sa_family) {
4420 case AF_INET:
4421 hlen = sizeof(struct ip);
4422 break;
4423 #ifdef INET6
4424 case AF_INET6:
4425 hlen = sizeof(struct ip6_hdr);
4426 break;
4427 #endif
4428 default:
4429 return (EAFNOSUPPORT);
4430 }
4431
4432 /* worst case scanario, since we don't know the option size yet */
4433 tlen = hlen + sizeof(struct tcphdr) + MAX_TCPOPTLEN;
4434
4435 /*
4436 * Create the IP+TCP header from scratch.
4437 */
4438 #ifdef DIAGNOSTIC
4439 if (max_linkhdr + tlen > MCLBYTES)
4440 return ENOBUFS;
4441 #endif
4442
4443 MGETHDR(m, M_DONTWAIT, MT_DATA);
4444 if (m && (max_linkhdr + tlen) > MHLEN) {
4445 MCLGET(m, M_DONTWAIT);
4446 if ((m->m_flags & M_EXT) == 0) {
4447 m_freem(m);
4448 m = NULL;
4449 }
4450 }
4451 if (m == NULL)
4452 return ENOBUFS;
4453 MCLAIM(m, &tcp_tx_mowner);
4454
4455 /* Fixup the mbuf. */
4456 m->m_data += max_linkhdr;
4457 if (sc->sc_tp)
4458 tp = sc->sc_tp;
4459 m_reset_rcvif(m);
4460 memset(mtod(m, u_char *), 0, tlen);
4461
4462 switch (sc->sc_src.sa.sa_family) {
4463 case AF_INET:
4464 ip = mtod(m, struct ip *);
4465 ip->ip_v = 4;
4466 ip->ip_dst = sc->sc_src.sin.sin_addr;
4467 ip->ip_src = sc->sc_dst.sin.sin_addr;
4468 ip->ip_p = IPPROTO_TCP;
4469 th = (struct tcphdr *)(ip + 1);
4470 th->th_dport = sc->sc_src.sin.sin_port;
4471 th->th_sport = sc->sc_dst.sin.sin_port;
4472 break;
4473 #ifdef INET6
4474 case AF_INET6:
4475 ip6 = mtod(m, struct ip6_hdr *);
4476 ip6->ip6_vfc = IPV6_VERSION;
4477 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4478 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4479 ip6->ip6_nxt = IPPROTO_TCP;
4480 /* ip6_plen will be updated in ip6_output() */
4481 th = (struct tcphdr *)(ip6 + 1);
4482 th->th_dport = sc->sc_src.sin6.sin6_port;
4483 th->th_sport = sc->sc_dst.sin6.sin6_port;
4484 break;
4485 #endif
4486 default:
4487 return ENOBUFS;
4488 }
4489
4490 th->th_seq = htonl(sc->sc_iss);
4491 th->th_ack = htonl(sc->sc_irs + 1);
4492 th->th_flags = TH_SYN|TH_ACK;
4493 th->th_win = htons(sc->sc_win);
4494 /* th_x2, th_sum, th_urp already 0 from memset */
4495
4496 /* Tack on the TCP options. */
4497 optp = (u_int8_t *)(th + 1);
4498 optlen = 0;
4499 *optp++ = TCPOPT_MAXSEG;
4500 *optp++ = TCPOLEN_MAXSEG;
4501 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4502 *optp++ = sc->sc_ourmaxseg & 0xff;
4503 optlen += TCPOLEN_MAXSEG;
4504
4505 if (sc->sc_request_r_scale != 15) {
4506 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4507 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4508 sc->sc_request_r_scale);
4509 optp += TCPOLEN_WINDOW + TCPOLEN_NOP;
4510 optlen += TCPOLEN_WINDOW + TCPOLEN_NOP;
4511 }
4512
4513 if (sc->sc_flags & SCF_SACK_PERMIT) {
4514 /* Let the peer know that we will SACK. */
4515 *optp++ = TCPOPT_SACK_PERMITTED;
4516 *optp++ = TCPOLEN_SACK_PERMITTED;
4517 optlen += TCPOLEN_SACK_PERMITTED;
4518 }
4519
4520 if (sc->sc_flags & SCF_TIMESTAMP) {
4521 while (optlen % 4 != 2) {
4522 optlen += TCPOLEN_NOP;
4523 *optp++ = TCPOPT_NOP;
4524 }
4525 *optp++ = TCPOPT_TIMESTAMP;
4526 *optp++ = TCPOLEN_TIMESTAMP;
4527 u_int32_t *lp = (u_int32_t *)(optp);
4528 /* Form timestamp option as shown in appendix A of RFC 1323. */
4529 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4530 *lp = htonl(sc->sc_timestamp);
4531 optp += TCPOLEN_TIMESTAMP - 2;
4532 optlen += TCPOLEN_TIMESTAMP;
4533 }
4534
4535 #ifdef TCP_SIGNATURE
4536 if (sc->sc_flags & SCF_SIGNATURE) {
4537 sav = tcp_signature_getsav(m);
4538 if (sav == NULL) {
4539 if (m)
4540 m_freem(m);
4541 return (EPERM);
4542 }
4543
4544 *optp++ = TCPOPT_SIGNATURE;
4545 *optp++ = TCPOLEN_SIGNATURE;
4546 sigp = optp;
4547 memset(optp, 0, TCP_SIGLEN);
4548 optp += TCP_SIGLEN;
4549 optlen += TCPOLEN_SIGNATURE;
4550
4551 }
4552 #endif
4553 /* Terminate and pad TCP options to a 4 byte boundary. */
4554 if (optlen % 4) {
4555 optlen += TCPOLEN_EOL;
4556 *optp++ = TCPOPT_EOL;
4557 }
4558 /*
4559 * According to RFC 793 (STD0007):
4560 * "The content of the header beyond the End-of-Option option
4561 * must be header padding (i.e., zero)."
4562 * and later: "The padding is composed of zeros."
4563 */
4564 while (optlen % 4) {
4565 optlen += TCPOLEN_PAD;
4566 *optp++ = TCPOPT_PAD;
4567 }
4568
4569 /* compute the actual values now that we've added the options */
4570 tlen = hlen + sizeof(struct tcphdr) + optlen;
4571 m->m_len = m->m_pkthdr.len = tlen;
4572 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4573
4574 #ifdef TCP_SIGNATURE
4575 if (sav) {
4576 (void)tcp_signature(m, th, hlen, sav, sigp);
4577 key_sa_recordxfer(sav, m);
4578 KEY_SA_UNREF(&sav);
4579 }
4580 #endif
4581
4582 /*
4583 * Send ECN SYN-ACK setup packet.
4584 * Routes can be asymetric, so, even if we receive a packet
4585 * with ECE and CWR set, we must not assume no one will block
4586 * the ECE packet we are about to send.
4587 */
4588 if ((sc->sc_flags & SCF_ECN_PERMIT) && tp &&
4589 SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
4590 th->th_flags |= TH_ECE;
4591 TCP_STATINC(TCP_STAT_ECN_SHS);
4592
4593 /*
4594 * draft-ietf-tcpm-ecnsyn-00.txt
4595 *
4596 * "[...] a TCP node MAY respond to an ECN-setup
4597 * SYN packet by setting ECT in the responding
4598 * ECN-setup SYN/ACK packet, indicating to routers
4599 * that the SYN/ACK packet is ECN-Capable.
4600 * This allows a congested router along the path
4601 * to mark the packet instead of dropping the
4602 * packet as an indication of congestion."
4603 *
4604 * "[...] There can be a great benefit in setting
4605 * an ECN-capable codepoint in SYN/ACK packets [...]
4606 * Congestion is most likely to occur in
4607 * the server-to-client direction. As a result,
4608 * setting an ECN-capable codepoint in SYN/ACK
4609 * packets can reduce the occurence of three-second
4610 * retransmit timeouts resulting from the drop
4611 * of SYN/ACK packets."
4612 *
4613 * Page 4 and 6, January 2006.
4614 */
4615
4616 switch (sc->sc_src.sa.sa_family) {
4617 #ifdef INET
4618 case AF_INET:
4619 ip->ip_tos |= IPTOS_ECN_ECT0;
4620 break;
4621 #endif
4622 #ifdef INET6
4623 case AF_INET6:
4624 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
4625 break;
4626 #endif
4627 }
4628 TCP_STATINC(TCP_STAT_ECN_ECT);
4629 }
4630
4631
4632 /* Compute the packet's checksum. */
4633 switch (sc->sc_src.sa.sa_family) {
4634 case AF_INET:
4635 ip->ip_len = htons(tlen - hlen);
4636 th->th_sum = 0;
4637 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4638 break;
4639 #ifdef INET6
4640 case AF_INET6:
4641 ip6->ip6_plen = htons(tlen - hlen);
4642 th->th_sum = 0;
4643 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4644 break;
4645 #endif
4646 }
4647
4648 /*
4649 * Fill in some straggling IP bits. Note the stack expects
4650 * ip_len to be in host order, for convenience.
4651 */
4652 switch (sc->sc_src.sa.sa_family) {
4653 #ifdef INET
4654 case AF_INET:
4655 ip->ip_len = htons(tlen);
4656 ip->ip_ttl = ip_defttl;
4657 /* XXX tos? */
4658 break;
4659 #endif
4660 #ifdef INET6
4661 case AF_INET6:
4662 ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4663 ip6->ip6_vfc |= IPV6_VERSION;
4664 ip6->ip6_plen = htons(tlen - hlen);
4665 /* ip6_hlim will be initialized afterwards */
4666 /* XXX flowlabel? */
4667 break;
4668 #endif
4669 }
4670
4671 /* XXX use IPsec policy on listening socket, on SYN ACK */
4672 tp = sc->sc_tp;
4673
4674 switch (sc->sc_src.sa.sa_family) {
4675 #ifdef INET
4676 case AF_INET:
4677 error = ip_output(m, sc->sc_ipopts, ro,
4678 (ip_mtudisc ? IP_MTUDISC : 0),
4679 NULL, tp ? tp->t_inpcb : NULL);
4680 break;
4681 #endif
4682 #ifdef INET6
4683 case AF_INET6:
4684 ip6->ip6_hlim = in6_selecthlim(NULL,
4685 (rt = rtcache_validate(ro)) != NULL ? rt->rt_ifp : NULL);
4686 rtcache_unref(rt, ro);
4687
4688 error = ip6_output(m, NULL /*XXX*/, ro, 0, NULL,
4689 tp ? tp->t_in6pcb : NULL, NULL);
4690 break;
4691 #endif
4692 default:
4693 error = EAFNOSUPPORT;
4694 break;
4695 }
4696 return (error);
4697 }
4698