Deleted Added
sdiff udiff text old ( 196019 ) new ( 196039 )
full compact
1/*-
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1994, 1995
3 * The Regents of the University of California. All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 4. Neither the name of the University nor the names of its contributors
14 * may be used to endorse or promote products derived from this software
15 * without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
30 */
31
32#include <sys/cdefs.h>
33__FBSDID("$FreeBSD: head/sys/netinet/tcp_input.c 196039 2009-08-02 19:43:32Z rwatson $");
34
35#include "opt_ipfw.h" /* for ipfw_fwd */
36#include "opt_inet.h"
37#include "opt_inet6.h"
38#include "opt_ipsec.h"
39#include "opt_tcpdebug.h"
40
41#include <sys/param.h>
42#include <sys/kernel.h>
43#include <sys/malloc.h>
44#include <sys/mbuf.h>
45#include <sys/proc.h> /* for proc0 declaration */
46#include <sys/protosw.h>
47#include <sys/signalvar.h>
48#include <sys/socket.h>
49#include <sys/socketvar.h>
50#include <sys/sysctl.h>
51#include <sys/syslog.h>
52#include <sys/systm.h>
53
54#include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
55
56#include <vm/uma.h>
57
58#include <net/if.h>
59#include <net/route.h>
60#include <net/vnet.h>
61
62#define TCPSTATES /* for logging */
63
64#include <netinet/in.h>
65#include <netinet/in_pcb.h>
66#include <netinet/in_systm.h>
67#include <netinet/in_var.h>
68#include <netinet/ip.h>
69#include <netinet/ip_icmp.h> /* required for icmp_var.h */
70#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
71#include <netinet/ip_var.h>
72#include <netinet/ip_options.h>
73#include <netinet/ip6.h>
74#include <netinet/icmp6.h>
75#include <netinet6/in6_pcb.h>
76#include <netinet6/ip6_var.h>
77#include <netinet6/nd6.h>
78#include <netinet/tcp.h>
79#include <netinet/tcp_fsm.h>
80#include <netinet/tcp_seq.h>
81#include <netinet/tcp_timer.h>
82#include <netinet/tcp_var.h>
83#include <netinet6/tcp6_var.h>
84#include <netinet/tcpip.h>
85#include <netinet/tcp_syncache.h>
86#ifdef TCPDEBUG
87#include <netinet/tcp_debug.h>
88#endif /* TCPDEBUG */
89
90#ifdef IPSEC
91#include <netipsec/ipsec.h>
92#include <netipsec/ipsec6.h>
93#endif /*IPSEC*/
94
95#include <machine/in_cksum.h>
96
97#include <security/mac/mac_framework.h>
98
99static const int tcprexmtthresh = 3;
100
101VNET_DEFINE(struct tcpstat, tcpstat);
102VNET_DEFINE(int, blackhole);
103VNET_DEFINE(int, tcp_delack_enabled);
104VNET_DEFINE(int, drop_synfin);
105VNET_DEFINE(int, tcp_do_rfc3042);
106VNET_DEFINE(int, tcp_do_rfc3390);
107VNET_DEFINE(int, tcp_do_ecn);
108VNET_DEFINE(int, tcp_ecn_maxretries);
109VNET_DEFINE(int, tcp_insecure_rst);
110VNET_DEFINE(int, tcp_do_autorcvbuf);
111VNET_DEFINE(int, tcp_autorcvbuf_inc);
112VNET_DEFINE(int, tcp_autorcvbuf_max);
113VNET_DEFINE(int, tcp_do_rfc3465);
114VNET_DEFINE(int, tcp_abc_l_var);
115
116SYSCTL_VNET_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RW,
117 &VNET_NAME(tcpstat), tcpstat,
118 "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
119
120int tcp_log_in_vain = 0;
121SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
122 &tcp_log_in_vain, 0,
123 "Log all incoming TCP segments to closed ports");
124
125SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, blackhole, CTLFLAG_RW,
126 &VNET_NAME(blackhole), 0,
127 "Do not send RST on segments to closed ports");
128
129SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
130 &VNET_NAME(tcp_delack_enabled), 0,
131 "Delay ACK to try and piggyback it onto a data packet");
132
133SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, drop_synfin, CTLFLAG_RW,
134 &VNET_NAME(drop_synfin), 0,
135 "Drop TCP packets with SYN+FIN set");
136
137SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3042, CTLFLAG_RW,
138 &VNET_NAME(tcp_do_rfc3042), 0,
139 "Enable RFC 3042 (Limited Transmit)");
140
141SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3390, CTLFLAG_RW,
142 &VNET_NAME(tcp_do_rfc3390), 0,
143 "Enable RFC 3390 (Increasing TCP's Initial Congestion Window)");
144
145SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, rfc3465, CTLFLAG_RW,
146 &VNET_NAME(tcp_do_rfc3465), 0,
147 "Enable RFC 3465 (Appropriate Byte Counting)");
148
149SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, abc_l_var, CTLFLAG_RW,
150 &VNET_NAME(tcp_abc_l_var), 2,
151 "Cap the max cwnd increment during slow-start to this number of segments");
152
153SYSCTL_NODE(_net_inet_tcp, OID_AUTO, ecn, CTLFLAG_RW, 0, "TCP ECN");
154
155SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, enable, CTLFLAG_RW,
156 &VNET_NAME(tcp_do_ecn), 0,
157 "TCP ECN support");
158
159SYSCTL_VNET_INT(_net_inet_tcp_ecn, OID_AUTO, maxretries, CTLFLAG_RW,
160 &VNET_NAME(tcp_ecn_maxretries), 0,
161 "Max retries before giving up on ECN");
162
163SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, insecure_rst, CTLFLAG_RW,
164 &VNET_NAME(tcp_insecure_rst), 0,
165 "Follow the old (insecure) criteria for accepting RST packets");
166
167SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_auto, CTLFLAG_RW,
168 &VNET_NAME(tcp_do_autorcvbuf), 0,
169 "Enable automatic receive buffer sizing");
170
171SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_inc, CTLFLAG_RW,
172 &VNET_NAME(tcp_autorcvbuf_inc), 0,
173 "Incrementor step size of automatic receive buffer");
174
175SYSCTL_VNET_INT(_net_inet_tcp, OID_AUTO, recvbuf_max, CTLFLAG_RW,
176 &VNET_NAME(tcp_autorcvbuf_max), 0,
177 "Max size of automatic receive buffer");
178
179int tcp_read_locking = 1;
180SYSCTL_INT(_net_inet_tcp, OID_AUTO, read_locking, CTLFLAG_RW,
181 &tcp_read_locking, 0, "Enable read locking strategy");
182
183int tcp_rlock_atfirst;
184SYSCTL_INT(_net_inet_tcp, OID_AUTO, rlock_atfirst, CTLFLAG_RD,
185 &tcp_rlock_atfirst, 0, "");
186
187int tcp_wlock_atfirst;
188SYSCTL_INT(_net_inet_tcp, OID_AUTO, tcp_wlock_atfirst, CTLFLAG_RD,
189 &tcp_wlock_atfirst, 0, "");
190
191int tcp_wlock_upgraded;
192SYSCTL_INT(_net_inet_tcp, OID_AUTO, wlock_upgraded, CTLFLAG_RD,
193 &tcp_wlock_upgraded, 0, "");
194
195int tcp_wlock_relocked;
196SYSCTL_INT(_net_inet_tcp, OID_AUTO, wlock_relocked, CTLFLAG_RD,
197 &tcp_wlock_relocked, 0, "");
198
199int tcp_wlock_looped;
200SYSCTL_INT(_net_inet_tcp, OID_AUTO, wlock_looped, CTLFLAG_RD,
201 &tcp_wlock_looped, 0, "");
202
203VNET_DEFINE(struct inpcbhead, tcb);
204VNET_DEFINE(struct inpcbinfo, tcbinfo);
205#define tcb6 tcb /* for KAME src sync over BSD*'s */
206
207static void tcp_dooptions(struct tcpopt *, u_char *, int, int);
208static void tcp_do_segment(struct mbuf *, struct tcphdr *,
209 struct socket *, struct tcpcb *, int, int, uint8_t,
210 int);
211static void tcp_dropwithreset(struct mbuf *, struct tcphdr *,
212 struct tcpcb *, int, int);
213static void tcp_pulloutofband(struct socket *,
214 struct tcphdr *, struct mbuf *, int);
215static void tcp_xmit_timer(struct tcpcb *, int);
216static void tcp_newreno_partial_ack(struct tcpcb *, struct tcphdr *);
217static void inline
218 tcp_congestion_exp(struct tcpcb *);
219
220/*
221 * Kernel module interface for updating tcpstat. The argument is an index
222 * into tcpstat treated as an array of u_long. While this encodes the
223 * general layout of tcpstat into the caller, it doesn't encode its location,
224 * so that future changes to add, for example, per-CPU stats support won't
225 * cause binary compatibility problems for kernel modules.
226 */
227void
228kmod_tcpstat_inc(int statnum)
229{
230
231 (*((u_long *)&V_tcpstat + statnum))++;
232}
233
234static void inline
235tcp_congestion_exp(struct tcpcb *tp)
236{
237 u_int win;
238
239 win = min(tp->snd_wnd, tp->snd_cwnd) /
240 2 / tp->t_maxseg;
241 if (win < 2)
242 win = 2;
243 tp->snd_ssthresh = win * tp->t_maxseg;
244 ENTER_FASTRECOVERY(tp);
245 tp->snd_recover = tp->snd_max;
246 if (tp->t_flags & TF_ECN_PERMIT)
247 tp->t_flags |= TF_ECN_SND_CWR;
248}
249
250/* Neighbor Discovery, Neighbor Unreachability Detection Upper layer hint. */
251#ifdef INET6
252#define ND6_HINT(tp) \
253do { \
254 if ((tp) && (tp)->t_inpcb && \
255 ((tp)->t_inpcb->inp_vflag & INP_IPV6) != 0) \
256 nd6_nud_hint(NULL, NULL, 0); \
257} while (0)
258#else
259#define ND6_HINT(tp)
260#endif
261
262/*
263 * Indicate whether this ack should be delayed. We can delay the ack if
264 * - there is no delayed ack timer in progress and
265 * - our last ack wasn't a 0-sized window. We never want to delay
266 * the ack that opens up a 0-sized window and
267 * - delayed acks are enabled or
268 * - this is a half-synchronized T/TCP connection.
269 */
270#define DELAY_ACK(tp) \
271 ((!tcp_timer_active(tp, TT_DELACK) && \
272 (tp->t_flags & TF_RXWIN0SENT) == 0) && \
273 (V_tcp_delack_enabled || (tp->t_flags & TF_NEEDSYN)))
274
275/*
276 * TCP input handling is split into multiple parts:
277 * tcp6_input is a thin wrapper around tcp_input for the extended
278 * ip6_protox[] call format in ip6_input
279 * tcp_input handles primary segment validation, inpcb lookup and
280 * SYN processing on listen sockets
281 * tcp_do_segment processes the ACK and text of the segment for
282 * establishing, established and closing connections
283 */
284#ifdef INET6
285int
286tcp6_input(struct mbuf **mp, int *offp, int proto)
287{
288 struct mbuf *m = *mp;
289 struct in6_ifaddr *ia6;
290
291 IP6_EXTHDR_CHECK(m, *offp, sizeof(struct tcphdr), IPPROTO_DONE);
292
293 /*
294 * draft-itojun-ipv6-tcp-to-anycast
295 * better place to put this in?
296 */
297 ia6 = ip6_getdstifaddr(m);
298 if (ia6 && (ia6->ia6_flags & IN6_IFF_ANYCAST)) {
299 struct ip6_hdr *ip6;
300
301 ifa_free(&ia6->ia_ifa);
302 ip6 = mtod(m, struct ip6_hdr *);
303 icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR,
304 (caddr_t)&ip6->ip6_dst - (caddr_t)ip6);
305 return IPPROTO_DONE;
306 }
307
308 tcp_input(m, *offp);
309 return IPPROTO_DONE;
310}
311#endif
312
313void
314tcp_input(struct mbuf *m, int off0)
315{
316 struct tcphdr *th;
317 struct ip *ip = NULL;
318 struct ipovly *ipov;
319 struct inpcb *inp = NULL;
320 struct tcpcb *tp = NULL;
321 struct socket *so = NULL;
322 u_char *optp = NULL;
323 int optlen = 0;
324 int len, tlen, off;
325 int drop_hdrlen;
326 int thflags;
327 int rstreason = 0; /* For badport_bandlim accounting purposes */
328 uint8_t iptos;
329#ifdef IPFIREWALL_FORWARD
330 struct m_tag *fwd_tag;
331#endif
332#ifdef INET6
333 struct ip6_hdr *ip6 = NULL;
334 int isipv6;
335#else
336 const void *ip6 = NULL;
337 const int isipv6 = 0;
338#endif
339 struct tcpopt to; /* options in this segment */
340 char *s = NULL; /* address and port logging */
341 int ti_locked;
342#define TI_UNLOCKED 1
343#define TI_RLOCKED 2
344#define TI_WLOCKED 3
345
346#ifdef TCPDEBUG
347 /*
348 * The size of tcp_saveipgen must be the size of the max ip header,
349 * now IPv6.
350 */
351 u_char tcp_saveipgen[IP6_HDR_LEN];
352 struct tcphdr tcp_savetcp;
353 short ostate = 0;
354#endif
355
356#ifdef INET6
357 isipv6 = (mtod(m, struct ip *)->ip_v == 6) ? 1 : 0;
358#endif
359
360 to.to_flags = 0;
361 TCPSTAT_INC(tcps_rcvtotal);
362
363 if (isipv6) {
364#ifdef INET6
365 /* IP6_EXTHDR_CHECK() is already done at tcp6_input(). */
366 ip6 = mtod(m, struct ip6_hdr *);
367 tlen = sizeof(*ip6) + ntohs(ip6->ip6_plen) - off0;
368 if (in6_cksum(m, IPPROTO_TCP, off0, tlen)) {
369 TCPSTAT_INC(tcps_rcvbadsum);
370 goto drop;
371 }
372 th = (struct tcphdr *)((caddr_t)ip6 + off0);
373
374 /*
375 * Be proactive about unspecified IPv6 address in source.
376 * As we use all-zero to indicate unbounded/unconnected pcb,
377 * unspecified IPv6 address can be used to confuse us.
378 *
379 * Note that packets with unspecified IPv6 destination is
380 * already dropped in ip6_input.
381 */
382 if (IN6_IS_ADDR_UNSPECIFIED(&ip6->ip6_src)) {
383 /* XXX stat */
384 goto drop;
385 }
386#else
387 th = NULL; /* XXX: Avoid compiler warning. */
388#endif
389 } else {
390 /*
391 * Get IP and TCP header together in first mbuf.
392 * Note: IP leaves IP header in first mbuf.
393 */
394 if (off0 > sizeof (struct ip)) {
395 ip_stripoptions(m, (struct mbuf *)0);
396 off0 = sizeof(struct ip);
397 }
398 if (m->m_len < sizeof (struct tcpiphdr)) {
399 if ((m = m_pullup(m, sizeof (struct tcpiphdr)))
400 == NULL) {
401 TCPSTAT_INC(tcps_rcvshort);
402 return;
403 }
404 }
405 ip = mtod(m, struct ip *);
406 ipov = (struct ipovly *)ip;
407 th = (struct tcphdr *)((caddr_t)ip + off0);
408 tlen = ip->ip_len;
409
410 if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
411 if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
412 th->th_sum = m->m_pkthdr.csum_data;
413 else
414 th->th_sum = in_pseudo(ip->ip_src.s_addr,
415 ip->ip_dst.s_addr,
416 htonl(m->m_pkthdr.csum_data +
417 ip->ip_len +
418 IPPROTO_TCP));
419 th->th_sum ^= 0xffff;
420#ifdef TCPDEBUG
421 ipov->ih_len = (u_short)tlen;
422 ipov->ih_len = htons(ipov->ih_len);
423#endif
424 } else {
425 /*
426 * Checksum extended TCP header and data.
427 */
428 len = sizeof (struct ip) + tlen;
429 bzero(ipov->ih_x1, sizeof(ipov->ih_x1));
430 ipov->ih_len = (u_short)tlen;
431 ipov->ih_len = htons(ipov->ih_len);
432 th->th_sum = in_cksum(m, len);
433 }
434 if (th->th_sum) {
435 TCPSTAT_INC(tcps_rcvbadsum);
436 goto drop;
437 }
438 /* Re-initialization for later version check */
439 ip->ip_v = IPVERSION;
440 }
441
442#ifdef INET6
443 if (isipv6)
444 iptos = (ntohl(ip6->ip6_flow) >> 20) & 0xff;
445 else
446#endif
447 iptos = ip->ip_tos;
448
449 /*
450 * Check that TCP offset makes sense,
451 * pull out TCP options and adjust length. XXX
452 */
453 off = th->th_off << 2;
454 if (off < sizeof (struct tcphdr) || off > tlen) {
455 TCPSTAT_INC(tcps_rcvbadoff);
456 goto drop;
457 }
458 tlen -= off; /* tlen is used instead of ti->ti_len */
459 if (off > sizeof (struct tcphdr)) {
460 if (isipv6) {
461#ifdef INET6
462 IP6_EXTHDR_CHECK(m, off0, off, );
463 ip6 = mtod(m, struct ip6_hdr *);
464 th = (struct tcphdr *)((caddr_t)ip6 + off0);
465#endif
466 } else {
467 if (m->m_len < sizeof(struct ip) + off) {
468 if ((m = m_pullup(m, sizeof (struct ip) + off))
469 == NULL) {
470 TCPSTAT_INC(tcps_rcvshort);
471 return;
472 }
473 ip = mtod(m, struct ip *);
474 ipov = (struct ipovly *)ip;
475 th = (struct tcphdr *)((caddr_t)ip + off0);
476 }
477 }
478 optlen = off - sizeof (struct tcphdr);
479 optp = (u_char *)(th + 1);
480 }
481 thflags = th->th_flags;
482
483 /*
484 * Convert TCP protocol specific fields to host format.
485 */
486 th->th_seq = ntohl(th->th_seq);
487 th->th_ack = ntohl(th->th_ack);
488 th->th_win = ntohs(th->th_win);
489 th->th_urp = ntohs(th->th_urp);
490
491 /*
492 * Delay dropping TCP, IP headers, IPv6 ext headers, and TCP options.
493 */
494 drop_hdrlen = off0 + off;
495
496 /*
497 * Locate pcb for segment, which requires a lock on tcbinfo.
498 * Optimisticaly acquire a global read lock rather than a write lock
499 * unless header flags necessarily imply a state change. There are
500 * two cases where we might discover later we need a write lock
501 * despite the flags: ACKs moving a connection out of the syncache,
502 * and ACKs for a connection in TIMEWAIT.
503 */
504 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
505 tcp_read_locking == 0) {
506 INP_INFO_WLOCK(&V_tcbinfo);
507 ti_locked = TI_WLOCKED;
508 tcp_wlock_atfirst++;
509 } else {
510 INP_INFO_RLOCK(&V_tcbinfo);
511 ti_locked = TI_RLOCKED;
512 tcp_rlock_atfirst++;
513 }
514
515findpcb:
516#ifdef INVARIANTS
517 if (ti_locked == TI_RLOCKED)
518 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
519 else if (ti_locked == TI_WLOCKED)
520 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
521 else
522 panic("%s: findpcb ti_locked %d\n", __func__, ti_locked);
523#endif
524
525#ifdef IPFIREWALL_FORWARD
526 /*
527 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
528 */
529 fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
530
531 if (fwd_tag != NULL && isipv6 == 0) { /* IPv6 support is not yet */
532 struct sockaddr_in *next_hop;
533
534 next_hop = (struct sockaddr_in *)(fwd_tag+1);
535 /*
536 * Transparently forwarded. Pretend to be the destination.
537 * already got one like this?
538 */
539 inp = in_pcblookup_hash(&V_tcbinfo,
540 ip->ip_src, th->th_sport,
541 ip->ip_dst, th->th_dport,
542 0, m->m_pkthdr.rcvif);
543 if (!inp) {
544 /* It's new. Try to find the ambushing socket. */
545 inp = in_pcblookup_hash(&V_tcbinfo,
546 ip->ip_src, th->th_sport,
547 next_hop->sin_addr,
548 next_hop->sin_port ?
549 ntohs(next_hop->sin_port) :
550 th->th_dport,
551 INPLOOKUP_WILDCARD,
552 m->m_pkthdr.rcvif);
553 }
554 /* Remove the tag from the packet. We don't need it anymore. */
555 m_tag_delete(m, fwd_tag);
556 } else
557#endif /* IPFIREWALL_FORWARD */
558 {
559 if (isipv6) {
560#ifdef INET6
561 inp = in6_pcblookup_hash(&V_tcbinfo,
562 &ip6->ip6_src, th->th_sport,
563 &ip6->ip6_dst, th->th_dport,
564 INPLOOKUP_WILDCARD,
565 m->m_pkthdr.rcvif);
566#endif
567 } else
568 inp = in_pcblookup_hash(&V_tcbinfo,
569 ip->ip_src, th->th_sport,
570 ip->ip_dst, th->th_dport,
571 INPLOOKUP_WILDCARD,
572 m->m_pkthdr.rcvif);
573 }
574
575 /*
576 * If the INPCB does not exist then all data in the incoming
577 * segment is discarded and an appropriate RST is sent back.
578 * XXX MRT Send RST using which routing table?
579 */
580 if (inp == NULL) {
581 /*
582 * Log communication attempts to ports that are not
583 * in use.
584 */
585 if ((tcp_log_in_vain == 1 && (thflags & TH_SYN)) ||
586 tcp_log_in_vain == 2) {
587 if ((s = tcp_log_addrs(NULL, th, (void *)ip, ip6)))
588 log(LOG_INFO, "%s; %s: Connection attempt "
589 "to closed port\n", s, __func__);
590 }
591 /*
592 * When blackholing do not respond with a RST but
593 * completely ignore the segment and drop it.
594 */
595 if ((V_blackhole == 1 && (thflags & TH_SYN)) ||
596 V_blackhole == 2)
597 goto dropunlock;
598
599 rstreason = BANDLIM_RST_CLOSEDPORT;
600 goto dropwithreset;
601 }
602 INP_WLOCK(inp);
603 if (!(inp->inp_flags & INP_HW_FLOWID)
604 && (m->m_flags & M_FLOWID)
605 && ((inp->inp_socket == NULL)
606 || !(inp->inp_socket->so_options & SO_ACCEPTCONN))) {
607 inp->inp_flags |= INP_HW_FLOWID;
608 inp->inp_flags &= ~INP_SW_FLOWID;
609 inp->inp_flowid = m->m_pkthdr.flowid;
610 }
611#ifdef IPSEC
612#ifdef INET6
613 if (isipv6 && ipsec6_in_reject(m, inp)) {
614 V_ipsec6stat.in_polvio++;
615 goto dropunlock;
616 } else
617#endif /* INET6 */
618 if (ipsec4_in_reject(m, inp) != 0) {
619 V_ipsec4stat.in_polvio++;
620 goto dropunlock;
621 }
622#endif /* IPSEC */
623
624 /*
625 * Check the minimum TTL for socket.
626 */
627 if (inp->inp_ip_minttl != 0) {
628#ifdef INET6
629 if (isipv6 && inp->inp_ip_minttl > ip6->ip6_hlim)
630 goto dropunlock;
631 else
632#endif
633 if (inp->inp_ip_minttl > ip->ip_ttl)
634 goto dropunlock;
635 }
636
637 /*
638 * A previous connection in TIMEWAIT state is supposed to catch stray
639 * or duplicate segments arriving late. If this segment was a
640 * legitimate new connection attempt the old INPCB gets removed and
641 * we can try again to find a listening socket.
642 *
643 * At this point, due to earlier optimism, we may hold a read lock on
644 * the inpcbinfo, rather than a write lock. If so, we need to
645 * upgrade, or if that fails, acquire a reference on the inpcb, drop
646 * all locks, acquire a global write lock, and then re-acquire the
647 * inpcb lock. We may at that point discover that another thread has
648 * tried to free the inpcb, in which case we need to loop back and
649 * try to find a new inpcb to deliver to.
650 */
651 if (inp->inp_flags & INP_TIMEWAIT) {
652 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
653 ("%s: INP_TIMEWAIT ti_locked %d", __func__, ti_locked));
654
655 if (ti_locked == TI_RLOCKED) {
656 if (rw_try_upgrade(&V_tcbinfo.ipi_lock) == 0) {
657 in_pcbref(inp);
658 INP_WUNLOCK(inp);
659 INP_INFO_RUNLOCK(&V_tcbinfo);
660 INP_INFO_WLOCK(&V_tcbinfo);
661 ti_locked = TI_WLOCKED;
662 INP_WLOCK(inp);
663 if (in_pcbrele(inp)) {
664 tcp_wlock_looped++;
665 inp = NULL;
666 goto findpcb;
667 }
668 tcp_wlock_relocked++;
669 } else {
670 ti_locked = TI_WLOCKED;
671 tcp_wlock_upgraded++;
672 }
673 }
674 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
675
676 if (thflags & TH_SYN)
677 tcp_dooptions(&to, optp, optlen, TO_SYN);
678 /*
679 * NB: tcp_twcheck unlocks the INP and frees the mbuf.
680 */
681 if (tcp_twcheck(inp, &to, th, m, tlen))
682 goto findpcb;
683 INP_INFO_WUNLOCK(&V_tcbinfo);
684 return;
685 }
686 /*
687 * The TCPCB may no longer exist if the connection is winding
688 * down or it is in the CLOSED state. Either way we drop the
689 * segment and send an appropriate response.
690 */
691 tp = intotcpcb(inp);
692 if (tp == NULL || tp->t_state == TCPS_CLOSED) {
693 rstreason = BANDLIM_RST_CLOSEDPORT;
694 goto dropwithreset;
695 }
696
697 /*
698 * We've identified a valid inpcb, but it could be that we need an
699 * inpcbinfo write lock and have only a read lock. In this case,
700 * attempt to upgrade/relock using the same strategy as the TIMEWAIT
701 * case above.
702 */
703 if (tp->t_state != TCPS_ESTABLISHED ||
704 (thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
705 tcp_read_locking == 0) {
706 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
707 ("%s: upgrade check ti_locked %d", __func__, ti_locked));
708
709 if (ti_locked == TI_RLOCKED) {
710 if (rw_try_upgrade(&V_tcbinfo.ipi_lock) == 0) {
711 in_pcbref(inp);
712 INP_WUNLOCK(inp);
713 INP_INFO_RUNLOCK(&V_tcbinfo);
714 INP_INFO_WLOCK(&V_tcbinfo);
715 ti_locked = TI_WLOCKED;
716 INP_WLOCK(inp);
717 if (in_pcbrele(inp)) {
718 tcp_wlock_looped++;
719 inp = NULL;
720 goto findpcb;
721 }
722 tcp_wlock_relocked++;
723 } else {
724 ti_locked = TI_WLOCKED;
725 tcp_wlock_upgraded++;
726 }
727 }
728 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
729 }
730
731#ifdef MAC
732 INP_WLOCK_ASSERT(inp);
733 if (mac_inpcb_check_deliver(inp, m))
734 goto dropunlock;
735#endif
736 so = inp->inp_socket;
737 KASSERT(so != NULL, ("%s: so == NULL", __func__));
738#ifdef TCPDEBUG
739 if (so->so_options & SO_DEBUG) {
740 ostate = tp->t_state;
741 if (isipv6) {
742#ifdef INET6
743 bcopy((char *)ip6, (char *)tcp_saveipgen, sizeof(*ip6));
744#endif
745 } else
746 bcopy((char *)ip, (char *)tcp_saveipgen, sizeof(*ip));
747 tcp_savetcp = *th;
748 }
749#endif
750 /*
751 * When the socket is accepting connections (the INPCB is in LISTEN
752 * state) we look into the SYN cache if this is a new connection
753 * attempt or the completion of a previous one.
754 */
755 if (so->so_options & SO_ACCEPTCONN) {
756 struct in_conninfo inc;
757
758 KASSERT(tp->t_state == TCPS_LISTEN, ("%s: so accepting but "
759 "tp not listening", __func__));
760
761 bzero(&inc, sizeof(inc));
762#ifdef INET6
763 if (isipv6) {
764 inc.inc_flags |= INC_ISIPV6;
765 inc.inc6_faddr = ip6->ip6_src;
766 inc.inc6_laddr = ip6->ip6_dst;
767 } else
768#endif
769 {
770 inc.inc_faddr = ip->ip_src;
771 inc.inc_laddr = ip->ip_dst;
772 }
773 inc.inc_fport = th->th_sport;
774 inc.inc_lport = th->th_dport;
775 inc.inc_fibnum = so->so_fibnum;
776
777 /*
778 * Check for an existing connection attempt in syncache if
779 * the flag is only ACK. A successful lookup creates a new
780 * socket appended to the listen queue in SYN_RECEIVED state.
781 */
782 if ((thflags & (TH_RST|TH_ACK|TH_SYN)) == TH_ACK) {
783 /*
784 * Parse the TCP options here because
785 * syncookies need access to the reflected
786 * timestamp.
787 */
788 tcp_dooptions(&to, optp, optlen, 0);
789 /*
790 * NB: syncache_expand() doesn't unlock
791 * inp and tcpinfo locks.
792 */
793 if (!syncache_expand(&inc, &to, th, &so, m)) {
794 /*
795 * No syncache entry or ACK was not
796 * for our SYN/ACK. Send a RST.
797 * NB: syncache did its own logging
798 * of the failure cause.
799 */
800 rstreason = BANDLIM_RST_OPENPORT;
801 goto dropwithreset;
802 }
803 if (so == NULL) {
804 /*
805 * We completed the 3-way handshake
806 * but could not allocate a socket
807 * either due to memory shortage,
808 * listen queue length limits or
809 * global socket limits. Send RST
810 * or wait and have the remote end
811 * retransmit the ACK for another
812 * try.
813 */
814 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
815 log(LOG_DEBUG, "%s; %s: Listen socket: "
816 "Socket allocation failed due to "
817 "limits or memory shortage, %s\n",
818 s, __func__,
819 V_tcp_sc_rst_sock_fail ?
820 "sending RST" : "try again");
821 if (V_tcp_sc_rst_sock_fail) {
822 rstreason = BANDLIM_UNLIMITED;
823 goto dropwithreset;
824 } else
825 goto dropunlock;
826 }
827 /*
828 * Socket is created in state SYN_RECEIVED.
829 * Unlock the listen socket, lock the newly
830 * created socket and update the tp variable.
831 */
832 INP_WUNLOCK(inp); /* listen socket */
833 inp = sotoinpcb(so);
834 INP_WLOCK(inp); /* new connection */
835 tp = intotcpcb(inp);
836 KASSERT(tp->t_state == TCPS_SYN_RECEIVED,
837 ("%s: ", __func__));
838 /*
839 * Process the segment and the data it
840 * contains. tcp_do_segment() consumes
841 * the mbuf chain and unlocks the inpcb.
842 */
843 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen,
844 iptos, ti_locked);
845 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
846 return;
847 }
848 /*
849 * Segment flag validation for new connection attempts:
850 *
851 * Our (SYN|ACK) response was rejected.
852 * Check with syncache and remove entry to prevent
853 * retransmits.
854 *
855 * NB: syncache_chkrst does its own logging of failure
856 * causes.
857 */
858 if (thflags & TH_RST) {
859 syncache_chkrst(&inc, th);
860 goto dropunlock;
861 }
862 /*
863 * We can't do anything without SYN.
864 */
865 if ((thflags & TH_SYN) == 0) {
866 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
867 log(LOG_DEBUG, "%s; %s: Listen socket: "
868 "SYN is missing, segment ignored\n",
869 s, __func__);
870 TCPSTAT_INC(tcps_badsyn);
871 goto dropunlock;
872 }
873 /*
874 * (SYN|ACK) is bogus on a listen socket.
875 */
876 if (thflags & TH_ACK) {
877 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
878 log(LOG_DEBUG, "%s; %s: Listen socket: "
879 "SYN|ACK invalid, segment rejected\n",
880 s, __func__);
881 syncache_badack(&inc); /* XXX: Not needed! */
882 TCPSTAT_INC(tcps_badsyn);
883 rstreason = BANDLIM_RST_OPENPORT;
884 goto dropwithreset;
885 }
886 /*
887 * If the drop_synfin option is enabled, drop all
888 * segments with both the SYN and FIN bits set.
889 * This prevents e.g. nmap from identifying the
890 * TCP/IP stack.
891 * XXX: Poor reasoning. nmap has other methods
892 * and is constantly refining its stack detection
893 * strategies.
894 * XXX: This is a violation of the TCP specification
895 * and was used by RFC1644.
896 */
897 if ((thflags & TH_FIN) && V_drop_synfin) {
898 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
899 log(LOG_DEBUG, "%s; %s: Listen socket: "
900 "SYN|FIN segment ignored (based on "
901 "sysctl setting)\n", s, __func__);
902 TCPSTAT_INC(tcps_badsyn);
903 goto dropunlock;
904 }
905 /*
906 * Segment's flags are (SYN) or (SYN|FIN).
907 *
908 * TH_PUSH, TH_URG, TH_ECE, TH_CWR are ignored
909 * as they do not affect the state of the TCP FSM.
910 * The data pointed to by TH_URG and th_urp is ignored.
911 */
912 KASSERT((thflags & (TH_RST|TH_ACK)) == 0,
913 ("%s: Listen socket: TH_RST or TH_ACK set", __func__));
914 KASSERT(thflags & (TH_SYN),
915 ("%s: Listen socket: TH_SYN not set", __func__));
916#ifdef INET6
917 /*
918 * If deprecated address is forbidden,
919 * we do not accept SYN to deprecated interface
920 * address to prevent any new inbound connection from
921 * getting established.
922 * When we do not accept SYN, we send a TCP RST,
923 * with deprecated source address (instead of dropping
924 * it). We compromise it as it is much better for peer
925 * to send a RST, and RST will be the final packet
926 * for the exchange.
927 *
928 * If we do not forbid deprecated addresses, we accept
929 * the SYN packet. RFC2462 does not suggest dropping
930 * SYN in this case.
931 * If we decipher RFC2462 5.5.4, it says like this:
932 * 1. use of deprecated addr with existing
933 * communication is okay - "SHOULD continue to be
934 * used"
935 * 2. use of it with new communication:
936 * (2a) "SHOULD NOT be used if alternate address
937 * with sufficient scope is available"
938 * (2b) nothing mentioned otherwise.
939 * Here we fall into (2b) case as we have no choice in
940 * our source address selection - we must obey the peer.
941 *
942 * The wording in RFC2462 is confusing, and there are
943 * multiple description text for deprecated address
944 * handling - worse, they are not exactly the same.
945 * I believe 5.5.4 is the best one, so we follow 5.5.4.
946 */
947 if (isipv6 && !V_ip6_use_deprecated) {
948 struct in6_ifaddr *ia6;
949
950 ia6 = ip6_getdstifaddr(m);
951 if (ia6 != NULL &&
952 (ia6->ia6_flags & IN6_IFF_DEPRECATED)) {
953 ifa_free(&ia6->ia_ifa);
954 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
955 log(LOG_DEBUG, "%s; %s: Listen socket: "
956 "Connection attempt to deprecated "
957 "IPv6 address rejected\n",
958 s, __func__);
959 rstreason = BANDLIM_RST_OPENPORT;
960 goto dropwithreset;
961 }
962 ifa_free(&ia6->ia_ifa);
963 }
964#endif
965 /*
966 * Basic sanity checks on incoming SYN requests:
967 * Don't respond if the destination is a link layer
968 * broadcast according to RFC1122 4.2.3.10, p. 104.
969 * If it is from this socket it must be forged.
970 * Don't respond if the source or destination is a
971 * global or subnet broad- or multicast address.
972 * Note that it is quite possible to receive unicast
973 * link-layer packets with a broadcast IP address. Use
974 * in_broadcast() to find them.
975 */
976 if (m->m_flags & (M_BCAST|M_MCAST)) {
977 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
978 log(LOG_DEBUG, "%s; %s: Listen socket: "
979 "Connection attempt from broad- or multicast "
980 "link layer address ignored\n", s, __func__);
981 goto dropunlock;
982 }
983 if (isipv6) {
984#ifdef INET6
985 if (th->th_dport == th->th_sport &&
986 IN6_ARE_ADDR_EQUAL(&ip6->ip6_dst, &ip6->ip6_src)) {
987 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
988 log(LOG_DEBUG, "%s; %s: Listen socket: "
989 "Connection attempt to/from self "
990 "ignored\n", s, __func__);
991 goto dropunlock;
992 }
993 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
994 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src)) {
995 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
996 log(LOG_DEBUG, "%s; %s: Listen socket: "
997 "Connection attempt from/to multicast "
998 "address ignored\n", s, __func__);
999 goto dropunlock;
1000 }
1001#endif
1002 } else {
1003 if (th->th_dport == th->th_sport &&
1004 ip->ip_dst.s_addr == ip->ip_src.s_addr) {
1005 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1006 log(LOG_DEBUG, "%s; %s: Listen socket: "
1007 "Connection attempt from/to self "
1008 "ignored\n", s, __func__);
1009 goto dropunlock;
1010 }
1011 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
1012 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
1013 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
1014 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
1015 if ((s = tcp_log_addrs(&inc, th, NULL, NULL)))
1016 log(LOG_DEBUG, "%s; %s: Listen socket: "
1017 "Connection attempt from/to broad- "
1018 "or multicast address ignored\n",
1019 s, __func__);
1020 goto dropunlock;
1021 }
1022 }
1023 /*
1024 * SYN appears to be valid. Create compressed TCP state
1025 * for syncache.
1026 */
1027#ifdef TCPDEBUG
1028 if (so->so_options & SO_DEBUG)
1029 tcp_trace(TA_INPUT, ostate, tp,
1030 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1031#endif
1032 tcp_dooptions(&to, optp, optlen, TO_SYN);
1033 syncache_add(&inc, &to, th, inp, &so, m);
1034 /*
1035 * Entry added to syncache and mbuf consumed.
1036 * Everything already unlocked by syncache_add().
1037 */
1038 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1039 return;
1040 }
1041
1042 /*
1043 * Segment belongs to a connection in SYN_SENT, ESTABLISHED or later
1044 * state. tcp_do_segment() always consumes the mbuf chain, unlocks
1045 * the inpcb, and unlocks pcbinfo.
1046 */
1047 tcp_do_segment(m, th, so, tp, drop_hdrlen, tlen, iptos, ti_locked);
1048 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1049 return;
1050
1051dropwithreset:
1052 if (ti_locked == TI_RLOCKED)
1053 INP_INFO_RUNLOCK(&V_tcbinfo);
1054 else if (ti_locked == TI_WLOCKED)
1055 INP_INFO_WUNLOCK(&V_tcbinfo);
1056 else
1057 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
1058 ti_locked = TI_UNLOCKED;
1059
1060 if (inp != NULL) {
1061 tcp_dropwithreset(m, th, tp, tlen, rstreason);
1062 INP_WUNLOCK(inp);
1063 } else
1064 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
1065 m = NULL; /* mbuf chain got consumed. */
1066 goto drop;
1067
1068dropunlock:
1069 if (ti_locked == TI_RLOCKED)
1070 INP_INFO_RUNLOCK(&V_tcbinfo);
1071 else if (ti_locked == TI_WLOCKED)
1072 INP_INFO_WUNLOCK(&V_tcbinfo);
1073 else
1074 panic("%s: dropunlock ti_locked %d", __func__, ti_locked);
1075 ti_locked = TI_UNLOCKED;
1076
1077 if (inp != NULL)
1078 INP_WUNLOCK(inp);
1079
1080drop:
1081 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
1082 if (s != NULL)
1083 free(s, M_TCPLOG);
1084 if (m != NULL)
1085 m_freem(m);
1086}
1087
1088static void
1089tcp_do_segment(struct mbuf *m, struct tcphdr *th, struct socket *so,
1090 struct tcpcb *tp, int drop_hdrlen, int tlen, uint8_t iptos,
1091 int ti_locked)
1092{
1093 int thflags, acked, ourfinisacked, needoutput = 0;
1094 int rstreason, todrop, win;
1095 u_long tiwin;
1096 struct tcpopt to;
1097
1098#ifdef TCPDEBUG
1099 /*
1100 * The size of tcp_saveipgen must be the size of the max ip header,
1101 * now IPv6.
1102 */
1103 u_char tcp_saveipgen[IP6_HDR_LEN];
1104 struct tcphdr tcp_savetcp;
1105 short ostate = 0;
1106#endif
1107 thflags = th->th_flags;
1108
1109 /*
1110 * If this is either a state-changing packet or current state isn't
1111 * established, we require a write lock on tcbinfo. Otherwise, we
1112 * allow either a read lock or a write lock, as we may have acquired
1113 * a write lock due to a race.
1114 *
1115 * Require a global write lock for SYN/FIN/RST segments or
1116 * non-established connections; otherwise accept either a read or
1117 * write lock, as we may have conservatively acquired a write lock in
1118 * certain cases in tcp_input() (is this still true?). Currently we
1119 * will never enter with no lock, so we try to drop it quickly in the
1120 * common pure ack/pure data cases.
1121 */
1122 if ((thflags & (TH_SYN | TH_FIN | TH_RST)) != 0 ||
1123 tp->t_state != TCPS_ESTABLISHED) {
1124 KASSERT(ti_locked == TI_WLOCKED, ("%s ti_locked %d for "
1125 "SYN/FIN/RST/!EST", __func__, ti_locked));
1126 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1127 } else {
1128#ifdef INVARIANTS
1129 if (ti_locked == TI_RLOCKED)
1130 INP_INFO_RLOCK_ASSERT(&V_tcbinfo);
1131 else if (ti_locked == TI_WLOCKED)
1132 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1133 else
1134 panic("%s: ti_locked %d for EST", __func__,
1135 ti_locked);
1136#endif
1137 }
1138 INP_WLOCK_ASSERT(tp->t_inpcb);
1139 KASSERT(tp->t_state > TCPS_LISTEN, ("%s: TCPS_LISTEN",
1140 __func__));
1141 KASSERT(tp->t_state != TCPS_TIME_WAIT, ("%s: TCPS_TIME_WAIT",
1142 __func__));
1143
1144 /*
1145 * Segment received on connection.
1146 * Reset idle time and keep-alive timer.
1147 * XXX: This should be done after segment
1148 * validation to ignore broken/spoofed segs.
1149 */
1150 tp->t_rcvtime = ticks;
1151 if (TCPS_HAVEESTABLISHED(tp->t_state))
1152 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1153
1154 /*
1155 * Unscale the window into a 32-bit value.
1156 * For the SYN_SENT state the scale is zero.
1157 */
1158 tiwin = th->th_win << tp->snd_scale;
1159
1160 /*
1161 * TCP ECN processing.
1162 */
1163 if (tp->t_flags & TF_ECN_PERMIT) {
1164 switch (iptos & IPTOS_ECN_MASK) {
1165 case IPTOS_ECN_CE:
1166 tp->t_flags |= TF_ECN_SND_ECE;
1167 TCPSTAT_INC(tcps_ecn_ce);
1168 break;
1169 case IPTOS_ECN_ECT0:
1170 TCPSTAT_INC(tcps_ecn_ect0);
1171 break;
1172 case IPTOS_ECN_ECT1:
1173 TCPSTAT_INC(tcps_ecn_ect1);
1174 break;
1175 }
1176
1177 if (thflags & TH_CWR)
1178 tp->t_flags &= ~TF_ECN_SND_ECE;
1179
1180 /*
1181 * Congestion experienced.
1182 * Ignore if we are already trying to recover.
1183 */
1184 if ((thflags & TH_ECE) &&
1185 SEQ_LEQ(th->th_ack, tp->snd_recover)) {
1186 TCPSTAT_INC(tcps_ecn_rcwnd);
1187 tcp_congestion_exp(tp);
1188 }
1189 }
1190
1191 /*
1192 * Parse options on any incoming segment.
1193 */
1194 tcp_dooptions(&to, (u_char *)(th + 1),
1195 (th->th_off << 2) - sizeof(struct tcphdr),
1196 (thflags & TH_SYN) ? TO_SYN : 0);
1197
1198 /*
1199 * If echoed timestamp is later than the current time,
1200 * fall back to non RFC1323 RTT calculation. Normalize
1201 * timestamp if syncookies were used when this connection
1202 * was established.
1203 */
1204 if ((to.to_flags & TOF_TS) && (to.to_tsecr != 0)) {
1205 to.to_tsecr -= tp->ts_offset;
1206 if (TSTMP_GT(to.to_tsecr, ticks))
1207 to.to_tsecr = 0;
1208 }
1209
1210 /*
1211 * Process options only when we get SYN/ACK back. The SYN case
1212 * for incoming connections is handled in tcp_syncache.
1213 * According to RFC1323 the window field in a SYN (i.e., a <SYN>
1214 * or <SYN,ACK>) segment itself is never scaled.
1215 * XXX this is traditional behavior, may need to be cleaned up.
1216 */
1217 if (tp->t_state == TCPS_SYN_SENT && (thflags & TH_SYN)) {
1218 if ((to.to_flags & TOF_SCALE) &&
1219 (tp->t_flags & TF_REQ_SCALE)) {
1220 tp->t_flags |= TF_RCVD_SCALE;
1221 tp->snd_scale = to.to_wscale;
1222 }
1223 /*
1224 * Initial send window. It will be updated with
1225 * the next incoming segment to the scaled value.
1226 */
1227 tp->snd_wnd = th->th_win;
1228 if (to.to_flags & TOF_TS) {
1229 tp->t_flags |= TF_RCVD_TSTMP;
1230 tp->ts_recent = to.to_tsval;
1231 tp->ts_recent_age = ticks;
1232 }
1233 if (to.to_flags & TOF_MSS)
1234 tcp_mss(tp, to.to_mss);
1235 if ((tp->t_flags & TF_SACK_PERMIT) &&
1236 (to.to_flags & TOF_SACKPERM) == 0)
1237 tp->t_flags &= ~TF_SACK_PERMIT;
1238 }
1239
1240 /*
1241 * Header prediction: check for the two common cases
1242 * of a uni-directional data xfer. If the packet has
1243 * no control flags, is in-sequence, the window didn't
1244 * change and we're not retransmitting, it's a
1245 * candidate. If the length is zero and the ack moved
1246 * forward, we're the sender side of the xfer. Just
1247 * free the data acked & wake any higher level process
1248 * that was blocked waiting for space. If the length
1249 * is non-zero and the ack didn't move, we're the
1250 * receiver side. If we're getting packets in-order
1251 * (the reassembly queue is empty), add the data to
1252 * the socket buffer and note that we need a delayed ack.
1253 * Make sure that the hidden state-flags are also off.
1254 * Since we check for TCPS_ESTABLISHED first, it can only
1255 * be TH_NEEDSYN.
1256 */
1257 if (tp->t_state == TCPS_ESTABLISHED &&
1258 th->th_seq == tp->rcv_nxt &&
1259 (thflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
1260 tp->snd_nxt == tp->snd_max &&
1261 tiwin && tiwin == tp->snd_wnd &&
1262 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
1263 LIST_EMPTY(&tp->t_segq) &&
1264 ((to.to_flags & TOF_TS) == 0 ||
1265 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) ) {
1266
1267 /*
1268 * If last ACK falls within this segment's sequence numbers,
1269 * record the timestamp.
1270 * NOTE that the test is modified according to the latest
1271 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1272 */
1273 if ((to.to_flags & TOF_TS) != 0 &&
1274 SEQ_LEQ(th->th_seq, tp->last_ack_sent)) {
1275 tp->ts_recent_age = ticks;
1276 tp->ts_recent = to.to_tsval;
1277 }
1278
1279 if (tlen == 0) {
1280 if (SEQ_GT(th->th_ack, tp->snd_una) &&
1281 SEQ_LEQ(th->th_ack, tp->snd_max) &&
1282 tp->snd_cwnd >= tp->snd_wnd &&
1283 ((!V_tcp_do_newreno &&
1284 !(tp->t_flags & TF_SACK_PERMIT) &&
1285 tp->t_dupacks < tcprexmtthresh) ||
1286 ((V_tcp_do_newreno ||
1287 (tp->t_flags & TF_SACK_PERMIT)) &&
1288 !IN_FASTRECOVERY(tp) &&
1289 (to.to_flags & TOF_SACK) == 0 &&
1290 TAILQ_EMPTY(&tp->snd_holes)))) {
1291 /*
1292 * This is a pure ack for outstanding data.
1293 */
1294 if (ti_locked == TI_RLOCKED)
1295 INP_INFO_RUNLOCK(&V_tcbinfo);
1296 else if (ti_locked == TI_WLOCKED)
1297 INP_INFO_WUNLOCK(&V_tcbinfo);
1298 else
1299 panic("%s: ti_locked %d on pure ACK",
1300 __func__, ti_locked);
1301 ti_locked = TI_UNLOCKED;
1302
1303 TCPSTAT_INC(tcps_predack);
1304
1305 /*
1306 * "bad retransmit" recovery.
1307 */
1308 if (tp->t_rxtshift == 1 &&
1309 (int)(ticks - tp->t_badrxtwin) < 0) {
1310 TCPSTAT_INC(tcps_sndrexmitbad);
1311 tp->snd_cwnd = tp->snd_cwnd_prev;
1312 tp->snd_ssthresh =
1313 tp->snd_ssthresh_prev;
1314 tp->snd_recover = tp->snd_recover_prev;
1315 if (tp->t_flags & TF_WASFRECOVERY)
1316 ENTER_FASTRECOVERY(tp);
1317 tp->snd_nxt = tp->snd_max;
1318 tp->t_badrxtwin = 0;
1319 }
1320
1321 /*
1322 * Recalculate the transmit timer / rtt.
1323 *
1324 * Some boxes send broken timestamp replies
1325 * during the SYN+ACK phase, ignore
1326 * timestamps of 0 or we could calculate a
1327 * huge RTT and blow up the retransmit timer.
1328 */
1329 if ((to.to_flags & TOF_TS) != 0 &&
1330 to.to_tsecr) {
1331 if (!tp->t_rttlow ||
1332 tp->t_rttlow > ticks - to.to_tsecr)
1333 tp->t_rttlow = ticks - to.to_tsecr;
1334 tcp_xmit_timer(tp,
1335 ticks - to.to_tsecr + 1);
1336 } else if (tp->t_rtttime &&
1337 SEQ_GT(th->th_ack, tp->t_rtseq)) {
1338 if (!tp->t_rttlow ||
1339 tp->t_rttlow > ticks - tp->t_rtttime)
1340 tp->t_rttlow = ticks - tp->t_rtttime;
1341 tcp_xmit_timer(tp,
1342 ticks - tp->t_rtttime);
1343 }
1344 tcp_xmit_bandwidth_limit(tp, th->th_ack);
1345 acked = th->th_ack - tp->snd_una;
1346 TCPSTAT_INC(tcps_rcvackpack);
1347 TCPSTAT_ADD(tcps_rcvackbyte, acked);
1348 sbdrop(&so->so_snd, acked);
1349 if (SEQ_GT(tp->snd_una, tp->snd_recover) &&
1350 SEQ_LEQ(th->th_ack, tp->snd_recover))
1351 tp->snd_recover = th->th_ack - 1;
1352 tp->snd_una = th->th_ack;
1353 /*
1354 * Pull snd_wl2 up to prevent seq wrap relative
1355 * to th_ack.
1356 */
1357 tp->snd_wl2 = th->th_ack;
1358 tp->t_dupacks = 0;
1359 m_freem(m);
1360 ND6_HINT(tp); /* Some progress has been made. */
1361
1362 /*
1363 * If all outstanding data are acked, stop
1364 * retransmit timer, otherwise restart timer
1365 * using current (possibly backed-off) value.
1366 * If process is waiting for space,
1367 * wakeup/selwakeup/signal. If data
1368 * are ready to send, let tcp_output
1369 * decide between more output or persist.
1370 */
1371#ifdef TCPDEBUG
1372 if (so->so_options & SO_DEBUG)
1373 tcp_trace(TA_INPUT, ostate, tp,
1374 (void *)tcp_saveipgen,
1375 &tcp_savetcp, 0);
1376#endif
1377 if (tp->snd_una == tp->snd_max)
1378 tcp_timer_activate(tp, TT_REXMT, 0);
1379 else if (!tcp_timer_active(tp, TT_PERSIST))
1380 tcp_timer_activate(tp, TT_REXMT,
1381 tp->t_rxtcur);
1382 sowwakeup(so);
1383 if (so->so_snd.sb_cc)
1384 (void) tcp_output(tp);
1385 goto check_delack;
1386 }
1387 } else if (th->th_ack == tp->snd_una &&
1388 tlen <= sbspace(&so->so_rcv)) {
1389 int newsize = 0; /* automatic sockbuf scaling */
1390
1391 /*
1392 * This is a pure, in-sequence data packet with
1393 * nothing on the reassembly queue and we have enough
1394 * buffer space to take it.
1395 */
1396 if (ti_locked == TI_RLOCKED)
1397 INP_INFO_RUNLOCK(&V_tcbinfo);
1398 else if (ti_locked == TI_WLOCKED)
1399 INP_INFO_WUNLOCK(&V_tcbinfo);
1400 else
1401 panic("%s: ti_locked %d on pure data "
1402 "segment", __func__, ti_locked);
1403 ti_locked = TI_UNLOCKED;
1404
1405 /* Clean receiver SACK report if present */
1406 if ((tp->t_flags & TF_SACK_PERMIT) && tp->rcv_numsacks)
1407 tcp_clean_sackreport(tp);
1408 TCPSTAT_INC(tcps_preddat);
1409 tp->rcv_nxt += tlen;
1410 /*
1411 * Pull snd_wl1 up to prevent seq wrap relative to
1412 * th_seq.
1413 */
1414 tp->snd_wl1 = th->th_seq;
1415 /*
1416 * Pull rcv_up up to prevent seq wrap relative to
1417 * rcv_nxt.
1418 */
1419 tp->rcv_up = tp->rcv_nxt;
1420 TCPSTAT_INC(tcps_rcvpack);
1421 TCPSTAT_ADD(tcps_rcvbyte, tlen);
1422 ND6_HINT(tp); /* Some progress has been made */
1423#ifdef TCPDEBUG
1424 if (so->so_options & SO_DEBUG)
1425 tcp_trace(TA_INPUT, ostate, tp,
1426 (void *)tcp_saveipgen, &tcp_savetcp, 0);
1427#endif
1428 /*
1429 * Automatic sizing of receive socket buffer. Often the send
1430 * buffer size is not optimally adjusted to the actual network
1431 * conditions at hand (delay bandwidth product). Setting the
1432 * buffer size too small limits throughput on links with high
1433 * bandwidth and high delay (eg. trans-continental/oceanic links).
1434 *
1435 * On the receive side the socket buffer memory is only rarely
1436 * used to any significant extent. This allows us to be much
1437 * more aggressive in scaling the receive socket buffer. For
1438 * the case that the buffer space is actually used to a large
1439 * extent and we run out of kernel memory we can simply drop
1440 * the new segments; TCP on the sender will just retransmit it
1441 * later. Setting the buffer size too big may only consume too
1442 * much kernel memory if the application doesn't read() from
1443 * the socket or packet loss or reordering makes use of the
1444 * reassembly queue.
1445 *
1446 * The criteria to step up the receive buffer one notch are:
1447 * 1. the number of bytes received during the time it takes
1448 * one timestamp to be reflected back to us (the RTT);
1449 * 2. received bytes per RTT is within seven eighth of the
1450 * current socket buffer size;
1451 * 3. receive buffer size has not hit maximal automatic size;
1452 *
1453 * This algorithm does one step per RTT at most and only if
1454 * we receive a bulk stream w/o packet losses or reorderings.
1455 * Shrinking the buffer during idle times is not necessary as
1456 * it doesn't consume any memory when idle.
1457 *
1458 * TODO: Only step up if the application is actually serving
1459 * the buffer to better manage the socket buffer resources.
1460 */
1461 if (V_tcp_do_autorcvbuf &&
1462 to.to_tsecr &&
1463 (so->so_rcv.sb_flags & SB_AUTOSIZE)) {
1464 if (to.to_tsecr > tp->rfbuf_ts &&
1465 to.to_tsecr - tp->rfbuf_ts < hz) {
1466 if (tp->rfbuf_cnt >
1467 (so->so_rcv.sb_hiwat / 8 * 7) &&
1468 so->so_rcv.sb_hiwat <
1469 V_tcp_autorcvbuf_max) {
1470 newsize =
1471 min(so->so_rcv.sb_hiwat +
1472 V_tcp_autorcvbuf_inc,
1473 V_tcp_autorcvbuf_max);
1474 }
1475 /* Start over with next RTT. */
1476 tp->rfbuf_ts = 0;
1477 tp->rfbuf_cnt = 0;
1478 } else
1479 tp->rfbuf_cnt += tlen; /* add up */
1480 }
1481
1482 /* Add data to socket buffer. */
1483 SOCKBUF_LOCK(&so->so_rcv);
1484 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
1485 m_freem(m);
1486 } else {
1487 /*
1488 * Set new socket buffer size.
1489 * Give up when limit is reached.
1490 */
1491 if (newsize)
1492 if (!sbreserve_locked(&so->so_rcv,
1493 newsize, so, NULL))
1494 so->so_rcv.sb_flags &= ~SB_AUTOSIZE;
1495 m_adj(m, drop_hdrlen); /* delayed header drop */
1496 sbappendstream_locked(&so->so_rcv, m);
1497 }
1498 /* NB: sorwakeup_locked() does an implicit unlock. */
1499 sorwakeup_locked(so);
1500 if (DELAY_ACK(tp)) {
1501 tp->t_flags |= TF_DELACK;
1502 } else {
1503 tp->t_flags |= TF_ACKNOW;
1504 tcp_output(tp);
1505 }
1506 goto check_delack;
1507 }
1508 }
1509
1510 /*
1511 * Calculate amount of space in receive window,
1512 * and then do TCP input processing.
1513 * Receive window is amount of space in rcv queue,
1514 * but not less than advertised window.
1515 */
1516 win = sbspace(&so->so_rcv);
1517 if (win < 0)
1518 win = 0;
1519 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
1520
1521 /* Reset receive buffer auto scaling when not in bulk receive mode. */
1522 tp->rfbuf_ts = 0;
1523 tp->rfbuf_cnt = 0;
1524
1525 switch (tp->t_state) {
1526
1527 /*
1528 * If the state is SYN_RECEIVED:
1529 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
1530 */
1531 case TCPS_SYN_RECEIVED:
1532 if ((thflags & TH_ACK) &&
1533 (SEQ_LEQ(th->th_ack, tp->snd_una) ||
1534 SEQ_GT(th->th_ack, tp->snd_max))) {
1535 rstreason = BANDLIM_RST_OPENPORT;
1536 goto dropwithreset;
1537 }
1538 break;
1539
1540 /*
1541 * If the state is SYN_SENT:
1542 * if seg contains an ACK, but not for our SYN, drop the input.
1543 * if seg contains a RST, then drop the connection.
1544 * if seg does not contain SYN, then drop it.
1545 * Otherwise this is an acceptable SYN segment
1546 * initialize tp->rcv_nxt and tp->irs
1547 * if seg contains ack then advance tp->snd_una
1548 * if seg contains an ECE and ECN support is enabled, the stream
1549 * is ECN capable.
1550 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
1551 * arrange for segment to be acked (eventually)
1552 * continue processing rest of data/controls, beginning with URG
1553 */
1554 case TCPS_SYN_SENT:
1555 if ((thflags & TH_ACK) &&
1556 (SEQ_LEQ(th->th_ack, tp->iss) ||
1557 SEQ_GT(th->th_ack, tp->snd_max))) {
1558 rstreason = BANDLIM_UNLIMITED;
1559 goto dropwithreset;
1560 }
1561 if ((thflags & (TH_ACK|TH_RST)) == (TH_ACK|TH_RST))
1562 tp = tcp_drop(tp, ECONNREFUSED);
1563 if (thflags & TH_RST)
1564 goto drop;
1565 if (!(thflags & TH_SYN))
1566 goto drop;
1567
1568 tp->irs = th->th_seq;
1569 tcp_rcvseqinit(tp);
1570 if (thflags & TH_ACK) {
1571 TCPSTAT_INC(tcps_connects);
1572 soisconnected(so);
1573#ifdef MAC
1574 mac_socketpeer_set_from_mbuf(m, so);
1575#endif
1576 /* Do window scaling on this connection? */
1577 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1578 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1579 tp->rcv_scale = tp->request_r_scale;
1580 }
1581 tp->rcv_adv += tp->rcv_wnd;
1582 tp->snd_una++; /* SYN is acked */
1583 /*
1584 * If there's data, delay ACK; if there's also a FIN
1585 * ACKNOW will be turned on later.
1586 */
1587 if (DELAY_ACK(tp) && tlen != 0)
1588 tcp_timer_activate(tp, TT_DELACK,
1589 tcp_delacktime);
1590 else
1591 tp->t_flags |= TF_ACKNOW;
1592
1593 if ((thflags & TH_ECE) && V_tcp_do_ecn) {
1594 tp->t_flags |= TF_ECN_PERMIT;
1595 TCPSTAT_INC(tcps_ecn_shs);
1596 }
1597
1598 /*
1599 * Received <SYN,ACK> in SYN_SENT[*] state.
1600 * Transitions:
1601 * SYN_SENT --> ESTABLISHED
1602 * SYN_SENT* --> FIN_WAIT_1
1603 */
1604 tp->t_starttime = ticks;
1605 if (tp->t_flags & TF_NEEDFIN) {
1606 tp->t_state = TCPS_FIN_WAIT_1;
1607 tp->t_flags &= ~TF_NEEDFIN;
1608 thflags &= ~TH_SYN;
1609 } else {
1610 tp->t_state = TCPS_ESTABLISHED;
1611 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
1612 }
1613 } else {
1614 /*
1615 * Received initial SYN in SYN-SENT[*] state =>
1616 * simultaneous open. If segment contains CC option
1617 * and there is a cached CC, apply TAO test.
1618 * If it succeeds, connection is * half-synchronized.
1619 * Otherwise, do 3-way handshake:
1620 * SYN-SENT -> SYN-RECEIVED
1621 * SYN-SENT* -> SYN-RECEIVED*
1622 * If there was no CC option, clear cached CC value.
1623 */
1624 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
1625 tcp_timer_activate(tp, TT_REXMT, 0);
1626 tp->t_state = TCPS_SYN_RECEIVED;
1627 }
1628
1629 KASSERT(ti_locked == TI_WLOCKED, ("%s: trimthenstep6: "
1630 "ti_locked %d", __func__, ti_locked));
1631 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1632 INP_WLOCK_ASSERT(tp->t_inpcb);
1633
1634 /*
1635 * Advance th->th_seq to correspond to first data byte.
1636 * If data, trim to stay within window,
1637 * dropping FIN if necessary.
1638 */
1639 th->th_seq++;
1640 if (tlen > tp->rcv_wnd) {
1641 todrop = tlen - tp->rcv_wnd;
1642 m_adj(m, -todrop);
1643 tlen = tp->rcv_wnd;
1644 thflags &= ~TH_FIN;
1645 TCPSTAT_INC(tcps_rcvpackafterwin);
1646 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1647 }
1648 tp->snd_wl1 = th->th_seq - 1;
1649 tp->rcv_up = th->th_seq;
1650 /*
1651 * Client side of transaction: already sent SYN and data.
1652 * If the remote host used T/TCP to validate the SYN,
1653 * our data will be ACK'd; if so, enter normal data segment
1654 * processing in the middle of step 5, ack processing.
1655 * Otherwise, goto step 6.
1656 */
1657 if (thflags & TH_ACK)
1658 goto process_ACK;
1659
1660 goto step6;
1661
1662 /*
1663 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
1664 * do normal processing.
1665 *
1666 * NB: Leftover from RFC1644 T/TCP. Cases to be reused later.
1667 */
1668 case TCPS_LAST_ACK:
1669 case TCPS_CLOSING:
1670 break; /* continue normal processing */
1671 }
1672
1673 /*
1674 * States other than LISTEN or SYN_SENT.
1675 * First check the RST flag and sequence number since reset segments
1676 * are exempt from the timestamp and connection count tests. This
1677 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
1678 * below which allowed reset segments in half the sequence space
1679 * to fall though and be processed (which gives forged reset
1680 * segments with a random sequence number a 50 percent chance of
1681 * killing a connection).
1682 * Then check timestamp, if present.
1683 * Then check the connection count, if present.
1684 * Then check that at least some bytes of segment are within
1685 * receive window. If segment begins before rcv_nxt,
1686 * drop leading data (and SYN); if nothing left, just ack.
1687 *
1688 *
1689 * If the RST bit is set, check the sequence number to see
1690 * if this is a valid reset segment.
1691 * RFC 793 page 37:
1692 * In all states except SYN-SENT, all reset (RST) segments
1693 * are validated by checking their SEQ-fields. A reset is
1694 * valid if its sequence number is in the window.
1695 * Note: this does not take into account delayed ACKs, so
1696 * we should test against last_ack_sent instead of rcv_nxt.
1697 * The sequence number in the reset segment is normally an
1698 * echo of our outgoing acknowlegement numbers, but some hosts
1699 * send a reset with the sequence number at the rightmost edge
1700 * of our receive window, and we have to handle this case.
1701 * Note 2: Paul Watson's paper "Slipping in the Window" has shown
1702 * that brute force RST attacks are possible. To combat this,
1703 * we use a much stricter check while in the ESTABLISHED state,
1704 * only accepting RSTs where the sequence number is equal to
1705 * last_ack_sent. In all other states (the states in which a
1706 * RST is more likely), the more permissive check is used.
1707 * If we have multiple segments in flight, the initial reset
1708 * segment sequence numbers will be to the left of last_ack_sent,
1709 * but they will eventually catch up.
1710 * In any case, it never made sense to trim reset segments to
1711 * fit the receive window since RFC 1122 says:
1712 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1713 *
1714 * A TCP SHOULD allow a received RST segment to include data.
1715 *
1716 * DISCUSSION
1717 * It has been suggested that a RST segment could contain
1718 * ASCII text that encoded and explained the cause of the
1719 * RST. No standard has yet been established for such
1720 * data.
1721 *
1722 * If the reset segment passes the sequence number test examine
1723 * the state:
1724 * SYN_RECEIVED STATE:
1725 * If passive open, return to LISTEN state.
1726 * If active open, inform user that connection was refused.
1727 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT_2, CLOSE_WAIT STATES:
1728 * Inform user that connection was reset, and close tcb.
1729 * CLOSING, LAST_ACK STATES:
1730 * Close the tcb.
1731 * TIME_WAIT STATE:
1732 * Drop the segment - see Stevens, vol. 2, p. 964 and
1733 * RFC 1337.
1734 */
1735 if (thflags & TH_RST) {
1736 if (SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1737 SEQ_LEQ(th->th_seq, tp->last_ack_sent + tp->rcv_wnd)) {
1738 switch (tp->t_state) {
1739
1740 case TCPS_SYN_RECEIVED:
1741 so->so_error = ECONNREFUSED;
1742 goto close;
1743
1744 case TCPS_ESTABLISHED:
1745 if (V_tcp_insecure_rst == 0 &&
1746 !(SEQ_GEQ(th->th_seq, tp->rcv_nxt - 1) &&
1747 SEQ_LEQ(th->th_seq, tp->rcv_nxt + 1)) &&
1748 !(SEQ_GEQ(th->th_seq, tp->last_ack_sent - 1) &&
1749 SEQ_LEQ(th->th_seq, tp->last_ack_sent + 1))) {
1750 TCPSTAT_INC(tcps_badrst);
1751 goto drop;
1752 }
1753 /* FALLTHROUGH */
1754 case TCPS_FIN_WAIT_1:
1755 case TCPS_FIN_WAIT_2:
1756 case TCPS_CLOSE_WAIT:
1757 so->so_error = ECONNRESET;
1758 close:
1759 KASSERT(ti_locked == TI_WLOCKED,
1760 ("tcp_do_segment: TH_RST 1 ti_locked %d",
1761 ti_locked));
1762 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1763
1764 tp->t_state = TCPS_CLOSED;
1765 TCPSTAT_INC(tcps_drops);
1766 tp = tcp_close(tp);
1767 break;
1768
1769 case TCPS_CLOSING:
1770 case TCPS_LAST_ACK:
1771 KASSERT(ti_locked == TI_WLOCKED,
1772 ("tcp_do_segment: TH_RST 2 ti_locked %d",
1773 ti_locked));
1774 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1775
1776 tp = tcp_close(tp);
1777 break;
1778 }
1779 }
1780 goto drop;
1781 }
1782
1783 /*
1784 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1785 * and it's less than ts_recent, drop it.
1786 */
1787 if ((to.to_flags & TOF_TS) != 0 && tp->ts_recent &&
1788 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1789
1790 /* Check to see if ts_recent is over 24 days old. */
1791 if (ticks - tp->ts_recent_age > TCP_PAWS_IDLE) {
1792 /*
1793 * Invalidate ts_recent. If this segment updates
1794 * ts_recent, the age will be reset later and ts_recent
1795 * will get a valid value. If it does not, setting
1796 * ts_recent to zero will at least satisfy the
1797 * requirement that zero be placed in the timestamp
1798 * echo reply when ts_recent isn't valid. The
1799 * age isn't reset until we get a valid ts_recent
1800 * because we don't want out-of-order segments to be
1801 * dropped when ts_recent is old.
1802 */
1803 tp->ts_recent = 0;
1804 } else {
1805 TCPSTAT_INC(tcps_rcvduppack);
1806 TCPSTAT_ADD(tcps_rcvdupbyte, tlen);
1807 TCPSTAT_INC(tcps_pawsdrop);
1808 if (tlen)
1809 goto dropafterack;
1810 goto drop;
1811 }
1812 }
1813
1814 /*
1815 * In the SYN-RECEIVED state, validate that the packet belongs to
1816 * this connection before trimming the data to fit the receive
1817 * window. Check the sequence number versus IRS since we know
1818 * the sequence numbers haven't wrapped. This is a partial fix
1819 * for the "LAND" DoS attack.
1820 */
1821 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(th->th_seq, tp->irs)) {
1822 rstreason = BANDLIM_RST_OPENPORT;
1823 goto dropwithreset;
1824 }
1825
1826 todrop = tp->rcv_nxt - th->th_seq;
1827 if (todrop > 0) {
1828 /*
1829 * If this is a duplicate SYN for our current connection,
1830 * advance over it and pretend and it's not a SYN.
1831 */
1832 if (thflags & TH_SYN && th->th_seq == tp->irs) {
1833 thflags &= ~TH_SYN;
1834 th->th_seq++;
1835 if (th->th_urp > 1)
1836 th->th_urp--;
1837 else
1838 thflags &= ~TH_URG;
1839 todrop--;
1840 }
1841 /*
1842 * Following if statement from Stevens, vol. 2, p. 960.
1843 */
1844 if (todrop > tlen
1845 || (todrop == tlen && (thflags & TH_FIN) == 0)) {
1846 /*
1847 * Any valid FIN must be to the left of the window.
1848 * At this point the FIN must be a duplicate or out
1849 * of sequence; drop it.
1850 */
1851 thflags &= ~TH_FIN;
1852
1853 /*
1854 * Send an ACK to resynchronize and drop any data.
1855 * But keep on processing for RST or ACK.
1856 */
1857 tp->t_flags |= TF_ACKNOW;
1858 todrop = tlen;
1859 TCPSTAT_INC(tcps_rcvduppack);
1860 TCPSTAT_ADD(tcps_rcvdupbyte, todrop);
1861 } else {
1862 TCPSTAT_INC(tcps_rcvpartduppack);
1863 TCPSTAT_ADD(tcps_rcvpartdupbyte, todrop);
1864 }
1865 drop_hdrlen += todrop; /* drop from the top afterwards */
1866 th->th_seq += todrop;
1867 tlen -= todrop;
1868 if (th->th_urp > todrop)
1869 th->th_urp -= todrop;
1870 else {
1871 thflags &= ~TH_URG;
1872 th->th_urp = 0;
1873 }
1874 }
1875
1876 /*
1877 * If new data are received on a connection after the
1878 * user processes are gone, then RST the other end.
1879 */
1880 if ((so->so_state & SS_NOFDREF) &&
1881 tp->t_state > TCPS_CLOSE_WAIT && tlen) {
1882 char *s;
1883
1884 KASSERT(ti_locked == TI_WLOCKED, ("%s: SS_NOFDEREF && "
1885 "CLOSE_WAIT && tlen ti_locked %d", __func__, ti_locked));
1886 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1887
1888 if ((s = tcp_log_addrs(&tp->t_inpcb->inp_inc, th, NULL, NULL))) {
1889 log(LOG_DEBUG, "%s; %s: %s: Received %d bytes of data after socket "
1890 "was closed, sending RST and removing tcpcb\n",
1891 s, __func__, tcpstates[tp->t_state], tlen);
1892 free(s, M_TCPLOG);
1893 }
1894 tp = tcp_close(tp);
1895 TCPSTAT_INC(tcps_rcvafterclose);
1896 rstreason = BANDLIM_UNLIMITED;
1897 goto dropwithreset;
1898 }
1899
1900 /*
1901 * If segment ends after window, drop trailing data
1902 * (and PUSH and FIN); if nothing left, just ACK.
1903 */
1904 todrop = (th->th_seq + tlen) - (tp->rcv_nxt + tp->rcv_wnd);
1905 if (todrop > 0) {
1906 TCPSTAT_INC(tcps_rcvpackafterwin);
1907 if (todrop >= tlen) {
1908 TCPSTAT_ADD(tcps_rcvbyteafterwin, tlen);
1909 /*
1910 * If window is closed can only take segments at
1911 * window edge, and have to drop data and PUSH from
1912 * incoming segments. Continue processing, but
1913 * remember to ack. Otherwise, drop segment
1914 * and ack.
1915 */
1916 if (tp->rcv_wnd == 0 && th->th_seq == tp->rcv_nxt) {
1917 tp->t_flags |= TF_ACKNOW;
1918 TCPSTAT_INC(tcps_rcvwinprobe);
1919 } else
1920 goto dropafterack;
1921 } else
1922 TCPSTAT_ADD(tcps_rcvbyteafterwin, todrop);
1923 m_adj(m, -todrop);
1924 tlen -= todrop;
1925 thflags &= ~(TH_PUSH|TH_FIN);
1926 }
1927
1928 /*
1929 * If last ACK falls within this segment's sequence numbers,
1930 * record its timestamp.
1931 * NOTE:
1932 * 1) That the test incorporates suggestions from the latest
1933 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1934 * 2) That updating only on newer timestamps interferes with
1935 * our earlier PAWS tests, so this check should be solely
1936 * predicated on the sequence space of this segment.
1937 * 3) That we modify the segment boundary check to be
1938 * Last.ACK.Sent <= SEG.SEQ + SEG.Len
1939 * instead of RFC1323's
1940 * Last.ACK.Sent < SEG.SEQ + SEG.Len,
1941 * This modified check allows us to overcome RFC1323's
1942 * limitations as described in Stevens TCP/IP Illustrated
1943 * Vol. 2 p.869. In such cases, we can still calculate the
1944 * RTT correctly when RCV.NXT == Last.ACK.Sent.
1945 */
1946 if ((to.to_flags & TOF_TS) != 0 &&
1947 SEQ_LEQ(th->th_seq, tp->last_ack_sent) &&
1948 SEQ_LEQ(tp->last_ack_sent, th->th_seq + tlen +
1949 ((thflags & (TH_SYN|TH_FIN)) != 0))) {
1950 tp->ts_recent_age = ticks;
1951 tp->ts_recent = to.to_tsval;
1952 }
1953
1954 /*
1955 * If a SYN is in the window, then this is an
1956 * error and we send an RST and drop the connection.
1957 */
1958 if (thflags & TH_SYN) {
1959 KASSERT(ti_locked == TI_WLOCKED,
1960 ("tcp_do_segment: TH_SYN ti_locked %d", ti_locked));
1961 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
1962
1963 tp = tcp_drop(tp, ECONNRESET);
1964 rstreason = BANDLIM_UNLIMITED;
1965 goto drop;
1966 }
1967
1968 /*
1969 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1970 * flag is on (half-synchronized state), then queue data for
1971 * later processing; else drop segment and return.
1972 */
1973 if ((thflags & TH_ACK) == 0) {
1974 if (tp->t_state == TCPS_SYN_RECEIVED ||
1975 (tp->t_flags & TF_NEEDSYN))
1976 goto step6;
1977 else if (tp->t_flags & TF_ACKNOW)
1978 goto dropafterack;
1979 else
1980 goto drop;
1981 }
1982
1983 /*
1984 * Ack processing.
1985 */
1986 switch (tp->t_state) {
1987
1988 /*
1989 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1990 * ESTABLISHED state and continue processing.
1991 * The ACK was checked above.
1992 */
1993 case TCPS_SYN_RECEIVED:
1994
1995 TCPSTAT_INC(tcps_connects);
1996 soisconnected(so);
1997 /* Do window scaling? */
1998 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1999 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2000 tp->rcv_scale = tp->request_r_scale;
2001 tp->snd_wnd = tiwin;
2002 }
2003 /*
2004 * Make transitions:
2005 * SYN-RECEIVED -> ESTABLISHED
2006 * SYN-RECEIVED* -> FIN-WAIT-1
2007 */
2008 tp->t_starttime = ticks;
2009 if (tp->t_flags & TF_NEEDFIN) {
2010 tp->t_state = TCPS_FIN_WAIT_1;
2011 tp->t_flags &= ~TF_NEEDFIN;
2012 } else {
2013 tp->t_state = TCPS_ESTABLISHED;
2014 tcp_timer_activate(tp, TT_KEEP, tcp_keepidle);
2015 }
2016 /*
2017 * If segment contains data or ACK, will call tcp_reass()
2018 * later; if not, do so now to pass queued data to user.
2019 */
2020 if (tlen == 0 && (thflags & TH_FIN) == 0)
2021 (void) tcp_reass(tp, (struct tcphdr *)0, 0,
2022 (struct mbuf *)0);
2023 tp->snd_wl1 = th->th_seq - 1;
2024 /* FALLTHROUGH */
2025
2026 /*
2027 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
2028 * ACKs. If the ack is in the range
2029 * tp->snd_una < th->th_ack <= tp->snd_max
2030 * then advance tp->snd_una to th->th_ack and drop
2031 * data from the retransmission queue. If this ACK reflects
2032 * more up to date window information we update our window information.
2033 */
2034 case TCPS_ESTABLISHED:
2035 case TCPS_FIN_WAIT_1:
2036 case TCPS_FIN_WAIT_2:
2037 case TCPS_CLOSE_WAIT:
2038 case TCPS_CLOSING:
2039 case TCPS_LAST_ACK:
2040 if (SEQ_GT(th->th_ack, tp->snd_max)) {
2041 TCPSTAT_INC(tcps_rcvacktoomuch);
2042 goto dropafterack;
2043 }
2044 if ((tp->t_flags & TF_SACK_PERMIT) &&
2045 ((to.to_flags & TOF_SACK) ||
2046 !TAILQ_EMPTY(&tp->snd_holes)))
2047 tcp_sack_doack(tp, &to, th->th_ack);
2048 if (SEQ_LEQ(th->th_ack, tp->snd_una)) {
2049 if (tlen == 0 && tiwin == tp->snd_wnd) {
2050 TCPSTAT_INC(tcps_rcvdupack);
2051 /*
2052 * If we have outstanding data (other than
2053 * a window probe), this is a completely
2054 * duplicate ack (ie, window info didn't
2055 * change), the ack is the biggest we've
2056 * seen and we've seen exactly our rexmt
2057 * threshhold of them, assume a packet
2058 * has been dropped and retransmit it.
2059 * Kludge snd_nxt & the congestion
2060 * window so we send only this one
2061 * packet.
2062 *
2063 * We know we're losing at the current
2064 * window size so do congestion avoidance
2065 * (set ssthresh to half the current window
2066 * and pull our congestion window back to
2067 * the new ssthresh).
2068 *
2069 * Dup acks mean that packets have left the
2070 * network (they're now cached at the receiver)
2071 * so bump cwnd by the amount in the receiver
2072 * to keep a constant cwnd packets in the
2073 * network.
2074 *
2075 * When using TCP ECN, notify the peer that
2076 * we reduced the cwnd.
2077 */
2078 if (!tcp_timer_active(tp, TT_REXMT) ||
2079 th->th_ack != tp->snd_una)
2080 tp->t_dupacks = 0;
2081 else if (++tp->t_dupacks > tcprexmtthresh ||
2082 ((V_tcp_do_newreno ||
2083 (tp->t_flags & TF_SACK_PERMIT)) &&
2084 IN_FASTRECOVERY(tp))) {
2085 if ((tp->t_flags & TF_SACK_PERMIT) &&
2086 IN_FASTRECOVERY(tp)) {
2087 int awnd;
2088
2089 /*
2090 * Compute the amount of data in flight first.
2091 * We can inject new data into the pipe iff
2092 * we have less than 1/2 the original window's
2093 * worth of data in flight.
2094 */
2095 awnd = (tp->snd_nxt - tp->snd_fack) +
2096 tp->sackhint.sack_bytes_rexmit;
2097 if (awnd < tp->snd_ssthresh) {
2098 tp->snd_cwnd += tp->t_maxseg;
2099 if (tp->snd_cwnd > tp->snd_ssthresh)
2100 tp->snd_cwnd = tp->snd_ssthresh;
2101 }
2102 } else
2103 tp->snd_cwnd += tp->t_maxseg;
2104 (void) tcp_output(tp);
2105 goto drop;
2106 } else if (tp->t_dupacks == tcprexmtthresh) {
2107 tcp_seq onxt = tp->snd_nxt;
2108
2109 /*
2110 * If we're doing sack, check to
2111 * see if we're already in sack
2112 * recovery. If we're not doing sack,
2113 * check to see if we're in newreno
2114 * recovery.
2115 */
2116 if (tp->t_flags & TF_SACK_PERMIT) {
2117 if (IN_FASTRECOVERY(tp)) {
2118 tp->t_dupacks = 0;
2119 break;
2120 }
2121 } else if (V_tcp_do_newreno ||
2122 V_tcp_do_ecn) {
2123 if (SEQ_LEQ(th->th_ack,
2124 tp->snd_recover)) {
2125 tp->t_dupacks = 0;
2126 break;
2127 }
2128 }
2129 tcp_congestion_exp(tp);
2130 tcp_timer_activate(tp, TT_REXMT, 0);
2131 tp->t_rtttime = 0;
2132 if (tp->t_flags & TF_SACK_PERMIT) {
2133 TCPSTAT_INC(
2134 tcps_sack_recovery_episode);
2135 tp->sack_newdata = tp->snd_nxt;
2136 tp->snd_cwnd = tp->t_maxseg;
2137 (void) tcp_output(tp);
2138 goto drop;
2139 }
2140 tp->snd_nxt = th->th_ack;
2141 tp->snd_cwnd = tp->t_maxseg;
2142 (void) tcp_output(tp);
2143 KASSERT(tp->snd_limited <= 2,
2144 ("%s: tp->snd_limited too big",
2145 __func__));
2146 tp->snd_cwnd = tp->snd_ssthresh +
2147 tp->t_maxseg *
2148 (tp->t_dupacks - tp->snd_limited);
2149 if (SEQ_GT(onxt, tp->snd_nxt))
2150 tp->snd_nxt = onxt;
2151 goto drop;
2152 } else if (V_tcp_do_rfc3042) {
2153 u_long oldcwnd = tp->snd_cwnd;
2154 tcp_seq oldsndmax = tp->snd_max;
2155 u_int sent;
2156
2157 KASSERT(tp->t_dupacks == 1 ||
2158 tp->t_dupacks == 2,
2159 ("%s: dupacks not 1 or 2",
2160 __func__));
2161 if (tp->t_dupacks == 1)
2162 tp->snd_limited = 0;
2163 tp->snd_cwnd =
2164 (tp->snd_nxt - tp->snd_una) +
2165 (tp->t_dupacks - tp->snd_limited) *
2166 tp->t_maxseg;
2167 (void) tcp_output(tp);
2168 sent = tp->snd_max - oldsndmax;
2169 if (sent > tp->t_maxseg) {
2170 KASSERT((tp->t_dupacks == 2 &&
2171 tp->snd_limited == 0) ||
2172 (sent == tp->t_maxseg + 1 &&
2173 tp->t_flags & TF_SENTFIN),
2174 ("%s: sent too much",
2175 __func__));
2176 tp->snd_limited = 2;
2177 } else if (sent > 0)
2178 ++tp->snd_limited;
2179 tp->snd_cwnd = oldcwnd;
2180 goto drop;
2181 }
2182 } else
2183 tp->t_dupacks = 0;
2184 break;
2185 }
2186
2187 KASSERT(SEQ_GT(th->th_ack, tp->snd_una),
2188 ("%s: th_ack <= snd_una", __func__));
2189
2190 /*
2191 * If the congestion window was inflated to account
2192 * for the other side's cached packets, retract it.
2193 */
2194 if (V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) {
2195 if (IN_FASTRECOVERY(tp)) {
2196 if (SEQ_LT(th->th_ack, tp->snd_recover)) {
2197 if (tp->t_flags & TF_SACK_PERMIT)
2198 tcp_sack_partialack(tp, th);
2199 else
2200 tcp_newreno_partial_ack(tp, th);
2201 } else {
2202 /*
2203 * Out of fast recovery.
2204 * Window inflation should have left us
2205 * with approximately snd_ssthresh
2206 * outstanding data.
2207 * But in case we would be inclined to
2208 * send a burst, better to do it via
2209 * the slow start mechanism.
2210 */
2211 if (SEQ_GT(th->th_ack +
2212 tp->snd_ssthresh,
2213 tp->snd_max))
2214 tp->snd_cwnd = tp->snd_max -
2215 th->th_ack +
2216 tp->t_maxseg;
2217 else
2218 tp->snd_cwnd = tp->snd_ssthresh;
2219 }
2220 }
2221 } else {
2222 if (tp->t_dupacks >= tcprexmtthresh &&
2223 tp->snd_cwnd > tp->snd_ssthresh)
2224 tp->snd_cwnd = tp->snd_ssthresh;
2225 }
2226 tp->t_dupacks = 0;
2227 /*
2228 * If we reach this point, ACK is not a duplicate,
2229 * i.e., it ACKs something we sent.
2230 */
2231 if (tp->t_flags & TF_NEEDSYN) {
2232 /*
2233 * T/TCP: Connection was half-synchronized, and our
2234 * SYN has been ACK'd (so connection is now fully
2235 * synchronized). Go to non-starred state,
2236 * increment snd_una for ACK of SYN, and check if
2237 * we can do window scaling.
2238 */
2239 tp->t_flags &= ~TF_NEEDSYN;
2240 tp->snd_una++;
2241 /* Do window scaling? */
2242 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
2243 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
2244 tp->rcv_scale = tp->request_r_scale;
2245 /* Send window already scaled. */
2246 }
2247 }
2248
2249process_ACK:
2250 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2251 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2252 ("tcp_input: process_ACK ti_locked %d", ti_locked));
2253 INP_WLOCK_ASSERT(tp->t_inpcb);
2254
2255 acked = th->th_ack - tp->snd_una;
2256 TCPSTAT_INC(tcps_rcvackpack);
2257 TCPSTAT_ADD(tcps_rcvackbyte, acked);
2258
2259 /*
2260 * If we just performed our first retransmit, and the ACK
2261 * arrives within our recovery window, then it was a mistake
2262 * to do the retransmit in the first place. Recover our
2263 * original cwnd and ssthresh, and proceed to transmit where
2264 * we left off.
2265 */
2266 if (tp->t_rxtshift == 1 && (int)(ticks - tp->t_badrxtwin) < 0) {
2267 TCPSTAT_INC(tcps_sndrexmitbad);
2268 tp->snd_cwnd = tp->snd_cwnd_prev;
2269 tp->snd_ssthresh = tp->snd_ssthresh_prev;
2270 tp->snd_recover = tp->snd_recover_prev;
2271 if (tp->t_flags & TF_WASFRECOVERY)
2272 ENTER_FASTRECOVERY(tp);
2273 tp->snd_nxt = tp->snd_max;
2274 tp->t_badrxtwin = 0; /* XXX probably not required */
2275 }
2276
2277 /*
2278 * If we have a timestamp reply, update smoothed
2279 * round trip time. If no timestamp is present but
2280 * transmit timer is running and timed sequence
2281 * number was acked, update smoothed round trip time.
2282 * Since we now have an rtt measurement, cancel the
2283 * timer backoff (cf., Phil Karn's retransmit alg.).
2284 * Recompute the initial retransmit timer.
2285 *
2286 * Some boxes send broken timestamp replies
2287 * during the SYN+ACK phase, ignore
2288 * timestamps of 0 or we could calculate a
2289 * huge RTT and blow up the retransmit timer.
2290 */
2291 if ((to.to_flags & TOF_TS) != 0 &&
2292 to.to_tsecr) {
2293 if (!tp->t_rttlow || tp->t_rttlow > ticks - to.to_tsecr)
2294 tp->t_rttlow = ticks - to.to_tsecr;
2295 tcp_xmit_timer(tp, ticks - to.to_tsecr + 1);
2296 } else if (tp->t_rtttime && SEQ_GT(th->th_ack, tp->t_rtseq)) {
2297 if (!tp->t_rttlow || tp->t_rttlow > ticks - tp->t_rtttime)
2298 tp->t_rttlow = ticks - tp->t_rtttime;
2299 tcp_xmit_timer(tp, ticks - tp->t_rtttime);
2300 }
2301 tcp_xmit_bandwidth_limit(tp, th->th_ack);
2302
2303 /*
2304 * If all outstanding data is acked, stop retransmit
2305 * timer and remember to restart (more output or persist).
2306 * If there is more data to be acked, restart retransmit
2307 * timer, using current (possibly backed-off) value.
2308 */
2309 if (th->th_ack == tp->snd_max) {
2310 tcp_timer_activate(tp, TT_REXMT, 0);
2311 needoutput = 1;
2312 } else if (!tcp_timer_active(tp, TT_PERSIST))
2313 tcp_timer_activate(tp, TT_REXMT, tp->t_rxtcur);
2314
2315 /*
2316 * If no data (only SYN) was ACK'd,
2317 * skip rest of ACK processing.
2318 */
2319 if (acked == 0)
2320 goto step6;
2321
2322 /*
2323 * When new data is acked, open the congestion window.
2324 * Method depends on which congestion control state we're
2325 * in (slow start or cong avoid) and if ABC (RFC 3465) is
2326 * enabled.
2327 *
2328 * slow start: cwnd <= ssthresh
2329 * cong avoid: cwnd > ssthresh
2330 *
2331 * slow start and ABC (RFC 3465):
2332 * Grow cwnd exponentially by the amount of data
2333 * ACKed capping the max increment per ACK to
2334 * (abc_l_var * maxseg) bytes.
2335 *
2336 * slow start without ABC (RFC 2581):
2337 * Grow cwnd exponentially by maxseg per ACK.
2338 *
2339 * cong avoid and ABC (RFC 3465):
2340 * Grow cwnd linearly by maxseg per RTT for each
2341 * cwnd worth of ACKed data.
2342 *
2343 * cong avoid without ABC (RFC 2581):
2344 * Grow cwnd linearly by approximately maxseg per RTT using
2345 * maxseg^2 / cwnd per ACK as the increment.
2346 * If cwnd > maxseg^2, fix the cwnd increment at 1 byte to
2347 * avoid capping cwnd.
2348 */
2349 if ((!V_tcp_do_newreno && !(tp->t_flags & TF_SACK_PERMIT)) ||
2350 !IN_FASTRECOVERY(tp)) {
2351 u_int cw = tp->snd_cwnd;
2352 u_int incr = tp->t_maxseg;
2353 /* In congestion avoidance? */
2354 if (cw > tp->snd_ssthresh) {
2355 if (V_tcp_do_rfc3465) {
2356 tp->t_bytes_acked += acked;
2357 if (tp->t_bytes_acked >= tp->snd_cwnd)
2358 tp->t_bytes_acked -= cw;
2359 else
2360 incr = 0;
2361 }
2362 else
2363 incr = max((incr * incr / cw), 1);
2364 /*
2365 * In slow-start with ABC enabled and no RTO in sight?
2366 * (Must not use abc_l_var > 1 if slow starting after an
2367 * RTO. On RTO, snd_nxt = snd_una, so the snd_nxt ==
2368 * snd_max check is sufficient to handle this).
2369 */
2370 } else if (V_tcp_do_rfc3465 &&
2371 tp->snd_nxt == tp->snd_max)
2372 incr = min(acked,
2373 V_tcp_abc_l_var * tp->t_maxseg);
2374 /* ABC is on by default, so (incr == 0) frequently. */
2375 if (incr > 0)
2376 tp->snd_cwnd = min(cw+incr, TCP_MAXWIN<<tp->snd_scale);
2377 }
2378 SOCKBUF_LOCK(&so->so_snd);
2379 if (acked > so->so_snd.sb_cc) {
2380 tp->snd_wnd -= so->so_snd.sb_cc;
2381 sbdrop_locked(&so->so_snd, (int)so->so_snd.sb_cc);
2382 ourfinisacked = 1;
2383 } else {
2384 sbdrop_locked(&so->so_snd, acked);
2385 tp->snd_wnd -= acked;
2386 ourfinisacked = 0;
2387 }
2388 /* NB: sowwakeup_locked() does an implicit unlock. */
2389 sowwakeup_locked(so);
2390 /* Detect una wraparound. */
2391 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2392 !IN_FASTRECOVERY(tp) &&
2393 SEQ_GT(tp->snd_una, tp->snd_recover) &&
2394 SEQ_LEQ(th->th_ack, tp->snd_recover))
2395 tp->snd_recover = th->th_ack - 1;
2396 if ((V_tcp_do_newreno || (tp->t_flags & TF_SACK_PERMIT)) &&
2397 IN_FASTRECOVERY(tp) &&
2398 SEQ_GEQ(th->th_ack, tp->snd_recover)) {
2399 EXIT_FASTRECOVERY(tp);
2400 tp->t_bytes_acked = 0;
2401 }
2402 tp->snd_una = th->th_ack;
2403 if (tp->t_flags & TF_SACK_PERMIT) {
2404 if (SEQ_GT(tp->snd_una, tp->snd_recover))
2405 tp->snd_recover = tp->snd_una;
2406 }
2407 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
2408 tp->snd_nxt = tp->snd_una;
2409
2410 switch (tp->t_state) {
2411
2412 /*
2413 * In FIN_WAIT_1 STATE in addition to the processing
2414 * for the ESTABLISHED state if our FIN is now acknowledged
2415 * then enter FIN_WAIT_2.
2416 */
2417 case TCPS_FIN_WAIT_1:
2418 if (ourfinisacked) {
2419 /*
2420 * If we can't receive any more
2421 * data, then closing user can proceed.
2422 * Starting the timer is contrary to the
2423 * specification, but if we don't get a FIN
2424 * we'll hang forever.
2425 *
2426 * XXXjl:
2427 * we should release the tp also, and use a
2428 * compressed state.
2429 */
2430 if (so->so_rcv.sb_state & SBS_CANTRCVMORE) {
2431 int timeout;
2432
2433 soisdisconnected(so);
2434 timeout = (tcp_fast_finwait2_recycle) ?
2435 tcp_finwait2_timeout : tcp_maxidle;
2436 tcp_timer_activate(tp, TT_2MSL, timeout);
2437 }
2438 tp->t_state = TCPS_FIN_WAIT_2;
2439 }
2440 break;
2441
2442 /*
2443 * In CLOSING STATE in addition to the processing for
2444 * the ESTABLISHED state if the ACK acknowledges our FIN
2445 * then enter the TIME-WAIT state, otherwise ignore
2446 * the segment.
2447 */
2448 case TCPS_CLOSING:
2449 if (ourfinisacked) {
2450 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2451 tcp_twstart(tp);
2452 INP_INFO_WUNLOCK(&V_tcbinfo);
2453 m_freem(m);
2454 return;
2455 }
2456 break;
2457
2458 /*
2459 * In LAST_ACK, we may still be waiting for data to drain
2460 * and/or to be acked, as well as for the ack of our FIN.
2461 * If our FIN is now acknowledged, delete the TCB,
2462 * enter the closed state and return.
2463 */
2464 case TCPS_LAST_ACK:
2465 if (ourfinisacked) {
2466 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2467 tp = tcp_close(tp);
2468 goto drop;
2469 }
2470 break;
2471 }
2472 }
2473
2474step6:
2475 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2476 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2477 ("tcp_do_segment: step6 ti_locked %d", ti_locked));
2478 INP_WLOCK_ASSERT(tp->t_inpcb);
2479
2480 /*
2481 * Update window information.
2482 * Don't look at window if no ACK: TAC's send garbage on first SYN.
2483 */
2484 if ((thflags & TH_ACK) &&
2485 (SEQ_LT(tp->snd_wl1, th->th_seq) ||
2486 (tp->snd_wl1 == th->th_seq && (SEQ_LT(tp->snd_wl2, th->th_ack) ||
2487 (tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd))))) {
2488 /* keep track of pure window updates */
2489 if (tlen == 0 &&
2490 tp->snd_wl2 == th->th_ack && tiwin > tp->snd_wnd)
2491 TCPSTAT_INC(tcps_rcvwinupd);
2492 tp->snd_wnd = tiwin;
2493 tp->snd_wl1 = th->th_seq;
2494 tp->snd_wl2 = th->th_ack;
2495 if (tp->snd_wnd > tp->max_sndwnd)
2496 tp->max_sndwnd = tp->snd_wnd;
2497 needoutput = 1;
2498 }
2499
2500 /*
2501 * Process segments with URG.
2502 */
2503 if ((thflags & TH_URG) && th->th_urp &&
2504 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2505 /*
2506 * This is a kludge, but if we receive and accept
2507 * random urgent pointers, we'll crash in
2508 * soreceive. It's hard to imagine someone
2509 * actually wanting to send this much urgent data.
2510 */
2511 SOCKBUF_LOCK(&so->so_rcv);
2512 if (th->th_urp + so->so_rcv.sb_cc > sb_max) {
2513 th->th_urp = 0; /* XXX */
2514 thflags &= ~TH_URG; /* XXX */
2515 SOCKBUF_UNLOCK(&so->so_rcv); /* XXX */
2516 goto dodata; /* XXX */
2517 }
2518 /*
2519 * If this segment advances the known urgent pointer,
2520 * then mark the data stream. This should not happen
2521 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
2522 * a FIN has been received from the remote side.
2523 * In these states we ignore the URG.
2524 *
2525 * According to RFC961 (Assigned Protocols),
2526 * the urgent pointer points to the last octet
2527 * of urgent data. We continue, however,
2528 * to consider it to indicate the first octet
2529 * of data past the urgent section as the original
2530 * spec states (in one of two places).
2531 */
2532 if (SEQ_GT(th->th_seq+th->th_urp, tp->rcv_up)) {
2533 tp->rcv_up = th->th_seq + th->th_urp;
2534 so->so_oobmark = so->so_rcv.sb_cc +
2535 (tp->rcv_up - tp->rcv_nxt) - 1;
2536 if (so->so_oobmark == 0)
2537 so->so_rcv.sb_state |= SBS_RCVATMARK;
2538 sohasoutofband(so);
2539 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
2540 }
2541 SOCKBUF_UNLOCK(&so->so_rcv);
2542 /*
2543 * Remove out of band data so doesn't get presented to user.
2544 * This can happen independent of advancing the URG pointer,
2545 * but if two URG's are pending at once, some out-of-band
2546 * data may creep in... ick.
2547 */
2548 if (th->th_urp <= (u_long)tlen &&
2549 !(so->so_options & SO_OOBINLINE)) {
2550 /* hdr drop is delayed */
2551 tcp_pulloutofband(so, th, m, drop_hdrlen);
2552 }
2553 } else {
2554 /*
2555 * If no out of band data is expected,
2556 * pull receive urgent pointer along
2557 * with the receive window.
2558 */
2559 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
2560 tp->rcv_up = tp->rcv_nxt;
2561 }
2562dodata: /* XXX */
2563 INP_INFO_LOCK_ASSERT(&V_tcbinfo);
2564 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2565 ("tcp_do_segment: dodata ti_locked %d", ti_locked));
2566 INP_WLOCK_ASSERT(tp->t_inpcb);
2567
2568 /*
2569 * Process the segment text, merging it into the TCP sequencing queue,
2570 * and arranging for acknowledgment of receipt if necessary.
2571 * This process logically involves adjusting tp->rcv_wnd as data
2572 * is presented to the user (this happens in tcp_usrreq.c,
2573 * case PRU_RCVD). If a FIN has already been received on this
2574 * connection then we just ignore the text.
2575 */
2576 if ((tlen || (thflags & TH_FIN)) &&
2577 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2578 tcp_seq save_start = th->th_seq;
2579 m_adj(m, drop_hdrlen); /* delayed header drop */
2580 /*
2581 * Insert segment which includes th into TCP reassembly queue
2582 * with control block tp. Set thflags to whether reassembly now
2583 * includes a segment with FIN. This handles the common case
2584 * inline (segment is the next to be received on an established
2585 * connection, and the queue is empty), avoiding linkage into
2586 * and removal from the queue and repetition of various
2587 * conversions.
2588 * Set DELACK for segments received in order, but ack
2589 * immediately when segments are out of order (so
2590 * fast retransmit can work).
2591 */
2592 if (th->th_seq == tp->rcv_nxt &&
2593 LIST_EMPTY(&tp->t_segq) &&
2594 TCPS_HAVEESTABLISHED(tp->t_state)) {
2595 if (DELAY_ACK(tp))
2596 tp->t_flags |= TF_DELACK;
2597 else
2598 tp->t_flags |= TF_ACKNOW;
2599 tp->rcv_nxt += tlen;
2600 thflags = th->th_flags & TH_FIN;
2601 TCPSTAT_INC(tcps_rcvpack);
2602 TCPSTAT_ADD(tcps_rcvbyte, tlen);
2603 ND6_HINT(tp);
2604 SOCKBUF_LOCK(&so->so_rcv);
2605 if (so->so_rcv.sb_state & SBS_CANTRCVMORE)
2606 m_freem(m);
2607 else
2608 sbappendstream_locked(&so->so_rcv, m);
2609 /* NB: sorwakeup_locked() does an implicit unlock. */
2610 sorwakeup_locked(so);
2611 } else {
2612 /*
2613 * XXX: Due to the header drop above "th" is
2614 * theoretically invalid by now. Fortunately
2615 * m_adj() doesn't actually frees any mbufs
2616 * when trimming from the head.
2617 */
2618 thflags = tcp_reass(tp, th, &tlen, m);
2619 tp->t_flags |= TF_ACKNOW;
2620 }
2621 if (tlen > 0 && (tp->t_flags & TF_SACK_PERMIT))
2622 tcp_update_sack_list(tp, save_start, save_start + tlen);
2623#if 0
2624 /*
2625 * Note the amount of data that peer has sent into
2626 * our window, in order to estimate the sender's
2627 * buffer size.
2628 * XXX: Unused.
2629 */
2630 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
2631#endif
2632 } else {
2633 m_freem(m);
2634 thflags &= ~TH_FIN;
2635 }
2636
2637 /*
2638 * If FIN is received ACK the FIN and let the user know
2639 * that the connection is closing.
2640 */
2641 if (thflags & TH_FIN) {
2642 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
2643 socantrcvmore(so);
2644 /*
2645 * If connection is half-synchronized
2646 * (ie NEEDSYN flag on) then delay ACK,
2647 * so it may be piggybacked when SYN is sent.
2648 * Otherwise, since we received a FIN then no
2649 * more input can be expected, send ACK now.
2650 */
2651 if (tp->t_flags & TF_NEEDSYN)
2652 tp->t_flags |= TF_DELACK;
2653 else
2654 tp->t_flags |= TF_ACKNOW;
2655 tp->rcv_nxt++;
2656 }
2657 switch (tp->t_state) {
2658
2659 /*
2660 * In SYN_RECEIVED and ESTABLISHED STATES
2661 * enter the CLOSE_WAIT state.
2662 */
2663 case TCPS_SYN_RECEIVED:
2664 tp->t_starttime = ticks;
2665 /* FALLTHROUGH */
2666 case TCPS_ESTABLISHED:
2667 tp->t_state = TCPS_CLOSE_WAIT;
2668 break;
2669
2670 /*
2671 * If still in FIN_WAIT_1 STATE FIN has not been acked so
2672 * enter the CLOSING state.
2673 */
2674 case TCPS_FIN_WAIT_1:
2675 tp->t_state = TCPS_CLOSING;
2676 break;
2677
2678 /*
2679 * In FIN_WAIT_2 state enter the TIME_WAIT state,
2680 * starting the time-wait timer, turning off the other
2681 * standard timers.
2682 */
2683 case TCPS_FIN_WAIT_2:
2684 INP_INFO_WLOCK_ASSERT(&V_tcbinfo);
2685 KASSERT(ti_locked == TI_WLOCKED, ("%s: dodata "
2686 "TCP_FIN_WAIT_2 ti_locked: %d", __func__,
2687 ti_locked));
2688
2689 tcp_twstart(tp);
2690 INP_INFO_WUNLOCK(&V_tcbinfo);
2691 return;
2692 }
2693 }
2694 if (ti_locked == TI_RLOCKED)
2695 INP_INFO_RUNLOCK(&V_tcbinfo);
2696 else if (ti_locked == TI_WLOCKED)
2697 INP_INFO_WUNLOCK(&V_tcbinfo);
2698 else
2699 panic("%s: dodata epilogue ti_locked %d", __func__,
2700 ti_locked);
2701 ti_locked = TI_UNLOCKED;
2702
2703#ifdef TCPDEBUG
2704 if (so->so_options & SO_DEBUG)
2705 tcp_trace(TA_INPUT, ostate, tp, (void *)tcp_saveipgen,
2706 &tcp_savetcp, 0);
2707#endif
2708
2709 /*
2710 * Return any desired output.
2711 */
2712 if (needoutput || (tp->t_flags & TF_ACKNOW))
2713 (void) tcp_output(tp);
2714
2715check_delack:
2716 KASSERT(ti_locked == TI_UNLOCKED, ("%s: check_delack ti_locked %d",
2717 __func__, ti_locked));
2718 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2719 INP_WLOCK_ASSERT(tp->t_inpcb);
2720
2721 if (tp->t_flags & TF_DELACK) {
2722 tp->t_flags &= ~TF_DELACK;
2723 tcp_timer_activate(tp, TT_DELACK, tcp_delacktime);
2724 }
2725 INP_WUNLOCK(tp->t_inpcb);
2726 return;
2727
2728dropafterack:
2729 KASSERT(ti_locked == TI_RLOCKED || ti_locked == TI_WLOCKED,
2730 ("tcp_do_segment: dropafterack ti_locked %d", ti_locked));
2731
2732 /*
2733 * Generate an ACK dropping incoming segment if it occupies
2734 * sequence space, where the ACK reflects our state.
2735 *
2736 * We can now skip the test for the RST flag since all
2737 * paths to this code happen after packets containing
2738 * RST have been dropped.
2739 *
2740 * In the SYN-RECEIVED state, don't send an ACK unless the
2741 * segment we received passes the SYN-RECEIVED ACK test.
2742 * If it fails send a RST. This breaks the loop in the
2743 * "LAND" DoS attack, and also prevents an ACK storm
2744 * between two listening ports that have been sent forged
2745 * SYN segments, each with the source address of the other.
2746 */
2747 if (tp->t_state == TCPS_SYN_RECEIVED && (thflags & TH_ACK) &&
2748 (SEQ_GT(tp->snd_una, th->th_ack) ||
2749 SEQ_GT(th->th_ack, tp->snd_max)) ) {
2750 rstreason = BANDLIM_RST_OPENPORT;
2751 goto dropwithreset;
2752 }
2753#ifdef TCPDEBUG
2754 if (so->so_options & SO_DEBUG)
2755 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2756 &tcp_savetcp, 0);
2757#endif
2758 if (ti_locked == TI_RLOCKED)
2759 INP_INFO_RUNLOCK(&V_tcbinfo);
2760 else if (ti_locked == TI_WLOCKED)
2761 INP_INFO_WUNLOCK(&V_tcbinfo);
2762 else
2763 panic("%s: dropafterack epilogue ti_locked %d", __func__,
2764 ti_locked);
2765 ti_locked = TI_UNLOCKED;
2766
2767 tp->t_flags |= TF_ACKNOW;
2768 (void) tcp_output(tp);
2769 INP_WUNLOCK(tp->t_inpcb);
2770 m_freem(m);
2771 return;
2772
2773dropwithreset:
2774 if (ti_locked == TI_RLOCKED)
2775 INP_INFO_RUNLOCK(&V_tcbinfo);
2776 else if (ti_locked == TI_WLOCKED)
2777 INP_INFO_WUNLOCK(&V_tcbinfo);
2778 else
2779 panic("%s: dropwithreset ti_locked %d", __func__, ti_locked);
2780 ti_locked = TI_UNLOCKED;
2781
2782 if (tp != NULL) {
2783 tcp_dropwithreset(m, th, tp, tlen, rstreason);
2784 INP_WUNLOCK(tp->t_inpcb);
2785 } else
2786 tcp_dropwithreset(m, th, NULL, tlen, rstreason);
2787 return;
2788
2789drop:
2790 if (ti_locked == TI_RLOCKED)
2791 INP_INFO_RUNLOCK(&V_tcbinfo);
2792 else if (ti_locked == TI_WLOCKED)
2793 INP_INFO_WUNLOCK(&V_tcbinfo);
2794#ifdef INVARIANTS
2795 else
2796 INP_INFO_UNLOCK_ASSERT(&V_tcbinfo);
2797#endif
2798 ti_locked = TI_UNLOCKED;
2799
2800 /*
2801 * Drop space held by incoming segment and return.
2802 */
2803#ifdef TCPDEBUG
2804 if (tp == NULL || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
2805 tcp_trace(TA_DROP, ostate, tp, (void *)tcp_saveipgen,
2806 &tcp_savetcp, 0);
2807#endif
2808 if (tp != NULL)
2809 INP_WUNLOCK(tp->t_inpcb);
2810 m_freem(m);
2811}
2812
2813/*
2814 * Issue RST and make ACK acceptable to originator of segment.
2815 * The mbuf must still include the original packet header.
2816 * tp may be NULL.
2817 */
2818static void
2819tcp_dropwithreset(struct mbuf *m, struct tcphdr *th, struct tcpcb *tp,
2820 int tlen, int rstreason)
2821{
2822 struct ip *ip;
2823#ifdef INET6
2824 struct ip6_hdr *ip6;
2825#endif
2826
2827 if (tp != NULL) {
2828 INP_WLOCK_ASSERT(tp->t_inpcb);
2829 }
2830
2831 /* Don't bother if destination was broadcast/multicast. */
2832 if ((th->th_flags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST))
2833 goto drop;
2834#ifdef INET6
2835 if (mtod(m, struct ip *)->ip_v == 6) {
2836 ip6 = mtod(m, struct ip6_hdr *);
2837 if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst) ||
2838 IN6_IS_ADDR_MULTICAST(&ip6->ip6_src))
2839 goto drop;
2840 /* IPv6 anycast check is done at tcp6_input() */
2841 } else
2842#endif
2843 {
2844 ip = mtod(m, struct ip *);
2845 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
2846 IN_MULTICAST(ntohl(ip->ip_src.s_addr)) ||
2847 ip->ip_src.s_addr == htonl(INADDR_BROADCAST) ||
2848 in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))
2849 goto drop;
2850 }
2851
2852 /* Perform bandwidth limiting. */
2853 if (badport_bandlim(rstreason) < 0)
2854 goto drop;
2855
2856 /* tcp_respond consumes the mbuf chain. */
2857 if (th->th_flags & TH_ACK) {
2858 tcp_respond(tp, mtod(m, void *), th, m, (tcp_seq)0,
2859 th->th_ack, TH_RST);
2860 } else {
2861 if (th->th_flags & TH_SYN)
2862 tlen++;
2863 tcp_respond(tp, mtod(m, void *), th, m, th->th_seq+tlen,
2864 (tcp_seq)0, TH_RST|TH_ACK);
2865 }
2866 return;
2867drop:
2868 m_freem(m);
2869}
2870
2871/*
2872 * Parse TCP options and place in tcpopt.
2873 */
2874static void
2875tcp_dooptions(struct tcpopt *to, u_char *cp, int cnt, int flags)
2876{
2877 int opt, optlen;
2878
2879 to->to_flags = 0;
2880 for (; cnt > 0; cnt -= optlen, cp += optlen) {
2881 opt = cp[0];
2882 if (opt == TCPOPT_EOL)
2883 break;
2884 if (opt == TCPOPT_NOP)
2885 optlen = 1;
2886 else {
2887 if (cnt < 2)
2888 break;
2889 optlen = cp[1];
2890 if (optlen < 2 || optlen > cnt)
2891 break;
2892 }
2893 switch (opt) {
2894 case TCPOPT_MAXSEG:
2895 if (optlen != TCPOLEN_MAXSEG)
2896 continue;
2897 if (!(flags & TO_SYN))
2898 continue;
2899 to->to_flags |= TOF_MSS;
2900 bcopy((char *)cp + 2,
2901 (char *)&to->to_mss, sizeof(to->to_mss));
2902 to->to_mss = ntohs(to->to_mss);
2903 break;
2904 case TCPOPT_WINDOW:
2905 if (optlen != TCPOLEN_WINDOW)
2906 continue;
2907 if (!(flags & TO_SYN))
2908 continue;
2909 to->to_flags |= TOF_SCALE;
2910 to->to_wscale = min(cp[2], TCP_MAX_WINSHIFT);
2911 break;
2912 case TCPOPT_TIMESTAMP:
2913 if (optlen != TCPOLEN_TIMESTAMP)
2914 continue;
2915 to->to_flags |= TOF_TS;
2916 bcopy((char *)cp + 2,
2917 (char *)&to->to_tsval, sizeof(to->to_tsval));
2918 to->to_tsval = ntohl(to->to_tsval);
2919 bcopy((char *)cp + 6,
2920 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
2921 to->to_tsecr = ntohl(to->to_tsecr);
2922 break;
2923#ifdef TCP_SIGNATURE
2924 /*
2925 * XXX In order to reply to a host which has set the
2926 * TCP_SIGNATURE option in its initial SYN, we have to
2927 * record the fact that the option was observed here
2928 * for the syncache code to perform the correct response.
2929 */
2930 case TCPOPT_SIGNATURE:
2931 if (optlen != TCPOLEN_SIGNATURE)
2932 continue;
2933 to->to_flags |= TOF_SIGNATURE;
2934 to->to_signature = cp + 2;
2935 break;
2936#endif
2937 case TCPOPT_SACK_PERMITTED:
2938 if (optlen != TCPOLEN_SACK_PERMITTED)
2939 continue;
2940 if (!(flags & TO_SYN))
2941 continue;
2942 if (!V_tcp_do_sack)
2943 continue;
2944 to->to_flags |= TOF_SACKPERM;
2945 break;
2946 case TCPOPT_SACK:
2947 if (optlen <= 2 || (optlen - 2) % TCPOLEN_SACK != 0)
2948 continue;
2949 if (flags & TO_SYN)
2950 continue;
2951 to->to_flags |= TOF_SACK;
2952 to->to_nsacks = (optlen - 2) / TCPOLEN_SACK;
2953 to->to_sacks = cp + 2;
2954 TCPSTAT_INC(tcps_sack_rcv_blocks);
2955 break;
2956 default:
2957 continue;
2958 }
2959 }
2960}
2961
2962/*
2963 * Pull out of band byte out of a segment so
2964 * it doesn't appear in the user's data queue.
2965 * It is still reflected in the segment length for
2966 * sequencing purposes.
2967 */
2968static void
2969tcp_pulloutofband(struct socket *so, struct tcphdr *th, struct mbuf *m,
2970 int off)
2971{
2972 int cnt = off + th->th_urp - 1;
2973
2974 while (cnt >= 0) {
2975 if (m->m_len > cnt) {
2976 char *cp = mtod(m, caddr_t) + cnt;
2977 struct tcpcb *tp = sototcpcb(so);
2978
2979 INP_WLOCK_ASSERT(tp->t_inpcb);
2980
2981 tp->t_iobc = *cp;
2982 tp->t_oobflags |= TCPOOB_HAVEDATA;
2983 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
2984 m->m_len--;
2985 if (m->m_flags & M_PKTHDR)
2986 m->m_pkthdr.len--;
2987 return;
2988 }
2989 cnt -= m->m_len;
2990 m = m->m_next;
2991 if (m == NULL)
2992 break;
2993 }
2994 panic("tcp_pulloutofband");
2995}
2996
2997/*
2998 * Collect new round-trip time estimate
2999 * and update averages and current timeout.
3000 */
3001static void
3002tcp_xmit_timer(struct tcpcb *tp, int rtt)
3003{
3004 int delta;
3005
3006 INP_WLOCK_ASSERT(tp->t_inpcb);
3007
3008 TCPSTAT_INC(tcps_rttupdated);
3009 tp->t_rttupdated++;
3010 if (tp->t_srtt != 0) {
3011 /*
3012 * srtt is stored as fixed point with 5 bits after the
3013 * binary point (i.e., scaled by 8). The following magic
3014 * is equivalent to the smoothing algorithm in rfc793 with
3015 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
3016 * point). Adjust rtt to origin 0.
3017 */
3018 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
3019 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
3020
3021 if ((tp->t_srtt += delta) <= 0)
3022 tp->t_srtt = 1;
3023
3024 /*
3025 * We accumulate a smoothed rtt variance (actually, a
3026 * smoothed mean difference), then set the retransmit
3027 * timer to smoothed rtt + 4 times the smoothed variance.
3028 * rttvar is stored as fixed point with 4 bits after the
3029 * binary point (scaled by 16). The following is
3030 * equivalent to rfc793 smoothing with an alpha of .75
3031 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
3032 * rfc793's wired-in beta.
3033 */
3034 if (delta < 0)
3035 delta = -delta;
3036 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
3037 if ((tp->t_rttvar += delta) <= 0)
3038 tp->t_rttvar = 1;
3039 if (tp->t_rttbest > tp->t_srtt + tp->t_rttvar)
3040 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3041 } else {
3042 /*
3043 * No rtt measurement yet - use the unsmoothed rtt.
3044 * Set the variance to half the rtt (so our first
3045 * retransmit happens at 3*rtt).
3046 */
3047 tp->t_srtt = rtt << TCP_RTT_SHIFT;
3048 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
3049 tp->t_rttbest = tp->t_srtt + tp->t_rttvar;
3050 }
3051 tp->t_rtttime = 0;
3052 tp->t_rxtshift = 0;
3053
3054 /*
3055 * the retransmit should happen at rtt + 4 * rttvar.
3056 * Because of the way we do the smoothing, srtt and rttvar
3057 * will each average +1/2 tick of bias. When we compute
3058 * the retransmit timer, we want 1/2 tick of rounding and
3059 * 1 extra tick because of +-1/2 tick uncertainty in the
3060 * firing of the timer. The bias will give us exactly the
3061 * 1.5 tick we need. But, because the bias is
3062 * statistical, we have to test that we don't drop below
3063 * the minimum feasible timer (which is 2 ticks).
3064 */
3065 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
3066 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
3067
3068 /*
3069 * We received an ack for a packet that wasn't retransmitted;
3070 * it is probably safe to discard any error indications we've
3071 * received recently. This isn't quite right, but close enough
3072 * for now (a route might have failed after we sent a segment,
3073 * and the return path might not be symmetrical).
3074 */
3075 tp->t_softerror = 0;
3076}
3077
3078/*
3079 * Determine a reasonable value for maxseg size.
3080 * If the route is known, check route for mtu.
3081 * If none, use an mss that can be handled on the outgoing
3082 * interface without forcing IP to fragment; if bigger than
3083 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
3084 * to utilize large mbufs. If no route is found, route has no mtu,
3085 * or the destination isn't local, use a default, hopefully conservative
3086 * size (usually 512 or the default IP max size, but no more than the mtu
3087 * of the interface), as we can't discover anything about intervening
3088 * gateways or networks. We also initialize the congestion/slow start
3089 * window to be a single segment if the destination isn't local.
3090 * While looking at the routing entry, we also initialize other path-dependent
3091 * parameters from pre-set or cached values in the routing entry.
3092 *
3093 * Also take into account the space needed for options that we
3094 * send regularly. Make maxseg shorter by that amount to assure
3095 * that we can send maxseg amount of data even when the options
3096 * are present. Store the upper limit of the length of options plus
3097 * data in maxopd.
3098 *
3099 * In case of T/TCP, we call this routine during implicit connection
3100 * setup as well (offer = -1), to initialize maxseg from the cached
3101 * MSS of our peer.
3102 *
3103 * NOTE that this routine is only called when we process an incoming
3104 * segment. Outgoing SYN/ACK MSS settings are handled in tcp_mssopt().
3105 */
3106void
3107tcp_mss_update(struct tcpcb *tp, int offer,
3108 struct hc_metrics_lite *metricptr, int *mtuflags)
3109{
3110 int mss;
3111 u_long maxmtu;
3112 struct inpcb *inp = tp->t_inpcb;
3113 struct hc_metrics_lite metrics;
3114 int origoffer = offer;
3115#ifdef INET6
3116 int isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3117 size_t min_protoh = isipv6 ?
3118 sizeof (struct ip6_hdr) + sizeof (struct tcphdr) :
3119 sizeof (struct tcpiphdr);
3120#else
3121 const size_t min_protoh = sizeof(struct tcpiphdr);
3122#endif
3123
3124 INP_WLOCK_ASSERT(tp->t_inpcb);
3125
3126 /* Initialize. */
3127#ifdef INET6
3128 if (isipv6) {
3129 maxmtu = tcp_maxmtu6(&inp->inp_inc, mtuflags);
3130 tp->t_maxopd = tp->t_maxseg = V_tcp_v6mssdflt;
3131 } else
3132#endif
3133 {
3134 maxmtu = tcp_maxmtu(&inp->inp_inc, mtuflags);
3135 tp->t_maxopd = tp->t_maxseg = V_tcp_mssdflt;
3136 }
3137
3138 /*
3139 * No route to sender, stay with default mss and return.
3140 */
3141 if (maxmtu == 0) {
3142 /*
3143 * In case we return early we need to initialize metrics
3144 * to a defined state as tcp_hc_get() would do for us
3145 * if there was no cache hit.
3146 */
3147 if (metricptr != NULL)
3148 bzero(metricptr, sizeof(struct hc_metrics_lite));
3149 return;
3150 }
3151
3152 /* What have we got? */
3153 switch (offer) {
3154 case 0:
3155 /*
3156 * Offer == 0 means that there was no MSS on the SYN
3157 * segment, in this case we use tcp_mssdflt as
3158 * already assigned to t_maxopd above.
3159 */
3160 offer = tp->t_maxopd;
3161 break;
3162
3163 case -1:
3164 /*
3165 * Offer == -1 means that we didn't receive SYN yet.
3166 */
3167 /* FALLTHROUGH */
3168
3169 default:
3170 /*
3171 * Prevent DoS attack with too small MSS. Round up
3172 * to at least minmss.
3173 */
3174 offer = max(offer, V_tcp_minmss);
3175 }
3176
3177 /*
3178 * rmx information is now retrieved from tcp_hostcache.
3179 */
3180 tcp_hc_get(&inp->inp_inc, &metrics);
3181 if (metricptr != NULL)
3182 bcopy(&metrics, metricptr, sizeof(struct hc_metrics_lite));
3183
3184 /*
3185 * If there's a discovered mtu int tcp hostcache, use it
3186 * else, use the link mtu.
3187 */
3188 if (metrics.rmx_mtu)
3189 mss = min(metrics.rmx_mtu, maxmtu) - min_protoh;
3190 else {
3191#ifdef INET6
3192 if (isipv6) {
3193 mss = maxmtu - min_protoh;
3194 if (!V_path_mtu_discovery &&
3195 !in6_localaddr(&inp->in6p_faddr))
3196 mss = min(mss, V_tcp_v6mssdflt);
3197 } else
3198#endif
3199 {
3200 mss = maxmtu - min_protoh;
3201 if (!V_path_mtu_discovery &&
3202 !in_localaddr(inp->inp_faddr))
3203 mss = min(mss, V_tcp_mssdflt);
3204 }
3205 /*
3206 * XXX - The above conditional (mss = maxmtu - min_protoh)
3207 * probably violates the TCP spec.
3208 * The problem is that, since we don't know the
3209 * other end's MSS, we are supposed to use a conservative
3210 * default. But, if we do that, then MTU discovery will
3211 * never actually take place, because the conservative
3212 * default is much less than the MTUs typically seen
3213 * on the Internet today. For the moment, we'll sweep
3214 * this under the carpet.
3215 *
3216 * The conservative default might not actually be a problem
3217 * if the only case this occurs is when sending an initial
3218 * SYN with options and data to a host we've never talked
3219 * to before. Then, they will reply with an MSS value which
3220 * will get recorded and the new parameters should get
3221 * recomputed. For Further Study.
3222 */
3223 }
3224 mss = min(mss, offer);
3225
3226 /*
3227 * Sanity check: make sure that maxopd will be large
3228 * enough to allow some data on segments even if the
3229 * all the option space is used (40bytes). Otherwise
3230 * funny things may happen in tcp_output.
3231 */
3232 mss = max(mss, 64);
3233
3234 /*
3235 * maxopd stores the maximum length of data AND options
3236 * in a segment; maxseg is the amount of data in a normal
3237 * segment. We need to store this value (maxopd) apart
3238 * from maxseg, because now every segment carries options
3239 * and thus we normally have somewhat less data in segments.
3240 */
3241 tp->t_maxopd = mss;
3242
3243 /*
3244 * origoffer==-1 indicates that no segments were received yet.
3245 * In this case we just guess.
3246 */
3247 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
3248 (origoffer == -1 ||
3249 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
3250 mss -= TCPOLEN_TSTAMP_APPA;
3251
3252#if (MCLBYTES & (MCLBYTES - 1)) == 0
3253 if (mss > MCLBYTES)
3254 mss &= ~(MCLBYTES-1);
3255#else
3256 if (mss > MCLBYTES)
3257 mss = mss / MCLBYTES * MCLBYTES;
3258#endif
3259 tp->t_maxseg = mss;
3260}
3261
3262void
3263tcp_mss(struct tcpcb *tp, int offer)
3264{
3265 int rtt, mss;
3266 u_long bufsize;
3267 struct inpcb *inp;
3268 struct socket *so;
3269 struct hc_metrics_lite metrics;
3270 int mtuflags = 0;
3271#ifdef INET6
3272 int isipv6;
3273#endif
3274 KASSERT(tp != NULL, ("%s: tp == NULL", __func__));
3275
3276 tcp_mss_update(tp, offer, &metrics, &mtuflags);
3277
3278 mss = tp->t_maxseg;
3279 inp = tp->t_inpcb;
3280#ifdef INET6
3281 isipv6 = ((inp->inp_vflag & INP_IPV6) != 0) ? 1 : 0;
3282#endif
3283
3284 /*
3285 * If there's a pipesize, change the socket buffer to that size,
3286 * don't change if sb_hiwat is different than default (then it
3287 * has been changed on purpose with setsockopt).
3288 * Make the socket buffers an integral number of mss units;
3289 * if the mss is larger than the socket buffer, decrease the mss.
3290 */
3291 so = inp->inp_socket;
3292 SOCKBUF_LOCK(&so->so_snd);
3293 if ((so->so_snd.sb_hiwat == tcp_sendspace) && metrics.rmx_sendpipe)
3294 bufsize = metrics.rmx_sendpipe;
3295 else
3296 bufsize = so->so_snd.sb_hiwat;
3297 if (bufsize < mss)
3298 mss = bufsize;
3299 else {
3300 bufsize = roundup(bufsize, mss);
3301 if (bufsize > sb_max)
3302 bufsize = sb_max;
3303 if (bufsize > so->so_snd.sb_hiwat)
3304 (void)sbreserve_locked(&so->so_snd, bufsize, so, NULL);
3305 }
3306 SOCKBUF_UNLOCK(&so->so_snd);
3307 tp->t_maxseg = mss;
3308
3309 SOCKBUF_LOCK(&so->so_rcv);
3310 if ((so->so_rcv.sb_hiwat == tcp_recvspace) && metrics.rmx_recvpipe)
3311 bufsize = metrics.rmx_recvpipe;
3312 else
3313 bufsize = so->so_rcv.sb_hiwat;
3314 if (bufsize > mss) {
3315 bufsize = roundup(bufsize, mss);
3316 if (bufsize > sb_max)
3317 bufsize = sb_max;
3318 if (bufsize > so->so_rcv.sb_hiwat)
3319 (void)sbreserve_locked(&so->so_rcv, bufsize, so, NULL);
3320 }
3321 SOCKBUF_UNLOCK(&so->so_rcv);
3322 /*
3323 * While we're here, check the others too.
3324 */
3325 if (tp->t_srtt == 0 && (rtt = metrics.rmx_rtt)) {
3326 tp->t_srtt = rtt;
3327 tp->t_rttbest = tp->t_srtt + TCP_RTT_SCALE;
3328 TCPSTAT_INC(tcps_usedrtt);
3329 if (metrics.rmx_rttvar) {
3330 tp->t_rttvar = metrics.rmx_rttvar;
3331 TCPSTAT_INC(tcps_usedrttvar);
3332 } else {
3333 /* default variation is +- 1 rtt */
3334 tp->t_rttvar =
3335 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
3336 }
3337 TCPT_RANGESET(tp->t_rxtcur,
3338 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
3339 tp->t_rttmin, TCPTV_REXMTMAX);
3340 }
3341 if (metrics.rmx_ssthresh) {
3342 /*
3343 * There's some sort of gateway or interface
3344 * buffer limit on the path. Use this to set
3345 * the slow start threshhold, but set the
3346 * threshold to no less than 2*mss.
3347 */
3348 tp->snd_ssthresh = max(2 * mss, metrics.rmx_ssthresh);
3349 TCPSTAT_INC(tcps_usedssthresh);
3350 }
3351 if (metrics.rmx_bandwidth)
3352 tp->snd_bandwidth = metrics.rmx_bandwidth;
3353
3354 /*
3355 * Set the slow-start flight size depending on whether this
3356 * is a local network or not.
3357 *
3358 * Extend this so we cache the cwnd too and retrieve it here.
3359 * Make cwnd even bigger than RFC3390 suggests but only if we
3360 * have previous experience with the remote host. Be careful
3361 * not make cwnd bigger than remote receive window or our own
3362 * send socket buffer. Maybe put some additional upper bound
3363 * on the retrieved cwnd. Should do incremental updates to
3364 * hostcache when cwnd collapses so next connection doesn't
3365 * overloads the path again.
3366 *
3367 * RFC3390 says only do this if SYN or SYN/ACK didn't got lost.
3368 * We currently check only in syncache_socket for that.
3369 */
3370#define TCP_METRICS_CWND
3371#ifdef TCP_METRICS_CWND
3372 if (metrics.rmx_cwnd)
3373 tp->snd_cwnd = max(mss,
3374 min(metrics.rmx_cwnd / 2,
3375 min(tp->snd_wnd, so->so_snd.sb_hiwat)));
3376 else
3377#endif
3378 if (V_tcp_do_rfc3390)
3379 tp->snd_cwnd = min(4 * mss, max(2 * mss, 4380));
3380#ifdef INET6
3381 else if ((isipv6 && in6_localaddr(&inp->in6p_faddr)) ||
3382 (!isipv6 && in_localaddr(inp->inp_faddr)))
3383#else
3384 else if (in_localaddr(inp->inp_faddr))
3385#endif
3386 tp->snd_cwnd = mss * V_ss_fltsz_local;
3387 else
3388 tp->snd_cwnd = mss * V_ss_fltsz;
3389
3390 /* Check the interface for TSO capabilities. */
3391 if (mtuflags & CSUM_TSO)
3392 tp->t_flags |= TF_TSO;
3393}
3394
3395/*
3396 * Determine the MSS option to send on an outgoing SYN.
3397 */
3398int
3399tcp_mssopt(struct in_conninfo *inc)
3400{
3401 int mss = 0;
3402 u_long maxmtu = 0;
3403 u_long thcmtu = 0;
3404 size_t min_protoh;
3405
3406 KASSERT(inc != NULL, ("tcp_mssopt with NULL in_conninfo pointer"));
3407
3408#ifdef INET6
3409 if (inc->inc_flags & INC_ISIPV6) {
3410 mss = V_tcp_v6mssdflt;
3411 maxmtu = tcp_maxmtu6(inc, NULL);
3412 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3413 min_protoh = sizeof(struct ip6_hdr) + sizeof(struct tcphdr);
3414 } else
3415#endif
3416 {
3417 mss = V_tcp_mssdflt;
3418 maxmtu = tcp_maxmtu(inc, NULL);
3419 thcmtu = tcp_hc_getmtu(inc); /* IPv4 and IPv6 */
3420 min_protoh = sizeof(struct tcpiphdr);
3421 }
3422 if (maxmtu && thcmtu)
3423 mss = min(maxmtu, thcmtu) - min_protoh;
3424 else if (maxmtu || thcmtu)
3425 mss = max(maxmtu, thcmtu) - min_protoh;
3426
3427 return (mss);
3428}
3429
3430
3431/*
3432 * On a partial ack arrives, force the retransmission of the
3433 * next unacknowledged segment. Do not clear tp->t_dupacks.
3434 * By setting snd_nxt to ti_ack, this forces retransmission timer to
3435 * be started again.
3436 */
3437static void
3438tcp_newreno_partial_ack(struct tcpcb *tp, struct tcphdr *th)
3439{
3440 tcp_seq onxt = tp->snd_nxt;
3441 u_long ocwnd = tp->snd_cwnd;
3442
3443 INP_WLOCK_ASSERT(tp->t_inpcb);
3444
3445 tcp_timer_activate(tp, TT_REXMT, 0);
3446 tp->t_rtttime = 0;
3447 tp->snd_nxt = th->th_ack;
3448 /*
3449 * Set snd_cwnd to one segment beyond acknowledged offset.
3450 * (tp->snd_una has not yet been updated when this function is called.)
3451 */
3452 tp->snd_cwnd = tp->t_maxseg + (th->th_ack - tp->snd_una);
3453 tp->t_flags |= TF_ACKNOW;
3454 (void) tcp_output(tp);
3455 tp->snd_cwnd = ocwnd;
3456 if (SEQ_GT(onxt, tp->snd_nxt))
3457 tp->snd_nxt = onxt;
3458 /*
3459 * Partial window deflation. Relies on fact that tp->snd_una
3460 * not updated yet.
3461 */
3462 if (tp->snd_cwnd > th->th_ack - tp->snd_una)
3463 tp->snd_cwnd -= th->th_ack - tp->snd_una;
3464 else
3465 tp->snd_cwnd = 0;
3466 tp->snd_cwnd += tp->t_maxseg;
3467}