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