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