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