]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/tcp_input.c
599c6e0d958ffed549a549877b37260b5062889a
[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 /* Unscale the window into a 32-bit value. */
726 if ((thflags & TH_SYN) == 0)
727 tiwin = th->th_win << tp->snd_scale;
728 else
729 tiwin = th->th_win;
730
731 so = inp->inp_socket;
732 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
733 #if TCPDEBUG
734 if (so->so_options & SO_DEBUG) {
735 ostate = tp->t_state;
736 #if INET6
737 if (isipv6)
738 tcp_saveip._tcp_si6 = *ip6;
739 else
740 tcp_saveip._tcp_si4 = *ip;
741 #else /* INET6 */
742 tcp_saveip = *ip;
743 #endif /* INET6 */
744
745 tcp_savetcp = *th;
746 }
747 #endif
748 if (so->so_options & SO_ACCEPTCONN) {
749 register struct tcpcb *tp0 = tp;
750 struct socket *so2;
751 #if IPSEC
752 struct socket *oso;
753 #endif
754 #if INET6
755 struct inpcb *oinp = sotoinpcb(so);
756 #endif /* INET6 */
757
758 #if !IPSEC
759 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
760 /*
761 * Note: dropwithreset makes sure we don't
762 * send a RST in response to a RST.
763 */
764 if (thflags & TH_ACK) {
765 tcpstat.tcps_badsyn++;
766 goto dropwithreset;
767 }
768 goto drop;
769 }
770 #endif
771 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_START,0,0,0,0,0);
772 so2 = sonewconn(so, 0);
773
774
775 if (so2 == 0) {
776 tcpstat.tcps_listendrop++;
777 so2 = sodropablereq(so);
778 if (so2) {
779 tcp_drop(sototcpcb(so2), ETIMEDOUT);
780 so2 = sonewconn(so, 0);
781 }
782 if (!so2)
783 goto drop;
784 }
785 #if IPSEC
786 oso = so;
787 #endif
788 so = so2;
789 /*
790 * This is ugly, but ....
791 *
792 * Mark socket as temporary until we're
793 * committed to keeping it. The code at
794 * ``drop'' and ``dropwithreset'' check the
795 * flag dropsocket to see if the temporary
796 * socket created here should be discarded.
797 * We mark the socket as discardable until
798 * we're committed to it below in TCPS_LISTEN.
799 */
800 dropsocket++;
801 inp = (struct inpcb *)so->so_pcb;
802 #if INET6
803 if (isipv6)
804 inp->in6p_laddr = ip6->ip6_dst;
805 else {
806 if (ip6_mapped_addr_on) {
807 inp->inp_vflag &= ~INP_IPV6;
808 inp->inp_vflag |= INP_IPV4;
809 }
810 #endif /* INET6 */
811 inp->inp_laddr = ip->ip_dst;
812 #if INET6
813 }
814 #endif /* INET6 */
815
816 inp->inp_lport = th->th_dport;
817 if (in_pcbinshash(inp) != 0) {
818 /*
819 * Undo the assignments above if we failed to put
820 * the PCB on the hash lists.
821 */
822 #if INET6
823 if (isipv6)
824 inp->in6p_laddr = in6addr_any;
825 else
826 #endif /* INET6 */
827 inp->inp_laddr.s_addr = INADDR_ANY;
828 inp->inp_lport = 0;
829 goto drop;
830 }
831 #if IPSEC
832 /*
833 * from IPsec perspective, it is important to do it
834 * after making actual listening socket.
835 * otherwise, cached security association will bark.
836 *
837 * Subject: (KAME-snap 748)
838 * From: Wayne Knowles <w.knowles@niwa.cri.nz>
839 */
840 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
841 /*
842 * Note: dropwithreset makes sure we don't
843 * send a RST in response to a RST.
844 */
845 if (thflags & TH_ACK) {
846 tcpstat.tcps_badsyn++;
847 goto dropwithreset;
848 }
849 goto drop;
850 }
851 #endif
852 #if INET6
853 if (isipv6) {
854 struct ip6_recvpktopts newopts;
855
856 /*
857 * Inherit socket options from the listening
858 * socket.
859 * Note that in6p_inputopts are not (even
860 * should not be) copied, since it stores
861 * previously received options and is used to
862 * detect if each new option is different than
863 * the previous one and hence should be passed
864 * to a user.
865 * If we copied in6p_inputopts, a user would
866 * not be able to receive options just after
867 * calling the accept system call.
868 */
869 inp->inp_flags |=
870 oinp->inp_flags & INP_CONTROLOPTS;
871 if (oinp->in6p_outputopts)
872 inp->in6p_outputopts =
873 ip6_copypktopts(oinp->in6p_outputopts,
874 M_NOWAIT);
875 } else
876 #endif /* INET6 */
877 inp->inp_options = ip_srcroute();
878 #if IPSEC
879 /* copy old policy into new socket's */
880 if (ipsec_copy_policy(sotoinpcb(oso)->inp_sp,
881 inp->inp_sp))
882 printf("tcp_input: could not copy policy\n");
883 #endif
884
885 tp = intotcpcb(inp);
886 tp->t_state = TCPS_LISTEN;
887 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
888
889 /* Compute proper scaling value from buffer space */
890 while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
891 TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
892 tp->request_r_scale++;
893
894 KERNEL_DEBUG(DBG_FNC_TCP_NEWCONN | DBG_FUNC_END,0,0,0,0,0);
895 }
896 }
897
898 #if INET6
899 /* save packet options if user wanted */
900 if (isipv6 && (inp->in6p_flags & INP_CONTROLOPTS) != 0) {
901 struct ip6_recvpktopts opts6;
902
903 /*
904 * Temporarily re-adjusting the mbuf before ip6_savecontrol(),
905 * which is necessary for FreeBSD only due to difference from
906 * other BSD stacks.
907 * XXX: we'll soon make a more natural fix after getting a
908 * consensus.
909 */
910 #ifndef DEFER_MADJ
911 m->m_data -= hdroptlen;
912 m->m_len += hdroptlen;
913 #endif
914 ip6_savecontrol(inp, ip6, m, &opts6, &inp->in6p_inputopts);
915 if (inp->in6p_inputopts)
916 ip6_update_recvpcbopt(inp->in6p_inputopts, &opts6);
917 if (opts6.head) {
918 if (sbappendcontrol(&inp->in6p_socket->so_rcv,
919 NULL, opts6.head)
920 == 0)
921 m_freem(opts6.head);
922 }
923 #ifndef DEFER_MADJ
924 m->m_data += hdroptlen; /* XXX */
925 m->m_len -= hdroptlen; /* XXX */
926 #endif
927 }
928 #endif /* INET6 */
929
930 /*
931 * Segment received on connection.
932 * Reset idle time and keep-alive timer.
933 */
934 tp->t_idle = 0;
935 if (TCPS_HAVEESTABLISHED(tp->t_state))
936 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
937
938 /*
939 * Process options if not in LISTEN state,
940 * else do it below (after getting remote address).
941 */
942 if (tp->t_state != TCPS_LISTEN && optp)
943 tcp_dooptions(tp, optp, optlen, th, &to);
944 if (th->th_flags & TH_SYN)
945 tcp_mss(tp, to.to_maxseg, isipv6); /* sets t_maxseg */
946
947 /*
948 * Header prediction: check for the two common cases
949 * of a uni-directional data xfer. If the packet has
950 * no control flags, is in-sequence, the window didn't
951 * change and we're not retransmitting, it's a
952 * candidate. If the length is zero and the ack moved
953 * forward, we're the sender side of the xfer. Just
954 * free the data acked & wake any higher level process
955 * that was blocked waiting for space. If the length
956 * is non-zero and the ack didn't move, we're the
957 * receiver side. If we're getting packets in-order
958 * (the reassembly queue is empty), add the data to
959 * the socket buffer and note that we need a delayed ack.
960 * Make sure that the hidden state-flags are also off.
961 * Since we check for TCPS_ESTABLISHED above, it can only
962 * be TH_NEEDSYN.
963 */
964 if (tp->t_state == TCPS_ESTABLISHED &&
965 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
966 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
967 ((to.to_flag & TOF_TS) == 0 ||
968 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
969 /*
970 * Using the CC option is compulsory if once started:
971 * the segment is OK if no T/TCP was negotiated or
972 * if the segment has a CC option equal to CCrecv
973 */
974 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
975 ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
976 th->th_seq == tp->rcv_nxt &&
977 tiwin && tiwin == tp->snd_wnd &&
978 tp->snd_nxt == tp->snd_max) {
979
980 /*
981 * If last ACK falls within this segment's sequence numbers,
982 * record the timestamp.
983 * NOTE that the test is modified according to the latest
984 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
985 */
986 if ((to.to_flag & TOF_TS) != 0 &&
987 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
988 tp->ts_recent_age = tcp_now;
989 tp->ts_recent = to.to_tsval;
990 }
991
992 if (tilen == 0) {
993 if (SEQ_GT(th->th_ack, tp->snd_una) &&
994 SEQ_LEQ(th->th_ack, tp->snd_max) &&
995 tp->snd_cwnd >= tp->snd_wnd &&
996 tp->t_dupacks < tcprexmtthresh) {
997 /*
998 * this is a pure ack for outstanding data.
999 */
1000 ++tcpstat.tcps_predack;
1001 if ((to.to_flag & TOF_TS) != 0)
1002 tcp_xmit_timer(tp,
1003 tcp_now - to.to_tsecr + 1);
1004 else if (tp->t_rtt &&
1005 SEQ_GT(th->th_ack, tp->t_rtseq))
1006 tcp_xmit_timer(tp, tp->t_rtt);
1007 acked = th->th_ack - tp->snd_una;
1008 tcpstat.tcps_rcvackpack++;
1009 tcpstat.tcps_rcvackbyte += acked;
1010 sbdrop(&so->so_snd, acked);
1011 tp->snd_una = th->th_ack;
1012 m_freem(m);
1013 #if INET6
1014 /* some progress has been done */
1015 if (isipv6)
1016 ND6_HINT(tp);
1017 #endif
1018
1019 /*
1020 * If all outstanding data are acked, stop
1021 * retransmit timer, otherwise restart timer
1022 * using current (possibly backed-off) value.
1023 * If process is waiting for space,
1024 * wakeup/selwakeup/signal. If data
1025 * are ready to send, let tcp_output
1026 * decide between more output or persist.
1027 */
1028 if (tp->snd_una == tp->snd_max)
1029 tp->t_timer[TCPT_REXMT] = 0;
1030 else if (tp->t_timer[TCPT_PERSIST] == 0)
1031 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1032
1033 if (so->so_snd.sb_cc)
1034 (void) tcp_output(tp);
1035 sowwakeup(so);
1036 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
1037 return;
1038 }
1039 } else if (th->th_ack == tp->snd_una &&
1040 tp->segq.lh_first == NULL &&
1041 tilen <= sbspace(&so->so_rcv)) {
1042 /*
1043 * this is a pure, in-sequence data packet
1044 * with nothing on the reassembly queue and
1045 * we have enough buffer space to take it.
1046 */
1047 ++tcpstat.tcps_preddat;
1048 tp->rcv_nxt += tilen;
1049 tcpstat.tcps_rcvpack++;
1050 tcpstat.tcps_rcvbyte += tilen;
1051 #if INET6
1052 /* some progress has been done */
1053 if (isipv6)
1054 ND6_HINT(tp);
1055 #endif
1056 sbappend(&so->so_rcv, m);
1057 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
1058 (((thtoti(th)->ti_src.s_addr & 0xffff) << 16) | (thtoti(th)->ti_dst.s_addr & 0xffff)),
1059 th->th_seq, th->th_ack, th->th_win);
1060 if (tcp_delack_enabled) {
1061 if (last_active_conn_count > DELACK_BITMASK_THRESH)
1062 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
1063 tp->t_flags |= TF_DELACK;
1064 } else {
1065 tp->t_flags |= TF_ACKNOW;
1066 tcp_output(tp);
1067 }
1068 sorwakeup(so);
1069 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
1070 return;
1071 }
1072 }
1073
1074 /*
1075 * Calculate amount of space in receive window,
1076 * and then do TCP input processing.
1077 * Receive window is amount of space in rcv queue,
1078 * but not less than advertised window.
1079 */
1080 { int win;
1081
1082 win = sbspace(&so->so_rcv);
1083 if (win < 0)
1084 win = 0;
1085 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1086 }
1087
1088 switch (tp->t_state) {
1089
1090 /*
1091 * If the state is LISTEN then ignore segment if it contains an RST.
1092 * If the segment contains an ACK then it is bad and send a RST.
1093 * If it does not contain a SYN then it is not interesting; drop it.
1094 * If it is from this socket, drop it, it must be forged.
1095 * Don't bother responding if the destination was a broadcast.
1096 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
1097 * tp->iss, and send a segment:
1098 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
1099 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
1100 * Fill in remote peer address fields if not previously specified.
1101 * Enter SYN_RECEIVED state, and process any other fields of this
1102 * segment in this state.
1103 */
1104 case TCPS_LISTEN: {
1105 register struct sockaddr_in *sin;
1106 #if 0
1107 register struct sockaddr_in6 *sin6;
1108 #endif
1109
1110 if (thflags & TH_RST)
1111 goto drop;
1112 if (thflags & TH_ACK)
1113 goto dropwithreset;
1114 if ((thflags & TH_SYN) == 0)
1115 goto drop;
1116 if (th->th_dport == th->th_sport) {
1117 #if INET6
1118 if (isipv6) {
1119 if (IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst,
1120 &ip6->ip6_src))
1121 goto drop;
1122 } else
1123 #endif /* INET6 */
1124 if (ip->ip_dst.s_addr == ip->ip_src.s_addr)
1125 goto drop;
1126 }
1127
1128 #if INET6
1129 if (isipv6) {
1130 if (m->m_flags & (M_BCAST|M_MCAST) ||
1131 IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
1132 goto drop;
1133 #if 1
1134 /*
1135 * Perhaps this should be a call/macro
1136 * to a function like in6_pcbconnect(), but almost
1137 * all of the checks have been done: we know
1138 * that the association is unique, and the
1139 * local address is always set here.
1140 */
1141 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1142 inp->in6p_laddr = ip6->ip6_dst;
1143 inp->in6p_faddr = ip6->ip6_src;
1144 inp->inp_fport = th->th_sport;
1145
1146 /* TODO: flowinfo initialization */
1147
1148 in_pcbrehash(inp);
1149 #else
1150 MALLOC(sin6, struct sockaddr_in6 *, sizeof *sin6,
1151 M_SONAME, M_NOWAIT);
1152 if (sin6 == NULL)
1153 goto drop;
1154 bzero(sin6, sizeof(*sin6));
1155 sin6->sin6_family = AF_INET6;
1156 sin6->sin6_len = sizeof(*sin6);
1157 sin6->sin6_addr = ip6->ip6_src;
1158 sin6->sin6_port = th->th_sport;
1159 laddr6 = inp->in6p_laddr;
1160 if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr))
1161 inp->in6p_laddr = ip6->ip6_dst;
1162 if (in6_pcbconnect(inp, (struct sockaddr *)sin6,
1163 &proc0)) {
1164 inp->in6p_laddr = laddr6;
1165 FREE(sin6, M_SONAME);
1166 goto drop;
1167 }
1168 FREE(sin6, M_SONAME);
1169 #endif
1170 }
1171 else {
1172 #endif /* INET6 */
1173 /*
1174 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
1175 * in_broadcast() should never return true on a received
1176 * packet with M_BCAST not set.
1177 */
1178 if (m->m_flags & (M_BCAST|M_MCAST) ||
1179 IN_MULTICAST(ntohl(ip->ip_dst.s_addr)))
1180 goto drop;
1181 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
1182 M_NOWAIT);
1183 if (sin == NULL)
1184 goto drop;
1185 sin->sin_family = AF_INET;
1186 sin->sin_len = sizeof(*sin);
1187 sin->sin_addr = ip->ip_src;
1188 sin->sin_port = th->th_sport;
1189 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
1190 laddr = inp->inp_laddr;
1191 if (inp->inp_laddr.s_addr == INADDR_ANY)
1192 inp->inp_laddr = ip->ip_dst;
1193 if (in_pcbconnect(inp, (struct sockaddr *)sin, &proc0)) {
1194 inp->inp_laddr = laddr;
1195 FREE(sin, M_SONAME);
1196 goto drop;
1197 }
1198 FREE(sin, M_SONAME);
1199 #if INET6
1200 }
1201 #endif /* INET6 */
1202
1203 tp->t_template = tcp_template(tp);
1204 if (tp->t_template == 0) {
1205 tp = tcp_drop(tp, ENOBUFS);
1206 dropsocket = 0; /* socket is already gone */
1207 goto drop;
1208 }
1209 if ((taop = tcp_gettaocache(inp)) == NULL) {
1210 taop = &tao_noncached;
1211 bzero(taop, sizeof(*taop));
1212 }
1213 tcp_dooptions(tp, optp, optlen, th, &to);
1214 if (th->th_flags & TH_SYN)
1215 tcp_mss(tp, to.to_maxseg, isipv6); /* sets t_maxseg */
1216 if (iss)
1217 tp->iss = iss;
1218 else {
1219 #ifdef TCP_COMPAT_42
1220 tcp_iss += TCP_ISSINCR/2;
1221 tp->iss = tcp_iss;
1222 #else
1223 tp->iss = tcp_rndiss_next();
1224 #endif /* TCP_COMPAT_42 */
1225 }
1226 tp->irs = th->th_seq;
1227 tcp_sendseqinit(tp);
1228 tcp_rcvseqinit(tp);
1229 /*
1230 * Initialization of the tcpcb for transaction;
1231 * set SND.WND = SEG.WND,
1232 * initialize CCsend and CCrecv.
1233 */
1234 tp->snd_wnd = tiwin; /* initial send-window */
1235 tp->cc_send = CC_INC(tcp_ccgen);
1236 tp->cc_recv = to.to_cc;
1237 /*
1238 * Perform TAO test on incoming CC (SEG.CC) option, if any.
1239 * - compare SEG.CC against cached CC from the same host,
1240 * if any.
1241 * - if SEG.CC > chached value, SYN must be new and is accepted
1242 * immediately: save new CC in the cache, mark the socket
1243 * connected, enter ESTABLISHED state, turn on flag to
1244 * send a SYN in the next segment.
1245 * A virtual advertised window is set in rcv_adv to
1246 * initialize SWS prevention. Then enter normal segment
1247 * processing: drop SYN, process data and FIN.
1248 * - otherwise do a normal 3-way handshake.
1249 */
1250 if ((to.to_flag & TOF_CC) != 0) {
1251 if (((tp->t_flags & TF_NOPUSH) != 0) &&
1252 taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
1253
1254 taop->tao_cc = to.to_cc;
1255 if (tp->t_state != TCPS_ESTABLISHED)
1256 current_active_connections++;
1257
1258 tp->t_state = TCPS_ESTABLISHED;
1259
1260 /*
1261 * If there is a FIN, or if there is data and the
1262 * connection is local, then delay SYN,ACK(SYN) in
1263 * the hope of piggy-backing it on a response
1264 * segment. Otherwise must send ACK now in case
1265 * the other side is slow starting.
1266 */
1267 if (tcp_delack_enabled &&
1268 ((thflags & TH_FIN) ||
1269 (tilen != 0 &&
1270 #if INET6
1271 (isipv6 && in6_localaddr(&inp->in6p_faddr))
1272 ||
1273 (!isipv6 &&
1274 #endif /* INET6 */
1275 in_localaddr(inp->inp_faddr)
1276 #if INET6
1277 )
1278 #endif /* INET6 */
1279 ))) {
1280 if (last_active_conn_count > DELACK_BITMASK_THRESH)
1281 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
1282
1283 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
1284 }
1285 else
1286 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1287
1288 /*
1289 * Limit the `virtual advertised window' to TCP_MAXWIN
1290 * here. Even if we requested window scaling, it will
1291 * become effective only later when our SYN is acked.
1292 */
1293 tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
1294 tcpstat.tcps_connects++;
1295 soisconnected(so);
1296 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
1297 dropsocket = 0; /* committed to socket */
1298 tcpstat.tcps_accepts++;
1299 goto trimthenstep6;
1300 }
1301 /* else do standard 3-way handshake */
1302 } else {
1303 /*
1304 * No CC option, but maybe CC.NEW:
1305 * invalidate cached value.
1306 */
1307 taop->tao_cc = 0;
1308 }
1309 /*
1310 * TAO test failed or there was no CC option,
1311 * do a standard 3-way handshake.
1312 */
1313 tp->t_flags |= TF_ACKNOW;
1314 tp->t_state = TCPS_SYN_RECEIVED;
1315 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
1316 dropsocket = 0; /* committed to socket */
1317 tcpstat.tcps_accepts++;
1318 goto trimthenstep6;
1319 }
1320
1321 /*
1322 * If the state is SYN_RECEIVED:
1323 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1324 */
1325 case TCPS_SYN_RECEIVED:
1326 if ((thflags & TH_ACK) &&
1327 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1328 SEQ_GT(th->th_ack, tp->snd_max)))
1329 goto dropwithreset;
1330 break;
1331
1332 /*
1333 * If the state is SYN_SENT:
1334 * if seg contains an ACK, but not for our SYN, drop the input.
1335 * if seg contains a RST, then drop the connection.
1336 * if seg does not contain SYN, then drop it.
1337 * Otherwise this is an acceptable SYN segment
1338 * initialize tp->rcv_nxt and tp->irs
1339 * if seg contains ack then advance tp->snd_una
1340 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1341 * arrange for segment to be acked (eventually)
1342 * continue processing rest of data/controls, beginning with URG
1343 */
1344 case TCPS_SYN_SENT:
1345 if ((taop = tcp_gettaocache(inp)) == NULL) {
1346 taop = &tao_noncached;
1347 bzero(taop, sizeof(*taop));
1348 }
1349
1350 if ((thflags & TH_ACK) &&
1351 (SEQ_LEQ(th->th_ack, tp->iss) ||
1352 SEQ_GT(th->th_ack, tp->snd_max))) {
1353 /*
1354 * If we have a cached CCsent for the remote host,
1355 * hence we haven't just crashed and restarted,
1356 * do not send a RST. This may be a retransmission
1357 * from the other side after our earlier ACK was lost.
1358 * Our new SYN, when it arrives, will serve as the
1359 * needed ACK.
1360 */
1361 if (taop->tao_ccsent != 0)
1362 goto drop;
1363 else
1364 goto dropwithreset;
1365 }
1366 if (thflags & TH_RST) {
1367 if (thflags & TH_ACK) {
1368 tp = tcp_drop(tp, ECONNREFUSED);
1369 postevent(so, 0, EV_RESET);
1370 }
1371 goto drop;
1372 }
1373 if ((thflags & TH_SYN) == 0)
1374 goto drop;
1375 tp->snd_wnd = th->th_win; /* initial send window */
1376 tp->cc_recv = to.to_cc; /* foreign CC */
1377
1378 tp->irs = th->th_seq;
1379 tcp_rcvseqinit(tp);
1380 if (thflags & TH_ACK) {
1381 /*
1382 * Our SYN was acked. If segment contains CC.ECHO
1383 * option, check it to make sure this segment really
1384 * matches our SYN. If not, just drop it as old
1385 * duplicate, but send an RST if we're still playing
1386 * by the old rules. If no CC.ECHO option, make sure
1387 * we don't get fooled into using T/TCP.
1388 */
1389 if (to.to_flag & TOF_CCECHO) {
1390 if (tp->cc_send != to.to_ccecho)
1391 if (taop->tao_ccsent != 0)
1392 goto drop;
1393 else
1394 goto dropwithreset;
1395 } else
1396 tp->t_flags &= ~TF_RCVD_CC;
1397 tcpstat.tcps_connects++;
1398 soisconnected(so);
1399 /* Do window scaling on this connection? */
1400 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1401 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1402 tp->snd_scale = tp->requested_s_scale;
1403 tp->rcv_scale = tp->request_r_scale;
1404 }
1405 /* Segment is acceptable, update cache if undefined. */
1406 if (taop->tao_ccsent == 0)
1407 taop->tao_ccsent = to.to_ccecho;
1408
1409 tp->rcv_adv += tp->rcv_wnd;
1410 tp->snd_una++; /* SYN is acked */
1411 /*
1412 * If there's data, delay ACK; if there's also a FIN
1413 * ACKNOW will be turned on later.
1414 */
1415 if (tcp_delack_enabled && tilen != 0) {
1416 if (last_active_conn_count > DELACK_BITMASK_THRESH)
1417 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
1418 tp->t_flags |= TF_DELACK;
1419 }
1420 else
1421 tp->t_flags |= TF_ACKNOW;
1422 /*
1423 * Received <SYN,ACK> in SYN_SENT[*] state.
1424 * Transitions:
1425 * SYN_SENT --> ESTABLISHED
1426 * SYN_SENT* --> FIN_WAIT_1
1427 */
1428 if (tp->t_flags & TF_NEEDFIN) {
1429 tp->t_state = TCPS_FIN_WAIT_1;
1430 tp->t_flags &= ~TF_NEEDFIN;
1431 thflags &= ~TH_SYN;
1432 } else {
1433 if (tp->t_state != TCPS_ESTABLISHED)
1434 current_active_connections++;
1435 tp->t_state = TCPS_ESTABLISHED;
1436 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1437 }
1438 } else {
1439 /*
1440 * Received initial SYN in SYN-SENT[*] state => simul-
1441 * taneous open. If segment contains CC option and there is
1442 * a cached CC, apply TAO test; if it succeeds, connection is
1443 * half-synchronized. Otherwise, do 3-way handshake:
1444 * SYN-SENT -> SYN-RECEIVED
1445 * SYN-SENT* -> SYN-RECEIVED*
1446 * If there was no CC option, clear cached CC value.
1447 */
1448 tp->t_flags |= TF_ACKNOW;
1449 tp->t_timer[TCPT_REXMT] = 0;
1450 if (to.to_flag & TOF_CC) {
1451 if (taop->tao_cc != 0 &&
1452 CC_GT(to.to_cc, taop->tao_cc)) {
1453 /*
1454 * update cache and make transition:
1455 * SYN-SENT -> ESTABLISHED*
1456 * SYN-SENT* -> FIN-WAIT-1*
1457 */
1458 taop->tao_cc = to.to_cc;
1459 if (tp->t_flags & TF_NEEDFIN) {
1460 tp->t_state = TCPS_FIN_WAIT_1;
1461 tp->t_flags &= ~TF_NEEDFIN;
1462 } else {
1463 if (tp->t_state != TCPS_ESTABLISHED)
1464 current_active_connections++;
1465 tp->t_state = TCPS_ESTABLISHED;
1466 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1467 }
1468 tp->t_flags |= TF_NEEDSYN;
1469 } else
1470 tp->t_state = TCPS_SYN_RECEIVED;
1471 } else {
1472 /* CC.NEW or no option => invalidate cache */
1473 taop->tao_cc = 0;
1474 tp->t_state = TCPS_SYN_RECEIVED;
1475 }
1476 }
1477
1478 trimthenstep6:
1479 /*
1480 * Advance th->th_seq to correspond to first data byte.
1481 * If data, trim to stay within window,
1482 * dropping FIN if necessary.
1483 */
1484 th->th_seq++;
1485 if (tilen > tp->rcv_wnd) {
1486 todrop = tilen - tp->rcv_wnd;
1487 m_adj(m, -todrop);
1488 tilen = tp->rcv_wnd;
1489 thflags &= ~TH_FIN;
1490 tcpstat.tcps_rcvpackafterwin++;
1491 tcpstat.tcps_rcvbyteafterwin += todrop;
1492 }
1493 tp->snd_wl1 = th->th_seq - 1;
1494 tp->rcv_up = th->th_seq;
1495 /*
1496 * Client side of transaction: already sent SYN and data.
1497 * If the remote host used T/TCP to validate the SYN,
1498 * our data will be ACK'd; if so, enter normal data segment
1499 * processing in the middle of step 5, ack processing.
1500 * Otherwise, goto step 6.
1501 */
1502 if (thflags & TH_ACK)
1503 goto process_ACK;
1504 goto step6;
1505 /*
1506 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1507 * if segment contains a SYN and CC [not CC.NEW] option:
1508 * if state == TIME_WAIT and connection duration > MSL,
1509 * drop packet and send RST;
1510 *
1511 * if SEG.CC > CCrecv then is new SYN, and can implicitly
1512 * ack the FIN (and data) in retransmission queue.
1513 * Complete close and delete TCPCB. Then reprocess
1514 * segment, hoping to find new TCPCB in LISTEN state;
1515 *
1516 * else must be old SYN; drop it.
1517 * else do normal processing.
1518 */
1519 case TCPS_LAST_ACK:
1520 case TCPS_CLOSING:
1521 case TCPS_TIME_WAIT:
1522 if ((thflags & TH_SYN) &&
1523 (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
1524 if (tp->t_state == TCPS_TIME_WAIT &&
1525 tp->t_duration > TCPTV_MSL)
1526 goto dropwithreset;
1527 if (CC_GT(to.to_cc, tp->cc_recv)) {
1528 tp = tcp_close(tp);
1529 goto findpcb;
1530 }
1531 else
1532 goto drop;
1533 }
1534 break; /* continue normal processing */
1535 }
1536
1537 /*
1538 * States other than LISTEN or SYN_SENT.
1539 * First check the RST flag and sequence number since reset segments
1540 * are exempt from the timestamp and connection count tests. This
1541 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1542 * below which allowed reset segments in half the sequence space
1543 * to fall though and be processed (which gives forged reset
1544 * segments with a random sequence number a 50 percent chance of
1545 * killing a connection).
1546 * Then check timestamp, if present.
1547 * Then check the connection count, if present.
1548 * Then check that at least some bytes of segment are within
1549 * receive window. If segment begins before rcv_nxt,
1550 * drop leading data (and SYN); if nothing left, just ack.
1551 *
1552 *
1553 * If the RST bit is set, check the sequence number to see
1554 * if this is a valid reset segment.
1555 * RFC 793 page 37:
1556 * In all states except SYN-SENT, all reset (RST) segments
1557 * are validated by checking their SEQ-fields. A reset is
1558 * valid if its sequence number is in the window.
1559 * Note: this does not take into account delayed ACKs, so
1560 * we should test against last_ack_sent instead of rcv_nxt.
1561 * Also, it does not make sense to allow reset segments with
1562 * sequence numbers greater than last_ack_sent to be processed
1563 * since these sequence numbers are just the acknowledgement
1564 * numbers in our outgoing packets being echoed back at us,
1565 * and these acknowledgement numbers are monotonically
1566 * increasing.
1567 * If we have multiple segments in flight, the intial reset
1568 * segment sequence numbers will be to the left of last_ack_sent,
1569 * but they will eventually catch up.
1570 * In any case, it never made sense to trim reset segments to
1571 * fit the receive window since RFC 1122 says:
1572 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1573 *
1574 * A TCP SHOULD allow a received RST segment to include data.
1575 *
1576 * DISCUSSION
1577 * It has been suggested that a RST segment could contain
1578 * ASCII text that encoded and explained the cause of the
1579 * RST. No standard has yet been established for such
1580 * data.
1581 *
1582 * If the reset segment passes the sequence number test examine
1583 * the state:
1584 * SYN_RECEIVED STATE:
1585 * If passive open, return to LISTEN state.
1586 * If active open, inform user that connection was refused.
1587 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1588 * Inform user that connection was reset, and close tcb.
1589 * CLOSING, LAST_ACK, TIME_WAIT STATES
1590 * Close the tcb.
1591 * TIME_WAIT state:
1592 * Drop the segment - see Stevens, vol. 2, p. 964 and
1593 * RFC 1337.
1594 */
1595 if (thflags & TH_RST) {
1596 if (tp->last_ack_sent == th->th_seq) {
1597 switch (tp->t_state) {
1598
1599 case TCPS_SYN_RECEIVED:
1600 so->so_error = ECONNREFUSED;
1601 goto close;
1602
1603 case TCPS_ESTABLISHED:
1604 case TCPS_FIN_WAIT_1:
1605 case TCPS_CLOSE_WAIT:
1606 current_active_connections--;
1607 /*
1608 Drop through ...
1609 */
1610 case TCPS_FIN_WAIT_2:
1611 so->so_error = ECONNRESET;
1612 close:
1613 postevent(so, 0, EV_RESET);
1614 tp->t_state = TCPS_CLOSED;
1615 tcpstat.tcps_drops++;
1616 tp = tcp_close(tp);
1617 break;
1618
1619 case TCPS_CLOSING:
1620 case TCPS_LAST_ACK:
1621 current_active_connections--;
1622 tp = tcp_close(tp);
1623 break;
1624
1625 case TCPS_TIME_WAIT:
1626 break;
1627 }
1628 }
1629 goto drop;
1630 }
1631
1632 /*
1633 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1634 * and it's less than ts_recent, drop it.
1635 */
1636 if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1637 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1638
1639 /* Check to see if ts_recent is over 24 days old. */
1640 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1641 /*
1642 * Invalidate ts_recent. If this segment updates
1643 * ts_recent, the age will be reset later and ts_recent
1644 * will get a valid value. If it does not, setting
1645 * ts_recent to zero will at least satisfy the
1646 * requirement that zero be placed in the timestamp
1647 * echo reply when ts_recent isn't valid. The
1648 * age isn't reset until we get a valid ts_recent
1649 * because we don't want out-of-order segments to be
1650 * dropped when ts_recent is old.
1651 */
1652 tp->ts_recent = 0;
1653 } else {
1654 tcpstat.tcps_rcvduppack++;
1655 tcpstat.tcps_rcvdupbyte += tilen;
1656 tcpstat.tcps_pawsdrop++;
1657 goto dropafterack;
1658 }
1659 }
1660
1661 /*
1662 * T/TCP mechanism
1663 * If T/TCP was negotiated and the segment doesn't have CC,
1664 * or if its CC is wrong then drop the segment.
1665 * RST segments do not have to comply with this.
1666 */
1667 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1668 ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1669 goto dropafterack;
1670
1671 /*
1672 * In the SYN-RECEIVED state, validate that the packet belongs to
1673 * this connection before trimming the data to fit the receive
1674 * window. Check the sequence number versus IRS since we know
1675 * the sequence numbers haven't wrapped. This is a partial fix
1676 * for the "LAND" DoS attack.
1677 */
1678 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs))
1679 goto dropwithreset;
1680
1681 todrop = tp->rcv_nxt - th->th_seq;
1682 if (todrop > 0) {
1683 if (thflags & TH_SYN) {
1684 thflags &= ~TH_SYN;
1685 th->th_seq++;
1686 if (th->th_urp > 1)
1687 th->th_urp--;
1688 else
1689 thflags &= ~TH_URG;
1690 todrop--;
1691 }
1692 /*
1693 * Following if statement from Stevens, vol. 2, p. 960.
1694 */
1695 if (todrop > tilen
1696 || (todrop == tilen && (thflags & TH_FIN) == 0)) {
1697 /*
1698 * Any valid FIN must be to the left of the window.
1699 * At this point the FIN must be a duplicate or out
1700 * of sequence; drop it.
1701 */
1702 thflags &= ~TH_FIN;
1703
1704 /*
1705 * Send an ACK to resynchronize and drop any data.
1706 * But keep on processing for RST or ACK.
1707 */
1708 tp->t_flags |= TF_ACKNOW;
1709 todrop = tilen;
1710 tcpstat.tcps_rcvduppack++;
1711 tcpstat.tcps_rcvdupbyte += todrop;
1712 } else {
1713 tcpstat.tcps_rcvpartduppack++;
1714 tcpstat.tcps_rcvpartdupbyte += todrop;
1715 }
1716 m_adj(m, todrop);
1717 th->th_seq += todrop;
1718 tilen -= todrop;
1719 if (th->th_urp > todrop)
1720 th->th_urp -= todrop;
1721 else {
1722 thflags &= ~TH_URG;
1723 th->th_urp = 0;
1724 }
1725 }
1726
1727 /*
1728 * If new data are received on a connection after the
1729 * user processes are gone, then RST the other end.
1730 */
1731 if ((so->so_state & SS_NOFDREF) &&
1732 tp->t_state > TCPS_CLOSE_WAIT && tilen) {
1733 tp = tcp_close(tp);
1734 tcpstat.tcps_rcvafterclose++;
1735 goto dropwithreset;
1736 }
1737
1738 /*
1739 * If segment ends after window, drop trailing data
1740 * (and PUSH and FIN); if nothing left, just ACK.
1741 */
1742 todrop = (th->th_seq+tilen) - (tp->rcv_nxt+tp->rcv_wnd);
1743 if (todrop > 0) {
1744 tcpstat.tcps_rcvpackafterwin++;
1745 if (todrop >= tilen) {
1746 tcpstat.tcps_rcvbyteafterwin += tilen;
1747 /*
1748 * If a new connection request is received
1749 * while in TIME_WAIT, drop the old connection
1750 * and start over if the sequence numbers
1751 * are above the previous ones.
1752 */
1753 if (thflags & TH_SYN &&
1754 tp->t_state == TCPS_TIME_WAIT &&
1755 SEQ_GT(th->th_seq, tp->rcv_nxt)) {
1756 #ifdef TCP_COMPAT_42
1757 iss = tp->rcv_nxt + TCP_ISSINCR;
1758 #else
1759 iss = tcp_rndiss_next();
1760 #endif /* TCP_COMPAT_42 */
1761 tp = tcp_close(tp);
1762 goto findpcb;
1763 }
1764 /*
1765 * If window is closed can only take segments at
1766 * window edge, and have to drop data and PUSH from
1767 * incoming segments. Continue processing, but
1768 * remember to ack. Otherwise, drop segment
1769 * and ack.
1770 */
1771 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1772 tp->t_flags |= TF_ACKNOW;
1773 tcpstat.tcps_rcvwinprobe++;
1774 } else
1775 goto dropafterack;
1776 } else
1777 tcpstat.tcps_rcvbyteafterwin += todrop;
1778 m_adj(m, -todrop);
1779 tilen -= todrop;
1780 thflags &= ~(TH_PUSH|TH_FIN);
1781 }
1782
1783 /*
1784 * If last ACK falls within this segment's sequence numbers,
1785 * record its timestamp.
1786 * NOTE that the test is modified according to the latest
1787 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1788 */
1789 if ((to.to_flag & TOF_TS) != 0 &&
1790 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1791 tp->ts_recent_age = tcp_now;
1792 tp->ts_recent = to.to_tsval;
1793 }
1794
1795 /*
1796 * If a SYN is in the window, then this is an
1797 * error and we send an RST and drop the connection.
1798 */
1799 if (thflags & TH_SYN) {
1800 tp = tcp_drop(tp, ECONNRESET);
1801 postevent(so, 0, EV_RESET);
1802 goto dropwithreset;
1803 }
1804
1805 /*
1806 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1807 * flag is on (half-synchronized state), then queue data for
1808 * later processing; else drop segment and return.
1809 */
1810 if ((thflags & TH_ACK) == 0) {
1811 if (tp->t_state == TCPS_SYN_RECEIVED ||
1812 (tp->t_flags & TF_NEEDSYN))
1813 goto step6;
1814 else
1815 goto drop;
1816 }
1817
1818 /*
1819 * Ack processing.
1820 */
1821 switch (tp->t_state) {
1822
1823 /*
1824 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1825 * ESTABLISHED state and continue processing.
1826 * The ACK was checked above.
1827 */
1828 case TCPS_SYN_RECEIVED:
1829
1830 tcpstat.tcps_connects++;
1831 soisconnected(so);
1832 current_active_connections++;
1833
1834 /* Do window scaling? */
1835 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1836 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1837 tp->snd_scale = tp->requested_s_scale;
1838 tp->rcv_scale = tp->request_r_scale;
1839 }
1840 /*
1841 * Upon successful completion of 3-way handshake,
1842 * update cache.CC if it was undefined, pass any queued
1843 * data to the user, and advance state appropriately.
1844 */
1845 if ((taop = tcp_gettaocache(inp)) != NULL &&
1846 taop->tao_cc == 0)
1847 taop->tao_cc = tp->cc_recv;
1848
1849 /*
1850 * Make transitions:
1851 * SYN-RECEIVED -> ESTABLISHED
1852 * SYN-RECEIVED* -> FIN-WAIT-1
1853 */
1854 if (tp->t_flags & TF_NEEDFIN) {
1855 tp->t_state = TCPS_FIN_WAIT_1;
1856 tp->t_flags &= ~TF_NEEDFIN;
1857 } else {
1858 tp->t_state = TCPS_ESTABLISHED;
1859 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1860 }
1861 /*
1862 * If segment contains data or ACK, will call tcp_reass()
1863 * later; if not, do so now to pass queued data to user.
1864 */
1865 if (tilen == 0 && (thflags & TH_FIN) == 0)
1866 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
1867 (struct mbuf *)0, isipv6);
1868 tp->snd_wl1 = th->th_seq - 1;
1869 /* fall into ... */
1870
1871 /*
1872 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1873 * ACKs. If the ack is in the range
1874 * tp->snd_una < th->th_ack <= tp->snd_max
1875 * then advance tp->snd_una to th->th_ack and drop
1876 * data from the retransmission queue. If this ACK reflects
1877 * more up to date window information we update our window information.
1878 */
1879 case TCPS_ESTABLISHED:
1880 case TCPS_FIN_WAIT_1:
1881 case TCPS_FIN_WAIT_2:
1882 case TCPS_CLOSE_WAIT:
1883 case TCPS_CLOSING:
1884 case TCPS_LAST_ACK:
1885 case TCPS_TIME_WAIT:
1886
1887 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
1888 if (tilen == 0 && tiwin == tp->snd_wnd) {
1889 tcpstat.tcps_rcvdupack++;
1890 /*
1891 * If we have outstanding data (other than
1892 * a window probe), this is a completely
1893 * duplicate ack (ie, window info didn't
1894 * change), the ack is the biggest we've
1895 * seen and we've seen exactly our rexmt
1896 * threshhold of them, assume a packet
1897 * has been dropped and retransmit it.
1898 * Kludge snd_nxt & the congestion
1899 * window so we send only this one
1900 * packet.
1901 *
1902 * We know we're losing at the current
1903 * window size so do congestion avoidance
1904 * (set ssthresh to half the current window
1905 * and pull our congestion window back to
1906 * the new ssthresh).
1907 *
1908 * Dup acks mean that packets have left the
1909 * network (they're now cached at the receiver)
1910 * so bump cwnd by the amount in the receiver
1911 * to keep a constant cwnd packets in the
1912 * network.
1913 */
1914 if (tp->t_timer[TCPT_REXMT] == 0 ||
1915 th->th_ack != tp->snd_una)
1916 tp->t_dupacks = 0;
1917 else if (++tp->t_dupacks == tcprexmtthresh) {
1918 tcp_seq onxt = tp->snd_nxt;
1919 u_int win =
1920 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1921 tp->t_maxseg;
1922
1923 if (win < 2)
1924 win = 2;
1925 tp->snd_ssthresh = win * tp->t_maxseg;
1926 tp->t_timer[TCPT_REXMT] = 0;
1927 tp->t_rtt = 0;
1928 tp->snd_nxt = th->th_ack;
1929 tp->snd_cwnd = tp->t_maxseg;
1930 (void) tcp_output(tp);
1931 tp->snd_cwnd = tp->snd_ssthresh +
1932 tp->t_maxseg * tp->t_dupacks;
1933 if (SEQ_GT(onxt, tp->snd_nxt))
1934 tp->snd_nxt = onxt;
1935 goto drop;
1936 } else if (tp->t_dupacks > tcprexmtthresh) {
1937 tp->snd_cwnd += tp->t_maxseg;
1938 (void) tcp_output(tp);
1939 goto drop;
1940 }
1941 } else
1942 tp->t_dupacks = 0;
1943 break;
1944 }
1945 /*
1946 * If the congestion window was inflated to account
1947 * for the other side's cached packets, retract it.
1948 */
1949 if (tp->t_dupacks >= tcprexmtthresh &&
1950 tp->snd_cwnd > tp->snd_ssthresh)
1951 tp->snd_cwnd = tp->snd_ssthresh;
1952 tp->t_dupacks = 0;
1953 if (SEQ_GT(th->th_ack, tp->snd_max)) {
1954 tcpstat.tcps_rcvacktoomuch++;
1955 goto dropafterack;
1956 }
1957 /*
1958 * If we reach this point, ACK is not a duplicate,
1959 * i.e., it ACKs something we sent.
1960 */
1961 if (tp->t_flags & TF_NEEDSYN) {
1962 /*
1963 * T/TCP: Connection was half-synchronized, and our
1964 * SYN has been ACK'd (so connection is now fully
1965 * synchronized). Go to non-starred state,
1966 * increment snd_una for ACK of SYN, and check if
1967 * we can do window scaling.
1968 */
1969 tp->t_flags &= ~TF_NEEDSYN;
1970 tp->snd_una++;
1971 /* Do window scaling? */
1972 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1973 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1974 tp->snd_scale = tp->requested_s_scale;
1975 tp->rcv_scale = tp->request_r_scale;
1976 }
1977 }
1978
1979 process_ACK:
1980 acked = th->th_ack - tp->snd_una;
1981 tcpstat.tcps_rcvackpack++;
1982 tcpstat.tcps_rcvackbyte += acked;
1983
1984 /*
1985 * If we have a timestamp reply, update smoothed
1986 * round trip time. If no timestamp is present but
1987 * transmit timer is running and timed sequence
1988 * number was acked, update smoothed round trip time.
1989 * Since we now have an rtt measurement, cancel the
1990 * timer backoff (cf., Phil Karn's retransmit alg.).
1991 * Recompute the initial retransmit timer.
1992 */
1993 if (to.to_flag & TOF_TS)
1994 tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1995 else if (tp->t_rtt && SEQ_GT(th->th_ack, tp->t_rtseq))
1996 tcp_xmit_timer(tp,tp->t_rtt);
1997
1998 /*
1999 * If all outstanding data is acked, stop retransmit
2000 * timer and remember to restart (more output or persist).
2001 * If there is more data to be acked, restart retransmit
2002 * timer, using current (possibly backed-off) value.
2003 */
2004 if (th->th_ack == tp->snd_max) {
2005 tp->t_timer[TCPT_REXMT] = 0;
2006 needoutput = 1;
2007 } else if (tp->t_timer[TCPT_PERSIST] == 0)
2008 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
2009
2010 /*
2011 * If no data (only SYN) was ACK'd,
2012 * skip rest of ACK processing.
2013 */
2014 if (acked == 0)
2015 goto step6;
2016
2017 /*
2018 * When new data is acked, open the congestion window.
2019 * If the window gives us less than ssthresh packets
2020 * in flight, open exponentially (maxseg per packet).
2021 * Otherwise open linearly: maxseg per window
2022 * (maxseg^2 / cwnd per packet).
2023 */
2024 {
2025 register u_int cw = tp->snd_cwnd;
2026 register u_int incr = tp->t_maxseg;
2027
2028 if (cw > tp->snd_ssthresh)
2029 incr = incr * incr / cw;
2030 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
2031 }
2032 if (acked > so->so_snd.sb_cc) {
2033 tp->snd_wnd -= so->so_snd.sb_cc;
2034 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
2035 ourfinisacked = 1;
2036 } else {
2037 sbdrop(&so->so_snd, acked);
2038 tp->snd_wnd -= acked;
2039 ourfinisacked = 0;
2040 }
2041 need_sowwakeup++;
2042 tp->snd_una = th->th_ack;
2043 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2044 tp->snd_nxt = tp->snd_una;
2045
2046 switch (tp->t_state) {
2047
2048 /*
2049 * In FIN_WAIT_1 STATE in addition to the processing
2050 * for the ESTABLISHED state if our FIN is now acknowledged
2051 * then enter FIN_WAIT_2.
2052 */
2053 case TCPS_FIN_WAIT_1:
2054 if (ourfinisacked) {
2055 /*
2056 * If we can't receive any more
2057 * data, then closing user can proceed.
2058 * Starting the timer is contrary to the
2059 * specification, but if we don't get a FIN
2060 * we'll hang forever.
2061 */
2062 if (so->so_state & SS_CANTRCVMORE) {
2063 soisdisconnected(so);
2064 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
2065 }
2066 add_to_time_wait(tp);
2067 current_active_connections--;
2068 tp->t_state = TCPS_FIN_WAIT_2;
2069 }
2070 break;
2071
2072 /*
2073 * In CLOSING STATE in addition to the processing for
2074 * the ESTABLISHED state if the ACK acknowledges our FIN
2075 * then enter the TIME-WAIT state, otherwise ignore
2076 * the segment.
2077 */
2078 case TCPS_CLOSING:
2079 if (ourfinisacked) {
2080 tp->t_state = TCPS_TIME_WAIT;
2081 tcp_canceltimers(tp);
2082 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2083 if (tp->cc_recv != 0 &&
2084 tp->t_duration < TCPTV_MSL)
2085 tp->t_timer[TCPT_2MSL] =
2086 tp->t_rxtcur * TCPTV_TWTRUNC;
2087 else
2088 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2089 add_to_time_wait(tp);
2090 current_active_connections--;
2091 soisdisconnected(so);
2092 }
2093 break;
2094
2095 /*
2096 * In LAST_ACK, we may still be waiting for data to drain
2097 * and/or to be acked, as well as for the ack of our FIN.
2098 * If our FIN is now acknowledged, delete the TCB,
2099 * enter the closed state and return.
2100 */
2101 case TCPS_LAST_ACK:
2102 if (ourfinisacked) {
2103 tp = tcp_close(tp);
2104 goto drop;
2105 }
2106 break;
2107
2108 /*
2109 * In TIME_WAIT state the only thing that should arrive
2110 * is a retransmission of the remote FIN. Acknowledge
2111 * it and restart the finack timer.
2112 */
2113 case TCPS_TIME_WAIT:
2114 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2115 add_to_time_wait(tp);
2116 goto dropafterack;
2117 }
2118 }
2119
2120 step6:
2121 /*
2122 * Update window information.
2123 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2124 */
2125 if ((thflags & TH_ACK) &&
2126 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2127 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2128 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2129 /* keep track of pure window updates */
2130 if (tilen == 0 &&
2131 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2132 tcpstat.tcps_rcvwinupd++;
2133 tp->snd_wnd = tiwin;
2134 tp->snd_wl1 = th->th_seq;
2135 tp->snd_wl2 = th->th_ack;
2136 if (tp->snd_wnd > tp->max_sndwnd)
2137 tp->max_sndwnd = tp->snd_wnd;
2138 needoutput = 1;
2139 }
2140
2141 /*
2142 * Process segments with URG.
2143 */
2144 if ((thflags & TH_URG) && th->th_urp &&
2145 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2146 /*
2147 * This is a kludge, but if we receive and accept
2148 * random urgent pointers, we'll crash in
2149 * soreceive. It's hard to imagine someone
2150 * actually wanting to send this much urgent data.
2151 */
2152 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2153 th->th_urp = 0; /* XXX */
2154 thflags &= ~TH_URG; /* XXX */
2155 goto dodata; /* XXX */
2156 }
2157 /*
2158 * If this segment advances the known urgent pointer,
2159 * then mark the data stream. This should not happen
2160 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2161 * a FIN has been received from the remote side.
2162 * In these states we ignore the URG.
2163 *
2164 * According to RFC961 (Assigned Protocols),
2165 * the urgent pointer points to the last octet
2166 * of urgent data. We continue, however,
2167 * to consider it to indicate the first octet
2168 * of data past the urgent section as the original
2169 * spec states (in one of two places).
2170 */
2171 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2172 tp->rcv_up = th->th_seq + th->th_urp;
2173 so->so_oobmark = so->so_rcv.sb_cc +
2174 (tp->rcv_up - tp->rcv_nxt) - 1;
2175 if (so->so_oobmark == 0) {
2176 so->so_state |= SS_RCVATMARK;
2177 postevent(so, 0, EV_OOB);
2178 }
2179 sohasoutofband(so);
2180 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2181 }
2182 /*
2183 * Remove out of band data so doesn't get presented to user.
2184 * This can happen independent of advancing the URG pointer,
2185 * but if two URG's are pending at once, some out-of-band
2186 * data may creep in... ick.
2187 */
2188 if (th->th_urp <= (u_long)tilen
2189 #if SO_OOBINLINE
2190 && (so->so_options & SO_OOBINLINE) == 0
2191 #endif
2192 )
2193 tcp_pulloutofband(so, th, m);
2194 } else
2195 /*
2196 * If no out of band data is expected,
2197 * pull receive urgent pointer along
2198 * with the receive window.
2199 */
2200 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2201 tp->rcv_up = tp->rcv_nxt;
2202 dodata: /* XXX */
2203
2204 /*
2205 * Process the segment text, merging it into the TCP sequencing queue,
2206 * and arranging for acknowledgment of receipt if necessary.
2207 * This process logically involves adjusting tp->rcv_wnd as data
2208 * is presented to the user (this happens in tcp_usrreq.c,
2209 * case PRU_RCVD). If a FIN has already been received on this
2210 * connection then we just ignore the text.
2211 */
2212 if ((tilen || (thflags&TH_FIN)) &&
2213 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2214 TCP_REASS(tp, th, tilen, m, so, thflags, isipv6, need_sorwakeup);
2215
2216 if (tp->t_flags & TF_DELACK)
2217 {
2218 KERNEL_DEBUG(DBG_LAYER_END, ((th->th_dport << 16) | th->th_sport),
2219 (((thtoti(th)->ti_src.s_addr & 0xffff) << 16) | (thtoti(th)->ti_dst.s_addr & 0xffff)),
2220 th->th_seq, th->th_ack, th->th_win);
2221 }
2222 /*
2223 * Note the amount of data that peer has sent into
2224 * our window, in order to estimate the sender's
2225 * buffer size.
2226 */
2227 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2228 } else {
2229 m_freem(m);
2230 thflags &= ~TH_FIN;
2231 }
2232
2233 /*
2234 * If FIN is received ACK the FIN and let the user know
2235 * that the connection is closing.
2236 */
2237 if (thflags & TH_FIN) {
2238 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2239 socantrcvmore(so);
2240 postevent(so, 0, EV_FIN);
2241 /*
2242 * If connection is half-synchronized
2243 * (ie NEEDSYN flag on) then delay ACK,
2244 * so it may be piggybacked when SYN is sent.
2245 * Otherwise, since we received a FIN then no
2246 * more input can be expected, send ACK now.
2247 */
2248 if (tcp_delack_enabled && (tp->t_flags & TF_NEEDSYN)) {
2249 if (last_active_conn_count > DELACK_BITMASK_THRESH)
2250 TCP_DELACK_BITSET(tp->t_inpcb->hash_element);
2251
2252 tp->t_flags |= TF_DELACK;
2253 }
2254 else
2255 tp->t_flags |= TF_ACKNOW;
2256 tp->rcv_nxt++;
2257 }
2258 switch (tp->t_state) {
2259
2260 /*
2261 * In SYN_RECEIVED and ESTABLISHED STATES
2262 * enter the CLOSE_WAIT state.
2263 */
2264 case TCPS_SYN_RECEIVED:
2265 case TCPS_ESTABLISHED:
2266 tp->t_state = TCPS_CLOSE_WAIT;
2267 break;
2268
2269 /*
2270 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2271 * enter the CLOSING state.
2272 */
2273 case TCPS_FIN_WAIT_1:
2274 tp->t_state = TCPS_CLOSING;
2275 break;
2276
2277 /*
2278 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2279 * starting the time-wait timer, turning off the other
2280 * standard timers.
2281 */
2282 case TCPS_FIN_WAIT_2:
2283 tp->t_state = TCPS_TIME_WAIT;
2284 tcp_canceltimers(tp);
2285 /* Shorten TIME_WAIT [RFC-1644, p.28] */
2286 if (tp->cc_recv != 0 &&
2287 tp->t_duration < TCPTV_MSL) {
2288 tp->t_timer[TCPT_2MSL] =
2289 tp->t_rxtcur * TCPTV_TWTRUNC;
2290 /* For transaction client, force ACK now. */
2291 tp->t_flags |= TF_ACKNOW;
2292 }
2293 else
2294 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2295
2296 add_to_time_wait(tp);
2297 soisdisconnected(so);
2298 break;
2299
2300 /*
2301 * In TIME_WAIT state restart the 2 MSL time_wait timer.
2302 */
2303 case TCPS_TIME_WAIT:
2304 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
2305 add_to_time_wait(tp);
2306 break;
2307 }
2308 }
2309 #if TCPDEBUG
2310 if (so->so_options & SO_DEBUG) {
2311 #if INET6
2312 if (isipv6)
2313 tcp_saveip._tcp_si6.ip6_plen = tilen;
2314 else
2315 tcp_saveip._tcp_si4.ip_len = tilen;
2316 #else /* INET6 */
2317 tcp_saveip.ip_len = tilen;
2318 #endif /* INET6 */
2319
2320 tcp_trace(TA_INPUT, ostate, tp, (void *)&tcp_saveip,
2321 &tcp_savetcp, 0);
2322 }
2323 #endif
2324
2325 /*
2326 * Return any desired output.
2327 */
2328 if (needoutput || (tp->t_flags & TF_ACKNOW))
2329 (void) tcp_output(tp);
2330 if (need_sorwakeup)
2331 sorwakeup(so);
2332 if (need_sowwakeup)
2333 sowwakeup(so);
2334 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2335 return;
2336
2337 dropafterack:
2338 /*
2339 * Generate an ACK dropping incoming segment if it occupies
2340 * sequence space, where the ACK reflects our state.
2341 *
2342 * We can now skip the test for the RST flag since all
2343 * paths to this code happen after packets containing
2344 * RST have been dropped.
2345 *
2346 * In the SYN-RECEIVED state, don't send an ACK unless the
2347 * segment we received passes the SYN-RECEIVED ACK test.
2348 * If it fails send a RST. This breaks the loop in the
2349 * "LAND" DoS attack, and also prevents an ACK storm
2350 * between two listening ports that have been sent forged
2351 * SYN segments, each with the source address of the other.
2352 */
2353 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2354 (SEQ_GT(tp->snd_una, th->th_ack) ||
2355 SEQ_GT(th->th_ack, tp->snd_max)) )
2356 goto dropwithreset;
2357 #if TCPDEBUG
2358 if (so->so_options & SO_DEBUG) {
2359 #if INET6
2360 if (isipv6)
2361 tcp_saveip._tcp_si6.ip6_plen = tilen;
2362 else
2363 tcp_saveip._tcp_si4.ip_len = tilen;
2364 #else /* INET6 */
2365 tcp_saveip.ip_len = tilen;
2366 #endif /* INET6 */
2367 tcp_trace(TA_DROP, ostate, tp, (void *)&tcp_saveip,
2368 &tcp_savetcp, 0);
2369 }
2370 #endif
2371 m_freem(m);
2372 tp->t_flags |= TF_ACKNOW;
2373 (void) tcp_output(tp);
2374 if (need_sorwakeup)
2375 sorwakeup(so);
2376 if (need_sowwakeup)
2377 sowwakeup(so);
2378 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2379 return;
2380
2381 dropwithreset:
2382 /*
2383 * Generate a RST, dropping incoming segment.
2384 * Make ACK acceptable to originator of segment.
2385 * Don't bother to respond if destination was broadcast/multicast.
2386 */
2387 if ((thflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2388 goto drop;
2389 #if INET6
2390 if (isipv6) {
2391 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))
2392 goto drop; /* anycast check is done at the top */
2393 } else
2394 #endif /* INET6 */
2395 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)))
2396 goto drop;
2397 #if TCPDEBUG
2398 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
2399 if (tp == 0) {
2400 #if INET6
2401 if (isipv6)
2402 tcp_saveip._tcp_si6 = *ip6;
2403 else
2404 tcp_saveip._tcp_si4 = *ip;
2405 #else /* INET6 */
2406 tcp_saveip = *ip;
2407 #endif /* INET6 */
2408 }
2409 #if INET6
2410 if (isipv6)
2411 tcp_saveip._tcp_si6.ip6_plen = tilen;
2412 else
2413 tcp_saveip._tcp_si4.ip_len = tilen;
2414 #else /* INET6 */
2415 tcp_saveip.ip_len = tilen;
2416 #endif /* INET6 */
2417 tcp_trace(TA_DROP, ostate, tp, (void *)&tcp_saveip,
2418 &tcp_savetcp, 0);
2419 }
2420 #endif
2421 if (thflags & TH_ACK)
2422 #if INET6
2423 tcp_respond(tp, isipv6 ? (void *)ip6 : (void *)ip, th, m,
2424 (tcp_seq)0, th->th_ack, TH_RST, isipv6);
2425 #else /* INET6 */
2426 tcp_respond(tp, (void *)ip, th, m,
2427 (tcp_seq)0, th->th_ack, TH_RST, isipv6);
2428 #endif /* INET6 */
2429 else {
2430 if (thflags & TH_SYN)
2431 tilen++;
2432 #if INET6
2433 tcp_respond(tp, isipv6 ? (void *)ip6 : (void *)ip, th, m,
2434 th->th_seq+tilen, (tcp_seq)0, TH_RST|TH_ACK,
2435 isipv6);
2436 #else /* INET6 */
2437 tcp_respond(tp, (void *)ip, th, m,
2438 th->th_seq+tilen, (tcp_seq)0, TH_RST|TH_ACK,
2439 isipv6);
2440 #endif /* INET6 */
2441 }
2442 /* destroy temporarily created socket */
2443 if (need_sorwakeup)
2444 sorwakeup(so);
2445 if (need_sowwakeup)
2446 sowwakeup(so);
2447 if (dropsocket)
2448 (void) soabort(so);
2449 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2450 return;
2451
2452 drop:
2453 /*
2454 * Drop space held by incoming segment and return.
2455 */
2456 #if TCPDEBUG
2457 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG)) {
2458 if (tp == 0) {
2459 #if INET6
2460 if (isipv6)
2461 tcp_saveip._tcp_si6 = *ip6;
2462 else
2463 tcp_saveip._tcp_si4 = *ip;
2464 #else /* INET6 */
2465 tcp_saveip = *ip;
2466 #endif /* INET6 */
2467 }
2468 #if INET6
2469 if (isipv6)
2470 tcp_saveip._tcp_si6.ip6_plen = tilen;
2471 else
2472 tcp_saveip._tcp_si4.ip_len = tilen;
2473 #else /* INET6 */
2474 tcp_saveip.ip_len = tilen;
2475 #endif /* INET6 */
2476 tcp_trace(TA_DROP, ostate, tp, (void *)&tcp_saveip,
2477 &tcp_savetcp, 0);
2478 }
2479 #endif
2480 m_freem(m);
2481 if (need_sorwakeup)
2482 sorwakeup(so);
2483 if (need_sowwakeup)
2484 sowwakeup(so);
2485 /* destroy temporarily created socket */
2486 if (dropsocket)
2487 (void) soabort(so);
2488 KERNEL_DEBUG(DBG_FNC_TCP_INPUT | DBG_FUNC_END,0,0,0,0,0);
2489 return;
2490 }
2491
2492 static void
2493 tcp_dooptions(tp, cp, cnt, th, to)
2494 struct tcpcb *tp;
2495 u_char *cp;
2496 int cnt;
2497 struct tcphdr *th;
2498 struct tcpopt *to;
2499 {
2500 u_short mss = 0;
2501 int opt, optlen;
2502
2503 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2504 opt = cp[0];
2505 if (opt == TCPOPT_EOL)
2506 break;
2507 if (opt == TCPOPT_NOP)
2508 optlen = 1;
2509 else {
2510 optlen = cp[1];
2511 if (optlen <= 0)
2512 break;
2513 }
2514 switch (opt) {
2515
2516 default:
2517 continue;
2518
2519 case TCPOPT_MAXSEG:
2520 if (optlen != TCPOLEN_MAXSEG)
2521 continue;
2522 if (!(th->th_flags & TH_SYN))
2523 continue;
2524 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
2525 to->to_maxseg = ntohs(mss);
2526 break;
2527
2528 case TCPOPT_WINDOW:
2529 if (optlen != TCPOLEN_WINDOW)
2530 continue;
2531 if (!(th->th_flags & TH_SYN))
2532 continue;
2533 tp->t_flags |= TF_RCVD_SCALE;
2534 tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
2535 break;
2536
2537 case TCPOPT_TIMESTAMP:
2538 if (optlen != TCPOLEN_TIMESTAMP)
2539 continue;
2540 to->to_flag |= TOF_TS;
2541 bcopy((char *)cp + 2,
2542 (char *)&to->to_tsval, sizeof(to->to_tsval));
2543 NTOHL(to->to_tsval);
2544 bcopy((char *)cp + 6,
2545 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2546 NTOHL(to->to_tsecr);
2547
2548 /*
2549 * A timestamp received in a SYN makes
2550 * it ok to send timestamp requests and replies.
2551 */
2552 if (th->th_flags & TH_SYN) {
2553 tp->t_flags |= TF_RCVD_TSTMP;
2554 tp->ts_recent = to->to_tsval;
2555 tp->ts_recent_age = tcp_now;
2556 }
2557 break;
2558 case TCPOPT_CC:
2559 if (optlen != TCPOLEN_CC)
2560 continue;
2561 to->to_flag |= TOF_CC;
2562 bcopy((char *)cp + 2,
2563 (char *)&to->to_cc, sizeof(to->to_cc));
2564 NTOHL(to->to_cc);
2565 /*
2566 * A CC or CC.new option received in a SYN makes
2567 * it ok to send CC in subsequent segments.
2568 */
2569 if (th->th_flags & TH_SYN)
2570 tp->t_flags |= TF_RCVD_CC;
2571 break;
2572 case TCPOPT_CCNEW:
2573 if (optlen != TCPOLEN_CC)
2574 continue;
2575 if (!(th->th_flags & TH_SYN))
2576 continue;
2577 to->to_flag |= TOF_CCNEW;
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 tp->t_flags |= TF_RCVD_CC;
2586 break;
2587 case TCPOPT_CCECHO:
2588 if (optlen != TCPOLEN_CC)
2589 continue;
2590 if (!(th->th_flags & TH_SYN))
2591 continue;
2592 to->to_flag |= TOF_CCECHO;
2593 bcopy((char *)cp + 2,
2594 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
2595 NTOHL(to->to_ccecho);
2596 break;
2597 }
2598 }
2599 }
2600
2601 /*
2602 * Pull out of band byte out of a segment so
2603 * it doesn't appear in the user's data queue.
2604 * It is still reflected in the segment length for
2605 * sequencing purposes.
2606 */
2607 static void
2608 tcp_pulloutofband(so, th, m)
2609 struct socket *so;
2610 struct tcphdr *th;
2611 register struct mbuf *m;
2612 {
2613 int cnt = th->th_urp - 1;
2614
2615 while (cnt >= 0) {
2616 if (m->m_len > cnt) {
2617 char *cp = mtod(m, caddr_t) + cnt;
2618 struct tcpcb *tp = sototcpcb(so);
2619
2620 tp->t_iobc = *cp;
2621 tp->t_oobflags |= TCPOOB_HAVEDATA;
2622 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2623 m->m_len--;
2624 return;
2625 }
2626 cnt -= m->m_len;
2627 m = m->m_next;
2628 if (m == 0)
2629 break;
2630 }
2631 panic("tcp_pulloutofband");
2632 }
2633
2634 /*
2635 * Collect new round-trip time estimate
2636 * and update averages and current timeout.
2637 */
2638 static void
2639 tcp_xmit_timer(tp, rtt)
2640 register struct tcpcb *tp;
2641 short rtt;
2642 {
2643 register int delta;
2644
2645 tcpstat.tcps_rttupdated++;
2646 tp->t_rttupdated++;
2647 if (tp->t_srtt != 0) {
2648 /*
2649 * srtt is stored as fixed point with 5 bits after the
2650 * binary point (i.e., scaled by 8). The following magic
2651 * is equivalent to the smoothing algorithm in rfc793 with
2652 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
2653 * point). Adjust rtt to origin 0.
2654 */
2655 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
2656 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
2657
2658 if ((tp->t_srtt += delta) <= 0)
2659 tp->t_srtt = 1;
2660
2661 /*
2662 * We accumulate a smoothed rtt variance (actually, a
2663 * smoothed mean difference), then set the retransmit
2664 * timer to smoothed rtt + 4 times the smoothed variance.
2665 * rttvar is stored as fixed point with 4 bits after the
2666 * binary point (scaled by 16). The following is
2667 * equivalent to rfc793 smoothing with an alpha of .75
2668 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
2669 * rfc793's wired-in beta.
2670 */
2671 if (delta < 0)
2672 delta = -delta;
2673 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
2674 if ((tp->t_rttvar += delta) <= 0)
2675 tp->t_rttvar = 1;
2676 } else {
2677 /*
2678 * No rtt measurement yet - use the unsmoothed rtt.
2679 * Set the variance to half the rtt (so our first
2680 * retransmit happens at 3*rtt).
2681 */
2682 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2683 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2684 }
2685 tp->t_rtt = 0;
2686 tp->t_rxtshift = 0;
2687
2688 /*
2689 * the retransmit should happen at rtt + 4 * rttvar.
2690 * Because of the way we do the smoothing, srtt and rttvar
2691 * will each average +1/2 tick of bias. When we compute
2692 * the retransmit timer, we want 1/2 tick of rounding and
2693 * 1 extra tick because of +-1/2 tick uncertainty in the
2694 * firing of the timer. The bias will give us exactly the
2695 * 1.5 tick we need. But, because the bias is
2696 * statistical, we have to test that we don't drop below
2697 * the minimum feasible timer (which is 2 ticks).
2698 */
2699 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2700 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2701
2702 /*
2703 * We received an ack for a packet that wasn't retransmitted;
2704 * it is probably safe to discard any error indications we've
2705 * received recently. This isn't quite right, but close enough
2706 * for now (a route might have failed after we sent a segment,
2707 * and the return path might not be symmetrical).
2708 */
2709 tp->t_softerror = 0;
2710 }
2711
2712 /*
2713 * Determine a reasonable value for maxseg size.
2714 * If the route is known, check route for mtu.
2715 * If none, use an mss that can be handled on the outgoing
2716 * interface without forcing IP to fragment; if bigger than
2717 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2718 * to utilize large mbufs. If no route is found, route has no mtu,
2719 * or the destination isn't local, use a default, hopefully conservative
2720 * size (usually 512 or the default IP max size, but no more than the mtu
2721 * of the interface), as we can't discover anything about intervening
2722 * gateways or networks. We also initialize the congestion/slow start
2723 * window to be a single segment if the destination isn't local.
2724 * While looking at the routing entry, we also initialize other path-dependent
2725 * parameters from pre-set or cached values in the routing entry.
2726 *
2727 * Also take into account the space needed for options that we
2728 * send regularly. Make maxseg shorter by that amount to assure
2729 * that we can send maxseg amount of data even when the options
2730 * are present. Store the upper limit of the length of options plus
2731 * data in maxopd.
2732 *
2733 * NOTE that this routine is only called when we process an incoming
2734 * segment, for outgoing segments only tcp_mssopt is called.
2735 *
2736 * In case of T/TCP, we call this routine during implicit connection
2737 * setup as well (offer = -1), to initialize maxseg from the cached
2738 * MSS of our peer.
2739 */
2740 void
2741 tcp_mss(tp, offer, isipv6)
2742 struct tcpcb *tp;
2743 int offer;
2744 #if INET6
2745 int isipv6;
2746 #endif
2747 {
2748 register struct rtentry *rt;
2749 struct ifnet *ifp;
2750 register int rtt, mss;
2751 u_long bufsize;
2752 struct inpcb *inp;
2753 struct socket *so;
2754 struct rmxp_tao *taop;
2755 int origoffer = offer;
2756 #if INET6
2757 int lgminh = isipv6 ? sizeof (struct tcpip6hdr) :
2758 sizeof (struct tcpiphdr);
2759 #else /* INET6 */
2760 #define lgminh (sizeof (struct tcpiphdr))
2761 #endif /* INET6 */
2762
2763 inp = tp->t_inpcb;
2764 #if INET6
2765 if (isipv6)
2766 rt = tcp_rtlookup6(inp);
2767 else
2768 #endif /* INET6 */
2769 rt = tcp_rtlookup(inp);
2770 if (rt == NULL) {
2771 tp->t_maxopd = tp->t_maxseg =
2772 #if INET6
2773 isipv6 ? tcp_v6mssdflt :
2774 #endif /* INET6 */
2775 tcp_mssdflt;
2776 return;
2777 }
2778 ifp = rt->rt_ifp;
2779 so = inp->inp_socket;
2780
2781 taop = rmx_taop(rt->rt_rmx);
2782 /*
2783 * Offer == -1 means that we didn't receive SYN yet,
2784 * use cached value in that case;
2785 */
2786 if (offer == -1)
2787 offer = taop->tao_mssopt;
2788 /*
2789 * Offer == 0 means that there was no MSS on the SYN segment,
2790 * in this case we use tcp_mssdflt.
2791 */
2792 if (offer == 0)
2793 offer =
2794 #if INET6
2795 isipv6 ? tcp_v6mssdflt :
2796 #endif /* INET6 */
2797 tcp_mssdflt;
2798 else
2799 /*
2800 * Sanity check: make sure that maxopd will be large
2801 * enough to allow some data on segments even is the
2802 * all the option space is used (40bytes). Otherwise
2803 * funny things may happen in tcp_output.
2804 */
2805 offer = max(offer, 64);
2806 taop->tao_mssopt = offer;
2807
2808 /*
2809 * While we're here, check if there's an initial rtt
2810 * or rttvar. Convert from the route-table units
2811 * to scaled multiples of the slow timeout timer.
2812 */
2813 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2814 /*
2815 * XXX the lock bit for RTT indicates that the value
2816 * is also a minimum value; this is subject to time.
2817 */
2818 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2819 tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2820 tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2821 tcpstat.tcps_usedrtt++;
2822 if (rt->rt_rmx.rmx_rttvar) {
2823 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2824 (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2825 tcpstat.tcps_usedrttvar++;
2826 } else {
2827 /* default variation is +- 1 rtt */
2828 tp->t_rttvar =
2829 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2830 }
2831 TCPT_RANGESET(tp->t_rxtcur,
2832 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2833 tp->t_rttmin, TCPTV_REXMTMAX);
2834 }
2835 /*
2836 * if there's an mtu associated with the route, use it
2837 * else, use the link mtu.
2838 */
2839 if (rt->rt_rmx.rmx_mtu)
2840 mss = rt->rt_rmx.rmx_mtu - lgminh;
2841 else
2842 mss =
2843 #if INET6
2844 isipv6 ? nd_ifinfo[rt->rt_ifp->if_index].linkmtu :
2845 #endif
2846 ifp->if_mtu - lgminh;
2847
2848 if (rt->rt_rmx.rmx_mtu == 0) {
2849 #if INET6
2850 if (isipv6) {
2851 if (!in6_localaddr(&inp->in6p_faddr))
2852 mss = min(mss, tcp_v6mssdflt);
2853 } else
2854 #endif /* INET6 */
2855 if (!in_localaddr(inp->inp_faddr))
2856 mss = min(mss, tcp_mssdflt);
2857 }
2858 mss = min(mss, offer);
2859 /*
2860 * maxopd stores the maximum length of data AND options
2861 * in a segment; maxseg is the amount of data in a normal
2862 * segment. We need to store this value (maxopd) apart
2863 * from maxseg, because now every segment carries options
2864 * and thus we normally have somewhat less data in segments.
2865 */
2866 tp->t_maxopd = mss;
2867
2868 /*
2869 * In case of T/TCP, origoffer==-1 indicates, that no segments
2870 * were received yet. In this case we just guess, otherwise
2871 * we do the same as before T/TCP.
2872 */
2873 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2874 (origoffer == -1 ||
2875 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2876 mss -= TCPOLEN_TSTAMP_APPA;
2877 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2878 (origoffer == -1 ||
2879 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2880 mss -= TCPOLEN_CC_APPA;
2881
2882 #if (MCLBYTES & (MCLBYTES - 1)) == 0
2883 if (mss > MCLBYTES)
2884 mss &= ~(MCLBYTES-1);
2885 #else
2886 if (mss > MCLBYTES)
2887 mss = mss / MCLBYTES * MCLBYTES;
2888 #endif
2889 /*
2890 * If there's a pipesize, change the socket buffer
2891 * to that size. Make the socket buffers an integral
2892 * number of mss units; if the mss is larger than
2893 * the socket buffer, decrease the mss.
2894 */
2895 #if RTV_SPIPE
2896 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2897 #endif
2898 bufsize = so->so_snd.sb_hiwat;
2899 if (bufsize < mss)
2900 mss = bufsize;
2901 else {
2902 bufsize = roundup(bufsize, mss);
2903 if (bufsize > sb_max)
2904 bufsize = sb_max;
2905 (void)sbreserve(&so->so_snd, bufsize);
2906 }
2907 tp->t_maxseg = mss;
2908
2909 #if RTV_RPIPE
2910 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2911 #endif
2912 bufsize = so->so_rcv.sb_hiwat;
2913 if (bufsize > mss) {
2914 bufsize = roundup(bufsize, mss);
2915 if (bufsize > sb_max)
2916 bufsize = sb_max;
2917 (void)sbreserve(&so->so_rcv, bufsize);
2918 }
2919 /*
2920 * Don't force slow-start on local network.
2921 */
2922 #if INET6
2923 if (isipv6) {
2924 if (!in6_localaddr(&inp->in6p_faddr))
2925 tp->snd_cwnd = mss;
2926 } else
2927 #endif /* INET6 */
2928 if (!in_localaddr(inp->inp_faddr))
2929 tp->snd_cwnd = mss;
2930
2931 if (rt->rt_rmx.rmx_ssthresh) {
2932 /*
2933 * There's some sort of gateway or interface
2934 * buffer limit on the path. Use this to set
2935 * the slow start threshhold, but set the
2936 * threshold to no less than 2*mss.
2937 */
2938 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2939 tcpstat.tcps_usedssthresh++;
2940 }
2941 }
2942
2943 /*
2944 * Determine the MSS option to send on an outgoing SYN.
2945 */
2946 int
2947 tcp_mssopt(tp, isipv6)
2948 struct tcpcb *tp;
2949 #if INET6
2950 int isipv6;
2951 #endif
2952 {
2953 struct rtentry *rt;
2954 int mss;
2955 #if INET6
2956 int lgminh = isipv6 ? sizeof (struct tcpip6hdr) :
2957 sizeof (struct tcpiphdr);
2958 #else /* INET6 */
2959 #define lgminh (sizeof (struct tcpiphdr))
2960 #endif /* INET6 */
2961
2962 #if INET6
2963 if (isipv6)
2964 rt = tcp_rtlookup6(tp->t_inpcb);
2965 else
2966 #endif /* INET6 */
2967 rt = tcp_rtlookup(tp->t_inpcb);
2968 if (rt == NULL)
2969 return
2970 #if INET6
2971 isipv6 ? tcp_v6mssdflt :
2972 #endif /* INET6 */
2973 tcp_mssdflt;
2974
2975 mss = rt->rt_ifp->if_mtu - lgminh;
2976
2977 return mss;
2978 }