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