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