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