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