]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/tcp_input.c
008e01fe4712852161a598a6d3fb63660ec98fae
[apple/xnu.git] / bsd / netinet / tcp_input.c
1 /*
2 * Copyright (c) 2000 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * The contents of this file constitute Original Code as defined in and
7 * are subject to the Apple Public Source License Version 1.1 (the
8 * "License"). You may not use this file except in compliance with the
9 * License. Please obtain a copy of the License at
10 * http://www.apple.com/publicsource and read it before using this file.
11 *
12 * This Original Code and all software distributed under the License are
13 * distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER
14 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
15 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
17 * License for the specific language governing rights and limitations
18 * under the License.
19 *
20 * @APPLE_LICENSE_HEADER_END@
21 */
22 /*
23 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
24 * The Regents of the University of California. All rights reserved.
25 *
26 * Redistribution and use in source and binary forms, with or without
27 * modification, are permitted provided that the following conditions
28 * are met:
29 * 1. Redistributions of source code must retain the above copyright
30 * notice, this list of conditions and the following disclaimer.
31 * 2. Redistributions in binary form must reproduce the above copyright
32 * notice, this list of conditions and the following disclaimer in the
33 * documentation and/or other materials provided with the distribution.
34 * 3. All advertising materials mentioning features or use of this software
35 * must display the following acknowledgement:
36 * This product includes software developed by the University of
37 * California, Berkeley and its contributors.
38 * 4. Neither the name of the University nor the names of its contributors
39 * may be used to endorse or promote products derived from this software
40 * without specific prior written permission.
41 *
42 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
43 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
44 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
45 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
46 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
47 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
48 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
49 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
50 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
51 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
52 * SUCH DAMAGE.
53 *
54 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
55 */
56
57 #if ISFB31
58 #include "opt_ipfw.h" /* for ipfw_fwd */
59 #include "opt_tcpdebug.h"
60 #endif
61
62 #include <sys/param.h>
63 #include <sys/systm.h>
64 #include <sys/kernel.h>
65 #include <sys/sysctl.h>
66 #include <sys/malloc.h>
67 #include <sys/mbuf.h>
68 #include <sys/proc.h> /* for proc0 declaration */
69 #include <sys/protosw.h>
70 #include <sys/socket.h>
71 #include <sys/socketvar.h>
72 #include <sys/syslog.h>
73
74 #include <kern/cpu_number.h> /* before tcp_seq.h, for tcp_random18() */
75
76 #include <net/if.h>
77 #include <net/route.h>
78
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/ip.h>
82 #include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
83 #include <netinet/in_var.h>
84 #include <netinet/ip_var.h>
85 #include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
86 #include <netinet/in_pcb.h>
87 #if INET6
88 #include <netinet/ip6.h>
89 #include <netinet/icmp6.h>
90 #include <netinet6/nd6.h>
91 #include <netinet6/ip6_var.h>
92 #include <netinet6/in6_pcb.h>
93 #endif
94 #include <netinet/tcp.h>
95 #include <netinet/tcp_fsm.h>
96 #include <netinet/tcp_seq.h>
97 #include <netinet/tcp_timer.h>
98 #include <netinet/tcp_var.h>
99 #include <netinet/tcpip.h>
100 #if TCPDEBUG
101 #include <netinet/tcp_debug.h>
102 #if INET6
103 union {
104 struct ip _tcp_si4;
105 struct ip6_hdr _tcp_si6;
106 } tcp_saveip;
107 #else
108 struct ip tcp_saveip;
109 #endif /* INET6 */
110 struct tcphdr tcp_savetcp;
111 #endif /* TCPDEBUG */
112
113 #if IPSEC
114 #include <netinet6/ipsec.h>
115 #include <netkey/key.h>
116 #endif /*IPSEC*/
117
118 #include <sys/kdebug.h>
119
120 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETTCP, 0)
121 #define DBG_LAYER_END NETDBG_CODE(DBG_NETTCP, 2)
122 #define DBG_FNC_TCP_INPUT NETDBG_CODE(DBG_NETTCP, (3 << 8))
123 #define DBG_FNC_TCP_NEWCONN NETDBG_CODE(DBG_NETTCP, (7 << 8))
124
125 static int tcprexmtthresh = 3;
126 tcp_seq tcp_iss;
127 tcp_cc tcp_ccgen;
128 extern int apple_hwcksum_rx;
129
130 struct tcpstat tcpstat;
131 SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats,
132 CTLFLAG_RD, &tcpstat , tcpstat, "");
133
134 int log_in_vain = 0;
135 SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
136 &log_in_vain, 0, "");
137
138 int tcp_delack_enabled = 1;
139 SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
140 &tcp_delack_enabled, 0, "");
141
142 u_long tcp_now;
143 struct inpcbhead tcb;
144 #define tcb6 tcb /* for KAME src sync over BSD*'s */
145 struct inpcbinfo tcbinfo;
146
147 static void tcp_dooptions __P((struct tcpcb *,
148 u_char *, int, struct tcphdr *, struct tcpopt *));
149 static void tcp_pulloutofband __P((struct socket *,
150 struct tcphdr *, struct mbuf *));
151 static void tcp_xmit_timer __P((struct tcpcb *, int));
152
153 /*
154 * Neighbor Discovery, Neighbor Unreachability Detection
155 * Upper layer hint.
156 */
157 #define ND6_HINT(tp) { \
158 if ((tp) && (tp)->t_inpcb && (tp)->t_inpcb->in6p_route.ro_rt) \
159 nd6_nud_hint((tp)->t_inpcb->in6p_route.ro_rt, NULL); \
160 }
161
162
163 extern u_long current_active_connections;
164 extern u_long last_active_conn_count;
165
166 extern u_long *delack_bitmask;
167
168
169
170
171 /*
172 * Insert segment ti into reassembly queue of tcp with
173 * control block tp. Return TH_FIN if reassembly now includes
174 * a segment with FIN. The macro form does the common case inline
175 * (segment is the next to be received on an established connection,
176 * and the queue is empty), avoiding linkage into and removal
177 * from the queue and repetition of various conversions.
178 * Set DELACK for segments received in order, but ack immediately
179 * when segments are out of order (so fast retransmit can work).
180 */
181 #if INET6
182 #define _ONLY_IF_INET6_(x) x
183 #else
184 #define _ONLY_IF_INET6_(x)
185 #endif
186 #define TCP_REASS(tp, th, tilen, m, so, flags, isipv6, needwakeup) { \
187 if ((th)->th_seq == (tp)->rcv_nxt && \
188 (tp)->segq.lh_first == NULL && \
189 (tp)->t_state == TCPS_ESTABLISHED) { \
190 if (tcp_delack_enabled) {\
191 if (last_active_conn_count > DELACK_BITMASK_THRESH) \
192 TCP_DELACK_BITSET(tp->t_inpcb->hash_element); \
193 tp->t_flags |= TF_DELACK; \
194 } \
195 else \
196 tp->t_flags |= TF_ACKNOW; \
197 (tp)->rcv_nxt += (tilen); \
198 flags = (th)->th_flags & TH_FIN; \
199 tcpstat.tcps_rcvpack++;\
200 tcpstat.tcps_rcvbyte += (tilen);\
201 _ONLY_IF_INET6_(ND6_HINT(tp);) \
202 sbappend(&(so)->so_rcv, (m)); \
203 needwakeup++; \
204 } else { \
205 (flags) = tcp_reass((tp), (th), (tilen), (m), (isipv6)); \
206 tp->t_flags |= TF_ACKNOW; \
207 } \
208 }
209
210 /*
211 * Note:
212 * in the ip header part of the ipqe_tcp structure only the length is used.
213 */
214 int
215 tcp_reass(tp, th, tilen, m, isipv6)
216 register struct tcpcb *tp;
217 register struct tcphdr *th;
218 u_int16_t tilen;
219 struct mbuf *m;
220 #if INET6
221 int isipv6;
222 #endif
223 {
224 register struct ipqent *p, *q, *nq, *tiqe;
225 struct socket *so = tp->t_inpcb->inp_socket;
226 int flags;
227
228 /*
229 * Call with th==0 after become established to
230 * force pre-ESTABLISHED data up to user socket.
231 */
232 if (th == 0)
233 goto present;
234
235 #if 0 /* Not using GETTCP(m) macro */
236 m->m_pkthdr.header = ti;
237 #endif
238
239 /*
240 * Allocate a new queue entry, before we throw away any data.
241 * If we can't, just drop the packet. XXX
242 */
243 MALLOC(tiqe, struct ipqent *, sizeof (struct ipqent), M_SONAME, M_NOWAIT);
244 if (tiqe == NULL) {
245 tcpstat.tcps_rcvmemdrop++;
246 m_freem(m);
247 return (0);
248 }
249
250 /*
251 * Find a segment which begins after this one does.
252 */
253 for (p = NULL, q = tp->segq.lh_first; q != NULL;
254 p = q, q = q->ipqe_q.le_next)
255 if (SEQ_GT(q->ipqe_tcp->ti_seq, th->th_seq))
256 break;
257
258 /*
259 * If there is a preceding segment, it may provide some of
260 * our data already. If so, drop the data from the incoming
261 * segment. If it provides all of our data, drop us.
262 */
263 if (p != NULL) {
264 register struct tcpiphdr *phdr = p->ipqe_tcp;
265 register int i;
266
267 /* conversion to int (in i) handles seq wraparound */
268 i = phdr->ti_seq + phdr->ti_len - th->th_seq;
269 if (i > 0) {
270 if (i >= tilen) {
271 tcpstat.tcps_rcvduppack++;
272 tcpstat.tcps_rcvdupbyte += tilen;
273 m_freem(m);
274 FREE(tiqe, M_SONAME);
275
276 #if 1 /* XXX: NetBSD just return 0 here */
277 /*
278 * Try to present any queued data
279 * at the left window edge to the user.
280 * This is needed after the 3-WHS
281 * completes.
282 */
283 goto present; /* ??? */
284 #endif
285 }
286 m_adj(m, i);
287 tilen -= i;
288 th->th_seq += i;
289 }
290 }
291 tcpstat.tcps_rcvoopack++;
292 tcpstat.tcps_rcvoobyte += tilen;
293
294 /*
295 * While we overlap succeeding segments trim them or,
296 * if they are completely covered, dequeue them.
297 */
298 while (q) {
299 register struct tcpiphdr *qhdr = q->ipqe_tcp;
300 register int i = (th->th_seq + tilen) - qhdr->ti_seq;
301
302 if (i <= 0)
303 break;
304 if (i < qhdr->ti_len) {
305 qhdr->ti_seq += i;
306 qhdr->ti_len -= i;
307 m_adj(q->ipqe_m, i);
308 break;
309 }
310 nq = q->ipqe_q.le_next;
311 m_freem(q->ipqe_m);
312 LIST_REMOVE(q, ipqe_q);
313 FREE(q, M_SONAME);
314 q = nq;
315 }
316
317 /* Insert the new fragment queue entry into place. */
318 tiqe->ipqe_m = m;
319 /*
320 * There is a IP or IPv6 header in the mbuf before th
321 * so there is space for an ip header (for the length field)
322 */
323 #define thtoti(x) \
324 ((struct tcpiphdr *)(((char *)(x)) - (sizeof (struct ip))))
325
326 tiqe->ipqe_tcp = thtoti(th);
327 tiqe->ipqe_tcp->ti_len = tilen;
328 if (p == NULL) {
329 LIST_INSERT_HEAD(&tp->segq, tiqe, ipqe_q);
330 } else {
331 LIST_INSERT_AFTER(p, tiqe, ipqe_q);
332 }
333
334 present:
335 /*
336 * Present data to user, advancing rcv_nxt through
337 * completed sequence space.
338 */
339 if (!TCPS_HAVEESTABLISHED(tp->t_state))
340 return (0);
341 q = tp->segq.lh_first;
342 if (!q || q->ipqe_tcp->ti_seq != tp->rcv_nxt)
343 return (0);
344 #if 0
345 /*
346 * XXX from INRIA for NetBSD, but should not happen because
347 * TCPS_HAVEESTABLISHED(tp->t_state) should be true here.
348 */
349 if (tp->t_state == TCPS_SYN_RECEIVED && q->ipqe_tcp->ti_len)
350 return (0);
351 #endif
352 do {
353 tp->rcv_nxt += q->ipqe_tcp->ti_len;
354 flags = q->ipqe_tcp->ti_flags & TH_FIN;
355 nq = q->ipqe_q.le_next;
356 LIST_REMOVE(q, ipqe_q);
357 if (so->so_state & SS_CANTRCVMORE)
358 m_freem(q->ipqe_m);
359 else
360 sbappend(&so->so_rcv, q->ipqe_m);
361 FREE(q, M_SONAME);
362 q = nq;
363 } while (q && q->ipqe_tcp->ti_seq == tp->rcv_nxt);
364 #if INET6
365 if (isipv6)
366 ND6_HINT(tp);
367 #endif
368
369 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
370 (((thtoti(th)->ti_src.s_addr & 0xffff) << 16) | (thtoti(th)->ti_dst.s_addr & 0xffff)),
371 th->th_seq, th->th_ack, th->th_win);
372
373 sorwakeup(so);
374 return (flags);
375 }
376
377 /*
378 * TCP input routine, follows pages 65-76 of the
379 * protocol specification dated September, 1981 very closely.
380 */
381 #if INET6
382 int
383 tcp6_input(mp, offp, proto)
384 struct mbuf **mp;
385 int *offp, proto;
386 {
387 tcp_input(*mp, *offp);
388 return IPPROTO_DONE;
389 }
390 #endif
391
392 void
393 tcp_input(m, off)
394 struct mbuf *m;
395 int off;
396 {
397 register struct tcphdr *th;
398 register struct ip *ip = NULL;
399 register struct ipovly *ipov;
400 register struct inpcb *inp;
401 u_char *optp = NULL;
402 int optlen = 0;
403 int len, toff;
404 int hdroptlen;
405 u_int16_t tilen;
406 register struct tcpcb *tp = 0;
407 register int thflags;
408 struct socket *so = 0;
409 int todrop, acked, ourfinisacked, needoutput = 0;
410 struct in_addr laddr;
411 #if 0
412 struct in6_addr laddr6;
413 #endif
414 int dropsocket = 0;
415 int iss = 0;
416 u_long tiwin;
417 struct tcpopt to; /* options in this segment */
418 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
419 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
420 int need_sowwakeup = 0;
421 int need_sorwakeup = 0;
422 #if TCPDEBUG
423 short ostate = 0;
424 #endif
425 #if INET6
426 struct ip6_hdr *ip6 = NULL;
427 int lgminh;
428 #else /* INET6 */
429 #define lgminh (sizeof (struct tcpiphdr))
430 #endif /* INET6 */
431 int isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
432
433 struct proc *proc0=current_proc();
434
435 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_START,0,0,0,0,0);
436
437 bzero((char *)&to, sizeof(to));
438
439 tcpstat.tcps_rcvtotal++;
440 /*
441 * Get IP and TCP header together in first mbuf.
442 * Note: IP leaves IP header in first mbuf.
443 */
444 th = mtod(m, struct tcpiphdr *);
445
446 KERNEL_DEBUG(DBG_LAYER_BEG, ((th->th_dport << 16) | th->th_sport),
447 (((thtoti(th)->ti_src.s_addr & 0xffff) << 16) | (thtoti(th)->ti_dst.s_addr & 0xffff)),
448 th->th_seq, th->th_ack, th->th_win);
449
450 #if INET6
451 if (isipv6) {
452 ip6 = mtod(m, struct ip6_hdr *);
453 lgminh = sizeof(struct tcpip6hdr);
454 } else {
455 lgminh = sizeof(struct tcpiphdr);
456 #endif /* INET6 */
457 ip = mtod(m, struct ip *);
458 ipov = (struct ipovly *)ip;
459 #if INET6
460 }
461 #endif /* INET6 */
462
463 #if INET6
464 /* XXX not a good place to put this into... */
465 if (isipv6 &&
466 m && (m->m_flags & M_ANYCAST6)) {
467 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
468 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
469 return;
470 }
471 #endif /* INET6 */
472
473 #if INET6
474 if (isipv6) {
475 IP6_EXTHDR_CHECK(m, off, sizeof(struct tcphdr), );
476 ip6 = mtod(m, struct ip6_hdr *);
477 tilen = ntohs(ip6->ip6_plen) - off + sizeof(*ip6);
478
479 if (in6_cksum(m, IPPROTO_TCP, off, tilen)) {
480 tcpstat.tcps_rcvbadsum++;
481 goto drop;
482 }
483 th = (struct tcphdr *)((caddr_t)ip6 + off);
484 } else
485 #endif /* INET6 */
486 {
487 /*
488 * Get IP and TCP header together in first mbuf.
489 * Note: IP leaves IP header in first mbuf.
490 */
491 /* XXX: should we still require this for IPv4? */
492 if (off > sizeof (struct ip)) {
493 ip_stripoptions(m, (struct mbuf *)0);
494 off = sizeof(struct ip);
495 if (m->m_pkthdr.csum_flags & CSUM_TCP_SUM16)
496 m->m_pkthdr.csum_flags = 0; /* invalidate hwcksuming */
497 }
498 if (m->m_len < lgminh) {
499 if ((m = m_pullup(m, lgminh)) == 0) {
500 tcpstat.tcps_rcvshort++;
501 return;
502 }
503 }
504 ip = mtod(m, struct ip *);
505 ipov = (struct ipovly *)ip;
506 th = (struct tcphdr *)((caddr_t)ip + off);
507 tilen = ip->ip_len;
508 len = sizeof (struct ip) + tilen;
509
510 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
511
512 if (apple_hwcksum_rx && (m->m_pkthdr.csum_flags & CSUM_TCP_SUM16)) {
513 u_short pseudo;
514 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
515 ipov->ih_len = (u_short)tilen;
516 HTONS(ipov->ih_len);
517 pseudo = in_cksum(m, sizeof (struct ip));
518 th->th_sum = in_addword(pseudo, (m->m_pkthdr.csum_data & 0xFFFF));
519 }
520 else {
521 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
522 th->th_sum = m->m_pkthdr.csum_data;
523 else goto dotcpcksum;
524 }
525 th->th_sum ^= 0xffff;
526
527 } else {
528 /*
529 * Checksum extended TCP header and data.
530 */
531 dotcpcksum:
532 if (th->th_sum) {
533 len = sizeof (struct ip) + tilen;
534 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
535 ipov->ih_len = (u_short)tilen;
536 HTONS(ipov->ih_len);
537 th = (struct tcphdr *)((caddr_t)ip + off);
538 th->th_sum = in_cksum(m, len);
539 }
540 }
541
542 if (th->th_sum) {
543 tcpstat.tcps_rcvbadsum++;
544 goto drop;
545 }
546 }
547
548 /*
549 * Check that TCP offset makes sense,
550 * pull out TCP options and adjust length. XXX
551 */
552 toff = th->th_off << 2;
553 if (toff < sizeof (struct tcphdr) || toff > tilen) {
554 tcpstat.tcps_rcvbadoff++;
555 goto drop;
556 }
557 tilen -= toff;
558 if (toff > sizeof (struct tcphdr)) {
559 #if INET6
560 if (isipv6) {
561 IP6_EXTHDR_CHECK(m, off, toff, );
562 ip6 = mtod(m, struct ip6_hdr *);
563 th = (struct tcphdr *)((caddr_t)ip6 + off);
564 } else
565 #endif /* INET6 */
566 {
567 if (m->m_len < sizeof(struct ip) + toff) {
568 if ((m = m_pullup(m, sizeof (struct ip) + toff)) == 0) {
569 tcpstat.tcps_rcvshort++;
570 return;
571 }
572 ip = mtod(m, struct ip *);
573 ipov = (struct ipovly *)ip;
574 th = (struct tcphdr *)((caddr_t)ip + off);
575 }
576 }
577 optlen = toff - sizeof (struct tcphdr);
578 optp = (u_char *)(th + 1);
579 /*
580 * Do quick retrieval of timestamp options ("options
581 * prediction?"). If timestamp is the only option and it's
582 * formatted as recommended in RFC 1323 appendix A, we
583 * quickly get the values now and not bother calling
584 * tcp_dooptions(), etc.
585 */
586 if ((optlen == TCPOLEN_TSTAMP_APPA ||
587 (optlen > TCPOLEN_TSTAMP_APPA &&
588 optp[TCPOLEN_TSTAMP_APPA] == TCPOPT_EOL)) &&
589 *(u_int32_t *)optp == htonl(TCPOPT_TSTAMP_HDR) &&
590 (th->th_flags & TH_SYN) == 0) {
591 to.to_flag |= TOF_TS;
592 to.to_tsval = ntohl(*(u_int32_t *)(optp + 4));
593 to.to_tsecr = ntohl(*(u_int32_t *)(optp + 8));
594 optp = NULL; /* we've parsed the options */
595 }
596 }
597 thflags = th->th_flags;
598
599 /*
600 * Convert TCP protocol specific fields to host format.
601 */
602 NTOHL(th->th_seq);
603 NTOHL(th->th_ack);
604 NTOHS(th->th_win);
605 NTOHS(th->th_urp);
606
607 /*
608 * Drop TCP, IP headers and TCP options.
609 */
610 hdroptlen = off+toff;
611 m->m_data += hdroptlen;
612 m->m_len -= hdroptlen;
613
614 /*
615 * Locate pcb for segment.
616 */
617 findpcb:
618 #if IPFIREWALL_FORWARD
619 if (ip_fw_fwd_addr != NULL
620 #if INET6
621 && isipv6 == NULL
622 #endif /* INET6 */
623 ) {
624 /*
625 * Diverted. Pretend to be the destination.
626 * already got one like this?
627 */
628 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
629 ip->ip_dst, th->th_dport, 0, m->m_pkthdr.rcvif);
630 if (!inp) {
631 /*
632 * No, then it's new. Try find the ambushing socket
633 */
634 if (!ip_fw_fwd_addr->sin_port) {
635 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src,
636 th->th_sport, ip_fw_fwd_addr->sin_addr,
637 th->th_dport, 1, m->m_pkthdr.rcvif);
638 } else {
639 inp = in_pcblookup_hash(&tcbinfo,
640 ip->ip_src, th->th_sport,
641 ip_fw_fwd_addr->sin_addr,
642 ntohs(ip_fw_fwd_addr->sin_port), 1,
643 m->m_pkthdr.rcvif);
644 }
645 }
646 ip_fw_fwd_addr = NULL;
647 } else
648 #endif /* IPFIREWALL_FORWARD */
649
650 #if INET6
651 if (isipv6)
652 inp = in6_pcblookup_hash(&tcbinfo, &ip6->ip6_src, th->th_sport,
653 &ip6->ip6_dst, th->th_dport, 1,
654 m->m_pkthdr.rcvif);
655 else
656 #endif /* INET6 */
657 inp = in_pcblookup_hash(&tcbinfo, ip->ip_src, th->th_sport,
658 ip->ip_dst, th->th_dport, 1, m->m_pkthdr.rcvif);
659
660 #if IPSEC
661 /* due to difference from other BSD stacks */
662 m->m_data -= hdroptlen;
663 m->m_len += hdroptlen;
664 #if INET6
665 if (isipv6) {
666 if (inp != NULL && ipsec6_in_reject_so(m, inp->inp_socket)) {
667 ipsec6stat.in_polvio++;
668 goto drop;
669 }
670 } else
671 #endif /* INET6 */
672 if (inp != NULL && ipsec4_in_reject_so(m, inp->inp_socket)) {
673 ipsecstat.in_polvio++;
674 goto drop;
675 }
676 m->m_data += hdroptlen;
677 m->m_len -= hdroptlen;
678 #endif /*IPSEC*/
679
680 /*
681 * If the state is CLOSED (i.e., TCB does not exist) then
682 * all data in the incoming segment is discarded.
683 * If the TCB exists but is in CLOSED state, it is embryonic,
684 * but should either do a listen or a connect soon.
685 */
686 if (inp == NULL) {
687 if (log_in_vain && thflags & TH_SYN) {
688 #if INET6
689 char buf[INET6_ADDRSTRLEN];
690 #else /* INET6 */
691 char buf[4*sizeof "123"];
692 #endif /* INET6 */
693
694 #if INET6
695 if (isipv6) {
696 strcpy(buf, ip6_sprintf(&ip6->ip6_dst));
697 log(LOG_INFO,
698 "Connection attempt to TCP %s:%d from %s:%d\n",
699 buf, ntohs(th->th_dport),
700 ip6_sprintf(&ip6->ip6_src),
701 ntohs(th->th_sport));
702 } else {
703 #endif
704 strcpy(buf, inet_ntoa(ip->ip_dst));
705 log(LOG_INFO,
706 "Connection attempt to TCP %s:%d from %s:%d\n",
707 buf, ntohs(th->th_dport), inet_ntoa(ip->ip_src),
708 ntohs(th->th_sport));
709 #if INET6
710 }
711 #endif /* INET6 */
712 }
713 #if ICMP_BANDLIM
714 if (badport_bandlim(1) < 0)
715 goto drop;
716 #endif
717 goto dropwithreset;
718 }
719 tp = intotcpcb(inp);
720 if (tp == 0)
721 goto dropwithreset;
722 if (tp->t_state == TCPS_CLOSED)
723 goto drop;
724 /*
725 * Bogus state when listening port owned by SharedIP with loopback as the
726 * only configured interface: BlueBox does not filters loopback
727 */
728 if (tp->t_state == TCP_NSTATES)
729 goto drop;
730
731 /* Unscale the window into a 32-bit value. */
732 if ((thflags & TH_SYN) == 0)
733 tiwin = th->th_win << tp->snd_scale;
734 else
735 tiwin = th->th_win;
736
737 so = inp->inp_socket;
738 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
739 #if TCPDEBUG
740 if (so->so_options & SO_DEBUG) {
741 ostate = tp->t_state;
742 #if INET6
743 if (isipv6)
744 tcp_saveip._tcp_si6 = *ip6;
745 else
746 tcp_saveip._tcp_si4 = *ip;
747 #else /* INET6 */
748 tcp_saveip = *ip;
749 #endif /* INET6 */
750
751 tcp_savetcp = *th;
752 }
753 #endif
754 if (so->so_options & SO_ACCEPTCONN) {
755 register struct tcpcb *tp0 = tp;
756 struct socket *so2;
757 #if IPSEC
758 struct socket *oso;
759 #endif
760 #if INET6
761 struct inpcb *oinp = sotoinpcb(so);
762 #endif /* INET6 */
763
764 #if !IPSEC
765 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
766 /*
767 * Note: dropwithreset makes sure we don't
768 * send a RST in response to a RST.
769 */
770 if (thflags & TH_ACK) {
771 tcpstat.tcps_badsyn++;
772 goto dropwithreset;
773 }
774 goto drop;
775 }
776 #endif
777 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START,0,0,0,0,0);
778 so2 = sonewconn(so, 0);
779
780
781 if (so2 == 0) {
782 tcpstat.tcps_listendrop++;
783 so2 = sodropablereq(so);
784 if (so2) {
785 tcp_drop(sototcpcb(so2), ETIMEDOUT);
786 so2 = sonewconn(so, 0);
787 }
788 if (!so2)
789 goto drop;
790 }
791 #if IPSEC
792 oso = so;
793 #endif
794 so = so2;
795 /*
796 * This is ugly, but ....
797 *
798 * Mark socket as temporary until we're
799 * committed to keeping it. The code at
800 * ``drop'' and ``dropwithreset'' check the
801 * flag dropsocket to see if the temporary
802 * socket created here should be discarded.
803 * We mark the socket as discardable until
804 * we're committed to it below in TCPS_LISTEN.
805 */
806 dropsocket++;
807 inp = (struct inpcb *)so->so_pcb;
808 #if INET6
809 if (isipv6)
810 inp->in6p_laddr = ip6->ip6_dst;
811 else {
812 if (ip6_mapped_addr_on) {
813 inp->inp_vflag &= ~INP_IPV6;
814 inp->inp_vflag |= INP_IPV4;
815 }
816 #endif /* INET6 */
817 inp->inp_laddr = ip->ip_dst;
818 #if INET6
819 }
820 #endif /* INET6 */
821
822 inp->inp_lport = th->th_dport;
823 if (in_pcbinshash(inp) != 0) {
824 /*
825 * Undo the assignments above if we failed to put
826 * the PCB on the hash lists.
827 */
828 #if INET6
829 if (isipv6)
830 inp->in6p_laddr = in6addr_any;
831 else
832 #endif /* INET6 */
833 inp->inp_laddr.s_addr = INADDR_ANY;
834 inp->inp_lport = 0;
835 goto drop;
836 }
837 #if IPSEC
838 /*
839 * from IPsec perspective, it is important to do it
840 * after making actual listening socket.
841 * otherwise, cached security association will bark.
842 *
843 * Subject: (KAME-snap 748)
844 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
845 */
846 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
847 /*
848 * Note: dropwithreset makes sure we don't
849 * send a RST in response to a RST.
850 */
851 if (thflags & TH_ACK) {
852 tcpstat.tcps_badsyn++;
853 goto dropwithreset;
854 }
855 goto drop;
856 }
857 #endif
858 #if INET6
859 if (isipv6) {
860 struct ip6_recvpktopts newopts;
861
862 /*
863 * Inherit socket options from the listening
864 * socket.
865 * Note that in6p_inputopts are not (even
866 * should not be) copied, since it stores
867 * previously received options and is used to
868 * detect if each new option is different than
869 * the previous one and hence should be passed
870 * to a user.
871 * If we copied in6p_inputopts, a user would
872 * not be able to receive options just after
873 * calling the accept system call.
874 */
875 inp->inp_flags |=
876 oinp->inp_flags & INP_CONTROLOPTS;
877 if (oinp->in6p_outputopts)
878 inp->in6p_outputopts =
879 ip6_copypktopts(oinp->in6p_outputopts,
880 M_NOWAIT);
881 } else
882 #endif /* INET6 */
883 inp->inp_options = ip_srcroute();
884 #if IPSEC
885 /* copy old policy into new socket's */
886 if (ipsec_copy_policy(sotoinpcb(oso)->inp_sp,
887 inp->inp_sp))
888 printf("tcp_input: could not copy policy\n");
889 #endif
890
891 tp = intotcpcb(inp);
892 tp->t_state = TCPS_LISTEN;
893 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
894
895 /* Compute proper scaling value from buffer space */
896 while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
897 TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
898 tp->request_r_scale++;
899
900 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END,0,0,0,0,0);
901 }
902 }
903
904 #if INET6
905 /* save packet options if user wanted */
906 if (isipv6 && (inp->in6p_flags & INP_CONTROLOPTS) != 0) {
907 struct ip6_recvpktopts opts6;
908
909 /*
910 * Temporarily re-adjusting the mbuf before ip6_savecontrol(),
911 * which is necessary for FreeBSD only due to difference from
912 * other BSD stacks.
913 * XXX: we'll soon make a more natural fix after getting a
914 * consensus.
915 */
916 #ifndef DEFER_MADJ
917 m->m_data -= hdroptlen;
918 m->m_len += hdroptlen;
919 #endif
920 ip6_savecontrol(inp, ip6, m, &opts6, &inp->in6p_inputopts);
921 if (inp->in6p_inputopts)
922 ip6_update_recvpcbopt(inp->in6p_inputopts, &opts6);
923 if (opts6.head) {
924 if (sbappendcontrol(&inp->in6p_socket->so_rcv,
925 NULL, opts6.head)
926 == 0)
927 m_freem(opts6.head);
928 }
929 #ifndef DEFER_MADJ
930 m->m_data += hdroptlen; /* XXX */
931 m->m_len -= hdroptlen; /* XXX */
932 #endif
933 }
934 #endif /* INET6 */
935
936 /*
937 * Segment received on connection.
938 * Reset idle time and keep-alive timer.
939 */
940 tp->t_idle = 0;
941 if (TCPS_HAVEESTABLISHED(tp->t_state))
942 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
943
944 /*
945 * Process options if not in LISTEN state,
946 * else do it below (after getting remote address).
947 */
948 if (tp->t_state != TCPS_LISTEN && optp)
949 tcp_dooptions(tp, optp, optlen, th, &to);
950 if (th->th_flags & TH_SYN)
951 tcp_mss(tp, to.to_maxseg, isipv6); /* sets t_maxseg */
952
953 /*
954 * Header prediction: check for the two common cases
955 * of a uni-directional data xfer. If the packet has
956 * no control flags, is in-sequence, the window didn't
957 * change and we're not retransmitting, it's a
958 * candidate. If the length is zero and the ack moved
959 * forward, we're the sender side of the xfer. Just
960 * free the data acked & wake any higher level process
961 * that was blocked waiting for space. If the length
962 * is non-zero and the ack didn't move, we're the
963 * receiver side. If we're getting packets in-order
964 * (the reassembly queue is empty), add the data to
965 * the socket buffer and note that we need a delayed ack.
966 * Make sure that the hidden state-flags are also off.
967 * Since we check for TCPS_ESTABLISHED above, it can only
968 * be TH_NEEDSYN.
969 */
970 if (tp->t_state == TCPS_ESTABLISHED &&
971 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
972 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
973 ((to.to_flag & TOF_TS) == 0 ||
974 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
975 /*
976 * Using the CC option is compulsory if once started:
977 * the segment is OK if no T/TCP was negotiated or
978 * if the segment has a CC option equal to CCrecv
979 */
980 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
981 ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
982 th->th_seq == tp->rcv_nxt &&
983 tiwin && tiwin == tp->snd_wnd &&
984 tp->snd_nxt == tp->snd_max) {
985
986 /*
987 * If last ACK falls within this segment's sequence numbers,
988 * record the timestamp.
989 * NOTE that the test is modified according to the latest
990 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
991 */
992 if ((to.to_flag & TOF_TS) != 0 &&
993 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
994 tp->ts_recent_age = tcp_now;
995 tp->ts_recent = to.to_tsval;
996 }
997
998 if (tilen == 0) {
999 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1000 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1001 tp->snd_cwnd >= tp->snd_wnd &&
1002 tp->t_dupacks < tcprexmtthresh) {
1003 /*
1004 * this is a pure ack for outstanding data.
1005 */
1006 ++tcpstat.tcps_predack;
1007 if ((to.to_flag & TOF_TS) != 0)
1008 tcp_xmit_timer(tp,
1009 tcp_now - to.to_tsecr + 1);
1010 else if (tp->t_rtt &&
1011 SEQ_GT(th->th_ack, tp->t_rtseq))
1012 tcp_xmit_timer(tp, tp->t_rtt);
1013 acked = th->th_ack - tp->snd_una;
1014 tcpstat.tcps_rcvackpack++;
1015 tcpstat.tcps_rcvackbyte += acked;
1016 sbdrop(&so->so_snd, acked);
1017 tp->snd_una = th->th_ack;
1018 m_freem(m);
1019 #if INET6
1020 /* some progress has been done */
1021 if (isipv6)
1022 ND6_HINT(tp);
1023 #endif
1024
1025 /*
1026 * If all outstanding data are acked, stop
1027 * retransmit timer, otherwise restart timer
1028 * using current (possibly backed-off) value.
1029 * If process is waiting for space,
1030 * wakeup/selwakeup/signal. If data
1031 * are ready to send, let tcp_output
1032 * decide between more output or persist.
1033 */
1034 if (tp->snd_una == tp->snd_max)
1035 tp->t_timer[TCPT_REXMT] = 0;
1036 else if (tp->t_timer[TCPT_PERSIST] == 0)
1037 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1038
1039 if (so->so_snd.sb_cc)
1040 (void) tcp_output(tp);
1041 sowwakeup(so);
1042 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
1043 return;
1044 }
1045 } else if (th->th_ack == tp->snd_una &&
1046 tp->segq.lh_first == NULL &&
1047 tilen <= sbspace(&so->so_rcv)) {
1048 /*
1049 * this is a pure, in-sequence data packet
1050 * with nothing on the reassembly queue and
1051 * we have enough buffer space to take it.
1052 */
1053 ++tcpstat.tcps_preddat;
1054 tp->rcv_nxt += tilen;
1055 tcpstat.tcps_rcvpack++;
1056 tcpstat.tcps_rcvbyte += tilen;
1057 #if INET6
1058 /* some progress has been done */
1059 if (isipv6)
1060 ND6_HINT(tp);
1061 #endif
1062 sbappend(&so->so_rcv, m);
1063 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
1064 (((thtoti(th)->ti_src.s_addr & 0xffff) << 16) | (thtoti(th)->ti_dst.s_addr & 0xffff)),
1065 th->th_seq, th->th_ack, th->th_win);
1066 if (tcp_delack_enabled) {
1067 if (last_active_conn_count > DELACK_BITMASK_THRESH)
1068 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
1069 tp->t_flags |= TF_DELACK;
1070 } else {
1071 tp->t_flags |= TF_ACKNOW;
1072 tcp_output(tp);
1073 }
1074 sorwakeup(so);
1075 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
1076 return;
1077 }
1078 }
1079
1080 /*
1081 * Calculate amount of space in receive window,
1082 * and then do TCP input processing.
1083 * Receive window is amount of space in rcv queue,
1084 * but not less than advertised window.
1085 */
1086 { int win;
1087
1088 win = sbspace(&so->so_rcv);
1089 if (win < 0)
1090 win = 0;
1091 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1092 }
1093
1094 switch (tp->t_state) {
1095
1096 /*
1097 * If the state is LISTEN then ignore segment if it contains an RST.
1098 * If the segment contains an ACK then it is bad and send a RST.
1099 * If it does not contain a SYN then it is not interesting; drop it.
1100 * If it is from this socket, drop it, it must be forged.
1101 * Don't bother responding if the destination was a broadcast.
1102 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1103 * tp->iss, and send a segment:
1104 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1105 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1106 * Fill in remote peer address fields if not previously specified.
1107 * Enter SYN_RECEIVED state, and process any other fields of this
1108 * segment in this state.
1109 */
1110 case TCPS_LISTEN: {
1111 register struct sockaddr_in *sin;
1112 #if 0
1113 register struct sockaddr_in6 *sin6;
1114 #endif
1115
1116 if (thflags & TH_RST)
1117 goto drop;
1118 if (thflags & TH_ACK)
1119 goto dropwithreset;
1120 if ((thflags & TH_SYN) == 0)
1121 goto drop;
1122 if (th->th_dport == th->th_sport) {
1123 #if INET6
1124 if (isipv6) {
1125 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1126 &ip6->ip6_src))
1127 goto drop;
1128 } else
1129 #endif /* INET6 */
1130 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1131 goto drop;
1132 }
1133
1134 #if INET6
1135 if (isipv6) {
1136 if (m->m_flags & (M_BCAST|M_MCAST) ||
1137 IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1138 goto drop;
1139 #if 1
1140 /*
1141 * Perhaps this should be a call/macro
1142 * to a function like in6_pcbconnect(), but almost
1143 * all of the checks have been done: we know
1144 * that the association is unique, and the
1145 * local address is always set here.
1146 */
1147 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1148 inp->in6p_laddr = ip6->ip6_dst;
1149 inp->in6p_faddr = ip6->ip6_src;
1150 inp->inp_fport = th->th_sport;
1151
1152 /* TODO: flowinfo initialization */
1153
1154 in_pcbrehash(inp);
1155 #else
1156 MALLOC(sin6, struct sockaddr_in6 *, sizeof *sin6,
1157 M_SONAME, M_NOWAIT);
1158 if (sin6 == NULL)
1159 goto drop;
1160 bzero(sin6, sizeof(*sin6));
1161 sin6->sin6_family = AF_INET6;
1162 sin6->sin6_len = sizeof(*sin6);
1163 sin6->sin6_addr = ip6->ip6_src;
1164 sin6->sin6_port = th->th_sport;
1165 laddr6 = inp->in6p_laddr;
1166 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1167 inp->in6p_laddr = ip6->ip6_dst;
1168 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
1169 &proc0)) {
1170 inp->in6p_laddr = laddr6;
1171 FREE(sin6, M_SONAME);
1172 goto drop;
1173 }
1174 FREE(sin6, M_SONAME);
1175 #endif
1176 }
1177 else {
1178 #endif /* INET6 */
1179 /*
1180 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1181 * in_broadcast() should never return true on a received
1182 * packet with M_BCAST not set.
1183 *
1184 * Packets with a multicast source address should also
1185 * be discarded.
1186 */
1187 if (m->m_flags & (M_BCAST|M_MCAST))
1188 goto drop;
1189 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1190 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1191 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1192 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
1193 goto drop;
1194 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
1195 M_NOWAIT);
1196 if (sin == NULL)
1197 goto drop;
1198 sin->sin_family = AF_INET;
1199 sin->sin_len = sizeof(*sin);
1200 sin->sin_addr = ip->ip_src;
1201 sin->sin_port = th->th_sport;
1202 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
1203 laddr = inp->inp_laddr;
1204 if (inp->inp_laddr.s_addr == INADDR_ANY)
1205 inp->inp_laddr = ip->ip_dst;
1206 if (in_pcbconnect(inp, (struct sockaddr *)sin, &proc0)) {
1207 inp->inp_laddr = laddr;
1208 FREE(sin, M_SONAME);
1209 goto drop;
1210 }
1211 FREE(sin, M_SONAME);
1212 #if INET6
1213 }
1214 #endif /* INET6 */
1215
1216 tp->t_template = tcp_template(tp);
1217 if (tp->t_template == 0) {
1218 tp = tcp_drop(tp, ENOBUFS);
1219 dropsocket = 0; /* socket is already gone */
1220 goto drop;
1221 }
1222 if ((taop = tcp_gettaocache(inp)) == NULL) {
1223 taop = &tao_noncached;
1224 bzero(taop, sizeof(*taop));
1225 }
1226 tcp_dooptions(tp, optp, optlen, th, &to);
1227 if (th->th_flags & TH_SYN)
1228 tcp_mss(tp, to.to_maxseg, isipv6); /* sets t_maxseg */
1229 if (iss)
1230 tp->iss = iss;
1231 else {
1232 #ifdef TCP_COMPAT_42
1233 tcp_iss += TCP_ISSINCR/2;
1234 tp->iss = tcp_iss;
1235 #else
1236 tp->iss = tcp_rndiss_next();
1237 #endif /* TCP_COMPAT_42 */
1238 }
1239 tp->irs = th->th_seq;
1240 tcp_sendseqinit(tp);
1241 tcp_rcvseqinit(tp);
1242 /*
1243 * Initialization of the tcpcb for transaction;
1244 * set SND.WND = SEG.WND,
1245 * initialize CCsend and CCrecv.
1246 */
1247 tp->snd_wnd = tiwin; /* initial send-window */
1248 tp->cc_send = CC_INC(tcp_ccgen);
1249 tp->cc_recv = to.to_cc;
1250 /*
1251 * Perform TAO test on incoming CC (SEG.CC) option, if any.
1252 * - compare SEG.CC against cached CC from the same host,
1253 * if any.
1254 * - if SEG.CC > chached value, SYN must be new and is accepted
1255 * immediately: save new CC in the cache, mark the socket
1256 * connected, enter ESTABLISHED state, turn on flag to
1257 * send a SYN in the next segment.
1258 * A virtual advertised window is set in rcv_adv to
1259 * initialize SWS prevention. Then enter normal segment
1260 * processing: drop SYN, process data and FIN.
1261 * - otherwise do a normal 3-way handshake.
1262 */
1263 if ((to.to_flag & TOF_CC) != 0) {
1264 if (((tp->t_flags & TF_NOPUSH) != 0) &&
1265 taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
1266
1267 taop->tao_cc = to.to_cc;
1268 if (tp->t_state != TCPS_ESTABLISHED)
1269 current_active_connections++;
1270
1271 tp->t_state = TCPS_ESTABLISHED;
1272
1273 /*
1274 * If there is a FIN, or if there is data and the
1275 * connection is local, then delay SYN,ACK(SYN) in
1276 * the hope of piggy-backing it on a response
1277 * segment. Otherwise must send ACK now in case
1278 * the other side is slow starting.
1279 */
1280 if (tcp_delack_enabled &&
1281 ((thflags & TH_FIN) ||
1282 (tilen != 0 &&
1283 #if INET6
1284 (isipv6 && in6_localaddr(&inp->in6p_faddr))
1285 ||
1286 (!isipv6 &&
1287 #endif /* INET6 */
1288 in_localaddr(inp->inp_faddr)
1289 #if INET6
1290 )
1291 #endif /* INET6 */
1292 ))) {
1293 if (last_active_conn_count > DELACK_BITMASK_THRESH)
1294 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
1295
1296 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
1297 }
1298 else
1299 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1300
1301 /*
1302 * Limit the `virtual advertised window' to TCP_MAXWIN
1303 * here. Even if we requested window scaling, it will
1304 * become effective only later when our SYN is acked.
1305 */
1306 tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
1307 tcpstat.tcps_connects++;
1308 soisconnected(so);
1309 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
1310 dropsocket = 0; /* committed to socket */
1311 tcpstat.tcps_accepts++;
1312 goto trimthenstep6;
1313 }
1314 /* else do standard 3-way handshake */
1315 } else {
1316 /*
1317 * No CC option, but maybe CC.NEW:
1318 * invalidate cached value.
1319 */
1320 taop->tao_cc = 0;
1321 }
1322 /*
1323 * TAO test failed or there was no CC option,
1324 * do a standard 3-way handshake.
1325 */
1326 tp->t_flags |= TF_ACKNOW;
1327 tp->t_state = TCPS_SYN_RECEIVED;
1328 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
1329 dropsocket = 0; /* committed to socket */
1330 tcpstat.tcps_accepts++;
1331 goto trimthenstep6;
1332 }
1333
1334 /*
1335 * If the state is SYN_RECEIVED:
1336 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1337 */
1338 case TCPS_SYN_RECEIVED:
1339 if ((thflags & TH_ACK) &&
1340 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1341 SEQ_GT(th->th_ack, tp->snd_max)))
1342 goto dropwithreset;
1343 break;
1344
1345 /*
1346 * If the state is SYN_SENT:
1347 * if seg contains an ACK, but not for our SYN, drop the input.
1348 * if seg contains a RST, then drop the connection.
1349 * if seg does not contain SYN, then drop it.
1350 * Otherwise this is an acceptable SYN segment
1351 * initialize tp->rcv_nxt and tp->irs
1352 * if seg contains ack then advance tp->snd_una
1353 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1354 * arrange for segment to be acked (eventually)
1355 * continue processing rest of data/controls, beginning with URG
1356 */
1357 case TCPS_SYN_SENT:
1358 if ((taop = tcp_gettaocache(inp)) == NULL) {
1359 taop = &tao_noncached;
1360 bzero(taop, sizeof(*taop));
1361 }
1362
1363 if ((thflags & TH_ACK) &&
1364 (SEQ_LEQ(th->th_ack, tp->iss) ||
1365 SEQ_GT(th->th_ack, tp->snd_max))) {
1366 /*
1367 * If we have a cached CCsent for the remote host,
1368 * hence we haven't just crashed and restarted,
1369 * do not send a RST. This may be a retransmission
1370 * from the other side after our earlier ACK was lost.
1371 * Our new SYN, when it arrives, will serve as the
1372 * needed ACK.
1373 */
1374 if (taop->tao_ccsent != 0)
1375 goto drop;
1376 else
1377 goto dropwithreset;
1378 }
1379 if (thflags & TH_RST) {
1380 if (thflags & TH_ACK) {
1381 tp = tcp_drop(tp, ECONNREFUSED);
1382 postevent(so, 0, EV_RESET);
1383 }
1384 goto drop;
1385 }
1386 if ((thflags & TH_SYN) == 0)
1387 goto drop;
1388 tp->snd_wnd = th->th_win; /* initial send window */
1389 tp->cc_recv = to.to_cc; /* foreign CC */
1390
1391 tp->irs = th->th_seq;
1392 tcp_rcvseqinit(tp);
1393 if (thflags & TH_ACK) {
1394 /*
1395 * Our SYN was acked. If segment contains CC.ECHO
1396 * option, check it to make sure this segment really
1397 * matches our SYN. If not, just drop it as old
1398 * duplicate, but send an RST if we're still playing
1399 * by the old rules. If no CC.ECHO option, make sure
1400 * we don't get fooled into using T/TCP.
1401 */
1402 if (to.to_flag & TOF_CCECHO) {
1403 if (tp->cc_send != to.to_ccecho)
1404 if (taop->tao_ccsent != 0)
1405 goto drop;
1406 else
1407 goto dropwithreset;
1408 } else
1409 tp->t_flags &= ~TF_RCVD_CC;
1410 tcpstat.tcps_connects++;
1411 soisconnected(so);
1412 /* Do window scaling on this connection? */
1413 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1414 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1415 tp->snd_scale = tp->requested_s_scale;
1416 tp->rcv_scale = tp->request_r_scale;
1417 }
1418 /* Segment is acceptable, update cache if undefined. */
1419 if (taop->tao_ccsent == 0)
1420 taop->tao_ccsent = to.to_ccecho;
1421
1422 tp->rcv_adv += tp->rcv_wnd;
1423 tp->snd_una++; /* SYN is acked */
1424 /*
1425 * If there's data, delay ACK; if there's also a FIN
1426 * ACKNOW will be turned on later.
1427 */
1428 if (tcp_delack_enabled && tilen != 0) {
1429 if (last_active_conn_count > DELACK_BITMASK_THRESH)
1430 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
1431 tp->t_flags |= TF_DELACK;
1432 }
1433 else
1434 tp->t_flags |= TF_ACKNOW;
1435 /*
1436 * Received <SYN,ACK> in SYN_SENT[*] state.
1437 * Transitions:
1438 * SYN_SENT --> ESTABLISHED
1439 * SYN_SENT* --> FIN_WAIT_1
1440 */
1441 if (tp->t_flags & TF_NEEDFIN) {
1442 tp->t_state = TCPS_FIN_WAIT_1;
1443 tp->t_flags &= ~TF_NEEDFIN;
1444 thflags &= ~TH_SYN;
1445 } else {
1446 if (tp->t_state != TCPS_ESTABLISHED)
1447 current_active_connections++;
1448 tp->t_state = TCPS_ESTABLISHED;
1449 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1450 }
1451 } else {
1452 /*
1453 * Received initial SYN in SYN-SENT[*] state => simul-
1454 * taneous open. If segment contains CC option and there is
1455 * a cached CC, apply TAO test; if it succeeds, connection is
1456 * half-synchronized. Otherwise, do 3-way handshake:
1457 * SYN-SENT -> SYN-RECEIVED
1458 * SYN-SENT* -> SYN-RECEIVED*
1459 * If there was no CC option, clear cached CC value.
1460 */
1461 tp->t_flags |= TF_ACKNOW;
1462 tp->t_timer[TCPT_REXMT] = 0;
1463 if (to.to_flag & TOF_CC) {
1464 if (taop->tao_cc != 0 &&
1465 CC_GT(to.to_cc, taop->tao_cc)) {
1466 /*
1467 * update cache and make transition:
1468 * SYN-SENT -> ESTABLISHED*
1469 * SYN-SENT* -> FIN-WAIT-1*
1470 */
1471 taop->tao_cc = to.to_cc;
1472 if (tp->t_flags & TF_NEEDFIN) {
1473 tp->t_state = TCPS_FIN_WAIT_1;
1474 tp->t_flags &= ~TF_NEEDFIN;
1475 } else {
1476 if (tp->t_state != TCPS_ESTABLISHED)
1477 current_active_connections++;
1478 tp->t_state = TCPS_ESTABLISHED;
1479 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1480 }
1481 tp->t_flags |= TF_NEEDSYN;
1482 } else
1483 tp->t_state = TCPS_SYN_RECEIVED;
1484 } else {
1485 /* CC.NEW or no option => invalidate cache */
1486 taop->tao_cc = 0;
1487 tp->t_state = TCPS_SYN_RECEIVED;
1488 }
1489 }
1490
1491 trimthenstep6:
1492 /*
1493 * Advance th->th_seq to correspond to first data byte.
1494 * If data, trim to stay within window,
1495 * dropping FIN if necessary.
1496 */
1497 th->th_seq++;
1498 if (tilen > tp->rcv_wnd) {
1499 todrop = tilen - tp->rcv_wnd;
1500 m_adj(m, -todrop);
1501 tilen = tp->rcv_wnd;
1502 thflags &= ~TH_FIN;
1503 tcpstat.tcps_rcvpackafterwin++;
1504 tcpstat.tcps_rcvbyteafterwin += todrop;
1505 }
1506 tp->snd_wl1 = th->th_seq - 1;
1507 tp->rcv_up = th->th_seq;
1508 /*
1509 * Client side of transaction: already sent SYN and data.
1510 * If the remote host used T/TCP to validate the SYN,
1511 * our data will be ACK'd; if so, enter normal data segment
1512 * processing in the middle of step 5, ack processing.
1513 * Otherwise, goto step 6.
1514 */
1515 if (thflags & TH_ACK)
1516 goto process_ACK;
1517 goto step6;
1518 /*
1519 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1520 * if segment contains a SYN and CC [not CC.NEW] option:
1521 * if state == TIME_WAIT and connection duration > MSL,
1522 * drop packet and send RST;
1523 *
1524 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1525 * ack the FIN (and data) in retransmission queue.
1526 * Complete close and delete TCPCB. Then reprocess
1527 * segment, hoping to find new TCPCB in LISTEN state;
1528 *
1529 * else must be old SYN; drop it.
1530 * else do normal processing.
1531 */
1532 case TCPS_LAST_ACK:
1533 case TCPS_CLOSING:
1534 case TCPS_TIME_WAIT:
1535 if ((thflags & TH_SYN) &&
1536 (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
1537 if (tp->t_state == TCPS_TIME_WAIT &&
1538 tp->t_duration > TCPTV_MSL)
1539 goto dropwithreset;
1540 if (CC_GT(to.to_cc, tp->cc_recv)) {
1541 tp = tcp_close(tp);
1542 goto findpcb;
1543 }
1544 else
1545 goto drop;
1546 }
1547 break; /* continue normal processing */
1548 }
1549
1550 /*
1551 * States other than LISTEN or SYN_SENT.
1552 * First check the RST flag and sequence number since reset segments
1553 * are exempt from the timestamp and connection count tests. This
1554 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1555 * below which allowed reset segments in half the sequence space
1556 * to fall though and be processed (which gives forged reset
1557 * segments with a random sequence number a 50 percent chance of
1558 * killing a connection).
1559 * Then check timestamp, if present.
1560 * Then check the connection count, if present.
1561 * Then check that at least some bytes of segment are within
1562 * receive window. If segment begins before rcv_nxt,
1563 * drop leading data (and SYN); if nothing left, just ack.
1564 *
1565 *
1566 * If the RST bit is set, check the sequence number to see
1567 * if this is a valid reset segment.
1568 * RFC 793 page 37:
1569 * In all states except SYN-SENT, all reset (RST) segments
1570 * are validated by checking their SEQ-fields. A reset is
1571 * valid if its sequence number is in the window.
1572 * Note: this does not take into account delayed ACKs, so
1573 * we should test against last_ack_sent instead of rcv_nxt.
1574 * Also, it does not make sense to allow reset segments with
1575 * sequence numbers greater than last_ack_sent to be processed
1576 * since these sequence numbers are just the acknowledgement
1577 * numbers in our outgoing packets being echoed back at us,
1578 * and these acknowledgement numbers are monotonically
1579 * increasing.
1580 * If we have multiple segments in flight, the intial reset
1581 * segment sequence numbers will be to the left of last_ack_sent,
1582 * but they will eventually catch up.
1583 * In any case, it never made sense to trim reset segments to
1584 * fit the receive window since RFC 1122 says:
1585 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1586 *
1587 * A TCP SHOULD allow a received RST segment to include data.
1588 *
1589 * DISCUSSION
1590 * It has been suggested that a RST segment could contain
1591 * ASCII text that encoded and explained the cause of the
1592 * RST. No standard has yet been established for such
1593 * data.
1594 *
1595 * If the reset segment passes the sequence number test examine
1596 * the state:
1597 * SYN_RECEIVED STATE:
1598 * If passive open, return to LISTEN state.
1599 * If active open, inform user that connection was refused.
1600 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1601 * Inform user that connection was reset, and close tcb.
1602 * CLOSING, LAST_ACK, TIME_WAIT STATES
1603 * Close the tcb.
1604 * TIME_WAIT state:
1605 * Drop the segment - see Stevens, vol. 2, p. 964 and
1606 * RFC 1337.
1607 */
1608 if (thflags & TH_RST) {
1609 if (tp->last_ack_sent == th->th_seq) {
1610 switch (tp->t_state) {
1611
1612 case TCPS_SYN_RECEIVED:
1613 so->so_error = ECONNREFUSED;
1614 goto close;
1615
1616 case TCPS_ESTABLISHED:
1617 case TCPS_FIN_WAIT_1:
1618 case TCPS_CLOSE_WAIT:
1619 current_active_connections--;
1620 /*
1621 Drop through ...
1622 */
1623 case TCPS_FIN_WAIT_2:
1624 so->so_error = ECONNRESET;
1625 close:
1626 postevent(so, 0, EV_RESET);
1627 tp->t_state = TCPS_CLOSED;
1628 tcpstat.tcps_drops++;
1629 tp = tcp_close(tp);
1630 break;
1631
1632 case TCPS_CLOSING:
1633 case TCPS_LAST_ACK:
1634 current_active_connections--;
1635 tp = tcp_close(tp);
1636 break;
1637
1638 case TCPS_TIME_WAIT:
1639 break;
1640 }
1641 }
1642 goto drop;
1643 }
1644
1645 /*
1646 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1647 * and it's less than ts_recent, drop it.
1648 */
1649 if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1650 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1651
1652 /* Check to see if ts_recent is over 24 days old. */
1653 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1654 /*
1655 * Invalidate ts_recent. If this segment updates
1656 * ts_recent, the age will be reset later and ts_recent
1657 * will get a valid value. If it does not, setting
1658 * ts_recent to zero will at least satisfy the
1659 * requirement that zero be placed in the timestamp
1660 * echo reply when ts_recent isn't valid. The
1661 * age isn't reset until we get a valid ts_recent
1662 * because we don't want out-of-order segments to be
1663 * dropped when ts_recent is old.
1664 */
1665 tp->ts_recent = 0;
1666 } else {
1667 tcpstat.tcps_rcvduppack++;
1668 tcpstat.tcps_rcvdupbyte += tilen;
1669 tcpstat.tcps_pawsdrop++;
1670 goto dropafterack;
1671 }
1672 }
1673
1674 /*
1675 * T/TCP mechanism
1676 * If T/TCP was negotiated and the segment doesn't have CC,
1677 * or if its CC is wrong then drop the segment.
1678 * RST segments do not have to comply with this.
1679 */
1680 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1681 ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1682 goto dropafterack;
1683
1684 /*
1685 * In the SYN-RECEIVED state, validate that the packet belongs to
1686 * this connection before trimming the data to fit the receive
1687 * window. Check the sequence number versus IRS since we know
1688 * the sequence numbers haven't wrapped. This is a partial fix
1689 * for the "LAND" DoS attack.
1690 */
1691 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs))
1692 goto dropwithreset;
1693
1694 todrop = tp->rcv_nxt - th->th_seq;
1695 if (todrop > 0) {
1696 if (thflags & TH_SYN) {
1697 thflags &= ~TH_SYN;
1698 th->th_seq++;
1699 if (th->th_urp > 1)
1700 th->th_urp--;
1701 else
1702 thflags &= ~TH_URG;
1703 todrop--;
1704 }
1705 /*
1706 * Following if statement from Stevens, vol. 2, p. 960.
1707 */
1708 if (todrop > tilen
1709 || (todrop == tilen && (thflags & TH_FIN) == 0)) {
1710 /*
1711 * Any valid FIN must be to the left of the window.
1712 * At this point the FIN must be a duplicate or out
1713 * of sequence; drop it.
1714 */
1715 thflags &= ~TH_FIN;
1716
1717 /*
1718 * Send an ACK to resynchronize and drop any data.
1719 * But keep on processing for RST or ACK.
1720 */
1721 tp->t_flags |= TF_ACKNOW;
1722 todrop = tilen;
1723 tcpstat.tcps_rcvduppack++;
1724 tcpstat.tcps_rcvdupbyte += todrop;
1725 } else {
1726 tcpstat.tcps_rcvpartduppack++;
1727 tcpstat.tcps_rcvpartdupbyte += todrop;
1728 }
1729 m_adj(m, todrop);
1730 th->th_seq += todrop;
1731 tilen -= todrop;
1732 if (th->th_urp > todrop)
1733 th->th_urp -= todrop;
1734 else {
1735 thflags &= ~TH_URG;
1736 th->th_urp = 0;
1737 }
1738 }
1739
1740 /*
1741 * If new data are received on a connection after the
1742 * user processes are gone, then RST the other end.
1743 */
1744 if ((so->so_state & SS_NOFDREF) &&
1745 tp->t_state > TCPS_CLOSE_WAIT && tilen) {
1746 tp = tcp_close(tp);
1747 tcpstat.tcps_rcvafterclose++;
1748 goto dropwithreset;
1749 }
1750
1751 /*
1752 * If segment ends after window, drop trailing data
1753 * (and PUSH and FIN); if nothing left, just ACK.
1754 */
1755 todrop = (th->th_seq+tilen) - (tp->rcv_nxt+tp->rcv_wnd);
1756 if (todrop > 0) {
1757 tcpstat.tcps_rcvpackafterwin++;
1758 if (todrop >= tilen) {
1759 tcpstat.tcps_rcvbyteafterwin += tilen;
1760 /*
1761 * If a new connection request is received
1762 * while in TIME_WAIT, drop the old connection
1763 * and start over if the sequence numbers
1764 * are above the previous ones.
1765 */
1766 if (thflags & TH_SYN &&
1767 tp->t_state == TCPS_TIME_WAIT &&
1768 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1769 #ifdef TCP_COMPAT_42
1770 iss = tp->rcv_nxt + TCP_ISSINCR;
1771 #else
1772 iss = tcp_rndiss_next();
1773 #endif /* TCP_COMPAT_42 */
1774 tp = tcp_close(tp);
1775 goto findpcb;
1776 }
1777 /*
1778 * If window is closed can only take segments at
1779 * window edge, and have to drop data and PUSH from
1780 * incoming segments. Continue processing, but
1781 * remember to ack. Otherwise, drop segment
1782 * and ack.
1783 */
1784 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1785 tp->t_flags |= TF_ACKNOW;
1786 tcpstat.tcps_rcvwinprobe++;
1787 } else
1788 goto dropafterack;
1789 } else
1790 tcpstat.tcps_rcvbyteafterwin += todrop;
1791 m_adj(m, -todrop);
1792 tilen -= todrop;
1793 thflags &= ~(TH_PUSH|TH_FIN);
1794 }
1795
1796 /*
1797 * If last ACK falls within this segment's sequence numbers,
1798 * record its timestamp.
1799 * NOTE that the test is modified according to the latest
1800 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1801 */
1802 if ((to.to_flag & TOF_TS) != 0 &&
1803 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1804 tp->ts_recent_age = tcp_now;
1805 tp->ts_recent = to.to_tsval;
1806 }
1807
1808 /*
1809 * If a SYN is in the window, then this is an
1810 * error and we send an RST and drop the connection.
1811 */
1812 if (thflags & TH_SYN) {
1813 tp = tcp_drop(tp, ECONNRESET);
1814 postevent(so, 0, EV_RESET);
1815 goto dropwithreset;
1816 }
1817
1818 /*
1819 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1820 * flag is on (half-synchronized state), then queue data for
1821 * later processing; else drop segment and return.
1822 */
1823 if ((thflags & TH_ACK) == 0) {
1824 if (tp->t_state == TCPS_SYN_RECEIVED ||
1825 (tp->t_flags & TF_NEEDSYN))
1826 goto step6;
1827 else
1828 goto drop;
1829 }
1830
1831 /*
1832 * Ack processing.
1833 */
1834 switch (tp->t_state) {
1835
1836 /*
1837 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1838 * ESTABLISHED state and continue processing.
1839 * The ACK was checked above.
1840 */
1841 case TCPS_SYN_RECEIVED:
1842
1843 tcpstat.tcps_connects++;
1844 soisconnected(so);
1845 current_active_connections++;
1846
1847 /* Do window scaling? */
1848 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1849 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1850 tp->snd_scale = tp->requested_s_scale;
1851 tp->rcv_scale = tp->request_r_scale;
1852 }
1853 /*
1854 * Upon successful completion of 3-way handshake,
1855 * update cache.CC if it was undefined, pass any queued
1856 * data to the user, and advance state appropriately.
1857 */
1858 if ((taop = tcp_gettaocache(inp)) != NULL &&
1859 taop->tao_cc == 0)
1860 taop->tao_cc = tp->cc_recv;
1861
1862 /*
1863 * Make transitions:
1864 * SYN-RECEIVED -> ESTABLISHED
1865 * SYN-RECEIVED* -> FIN-WAIT-1
1866 */
1867 if (tp->t_flags & TF_NEEDFIN) {
1868 tp->t_state = TCPS_FIN_WAIT_1;
1869 tp->t_flags &= ~TF_NEEDFIN;
1870 } else {
1871 tp->t_state = TCPS_ESTABLISHED;
1872 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1873 }
1874 /*
1875 * If segment contains data or ACK, will call tcp_reass()
1876 * later; if not, do so now to pass queued data to user.
1877 */
1878 if (tilen == 0 && (thflags & TH_FIN) == 0)
1879 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1880 (struct mbuf *)0, isipv6);
1881 tp->snd_wl1 = th->th_seq - 1;
1882 /* fall into ... */
1883
1884 /*
1885 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1886 * ACKs. If the ack is in the range
1887 * tp->snd_una < th->th_ack <= tp->snd_max
1888 * then advance tp->snd_una to th->th_ack and drop
1889 * data from the retransmission queue. If this ACK reflects
1890 * more up to date window information we update our window information.
1891 */
1892 case TCPS_ESTABLISHED:
1893 case TCPS_FIN_WAIT_1:
1894 case TCPS_FIN_WAIT_2:
1895 case TCPS_CLOSE_WAIT:
1896 case TCPS_CLOSING:
1897 case TCPS_LAST_ACK:
1898 case TCPS_TIME_WAIT:
1899
1900 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1901 if (tilen == 0 && tiwin == tp->snd_wnd) {
1902 tcpstat.tcps_rcvdupack++;
1903 /*
1904 * If we have outstanding data (other than
1905 * a window probe), this is a completely
1906 * duplicate ack (ie, window info didn't
1907 * change), the ack is the biggest we've
1908 * seen and we've seen exactly our rexmt
1909 * threshhold of them, assume a packet
1910 * has been dropped and retransmit it.
1911 * Kludge snd_nxt & the congestion
1912 * window so we send only this one
1913 * packet.
1914 *
1915 * We know we're losing at the current
1916 * window size so do congestion avoidance
1917 * (set ssthresh to half the current window
1918 * and pull our congestion window back to
1919 * the new ssthresh).
1920 *
1921 * Dup acks mean that packets have left the
1922 * network (they're now cached at the receiver)
1923 * so bump cwnd by the amount in the receiver
1924 * to keep a constant cwnd packets in the
1925 * network.
1926 */
1927 if (tp->t_timer[TCPT_REXMT] == 0 ||
1928 th->th_ack != tp->snd_una)
1929 tp->t_dupacks = 0;
1930 else if (++tp->t_dupacks == tcprexmtthresh) {
1931 tcp_seq onxt = tp->snd_nxt;
1932 u_int win =
1933 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1934 tp->t_maxseg;
1935
1936 if (win < 2)
1937 win = 2;
1938 tp->snd_ssthresh = win * tp->t_maxseg;
1939 tp->t_timer[TCPT_REXMT] = 0;
1940 tp->t_rtt = 0;
1941 tp->snd_nxt = th->th_ack;
1942 tp->snd_cwnd = tp->t_maxseg;
1943 (void) tcp_output(tp);
1944 tp->snd_cwnd = tp->snd_ssthresh +
1945 tp->t_maxseg * tp->t_dupacks;
1946 if (SEQ_GT(onxt, tp->snd_nxt))
1947 tp->snd_nxt = onxt;
1948 goto drop;
1949 } else if (tp->t_dupacks > tcprexmtthresh) {
1950 tp->snd_cwnd += tp->t_maxseg;
1951 (void) tcp_output(tp);
1952 goto drop;
1953 }
1954 } else
1955 tp->t_dupacks = 0;
1956 break;
1957 }
1958 /*
1959 * If the congestion window was inflated to account
1960 * for the other side's cached packets, retract it.
1961 */
1962 if (tp->t_dupacks >= tcprexmtthresh &&
1963 tp->snd_cwnd > tp->snd_ssthresh)
1964 tp->snd_cwnd = tp->snd_ssthresh;
1965 tp->t_dupacks = 0;
1966 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1967 tcpstat.tcps_rcvacktoomuch++;
1968 goto dropafterack;
1969 }
1970 /*
1971 * If we reach this point, ACK is not a duplicate,
1972 * i.e., it ACKs something we sent.
1973 */
1974 if (tp->t_flags & TF_NEEDSYN) {
1975 /*
1976 * T/TCP: Connection was half-synchronized, and our
1977 * SYN has been ACK'd (so connection is now fully
1978 * synchronized). Go to non-starred state,
1979 * increment snd_una for ACK of SYN, and check if
1980 * we can do window scaling.
1981 */
1982 tp->t_flags &= ~TF_NEEDSYN;
1983 tp->snd_una++;
1984 /* Do window scaling? */
1985 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1986 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1987 tp->snd_scale = tp->requested_s_scale;
1988 tp->rcv_scale = tp->request_r_scale;
1989 }
1990 }
1991
1992 process_ACK:
1993 acked = th->th_ack - tp->snd_una;
1994 tcpstat.tcps_rcvackpack++;
1995 tcpstat.tcps_rcvackbyte += acked;
1996
1997 /*
1998 * If we have a timestamp reply, update smoothed
1999 * round trip time. If no timestamp is present but
2000 * transmit timer is running and timed sequence
2001 * number was acked, update smoothed round trip time.
2002 * Since we now have an rtt measurement, cancel the
2003 * timer backoff (cf., Phil Karn's retransmit alg.).
2004 * Recompute the initial retransmit timer.
2005 */
2006 if (to.to_flag & TOF_TS)
2007 tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
2008 else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
2009 tcp_xmit_timer(tp,tp->t_rtt);
2010
2011 /*
2012 * If all outstanding data is acked, stop retransmit
2013 * timer and remember to restart (more output or persist).
2014 * If there is more data to be acked, restart retransmit
2015 * timer, using current (possibly backed-off) value.
2016 */
2017 if (th->th_ack == tp->snd_max) {
2018 tp->t_timer[TCPT_REXMT] = 0;
2019 needoutput = 1;
2020 } else if (tp->t_timer[TCPT_PERSIST] == 0)
2021 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
2022
2023 /*
2024 * If no data (only SYN) was ACK'd,
2025 * skip rest of ACK processing.
2026 */
2027 if (acked == 0)
2028 goto step6;
2029
2030 /*
2031 * When new data is acked, open the congestion window.
2032 * If the window gives us less than ssthresh packets
2033 * in flight, open exponentially (maxseg per packet).
2034 * Otherwise open linearly: maxseg per window
2035 * (maxseg^2 / cwnd per packet).
2036 */
2037 {
2038 register u_int cw = tp->snd_cwnd;
2039 register u_int incr = tp->t_maxseg;
2040
2041 if (cw > tp->snd_ssthresh)
2042 incr = incr * incr / cw;
2043 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
2044 }
2045 if (acked > so->so_snd.sb_cc) {
2046 tp->snd_wnd -= so->so_snd.sb_cc;
2047 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2048 ourfinisacked = 1;
2049 } else {
2050 sbdrop(&so->so_snd, acked);
2051 tp->snd_wnd -= acked;
2052 ourfinisacked = 0;
2053 }
2054 need_sowwakeup++;
2055 tp->snd_una = th->th_ack;
2056 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2057 tp->snd_nxt = tp->snd_una;
2058
2059 switch (tp->t_state) {
2060
2061 /*
2062 * In FIN_WAIT_1 STATE in addition to the processing
2063 * for the ESTABLISHED state if our FIN is now acknowledged
2064 * then enter FIN_WAIT_2.
2065 */
2066 case TCPS_FIN_WAIT_1:
2067 if (ourfinisacked) {
2068 /*
2069 * If we can't receive any more
2070 * data, then closing user can proceed.
2071 * Starting the timer is contrary to the
2072 * specification, but if we don't get a FIN
2073 * we'll hang forever.
2074 */
2075 if (so->so_state & SS_CANTRCVMORE) {
2076 soisdisconnected(so);
2077 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
2078 }
2079 add_to_time_wait(tp);
2080 current_active_connections--;
2081 tp->t_state = TCPS_FIN_WAIT_2;
2082 }
2083 break;
2084
2085 /*
2086 * In CLOSING STATE in addition to the processing for
2087 * the ESTABLISHED state if the ACK acknowledges our FIN
2088 * then enter the TIME-WAIT state, otherwise ignore
2089 * the segment.
2090 */
2091 case TCPS_CLOSING:
2092 if (ourfinisacked) {
2093 tp->t_state = TCPS_TIME_WAIT;
2094 tcp_canceltimers(tp);
2095 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2096 if (tp->cc_recv != 0 &&
2097 tp->t_duration < TCPTV_MSL)
2098 tp->t_timer[TCPT_2MSL] =
2099 tp->t_rxtcur * TCPTV_TWTRUNC;
2100 else
2101 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2102 add_to_time_wait(tp);
2103 current_active_connections--;
2104 soisdisconnected(so);
2105 }
2106 break;
2107
2108 /*
2109 * In LAST_ACK, we may still be waiting for data to drain
2110 * and/or to be acked, as well as for the ack of our FIN.
2111 * If our FIN is now acknowledged, delete the TCB,
2112 * enter the closed state and return.
2113 */
2114 case TCPS_LAST_ACK:
2115 if (ourfinisacked) {
2116 tp = tcp_close(tp);
2117 goto drop;
2118 }
2119 break;
2120
2121 /*
2122 * In TIME_WAIT state the only thing that should arrive
2123 * is a retransmission of the remote FIN. Acknowledge
2124 * it and restart the finack timer.
2125 */
2126 case TCPS_TIME_WAIT:
2127 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2128 add_to_time_wait(tp);
2129 goto dropafterack;
2130 }
2131 }
2132
2133 step6:
2134 /*
2135 * Update window information.
2136 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2137 */
2138 if ((thflags & TH_ACK) &&
2139 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2140 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2141 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2142 /* keep track of pure window updates */
2143 if (tilen == 0 &&
2144 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2145 tcpstat.tcps_rcvwinupd++;
2146 tp->snd_wnd = tiwin;
2147 tp->snd_wl1 = th->th_seq;
2148 tp->snd_wl2 = th->th_ack;
2149 if (tp->snd_wnd > tp->max_sndwnd)
2150 tp->max_sndwnd = tp->snd_wnd;
2151 needoutput = 1;
2152 }
2153
2154 /*
2155 * Process segments with URG.
2156 */
2157 if ((thflags & TH_URG) && th->th_urp &&
2158 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2159 /*
2160 * This is a kludge, but if we receive and accept
2161 * random urgent pointers, we'll crash in
2162 * soreceive. It's hard to imagine someone
2163 * actually wanting to send this much urgent data.
2164 */
2165 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2166 th->th_urp = 0; /* XXX */
2167 thflags &= ~TH_URG; /* XXX */
2168 goto dodata; /* XXX */
2169 }
2170 /*
2171 * If this segment advances the known urgent pointer,
2172 * then mark the data stream. This should not happen
2173 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2174 * a FIN has been received from the remote side.
2175 * In these states we ignore the URG.
2176 *
2177 * According to RFC961 (Assigned Protocols),
2178 * the urgent pointer points to the last octet
2179 * of urgent data. We continue, however,
2180 * to consider it to indicate the first octet
2181 * of data past the urgent section as the original
2182 * spec states (in one of two places).
2183 */
2184 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2185 tp->rcv_up = th->th_seq + th->th_urp;
2186 so->so_oobmark = so->so_rcv.sb_cc +
2187 (tp->rcv_up - tp->rcv_nxt) - 1;
2188 if (so->so_oobmark == 0) {
2189 so->so_state |= SS_RCVATMARK;
2190 postevent(so, 0, EV_OOB);
2191 }
2192 sohasoutofband(so);
2193 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2194 }
2195 /*
2196 * Remove out of band data so doesn't get presented to user.
2197 * This can happen independent of advancing the URG pointer,
2198 * but if two URG's are pending at once, some out-of-band
2199 * data may creep in... ick.
2200 */
2201 if (th->th_urp <= (u_long)tilen
2202 #if SO_OOBINLINE
2203 && (so->so_options & SO_OOBINLINE) == 0
2204 #endif
2205 )
2206 tcp_pulloutofband(so, th, m);
2207 } else
2208 /*
2209 * If no out of band data is expected,
2210 * pull receive urgent pointer along
2211 * with the receive window.
2212 */
2213 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2214 tp->rcv_up = tp->rcv_nxt;
2215 dodata: /* XXX */
2216
2217 /*
2218 * Process the segment text, merging it into the TCP sequencing queue,
2219 * and arranging for acknowledgment of receipt if necessary.
2220 * This process logically involves adjusting tp->rcv_wnd as data
2221 * is presented to the user (this happens in tcp_usrreq.c,
2222 * case PRU_RCVD). If a FIN has already been received on this
2223 * connection then we just ignore the text.
2224 */
2225 if ((tilen || (thflags&TH_FIN)) &&
2226 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2227 TCP_REASS(tp, th, tilen, m, so, thflags, isipv6, need_sorwakeup);
2228
2229 if (tp->t_flags & TF_DELACK)
2230 {
2231 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
2232 (((thtoti(th)->ti_src.s_addr & 0xffff) << 16) | (thtoti(th)->ti_dst.s_addr & 0xffff)),
2233 th->th_seq, th->th_ack, th->th_win);
2234 }
2235 /*
2236 * Note the amount of data that peer has sent into
2237 * our window, in order to estimate the sender's
2238 * buffer size.
2239 */
2240 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2241 } else {
2242 m_freem(m);
2243 thflags &= ~TH_FIN;
2244 }
2245
2246 /*
2247 * If FIN is received ACK the FIN and let the user know
2248 * that the connection is closing.
2249 */
2250 if (thflags & TH_FIN) {
2251 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2252 socantrcvmore(so);
2253 postevent(so, 0, EV_FIN);
2254 /*
2255 * If connection is half-synchronized
2256 * (ie NEEDSYN flag on) then delay ACK,
2257 * so it may be piggybacked when SYN is sent.
2258 * Otherwise, since we received a FIN then no
2259 * more input can be expected, send ACK now.
2260 */
2261 if (tcp_delack_enabled && (tp->t_flags & TF_NEEDSYN)) {
2262 if (last_active_conn_count > DELACK_BITMASK_THRESH)
2263 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
2264
2265 tp->t_flags |= TF_DELACK;
2266 }
2267 else
2268 tp->t_flags |= TF_ACKNOW;
2269 tp->rcv_nxt++;
2270 }
2271 switch (tp->t_state) {
2272
2273 /*
2274 * In SYN_RECEIVED and ESTABLISHED STATES
2275 * enter the CLOSE_WAIT state.
2276 */
2277 case TCPS_SYN_RECEIVED:
2278 case TCPS_ESTABLISHED:
2279 tp->t_state = TCPS_CLOSE_WAIT;
2280 break;
2281
2282 /*
2283 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2284 * enter the CLOSING state.
2285 */
2286 case TCPS_FIN_WAIT_1:
2287 tp->t_state = TCPS_CLOSING;
2288 break;
2289
2290 /*
2291 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2292 * starting the time-wait timer, turning off the other
2293 * standard timers.
2294 */
2295 case TCPS_FIN_WAIT_2:
2296 tp->t_state = TCPS_TIME_WAIT;
2297 tcp_canceltimers(tp);
2298 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2299 if (tp->cc_recv != 0 &&
2300 tp->t_duration < TCPTV_MSL) {
2301 tp->t_timer[TCPT_2MSL] =
2302 tp->t_rxtcur * TCPTV_TWTRUNC;
2303 /* For transaction client, force ACK now. */
2304 tp->t_flags |= TF_ACKNOW;
2305 }
2306 else
2307 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2308
2309 add_to_time_wait(tp);
2310 soisdisconnected(so);
2311 break;
2312
2313 /*
2314 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2315 */
2316 case TCPS_TIME_WAIT:
2317 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2318 add_to_time_wait(tp);
2319 break;
2320 }
2321 }
2322 #if TCPDEBUG
2323 if (so->so_options & SO_DEBUG) {
2324 #if INET6
2325 if (isipv6)
2326 tcp_saveip._tcp_si6.ip6_plen = tilen;
2327 else
2328 tcp_saveip._tcp_si4.ip_len = tilen;
2329 #else /* INET6 */
2330 tcp_saveip.ip_len = tilen;
2331 #endif /* INET6 */
2332
2333 tcp_trace(TA_INPUT, ostate, tp, (void *)&tcp_saveip,
2334 &tcp_savetcp, 0);
2335 }
2336 #endif
2337
2338 /*
2339 * Return any desired output.
2340 */
2341 if (needoutput || (tp->t_flags & TF_ACKNOW))
2342 (void) tcp_output(tp);
2343 if (need_sorwakeup)
2344 sorwakeup(so);
2345 if (need_sowwakeup)
2346 sowwakeup(so);
2347 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2348 return;
2349
2350 dropafterack:
2351 /*
2352 * Generate an ACK dropping incoming segment if it occupies
2353 * sequence space, where the ACK reflects our state.
2354 *
2355 * We can now skip the test for the RST flag since all
2356 * paths to this code happen after packets containing
2357 * RST have been dropped.
2358 *
2359 * In the SYN-RECEIVED state, don't send an ACK unless the
2360 * segment we received passes the SYN-RECEIVED ACK test.
2361 * If it fails send a RST. This breaks the loop in the
2362 * "LAND" DoS attack, and also prevents an ACK storm
2363 * between two listening ports that have been sent forged
2364 * SYN segments, each with the source address of the other.
2365 */
2366 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2367 (SEQ_GT(tp->snd_una, th->th_ack) ||
2368 SEQ_GT(th->th_ack, tp->snd_max)) )
2369 goto dropwithreset;
2370 #if TCPDEBUG
2371 if (so->so_options & SO_DEBUG) {
2372 #if INET6
2373 if (isipv6)
2374 tcp_saveip._tcp_si6.ip6_plen = tilen;
2375 else
2376 tcp_saveip._tcp_si4.ip_len = tilen;
2377 #else /* INET6 */
2378 tcp_saveip.ip_len = tilen;
2379 #endif /* INET6 */
2380 tcp_trace(TA_DROP, ostate, tp, (void *)&tcp_saveip,
2381 &tcp_savetcp, 0);
2382 }
2383 #endif
2384 m_freem(m);
2385 tp->t_flags |= TF_ACKNOW;
2386 (void) tcp_output(tp);
2387 if (need_sorwakeup)
2388 sorwakeup(so);
2389 if (need_sowwakeup)
2390 sowwakeup(so);
2391 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2392 return;
2393
2394 dropwithreset:
2395 /*
2396 * Generate a RST, dropping incoming segment.
2397 * Make ACK acceptable to originator of segment.
2398 * Don't bother to respond if destination was broadcast/multicast.
2399 */
2400 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2401 goto drop;
2402 #if INET6
2403 if (isipv6) {
2404 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2405 goto drop; /* anycast check is done at the top */
2406 } else
2407 #endif /* INET6 */
2408 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2409 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2410 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2411 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2412 goto drop;
2413 #if TCPDEBUG
2414 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
2415 if (tp == 0) {
2416 #if INET6
2417 if (isipv6)
2418 tcp_saveip._tcp_si6 = *ip6;
2419 else
2420 tcp_saveip._tcp_si4 = *ip;
2421 #else /* INET6 */
2422 tcp_saveip = *ip;
2423 #endif /* INET6 */
2424 }
2425 #if INET6
2426 if (isipv6)
2427 tcp_saveip._tcp_si6.ip6_plen = tilen;
2428 else
2429 tcp_saveip._tcp_si4.ip_len = tilen;
2430 #else /* INET6 */
2431 tcp_saveip.ip_len = tilen;
2432 #endif /* INET6 */
2433 tcp_trace(TA_DROP, ostate, tp, (void *)&tcp_saveip,
2434 &tcp_savetcp, 0);
2435 }
2436 #endif
2437 if (thflags & TH_ACK)
2438 #if INET6
2439 tcp_respond(tp, isipv6 ? (void *)ip6 : (void *)ip, th, m,
2440 (tcp_seq)0, th->th_ack, TH_RST, isipv6);
2441 #else /* INET6 */
2442 tcp_respond(tp, (void *)ip, th, m,
2443 (tcp_seq)0, th->th_ack, TH_RST, isipv6);
2444 #endif /* INET6 */
2445 else {
2446 if (thflags & TH_SYN)
2447 tilen++;
2448 #if INET6
2449 tcp_respond(tp, isipv6 ? (void *)ip6 : (void *)ip, th, m,
2450 th->th_seq+tilen, (tcp_seq)0, TH_RST|TH_ACK,
2451 isipv6);
2452 #else /* INET6 */
2453 tcp_respond(tp, (void *)ip, th, m,
2454 th->th_seq+tilen, (tcp_seq)0, TH_RST|TH_ACK,
2455 isipv6);
2456 #endif /* INET6 */
2457 }
2458 /* destroy temporarily created socket */
2459 if (need_sorwakeup)
2460 sorwakeup(so);
2461 if (need_sowwakeup)
2462 sowwakeup(so);
2463 if (dropsocket)
2464 (void) soabort(so);
2465 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2466 return;
2467
2468 drop:
2469 /*
2470 * Drop space held by incoming segment and return.
2471 */
2472 #if TCPDEBUG
2473 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
2474 if (tp == 0) {
2475 #if INET6
2476 if (isipv6)
2477 tcp_saveip._tcp_si6 = *ip6;
2478 else
2479 tcp_saveip._tcp_si4 = *ip;
2480 #else /* INET6 */
2481 tcp_saveip = *ip;
2482 #endif /* INET6 */
2483 }
2484 #if INET6
2485 if (isipv6)
2486 tcp_saveip._tcp_si6.ip6_plen = tilen;
2487 else
2488 tcp_saveip._tcp_si4.ip_len = tilen;
2489 #else /* INET6 */
2490 tcp_saveip.ip_len = tilen;
2491 #endif /* INET6 */
2492 tcp_trace(TA_DROP, ostate, tp, (void *)&tcp_saveip,
2493 &tcp_savetcp, 0);
2494 }
2495 #endif
2496 m_freem(m);
2497 if (need_sorwakeup)
2498 sorwakeup(so);
2499 if (need_sowwakeup)
2500 sowwakeup(so);
2501 /* destroy temporarily created socket */
2502 if (dropsocket)
2503 (void) soabort(so);
2504 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2505 return;
2506 }
2507
2508 static void
2509 tcp_dooptions(tp, cp, cnt, th, to)
2510 struct tcpcb *tp;
2511 u_char *cp;
2512 int cnt;
2513 struct tcphdr *th;
2514 struct tcpopt *to;
2515 {
2516 u_short mss = 0;
2517 int opt, optlen;
2518
2519 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2520 opt = cp[0];
2521 if (opt == TCPOPT_EOL)
2522 break;
2523 if (opt == TCPOPT_NOP)
2524 optlen = 1;
2525 else {
2526 optlen = cp[1];
2527 if (optlen <= 0)
2528 break;
2529 }
2530 switch (opt) {
2531
2532 default:
2533 continue;
2534
2535 case TCPOPT_MAXSEG:
2536 if (optlen != TCPOLEN_MAXSEG)
2537 continue;
2538 if (!(th->th_flags & TH_SYN))
2539 continue;
2540 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
2541 to->to_maxseg = ntohs(mss);
2542 break;
2543
2544 case TCPOPT_WINDOW:
2545 if (optlen != TCPOLEN_WINDOW)
2546 continue;
2547 if (!(th->th_flags & TH_SYN))
2548 continue;
2549 tp->t_flags |= TF_RCVD_SCALE;
2550 tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2551 break;
2552
2553 case TCPOPT_TIMESTAMP:
2554 if (optlen != TCPOLEN_TIMESTAMP)
2555 continue;
2556 to->to_flag |= TOF_TS;
2557 bcopy((char *)cp + 2,
2558 (char *)&to->to_tsval, sizeof(to->to_tsval));
2559 NTOHL(to->to_tsval);
2560 bcopy((char *)cp + 6,
2561 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2562 NTOHL(to->to_tsecr);
2563
2564 /*
2565 * A timestamp received in a SYN makes
2566 * it ok to send timestamp requests and replies.
2567 */
2568 if (th->th_flags & TH_SYN) {
2569 tp->t_flags |= TF_RCVD_TSTMP;
2570 tp->ts_recent = to->to_tsval;
2571 tp->ts_recent_age = tcp_now;
2572 }
2573 break;
2574 case TCPOPT_CC:
2575 if (optlen != TCPOLEN_CC)
2576 continue;
2577 to->to_flag |= TOF_CC;
2578 bcopy((char *)cp + 2,
2579 (char *)&to->to_cc, sizeof(to->to_cc));
2580 NTOHL(to->to_cc);
2581 /*
2582 * A CC or CC.new option received in a SYN makes
2583 * it ok to send CC in subsequent segments.
2584 */
2585 if (th->th_flags & TH_SYN)
2586 tp->t_flags |= TF_RCVD_CC;
2587 break;
2588 case TCPOPT_CCNEW:
2589 if (optlen != TCPOLEN_CC)
2590 continue;
2591 if (!(th->th_flags & TH_SYN))
2592 continue;
2593 to->to_flag |= TOF_CCNEW;
2594 bcopy((char *)cp + 2,
2595 (char *)&to->to_cc, sizeof(to->to_cc));
2596 NTOHL(to->to_cc);
2597 /*
2598 * A CC or CC.new option received in a SYN makes
2599 * it ok to send CC in subsequent segments.
2600 */
2601 tp->t_flags |= TF_RCVD_CC;
2602 break;
2603 case TCPOPT_CCECHO:
2604 if (optlen != TCPOLEN_CC)
2605 continue;
2606 if (!(th->th_flags & TH_SYN))
2607 continue;
2608 to->to_flag |= TOF_CCECHO;
2609 bcopy((char *)cp + 2,
2610 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2611 NTOHL(to->to_ccecho);
2612 break;
2613 }
2614 }
2615 }
2616
2617 /*
2618 * Pull out of band byte out of a segment so
2619 * it doesn't appear in the user's data queue.
2620 * It is still reflected in the segment length for
2621 * sequencing purposes.
2622 */
2623 static void
2624 tcp_pulloutofband(so, th, m)
2625 struct socket *so;
2626 struct tcphdr *th;
2627 register struct mbuf *m;
2628 {
2629 int cnt = th->th_urp - 1;
2630
2631 while (cnt >= 0) {
2632 if (m->m_len > cnt) {
2633 char *cp = mtod(m, caddr_t) + cnt;
2634 struct tcpcb *tp = sototcpcb(so);
2635
2636 tp->t_iobc = *cp;
2637 tp->t_oobflags |= TCPOOB_HAVEDATA;
2638 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2639 m->m_len--;
2640 return;
2641 }
2642 cnt -= m->m_len;
2643 m = m->m_next;
2644 if (m == 0)
2645 break;
2646 }
2647 panic("tcp_pulloutofband");
2648 }
2649
2650 /*
2651 * Collect new round-trip time estimate
2652 * and update averages and current timeout.
2653 */
2654 static void
2655 tcp_xmit_timer(tp, rtt)
2656 register struct tcpcb *tp;
2657 short rtt;
2658 {
2659 register int delta;
2660
2661 tcpstat.tcps_rttupdated++;
2662 tp->t_rttupdated++;
2663 if (tp->t_srtt != 0) {
2664 /*
2665 * srtt is stored as fixed point with 5 bits after the
2666 * binary point (i.e., scaled by 8). The following magic
2667 * is equivalent to the smoothing algorithm in rfc793 with
2668 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2669 * point). Adjust rtt to origin 0.
2670 */
2671 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2672 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2673
2674 if ((tp->t_srtt += delta) <= 0)
2675 tp->t_srtt = 1;
2676
2677 /*
2678 * We accumulate a smoothed rtt variance (actually, a
2679 * smoothed mean difference), then set the retransmit
2680 * timer to smoothed rtt + 4 times the smoothed variance.
2681 * rttvar is stored as fixed point with 4 bits after the
2682 * binary point (scaled by 16). The following is
2683 * equivalent to rfc793 smoothing with an alpha of .75
2684 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2685 * rfc793's wired-in beta.
2686 */
2687 if (delta < 0)
2688 delta = -delta;
2689 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2690 if ((tp->t_rttvar += delta) <= 0)
2691 tp->t_rttvar = 1;
2692 } else {
2693 /*
2694 * No rtt measurement yet - use the unsmoothed rtt.
2695 * Set the variance to half the rtt (so our first
2696 * retransmit happens at 3*rtt).
2697 */
2698 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2699 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2700 }
2701 tp->t_rtt = 0;
2702 tp->t_rxtshift = 0;
2703
2704 /*
2705 * the retransmit should happen at rtt + 4 * rttvar.
2706 * Because of the way we do the smoothing, srtt and rttvar
2707 * will each average +1/2 tick of bias. When we compute
2708 * the retransmit timer, we want 1/2 tick of rounding and
2709 * 1 extra tick because of +-1/2 tick uncertainty in the
2710 * firing of the timer. The bias will give us exactly the
2711 * 1.5 tick we need. But, because the bias is
2712 * statistical, we have to test that we don't drop below
2713 * the minimum feasible timer (which is 2 ticks).
2714 */
2715 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2716 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2717
2718 /*
2719 * We received an ack for a packet that wasn't retransmitted;
2720 * it is probably safe to discard any error indications we've
2721 * received recently. This isn't quite right, but close enough
2722 * for now (a route might have failed after we sent a segment,
2723 * and the return path might not be symmetrical).
2724 */
2725 tp->t_softerror = 0;
2726 }
2727
2728 /*
2729 * Determine a reasonable value for maxseg size.
2730 * If the route is known, check route for mtu.
2731 * If none, use an mss that can be handled on the outgoing
2732 * interface without forcing IP to fragment; if bigger than
2733 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2734 * to utilize large mbufs. If no route is found, route has no mtu,
2735 * or the destination isn't local, use a default, hopefully conservative
2736 * size (usually 512 or the default IP max size, but no more than the mtu
2737 * of the interface), as we can't discover anything about intervening
2738 * gateways or networks. We also initialize the congestion/slow start
2739 * window to be a single segment if the destination isn't local.
2740 * While looking at the routing entry, we also initialize other path-dependent
2741 * parameters from pre-set or cached values in the routing entry.
2742 *
2743 * Also take into account the space needed for options that we
2744 * send regularly. Make maxseg shorter by that amount to assure
2745 * that we can send maxseg amount of data even when the options
2746 * are present. Store the upper limit of the length of options plus
2747 * data in maxopd.
2748 *
2749 * NOTE that this routine is only called when we process an incoming
2750 * segment, for outgoing segments only tcp_mssopt is called.
2751 *
2752 * In case of T/TCP, we call this routine during implicit connection
2753 * setup as well (offer = -1), to initialize maxseg from the cached
2754 * MSS of our peer.
2755 */
2756 void
2757 tcp_mss(tp, offer, isipv6)
2758 struct tcpcb *tp;
2759 int offer;
2760 #if INET6
2761 int isipv6;
2762 #endif
2763 {
2764 register struct rtentry *rt;
2765 struct ifnet *ifp;
2766 register int rtt, mss;
2767 u_long bufsize;
2768 struct inpcb *inp;
2769 struct socket *so;
2770 struct rmxp_tao *taop;
2771 int origoffer = offer;
2772 #if INET6
2773 int lgminh = isipv6 ? sizeof (struct tcpip6hdr) :
2774 sizeof (struct tcpiphdr);
2775 #else /* INET6 */
2776 #define lgminh (sizeof (struct tcpiphdr))
2777 #endif /* INET6 */
2778
2779 inp = tp->t_inpcb;
2780 #if INET6
2781 if (isipv6)
2782 rt = tcp_rtlookup6(inp);
2783 else
2784 #endif /* INET6 */
2785 rt = tcp_rtlookup(inp);
2786 if (rt == NULL) {
2787 tp->t_maxopd = tp->t_maxseg =
2788 #if INET6
2789 isipv6 ? tcp_v6mssdflt :
2790 #endif /* INET6 */
2791 tcp_mssdflt;
2792 return;
2793 }
2794 ifp = rt->rt_ifp;
2795 so = inp->inp_socket;
2796
2797 taop = rmx_taop(rt->rt_rmx);
2798 /*
2799 * Offer == -1 means that we didn't receive SYN yet,
2800 * use cached value in that case;
2801 */
2802 if (offer == -1)
2803 offer = taop->tao_mssopt;
2804 /*
2805 * Offer == 0 means that there was no MSS on the SYN segment,
2806 * in this case we use tcp_mssdflt.
2807 */
2808 if (offer == 0)
2809 offer =
2810 #if INET6
2811 isipv6 ? tcp_v6mssdflt :
2812 #endif /* INET6 */
2813 tcp_mssdflt;
2814 else
2815 /*
2816 * Sanity check: make sure that maxopd will be large
2817 * enough to allow some data on segments even is the
2818 * all the option space is used (40bytes). Otherwise
2819 * funny things may happen in tcp_output.
2820 */
2821 offer = max(offer, 64);
2822 taop->tao_mssopt = offer;
2823
2824 /*
2825 * While we're here, check if there's an initial rtt
2826 * or rttvar. Convert from the route-table units
2827 * to scaled multiples of the slow timeout timer.
2828 */
2829 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2830 /*
2831 * XXX the lock bit for RTT indicates that the value
2832 * is also a minimum value; this is subject to time.
2833 */
2834 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2835 tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2836 tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2837 tcpstat.tcps_usedrtt++;
2838 if (rt->rt_rmx.rmx_rttvar) {
2839 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2840 (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2841 tcpstat.tcps_usedrttvar++;
2842 } else {
2843 /* default variation is +- 1 rtt */
2844 tp->t_rttvar =
2845 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2846 }
2847 TCPT_RANGESET(tp->t_rxtcur,
2848 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2849 tp->t_rttmin, TCPTV_REXMTMAX);
2850 }
2851 /*
2852 * if there's an mtu associated with the route, use it
2853 * else, use the link mtu.
2854 */
2855 if (rt->rt_rmx.rmx_mtu)
2856 mss = rt->rt_rmx.rmx_mtu - lgminh;
2857 else
2858 mss =
2859 #if INET6
2860 isipv6 ? nd_ifinfo[rt->rt_ifp->if_index].linkmtu :
2861 #endif
2862 ifp->if_mtu - lgminh;
2863
2864 if (rt->rt_rmx.rmx_mtu == 0) {
2865 #if INET6
2866 if (isipv6) {
2867 if (!in6_localaddr(&inp->in6p_faddr))
2868 mss = min(mss, tcp_v6mssdflt);
2869 } else
2870 #endif /* INET6 */
2871 if (!in_localaddr(inp->inp_faddr))
2872 mss = min(mss, tcp_mssdflt);
2873 }
2874 mss = min(mss, offer);
2875 /*
2876 * maxopd stores the maximum length of data AND options
2877 * in a segment; maxseg is the amount of data in a normal
2878 * segment. We need to store this value (maxopd) apart
2879 * from maxseg, because now every segment carries options
2880 * and thus we normally have somewhat less data in segments.
2881 */
2882 tp->t_maxopd = mss;
2883
2884 /*
2885 * In case of T/TCP, origoffer==-1 indicates, that no segments
2886 * were received yet. In this case we just guess, otherwise
2887 * we do the same as before T/TCP.
2888 */
2889 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2890 (origoffer == -1 ||
2891 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2892 mss -= TCPOLEN_TSTAMP_APPA;
2893 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2894 (origoffer == -1 ||
2895 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2896 mss -= TCPOLEN_CC_APPA;
2897
2898 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2899 if (mss > MCLBYTES)
2900 mss &= ~(MCLBYTES-1);
2901 #else
2902 if (mss > MCLBYTES)
2903 mss = mss / MCLBYTES * MCLBYTES;
2904 #endif
2905 /*
2906 * If there's a pipesize, change the socket buffer
2907 * to that size. Make the socket buffers an integral
2908 * number of mss units; if the mss is larger than
2909 * the socket buffer, decrease the mss.
2910 */
2911 #if RTV_SPIPE
2912 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2913 #endif
2914 bufsize = so->so_snd.sb_hiwat;
2915 if (bufsize < mss)
2916 mss = bufsize;
2917 else {
2918 bufsize = roundup(bufsize, mss);
2919 if (bufsize > sb_max)
2920 bufsize = sb_max;
2921 (void)sbreserve(&so->so_snd, bufsize);
2922 }
2923 tp->t_maxseg = mss;
2924
2925 #if RTV_RPIPE
2926 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2927 #endif
2928 bufsize = so->so_rcv.sb_hiwat;
2929 if (bufsize > mss) {
2930 bufsize = roundup(bufsize, mss);
2931 if (bufsize > sb_max)
2932 bufsize = sb_max;
2933 (void)sbreserve(&so->so_rcv, bufsize);
2934 }
2935 /*
2936 * Don't force slow-start on local network.
2937 */
2938 #if INET6
2939 if (isipv6) {
2940 if (!in6_localaddr(&inp->in6p_faddr))
2941 tp->snd_cwnd = mss;
2942 } else
2943 #endif /* INET6 */
2944 if (!in_localaddr(inp->inp_faddr))
2945 tp->snd_cwnd = mss;
2946
2947 if (rt->rt_rmx.rmx_ssthresh) {
2948 /*
2949 * There's some sort of gateway or interface
2950 * buffer limit on the path. Use this to set
2951 * the slow start threshhold, but set the
2952 * threshold to no less than 2*mss.
2953 */
2954 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2955 tcpstat.tcps_usedssthresh++;
2956 }
2957 }
2958
2959 /*
2960 * Determine the MSS option to send on an outgoing SYN.
2961 */
2962 int
2963 tcp_mssopt(tp, isipv6)
2964 struct tcpcb *tp;
2965 #if INET6
2966 int isipv6;
2967 #endif
2968 {
2969 struct rtentry *rt;
2970 int mss;
2971 #if INET6
2972 int lgminh = isipv6 ? sizeof (struct tcpip6hdr) :
2973 sizeof (struct tcpiphdr);
2974 #else /* INET6 */
2975 #define lgminh (sizeof (struct tcpiphdr))
2976 #endif /* INET6 */
2977
2978 #if INET6
2979 if (isipv6)
2980 rt = tcp_rtlookup6(tp->t_inpcb);
2981 else
2982 #endif /* INET6 */
2983 rt = tcp_rtlookup(tp->t_inpcb);
2984 if (rt == NULL)
2985 return
2986 #if INET6
2987 isipv6 ? tcp_v6mssdflt :
2988 #endif /* INET6 */
2989 tcp_mssdflt;
2990
2991 mss = rt->rt_ifp->if_mtu - lgminh;
2992
2993 return mss;
2994 }