tcp_input.c revision 1.398 1 /* $NetBSD: tcp_input.c,v 1.398 2018/03/29 17:12:36 maxv Exp $ */
2
3 /*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32 /*
33 * @(#)COPYRIGHT 1.1 (NRL) 17 January 1995
34 *
35 * NRL grants permission for redistribution and use in source and binary
36 * forms, with or without modification, of the software and documentation
37 * created at NRL provided that the following conditions are met:
38 *
39 * 1. Redistributions of source code must retain the above copyright
40 * notice, this list of conditions and the following disclaimer.
41 * 2. Redistributions in binary form must reproduce the above copyright
42 * notice, this list of conditions and the following disclaimer in the
43 * documentation and/or other materials provided with the distribution.
44 * 3. All advertising materials mentioning features or use of this software
45 * must display the following acknowledgements:
46 * This product includes software developed by the University of
47 * California, Berkeley and its contributors.
48 * This product includes software developed at the Information
49 * Technology Division, US Naval Research Laboratory.
50 * 4. Neither the name of the NRL nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
53 *
54 * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
55 * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
56 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
57 * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL NRL OR
58 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
59 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
60 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
61 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
62 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
63 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
64 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
65 *
66 * The views and conclusions contained in the software and documentation
67 * are those of the authors and should not be interpreted as representing
68 * official policies, either expressed or implied, of the US Naval
69 * Research Laboratory (NRL).
70 */
71
72 /*-
73 * Copyright (c) 1997, 1998, 1999, 2001, 2005, 2006,
74 * 2011 The NetBSD Foundation, Inc.
75 * All rights reserved.
76 *
77 * This code is derived from software contributed to The NetBSD Foundation
78 * by Coyote Point Systems, Inc.
79 * This code is derived from software contributed to The NetBSD Foundation
80 * by Jason R. Thorpe and Kevin M. Lahey of the Numerical Aerospace Simulation
81 * Facility, NASA Ames Research Center.
82 * This code is derived from software contributed to The NetBSD Foundation
83 * by Charles M. Hannum.
84 * This code is derived from software contributed to The NetBSD Foundation
85 * by Rui Paulo.
86 *
87 * Redistribution and use in source and binary forms, with or without
88 * modification, are permitted provided that the following conditions
89 * are met:
90 * 1. Redistributions of source code must retain the above copyright
91 * notice, this list of conditions and the following disclaimer.
92 * 2. Redistributions in binary form must reproduce the above copyright
93 * notice, this list of conditions and the following disclaimer in the
94 * documentation and/or other materials provided with the distribution.
95 *
96 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
97 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
98 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
99 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
100 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
101 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
102 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
103 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
104 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
105 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
106 * POSSIBILITY OF SUCH DAMAGE.
107 */
108
109 /*
110 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
111 * The Regents of the University of California. All rights reserved.
112 *
113 * Redistribution and use in source and binary forms, with or without
114 * modification, are permitted provided that the following conditions
115 * are met:
116 * 1. Redistributions of source code must retain the above copyright
117 * notice, this list of conditions and the following disclaimer.
118 * 2. Redistributions in binary form must reproduce the above copyright
119 * notice, this list of conditions and the following disclaimer in the
120 * documentation and/or other materials provided with the distribution.
121 * 3. Neither the name of the University nor the names of its contributors
122 * may be used to endorse or promote products derived from this software
123 * without specific prior written permission.
124 *
125 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
126 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
127 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
128 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
129 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
130 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
131 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
132 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
133 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
134 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
135 * SUCH DAMAGE.
136 *
137 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
138 */
139
140 /*
141 * TODO list for SYN cache stuff:
142 *
143 * Find room for a "state" field, which is needed to keep a
144 * compressed state for TIME_WAIT TCBs. It's been noted already
145 * that this is fairly important for very high-volume web and
146 * mail servers, which use a large number of short-lived
147 * connections.
148 */
149
150 #include <sys/cdefs.h>
151 __KERNEL_RCSID(0, "$NetBSD: tcp_input.c,v 1.398 2018/03/29 17:12:36 maxv Exp $");
152
153 #ifdef _KERNEL_OPT
154 #include "opt_inet.h"
155 #include "opt_ipsec.h"
156 #include "opt_inet_csum.h"
157 #include "opt_tcp_debug.h"
158 #endif
159
160 #include <sys/param.h>
161 #include <sys/systm.h>
162 #include <sys/malloc.h>
163 #include <sys/mbuf.h>
164 #include <sys/protosw.h>
165 #include <sys/socket.h>
166 #include <sys/socketvar.h>
167 #include <sys/errno.h>
168 #include <sys/syslog.h>
169 #include <sys/pool.h>
170 #include <sys/domain.h>
171 #include <sys/kernel.h>
172 #ifdef TCP_SIGNATURE
173 #include <sys/md5.h>
174 #endif
175 #include <sys/lwp.h> /* for lwp0 */
176 #include <sys/cprng.h>
177
178 #include <net/if.h>
179 #include <net/if_types.h>
180
181 #include <netinet/in.h>
182 #include <netinet/in_systm.h>
183 #include <netinet/ip.h>
184 #include <netinet/in_pcb.h>
185 #include <netinet/in_var.h>
186 #include <netinet/ip_var.h>
187 #include <netinet/in_offload.h>
188
189 #ifdef INET6
190 #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 goto drop;
1146 }
1147
1148 /*
1149 * In TIME_WAIT state the only thing that should arrive
1150 * is a retransmission of the remote FIN. Acknowledge
1151 * it and restart the finack timer.
1152 */
1153 vtw_restart(vp);
1154 goto dropafterack;
1155
1156 dropafterack:
1157 /*
1158 * Generate an ACK dropping incoming segment if it occupies
1159 * sequence space, where the ACK reflects our state.
1160 */
1161 if (tiflags & TH_RST)
1162 goto drop;
1163 goto dropafterack2;
1164
1165 dropafterack_ratelim:
1166 /*
1167 * We may want to rate-limit ACKs against SYN/RST attack.
1168 */
1169 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
1170 tcp_ackdrop_ppslim) == 0) {
1171 /* XXX stat */
1172 goto drop;
1173 }
1174 /* ...fall into dropafterack2... */
1175
1176 dropafterack2:
1177 (void)tcp_respond(0, m, m, th, th->th_seq + tlen, th->th_ack, TH_ACK);
1178 return;
1179
1180 dropwithreset:
1181 /*
1182 * Generate a RST, dropping incoming segment.
1183 * Make ACK acceptable to originator of segment.
1184 */
1185 if (tiflags & TH_RST)
1186 goto drop;
1187
1188 if (tiflags & TH_ACK) {
1189 tcp_respond(0, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
1190 } else {
1191 if (tiflags & TH_SYN)
1192 ++tlen;
1193 (void)tcp_respond(0, m, m, th, th->th_seq + tlen, (tcp_seq)0,
1194 TH_RST|TH_ACK);
1195 }
1196 return;
1197 drop:
1198 m_freem(m);
1199 }
1200
1201 /*
1202 * TCP input routine, follows pages 65-76 of RFC 793 very closely.
1203 */
1204 void
1205 tcp_input(struct mbuf *m, ...)
1206 {
1207 struct tcphdr *th;
1208 struct ip *ip;
1209 struct inpcb *inp;
1210 #ifdef INET6
1211 struct ip6_hdr *ip6;
1212 struct in6pcb *in6p;
1213 #endif
1214 u_int8_t *optp = NULL;
1215 int optlen = 0;
1216 int len, tlen, toff, hdroptlen = 0;
1217 struct tcpcb *tp = NULL;
1218 int tiflags;
1219 struct socket *so = NULL;
1220 int todrop, acked, ourfinisacked, needoutput = 0;
1221 bool dupseg;
1222 #ifdef TCP_DEBUG
1223 short ostate = 0;
1224 #endif
1225 u_long tiwin;
1226 struct tcp_opt_info opti;
1227 int off, iphlen;
1228 va_list ap;
1229 int af; /* af on the wire */
1230 struct mbuf *tcp_saveti = NULL;
1231 uint32_t ts_rtt;
1232 uint8_t iptos;
1233 uint64_t *tcps;
1234 vestigial_inpcb_t vestige;
1235
1236 vestige.valid = 0;
1237
1238 MCLAIM(m, &tcp_rx_mowner);
1239 va_start(ap, m);
1240 toff = va_arg(ap, int);
1241 (void)va_arg(ap, int); /* ignore value, advance ap */
1242 va_end(ap);
1243
1244 TCP_STATINC(TCP_STAT_RCVTOTAL);
1245
1246 memset(&opti, 0, sizeof(opti));
1247 opti.ts_present = 0;
1248 opti.maxseg = 0;
1249
1250 /*
1251 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN.
1252 *
1253 * TCP is, by definition, unicast, so we reject all
1254 * multicast outright.
1255 *
1256 * Note, there are additional src/dst address checks in
1257 * the AF-specific code below.
1258 */
1259 if (m->m_flags & (M_BCAST|M_MCAST)) {
1260 /* XXX stat */
1261 goto drop;
1262 }
1263 #ifdef INET6
1264 if (m->m_flags & M_ANYCAST6) {
1265 /* XXX stat */
1266 goto drop;
1267 }
1268 #endif
1269
1270 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, sizeof(struct tcphdr));
1271 if (th == NULL) {
1272 TCP_STATINC(TCP_STAT_RCVSHORT);
1273 return;
1274 }
1275
1276 /*
1277 * Get IP and TCP header.
1278 * Note: IP leaves IP header in first mbuf.
1279 */
1280 ip = mtod(m, struct ip *);
1281 switch (ip->ip_v) {
1282 case 4:
1283 #ifdef INET6
1284 ip6 = NULL;
1285 #endif
1286 af = AF_INET;
1287 iphlen = sizeof(struct ip);
1288
1289 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
1290 in_broadcast(ip->ip_dst, m_get_rcvif_NOMPSAFE(m)))
1291 goto drop;
1292
1293 /* We do the checksum after PCB lookup... */
1294 len = ntohs(ip->ip_len);
1295 tlen = len - toff;
1296 iptos = ip->ip_tos;
1297 break;
1298 #ifdef INET6
1299 case 6:
1300 ip = NULL;
1301 iphlen = sizeof(struct ip6_hdr);
1302 af = AF_INET6;
1303 ip6 = mtod(m, struct ip6_hdr *);
1304
1305 /*
1306 * Be proactive about unspecified IPv6 address in source.
1307 * As we use all-zero to indicate unbounded/unconnected pcb,
1308 * unspecified IPv6 address can be used to confuse us.
1309 *
1310 * Note that packets with unspecified IPv6 destination is
1311 * already dropped in ip6_input.
1312 */
1313 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
1314 /* XXX stat */
1315 goto drop;
1316 }
1317
1318 /*
1319 * Make sure destination address is not multicast.
1320 * Source address checked in ip6_input().
1321 */
1322 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
1323 /* XXX stat */
1324 goto drop;
1325 }
1326
1327 /* We do the checksum after PCB lookup... */
1328 len = m->m_pkthdr.len;
1329 tlen = len - toff;
1330 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
1331 break;
1332 #endif
1333 default:
1334 m_freem(m);
1335 return;
1336 }
1337
1338 /*
1339 * Enforce alignment requirements that are violated in
1340 * some cases, see kern/50766 for details.
1341 */
1342 if (TCP_HDR_ALIGNED_P(th) == 0) {
1343 m = m_copyup(m, toff + sizeof(struct tcphdr), 0);
1344 if (m == NULL) {
1345 TCP_STATINC(TCP_STAT_RCVSHORT);
1346 return;
1347 }
1348 ip = mtod(m, struct ip *);
1349 #ifdef INET6
1350 ip6 = mtod(m, struct ip6_hdr *);
1351 #endif
1352 th = (struct tcphdr *)(mtod(m, char *) + toff);
1353 }
1354 KASSERT(TCP_HDR_ALIGNED_P(th));
1355
1356 /*
1357 * Check that TCP offset makes sense, pull out TCP options and
1358 * adjust length.
1359 */
1360 off = th->th_off << 2;
1361 if (off < sizeof(struct tcphdr) || off > tlen) {
1362 TCP_STATINC(TCP_STAT_RCVBADOFF);
1363 goto drop;
1364 }
1365 tlen -= off;
1366
1367 if (off > sizeof(struct tcphdr)) {
1368 IP6_EXTHDR_GET(th, struct tcphdr *, m, toff, off);
1369 if (th == NULL) {
1370 TCP_STATINC(TCP_STAT_RCVSHORT);
1371 return;
1372 }
1373 KASSERT(TCP_HDR_ALIGNED_P(th));
1374 optlen = off - sizeof(struct tcphdr);
1375 optp = ((u_int8_t *)th) + sizeof(struct tcphdr);
1376
1377 /*
1378 * Do quick retrieval of timestamp options.
1379 *
1380 * If timestamp is the only option and it's formatted as
1381 * recommended in RFC 1323 appendix A, we quickly get the
1382 * values now and don't bother calling tcp_dooptions(),
1383 * etc.
1384 */
1385 if ((optlen == TCPOLEN_TSTAMP_APPA ||
1386 (optlen > TCPOLEN_TSTAMP_APPA &&
1387 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
1388 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
1389 (th->th_flags & TH_SYN) == 0) {
1390 opti.ts_present = 1;
1391 opti.ts_val = ntohl(*(u_int32_t *)(optp + 4));
1392 opti.ts_ecr = ntohl(*(u_int32_t *)(optp + 8));
1393 optp = NULL; /* we've parsed the options */
1394 }
1395 }
1396 tiflags = th->th_flags;
1397
1398 /*
1399 * Checksum extended TCP header and data
1400 */
1401 if (tcp_input_checksum(af, m, th, toff, off, tlen))
1402 goto badcsum;
1403
1404 /*
1405 * Locate pcb for segment.
1406 */
1407 findpcb:
1408 inp = NULL;
1409 #ifdef INET6
1410 in6p = NULL;
1411 #endif
1412 switch (af) {
1413 case AF_INET:
1414 inp = in_pcblookup_connect(&tcbtable, ip->ip_src, th->th_sport,
1415 ip->ip_dst, th->th_dport, &vestige);
1416 if (inp == NULL && !vestige.valid) {
1417 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1418 inp = in_pcblookup_bind(&tcbtable, ip->ip_dst,
1419 th->th_dport);
1420 }
1421 #ifdef INET6
1422 if (inp == NULL && !vestige.valid) {
1423 struct in6_addr s, d;
1424
1425 /* mapped addr case */
1426 in6_in_2_v4mapin6(&ip->ip_src, &s);
1427 in6_in_2_v4mapin6(&ip->ip_dst, &d);
1428 in6p = in6_pcblookup_connect(&tcbtable, &s,
1429 th->th_sport, &d, th->th_dport, 0, &vestige);
1430 if (in6p == 0 && !vestige.valid) {
1431 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1432 in6p = in6_pcblookup_bind(&tcbtable, &d,
1433 th->th_dport, 0);
1434 }
1435 }
1436 #endif
1437 #ifndef INET6
1438 if (inp == NULL && !vestige.valid)
1439 #else
1440 if (inp == NULL && in6p == NULL && !vestige.valid)
1441 #endif
1442 {
1443 TCP_STATINC(TCP_STAT_NOPORT);
1444 if (tcp_log_refused &&
1445 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1446 tcp4_log_refused(ip, th);
1447 }
1448 tcp_fields_to_host(th);
1449 goto dropwithreset_ratelim;
1450 }
1451 #if defined(IPSEC)
1452 if (ipsec_used) {
1453 if (inp && ipsec_in_reject(m, inp)) {
1454 goto drop;
1455 }
1456 #ifdef INET6
1457 else if (in6p && ipsec_in_reject(m, in6p)) {
1458 goto drop;
1459 }
1460 #endif
1461 }
1462 #endif /*IPSEC*/
1463 break;
1464 #ifdef INET6
1465 case AF_INET6:
1466 {
1467 int faith;
1468
1469 #if defined(NFAITH) && NFAITH > 0
1470 faith = faithprefix(&ip6->ip6_dst);
1471 #else
1472 faith = 0;
1473 #endif
1474 in6p = in6_pcblookup_connect(&tcbtable, &ip6->ip6_src,
1475 th->th_sport, &ip6->ip6_dst, th->th_dport, faith, &vestige);
1476 if (!in6p && !vestige.valid) {
1477 TCP_STATINC(TCP_STAT_PCBHASHMISS);
1478 in6p = in6_pcblookup_bind(&tcbtable, &ip6->ip6_dst,
1479 th->th_dport, faith);
1480 }
1481 if (!in6p && !vestige.valid) {
1482 TCP_STATINC(TCP_STAT_NOPORT);
1483 if (tcp_log_refused &&
1484 (tiflags & (TH_RST|TH_ACK|TH_SYN)) == TH_SYN) {
1485 tcp6_log_refused(ip6, th);
1486 }
1487 tcp_fields_to_host(th);
1488 goto dropwithreset_ratelim;
1489 }
1490 #if defined(IPSEC)
1491 if (ipsec_used && in6p && ipsec_in_reject(m, in6p)) {
1492 goto drop;
1493 }
1494 #endif
1495 break;
1496 }
1497 #endif
1498 }
1499
1500 tcp_fields_to_host(th);
1501
1502 /*
1503 * If the state is CLOSED (i.e., TCB does not exist) then
1504 * all data in the incoming segment is discarded.
1505 * If the TCB exists but is in CLOSED state, it is embryonic,
1506 * but should either do a listen or a connect soon.
1507 */
1508 tp = NULL;
1509 so = NULL;
1510 if (inp) {
1511 /* Check the minimum TTL for socket. */
1512 if (ip->ip_ttl < inp->inp_ip_minttl)
1513 goto drop;
1514
1515 tp = intotcpcb(inp);
1516 so = inp->inp_socket;
1517 }
1518 #ifdef INET6
1519 else if (in6p) {
1520 tp = in6totcpcb(in6p);
1521 so = in6p->in6p_socket;
1522 }
1523 #endif
1524 else if (vestige.valid) {
1525 /* We do not support the resurrection of vtw tcpcps. */
1526 tcp_vtw_input(th, &vestige, m, tlen);
1527 m = NULL;
1528 goto drop;
1529 }
1530
1531 if (tp == NULL)
1532 goto dropwithreset_ratelim;
1533 if (tp->t_state == TCPS_CLOSED)
1534 goto drop;
1535
1536 KASSERT(so->so_lock == softnet_lock);
1537 KASSERT(solocked(so));
1538
1539 /* Unscale the window into a 32-bit value. */
1540 if ((tiflags & TH_SYN) == 0)
1541 tiwin = th->th_win << tp->snd_scale;
1542 else
1543 tiwin = th->th_win;
1544
1545 #ifdef INET6
1546 /* save packet options if user wanted */
1547 if (in6p && (in6p->in6p_flags & IN6P_CONTROLOPTS)) {
1548 if (in6p->in6p_options) {
1549 m_freem(in6p->in6p_options);
1550 in6p->in6p_options = NULL;
1551 }
1552 KASSERT(ip6 != NULL);
1553 ip6_savecontrol(in6p, &in6p->in6p_options, ip6, m);
1554 }
1555 #endif
1556
1557 if (so->so_options & SO_DEBUG) {
1558 #ifdef TCP_DEBUG
1559 ostate = tp->t_state;
1560 #endif
1561
1562 tcp_saveti = NULL;
1563 if (iphlen + sizeof(struct tcphdr) > MHLEN)
1564 goto nosave;
1565
1566 if (m->m_len > iphlen && (m->m_flags & M_EXT) == 0) {
1567 tcp_saveti = m_copym(m, 0, iphlen, M_DONTWAIT);
1568 if (tcp_saveti == NULL)
1569 goto nosave;
1570 } else {
1571 MGETHDR(tcp_saveti, M_DONTWAIT, MT_HEADER);
1572 if (tcp_saveti == NULL)
1573 goto nosave;
1574 MCLAIM(m, &tcp_mowner);
1575 tcp_saveti->m_len = iphlen;
1576 m_copydata(m, 0, iphlen,
1577 mtod(tcp_saveti, void *));
1578 }
1579
1580 if (M_TRAILINGSPACE(tcp_saveti) < sizeof(struct tcphdr)) {
1581 m_freem(tcp_saveti);
1582 tcp_saveti = NULL;
1583 } else {
1584 tcp_saveti->m_len += sizeof(struct tcphdr);
1585 memcpy(mtod(tcp_saveti, char *) + iphlen, th,
1586 sizeof(struct tcphdr));
1587 }
1588 nosave:;
1589 }
1590
1591 if (so->so_options & SO_ACCEPTCONN) {
1592 union syn_cache_sa src;
1593 union syn_cache_sa dst;
1594
1595 KASSERT(tp->t_state == TCPS_LISTEN);
1596
1597 memset(&src, 0, sizeof(src));
1598 memset(&dst, 0, sizeof(dst));
1599 switch (af) {
1600 case AF_INET:
1601 src.sin.sin_len = sizeof(struct sockaddr_in);
1602 src.sin.sin_family = AF_INET;
1603 src.sin.sin_addr = ip->ip_src;
1604 src.sin.sin_port = th->th_sport;
1605
1606 dst.sin.sin_len = sizeof(struct sockaddr_in);
1607 dst.sin.sin_family = AF_INET;
1608 dst.sin.sin_addr = ip->ip_dst;
1609 dst.sin.sin_port = th->th_dport;
1610 break;
1611 #ifdef INET6
1612 case AF_INET6:
1613 src.sin6.sin6_len = sizeof(struct sockaddr_in6);
1614 src.sin6.sin6_family = AF_INET6;
1615 src.sin6.sin6_addr = ip6->ip6_src;
1616 src.sin6.sin6_port = th->th_sport;
1617
1618 dst.sin6.sin6_len = sizeof(struct sockaddr_in6);
1619 dst.sin6.sin6_family = AF_INET6;
1620 dst.sin6.sin6_addr = ip6->ip6_dst;
1621 dst.sin6.sin6_port = th->th_dport;
1622 break;
1623 #endif
1624 }
1625
1626 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
1627 if (tiflags & TH_RST) {
1628 syn_cache_reset(&src.sa, &dst.sa, th);
1629 } else if ((tiflags & (TH_ACK|TH_SYN)) ==
1630 (TH_ACK|TH_SYN)) {
1631 /*
1632 * Received a SYN,ACK. This should never
1633 * happen while we are in LISTEN. Send an RST.
1634 */
1635 goto badsyn;
1636 } else if (tiflags & TH_ACK) {
1637 so = syn_cache_get(&src.sa, &dst.sa, th, so, m);
1638 if (so == NULL) {
1639 /*
1640 * We don't have a SYN for this ACK;
1641 * send an RST.
1642 */
1643 goto badsyn;
1644 } else if (so == (struct socket *)(-1)) {
1645 /*
1646 * We were unable to create the
1647 * connection. If the 3-way handshake
1648 * was completed, and RST has been
1649 * sent to the peer. Since the mbuf
1650 * might be in use for the reply, do
1651 * not free it.
1652 */
1653 m = NULL;
1654 } else {
1655 /*
1656 * We have created a full-blown
1657 * connection.
1658 */
1659 tp = NULL;
1660 inp = NULL;
1661 #ifdef INET6
1662 in6p = NULL;
1663 #endif
1664 switch (so->so_proto->pr_domain->dom_family) {
1665 case AF_INET:
1666 inp = sotoinpcb(so);
1667 tp = intotcpcb(inp);
1668 break;
1669 #ifdef INET6
1670 case AF_INET6:
1671 in6p = sotoin6pcb(so);
1672 tp = in6totcpcb(in6p);
1673 break;
1674 #endif
1675 }
1676 if (tp == NULL)
1677 goto badsyn; /*XXX*/
1678 tiwin <<= tp->snd_scale;
1679 goto after_listen;
1680 }
1681 } else {
1682 /*
1683 * None of RST, SYN or ACK was set.
1684 * This is an invalid packet for a
1685 * TCB in LISTEN state. Send a RST.
1686 */
1687 goto badsyn;
1688 }
1689 } else {
1690 /*
1691 * Received a SYN.
1692 */
1693
1694 #ifdef INET6
1695 /*
1696 * If deprecated address is forbidden, we do
1697 * not accept SYN to deprecated interface
1698 * address to prevent any new inbound
1699 * connection from getting established.
1700 * When we do not accept SYN, we send a TCP
1701 * RST, with deprecated source address (instead
1702 * of dropping it). We compromise it as it is
1703 * much better for peer to send a RST, and
1704 * RST will be the final packet for the
1705 * exchange.
1706 *
1707 * If we do not forbid deprecated addresses, we
1708 * accept the SYN packet. RFC2462 does not
1709 * suggest dropping SYN in this case.
1710 * If we decipher RFC2462 5.5.4, it says like
1711 * this:
1712 * 1. use of deprecated addr with existing
1713 * communication is okay - "SHOULD continue
1714 * to be used"
1715 * 2. use of it with new communication:
1716 * (2a) "SHOULD NOT be used if alternate
1717 * address with sufficient scope is
1718 * available"
1719 * (2b) nothing mentioned otherwise.
1720 * Here we fall into (2b) case as we have no
1721 * choice in our source address selection - we
1722 * must obey the peer.
1723 *
1724 * The wording in RFC2462 is confusing, and
1725 * there are multiple description text for
1726 * deprecated address handling - worse, they
1727 * are not exactly the same. I believe 5.5.4
1728 * is the best one, so we follow 5.5.4.
1729 */
1730 if (af == AF_INET6 && !ip6_use_deprecated) {
1731 struct in6_ifaddr *ia6;
1732 int s;
1733 struct ifnet *rcvif = m_get_rcvif(m, &s);
1734 if (rcvif == NULL)
1735 goto dropwithreset; /* XXX */
1736 if ((ia6 = in6ifa_ifpwithaddr(rcvif,
1737 &ip6->ip6_dst)) &&
1738 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
1739 tp = NULL;
1740 m_put_rcvif(rcvif, &s);
1741 goto dropwithreset;
1742 }
1743 m_put_rcvif(rcvif, &s);
1744 }
1745 #endif
1746
1747 /*
1748 * LISTEN socket received a SYN from itself? This
1749 * can't possibly be valid; drop the packet.
1750 */
1751 if (th->th_sport == th->th_dport) {
1752 int eq = 0;
1753
1754 switch (af) {
1755 case AF_INET:
1756 eq = in_hosteq(ip->ip_src, ip->ip_dst);
1757 break;
1758 #ifdef INET6
1759 case AF_INET6:
1760 eq = IN6_ARE_ADDR_EQUAL(&ip6->ip6_src,
1761 &ip6->ip6_dst);
1762 break;
1763 #endif
1764 }
1765 if (eq) {
1766 TCP_STATINC(TCP_STAT_BADSYN);
1767 goto drop;
1768 }
1769 }
1770
1771 /*
1772 * SYN looks ok; create compressed TCP
1773 * state for it.
1774 */
1775 if (so->so_qlen <= so->so_qlimit &&
1776 syn_cache_add(&src.sa, &dst.sa, th, toff,
1777 so, m, optp, optlen, &opti))
1778 m = NULL;
1779 }
1780
1781 goto drop;
1782 }
1783
1784 after_listen:
1785 /*
1786 * From here on, we're dealing with !LISTEN.
1787 */
1788 KASSERT(tp->t_state != TCPS_LISTEN);
1789
1790 /*
1791 * Segment received on connection.
1792 * Reset idle time and keep-alive timer.
1793 */
1794 tp->t_rcvtime = tcp_now;
1795 if (TCPS_HAVEESTABLISHED(tp->t_state))
1796 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepidle);
1797
1798 /*
1799 * Process options.
1800 */
1801 #ifdef TCP_SIGNATURE
1802 if (optp || (tp->t_flags & TF_SIGNATURE))
1803 #else
1804 if (optp)
1805 #endif
1806 if (tcp_dooptions(tp, optp, optlen, th, m, toff, &opti) < 0)
1807 goto drop;
1808
1809 if (TCP_SACK_ENABLED(tp)) {
1810 tcp_del_sackholes(tp, th);
1811 }
1812
1813 if (TCP_ECN_ALLOWED(tp)) {
1814 if (tiflags & TH_CWR) {
1815 tp->t_flags &= ~TF_ECN_SND_ECE;
1816 }
1817 switch (iptos & IPTOS_ECN_MASK) {
1818 case IPTOS_ECN_CE:
1819 tp->t_flags |= TF_ECN_SND_ECE;
1820 TCP_STATINC(TCP_STAT_ECN_CE);
1821 break;
1822 case IPTOS_ECN_ECT0:
1823 TCP_STATINC(TCP_STAT_ECN_ECT);
1824 break;
1825 case IPTOS_ECN_ECT1:
1826 /* XXX: ignore for now -- rpaulo */
1827 break;
1828 }
1829 /*
1830 * Congestion experienced.
1831 * Ignore if we are already trying to recover.
1832 */
1833 if ((tiflags & TH_ECE) && SEQ_GEQ(tp->snd_una, tp->snd_recover))
1834 tp->t_congctl->cong_exp(tp);
1835 }
1836
1837 if (opti.ts_present && opti.ts_ecr) {
1838 /*
1839 * Calculate the RTT from the returned time stamp and the
1840 * connection's time base. If the time stamp is later than
1841 * the current time, or is extremely old, fall back to non-1323
1842 * RTT calculation. Since ts_rtt is unsigned, we can test both
1843 * at the same time.
1844 *
1845 * Note that ts_rtt is in units of slow ticks (500
1846 * ms). Since most earthbound RTTs are < 500 ms,
1847 * observed values will have large quantization noise.
1848 * Our smoothed RTT is then the fraction of observed
1849 * samples that are 1 tick instead of 0 (times 500
1850 * ms).
1851 *
1852 * ts_rtt is increased by 1 to denote a valid sample,
1853 * with 0 indicating an invalid measurement. This
1854 * extra 1 must be removed when ts_rtt is used, or
1855 * else an an erroneous extra 500 ms will result.
1856 */
1857 ts_rtt = TCP_TIMESTAMP(tp) - opti.ts_ecr + 1;
1858 if (ts_rtt > TCP_PAWS_IDLE)
1859 ts_rtt = 0;
1860 } else {
1861 ts_rtt = 0;
1862 }
1863
1864 /*
1865 * Fast path: check for the two common cases of a uni-directional
1866 * data transfer. If:
1867 * o We are in the ESTABLISHED state, and
1868 * o The packet has no control flags, and
1869 * o The packet is in-sequence, and
1870 * o The window didn't change, and
1871 * o We are not retransmitting
1872 * It's a candidate.
1873 *
1874 * If the length (tlen) is zero and the ack moved forward, we're
1875 * the sender side of the transfer. Just free the data acked and
1876 * wake any higher level process that was blocked waiting for
1877 * space.
1878 *
1879 * If the length is non-zero and the ack didn't move, we're the
1880 * receiver side. If we're getting packets in-order (the reassembly
1881 * queue is empty), add the data to the socket buffer and note
1882 * that we need a delayed ack.
1883 */
1884 if (tp->t_state == TCPS_ESTABLISHED &&
1885 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ECE|TH_CWR|TH_ACK))
1886 == TH_ACK &&
1887 (!opti.ts_present || TSTMP_GEQ(opti.ts_val, tp->ts_recent)) &&
1888 th->th_seq == tp->rcv_nxt &&
1889 tiwin && tiwin == tp->snd_wnd &&
1890 tp->snd_nxt == tp->snd_max) {
1891
1892 /*
1893 * If last ACK falls within this segment's sequence numbers,
1894 * record the timestamp.
1895 * NOTE that the test is modified according to the latest
1896 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
1897 *
1898 * note that we already know
1899 * TSTMP_GEQ(opti.ts_val, tp->ts_recent)
1900 */
1901 if (opti.ts_present && SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1902 tp->ts_recent_age = tcp_now;
1903 tp->ts_recent = opti.ts_val;
1904 }
1905
1906 if (tlen == 0) {
1907 /* Ack prediction. */
1908 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1909 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1910 tp->snd_cwnd >= tp->snd_wnd &&
1911 tp->t_partialacks < 0) {
1912 /*
1913 * this is a pure ack for outstanding data.
1914 */
1915 if (ts_rtt)
1916 tcp_xmit_timer(tp, ts_rtt - 1);
1917 else if (tp->t_rtttime &&
1918 SEQ_GT(th->th_ack, tp->t_rtseq))
1919 tcp_xmit_timer(tp,
1920 tcp_now - tp->t_rtttime);
1921 acked = th->th_ack - tp->snd_una;
1922 tcps = TCP_STAT_GETREF();
1923 tcps[TCP_STAT_PREDACK]++;
1924 tcps[TCP_STAT_RCVACKPACK]++;
1925 tcps[TCP_STAT_RCVACKBYTE] += acked;
1926 TCP_STAT_PUTREF();
1927 nd6_hint(tp);
1928
1929 if (acked > (tp->t_lastoff - tp->t_inoff))
1930 tp->t_lastm = NULL;
1931 sbdrop(&so->so_snd, acked);
1932 tp->t_lastoff -= acked;
1933
1934 icmp_check(tp, th, acked);
1935
1936 tp->snd_una = th->th_ack;
1937 tp->snd_fack = tp->snd_una;
1938 if (SEQ_LT(tp->snd_high, tp->snd_una))
1939 tp->snd_high = tp->snd_una;
1940 m_freem(m);
1941
1942 /*
1943 * If all outstanding data are acked, stop
1944 * retransmit timer, otherwise restart timer
1945 * using current (possibly backed-off) value.
1946 * If process is waiting for space,
1947 * wakeup/selnotify/signal. If data
1948 * are ready to send, let tcp_output
1949 * decide between more output or persist.
1950 */
1951 if (tp->snd_una == tp->snd_max)
1952 TCP_TIMER_DISARM(tp, TCPT_REXMT);
1953 else if (TCP_TIMER_ISARMED(tp,
1954 TCPT_PERSIST) == 0)
1955 TCP_TIMER_ARM(tp, TCPT_REXMT,
1956 tp->t_rxtcur);
1957
1958 sowwakeup(so);
1959 if (so->so_snd.sb_cc) {
1960 KERNEL_LOCK(1, NULL);
1961 (void)tcp_output(tp);
1962 KERNEL_UNLOCK_ONE(NULL);
1963 }
1964 if (tcp_saveti)
1965 m_freem(tcp_saveti);
1966 return;
1967 }
1968 } else if (th->th_ack == tp->snd_una &&
1969 TAILQ_FIRST(&tp->segq) == NULL &&
1970 tlen <= sbspace(&so->so_rcv)) {
1971 int newsize = 0;
1972
1973 /*
1974 * this is a pure, in-sequence data packet
1975 * with nothing on the reassembly queue and
1976 * we have enough buffer space to take it.
1977 */
1978 tp->rcv_nxt += tlen;
1979 tcps = TCP_STAT_GETREF();
1980 tcps[TCP_STAT_PREDDAT]++;
1981 tcps[TCP_STAT_RCVPACK]++;
1982 tcps[TCP_STAT_RCVBYTE] += tlen;
1983 TCP_STAT_PUTREF();
1984 nd6_hint(tp);
1985
1986 /*
1987 * Automatic sizing enables the performance of large buffers
1988 * and most of the efficiency of small ones by only allocating
1989 * space when it is needed.
1990 *
1991 * On the receive side the socket buffer memory is only rarely
1992 * used to any significant extent. This allows us to be much
1993 * more aggressive in scaling the receive socket buffer. For
1994 * the case that the buffer space is actually used to a large
1995 * extent and we run out of kernel memory we can simply drop
1996 * the new segments; TCP on the sender will just retransmit it
1997 * later. Setting the buffer size too big may only consume too
1998 * much kernel memory if the application doesn't read() from
1999 * the socket or packet loss or reordering makes use of the
2000 * reassembly queue.
2001 *
2002 * The criteria to step up the receive buffer one notch are:
2003 * 1. the number of bytes received during the time it takes
2004 * one timestamp to be reflected back to us (the RTT);
2005 * 2. received bytes per RTT is within seven eighth of the
2006 * current socket buffer size;
2007 * 3. receive buffer size has not hit maximal automatic size;
2008 *
2009 * This algorithm does one step per RTT at most and only if
2010 * we receive a bulk stream w/o packet losses or reorderings.
2011 * Shrinking the buffer during idle times is not necessary as
2012 * it doesn't consume any memory when idle.
2013 *
2014 * TODO: Only step up if the application is actually serving
2015 * the buffer to better manage the socket buffer resources.
2016 */
2017 if (tcp_do_autorcvbuf &&
2018 opti.ts_ecr &&
2019 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
2020 if (opti.ts_ecr > tp->rfbuf_ts &&
2021 opti.ts_ecr - tp->rfbuf_ts < PR_SLOWHZ) {
2022 if (tp->rfbuf_cnt >
2023 (so->so_rcv.sb_hiwat / 8 * 7) &&
2024 so->so_rcv.sb_hiwat <
2025 tcp_autorcvbuf_max) {
2026 newsize =
2027 min(so->so_rcv.sb_hiwat +
2028 tcp_autorcvbuf_inc,
2029 tcp_autorcvbuf_max);
2030 }
2031 /* Start over with next RTT. */
2032 tp->rfbuf_ts = 0;
2033 tp->rfbuf_cnt = 0;
2034 } else
2035 tp->rfbuf_cnt += tlen; /* add up */
2036 }
2037
2038 /*
2039 * Drop TCP, IP headers and TCP options then add data
2040 * to socket buffer.
2041 */
2042 if (so->so_state & SS_CANTRCVMORE) {
2043 m_freem(m);
2044 } else {
2045 /*
2046 * Set new socket buffer size.
2047 * Give up when limit is reached.
2048 */
2049 if (newsize)
2050 if (!sbreserve(&so->so_rcv,
2051 newsize, so))
2052 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
2053 m_adj(m, toff + off);
2054 sbappendstream(&so->so_rcv, m);
2055 }
2056 sorwakeup(so);
2057 tcp_setup_ack(tp, th);
2058 if (tp->t_flags & TF_ACKNOW) {
2059 KERNEL_LOCK(1, NULL);
2060 (void)tcp_output(tp);
2061 KERNEL_UNLOCK_ONE(NULL);
2062 }
2063 if (tcp_saveti)
2064 m_freem(tcp_saveti);
2065 return;
2066 }
2067 }
2068
2069 /*
2070 * Compute mbuf offset to TCP data segment.
2071 */
2072 hdroptlen = toff + off;
2073
2074 /*
2075 * Calculate amount of space in receive window. Receive window is
2076 * amount of space in rcv queue, but not less than advertised
2077 * window.
2078 */
2079 {
2080 int win;
2081 win = sbspace(&so->so_rcv);
2082 if (win < 0)
2083 win = 0;
2084 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
2085 }
2086
2087 /* Reset receive buffer auto scaling when not in bulk receive mode. */
2088 tp->rfbuf_ts = 0;
2089 tp->rfbuf_cnt = 0;
2090
2091 switch (tp->t_state) {
2092 /*
2093 * If the state is SYN_SENT:
2094 * if seg contains an ACK, but not for our SYN, drop the input.
2095 * if seg contains a RST, then drop the connection.
2096 * if seg does not contain SYN, then drop it.
2097 * Otherwise this is an acceptable SYN segment
2098 * initialize tp->rcv_nxt and tp->irs
2099 * if seg contains ack then advance tp->snd_una
2100 * if seg contains a ECE and ECN support is enabled, the stream
2101 * is ECN capable.
2102 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
2103 * arrange for segment to be acked (eventually)
2104 * continue processing rest of data/controls, beginning with URG
2105 */
2106 case TCPS_SYN_SENT:
2107 if ((tiflags & TH_ACK) &&
2108 (SEQ_LEQ(th->th_ack, tp->iss) ||
2109 SEQ_GT(th->th_ack, tp->snd_max)))
2110 goto dropwithreset;
2111 if (tiflags & TH_RST) {
2112 if (tiflags & TH_ACK)
2113 tp = tcp_drop(tp, ECONNREFUSED);
2114 goto drop;
2115 }
2116 if ((tiflags & TH_SYN) == 0)
2117 goto drop;
2118 if (tiflags & TH_ACK) {
2119 tp->snd_una = th->th_ack;
2120 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2121 tp->snd_nxt = tp->snd_una;
2122 if (SEQ_LT(tp->snd_high, tp->snd_una))
2123 tp->snd_high = tp->snd_una;
2124 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2125
2126 if ((tiflags & TH_ECE) && tcp_do_ecn) {
2127 tp->t_flags |= TF_ECN_PERMIT;
2128 TCP_STATINC(TCP_STAT_ECN_SHS);
2129 }
2130 }
2131 tp->irs = th->th_seq;
2132 tcp_rcvseqinit(tp);
2133 tp->t_flags |= TF_ACKNOW;
2134 tcp_mss_from_peer(tp, opti.maxseg);
2135
2136 /*
2137 * Initialize the initial congestion window. If we
2138 * had to retransmit the SYN, we must initialize cwnd
2139 * to 1 segment (i.e. the Loss Window).
2140 */
2141 if (tp->t_flags & TF_SYN_REXMT)
2142 tp->snd_cwnd = tp->t_peermss;
2143 else {
2144 int ss = tcp_init_win;
2145 if (inp != NULL && in_localaddr(inp->inp_faddr))
2146 ss = tcp_init_win_local;
2147 #ifdef INET6
2148 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
2149 ss = tcp_init_win_local;
2150 #endif
2151 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
2152 }
2153
2154 tcp_rmx_rtt(tp);
2155 if (tiflags & TH_ACK) {
2156 TCP_STATINC(TCP_STAT_CONNECTS);
2157 /*
2158 * move tcp_established before soisconnected
2159 * because upcall handler can drive tcp_output
2160 * functionality.
2161 * XXX we might call soisconnected at the end of
2162 * all processing
2163 */
2164 tcp_established(tp);
2165 soisconnected(so);
2166 /* Do window scaling on this connection? */
2167 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2168 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2169 tp->snd_scale = tp->requested_s_scale;
2170 tp->rcv_scale = tp->request_r_scale;
2171 }
2172 TCP_REASS_LOCK(tp);
2173 (void)tcp_reass(tp, NULL, NULL, tlen);
2174 /*
2175 * if we didn't have to retransmit the SYN,
2176 * use its rtt as our initial srtt & rtt var.
2177 */
2178 if (tp->t_rtttime)
2179 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2180 } else {
2181 tp->t_state = TCPS_SYN_RECEIVED;
2182 }
2183
2184 /*
2185 * Advance th->th_seq to correspond to first data byte.
2186 * If data, trim to stay within window,
2187 * dropping FIN if necessary.
2188 */
2189 th->th_seq++;
2190 if (tlen > tp->rcv_wnd) {
2191 todrop = tlen - tp->rcv_wnd;
2192 m_adj(m, -todrop);
2193 tlen = tp->rcv_wnd;
2194 tiflags &= ~TH_FIN;
2195 tcps = TCP_STAT_GETREF();
2196 tcps[TCP_STAT_RCVPACKAFTERWIN]++;
2197 tcps[TCP_STAT_RCVBYTEAFTERWIN] += todrop;
2198 TCP_STAT_PUTREF();
2199 }
2200 tp->snd_wl1 = th->th_seq - 1;
2201 tp->rcv_up = th->th_seq;
2202 goto step6;
2203
2204 /*
2205 * If the state is SYN_RECEIVED:
2206 * If seg contains an ACK, but not for our SYN, drop the input
2207 * and generate an RST. See page 36, rfc793
2208 */
2209 case TCPS_SYN_RECEIVED:
2210 if ((tiflags & TH_ACK) &&
2211 (SEQ_LEQ(th->th_ack, tp->iss) ||
2212 SEQ_GT(th->th_ack, tp->snd_max)))
2213 goto dropwithreset;
2214 break;
2215 }
2216
2217 /*
2218 * From here on, we're dealing with !LISTEN and !SYN_SENT.
2219 */
2220 KASSERT(tp->t_state != TCPS_LISTEN &&
2221 tp->t_state != TCPS_SYN_SENT);
2222
2223 /*
2224 * RFC1323 PAWS: if we have a timestamp reply on this segment and
2225 * it's less than ts_recent, drop it.
2226 */
2227 if (opti.ts_present && (tiflags & TH_RST) == 0 && tp->ts_recent &&
2228 TSTMP_LT(opti.ts_val, tp->ts_recent)) {
2229 /* Check to see if ts_recent is over 24 days old. */
2230 if (tcp_now - tp->ts_recent_age > TCP_PAWS_IDLE) {
2231 /*
2232 * Invalidate ts_recent. If this segment updates
2233 * ts_recent, the age will be reset later and ts_recent
2234 * will get a valid value. If it does not, setting
2235 * ts_recent to zero will at least satisfy the
2236 * requirement that zero be placed in the timestamp
2237 * echo reply when ts_recent isn't valid. The
2238 * age isn't reset until we get a valid ts_recent
2239 * because we don't want out-of-order segments to be
2240 * dropped when ts_recent is old.
2241 */
2242 tp->ts_recent = 0;
2243 } else {
2244 tcps = TCP_STAT_GETREF();
2245 tcps[TCP_STAT_RCVDUPPACK]++;
2246 tcps[TCP_STAT_RCVDUPBYTE] += tlen;
2247 tcps[TCP_STAT_PAWSDROP]++;
2248 TCP_STAT_PUTREF();
2249 tcp_new_dsack(tp, th->th_seq, tlen);
2250 goto dropafterack;
2251 }
2252 }
2253
2254 /*
2255 * Check that at least some bytes of the segment are within the
2256 * receive window. If segment begins before rcv_nxt, drop leading
2257 * data (and SYN); if nothing left, just ack.
2258 */
2259 todrop = tp->rcv_nxt - th->th_seq;
2260 dupseg = false;
2261 if (todrop > 0) {
2262 if (tiflags & TH_SYN) {
2263 tiflags &= ~TH_SYN;
2264 th->th_seq++;
2265 tcp_urp_drop(th, 1, &tiflags);
2266 todrop--;
2267 }
2268 if (todrop > tlen ||
2269 (todrop == tlen && (tiflags & TH_FIN) == 0)) {
2270 /*
2271 * Any valid FIN or RST must be to the left of the
2272 * window. At this point the FIN or RST must be a
2273 * duplicate or out of sequence; drop it.
2274 */
2275 if (tiflags & TH_RST)
2276 goto drop;
2277 tiflags &= ~(TH_FIN|TH_RST);
2278
2279 /*
2280 * Send an ACK to resynchronize and drop any data.
2281 * But keep on processing for RST or ACK.
2282 */
2283 tp->t_flags |= TF_ACKNOW;
2284 todrop = tlen;
2285 dupseg = true;
2286 tcps = TCP_STAT_GETREF();
2287 tcps[TCP_STAT_RCVDUPPACK]++;
2288 tcps[TCP_STAT_RCVDUPBYTE] += todrop;
2289 TCP_STAT_PUTREF();
2290 } else if ((tiflags & TH_RST) && th->th_seq != tp->rcv_nxt) {
2291 /*
2292 * Test for reset before adjusting the sequence
2293 * number for overlapping data.
2294 */
2295 goto dropafterack_ratelim;
2296 } else {
2297 tcps = TCP_STAT_GETREF();
2298 tcps[TCP_STAT_RCVPARTDUPPACK]++;
2299 tcps[TCP_STAT_RCVPARTDUPBYTE] += todrop;
2300 TCP_STAT_PUTREF();
2301 }
2302 tcp_new_dsack(tp, th->th_seq, todrop);
2303 hdroptlen += todrop; /* drop from head afterwards */
2304 th->th_seq += todrop;
2305 tlen -= todrop;
2306 tcp_urp_drop(th, todrop, &tiflags);
2307 }
2308
2309 /*
2310 * If new data is received on a connection after the user processes
2311 * are gone, then RST the other end.
2312 */
2313 if ((so->so_state & SS_NOFDREF) &&
2314 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
2315 tp = tcp_close(tp);
2316 TCP_STATINC(TCP_STAT_RCVAFTERCLOSE);
2317 goto dropwithreset;
2318 }
2319
2320 /*
2321 * If the segment ends after the window, drop trailing data (and
2322 * PUSH and FIN); if nothing left, just ACK.
2323 */
2324 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
2325 if (todrop > 0) {
2326 TCP_STATINC(TCP_STAT_RCVPACKAFTERWIN);
2327 if (todrop >= tlen) {
2328 /*
2329 * The segment actually starts after the window.
2330 * th->th_seq + tlen - tp->rcv_nxt - tp->rcv_wnd >= tlen
2331 * th->th_seq - tp->rcv_nxt - tp->rcv_wnd >= 0
2332 * th->th_seq >= tp->rcv_nxt + tp->rcv_wnd
2333 */
2334 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, tlen);
2335
2336 /*
2337 * If a new connection request is received while in
2338 * TIME_WAIT, drop the old connection and start over
2339 * if the sequence numbers are above the previous
2340 * ones.
2341 *
2342 * NOTE: We need to put the header fields back into
2343 * network order.
2344 */
2345 if ((tiflags & TH_SYN) &&
2346 tp->t_state == TCPS_TIME_WAIT &&
2347 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
2348 tp = tcp_close(tp);
2349 tcp_fields_to_net(th);
2350 m_freem(tcp_saveti);
2351 tcp_saveti = NULL;
2352 goto findpcb;
2353 }
2354
2355 /*
2356 * If window is closed can only take segments at
2357 * window edge, and have to drop data and PUSH from
2358 * incoming segments. Continue processing, but
2359 * remember to ack. Otherwise, drop segment
2360 * and (if not RST) ack.
2361 */
2362 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
2363 KASSERT(todrop == tlen);
2364 tp->t_flags |= TF_ACKNOW;
2365 TCP_STATINC(TCP_STAT_RCVWINPROBE);
2366 } else {
2367 goto dropafterack;
2368 }
2369 } else {
2370 TCP_STATADD(TCP_STAT_RCVBYTEAFTERWIN, todrop);
2371 }
2372 m_adj(m, -todrop);
2373 tlen -= todrop;
2374 tiflags &= ~(TH_PUSH|TH_FIN);
2375 }
2376
2377 /*
2378 * If last ACK falls within this segment's sequence numbers,
2379 * record the timestamp.
2380 * NOTE:
2381 * 1) That the test incorporates suggestions from the latest
2382 * proposal of the tcplw (at) cray.com list (Braden 1993/04/26).
2383 * 2) That updating only on newer timestamps interferes with
2384 * our earlier PAWS tests, so this check should be solely
2385 * predicated on the sequence space of this segment.
2386 * 3) That we modify the segment boundary check to be
2387 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
2388 * instead of RFC1323's
2389 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
2390 * This modified check allows us to overcome RFC1323's
2391 * limitations as described in Stevens TCP/IP Illustrated
2392 * Vol. 2 p.869. In such cases, we can still calculate the
2393 * RTT correctly when RCV.NXT == Last.ACK.Sent.
2394 */
2395 if (opti.ts_present &&
2396 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
2397 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
2398 ((tiflags & (TH_SYN|TH_FIN)) != 0))) {
2399 tp->ts_recent_age = tcp_now;
2400 tp->ts_recent = opti.ts_val;
2401 }
2402
2403 /*
2404 * If the RST bit is set examine the state:
2405 * RECEIVED state:
2406 * If passive open, return to LISTEN state.
2407 * If active open, inform user that connection was refused.
2408 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT states:
2409 * Inform user that connection was reset, and close tcb.
2410 * CLOSING, LAST_ACK, TIME_WAIT states:
2411 * Close the tcb.
2412 */
2413 if (tiflags & TH_RST) {
2414 if (th->th_seq != tp->rcv_nxt)
2415 goto dropafterack_ratelim;
2416
2417 switch (tp->t_state) {
2418 case TCPS_SYN_RECEIVED:
2419 so->so_error = ECONNREFUSED;
2420 goto close;
2421
2422 case TCPS_ESTABLISHED:
2423 case TCPS_FIN_WAIT_1:
2424 case TCPS_FIN_WAIT_2:
2425 case TCPS_CLOSE_WAIT:
2426 so->so_error = ECONNRESET;
2427 close:
2428 tp->t_state = TCPS_CLOSED;
2429 TCP_STATINC(TCP_STAT_DROPS);
2430 tp = tcp_close(tp);
2431 goto drop;
2432
2433 case TCPS_CLOSING:
2434 case TCPS_LAST_ACK:
2435 case TCPS_TIME_WAIT:
2436 tp = tcp_close(tp);
2437 goto drop;
2438 }
2439 }
2440
2441 /*
2442 * Since we've covered the SYN-SENT and SYN-RECEIVED states above
2443 * we must be in a synchronized state. RFC791 states (under RST
2444 * generation) that any unacceptable segment (an out-of-order SYN
2445 * qualifies) received in a synchronized state must elicit only an
2446 * empty acknowledgment segment ... and the connection remains in
2447 * the same state.
2448 */
2449 if (tiflags & TH_SYN) {
2450 if (tp->rcv_nxt == th->th_seq) {
2451 tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack - 1,
2452 TH_ACK);
2453 if (tcp_saveti)
2454 m_freem(tcp_saveti);
2455 return;
2456 }
2457
2458 goto dropafterack_ratelim;
2459 }
2460
2461 /*
2462 * If the ACK bit is off we drop the segment and return.
2463 */
2464 if ((tiflags & TH_ACK) == 0) {
2465 if (tp->t_flags & TF_ACKNOW)
2466 goto dropafterack;
2467 goto drop;
2468 }
2469
2470 /*
2471 * From here on, we're doing ACK processing.
2472 */
2473
2474 switch (tp->t_state) {
2475 /*
2476 * In SYN_RECEIVED state if the ack ACKs our SYN then enter
2477 * ESTABLISHED state and continue processing, otherwise
2478 * send an RST.
2479 */
2480 case TCPS_SYN_RECEIVED:
2481 if (SEQ_GT(tp->snd_una, th->th_ack) ||
2482 SEQ_GT(th->th_ack, tp->snd_max))
2483 goto dropwithreset;
2484 TCP_STATINC(TCP_STAT_CONNECTS);
2485 soisconnected(so);
2486 tcp_established(tp);
2487 /* Do window scaling? */
2488 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2489 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2490 tp->snd_scale = tp->requested_s_scale;
2491 tp->rcv_scale = tp->request_r_scale;
2492 }
2493 TCP_REASS_LOCK(tp);
2494 (void)tcp_reass(tp, NULL, NULL, tlen);
2495 tp->snd_wl1 = th->th_seq - 1;
2496 /* FALLTHROUGH */
2497
2498 /*
2499 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2500 * ACKs. If the ack is in the range
2501 * tp->snd_una < th->th_ack <= tp->snd_max
2502 * then advance tp->snd_una to th->th_ack and drop
2503 * data from the retransmission queue. If this ACK reflects
2504 * more up to date window information we update our window information.
2505 */
2506 case TCPS_ESTABLISHED:
2507 case TCPS_FIN_WAIT_1:
2508 case TCPS_FIN_WAIT_2:
2509 case TCPS_CLOSE_WAIT:
2510 case TCPS_CLOSING:
2511 case TCPS_LAST_ACK:
2512 case TCPS_TIME_WAIT:
2513 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2514 if (tlen == 0 && !dupseg && tiwin == tp->snd_wnd) {
2515 TCP_STATINC(TCP_STAT_RCVDUPACK);
2516 /*
2517 * If we have outstanding data (other than
2518 * a window probe), this is a completely
2519 * duplicate ack (ie, window info didn't
2520 * change), the ack is the biggest we've
2521 * seen and we've seen exactly our rexmt
2522 * threshhold of them, assume a packet
2523 * has been dropped and retransmit it.
2524 * Kludge snd_nxt & the congestion
2525 * window so we send only this one
2526 * packet.
2527 */
2528 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2529 th->th_ack != tp->snd_una)
2530 tp->t_dupacks = 0;
2531 else if (tp->t_partialacks < 0 &&
2532 (++tp->t_dupacks == tcprexmtthresh ||
2533 TCP_FACK_FASTRECOV(tp))) {
2534 /*
2535 * Do the fast retransmit, and adjust
2536 * congestion control paramenters.
2537 */
2538 if (tp->t_congctl->fast_retransmit(tp, th)) {
2539 /* False fast retransmit */
2540 break;
2541 }
2542 goto drop;
2543 } else if (tp->t_dupacks > tcprexmtthresh) {
2544 tp->snd_cwnd += tp->t_segsz;
2545 KERNEL_LOCK(1, NULL);
2546 (void)tcp_output(tp);
2547 KERNEL_UNLOCK_ONE(NULL);
2548 goto drop;
2549 }
2550 } else {
2551 /*
2552 * If the ack appears to be very old, only
2553 * allow data that is in-sequence. This
2554 * makes it somewhat more difficult to insert
2555 * forged data by guessing sequence numbers.
2556 * Sent an ack to try to update the send
2557 * sequence number on the other side.
2558 */
2559 if (tlen && th->th_seq != tp->rcv_nxt &&
2560 SEQ_LT(th->th_ack,
2561 tp->snd_una - tp->max_sndwnd))
2562 goto dropafterack;
2563 }
2564 break;
2565 }
2566 /*
2567 * If the congestion window was inflated to account
2568 * for the other side's cached packets, retract it.
2569 */
2570 tp->t_congctl->fast_retransmit_newack(tp, th);
2571
2572 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2573 TCP_STATINC(TCP_STAT_RCVACKTOOMUCH);
2574 goto dropafterack;
2575 }
2576 acked = th->th_ack - tp->snd_una;
2577 tcps = TCP_STAT_GETREF();
2578 tcps[TCP_STAT_RCVACKPACK]++;
2579 tcps[TCP_STAT_RCVACKBYTE] += acked;
2580 TCP_STAT_PUTREF();
2581
2582 /*
2583 * If we have a timestamp reply, update smoothed
2584 * round trip time. If no timestamp is present but
2585 * transmit timer is running and timed sequence
2586 * number was acked, update smoothed round trip time.
2587 * Since we now have an rtt measurement, cancel the
2588 * timer backoff (cf., Phil Karn's retransmit alg.).
2589 * Recompute the initial retransmit timer.
2590 */
2591 if (ts_rtt)
2592 tcp_xmit_timer(tp, ts_rtt - 1);
2593 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2594 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2595
2596 /*
2597 * If all outstanding data is acked, stop retransmit
2598 * timer and remember to restart (more output or persist).
2599 * If there is more data to be acked, restart retransmit
2600 * timer, using current (possibly backed-off) value.
2601 */
2602 if (th->th_ack == tp->snd_max) {
2603 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2604 needoutput = 1;
2605 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2606 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2607
2608 /*
2609 * New data has been acked, adjust the congestion window.
2610 */
2611 tp->t_congctl->newack(tp, th);
2612
2613 nd6_hint(tp);
2614 if (acked > so->so_snd.sb_cc) {
2615 tp->snd_wnd -= so->so_snd.sb_cc;
2616 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2617 ourfinisacked = 1;
2618 } else {
2619 if (acked > (tp->t_lastoff - tp->t_inoff))
2620 tp->t_lastm = NULL;
2621 sbdrop(&so->so_snd, acked);
2622 tp->t_lastoff -= acked;
2623 if (tp->snd_wnd > acked)
2624 tp->snd_wnd -= acked;
2625 else
2626 tp->snd_wnd = 0;
2627 ourfinisacked = 0;
2628 }
2629 sowwakeup(so);
2630
2631 icmp_check(tp, th, acked);
2632
2633 tp->snd_una = th->th_ack;
2634 if (SEQ_GT(tp->snd_una, tp->snd_fack))
2635 tp->snd_fack = tp->snd_una;
2636 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2637 tp->snd_nxt = tp->snd_una;
2638 if (SEQ_LT(tp->snd_high, tp->snd_una))
2639 tp->snd_high = tp->snd_una;
2640
2641 switch (tp->t_state) {
2642
2643 /*
2644 * In FIN_WAIT_1 STATE in addition to the processing
2645 * for the ESTABLISHED state if our FIN is now acknowledged
2646 * then enter FIN_WAIT_2.
2647 */
2648 case TCPS_FIN_WAIT_1:
2649 if (ourfinisacked) {
2650 /*
2651 * If we can't receive any more
2652 * data, then closing user can proceed.
2653 * Starting the timer is contrary to the
2654 * specification, but if we don't get a FIN
2655 * we'll hang forever.
2656 */
2657 if (so->so_state & SS_CANTRCVMORE) {
2658 soisdisconnected(so);
2659 if (tp->t_maxidle > 0)
2660 TCP_TIMER_ARM(tp, TCPT_2MSL,
2661 tp->t_maxidle);
2662 }
2663 tp->t_state = TCPS_FIN_WAIT_2;
2664 }
2665 break;
2666
2667 /*
2668 * In CLOSING STATE in addition to the processing for
2669 * the ESTABLISHED state if the ACK acknowledges our FIN
2670 * then enter the TIME-WAIT state, otherwise ignore
2671 * the segment.
2672 */
2673 case TCPS_CLOSING:
2674 if (ourfinisacked) {
2675 tp->t_state = TCPS_TIME_WAIT;
2676 tcp_canceltimers(tp);
2677 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2678 soisdisconnected(so);
2679 }
2680 break;
2681
2682 /*
2683 * In LAST_ACK, we may still be waiting for data to drain
2684 * and/or to be acked, as well as for the ack of our FIN.
2685 * If our FIN is now acknowledged, delete the TCB,
2686 * enter the closed state and return.
2687 */
2688 case TCPS_LAST_ACK:
2689 if (ourfinisacked) {
2690 tp = tcp_close(tp);
2691 goto drop;
2692 }
2693 break;
2694
2695 /*
2696 * In TIME_WAIT state the only thing that should arrive
2697 * is a retransmission of the remote FIN. Acknowledge
2698 * it and restart the finack timer.
2699 */
2700 case TCPS_TIME_WAIT:
2701 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2702 goto dropafterack;
2703 }
2704 }
2705
2706 step6:
2707 /*
2708 * Update window information.
2709 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2710 */
2711 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2712 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2713 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2714 /* keep track of pure window updates */
2715 if (tlen == 0 &&
2716 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2717 TCP_STATINC(TCP_STAT_RCVWINUPD);
2718 tp->snd_wnd = tiwin;
2719 tp->snd_wl1 = th->th_seq;
2720 tp->snd_wl2 = th->th_ack;
2721 if (tp->snd_wnd > tp->max_sndwnd)
2722 tp->max_sndwnd = tp->snd_wnd;
2723 needoutput = 1;
2724 }
2725
2726 /*
2727 * Process segments with URG.
2728 */
2729 if ((tiflags & TH_URG) && th->th_urp &&
2730 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2731 /*
2732 * This is a kludge, but if we receive and accept
2733 * random urgent pointers, we'll crash in
2734 * soreceive. It's hard to imagine someone
2735 * actually wanting to send this much urgent data.
2736 */
2737 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2738 th->th_urp = 0; /* XXX */
2739 tiflags &= ~TH_URG; /* XXX */
2740 goto dodata; /* XXX */
2741 }
2742
2743 /*
2744 * If this segment advances the known urgent pointer,
2745 * then mark the data stream. This should not happen
2746 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2747 * a FIN has been received from the remote side.
2748 * In these states we ignore the URG.
2749 *
2750 * According to RFC961 (Assigned Protocols),
2751 * the urgent pointer points to the last octet
2752 * of urgent data. We continue, however,
2753 * to consider it to indicate the first octet
2754 * of data past the urgent section as the original
2755 * spec states (in one of two places).
2756 */
2757 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2758 tp->rcv_up = th->th_seq + th->th_urp;
2759 so->so_oobmark = so->so_rcv.sb_cc +
2760 (tp->rcv_up - tp->rcv_nxt) - 1;
2761 if (so->so_oobmark == 0)
2762 so->so_state |= SS_RCVATMARK;
2763 sohasoutofband(so);
2764 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2765 }
2766
2767 /*
2768 * Remove out of band data so doesn't get presented to user.
2769 * This can happen independent of advancing the URG pointer,
2770 * but if two URG's are pending at once, some out-of-band
2771 * data may creep in... ick.
2772 */
2773 if (th->th_urp <= (u_int16_t)tlen &&
2774 (so->so_options & SO_OOBINLINE) == 0)
2775 tcp_pulloutofband(so, th, m, hdroptlen);
2776 } else {
2777 /*
2778 * If no out of band data is expected,
2779 * pull receive urgent pointer along
2780 * with the receive window.
2781 */
2782 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2783 tp->rcv_up = tp->rcv_nxt;
2784 }
2785 dodata:
2786
2787 /*
2788 * Process the segment text, merging it into the TCP sequencing queue,
2789 * and arranging for acknowledgement of receipt if necessary.
2790 * This process logically involves adjusting tp->rcv_wnd as data
2791 * is presented to the user (this happens in tcp_usrreq.c,
2792 * tcp_rcvd()). If a FIN has already been received on this
2793 * connection then we just ignore the text.
2794 */
2795 if ((tlen || (tiflags & TH_FIN)) &&
2796 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2797 /*
2798 * Insert segment ti into reassembly queue of tcp with
2799 * control block tp. Return TH_FIN if reassembly now includes
2800 * a segment with FIN. The macro form does the common case
2801 * inline (segment is the next to be received on an
2802 * established connection, and the queue is empty),
2803 * avoiding linkage into and removal from the queue and
2804 * repetition of various conversions.
2805 * Set DELACK for segments received in order, but ack
2806 * immediately when segments are out of order
2807 * (so fast retransmit can work).
2808 */
2809 /* NOTE: this was TCP_REASS() macro, but used only once */
2810 TCP_REASS_LOCK(tp);
2811 if (th->th_seq == tp->rcv_nxt &&
2812 TAILQ_FIRST(&tp->segq) == NULL &&
2813 tp->t_state == TCPS_ESTABLISHED) {
2814 tcp_setup_ack(tp, th);
2815 tp->rcv_nxt += tlen;
2816 tiflags = th->th_flags & TH_FIN;
2817 tcps = TCP_STAT_GETREF();
2818 tcps[TCP_STAT_RCVPACK]++;
2819 tcps[TCP_STAT_RCVBYTE] += tlen;
2820 TCP_STAT_PUTREF();
2821 nd6_hint(tp);
2822 if (so->so_state & SS_CANTRCVMORE) {
2823 m_freem(m);
2824 } else {
2825 m_adj(m, hdroptlen);
2826 sbappendstream(&(so)->so_rcv, m);
2827 }
2828 TCP_REASS_UNLOCK(tp);
2829 sorwakeup(so);
2830 } else {
2831 m_adj(m, hdroptlen);
2832 tiflags = tcp_reass(tp, th, m, tlen);
2833 tp->t_flags |= TF_ACKNOW;
2834 }
2835
2836 /*
2837 * Note the amount of data that peer has sent into
2838 * our window, in order to estimate the sender's
2839 * buffer size.
2840 */
2841 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2842 } else {
2843 m_freem(m);
2844 m = NULL;
2845 tiflags &= ~TH_FIN;
2846 }
2847
2848 /*
2849 * If FIN is received ACK the FIN and let the user know
2850 * that the connection is closing. Ignore a FIN received before
2851 * the connection is fully established.
2852 */
2853 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2854 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2855 socantrcvmore(so);
2856 tp->t_flags |= TF_ACKNOW;
2857 tp->rcv_nxt++;
2858 }
2859 switch (tp->t_state) {
2860
2861 /*
2862 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2863 */
2864 case TCPS_ESTABLISHED:
2865 tp->t_state = TCPS_CLOSE_WAIT;
2866 break;
2867
2868 /*
2869 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2870 * enter the CLOSING state.
2871 */
2872 case TCPS_FIN_WAIT_1:
2873 tp->t_state = TCPS_CLOSING;
2874 break;
2875
2876 /*
2877 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2878 * starting the time-wait timer, turning off the other
2879 * standard timers.
2880 */
2881 case TCPS_FIN_WAIT_2:
2882 tp->t_state = TCPS_TIME_WAIT;
2883 tcp_canceltimers(tp);
2884 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2885 soisdisconnected(so);
2886 break;
2887
2888 /*
2889 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2890 */
2891 case TCPS_TIME_WAIT:
2892 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * tp->t_msl);
2893 break;
2894 }
2895 }
2896 #ifdef TCP_DEBUG
2897 if (so->so_options & SO_DEBUG)
2898 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2899 #endif
2900
2901 /*
2902 * Return any desired output.
2903 */
2904 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2905 KERNEL_LOCK(1, NULL);
2906 (void)tcp_output(tp);
2907 KERNEL_UNLOCK_ONE(NULL);
2908 }
2909 if (tcp_saveti)
2910 m_freem(tcp_saveti);
2911
2912 if (tp->t_state == TCPS_TIME_WAIT
2913 && (so->so_state & SS_NOFDREF)
2914 && (tp->t_inpcb || af != AF_INET)
2915 && (tp->t_in6pcb || af != AF_INET6)
2916 && ((af == AF_INET ? tcp4_vtw_enable : tcp6_vtw_enable) & 1) != 0
2917 && TAILQ_EMPTY(&tp->segq)
2918 && vtw_add(af, tp)) {
2919 ;
2920 }
2921 return;
2922
2923 badsyn:
2924 /*
2925 * Received a bad SYN. Increment counters and dropwithreset.
2926 */
2927 TCP_STATINC(TCP_STAT_BADSYN);
2928 tp = NULL;
2929 goto dropwithreset;
2930
2931 dropafterack:
2932 /*
2933 * Generate an ACK dropping incoming segment if it occupies
2934 * sequence space, where the ACK reflects our state.
2935 */
2936 if (tiflags & TH_RST)
2937 goto drop;
2938 goto dropafterack2;
2939
2940 dropafterack_ratelim:
2941 /*
2942 * We may want to rate-limit ACKs against SYN/RST attack.
2943 */
2944 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
2945 tcp_ackdrop_ppslim) == 0) {
2946 /* XXX stat */
2947 goto drop;
2948 }
2949
2950 dropafterack2:
2951 m_freem(m);
2952 tp->t_flags |= TF_ACKNOW;
2953 KERNEL_LOCK(1, NULL);
2954 (void)tcp_output(tp);
2955 KERNEL_UNLOCK_ONE(NULL);
2956 if (tcp_saveti)
2957 m_freem(tcp_saveti);
2958 return;
2959
2960 dropwithreset_ratelim:
2961 /*
2962 * We may want to rate-limit RSTs in certain situations,
2963 * particularly if we are sending an RST in response to
2964 * an attempt to connect to or otherwise communicate with
2965 * a port for which we have no socket.
2966 */
2967 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2968 tcp_rst_ppslim) == 0) {
2969 /* XXX stat */
2970 goto drop;
2971 }
2972
2973 dropwithreset:
2974 /*
2975 * Generate a RST, dropping incoming segment.
2976 * Make ACK acceptable to originator of segment.
2977 */
2978 if (tiflags & TH_RST)
2979 goto drop;
2980 if (tiflags & TH_ACK) {
2981 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2982 } else {
2983 if (tiflags & TH_SYN)
2984 tlen++;
2985 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2986 TH_RST|TH_ACK);
2987 }
2988 if (tcp_saveti)
2989 m_freem(tcp_saveti);
2990 return;
2991
2992 badcsum:
2993 drop:
2994 /*
2995 * Drop space held by incoming segment and return.
2996 */
2997 if (tp) {
2998 if (tp->t_inpcb)
2999 so = tp->t_inpcb->inp_socket;
3000 #ifdef INET6
3001 else if (tp->t_in6pcb)
3002 so = tp->t_in6pcb->in6p_socket;
3003 #endif
3004 else
3005 so = NULL;
3006 #ifdef TCP_DEBUG
3007 if (so && (so->so_options & SO_DEBUG) != 0)
3008 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
3009 #endif
3010 }
3011 if (tcp_saveti)
3012 m_freem(tcp_saveti);
3013 m_freem(m);
3014 return;
3015 }
3016
3017 #ifdef TCP_SIGNATURE
3018 int
3019 tcp_signature_apply(void *fstate, void *data, u_int len)
3020 {
3021
3022 MD5Update(fstate, (u_char *)data, len);
3023 return (0);
3024 }
3025
3026 struct secasvar *
3027 tcp_signature_getsav(struct mbuf *m)
3028 {
3029 struct ip *ip;
3030 struct ip6_hdr *ip6;
3031
3032 ip = mtod(m, struct ip *);
3033 switch (ip->ip_v) {
3034 case 4:
3035 ip = mtod(m, struct ip *);
3036 ip6 = NULL;
3037 break;
3038 case 6:
3039 ip = NULL;
3040 ip6 = mtod(m, struct ip6_hdr *);
3041 break;
3042 default:
3043 return (NULL);
3044 }
3045
3046 #ifdef IPSEC
3047 union sockaddr_union dst;
3048
3049 /* Extract the destination from the IP header in the mbuf. */
3050 memset(&dst, 0, sizeof(union sockaddr_union));
3051 if (ip != NULL) {
3052 dst.sa.sa_len = sizeof(struct sockaddr_in);
3053 dst.sa.sa_family = AF_INET;
3054 dst.sin.sin_addr = ip->ip_dst;
3055 } else {
3056 dst.sa.sa_len = sizeof(struct sockaddr_in6);
3057 dst.sa.sa_family = AF_INET6;
3058 dst.sin6.sin6_addr = ip6->ip6_dst;
3059 }
3060
3061 /*
3062 * Look up an SADB entry which matches the address of the peer.
3063 */
3064 return KEY_LOOKUP_SA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI), 0, 0);
3065 #else
3066 return NULL;
3067 #endif
3068 }
3069
3070 int
3071 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
3072 struct secasvar *sav, char *sig)
3073 {
3074 MD5_CTX ctx;
3075 struct ip *ip;
3076 struct ipovly *ipovly;
3077 #ifdef INET6
3078 struct ip6_hdr *ip6;
3079 struct ip6_hdr_pseudo ip6pseudo;
3080 #endif
3081 struct ippseudo ippseudo;
3082 struct tcphdr th0;
3083 int l, tcphdrlen;
3084
3085 if (sav == NULL)
3086 return (-1);
3087
3088 tcphdrlen = th->th_off * 4;
3089
3090 switch (mtod(m, struct ip *)->ip_v) {
3091 case 4:
3092 MD5Init(&ctx);
3093 ip = mtod(m, struct ip *);
3094 memset(&ippseudo, 0, sizeof(ippseudo));
3095 ipovly = (struct ipovly *)ip;
3096 ippseudo.ippseudo_src = ipovly->ih_src;
3097 ippseudo.ippseudo_dst = ipovly->ih_dst;
3098 ippseudo.ippseudo_pad = 0;
3099 ippseudo.ippseudo_p = IPPROTO_TCP;
3100 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
3101 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
3102 break;
3103 #if INET6
3104 case 6:
3105 MD5Init(&ctx);
3106 ip6 = mtod(m, struct ip6_hdr *);
3107 memset(&ip6pseudo, 0, sizeof(ip6pseudo));
3108 ip6pseudo.ip6ph_src = ip6->ip6_src;
3109 in6_clearscope(&ip6pseudo.ip6ph_src);
3110 ip6pseudo.ip6ph_dst = ip6->ip6_dst;
3111 in6_clearscope(&ip6pseudo.ip6ph_dst);
3112 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
3113 ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
3114 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
3115 break;
3116 #endif
3117 default:
3118 return (-1);
3119 }
3120
3121 th0 = *th;
3122 th0.th_sum = 0;
3123 MD5Update(&ctx, (char *)&th0, sizeof(th0));
3124
3125 l = m->m_pkthdr.len - thoff - tcphdrlen;
3126 if (l > 0)
3127 m_apply(m, thoff + tcphdrlen,
3128 m->m_pkthdr.len - thoff - tcphdrlen,
3129 tcp_signature_apply, &ctx);
3130
3131 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
3132 MD5Final(sig, &ctx);
3133
3134 return (0);
3135 }
3136 #endif
3137
3138 /*
3139 * Parse and process tcp options.
3140 *
3141 * Returns -1 if this segment should be dropped. (eg. wrong signature)
3142 * Otherwise returns 0.
3143 */
3144 static int
3145 tcp_dooptions(struct tcpcb *tp, const u_char *cp, int cnt, struct tcphdr *th,
3146 struct mbuf *m, int toff, struct tcp_opt_info *oi)
3147 {
3148 u_int16_t mss;
3149 int opt, optlen = 0;
3150 #ifdef TCP_SIGNATURE
3151 void *sigp = NULL;
3152 char sigbuf[TCP_SIGLEN];
3153 struct secasvar *sav = NULL;
3154 #endif
3155
3156 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
3157 opt = cp[0];
3158 if (opt == TCPOPT_EOL)
3159 break;
3160 if (opt == TCPOPT_NOP)
3161 optlen = 1;
3162 else {
3163 if (cnt < 2)
3164 break;
3165 optlen = cp[1];
3166 if (optlen < 2 || optlen > cnt)
3167 break;
3168 }
3169 switch (opt) {
3170
3171 default:
3172 continue;
3173
3174 case TCPOPT_MAXSEG:
3175 if (optlen != TCPOLEN_MAXSEG)
3176 continue;
3177 if (!(th->th_flags & TH_SYN))
3178 continue;
3179 if (TCPS_HAVERCVDSYN(tp->t_state))
3180 continue;
3181 memcpy(&mss, cp + 2, sizeof(mss));
3182 oi->maxseg = ntohs(mss);
3183 break;
3184
3185 case TCPOPT_WINDOW:
3186 if (optlen != TCPOLEN_WINDOW)
3187 continue;
3188 if (!(th->th_flags & TH_SYN))
3189 continue;
3190 if (TCPS_HAVERCVDSYN(tp->t_state))
3191 continue;
3192 tp->t_flags |= TF_RCVD_SCALE;
3193 tp->requested_s_scale = cp[2];
3194 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
3195 char buf[INET6_ADDRSTRLEN];
3196 struct ip *ip = mtod(m, struct ip *);
3197 #ifdef INET6
3198 struct ip6_hdr *ip6 = mtod(m, struct ip6_hdr *);
3199 #endif
3200 if (ip)
3201 in_print(buf, sizeof(buf),
3202 &ip->ip_src);
3203 #ifdef INET6
3204 else if (ip6)
3205 in6_print(buf, sizeof(buf),
3206 &ip6->ip6_src);
3207 #endif
3208 else
3209 strlcpy(buf, "(unknown)", sizeof(buf));
3210 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
3211 "assuming %d\n",
3212 tp->requested_s_scale, buf,
3213 TCP_MAX_WINSHIFT);
3214 tp->requested_s_scale = TCP_MAX_WINSHIFT;
3215 }
3216 break;
3217
3218 case TCPOPT_TIMESTAMP:
3219 if (optlen != TCPOLEN_TIMESTAMP)
3220 continue;
3221 oi->ts_present = 1;
3222 memcpy(&oi->ts_val, cp + 2, sizeof(oi->ts_val));
3223 NTOHL(oi->ts_val);
3224 memcpy(&oi->ts_ecr, cp + 6, sizeof(oi->ts_ecr));
3225 NTOHL(oi->ts_ecr);
3226
3227 if (!(th->th_flags & TH_SYN))
3228 continue;
3229 if (TCPS_HAVERCVDSYN(tp->t_state))
3230 continue;
3231 /*
3232 * A timestamp received in a SYN makes
3233 * it ok to send timestamp requests and replies.
3234 */
3235 tp->t_flags |= TF_RCVD_TSTMP;
3236 tp->ts_recent = oi->ts_val;
3237 tp->ts_recent_age = tcp_now;
3238 break;
3239
3240 case TCPOPT_SACK_PERMITTED:
3241 if (optlen != TCPOLEN_SACK_PERMITTED)
3242 continue;
3243 if (!(th->th_flags & TH_SYN))
3244 continue;
3245 if (TCPS_HAVERCVDSYN(tp->t_state))
3246 continue;
3247 if (tcp_do_sack) {
3248 tp->t_flags |= TF_SACK_PERMIT;
3249 tp->t_flags |= TF_WILL_SACK;
3250 }
3251 break;
3252
3253 case TCPOPT_SACK:
3254 tcp_sack_option(tp, th, cp, optlen);
3255 break;
3256 #ifdef TCP_SIGNATURE
3257 case TCPOPT_SIGNATURE:
3258 if (optlen != TCPOLEN_SIGNATURE)
3259 continue;
3260 if (sigp && memcmp(sigp, cp + 2, TCP_SIGLEN))
3261 return (-1);
3262
3263 sigp = sigbuf;
3264 memcpy(sigbuf, cp + 2, TCP_SIGLEN);
3265 tp->t_flags |= TF_SIGNATURE;
3266 break;
3267 #endif
3268 }
3269 }
3270
3271 #ifndef TCP_SIGNATURE
3272 return 0;
3273 #else
3274 if (tp->t_flags & TF_SIGNATURE) {
3275 sav = tcp_signature_getsav(m);
3276 if (sav == NULL && tp->t_state == TCPS_LISTEN)
3277 return (-1);
3278 }
3279
3280 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE))
3281 goto out;
3282
3283 if (sigp) {
3284 char sig[TCP_SIGLEN];
3285
3286 tcp_fields_to_net(th);
3287 if (tcp_signature(m, th, toff, sav, sig) < 0) {
3288 tcp_fields_to_host(th);
3289 goto out;
3290 }
3291 tcp_fields_to_host(th);
3292
3293 if (memcmp(sig, sigp, TCP_SIGLEN)) {
3294 TCP_STATINC(TCP_STAT_BADSIG);
3295 goto out;
3296 } else
3297 TCP_STATINC(TCP_STAT_GOODSIG);
3298
3299 key_sa_recordxfer(sav, m);
3300 KEY_SA_UNREF(&sav);
3301 }
3302 return 0;
3303 out:
3304 if (sav != NULL)
3305 KEY_SA_UNREF(&sav);
3306 return -1;
3307 #endif
3308 }
3309
3310 /*
3311 * Pull out of band byte out of a segment so
3312 * it doesn't appear in the user's data queue.
3313 * It is still reflected in the segment length for
3314 * sequencing purposes.
3315 */
3316 void
3317 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3318 struct mbuf *m, int off)
3319 {
3320 int cnt = off + th->th_urp - 1;
3321
3322 while (cnt >= 0) {
3323 if (m->m_len > cnt) {
3324 char *cp = mtod(m, char *) + cnt;
3325 struct tcpcb *tp = sototcpcb(so);
3326
3327 tp->t_iobc = *cp;
3328 tp->t_oobflags |= TCPOOB_HAVEDATA;
3329 memmove(cp, cp + 1, (unsigned)(m->m_len - cnt - 1));
3330 m->m_len--;
3331 return;
3332 }
3333 cnt -= m->m_len;
3334 m = m->m_next;
3335 if (m == NULL)
3336 break;
3337 }
3338 panic("tcp_pulloutofband");
3339 }
3340
3341 /*
3342 * Collect new round-trip time estimate
3343 * and update averages and current timeout.
3344 *
3345 * rtt is in units of slow ticks (typically 500 ms) -- essentially the
3346 * difference of two timestamps.
3347 */
3348 void
3349 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3350 {
3351 int32_t delta;
3352
3353 TCP_STATINC(TCP_STAT_RTTUPDATED);
3354 if (tp->t_srtt != 0) {
3355 /*
3356 * Compute the amount to add to srtt for smoothing,
3357 * *alpha, or 2^(-TCP_RTT_SHIFT). Because
3358 * srtt is stored in 1/32 slow ticks, we conceptually
3359 * shift left 5 bits, subtract srtt to get the
3360 * diference, and then shift right by TCP_RTT_SHIFT
3361 * (3) to obtain 1/8 of the difference.
3362 */
3363 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3364 /*
3365 * This can never happen, because delta's lowest
3366 * possible value is 1/8 of t_srtt. But if it does,
3367 * set srtt to some reasonable value, here chosen
3368 * as 1/8 tick.
3369 */
3370 if ((tp->t_srtt += delta) <= 0)
3371 tp->t_srtt = 1 << 2;
3372 /*
3373 * RFC2988 requires that rttvar be updated first.
3374 * This code is compliant because "delta" is the old
3375 * srtt minus the new observation (scaled).
3376 *
3377 * RFC2988 says:
3378 * rttvar = (1-beta) * rttvar + beta * |srtt-observed|
3379 *
3380 * delta is in units of 1/32 ticks, and has then been
3381 * divided by 8. This is equivalent to being in 1/16s
3382 * units and divided by 4. Subtract from it 1/4 of
3383 * the existing rttvar to form the (signed) amount to
3384 * adjust.
3385 */
3386 if (delta < 0)
3387 delta = -delta;
3388 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3389 /*
3390 * As with srtt, this should never happen. There is
3391 * no support in RFC2988 for this operation. But 1/4s
3392 * as rttvar when faced with something arguably wrong
3393 * is ok.
3394 */
3395 if ((tp->t_rttvar += delta) <= 0)
3396 tp->t_rttvar = 1 << 2;
3397
3398 /*
3399 * If srtt exceeds .01 second, ensure we use the 'remote' MSL
3400 * Problem is: it doesn't work. Disabled by defaulting
3401 * tcp_rttlocal to 0; see corresponding code in
3402 * tcp_subr that selects local vs remote in a different way.
3403 *
3404 * The static branch prediction hint here should be removed
3405 * when the rtt estimator is fixed and the rtt_enable code
3406 * is turned back on.
3407 */
3408 if (__predict_false(tcp_rttlocal) && tcp_msl_enable
3409 && tp->t_srtt > tcp_msl_remote_threshold
3410 && tp->t_msl < tcp_msl_remote) {
3411 tp->t_msl = tcp_msl_remote;
3412 }
3413 } else {
3414 /*
3415 * This is the first measurement. Per RFC2988, 2.2,
3416 * set rtt=R and srtt=R/2.
3417 * For srtt, storage representation is 1/32 ticks,
3418 * so shift left by 5.
3419 * For rttvar, storage representation is 1/16 ticks,
3420 * So shift left by 4, but then right by 1 to halve.
3421 */
3422 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3423 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3424 }
3425 tp->t_rtttime = 0;
3426 tp->t_rxtshift = 0;
3427
3428 /*
3429 * the retransmit should happen at rtt + 4 * rttvar.
3430 * Because of the way we do the smoothing, srtt and rttvar
3431 * will each average +1/2 tick of bias. When we compute
3432 * the retransmit timer, we want 1/2 tick of rounding and
3433 * 1 extra tick because of +-1/2 tick uncertainty in the
3434 * firing of the timer. The bias will give us exactly the
3435 * 1.5 tick we need. But, because the bias is
3436 * statistical, we have to test that we don't drop below
3437 * the minimum feasible timer (which is 2 ticks).
3438 */
3439 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3440 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3441
3442 /*
3443 * We received an ack for a packet that wasn't retransmitted;
3444 * it is probably safe to discard any error indications we've
3445 * received recently. This isn't quite right, but close enough
3446 * for now (a route might have failed after we sent a segment,
3447 * and the return path might not be symmetrical).
3448 */
3449 tp->t_softerror = 0;
3450 }
3451
3452
3453 /*
3454 * TCP compressed state engine. Currently used to hold compressed
3455 * state for SYN_RECEIVED.
3456 */
3457
3458 u_long syn_cache_count;
3459 u_int32_t syn_hash1, syn_hash2;
3460
3461 #define SYN_HASH(sa, sp, dp) \
3462 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3463 ((u_int32_t)(sp)))^syn_hash2)))
3464 #ifndef INET6
3465 #define SYN_HASHALL(hash, src, dst) \
3466 do { \
3467 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3468 ((const struct sockaddr_in *)(src))->sin_port, \
3469 ((const struct sockaddr_in *)(dst))->sin_port); \
3470 } while (/*CONSTCOND*/ 0)
3471 #else
3472 #define SYN_HASH6(sa, sp, dp) \
3473 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3474 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3475 & 0x7fffffff)
3476
3477 #define SYN_HASHALL(hash, src, dst) \
3478 do { \
3479 switch ((src)->sa_family) { \
3480 case AF_INET: \
3481 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3482 ((const struct sockaddr_in *)(src))->sin_port, \
3483 ((const struct sockaddr_in *)(dst))->sin_port); \
3484 break; \
3485 case AF_INET6: \
3486 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3487 ((const struct sockaddr_in6 *)(src))->sin6_port, \
3488 ((const struct sockaddr_in6 *)(dst))->sin6_port); \
3489 break; \
3490 default: \
3491 hash = 0; \
3492 } \
3493 } while (/*CONSTCOND*/0)
3494 #endif /* INET6 */
3495
3496 static struct pool syn_cache_pool;
3497
3498 /*
3499 * We don't estimate RTT with SYNs, so each packet starts with the default
3500 * RTT and each timer step has a fixed timeout value.
3501 */
3502 static inline void
3503 syn_cache_timer_arm(struct syn_cache *sc)
3504 {
3505
3506 TCPT_RANGESET(sc->sc_rxtcur,
3507 TCPTV_SRTTDFLT * tcp_backoff[sc->sc_rxtshift], TCPTV_MIN,
3508 TCPTV_REXMTMAX);
3509 callout_reset(&sc->sc_timer,
3510 sc->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, sc);
3511 }
3512
3513 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase)
3514
3515 static inline void
3516 syn_cache_rm(struct syn_cache *sc)
3517 {
3518 TAILQ_REMOVE(&tcp_syn_cache[sc->sc_bucketidx].sch_bucket,
3519 sc, sc_bucketq);
3520 sc->sc_tp = NULL;
3521 LIST_REMOVE(sc, sc_tpq);
3522 tcp_syn_cache[sc->sc_bucketidx].sch_length--;
3523 callout_stop(&sc->sc_timer);
3524 syn_cache_count--;
3525 }
3526
3527 static inline void
3528 syn_cache_put(struct syn_cache *sc)
3529 {
3530 if (sc->sc_ipopts)
3531 (void) m_free(sc->sc_ipopts);
3532 rtcache_free(&sc->sc_route);
3533 sc->sc_flags |= SCF_DEAD;
3534 if (!callout_invoking(&sc->sc_timer))
3535 callout_schedule(&(sc)->sc_timer, 1);
3536 }
3537
3538 void
3539 syn_cache_init(void)
3540 {
3541 int i;
3542
3543 pool_init(&syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0,
3544 "synpl", NULL, IPL_SOFTNET);
3545
3546 /* Initialize the hash buckets. */
3547 for (i = 0; i < tcp_syn_cache_size; i++)
3548 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3549 }
3550
3551 void
3552 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3553 {
3554 struct syn_cache_head *scp;
3555 struct syn_cache *sc2;
3556 int s;
3557
3558 /*
3559 * If there are no entries in the hash table, reinitialize
3560 * the hash secrets.
3561 */
3562 if (syn_cache_count == 0) {
3563 syn_hash1 = cprng_fast32();
3564 syn_hash2 = cprng_fast32();
3565 }
3566
3567 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3568 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3569 scp = &tcp_syn_cache[sc->sc_bucketidx];
3570
3571 /*
3572 * Make sure that we don't overflow the per-bucket
3573 * limit or the total cache size limit.
3574 */
3575 s = splsoftnet();
3576 if (scp->sch_length >= tcp_syn_bucket_limit) {
3577 TCP_STATINC(TCP_STAT_SC_BUCKETOVERFLOW);
3578 /*
3579 * The bucket is full. Toss the oldest element in the
3580 * bucket. This will be the first entry in the bucket.
3581 */
3582 sc2 = TAILQ_FIRST(&scp->sch_bucket);
3583 #ifdef DIAGNOSTIC
3584 /*
3585 * This should never happen; we should always find an
3586 * entry in our bucket.
3587 */
3588 if (sc2 == NULL)
3589 panic("syn_cache_insert: bucketoverflow: impossible");
3590 #endif
3591 syn_cache_rm(sc2);
3592 syn_cache_put(sc2); /* calls pool_put but see spl above */
3593 } else if (syn_cache_count >= tcp_syn_cache_limit) {
3594 struct syn_cache_head *scp2, *sce;
3595
3596 TCP_STATINC(TCP_STAT_SC_OVERFLOWED);
3597 /*
3598 * The cache is full. Toss the oldest entry in the
3599 * first non-empty bucket we can find.
3600 *
3601 * XXX We would really like to toss the oldest
3602 * entry in the cache, but we hope that this
3603 * condition doesn't happen very often.
3604 */
3605 scp2 = scp;
3606 if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3607 sce = &tcp_syn_cache[tcp_syn_cache_size];
3608 for (++scp2; scp2 != scp; scp2++) {
3609 if (scp2 >= sce)
3610 scp2 = &tcp_syn_cache[0];
3611 if (! TAILQ_EMPTY(&scp2->sch_bucket))
3612 break;
3613 }
3614 #ifdef DIAGNOSTIC
3615 /*
3616 * This should never happen; we should always find a
3617 * non-empty bucket.
3618 */
3619 if (scp2 == scp)
3620 panic("syn_cache_insert: cacheoverflow: "
3621 "impossible");
3622 #endif
3623 }
3624 sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3625 syn_cache_rm(sc2);
3626 syn_cache_put(sc2); /* calls pool_put but see spl above */
3627 }
3628
3629 /*
3630 * Initialize the entry's timer.
3631 */
3632 sc->sc_rxttot = 0;
3633 sc->sc_rxtshift = 0;
3634 syn_cache_timer_arm(sc);
3635
3636 /* Link it from tcpcb entry */
3637 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3638
3639 /* Put it into the bucket. */
3640 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3641 scp->sch_length++;
3642 syn_cache_count++;
3643
3644 TCP_STATINC(TCP_STAT_SC_ADDED);
3645 splx(s);
3646 }
3647
3648 /*
3649 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3650 * If we have retransmitted an entry the maximum number of times, expire
3651 * that entry.
3652 */
3653 static void
3654 syn_cache_timer(void *arg)
3655 {
3656 struct syn_cache *sc = arg;
3657
3658 mutex_enter(softnet_lock);
3659 KERNEL_LOCK(1, NULL);
3660
3661 callout_ack(&sc->sc_timer);
3662
3663 if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3664 TCP_STATINC(TCP_STAT_SC_DELAYED_FREE);
3665 goto free;
3666 }
3667
3668 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3669 /* Drop it -- too many retransmissions. */
3670 goto dropit;
3671 }
3672
3673 /*
3674 * Compute the total amount of time this entry has
3675 * been on a queue. If this entry has been on longer
3676 * than the keep alive timer would allow, expire it.
3677 */
3678 sc->sc_rxttot += sc->sc_rxtcur;
3679 if (sc->sc_rxttot >= tcp_keepinit)
3680 goto dropit;
3681
3682 TCP_STATINC(TCP_STAT_SC_RETRANSMITTED);
3683 (void)syn_cache_respond(sc);
3684
3685 /* Advance the timer back-off. */
3686 sc->sc_rxtshift++;
3687 syn_cache_timer_arm(sc);
3688
3689 goto out;
3690
3691 dropit:
3692 TCP_STATINC(TCP_STAT_SC_TIMED_OUT);
3693 syn_cache_rm(sc);
3694 if (sc->sc_ipopts)
3695 (void) m_free(sc->sc_ipopts);
3696 rtcache_free(&sc->sc_route);
3697
3698 free:
3699 callout_destroy(&sc->sc_timer);
3700 pool_put(&syn_cache_pool, sc);
3701
3702 out:
3703 KERNEL_UNLOCK_ONE(NULL);
3704 mutex_exit(softnet_lock);
3705 }
3706
3707 /*
3708 * Remove syn cache created by the specified tcb entry,
3709 * because this does not make sense to keep them
3710 * (if there's no tcb entry, syn cache entry will never be used)
3711 */
3712 void
3713 syn_cache_cleanup(struct tcpcb *tp)
3714 {
3715 struct syn_cache *sc, *nsc;
3716 int s;
3717
3718 s = splsoftnet();
3719
3720 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3721 nsc = LIST_NEXT(sc, sc_tpq);
3722
3723 #ifdef DIAGNOSTIC
3724 if (sc->sc_tp != tp)
3725 panic("invalid sc_tp in syn_cache_cleanup");
3726 #endif
3727 syn_cache_rm(sc);
3728 syn_cache_put(sc); /* calls pool_put but see spl above */
3729 }
3730 /* just for safety */
3731 LIST_INIT(&tp->t_sc);
3732
3733 splx(s);
3734 }
3735
3736 /*
3737 * Find an entry in the syn cache.
3738 */
3739 struct syn_cache *
3740 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3741 struct syn_cache_head **headp)
3742 {
3743 struct syn_cache *sc;
3744 struct syn_cache_head *scp;
3745 u_int32_t hash;
3746 int s;
3747
3748 SYN_HASHALL(hash, src, dst);
3749
3750 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3751 *headp = scp;
3752 s = splsoftnet();
3753 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3754 sc = TAILQ_NEXT(sc, sc_bucketq)) {
3755 if (sc->sc_hash != hash)
3756 continue;
3757 if (!memcmp(&sc->sc_src, src, src->sa_len) &&
3758 !memcmp(&sc->sc_dst, dst, dst->sa_len)) {
3759 splx(s);
3760 return (sc);
3761 }
3762 }
3763 splx(s);
3764 return (NULL);
3765 }
3766
3767 /*
3768 * This function gets called when we receive an ACK for a socket in the
3769 * LISTEN state. We look up the connection in the syn cache, and if it's
3770 * there, we pull it out of the cache and turn it into a full-blown
3771 * connection in the SYN-RECEIVED state.
3772 *
3773 * The return values may not be immediately obvious, and their effects
3774 * can be subtle, so here they are:
3775 *
3776 * NULL SYN was not found in cache; caller should drop the
3777 * packet and send an RST.
3778 *
3779 * -1 We were unable to create the new connection, and are
3780 * aborting it. An ACK,RST is being sent to the peer
3781 * (unless we got screwey sequence numbers; see below),
3782 * because the 3-way handshake has been completed. Caller
3783 * should not free the mbuf, since we may be using it. If
3784 * we are not, we will free it.
3785 *
3786 * Otherwise, the return value is a pointer to the new socket
3787 * associated with the connection.
3788 */
3789 struct socket *
3790 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3791 struct tcphdr *th, struct socket *so, struct mbuf *m)
3792 {
3793 struct syn_cache *sc;
3794 struct syn_cache_head *scp;
3795 struct inpcb *inp = NULL;
3796 #ifdef INET6
3797 struct in6pcb *in6p = NULL;
3798 #endif
3799 struct tcpcb *tp;
3800 int s;
3801 struct socket *oso;
3802
3803 s = splsoftnet();
3804 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3805 splx(s);
3806 return NULL;
3807 }
3808
3809 /*
3810 * Verify the sequence and ack numbers. Try getting the correct
3811 * response again.
3812 */
3813 if ((th->th_ack != sc->sc_iss + 1) ||
3814 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3815 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3816 m_freem(m);
3817 (void)syn_cache_respond(sc);
3818 splx(s);
3819 return ((struct socket *)(-1));
3820 }
3821
3822 /* Remove this cache entry */
3823 syn_cache_rm(sc);
3824 splx(s);
3825
3826 /*
3827 * Ok, create the full blown connection, and set things up
3828 * as they would have been set up if we had created the
3829 * connection when the SYN arrived. If we can't create
3830 * the connection, abort it.
3831 */
3832 /*
3833 * inp still has the OLD in_pcb stuff, set the
3834 * v6-related flags on the new guy, too. This is
3835 * done particularly for the case where an AF_INET6
3836 * socket is bound only to a port, and a v4 connection
3837 * comes in on that port.
3838 * we also copy the flowinfo from the original pcb
3839 * to the new one.
3840 */
3841 oso = so;
3842 so = sonewconn(so, true);
3843 if (so == NULL)
3844 goto resetandabort;
3845
3846 switch (so->so_proto->pr_domain->dom_family) {
3847 case AF_INET:
3848 inp = sotoinpcb(so);
3849 break;
3850 #ifdef INET6
3851 case AF_INET6:
3852 in6p = sotoin6pcb(so);
3853 break;
3854 #endif
3855 }
3856
3857 switch (src->sa_family) {
3858 case AF_INET:
3859 if (inp) {
3860 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3861 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3862 inp->inp_options = ip_srcroute(m);
3863 in_pcbstate(inp, INP_BOUND);
3864 if (inp->inp_options == NULL) {
3865 inp->inp_options = sc->sc_ipopts;
3866 sc->sc_ipopts = NULL;
3867 }
3868 }
3869 #ifdef INET6
3870 else if (in6p) {
3871 /* IPv4 packet to AF_INET6 socket */
3872 memset(&in6p->in6p_laddr, 0, sizeof(in6p->in6p_laddr));
3873 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3874 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3875 &in6p->in6p_laddr.s6_addr32[3],
3876 sizeof(((struct sockaddr_in *)dst)->sin_addr));
3877 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
3878 in6totcpcb(in6p)->t_family = AF_INET;
3879 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
3880 in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
3881 else
3882 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
3883 in6_pcbstate(in6p, IN6P_BOUND);
3884 }
3885 #endif
3886 break;
3887 #ifdef INET6
3888 case AF_INET6:
3889 if (in6p) {
3890 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
3891 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
3892 in6_pcbstate(in6p, IN6P_BOUND);
3893 }
3894 break;
3895 #endif
3896 }
3897
3898 #ifdef INET6
3899 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
3900 struct in6pcb *oin6p = sotoin6pcb(oso);
3901 /* inherit socket options from the listening socket */
3902 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
3903 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
3904 m_freem(in6p->in6p_options);
3905 in6p->in6p_options = NULL;
3906 }
3907 ip6_savecontrol(in6p, &in6p->in6p_options,
3908 mtod(m, struct ip6_hdr *), m);
3909 }
3910 #endif
3911
3912 #if defined(IPSEC)
3913 if (ipsec_used) {
3914 /*
3915 * we make a copy of policy, instead of sharing the policy, for
3916 * better behavior in terms of SA lookup and dead SA removal.
3917 */
3918 if (inp) {
3919 /* copy old policy into new socket's */
3920 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp,
3921 inp->inp_sp))
3922 printf("tcp_input: could not copy policy\n");
3923 }
3924 #ifdef INET6
3925 else if (in6p) {
3926 /* copy old policy into new socket's */
3927 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
3928 in6p->in6p_sp))
3929 printf("tcp_input: could not copy policy\n");
3930 }
3931 #endif
3932 }
3933 #endif
3934
3935 /*
3936 * Give the new socket our cached route reference.
3937 */
3938 if (inp) {
3939 rtcache_copy(&inp->inp_route, &sc->sc_route);
3940 rtcache_free(&sc->sc_route);
3941 }
3942 #ifdef INET6
3943 else {
3944 rtcache_copy(&in6p->in6p_route, &sc->sc_route);
3945 rtcache_free(&sc->sc_route);
3946 }
3947 #endif
3948
3949 if (inp) {
3950 struct sockaddr_in sin;
3951 memcpy(&sin, src, src->sa_len);
3952 if (in_pcbconnect(inp, &sin, &lwp0)) {
3953 goto resetandabort;
3954 }
3955 }
3956 #ifdef INET6
3957 else if (in6p) {
3958 struct sockaddr_in6 sin6;
3959 memcpy(&sin6, src, src->sa_len);
3960 if (src->sa_family == AF_INET) {
3961 /* IPv4 packet to AF_INET6 socket */
3962 in6_sin_2_v4mapsin6((struct sockaddr_in *)src, &sin6);
3963 }
3964 if (in6_pcbconnect(in6p, &sin6, NULL)) {
3965 goto resetandabort;
3966 }
3967 }
3968 #endif
3969 else {
3970 goto resetandabort;
3971 }
3972
3973 if (inp)
3974 tp = intotcpcb(inp);
3975 #ifdef INET6
3976 else if (in6p)
3977 tp = in6totcpcb(in6p);
3978 #endif
3979 else
3980 tp = NULL;
3981
3982 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
3983 if (sc->sc_request_r_scale != 15) {
3984 tp->requested_s_scale = sc->sc_requested_s_scale;
3985 tp->request_r_scale = sc->sc_request_r_scale;
3986 tp->snd_scale = sc->sc_requested_s_scale;
3987 tp->rcv_scale = sc->sc_request_r_scale;
3988 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
3989 }
3990 if (sc->sc_flags & SCF_TIMESTAMP)
3991 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
3992 tp->ts_timebase = sc->sc_timebase;
3993
3994 tp->t_template = tcp_template(tp);
3995 if (tp->t_template == 0) {
3996 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
3997 so = NULL;
3998 m_freem(m);
3999 goto abort;
4000 }
4001
4002 tp->iss = sc->sc_iss;
4003 tp->irs = sc->sc_irs;
4004 tcp_sendseqinit(tp);
4005 tcp_rcvseqinit(tp);
4006 tp->t_state = TCPS_SYN_RECEIVED;
4007 TCP_TIMER_ARM(tp, TCPT_KEEP, tp->t_keepinit);
4008 TCP_STATINC(TCP_STAT_ACCEPTS);
4009
4010 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
4011 tp->t_flags |= TF_WILL_SACK;
4012
4013 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
4014 tp->t_flags |= TF_ECN_PERMIT;
4015
4016 #ifdef TCP_SIGNATURE
4017 if (sc->sc_flags & SCF_SIGNATURE)
4018 tp->t_flags |= TF_SIGNATURE;
4019 #endif
4020
4021 /* Initialize tp->t_ourmss before we deal with the peer's! */
4022 tp->t_ourmss = sc->sc_ourmaxseg;
4023 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
4024
4025 /*
4026 * Initialize the initial congestion window. If we
4027 * had to retransmit the SYN,ACK, we must initialize cwnd
4028 * to 1 segment (i.e. the Loss Window).
4029 */
4030 if (sc->sc_rxtshift)
4031 tp->snd_cwnd = tp->t_peermss;
4032 else {
4033 int ss = tcp_init_win;
4034 if (inp != NULL && in_localaddr(inp->inp_faddr))
4035 ss = tcp_init_win_local;
4036 #ifdef INET6
4037 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
4038 ss = tcp_init_win_local;
4039 #endif
4040 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
4041 }
4042
4043 tcp_rmx_rtt(tp);
4044 tp->snd_wl1 = sc->sc_irs;
4045 tp->rcv_up = sc->sc_irs + 1;
4046
4047 /*
4048 * This is what whould have happened in tcp_output() when
4049 * the SYN,ACK was sent.
4050 */
4051 tp->snd_up = tp->snd_una;
4052 tp->snd_max = tp->snd_nxt = tp->iss+1;
4053 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
4054 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
4055 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
4056 tp->last_ack_sent = tp->rcv_nxt;
4057 tp->t_partialacks = -1;
4058 tp->t_dupacks = 0;
4059
4060 TCP_STATINC(TCP_STAT_SC_COMPLETED);
4061 s = splsoftnet();
4062 syn_cache_put(sc);
4063 splx(s);
4064 return so;
4065
4066 resetandabort:
4067 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
4068 abort:
4069 if (so != NULL) {
4070 (void) soqremque(so, 1);
4071 (void) soabort(so);
4072 mutex_enter(softnet_lock);
4073 }
4074 s = splsoftnet();
4075 syn_cache_put(sc);
4076 splx(s);
4077 TCP_STATINC(TCP_STAT_SC_ABORTED);
4078 return ((struct socket *)(-1));
4079 }
4080
4081 /*
4082 * This function is called when we get a RST for a
4083 * non-existent connection, so that we can see if the
4084 * connection is in the syn cache. If it is, zap it.
4085 */
4086
4087 void
4088 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
4089 {
4090 struct syn_cache *sc;
4091 struct syn_cache_head *scp;
4092 int s = splsoftnet();
4093
4094 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4095 splx(s);
4096 return;
4097 }
4098 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
4099 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
4100 splx(s);
4101 return;
4102 }
4103 syn_cache_rm(sc);
4104 TCP_STATINC(TCP_STAT_SC_RESET);
4105 syn_cache_put(sc); /* calls pool_put but see spl above */
4106 splx(s);
4107 }
4108
4109 void
4110 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
4111 struct tcphdr *th)
4112 {
4113 struct syn_cache *sc;
4114 struct syn_cache_head *scp;
4115 int s;
4116
4117 s = splsoftnet();
4118 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
4119 splx(s);
4120 return;
4121 }
4122 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
4123 if (ntohl(th->th_seq) != sc->sc_iss) {
4124 splx(s);
4125 return;
4126 }
4127
4128 /*
4129 * If we've retransmitted 3 times and this is our second error,
4130 * we remove the entry. Otherwise, we allow it to continue on.
4131 * This prevents us from incorrectly nuking an entry during a
4132 * spurious network outage.
4133 *
4134 * See tcp_notify().
4135 */
4136 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
4137 sc->sc_flags |= SCF_UNREACH;
4138 splx(s);
4139 return;
4140 }
4141
4142 syn_cache_rm(sc);
4143 TCP_STATINC(TCP_STAT_SC_UNREACH);
4144 syn_cache_put(sc); /* calls pool_put but see spl above */
4145 splx(s);
4146 }
4147
4148 /*
4149 * Given a LISTEN socket and an inbound SYN request, add this to the syn
4150 * cache, and send back a segment:
4151 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
4152 * to the source.
4153 *
4154 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
4155 * Doing so would require that we hold onto the data and deliver it
4156 * to the application. However, if we are the target of a SYN-flood
4157 * DoS attack, an attacker could send data which would eventually
4158 * consume all available buffer space if it were ACKed. By not ACKing
4159 * the data, we avoid this DoS scenario.
4160 */
4161 int
4162 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
4163 unsigned int toff, struct socket *so, struct mbuf *m, u_char *optp,
4164 int optlen, struct tcp_opt_info *oi)
4165 {
4166 struct tcpcb tb, *tp;
4167 long win;
4168 struct syn_cache *sc;
4169 struct syn_cache_head *scp;
4170 struct mbuf *ipopts;
4171 int s;
4172
4173 tp = sototcpcb(so);
4174
4175 /*
4176 * Initialize some local state.
4177 */
4178 win = sbspace(&so->so_rcv);
4179 if (win > TCP_MAXWIN)
4180 win = TCP_MAXWIN;
4181
4182 #ifdef TCP_SIGNATURE
4183 if (optp || (tp->t_flags & TF_SIGNATURE))
4184 #else
4185 if (optp)
4186 #endif
4187 {
4188 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
4189 #ifdef TCP_SIGNATURE
4190 tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
4191 #endif
4192 tb.t_state = TCPS_LISTEN;
4193 if (tcp_dooptions(&tb, optp, optlen, th, m, toff, 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