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