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