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