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