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