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