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