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