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