tcp_input.c revision 1.250 1 /* $NetBSD: tcp_input.c,v 1.250 2006/10/12 11:46:30 rpaulo 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.250 2006/10/12 11:46:30 rpaulo 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 tcp_reno_congestion_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 * We know we're losing at the current
2229 * window size so do congestion avoidance
2230 * (set ssthresh to half the current window
2231 * and pull our congestion window back to
2232 * the new ssthresh).
2233 *
2234 * Dup acks mean that packets have left the
2235 * network (they're now cached at the receiver)
2236 * so bump cwnd by the amount in the receiver
2237 * to keep a constant cwnd packets in the
2238 * network.
2239 *
2240 * When using TCP ECN, notify the peer that
2241 * we reduced the cwnd.
2242 *
2243 * If we are using TCP/SACK, then enter
2244 * Fast Recovery if the receiver SACKs
2245 * data that is tcprexmtthresh * MSS
2246 * bytes past the last ACKed segment,
2247 * irrespective of the number of DupAcks.
2248 */
2249 if (TCP_TIMER_ISARMED(tp, TCPT_REXMT) == 0 ||
2250 th->th_ack != tp->snd_una)
2251 tp->t_dupacks = 0;
2252 else if (tp->t_partialacks < 0 &&
2253 (++tp->t_dupacks == tcprexmtthresh ||
2254 TCP_FACK_FASTRECOV(tp))) {
2255 /*
2256 * Do the fast retransmit, and adjust
2257 * congestion control paramenters.
2258 */
2259 if (tp->t_congctl->fast_retransmit(tp, th)) {
2260 /* False fast retransmit */
2261 break;
2262 } else
2263 goto drop;
2264 } else if (tp->t_dupacks > tcprexmtthresh) {
2265 tp->snd_cwnd += tp->t_segsz;
2266 (void) tcp_output(tp);
2267 goto drop;
2268 }
2269 } else {
2270 /*
2271 * If the ack appears to be very old, only
2272 * allow data that is in-sequence. This
2273 * makes it somewhat more difficult to insert
2274 * forged data by guessing sequence numbers.
2275 * Sent an ack to try to update the send
2276 * sequence number on the other side.
2277 */
2278 if (tlen && th->th_seq != tp->rcv_nxt &&
2279 SEQ_LT(th->th_ack,
2280 tp->snd_una - tp->max_sndwnd))
2281 goto dropafterack;
2282 }
2283 break;
2284 }
2285 /*
2286 * If the congestion window was inflated to account
2287 * for the other side's cached packets, retract it.
2288 */
2289 /* XXX: make SACK have his own congestion control
2290 * struct -- rpaulo */
2291 if (TCP_SACK_ENABLED(tp))
2292 tcp_sack_newack(tp, th);
2293 else
2294 tp->t_congctl->fast_retransmit_newack(tp, th);
2295 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2296 tcpstat.tcps_rcvacktoomuch++;
2297 goto dropafterack;
2298 }
2299 acked = th->th_ack - tp->snd_una;
2300 tcpstat.tcps_rcvackpack++;
2301 tcpstat.tcps_rcvackbyte += acked;
2302
2303 /*
2304 * If we have a timestamp reply, update smoothed
2305 * round trip time. If no timestamp is present but
2306 * transmit timer is running and timed sequence
2307 * number was acked, update smoothed round trip time.
2308 * Since we now have an rtt measurement, cancel the
2309 * timer backoff (cf., Phil Karn's retransmit alg.).
2310 * Recompute the initial retransmit timer.
2311 */
2312 if (ts_rtt)
2313 tcp_xmit_timer(tp, ts_rtt);
2314 else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq))
2315 tcp_xmit_timer(tp, tcp_now - tp->t_rtttime);
2316
2317 /*
2318 * If all outstanding data is acked, stop retransmit
2319 * timer and remember to restart (more output or persist).
2320 * If there is more data to be acked, restart retransmit
2321 * timer, using current (possibly backed-off) value.
2322 */
2323 if (th->th_ack == tp->snd_max) {
2324 TCP_TIMER_DISARM(tp, TCPT_REXMT);
2325 needoutput = 1;
2326 } else if (TCP_TIMER_ISARMED(tp, TCPT_PERSIST) == 0)
2327 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
2328
2329 /*
2330 * New data has been acked, adjust the congestion window.
2331 */
2332 tp->t_congctl->newack(tp, th);
2333
2334 ND6_HINT(tp);
2335 if (acked > so->so_snd.sb_cc) {
2336 tp->snd_wnd -= so->so_snd.sb_cc;
2337 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2338 ourfinisacked = 1;
2339 } else {
2340 if (acked > (tp->t_lastoff - tp->t_inoff))
2341 tp->t_lastm = NULL;
2342 sbdrop(&so->so_snd, acked);
2343 tp->t_lastoff -= acked;
2344 tp->snd_wnd -= acked;
2345 ourfinisacked = 0;
2346 }
2347 sowwakeup(so);
2348
2349 ICMP_CHECK(tp, th, acked);
2350
2351 tp->snd_una = th->th_ack;
2352 if (SEQ_GT(tp->snd_una, tp->snd_fack))
2353 tp->snd_fack = tp->snd_una;
2354 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2355 tp->snd_nxt = tp->snd_una;
2356 if (SEQ_LT(tp->snd_high, tp->snd_una))
2357 tp->snd_high = tp->snd_una;
2358
2359 switch (tp->t_state) {
2360
2361 /*
2362 * In FIN_WAIT_1 STATE in addition to the processing
2363 * for the ESTABLISHED state if our FIN is now acknowledged
2364 * then enter FIN_WAIT_2.
2365 */
2366 case TCPS_FIN_WAIT_1:
2367 if (ourfinisacked) {
2368 /*
2369 * If we can't receive any more
2370 * data, then closing user can proceed.
2371 * Starting the timer is contrary to the
2372 * specification, but if we don't get a FIN
2373 * we'll hang forever.
2374 */
2375 if (so->so_state & SS_CANTRCVMORE) {
2376 soisdisconnected(so);
2377 if (tcp_maxidle > 0)
2378 TCP_TIMER_ARM(tp, TCPT_2MSL,
2379 tcp_maxidle);
2380 }
2381 tp->t_state = TCPS_FIN_WAIT_2;
2382 }
2383 break;
2384
2385 /*
2386 * In CLOSING STATE in addition to the processing for
2387 * the ESTABLISHED state if the ACK acknowledges our FIN
2388 * then enter the TIME-WAIT state, otherwise ignore
2389 * the segment.
2390 */
2391 case TCPS_CLOSING:
2392 if (ourfinisacked) {
2393 tp->t_state = TCPS_TIME_WAIT;
2394 tcp_canceltimers(tp);
2395 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2396 soisdisconnected(so);
2397 }
2398 break;
2399
2400 /*
2401 * In LAST_ACK, we may still be waiting for data to drain
2402 * and/or to be acked, as well as for the ack of our FIN.
2403 * If our FIN is now acknowledged, delete the TCB,
2404 * enter the closed state and return.
2405 */
2406 case TCPS_LAST_ACK:
2407 if (ourfinisacked) {
2408 tp = tcp_close(tp);
2409 goto drop;
2410 }
2411 break;
2412
2413 /*
2414 * In TIME_WAIT state the only thing that should arrive
2415 * is a retransmission of the remote FIN. Acknowledge
2416 * it and restart the finack timer.
2417 */
2418 case TCPS_TIME_WAIT:
2419 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2420 goto dropafterack;
2421 }
2422 }
2423
2424 step6:
2425 /*
2426 * Update window information.
2427 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2428 */
2429 if ((tiflags & TH_ACK) && (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2430 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2431 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2432 /* keep track of pure window updates */
2433 if (tlen == 0 &&
2434 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2435 tcpstat.tcps_rcvwinupd++;
2436 tp->snd_wnd = tiwin;
2437 tp->snd_wl1 = th->th_seq;
2438 tp->snd_wl2 = th->th_ack;
2439 if (tp->snd_wnd > tp->max_sndwnd)
2440 tp->max_sndwnd = tp->snd_wnd;
2441 needoutput = 1;
2442 }
2443
2444 /*
2445 * Process segments with URG.
2446 */
2447 if ((tiflags & TH_URG) && th->th_urp &&
2448 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2449 /*
2450 * This is a kludge, but if we receive and accept
2451 * random urgent pointers, we'll crash in
2452 * soreceive. It's hard to imagine someone
2453 * actually wanting to send this much urgent data.
2454 */
2455 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2456 th->th_urp = 0; /* XXX */
2457 tiflags &= ~TH_URG; /* XXX */
2458 goto dodata; /* XXX */
2459 }
2460 /*
2461 * If this segment advances the known urgent pointer,
2462 * then mark the data stream. This should not happen
2463 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2464 * a FIN has been received from the remote side.
2465 * In these states we ignore the URG.
2466 *
2467 * According to RFC961 (Assigned Protocols),
2468 * the urgent pointer points to the last octet
2469 * of urgent data. We continue, however,
2470 * to consider it to indicate the first octet
2471 * of data past the urgent section as the original
2472 * spec states (in one of two places).
2473 */
2474 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2475 tp->rcv_up = th->th_seq + th->th_urp;
2476 so->so_oobmark = so->so_rcv.sb_cc +
2477 (tp->rcv_up - tp->rcv_nxt) - 1;
2478 if (so->so_oobmark == 0)
2479 so->so_state |= SS_RCVATMARK;
2480 sohasoutofband(so);
2481 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2482 }
2483 /*
2484 * Remove out of band data so doesn't get presented to user.
2485 * This can happen independent of advancing the URG pointer,
2486 * but if two URG's are pending at once, some out-of-band
2487 * data may creep in... ick.
2488 */
2489 if (th->th_urp <= (u_int16_t) tlen
2490 #ifdef SO_OOBINLINE
2491 && (so->so_options & SO_OOBINLINE) == 0
2492 #endif
2493 )
2494 tcp_pulloutofband(so, th, m, hdroptlen);
2495 } else
2496 /*
2497 * If no out of band data is expected,
2498 * pull receive urgent pointer along
2499 * with the receive window.
2500 */
2501 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2502 tp->rcv_up = tp->rcv_nxt;
2503 dodata: /* XXX */
2504
2505 /*
2506 * Process the segment text, merging it into the TCP sequencing queue,
2507 * and arranging for acknowledgement of receipt if necessary.
2508 * This process logically involves adjusting tp->rcv_wnd as data
2509 * is presented to the user (this happens in tcp_usrreq.c,
2510 * case PRU_RCVD). If a FIN has already been received on this
2511 * connection then we just ignore the text.
2512 */
2513 if ((tlen || (tiflags & TH_FIN)) &&
2514 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2515 /*
2516 * Insert segment ti into reassembly queue of tcp with
2517 * control block tp. Return TH_FIN if reassembly now includes
2518 * a segment with FIN. The macro form does the common case
2519 * inline (segment is the next to be received on an
2520 * established connection, and the queue is empty),
2521 * avoiding linkage into and removal from the queue and
2522 * repetition of various conversions.
2523 * Set DELACK for segments received in order, but ack
2524 * immediately when segments are out of order
2525 * (so fast retransmit can work).
2526 */
2527 /* NOTE: this was TCP_REASS() macro, but used only once */
2528 TCP_REASS_LOCK(tp);
2529 if (th->th_seq == tp->rcv_nxt &&
2530 TAILQ_FIRST(&tp->segq) == NULL &&
2531 tp->t_state == TCPS_ESTABLISHED) {
2532 TCP_SETUP_ACK(tp, th);
2533 tp->rcv_nxt += tlen;
2534 tiflags = th->th_flags & TH_FIN;
2535 tcpstat.tcps_rcvpack++;
2536 tcpstat.tcps_rcvbyte += tlen;
2537 ND6_HINT(tp);
2538 if (so->so_state & SS_CANTRCVMORE)
2539 m_freem(m);
2540 else {
2541 m_adj(m, hdroptlen);
2542 sbappendstream(&(so)->so_rcv, m);
2543 }
2544 sorwakeup(so);
2545 } else {
2546 m_adj(m, hdroptlen);
2547 tiflags = tcp_reass(tp, th, m, &tlen);
2548 tp->t_flags |= TF_ACKNOW;
2549 }
2550 TCP_REASS_UNLOCK(tp);
2551
2552 /*
2553 * Note the amount of data that peer has sent into
2554 * our window, in order to estimate the sender's
2555 * buffer size.
2556 */
2557 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2558 } else {
2559 m_freem(m);
2560 m = NULL;
2561 tiflags &= ~TH_FIN;
2562 }
2563
2564 /*
2565 * If FIN is received ACK the FIN and let the user know
2566 * that the connection is closing. Ignore a FIN received before
2567 * the connection is fully established.
2568 */
2569 if ((tiflags & TH_FIN) && TCPS_HAVEESTABLISHED(tp->t_state)) {
2570 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2571 socantrcvmore(so);
2572 tp->t_flags |= TF_ACKNOW;
2573 tp->rcv_nxt++;
2574 }
2575 switch (tp->t_state) {
2576
2577 /*
2578 * In ESTABLISHED STATE enter the CLOSE_WAIT state.
2579 */
2580 case TCPS_ESTABLISHED:
2581 tp->t_state = TCPS_CLOSE_WAIT;
2582 break;
2583
2584 /*
2585 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2586 * enter the CLOSING state.
2587 */
2588 case TCPS_FIN_WAIT_1:
2589 tp->t_state = TCPS_CLOSING;
2590 break;
2591
2592 /*
2593 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2594 * starting the time-wait timer, turning off the other
2595 * standard timers.
2596 */
2597 case TCPS_FIN_WAIT_2:
2598 tp->t_state = TCPS_TIME_WAIT;
2599 tcp_canceltimers(tp);
2600 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2601 soisdisconnected(so);
2602 break;
2603
2604 /*
2605 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2606 */
2607 case TCPS_TIME_WAIT:
2608 TCP_TIMER_ARM(tp, TCPT_2MSL, 2 * TCPTV_MSL);
2609 break;
2610 }
2611 }
2612 #ifdef TCP_DEBUG
2613 if (so->so_options & SO_DEBUG)
2614 tcp_trace(TA_INPUT, ostate, tp, tcp_saveti, 0);
2615 #endif
2616
2617 /*
2618 * Return any desired output.
2619 */
2620 if (needoutput || (tp->t_flags & TF_ACKNOW)) {
2621 (void) tcp_output(tp);
2622 }
2623 if (tcp_saveti)
2624 m_freem(tcp_saveti);
2625 return;
2626
2627 badsyn:
2628 /*
2629 * Received a bad SYN. Increment counters and dropwithreset.
2630 */
2631 tcpstat.tcps_badsyn++;
2632 tp = NULL;
2633 goto dropwithreset;
2634
2635 dropafterack:
2636 /*
2637 * Generate an ACK dropping incoming segment if it occupies
2638 * sequence space, where the ACK reflects our state.
2639 */
2640 if (tiflags & TH_RST)
2641 goto drop;
2642 goto dropafterack2;
2643
2644 dropafterack_ratelim:
2645 /*
2646 * We may want to rate-limit ACKs against SYN/RST attack.
2647 */
2648 if (ppsratecheck(&tcp_ackdrop_ppslim_last, &tcp_ackdrop_ppslim_count,
2649 tcp_ackdrop_ppslim) == 0) {
2650 /* XXX stat */
2651 goto drop;
2652 }
2653 /* ...fall into dropafterack2... */
2654
2655 dropafterack2:
2656 m_freem(m);
2657 tp->t_flags |= TF_ACKNOW;
2658 (void) tcp_output(tp);
2659 if (tcp_saveti)
2660 m_freem(tcp_saveti);
2661 return;
2662
2663 dropwithreset_ratelim:
2664 /*
2665 * We may want to rate-limit RSTs in certain situations,
2666 * particularly if we are sending an RST in response to
2667 * an attempt to connect to or otherwise communicate with
2668 * a port for which we have no socket.
2669 */
2670 if (ppsratecheck(&tcp_rst_ppslim_last, &tcp_rst_ppslim_count,
2671 tcp_rst_ppslim) == 0) {
2672 /* XXX stat */
2673 goto drop;
2674 }
2675 /* ...fall into dropwithreset... */
2676
2677 dropwithreset:
2678 /*
2679 * Generate a RST, dropping incoming segment.
2680 * Make ACK acceptable to originator of segment.
2681 */
2682 if (tiflags & TH_RST)
2683 goto drop;
2684
2685 switch (af) {
2686 #ifdef INET6
2687 case AF_INET6:
2688 /* For following calls to tcp_respond */
2689 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2690 goto drop;
2691 break;
2692 #endif /* INET6 */
2693 case AF_INET:
2694 if (IN_MULTICAST(ip->ip_dst.s_addr) ||
2695 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2696 goto drop;
2697 }
2698
2699 if (tiflags & TH_ACK)
2700 (void)tcp_respond(tp, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
2701 else {
2702 if (tiflags & TH_SYN)
2703 tlen++;
2704 (void)tcp_respond(tp, m, m, th, th->th_seq + tlen, (tcp_seq)0,
2705 TH_RST|TH_ACK);
2706 }
2707 if (tcp_saveti)
2708 m_freem(tcp_saveti);
2709 return;
2710
2711 badcsum:
2712 drop:
2713 /*
2714 * Drop space held by incoming segment and return.
2715 */
2716 if (tp) {
2717 if (tp->t_inpcb)
2718 so = tp->t_inpcb->inp_socket;
2719 #ifdef INET6
2720 else if (tp->t_in6pcb)
2721 so = tp->t_in6pcb->in6p_socket;
2722 #endif
2723 else
2724 so = NULL;
2725 #ifdef TCP_DEBUG
2726 if (so && (so->so_options & SO_DEBUG) != 0)
2727 tcp_trace(TA_DROP, ostate, tp, tcp_saveti, 0);
2728 #endif
2729 }
2730 if (tcp_saveti)
2731 m_freem(tcp_saveti);
2732 m_freem(m);
2733 return;
2734 }
2735
2736 #ifdef TCP_SIGNATURE
2737 int
2738 tcp_signature_apply(void *fstate, caddr_t data, u_int len)
2739 {
2740
2741 MD5Update(fstate, (u_char *)data, len);
2742 return (0);
2743 }
2744
2745 struct secasvar *
2746 tcp_signature_getsav(struct mbuf *m, struct tcphdr *th)
2747 {
2748 struct secasvar *sav;
2749 #ifdef FAST_IPSEC
2750 union sockaddr_union dst;
2751 #endif
2752 struct ip *ip;
2753 struct ip6_hdr *ip6;
2754
2755 ip = mtod(m, struct ip *);
2756 switch (ip->ip_v) {
2757 case 4:
2758 ip = mtod(m, struct ip *);
2759 ip6 = NULL;
2760 break;
2761 case 6:
2762 ip = NULL;
2763 ip6 = mtod(m, struct ip6_hdr *);
2764 break;
2765 default:
2766 return (NULL);
2767 }
2768
2769 #ifdef FAST_IPSEC
2770 /* Extract the destination from the IP header in the mbuf. */
2771 bzero(&dst, sizeof(union sockaddr_union));
2772 dst.sa.sa_len = sizeof(struct sockaddr_in);
2773 dst.sa.sa_family = AF_INET;
2774 dst.sin.sin_addr = ip->ip_dst;
2775
2776 /*
2777 * Look up an SADB entry which matches the address of the peer.
2778 */
2779 sav = KEY_ALLOCSA(&dst, IPPROTO_TCP, htonl(TCP_SIG_SPI));
2780 #else
2781 if (ip)
2782 sav = key_allocsa(AF_INET, (caddr_t)&ip->ip_src,
2783 (caddr_t)&ip->ip_dst, IPPROTO_TCP,
2784 htonl(TCP_SIG_SPI), 0, 0);
2785 else
2786 sav = key_allocsa(AF_INET6, (caddr_t)&ip6->ip6_src,
2787 (caddr_t)&ip6->ip6_dst, IPPROTO_TCP,
2788 htonl(TCP_SIG_SPI), 0, 0);
2789 #endif
2790
2791 return (sav); /* freesav must be performed by caller */
2792 }
2793
2794 int
2795 tcp_signature(struct mbuf *m, struct tcphdr *th, int thoff,
2796 struct secasvar *sav, char *sig)
2797 {
2798 MD5_CTX ctx;
2799 struct ip *ip;
2800 struct ipovly *ipovly;
2801 struct ip6_hdr *ip6;
2802 struct ippseudo ippseudo;
2803 struct ip6_hdr_pseudo ip6pseudo;
2804 struct tcphdr th0;
2805 int l, tcphdrlen;
2806
2807 if (sav == NULL)
2808 return (-1);
2809
2810 tcphdrlen = th->th_off * 4;
2811
2812 switch (mtod(m, struct ip *)->ip_v) {
2813 case 4:
2814 ip = mtod(m, struct ip *);
2815 ip6 = NULL;
2816 break;
2817 case 6:
2818 ip = NULL;
2819 ip6 = mtod(m, struct ip6_hdr *);
2820 break;
2821 default:
2822 return (-1);
2823 }
2824
2825 MD5Init(&ctx);
2826
2827 if (ip) {
2828 memset(&ippseudo, 0, sizeof(ippseudo));
2829 ipovly = (struct ipovly *)ip;
2830 ippseudo.ippseudo_src = ipovly->ih_src;
2831 ippseudo.ippseudo_dst = ipovly->ih_dst;
2832 ippseudo.ippseudo_pad = 0;
2833 ippseudo.ippseudo_p = IPPROTO_TCP;
2834 ippseudo.ippseudo_len = htons(m->m_pkthdr.len - thoff);
2835 MD5Update(&ctx, (char *)&ippseudo, sizeof(ippseudo));
2836 } else {
2837 memset(&ip6pseudo, 0, sizeof(ip6pseudo));
2838 ip6pseudo.ip6ph_src = ip6->ip6_src;
2839 in6_clearscope(&ip6pseudo.ip6ph_src);
2840 ip6pseudo.ip6ph_dst = ip6->ip6_dst;
2841 in6_clearscope(&ip6pseudo.ip6ph_dst);
2842 ip6pseudo.ip6ph_len = htons(m->m_pkthdr.len - thoff);
2843 ip6pseudo.ip6ph_nxt = IPPROTO_TCP;
2844 MD5Update(&ctx, (char *)&ip6pseudo, sizeof(ip6pseudo));
2845 }
2846
2847 th0 = *th;
2848 th0.th_sum = 0;
2849 MD5Update(&ctx, (char *)&th0, sizeof(th0));
2850
2851 l = m->m_pkthdr.len - thoff - tcphdrlen;
2852 if (l > 0)
2853 m_apply(m, thoff + tcphdrlen,
2854 m->m_pkthdr.len - thoff - tcphdrlen,
2855 tcp_signature_apply, &ctx);
2856
2857 MD5Update(&ctx, _KEYBUF(sav->key_auth), _KEYLEN(sav->key_auth));
2858 MD5Final(sig, &ctx);
2859
2860 return (0);
2861 }
2862 #endif
2863
2864 int
2865 tcp_dooptions(struct tcpcb *tp, u_char *cp, int cnt, struct tcphdr *th,
2866 struct mbuf *m __unused, int toff __unused, struct tcp_opt_info *oi)
2867 {
2868 u_int16_t mss;
2869 int opt, optlen = 0;
2870 #ifdef TCP_SIGNATURE
2871 caddr_t sigp = NULL;
2872 char sigbuf[TCP_SIGLEN];
2873 struct secasvar *sav = NULL;
2874 #endif
2875
2876 for (; cp && cnt > 0; cnt -= optlen, cp += optlen) {
2877 opt = cp[0];
2878 if (opt == TCPOPT_EOL)
2879 break;
2880 if (opt == TCPOPT_NOP)
2881 optlen = 1;
2882 else {
2883 if (cnt < 2)
2884 break;
2885 optlen = cp[1];
2886 if (optlen < 2 || optlen > cnt)
2887 break;
2888 }
2889 switch (opt) {
2890
2891 default:
2892 continue;
2893
2894 case TCPOPT_MAXSEG:
2895 if (optlen != TCPOLEN_MAXSEG)
2896 continue;
2897 if (!(th->th_flags & TH_SYN))
2898 continue;
2899 if (TCPS_HAVERCVDSYN(tp->t_state))
2900 continue;
2901 bcopy(cp + 2, &mss, sizeof(mss));
2902 oi->maxseg = ntohs(mss);
2903 break;
2904
2905 case TCPOPT_WINDOW:
2906 if (optlen != TCPOLEN_WINDOW)
2907 continue;
2908 if (!(th->th_flags & TH_SYN))
2909 continue;
2910 if (TCPS_HAVERCVDSYN(tp->t_state))
2911 continue;
2912 tp->t_flags |= TF_RCVD_SCALE;
2913 tp->requested_s_scale = cp[2];
2914 if (tp->requested_s_scale > TCP_MAX_WINSHIFT) {
2915 #if 0 /*XXX*/
2916 char *p;
2917
2918 if (ip)
2919 p = ntohl(ip->ip_src);
2920 #ifdef INET6
2921 else if (ip6)
2922 p = ip6_sprintf(&ip6->ip6_src);
2923 #endif
2924 else
2925 p = "(unknown)";
2926 log(LOG_ERR, "TCP: invalid wscale %d from %s, "
2927 "assuming %d\n",
2928 tp->requested_s_scale, p,
2929 TCP_MAX_WINSHIFT);
2930 #else
2931 log(LOG_ERR, "TCP: invalid wscale %d, "
2932 "assuming %d\n",
2933 tp->requested_s_scale,
2934 TCP_MAX_WINSHIFT);
2935 #endif
2936 tp->requested_s_scale = TCP_MAX_WINSHIFT;
2937 }
2938 break;
2939
2940 case TCPOPT_TIMESTAMP:
2941 if (optlen != TCPOLEN_TIMESTAMP)
2942 continue;
2943 oi->ts_present = 1;
2944 bcopy(cp + 2, &oi->ts_val, sizeof(oi->ts_val));
2945 NTOHL(oi->ts_val);
2946 bcopy(cp + 6, &oi->ts_ecr, sizeof(oi->ts_ecr));
2947 NTOHL(oi->ts_ecr);
2948
2949 if (!(th->th_flags & TH_SYN))
2950 continue;
2951 if (TCPS_HAVERCVDSYN(tp->t_state))
2952 continue;
2953 /*
2954 * A timestamp received in a SYN makes
2955 * it ok to send timestamp requests and replies.
2956 */
2957 tp->t_flags |= TF_RCVD_TSTMP;
2958 tp->ts_recent = oi->ts_val;
2959 tp->ts_recent_age = tcp_now;
2960 break;
2961
2962 case TCPOPT_SACK_PERMITTED:
2963 if (optlen != TCPOLEN_SACK_PERMITTED)
2964 continue;
2965 if (!(th->th_flags & TH_SYN))
2966 continue;
2967 if (TCPS_HAVERCVDSYN(tp->t_state))
2968 continue;
2969 if (tcp_do_sack) {
2970 tp->t_flags |= TF_SACK_PERMIT;
2971 tp->t_flags |= TF_WILL_SACK;
2972 }
2973 break;
2974
2975 case TCPOPT_SACK:
2976 tcp_sack_option(tp, th, cp, optlen);
2977 break;
2978 #ifdef TCP_SIGNATURE
2979 case TCPOPT_SIGNATURE:
2980 if (optlen != TCPOLEN_SIGNATURE)
2981 continue;
2982 if (sigp && bcmp(sigp, cp + 2, TCP_SIGLEN))
2983 return (-1);
2984
2985 sigp = sigbuf;
2986 memcpy(sigbuf, cp + 2, TCP_SIGLEN);
2987 memset(cp + 2, 0, TCP_SIGLEN);
2988 tp->t_flags |= TF_SIGNATURE;
2989 break;
2990 #endif
2991 }
2992 }
2993
2994 #ifdef TCP_SIGNATURE
2995 if (tp->t_flags & TF_SIGNATURE) {
2996
2997 sav = tcp_signature_getsav(m, th);
2998
2999 if (sav == NULL && tp->t_state == TCPS_LISTEN)
3000 return (-1);
3001 }
3002
3003 if ((sigp ? TF_SIGNATURE : 0) ^ (tp->t_flags & TF_SIGNATURE)) {
3004 if (sav == NULL)
3005 return (-1);
3006 #ifdef FAST_IPSEC
3007 KEY_FREESAV(&sav);
3008 #else
3009 key_freesav(sav);
3010 #endif
3011 return (-1);
3012 }
3013
3014 if (sigp) {
3015 char sig[TCP_SIGLEN];
3016
3017 TCP_FIELDS_TO_NET(th);
3018 if (tcp_signature(m, th, toff, sav, sig) < 0) {
3019 TCP_FIELDS_TO_HOST(th);
3020 if (sav == NULL)
3021 return (-1);
3022 #ifdef FAST_IPSEC
3023 KEY_FREESAV(&sav);
3024 #else
3025 key_freesav(sav);
3026 #endif
3027 return (-1);
3028 }
3029 TCP_FIELDS_TO_HOST(th);
3030
3031 if (bcmp(sig, sigp, TCP_SIGLEN)) {
3032 tcpstat.tcps_badsig++;
3033 if (sav == NULL)
3034 return (-1);
3035 #ifdef FAST_IPSEC
3036 KEY_FREESAV(&sav);
3037 #else
3038 key_freesav(sav);
3039 #endif
3040 return (-1);
3041 } else
3042 tcpstat.tcps_goodsig++;
3043
3044 key_sa_recordxfer(sav, m);
3045 #ifdef FAST_IPSEC
3046 KEY_FREESAV(&sav);
3047 #else
3048 key_freesav(sav);
3049 #endif
3050 }
3051 #endif
3052
3053 return (0);
3054 }
3055
3056 /*
3057 * Pull out of band byte out of a segment so
3058 * it doesn't appear in the user's data queue.
3059 * It is still reflected in the segment length for
3060 * sequencing purposes.
3061 */
3062 void
3063 tcp_pulloutofband(struct socket *so, struct tcphdr *th,
3064 struct mbuf *m, int off)
3065 {
3066 int cnt = off + th->th_urp - 1;
3067
3068 while (cnt >= 0) {
3069 if (m->m_len > cnt) {
3070 char *cp = mtod(m, caddr_t) + cnt;
3071 struct tcpcb *tp = sototcpcb(so);
3072
3073 tp->t_iobc = *cp;
3074 tp->t_oobflags |= TCPOOB_HAVEDATA;
3075 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
3076 m->m_len--;
3077 return;
3078 }
3079 cnt -= m->m_len;
3080 m = m->m_next;
3081 if (m == 0)
3082 break;
3083 }
3084 panic("tcp_pulloutofband");
3085 }
3086
3087 /*
3088 * Collect new round-trip time estimate
3089 * and update averages and current timeout.
3090 */
3091 void
3092 tcp_xmit_timer(struct tcpcb *tp, uint32_t rtt)
3093 {
3094 int32_t delta;
3095
3096 tcpstat.tcps_rttupdated++;
3097 if (tp->t_srtt != 0) {
3098 /*
3099 * srtt is stored as fixed point with 3 bits after the
3100 * binary point (i.e., scaled by 8). The following magic
3101 * is equivalent to the smoothing algorithm in rfc793 with
3102 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3103 * point). Adjust rtt to origin 0.
3104 */
3105 delta = (rtt << 2) - (tp->t_srtt >> TCP_RTT_SHIFT);
3106 if ((tp->t_srtt += delta) <= 0)
3107 tp->t_srtt = 1 << 2;
3108 /*
3109 * We accumulate a smoothed rtt variance (actually, a
3110 * smoothed mean difference), then set the retransmit
3111 * timer to smoothed rtt + 4 times the smoothed variance.
3112 * rttvar is stored as fixed point with 2 bits after the
3113 * binary point (scaled by 4). The following is
3114 * equivalent to rfc793 smoothing with an alpha of .75
3115 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3116 * rfc793's wired-in beta.
3117 */
3118 if (delta < 0)
3119 delta = -delta;
3120 delta -= (tp->t_rttvar >> TCP_RTTVAR_SHIFT);
3121 if ((tp->t_rttvar += delta) <= 0)
3122 tp->t_rttvar = 1 << 2;
3123 } else {
3124 /*
3125 * No rtt measurement yet - use the unsmoothed rtt.
3126 * Set the variance to half the rtt (so our first
3127 * retransmit happens at 3*rtt).
3128 */
3129 tp->t_srtt = rtt << (TCP_RTT_SHIFT + 2);
3130 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT + 2 - 1);
3131 }
3132 tp->t_rtttime = 0;
3133 tp->t_rxtshift = 0;
3134
3135 /*
3136 * the retransmit should happen at rtt + 4 * rttvar.
3137 * Because of the way we do the smoothing, srtt and rttvar
3138 * will each average +1/2 tick of bias. When we compute
3139 * the retransmit timer, we want 1/2 tick of rounding and
3140 * 1 extra tick because of +-1/2 tick uncertainty in the
3141 * firing of the timer. The bias will give us exactly the
3142 * 1.5 tick we need. But, because the bias is
3143 * statistical, we have to test that we don't drop below
3144 * the minimum feasible timer (which is 2 ticks).
3145 */
3146 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3147 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3148
3149 /*
3150 * We received an ack for a packet that wasn't retransmitted;
3151 * it is probably safe to discard any error indications we've
3152 * received recently. This isn't quite right, but close enough
3153 * for now (a route might have failed after we sent a segment,
3154 * and the return path might not be symmetrical).
3155 */
3156 tp->t_softerror = 0;
3157 }
3158
3159
3160 /*
3161 * TCP compressed state engine. Currently used to hold compressed
3162 * state for SYN_RECEIVED.
3163 */
3164
3165 u_long syn_cache_count;
3166 u_int32_t syn_hash1, syn_hash2;
3167
3168 #define SYN_HASH(sa, sp, dp) \
3169 ((((sa)->s_addr^syn_hash1)*(((((u_int32_t)(dp))<<16) + \
3170 ((u_int32_t)(sp)))^syn_hash2)))
3171 #ifndef INET6
3172 #define SYN_HASHALL(hash, src, dst) \
3173 do { \
3174 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3175 ((const struct sockaddr_in *)(src))->sin_port, \
3176 ((const struct sockaddr_in *)(dst))->sin_port); \
3177 } while (/*CONSTCOND*/ 0)
3178 #else
3179 #define SYN_HASH6(sa, sp, dp) \
3180 ((((sa)->s6_addr32[0] ^ (sa)->s6_addr32[3] ^ syn_hash1) * \
3181 (((((u_int32_t)(dp))<<16) + ((u_int32_t)(sp)))^syn_hash2)) \
3182 & 0x7fffffff)
3183
3184 #define SYN_HASHALL(hash, src, dst) \
3185 do { \
3186 switch ((src)->sa_family) { \
3187 case AF_INET: \
3188 hash = SYN_HASH(&((const struct sockaddr_in *)(src))->sin_addr, \
3189 ((const struct sockaddr_in *)(src))->sin_port, \
3190 ((const struct sockaddr_in *)(dst))->sin_port); \
3191 break; \
3192 case AF_INET6: \
3193 hash = SYN_HASH6(&((const struct sockaddr_in6 *)(src))->sin6_addr, \
3194 ((const struct sockaddr_in6 *)(src))->sin6_port, \
3195 ((const struct sockaddr_in6 *)(dst))->sin6_port); \
3196 break; \
3197 default: \
3198 hash = 0; \
3199 } \
3200 } while (/*CONSTCOND*/0)
3201 #endif /* INET6 */
3202
3203 #define SYN_CACHE_RM(sc) \
3204 do { \
3205 TAILQ_REMOVE(&tcp_syn_cache[(sc)->sc_bucketidx].sch_bucket, \
3206 (sc), sc_bucketq); \
3207 (sc)->sc_tp = NULL; \
3208 LIST_REMOVE((sc), sc_tpq); \
3209 tcp_syn_cache[(sc)->sc_bucketidx].sch_length--; \
3210 callout_stop(&(sc)->sc_timer); \
3211 syn_cache_count--; \
3212 } while (/*CONSTCOND*/0)
3213
3214 #define SYN_CACHE_PUT(sc) \
3215 do { \
3216 if ((sc)->sc_ipopts) \
3217 (void) m_free((sc)->sc_ipopts); \
3218 if ((sc)->sc_route4.ro_rt != NULL) \
3219 RTFREE((sc)->sc_route4.ro_rt); \
3220 if (callout_invoking(&(sc)->sc_timer)) \
3221 (sc)->sc_flags |= SCF_DEAD; \
3222 else \
3223 pool_put(&syn_cache_pool, (sc)); \
3224 } while (/*CONSTCOND*/0)
3225
3226 POOL_INIT(syn_cache_pool, sizeof(struct syn_cache), 0, 0, 0, "synpl", NULL);
3227
3228 /*
3229 * We don't estimate RTT with SYNs, so each packet starts with the default
3230 * RTT and each timer step has a fixed timeout value.
3231 */
3232 #define SYN_CACHE_TIMER_ARM(sc) \
3233 do { \
3234 TCPT_RANGESET((sc)->sc_rxtcur, \
3235 TCPTV_SRTTDFLT * tcp_backoff[(sc)->sc_rxtshift], TCPTV_MIN, \
3236 TCPTV_REXMTMAX); \
3237 callout_reset(&(sc)->sc_timer, \
3238 (sc)->sc_rxtcur * (hz / PR_SLOWHZ), syn_cache_timer, (sc)); \
3239 } while (/*CONSTCOND*/0)
3240
3241 #define SYN_CACHE_TIMESTAMP(sc) (tcp_now - (sc)->sc_timebase)
3242
3243 void
3244 syn_cache_init(void)
3245 {
3246 int i;
3247
3248 /* Initialize the hash buckets. */
3249 for (i = 0; i < tcp_syn_cache_size; i++)
3250 TAILQ_INIT(&tcp_syn_cache[i].sch_bucket);
3251 }
3252
3253 void
3254 syn_cache_insert(struct syn_cache *sc, struct tcpcb *tp)
3255 {
3256 struct syn_cache_head *scp;
3257 struct syn_cache *sc2;
3258 int s;
3259
3260 /*
3261 * If there are no entries in the hash table, reinitialize
3262 * the hash secrets.
3263 */
3264 if (syn_cache_count == 0) {
3265 syn_hash1 = arc4random();
3266 syn_hash2 = arc4random();
3267 }
3268
3269 SYN_HASHALL(sc->sc_hash, &sc->sc_src.sa, &sc->sc_dst.sa);
3270 sc->sc_bucketidx = sc->sc_hash % tcp_syn_cache_size;
3271 scp = &tcp_syn_cache[sc->sc_bucketidx];
3272
3273 /*
3274 * Make sure that we don't overflow the per-bucket
3275 * limit or the total cache size limit.
3276 */
3277 s = splsoftnet();
3278 if (scp->sch_length >= tcp_syn_bucket_limit) {
3279 tcpstat.tcps_sc_bucketoverflow++;
3280 /*
3281 * The bucket is full. Toss the oldest element in the
3282 * bucket. This will be the first entry in the bucket.
3283 */
3284 sc2 = TAILQ_FIRST(&scp->sch_bucket);
3285 #ifdef DIAGNOSTIC
3286 /*
3287 * This should never happen; we should always find an
3288 * entry in our bucket.
3289 */
3290 if (sc2 == NULL)
3291 panic("syn_cache_insert: bucketoverflow: impossible");
3292 #endif
3293 SYN_CACHE_RM(sc2);
3294 SYN_CACHE_PUT(sc2); /* calls pool_put but see spl above */
3295 } else if (syn_cache_count >= tcp_syn_cache_limit) {
3296 struct syn_cache_head *scp2, *sce;
3297
3298 tcpstat.tcps_sc_overflowed++;
3299 /*
3300 * The cache is full. Toss the oldest entry in the
3301 * first non-empty bucket we can find.
3302 *
3303 * XXX We would really like to toss the oldest
3304 * entry in the cache, but we hope that this
3305 * condition doesn't happen very often.
3306 */
3307 scp2 = scp;
3308 if (TAILQ_EMPTY(&scp2->sch_bucket)) {
3309 sce = &tcp_syn_cache[tcp_syn_cache_size];
3310 for (++scp2; scp2 != scp; scp2++) {
3311 if (scp2 >= sce)
3312 scp2 = &tcp_syn_cache[0];
3313 if (! TAILQ_EMPTY(&scp2->sch_bucket))
3314 break;
3315 }
3316 #ifdef DIAGNOSTIC
3317 /*
3318 * This should never happen; we should always find a
3319 * non-empty bucket.
3320 */
3321 if (scp2 == scp)
3322 panic("syn_cache_insert: cacheoverflow: "
3323 "impossible");
3324 #endif
3325 }
3326 sc2 = TAILQ_FIRST(&scp2->sch_bucket);
3327 SYN_CACHE_RM(sc2);
3328 SYN_CACHE_PUT(sc2); /* calls pool_put but see spl above */
3329 }
3330
3331 /*
3332 * Initialize the entry's timer.
3333 */
3334 sc->sc_rxttot = 0;
3335 sc->sc_rxtshift = 0;
3336 SYN_CACHE_TIMER_ARM(sc);
3337
3338 /* Link it from tcpcb entry */
3339 LIST_INSERT_HEAD(&tp->t_sc, sc, sc_tpq);
3340
3341 /* Put it into the bucket. */
3342 TAILQ_INSERT_TAIL(&scp->sch_bucket, sc, sc_bucketq);
3343 scp->sch_length++;
3344 syn_cache_count++;
3345
3346 tcpstat.tcps_sc_added++;
3347 splx(s);
3348 }
3349
3350 /*
3351 * Walk the timer queues, looking for SYN,ACKs that need to be retransmitted.
3352 * If we have retransmitted an entry the maximum number of times, expire
3353 * that entry.
3354 */
3355 void
3356 syn_cache_timer(void *arg)
3357 {
3358 struct syn_cache *sc = arg;
3359 int s;
3360
3361 s = splsoftnet();
3362 callout_ack(&sc->sc_timer);
3363
3364 if (__predict_false(sc->sc_flags & SCF_DEAD)) {
3365 tcpstat.tcps_sc_delayed_free++;
3366 pool_put(&syn_cache_pool, sc);
3367 splx(s);
3368 return;
3369 }
3370
3371 if (__predict_false(sc->sc_rxtshift == TCP_MAXRXTSHIFT)) {
3372 /* Drop it -- too many retransmissions. */
3373 goto dropit;
3374 }
3375
3376 /*
3377 * Compute the total amount of time this entry has
3378 * been on a queue. If this entry has been on longer
3379 * than the keep alive timer would allow, expire it.
3380 */
3381 sc->sc_rxttot += sc->sc_rxtcur;
3382 if (sc->sc_rxttot >= TCPTV_KEEP_INIT)
3383 goto dropit;
3384
3385 tcpstat.tcps_sc_retransmitted++;
3386 (void) syn_cache_respond(sc, NULL);
3387
3388 /* Advance the timer back-off. */
3389 sc->sc_rxtshift++;
3390 SYN_CACHE_TIMER_ARM(sc);
3391
3392 splx(s);
3393 return;
3394
3395 dropit:
3396 tcpstat.tcps_sc_timed_out++;
3397 SYN_CACHE_RM(sc);
3398 SYN_CACHE_PUT(sc); /* calls pool_put but see spl above */
3399 splx(s);
3400 }
3401
3402 /*
3403 * Remove syn cache created by the specified tcb entry,
3404 * because this does not make sense to keep them
3405 * (if there's no tcb entry, syn cache entry will never be used)
3406 */
3407 void
3408 syn_cache_cleanup(struct tcpcb *tp)
3409 {
3410 struct syn_cache *sc, *nsc;
3411 int s;
3412
3413 s = splsoftnet();
3414
3415 for (sc = LIST_FIRST(&tp->t_sc); sc != NULL; sc = nsc) {
3416 nsc = LIST_NEXT(sc, sc_tpq);
3417
3418 #ifdef DIAGNOSTIC
3419 if (sc->sc_tp != tp)
3420 panic("invalid sc_tp in syn_cache_cleanup");
3421 #endif
3422 SYN_CACHE_RM(sc);
3423 SYN_CACHE_PUT(sc); /* calls pool_put but see spl above */
3424 }
3425 /* just for safety */
3426 LIST_INIT(&tp->t_sc);
3427
3428 splx(s);
3429 }
3430
3431 /*
3432 * Find an entry in the syn cache.
3433 */
3434 struct syn_cache *
3435 syn_cache_lookup(const struct sockaddr *src, const struct sockaddr *dst,
3436 struct syn_cache_head **headp)
3437 {
3438 struct syn_cache *sc;
3439 struct syn_cache_head *scp;
3440 u_int32_t hash;
3441 int s;
3442
3443 SYN_HASHALL(hash, src, dst);
3444
3445 scp = &tcp_syn_cache[hash % tcp_syn_cache_size];
3446 *headp = scp;
3447 s = splsoftnet();
3448 for (sc = TAILQ_FIRST(&scp->sch_bucket); sc != NULL;
3449 sc = TAILQ_NEXT(sc, sc_bucketq)) {
3450 if (sc->sc_hash != hash)
3451 continue;
3452 if (!bcmp(&sc->sc_src, src, src->sa_len) &&
3453 !bcmp(&sc->sc_dst, dst, dst->sa_len)) {
3454 splx(s);
3455 return (sc);
3456 }
3457 }
3458 splx(s);
3459 return (NULL);
3460 }
3461
3462 /*
3463 * This function gets called when we receive an ACK for a
3464 * socket in the LISTEN state. We look up the connection
3465 * in the syn cache, and if its there, we pull it out of
3466 * the cache and turn it into a full-blown connection in
3467 * the SYN-RECEIVED state.
3468 *
3469 * The return values may not be immediately obvious, and their effects
3470 * can be subtle, so here they are:
3471 *
3472 * NULL SYN was not found in cache; caller should drop the
3473 * packet and send an RST.
3474 *
3475 * -1 We were unable to create the new connection, and are
3476 * aborting it. An ACK,RST is being sent to the peer
3477 * (unless we got screwey sequence numbners; see below),
3478 * because the 3-way handshake has been completed. Caller
3479 * should not free the mbuf, since we may be using it. If
3480 * we are not, we will free it.
3481 *
3482 * Otherwise, the return value is a pointer to the new socket
3483 * associated with the connection.
3484 */
3485 struct socket *
3486 syn_cache_get(struct sockaddr *src, struct sockaddr *dst,
3487 struct tcphdr *th, unsigned int hlen __unused, unsigned int tlen __unused,
3488 struct socket *so, struct mbuf *m)
3489 {
3490 struct syn_cache *sc;
3491 struct syn_cache_head *scp;
3492 struct inpcb *inp = NULL;
3493 #ifdef INET6
3494 struct in6pcb *in6p = NULL;
3495 #endif
3496 struct tcpcb *tp = 0;
3497 struct mbuf *am;
3498 int s;
3499 struct socket *oso;
3500
3501 s = splsoftnet();
3502 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3503 splx(s);
3504 return (NULL);
3505 }
3506
3507 /*
3508 * Verify the sequence and ack numbers. Try getting the correct
3509 * response again.
3510 */
3511 if ((th->th_ack != sc->sc_iss + 1) ||
3512 SEQ_LEQ(th->th_seq, sc->sc_irs) ||
3513 SEQ_GT(th->th_seq, sc->sc_irs + 1 + sc->sc_win)) {
3514 (void) syn_cache_respond(sc, m);
3515 splx(s);
3516 return ((struct socket *)(-1));
3517 }
3518
3519 /* Remove this cache entry */
3520 SYN_CACHE_RM(sc);
3521 splx(s);
3522
3523 /*
3524 * Ok, create the full blown connection, and set things up
3525 * as they would have been set up if we had created the
3526 * connection when the SYN arrived. If we can't create
3527 * the connection, abort it.
3528 */
3529 /*
3530 * inp still has the OLD in_pcb stuff, set the
3531 * v6-related flags on the new guy, too. This is
3532 * done particularly for the case where an AF_INET6
3533 * socket is bound only to a port, and a v4 connection
3534 * comes in on that port.
3535 * we also copy the flowinfo from the original pcb
3536 * to the new one.
3537 */
3538 oso = so;
3539 so = sonewconn(so, SS_ISCONNECTED);
3540 if (so == NULL)
3541 goto resetandabort;
3542
3543 switch (so->so_proto->pr_domain->dom_family) {
3544 #ifdef INET
3545 case AF_INET:
3546 inp = sotoinpcb(so);
3547 break;
3548 #endif
3549 #ifdef INET6
3550 case AF_INET6:
3551 in6p = sotoin6pcb(so);
3552 break;
3553 #endif
3554 }
3555 switch (src->sa_family) {
3556 #ifdef INET
3557 case AF_INET:
3558 if (inp) {
3559 inp->inp_laddr = ((struct sockaddr_in *)dst)->sin_addr;
3560 inp->inp_lport = ((struct sockaddr_in *)dst)->sin_port;
3561 inp->inp_options = ip_srcroute();
3562 in_pcbstate(inp, INP_BOUND);
3563 if (inp->inp_options == NULL) {
3564 inp->inp_options = sc->sc_ipopts;
3565 sc->sc_ipopts = NULL;
3566 }
3567 }
3568 #ifdef INET6
3569 else if (in6p) {
3570 /* IPv4 packet to AF_INET6 socket */
3571 bzero(&in6p->in6p_laddr, sizeof(in6p->in6p_laddr));
3572 in6p->in6p_laddr.s6_addr16[5] = htons(0xffff);
3573 bcopy(&((struct sockaddr_in *)dst)->sin_addr,
3574 &in6p->in6p_laddr.s6_addr32[3],
3575 sizeof(((struct sockaddr_in *)dst)->sin_addr));
3576 in6p->in6p_lport = ((struct sockaddr_in *)dst)->sin_port;
3577 in6totcpcb(in6p)->t_family = AF_INET;
3578 if (sotoin6pcb(oso)->in6p_flags & IN6P_IPV6_V6ONLY)
3579 in6p->in6p_flags |= IN6P_IPV6_V6ONLY;
3580 else
3581 in6p->in6p_flags &= ~IN6P_IPV6_V6ONLY;
3582 in6_pcbstate(in6p, IN6P_BOUND);
3583 }
3584 #endif
3585 break;
3586 #endif
3587 #ifdef INET6
3588 case AF_INET6:
3589 if (in6p) {
3590 in6p->in6p_laddr = ((struct sockaddr_in6 *)dst)->sin6_addr;
3591 in6p->in6p_lport = ((struct sockaddr_in6 *)dst)->sin6_port;
3592 in6_pcbstate(in6p, IN6P_BOUND);
3593 }
3594 break;
3595 #endif
3596 }
3597 #ifdef INET6
3598 if (in6p && in6totcpcb(in6p)->t_family == AF_INET6 && sotoinpcb(oso)) {
3599 struct in6pcb *oin6p = sotoin6pcb(oso);
3600 /* inherit socket options from the listening socket */
3601 in6p->in6p_flags |= (oin6p->in6p_flags & IN6P_CONTROLOPTS);
3602 if (in6p->in6p_flags & IN6P_CONTROLOPTS) {
3603 m_freem(in6p->in6p_options);
3604 in6p->in6p_options = 0;
3605 }
3606 ip6_savecontrol(in6p, &in6p->in6p_options,
3607 mtod(m, struct ip6_hdr *), m);
3608 }
3609 #endif
3610
3611 #if defined(IPSEC) || defined(FAST_IPSEC)
3612 /*
3613 * we make a copy of policy, instead of sharing the policy,
3614 * for better behavior in terms of SA lookup and dead SA removal.
3615 */
3616 if (inp) {
3617 /* copy old policy into new socket's */
3618 if (ipsec_copy_pcbpolicy(sotoinpcb(oso)->inp_sp, inp->inp_sp))
3619 printf("tcp_input: could not copy policy\n");
3620 }
3621 #ifdef INET6
3622 else if (in6p) {
3623 /* copy old policy into new socket's */
3624 if (ipsec_copy_pcbpolicy(sotoin6pcb(oso)->in6p_sp,
3625 in6p->in6p_sp))
3626 printf("tcp_input: could not copy policy\n");
3627 }
3628 #endif
3629 #endif
3630
3631 /*
3632 * Give the new socket our cached route reference.
3633 */
3634 if (inp)
3635 inp->inp_route = sc->sc_route4; /* struct assignment */
3636 #ifdef INET6
3637 else
3638 in6p->in6p_route = sc->sc_route6;
3639 #endif
3640 sc->sc_route4.ro_rt = NULL;
3641
3642 am = m_get(M_DONTWAIT, MT_SONAME); /* XXX */
3643 if (am == NULL)
3644 goto resetandabort;
3645 MCLAIM(am, &tcp_mowner);
3646 am->m_len = src->sa_len;
3647 bcopy(src, mtod(am, caddr_t), src->sa_len);
3648 if (inp) {
3649 if (in_pcbconnect(inp, am, NULL)) {
3650 (void) m_free(am);
3651 goto resetandabort;
3652 }
3653 }
3654 #ifdef INET6
3655 else if (in6p) {
3656 if (src->sa_family == AF_INET) {
3657 /* IPv4 packet to AF_INET6 socket */
3658 struct sockaddr_in6 *sin6;
3659 sin6 = mtod(am, struct sockaddr_in6 *);
3660 am->m_len = sizeof(*sin6);
3661 bzero(sin6, sizeof(*sin6));
3662 sin6->sin6_family = AF_INET6;
3663 sin6->sin6_len = sizeof(*sin6);
3664 sin6->sin6_port = ((struct sockaddr_in *)src)->sin_port;
3665 sin6->sin6_addr.s6_addr16[5] = htons(0xffff);
3666 bcopy(&((struct sockaddr_in *)src)->sin_addr,
3667 &sin6->sin6_addr.s6_addr32[3],
3668 sizeof(sin6->sin6_addr.s6_addr32[3]));
3669 }
3670 if (in6_pcbconnect(in6p, am, NULL)) {
3671 (void) m_free(am);
3672 goto resetandabort;
3673 }
3674 }
3675 #endif
3676 else {
3677 (void) m_free(am);
3678 goto resetandabort;
3679 }
3680 (void) m_free(am);
3681
3682 if (inp)
3683 tp = intotcpcb(inp);
3684 #ifdef INET6
3685 else if (in6p)
3686 tp = in6totcpcb(in6p);
3687 #endif
3688 else
3689 tp = NULL;
3690 tp->t_flags = sototcpcb(oso)->t_flags & TF_NODELAY;
3691 if (sc->sc_request_r_scale != 15) {
3692 tp->requested_s_scale = sc->sc_requested_s_scale;
3693 tp->request_r_scale = sc->sc_request_r_scale;
3694 tp->snd_scale = sc->sc_requested_s_scale;
3695 tp->rcv_scale = sc->sc_request_r_scale;
3696 tp->t_flags |= TF_REQ_SCALE|TF_RCVD_SCALE;
3697 }
3698 if (sc->sc_flags & SCF_TIMESTAMP)
3699 tp->t_flags |= TF_REQ_TSTMP|TF_RCVD_TSTMP;
3700 tp->ts_timebase = sc->sc_timebase;
3701
3702 tp->t_template = tcp_template(tp);
3703 if (tp->t_template == 0) {
3704 tp = tcp_drop(tp, ENOBUFS); /* destroys socket */
3705 so = NULL;
3706 m_freem(m);
3707 goto abort;
3708 }
3709
3710 tp->iss = sc->sc_iss;
3711 tp->irs = sc->sc_irs;
3712 tcp_sendseqinit(tp);
3713 tcp_rcvseqinit(tp);
3714 tp->t_state = TCPS_SYN_RECEIVED;
3715 TCP_TIMER_ARM(tp, TCPT_KEEP, TCPTV_KEEP_INIT);
3716 tcpstat.tcps_accepts++;
3717
3718 if ((sc->sc_flags & SCF_SACK_PERMIT) && tcp_do_sack)
3719 tp->t_flags |= TF_WILL_SACK;
3720
3721 if ((sc->sc_flags & SCF_ECN_PERMIT) && tcp_do_ecn)
3722 tp->t_flags |= TF_ECN_PERMIT;
3723
3724 #ifdef TCP_SIGNATURE
3725 if (sc->sc_flags & SCF_SIGNATURE)
3726 tp->t_flags |= TF_SIGNATURE;
3727 #endif
3728
3729 /* Initialize tp->t_ourmss before we deal with the peer's! */
3730 tp->t_ourmss = sc->sc_ourmaxseg;
3731 tcp_mss_from_peer(tp, sc->sc_peermaxseg);
3732
3733 /*
3734 * Initialize the initial congestion window. If we
3735 * had to retransmit the SYN,ACK, we must initialize cwnd
3736 * to 1 segment (i.e. the Loss Window).
3737 */
3738 if (sc->sc_rxtshift)
3739 tp->snd_cwnd = tp->t_peermss;
3740 else {
3741 int ss = tcp_init_win;
3742 #ifdef INET
3743 if (inp != NULL && in_localaddr(inp->inp_faddr))
3744 ss = tcp_init_win_local;
3745 #endif
3746 #ifdef INET6
3747 if (in6p != NULL && in6_localaddr(&in6p->in6p_faddr))
3748 ss = tcp_init_win_local;
3749 #endif
3750 tp->snd_cwnd = TCP_INITIAL_WINDOW(ss, tp->t_peermss);
3751 }
3752
3753 tcp_rmx_rtt(tp);
3754 tp->snd_wl1 = sc->sc_irs;
3755 tp->rcv_up = sc->sc_irs + 1;
3756
3757 /*
3758 * This is what whould have happened in tcp_output() when
3759 * the SYN,ACK was sent.
3760 */
3761 tp->snd_up = tp->snd_una;
3762 tp->snd_max = tp->snd_nxt = tp->iss+1;
3763 TCP_TIMER_ARM(tp, TCPT_REXMT, tp->t_rxtcur);
3764 if (sc->sc_win > 0 && SEQ_GT(tp->rcv_nxt + sc->sc_win, tp->rcv_adv))
3765 tp->rcv_adv = tp->rcv_nxt + sc->sc_win;
3766 tp->last_ack_sent = tp->rcv_nxt;
3767 tp->t_partialacks = -1;
3768 tp->t_dupacks = 0;
3769
3770 tcpstat.tcps_sc_completed++;
3771 s = splsoftnet();
3772 SYN_CACHE_PUT(sc);
3773 splx(s);
3774 return (so);
3775
3776 resetandabort:
3777 (void)tcp_respond(NULL, m, m, th, (tcp_seq)0, th->th_ack, TH_RST);
3778 abort:
3779 if (so != NULL)
3780 (void) soabort(so);
3781 s = splsoftnet();
3782 SYN_CACHE_PUT(sc);
3783 splx(s);
3784 tcpstat.tcps_sc_aborted++;
3785 return ((struct socket *)(-1));
3786 }
3787
3788 /*
3789 * This function is called when we get a RST for a
3790 * non-existent connection, so that we can see if the
3791 * connection is in the syn cache. If it is, zap it.
3792 */
3793
3794 void
3795 syn_cache_reset(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th)
3796 {
3797 struct syn_cache *sc;
3798 struct syn_cache_head *scp;
3799 int s = splsoftnet();
3800
3801 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3802 splx(s);
3803 return;
3804 }
3805 if (SEQ_LT(th->th_seq, sc->sc_irs) ||
3806 SEQ_GT(th->th_seq, sc->sc_irs+1)) {
3807 splx(s);
3808 return;
3809 }
3810 SYN_CACHE_RM(sc);
3811 tcpstat.tcps_sc_reset++;
3812 SYN_CACHE_PUT(sc); /* calls pool_put but see spl above */
3813 splx(s);
3814 }
3815
3816 void
3817 syn_cache_unreach(const struct sockaddr *src, const struct sockaddr *dst,
3818 struct tcphdr *th)
3819 {
3820 struct syn_cache *sc;
3821 struct syn_cache_head *scp;
3822 int s;
3823
3824 s = splsoftnet();
3825 if ((sc = syn_cache_lookup(src, dst, &scp)) == NULL) {
3826 splx(s);
3827 return;
3828 }
3829 /* If the sequence number != sc_iss, then it's a bogus ICMP msg */
3830 if (ntohl (th->th_seq) != sc->sc_iss) {
3831 splx(s);
3832 return;
3833 }
3834
3835 /*
3836 * If we've retransmitted 3 times and this is our second error,
3837 * we remove the entry. Otherwise, we allow it to continue on.
3838 * This prevents us from incorrectly nuking an entry during a
3839 * spurious network outage.
3840 *
3841 * See tcp_notify().
3842 */
3843 if ((sc->sc_flags & SCF_UNREACH) == 0 || sc->sc_rxtshift < 3) {
3844 sc->sc_flags |= SCF_UNREACH;
3845 splx(s);
3846 return;
3847 }
3848
3849 SYN_CACHE_RM(sc);
3850 tcpstat.tcps_sc_unreach++;
3851 SYN_CACHE_PUT(sc); /* calls pool_put but see spl above */
3852 splx(s);
3853 }
3854
3855 /*
3856 * Given a LISTEN socket and an inbound SYN request, add
3857 * this to the syn cache, and send back a segment:
3858 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
3859 * to the source.
3860 *
3861 * IMPORTANT NOTE: We do _NOT_ ACK data that might accompany the SYN.
3862 * Doing so would require that we hold onto the data and deliver it
3863 * to the application. However, if we are the target of a SYN-flood
3864 * DoS attack, an attacker could send data which would eventually
3865 * consume all available buffer space if it were ACKed. By not ACKing
3866 * the data, we avoid this DoS scenario.
3867 */
3868
3869 int
3870 syn_cache_add(struct sockaddr *src, struct sockaddr *dst, struct tcphdr *th,
3871 unsigned int hlen, struct socket *so, struct mbuf *m, u_char *optp,
3872 int optlen, struct tcp_opt_info *oi)
3873 {
3874 struct tcpcb tb, *tp;
3875 long win;
3876 struct syn_cache *sc;
3877 struct syn_cache_head *scp;
3878 struct mbuf *ipopts;
3879 struct tcp_opt_info opti;
3880 int s;
3881
3882 tp = sototcpcb(so);
3883
3884 bzero(&opti, sizeof(opti));
3885
3886 /*
3887 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
3888 *
3889 * Note this check is performed in tcp_input() very early on.
3890 */
3891
3892 /*
3893 * Initialize some local state.
3894 */
3895 win = sbspace(&so->so_rcv);
3896 if (win > TCP_MAXWIN)
3897 win = TCP_MAXWIN;
3898
3899 switch (src->sa_family) {
3900 #ifdef INET
3901 case AF_INET:
3902 /*
3903 * Remember the IP options, if any.
3904 */
3905 ipopts = ip_srcroute();
3906 break;
3907 #endif
3908 default:
3909 ipopts = NULL;
3910 }
3911
3912 #ifdef TCP_SIGNATURE
3913 if (optp || (tp->t_flags & TF_SIGNATURE))
3914 #else
3915 if (optp)
3916 #endif
3917 {
3918 tb.t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
3919 #ifdef TCP_SIGNATURE
3920 tb.t_flags |= (tp->t_flags & TF_SIGNATURE);
3921 #endif
3922 tb.t_state = TCPS_LISTEN;
3923 if (tcp_dooptions(&tb, optp, optlen, th, m, m->m_pkthdr.len -
3924 sizeof(struct tcphdr) - optlen - hlen, oi) < 0)
3925 return (0);
3926 } else
3927 tb.t_flags = 0;
3928
3929 /*
3930 * See if we already have an entry for this connection.
3931 * If we do, resend the SYN,ACK. We do not count this
3932 * as a retransmission (XXX though maybe we should).
3933 */
3934 if ((sc = syn_cache_lookup(src, dst, &scp)) != NULL) {
3935 tcpstat.tcps_sc_dupesyn++;
3936 if (ipopts) {
3937 /*
3938 * If we were remembering a previous source route,
3939 * forget it and use the new one we've been given.
3940 */
3941 if (sc->sc_ipopts)
3942 (void) m_free(sc->sc_ipopts);
3943 sc->sc_ipopts = ipopts;
3944 }
3945 sc->sc_timestamp = tb.ts_recent;
3946 if (syn_cache_respond(sc, m) == 0) {
3947 tcpstat.tcps_sndacks++;
3948 tcpstat.tcps_sndtotal++;
3949 }
3950 return (1);
3951 }
3952
3953 s = splsoftnet();
3954 sc = pool_get(&syn_cache_pool, PR_NOWAIT);
3955 splx(s);
3956 if (sc == NULL) {
3957 if (ipopts)
3958 (void) m_free(ipopts);
3959 return (0);
3960 }
3961
3962 /*
3963 * Fill in the cache, and put the necessary IP and TCP
3964 * options into the reply.
3965 */
3966 bzero(sc, sizeof(struct syn_cache));
3967 callout_init(&sc->sc_timer);
3968 bcopy(src, &sc->sc_src, src->sa_len);
3969 bcopy(dst, &sc->sc_dst, dst->sa_len);
3970 sc->sc_flags = 0;
3971 sc->sc_ipopts = ipopts;
3972 sc->sc_irs = th->th_seq;
3973 switch (src->sa_family) {
3974 #ifdef INET
3975 case AF_INET:
3976 {
3977 struct sockaddr_in *srcin = (void *) src;
3978 struct sockaddr_in *dstin = (void *) dst;
3979
3980 sc->sc_iss = tcp_new_iss1(&dstin->sin_addr,
3981 &srcin->sin_addr, dstin->sin_port,
3982 srcin->sin_port, sizeof(dstin->sin_addr), 0);
3983 break;
3984 }
3985 #endif /* INET */
3986 #ifdef INET6
3987 case AF_INET6:
3988 {
3989 struct sockaddr_in6 *srcin6 = (void *) src;
3990 struct sockaddr_in6 *dstin6 = (void *) dst;
3991
3992 sc->sc_iss = tcp_new_iss1(&dstin6->sin6_addr,
3993 &srcin6->sin6_addr, dstin6->sin6_port,
3994 srcin6->sin6_port, sizeof(dstin6->sin6_addr), 0);
3995 break;
3996 }
3997 #endif /* INET6 */
3998 }
3999 sc->sc_peermaxseg = oi->maxseg;
4000 sc->sc_ourmaxseg = tcp_mss_to_advertise(m->m_flags & M_PKTHDR ?
4001 m->m_pkthdr.rcvif : NULL,
4002 sc->sc_src.sa.sa_family);
4003 sc->sc_win = win;
4004 sc->sc_timebase = tcp_now; /* see tcp_newtcpcb() */
4005 sc->sc_timestamp = tb.ts_recent;
4006 if ((tb.t_flags & (TF_REQ_TSTMP|TF_RCVD_TSTMP)) ==
4007 (TF_REQ_TSTMP|TF_RCVD_TSTMP))
4008 sc->sc_flags |= SCF_TIMESTAMP;
4009 if ((tb.t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
4010 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
4011 sc->sc_requested_s_scale = tb.requested_s_scale;
4012 sc->sc_request_r_scale = 0;
4013 while (sc->sc_request_r_scale < TCP_MAX_WINSHIFT &&
4014 TCP_MAXWIN << sc->sc_request_r_scale <
4015 so->so_rcv.sb_hiwat)
4016 sc->sc_request_r_scale++;
4017 } else {
4018 sc->sc_requested_s_scale = 15;
4019 sc->sc_request_r_scale = 15;
4020 }
4021 if ((tb.t_flags & TF_SACK_PERMIT) && tcp_do_sack)
4022 sc->sc_flags |= SCF_SACK_PERMIT;
4023
4024 /*
4025 * ECN setup packet recieved.
4026 */
4027 if ((th->th_flags & (TH_ECE|TH_CWR)) && tcp_do_ecn)
4028 sc->sc_flags |= SCF_ECN_PERMIT;
4029
4030 #ifdef TCP_SIGNATURE
4031 if (tb.t_flags & TF_SIGNATURE)
4032 sc->sc_flags |= SCF_SIGNATURE;
4033 #endif
4034 sc->sc_tp = tp;
4035 if (syn_cache_respond(sc, m) == 0) {
4036 syn_cache_insert(sc, tp);
4037 tcpstat.tcps_sndacks++;
4038 tcpstat.tcps_sndtotal++;
4039 } else {
4040 s = splsoftnet();
4041 SYN_CACHE_PUT(sc);
4042 splx(s);
4043 tcpstat.tcps_sc_dropped++;
4044 }
4045 return (1);
4046 }
4047
4048 int
4049 syn_cache_respond(struct syn_cache *sc, struct mbuf *m)
4050 {
4051 struct route *ro;
4052 u_int8_t *optp;
4053 int optlen, error;
4054 u_int16_t tlen;
4055 struct ip *ip = NULL;
4056 #ifdef INET6
4057 struct ip6_hdr *ip6 = NULL;
4058 #endif
4059 struct tcpcb *tp = NULL;
4060 struct tcphdr *th;
4061 u_int hlen;
4062 struct socket *so;
4063
4064 switch (sc->sc_src.sa.sa_family) {
4065 case AF_INET:
4066 hlen = sizeof(struct ip);
4067 ro = &sc->sc_route4;
4068 break;
4069 #ifdef INET6
4070 case AF_INET6:
4071 hlen = sizeof(struct ip6_hdr);
4072 ro = (struct route *)&sc->sc_route6;
4073 break;
4074 #endif
4075 default:
4076 if (m)
4077 m_freem(m);
4078 return (EAFNOSUPPORT);
4079 }
4080
4081 /* Compute the size of the TCP options. */
4082 optlen = 4 + (sc->sc_request_r_scale != 15 ? 4 : 0) +
4083 ((sc->sc_flags & SCF_SACK_PERMIT) ? (TCPOLEN_SACK_PERMITTED + 2) : 0) +
4084 #ifdef TCP_SIGNATURE
4085 ((sc->sc_flags & SCF_SIGNATURE) ? (TCPOLEN_SIGNATURE + 2) : 0) +
4086 #endif
4087 ((sc->sc_flags & SCF_TIMESTAMP) ? TCPOLEN_TSTAMP_APPA : 0);
4088
4089 tlen = hlen + sizeof(struct tcphdr) + optlen;
4090
4091 /*
4092 * Create the IP+TCP header from scratch.
4093 */
4094 if (m)
4095 m_freem(m);
4096 #ifdef DIAGNOSTIC
4097 if (max_linkhdr + tlen > MCLBYTES)
4098 return (ENOBUFS);
4099 #endif
4100 MGETHDR(m, M_DONTWAIT, MT_DATA);
4101 if (m && tlen > MHLEN) {
4102 MCLGET(m, M_DONTWAIT);
4103 if ((m->m_flags & M_EXT) == 0) {
4104 m_freem(m);
4105 m = NULL;
4106 }
4107 }
4108 if (m == NULL)
4109 return (ENOBUFS);
4110 MCLAIM(m, &tcp_tx_mowner);
4111
4112 /* Fixup the mbuf. */
4113 m->m_data += max_linkhdr;
4114 m->m_len = m->m_pkthdr.len = tlen;
4115 if (sc->sc_tp) {
4116 tp = sc->sc_tp;
4117 if (tp->t_inpcb)
4118 so = tp->t_inpcb->inp_socket;
4119 #ifdef INET6
4120 else if (tp->t_in6pcb)
4121 so = tp->t_in6pcb->in6p_socket;
4122 #endif
4123 else
4124 so = NULL;
4125 } else
4126 so = NULL;
4127 m->m_pkthdr.rcvif = NULL;
4128 memset(mtod(m, u_char *), 0, tlen);
4129
4130 switch (sc->sc_src.sa.sa_family) {
4131 case AF_INET:
4132 ip = mtod(m, struct ip *);
4133 ip->ip_v = 4;
4134 ip->ip_dst = sc->sc_src.sin.sin_addr;
4135 ip->ip_src = sc->sc_dst.sin.sin_addr;
4136 ip->ip_p = IPPROTO_TCP;
4137 th = (struct tcphdr *)(ip + 1);
4138 th->th_dport = sc->sc_src.sin.sin_port;
4139 th->th_sport = sc->sc_dst.sin.sin_port;
4140 break;
4141 #ifdef INET6
4142 case AF_INET6:
4143 ip6 = mtod(m, struct ip6_hdr *);
4144 ip6->ip6_vfc = IPV6_VERSION;
4145 ip6->ip6_dst = sc->sc_src.sin6.sin6_addr;
4146 ip6->ip6_src = sc->sc_dst.sin6.sin6_addr;
4147 ip6->ip6_nxt = IPPROTO_TCP;
4148 /* ip6_plen will be updated in ip6_output() */
4149 th = (struct tcphdr *)(ip6 + 1);
4150 th->th_dport = sc->sc_src.sin6.sin6_port;
4151 th->th_sport = sc->sc_dst.sin6.sin6_port;
4152 break;
4153 #endif
4154 default:
4155 th = NULL;
4156 }
4157
4158 th->th_seq = htonl(sc->sc_iss);
4159 th->th_ack = htonl(sc->sc_irs + 1);
4160 th->th_off = (sizeof(struct tcphdr) + optlen) >> 2;
4161 th->th_flags = TH_SYN|TH_ACK;
4162 th->th_win = htons(sc->sc_win);
4163 /* th_sum already 0 */
4164 /* th_urp already 0 */
4165
4166 /* Tack on the TCP options. */
4167 optp = (u_int8_t *)(th + 1);
4168 *optp++ = TCPOPT_MAXSEG;
4169 *optp++ = 4;
4170 *optp++ = (sc->sc_ourmaxseg >> 8) & 0xff;
4171 *optp++ = sc->sc_ourmaxseg & 0xff;
4172
4173 if (sc->sc_request_r_scale != 15) {
4174 *((u_int32_t *)optp) = htonl(TCPOPT_NOP << 24 |
4175 TCPOPT_WINDOW << 16 | TCPOLEN_WINDOW << 8 |
4176 sc->sc_request_r_scale);
4177 optp += 4;
4178 }
4179
4180 if (sc->sc_flags & SCF_TIMESTAMP) {
4181 u_int32_t *lp = (u_int32_t *)(optp);
4182 /* Form timestamp option as shown in appendix A of RFC 1323. */
4183 *lp++ = htonl(TCPOPT_TSTAMP_HDR);
4184 *lp++ = htonl(SYN_CACHE_TIMESTAMP(sc));
4185 *lp = htonl(sc->sc_timestamp);
4186 optp += TCPOLEN_TSTAMP_APPA;
4187 }
4188
4189 if (sc->sc_flags & SCF_SACK_PERMIT) {
4190 u_int8_t *p = optp;
4191
4192 /* Let the peer know that we will SACK. */
4193 p[0] = TCPOPT_SACK_PERMITTED;
4194 p[1] = 2;
4195 p[2] = TCPOPT_NOP;
4196 p[3] = TCPOPT_NOP;
4197 optp += 4;
4198 }
4199
4200 /*
4201 * Send ECN SYN-ACK setup packet.
4202 * Routes can be asymetric, so, even if we receive a packet
4203 * with ECE and CWR set, we must not assume no one will block
4204 * the ECE packet we are about to send.
4205 */
4206 if ((sc->sc_flags & SCF_ECN_PERMIT) && tp &&
4207 SEQ_GEQ(tp->snd_nxt, tp->snd_max)) {
4208 th->th_flags |= TH_ECE;
4209 tcpstat.tcps_ecn_shs++;
4210
4211 /*
4212 * draft-ietf-tcpm-ecnsyn-00.txt
4213 *
4214 * "[...] a TCP node MAY respond to an ECN-setup
4215 * SYN packet by setting ECT in the responding
4216 * ECN-setup SYN/ACK packet, indicating to routers
4217 * that the SYN/ACK packet is ECN-Capable.
4218 * This allows a congested router along the path
4219 * to mark the packet instead of dropping the
4220 * packet as an indication of congestion."
4221 *
4222 * "[...] There can be a great benefit in setting
4223 * an ECN-capable codepoint in SYN/ACK packets [...]
4224 * Congestion is most likely to occur in
4225 * the server-to-client direction. As a result,
4226 * setting an ECN-capable codepoint in SYN/ACK
4227 * packets can reduce the occurence of three-second
4228 * retransmit timeouts resulting from the drop
4229 * of SYN/ACK packets."
4230 *
4231 * Page 4 and 6, January 2006.
4232 */
4233
4234 switch (sc->sc_src.sa.sa_family) {
4235 #ifdef INET
4236 case AF_INET:
4237 ip->ip_tos |= IPTOS_ECN_ECT0;
4238 break;
4239 #endif
4240 #ifdef INET6
4241 case AF_INET6:
4242 ip6->ip6_flow |= htonl(IPTOS_ECN_ECT0 << 20);
4243 break;
4244 #endif
4245 }
4246 tcpstat.tcps_ecn_ect++;
4247 }
4248
4249 #ifdef TCP_SIGNATURE
4250 if (sc->sc_flags & SCF_SIGNATURE) {
4251 struct secasvar *sav;
4252 u_int8_t *sigp;
4253
4254 sav = tcp_signature_getsav(m, th);
4255
4256 if (sav == NULL) {
4257 if (m)
4258 m_freem(m);
4259 return (EPERM);
4260 }
4261
4262 *optp++ = TCPOPT_SIGNATURE;
4263 *optp++ = TCPOLEN_SIGNATURE;
4264 sigp = optp;
4265 bzero(optp, TCP_SIGLEN);
4266 optp += TCP_SIGLEN;
4267 *optp++ = TCPOPT_NOP;
4268 *optp++ = TCPOPT_EOL;
4269
4270 (void)tcp_signature(m, th, hlen, sav, sigp);
4271
4272 key_sa_recordxfer(sav, m);
4273 #ifdef FAST_IPSEC
4274 KEY_FREESAV(&sav);
4275 #else
4276 key_freesav(sav);
4277 #endif
4278 }
4279 #endif
4280
4281 /* Compute the packet's checksum. */
4282 switch (sc->sc_src.sa.sa_family) {
4283 case AF_INET:
4284 ip->ip_len = htons(tlen - hlen);
4285 th->th_sum = 0;
4286 th->th_sum = in4_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4287 break;
4288 #ifdef INET6
4289 case AF_INET6:
4290 ip6->ip6_plen = htons(tlen - hlen);
4291 th->th_sum = 0;
4292 th->th_sum = in6_cksum(m, IPPROTO_TCP, hlen, tlen - hlen);
4293 break;
4294 #endif
4295 }
4296
4297 /*
4298 * Fill in some straggling IP bits. Note the stack expects
4299 * ip_len to be in host order, for convenience.
4300 */
4301 switch (sc->sc_src.sa.sa_family) {
4302 #ifdef INET
4303 case AF_INET:
4304 ip->ip_len = htons(tlen);
4305 ip->ip_ttl = ip_defttl;
4306 /* XXX tos? */
4307 break;
4308 #endif
4309 #ifdef INET6
4310 case AF_INET6:
4311 ip6->ip6_vfc &= ~IPV6_VERSION_MASK;
4312 ip6->ip6_vfc |= IPV6_VERSION;
4313 ip6->ip6_plen = htons(tlen - hlen);
4314 /* ip6_hlim will be initialized afterwards */
4315 /* XXX flowlabel? */
4316 break;
4317 #endif
4318 }
4319
4320 /* XXX use IPsec policy on listening socket, on SYN ACK */
4321 tp = sc->sc_tp;
4322
4323 switch (sc->sc_src.sa.sa_family) {
4324 #ifdef INET
4325 case AF_INET:
4326 error = ip_output(m, sc->sc_ipopts, ro,
4327 (ip_mtudisc ? IP_MTUDISC : 0),
4328 (struct ip_moptions *)NULL, so);
4329 break;
4330 #endif
4331 #ifdef INET6
4332 case AF_INET6:
4333 ip6->ip6_hlim = in6_selecthlim(NULL,
4334 ro->ro_rt ? ro->ro_rt->rt_ifp : NULL);
4335
4336 error = ip6_output(m, NULL /*XXX*/, (struct route_in6 *)ro, 0,
4337 (struct ip6_moptions *)0, so, NULL);
4338 break;
4339 #endif
4340 default:
4341 error = EAFNOSUPPORT;
4342 break;
4343 }
4344 return (error);
4345 }
4346