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