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 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
34 * $Id: tcp_input.c,v 1.85 1999/05/03 23:57:30 billf Exp $
35 */
36
37#include "opt_ipfw.h" /* for ipfw_fwd */
38#include "opt_tcpdebug.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/kernel.h>
43#include <sys/sysctl.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/proc.h> /* for proc0 declaration */
47#include <sys/protosw.h>
48#include <sys/socket.h>
49#include <sys/socketvar.h>
50#include <sys/syslog.h>
51
52#include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
53
54#include <net/if.h>
55#include <net/route.h>
56
57#include <netinet/in.h>
58#include <netinet/in_systm.h>
59#include <netinet/ip.h>
60#include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
61#include <netinet/in_pcb.h>
62#include <netinet/ip_var.h>
63#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
64#include <netinet/tcp.h>
65#include <netinet/tcp_fsm.h>
66#include <netinet/tcp_seq.h>
67#include <netinet/tcp_timer.h>
68#include <netinet/tcp_var.h>
69#include <netinet/tcpip.h>
70#ifdef TCPDEBUG
71#include <netinet/tcp_debug.h>
72static struct tcpiphdr tcp_saveti;
73#endif
74
75static int tcprexmtthresh = 3;
76tcp_seq tcp_iss;
77tcp_cc tcp_ccgen;
78
79struct tcpstat tcpstat;
80SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RD,
81 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
82
83static int log_in_vain = 0;
84SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
85 &log_in_vain, 0, "Log all incoming TCP connections");
86
87int tcp_delack_enabled = 1;
88SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
89 &tcp_delack_enabled, 0,
90 "Delay ACK to try and piggyback it onto a data packet");
91
92u_long tcp_now;
93struct inpcbhead tcb;
94struct inpcbinfo tcbinfo;
95
96static void tcp_dooptions __P((struct tcpcb *,
97 u_char *, int, struct tcpiphdr *, struct tcpopt *));
98static void tcp_pulloutofband __P((struct socket *,
99 struct tcpiphdr *, struct mbuf *));
100static int tcp_reass __P((struct tcpcb *, struct tcpiphdr *, struct mbuf *));
101static void tcp_xmit_timer __P((struct tcpcb *, int));
102
103
104/*
105 * Insert segment ti into reassembly queue of tcp with
106 * control block tp. Return TH_FIN if reassembly now includes
107 * a segment with FIN. The macro form does the common case inline
108 * (segment is the next to be received on an established connection,
109 * and the queue is empty), avoiding linkage into and removal
110 * from the queue and repetition of various conversions.
111 * Set DELACK for segments received in order, but ack immediately
112 * when segments are out of order (so fast retransmit can work).
113 */
114#define TCP_REASS(tp, ti, m, so, flags) { \
115 if ((ti)->ti_seq == (tp)->rcv_nxt && \
116 (tp)->t_segq == NULL && \
117 (tp)->t_state == TCPS_ESTABLISHED) { \
118 if (tcp_delack_enabled) \
119 tp->t_flags |= TF_DELACK; \
120 else \
121 tp->t_flags |= TF_ACKNOW; \
122 (tp)->rcv_nxt += (ti)->ti_len; \
123 flags = (ti)->ti_flags & TH_FIN; \
124 tcpstat.tcps_rcvpack++;\
125 tcpstat.tcps_rcvbyte += (ti)->ti_len;\
126 sbappend(&(so)->so_rcv, (m)); \
127 sorwakeup(so); \
128 } else { \
129 (flags) = tcp_reass((tp), (ti), (m)); \
130 tp->t_flags |= TF_ACKNOW; \
131 } \
132}
133
134static int
135tcp_reass(tp, ti, m)
136 register struct tcpcb *tp;
137 register struct tcpiphdr *ti;
138 struct mbuf *m;
139{
140 struct mbuf *q;
141 struct mbuf *p;
142 struct mbuf *nq;
143 struct socket *so = tp->t_inpcb->inp_socket;
144 int flags;
145
146#define GETTCP(m) ((struct tcpiphdr *)m->m_pkthdr.header)
147
148 /*
149 * Call with ti==0 after become established to
150 * force pre-ESTABLISHED data up to user socket.
151 */
152 if (ti == 0)
153 goto present;
154
155 m->m_pkthdr.header = ti;
156
157 /*
158 * Find a segment which begins after this one does.
159 */
160 for (q = tp->t_segq, p = NULL; q; p = q, q = q->m_nextpkt)
161 if (SEQ_GT(GETTCP(q)->ti_seq, ti->ti_seq))
162 break;
163
164 /*
165 * If there is a preceding segment, it may provide some of
166 * our data already. If so, drop the data from the incoming
167 * segment. If it provides all of our data, drop us.
168 */
169 if (p != NULL) {
170 register int i;
171 /* conversion to int (in i) handles seq wraparound */
172 i = GETTCP(p)->ti_seq + GETTCP(p)->ti_len - ti->ti_seq;
173 if (i > 0) {
174 if (i >= ti->ti_len) {
175 tcpstat.tcps_rcvduppack++;
176 tcpstat.tcps_rcvdupbyte += ti->ti_len;
177 m_freem(m);
178 /*
179 * Try to present any queued data
180 * at the left window edge to the user.
181 * This is needed after the 3-WHS
182 * completes.
183 */
184 goto present; /* ??? */
185 }
186 m_adj(m, i);
187 ti->ti_len -= i;
188 ti->ti_seq += i;
189 }
190 }
191 tcpstat.tcps_rcvoopack++;
192 tcpstat.tcps_rcvoobyte += ti->ti_len;
193
194 /*
195 * While we overlap succeeding segments trim them or,
196 * if they are completely covered, dequeue them.
197 */
198 while (q) {
199 register int i = (ti->ti_seq + ti->ti_len) - GETTCP(q)->ti_seq;
200 if (i <= 0)
201 break;
202 if (i < GETTCP(q)->ti_len) {
203 GETTCP(q)->ti_seq += i;
204 GETTCP(q)->ti_len -= i;
205 m_adj(q, i);
206 break;
207 }
208
209 nq = q->m_nextpkt;
210 if (p)
211 p->m_nextpkt = nq;
212 else
213 tp->t_segq = nq;
214 m_freem(q);
215 q = nq;
216 }
217
218 if (p == NULL) {
219 m->m_nextpkt = tp->t_segq;
220 tp->t_segq = m;
221 } else {
222 m->m_nextpkt = p->m_nextpkt;
223 p->m_nextpkt = m;
224 }
225
226present:
227 /*
228 * Present data to user, advancing rcv_nxt through
229 * completed sequence space.
230 */
231 if (!TCPS_HAVEESTABLISHED(tp->t_state))
232 return (0);
233 q = tp->t_segq;
234 if (!q || GETTCP(q)->ti_seq != tp->rcv_nxt)
235 return (0);
236 do {
237 tp->rcv_nxt += GETTCP(q)->ti_len;
238 flags = GETTCP(q)->ti_flags & TH_FIN;
239 nq = q->m_nextpkt;
240 tp->t_segq = nq;
241 q->m_nextpkt = NULL;
242 if (so->so_state & SS_CANTRCVMORE)
243 m_freem(q);
244 else
245 sbappend(&so->so_rcv, q);
246 q = nq;
247 } while (q && GETTCP(q)->ti_seq == tp->rcv_nxt);
248 sorwakeup(so);
249 return (flags);
250
251#undef GETTCP
252}
253
254/*
255 * TCP input routine, follows pages 65-76 of the
256 * protocol specification dated September, 1981 very closely.
257 */
258void
259tcp_input(m, iphlen)
260 register struct mbuf *m;
261 int iphlen;
262{
263 register struct tcpiphdr *ti;
264 register struct inpcb *inp;
265 u_char *optp = NULL;
266 int optlen = 0;
267 int len, tlen, off;
268 register struct tcpcb *tp = 0;
269 register int tiflags;
270 struct socket *so = 0;
271 int todrop, acked, ourfinisacked, needoutput = 0;
272 struct in_addr laddr;
273 int dropsocket = 0;
274 int iss = 0;
275 u_long tiwin;
276 struct tcpopt to; /* options in this segment */
277 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
278 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
279#ifdef TCPDEBUG
280 short ostate = 0;
281#endif
282
283 bzero((char *)&to, sizeof(to));
284
285 tcpstat.tcps_rcvtotal++;
286 /*
287 * Get IP and TCP header together in first mbuf.
288 * Note: IP leaves IP header in first mbuf.
289 */
290 ti = mtod(m, struct tcpiphdr *);
291 if (iphlen > sizeof (struct ip))
292 ip_stripoptions(m, (struct mbuf *)0);
293 if (m->m_len < sizeof (struct tcpiphdr)) {
294 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
295 tcpstat.tcps_rcvshort++;
296 return;
297 }
298 ti = mtod(m, struct tcpiphdr *);
299 }
300
301 /*
302 * Checksum extended TCP header and data.
303 */
304 tlen = ((struct ip *)ti)->ip_len;
305 len = sizeof (struct ip) + tlen;
306 bzero(ti->ti_x1, sizeof(ti->ti_x1));
307 ti->ti_len = (u_short)tlen;
308 HTONS(ti->ti_len);
309 ti->ti_sum = in_cksum(m, len);
310 if (ti->ti_sum) {
311 tcpstat.tcps_rcvbadsum++;
312 goto drop;
313 }
314
315 /*
316 * Check that TCP offset makes sense,
317 * pull out TCP options and adjust length. XXX
318 */
319 off = ti->ti_off << 2;
320 if (off < sizeof (struct tcphdr) || off > tlen) {
321 tcpstat.tcps_rcvbadoff++;
322 goto drop;
323 }
324 tlen -= off;
325 ti->ti_len = tlen;
326 if (off > sizeof (struct tcphdr)) {
327 if (m->m_len < sizeof(struct ip) + off) {
328 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
329 tcpstat.tcps_rcvshort++;
330 return;
331 }
332 ti = mtod(m, struct tcpiphdr *);
333 }
334 optlen = off - sizeof (struct tcphdr);
335 optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
336 }
337 tiflags = ti->ti_flags;
338
339 /*
340 * Convert TCP protocol specific fields to host format.
341 */
342 NTOHL(ti->ti_seq);
343 NTOHL(ti->ti_ack);
344 NTOHS(ti->ti_win);
345 NTOHS(ti->ti_urp);
346
347 /*
348 * Drop TCP, IP headers and TCP options.
349 */
350 m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
351 m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
352
353 /*
354 * Locate pcb for segment.
355 */
356findpcb:
357#ifdef IPFIREWALL_FORWARD
358 if (ip_fw_fwd_addr != NULL) {
359 /*
360 * Diverted. Pretend to be the destination.
361 * already got one like this?
362 */
363 inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
364 ti->ti_dst, ti->ti_dport, 0);
365 if (!inp) {
366 /*
367 * No, then it's new. Try find the ambushing socket
368 */
369 if (!ip_fw_fwd_addr->sin_port) {
370 inp = in_pcblookup_hash(&tcbinfo, ti->ti_src,
371 ti->ti_sport, ip_fw_fwd_addr->sin_addr,
372 ti->ti_dport, 1);
373 } else {
374 inp = in_pcblookup_hash(&tcbinfo,
375 ti->ti_src, ti->ti_sport,
376 ip_fw_fwd_addr->sin_addr,
377 ntohs(ip_fw_fwd_addr->sin_port), 1);
378 }
379 }
380 ip_fw_fwd_addr = NULL;
381 } else
382#endif /* IPFIREWALL_FORWARD */
383
384 inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
385 ti->ti_dst, ti->ti_dport, 1);
386
387 /*
388 * If the state is CLOSED (i.e., TCB does not exist) then
389 * all data in the incoming segment is discarded.
390 * If the TCB exists but is in CLOSED state, it is embryonic,
391 * but should either do a listen or a connect soon.
392 */
393 if (inp == NULL) {
394 if (log_in_vain && tiflags & TH_SYN) {
395 char buf[4*sizeof "123"];
396
397 strcpy(buf, inet_ntoa(ti->ti_dst));
398 log(LOG_INFO,
399 "Connection attempt to TCP %s:%d from %s:%d\n",
400 buf, ntohs(ti->ti_dport), inet_ntoa(ti->ti_src),
401 ntohs(ti->ti_sport));
402 }
403#ifdef ICMP_BANDLIM
404 if (badport_bandlim(1) < 0)
405 goto drop;
406#endif
407 goto dropwithreset;
408 }
409 tp = intotcpcb(inp);
410 if (tp == 0)
411 goto dropwithreset;
412 if (tp->t_state == TCPS_CLOSED)
413 goto drop;
414
415 /* Unscale the window into a 32-bit value. */
416 if ((tiflags & TH_SYN) == 0)
417 tiwin = ti->ti_win << tp->snd_scale;
418 else
419 tiwin = ti->ti_win;
420
421 so = inp->inp_socket;
422 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
423#ifdef TCPDEBUG
424 if (so->so_options & SO_DEBUG) {
425 ostate = tp->t_state;
426 tcp_saveti = *ti;
427 }
428#endif
429 if (so->so_options & SO_ACCEPTCONN) {
430 register struct tcpcb *tp0 = tp;
431 struct socket *so2;
432 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
433 /*
434 * Note: dropwithreset makes sure we don't
435 * send a RST in response to a RST.
436 */
437 if (tiflags & TH_ACK) {
438 tcpstat.tcps_badsyn++;
439 goto dropwithreset;
440 }
441 goto drop;
442 }
443 so2 = sonewconn(so, 0);
444 if (so2 == 0) {
445 tcpstat.tcps_listendrop++;
446 so2 = sodropablereq(so);
447 if (so2) {
448 tcp_drop(sototcpcb(so2), ETIMEDOUT);
449 so2 = sonewconn(so, 0);
450 }
451 if (!so2)
452 goto drop;
453 }
454 so = so2;
455 /*
456 * This is ugly, but ....
457 *
458 * Mark socket as temporary until we're
459 * committed to keeping it. The code at
460 * ``drop'' and ``dropwithreset'' check the
461 * flag dropsocket to see if the temporary
462 * socket created here should be discarded.
463 * We mark the socket as discardable until
464 * we're committed to it below in TCPS_LISTEN.
465 */
466 dropsocket++;
467 inp = (struct inpcb *)so->so_pcb;
468 inp->inp_laddr = ti->ti_dst;
469 inp->inp_lport = ti->ti_dport;
470 if (in_pcbinshash(inp) != 0) {
471 /*
472 * Undo the assignments above if we failed to put
473 * the PCB on the hash lists.
474 */
475 inp->inp_laddr.s_addr = INADDR_ANY;
476 inp->inp_lport = 0;
477 goto drop;
478 }
479 inp->inp_options = ip_srcroute();
480 tp = intotcpcb(inp);
481 tp->t_state = TCPS_LISTEN;
482 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
483
484 /* Compute proper scaling value from buffer space */
485 while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
486 TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
487 tp->request_r_scale++;
488 }
489 }
490
491 /*
492 * Segment received on connection.
493 * Reset idle time and keep-alive timer.
494 */
495 tp->t_idle = 0;
496 if (TCPS_HAVEESTABLISHED(tp->t_state))
497 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
498
499 /*
500 * Process options if not in LISTEN state,
501 * else do it below (after getting remote address).
502 */
503 if (tp->t_state != TCPS_LISTEN)
504 tcp_dooptions(tp, optp, optlen, ti, &to);
505
506 /*
507 * Header prediction: check for the two common cases
508 * of a uni-directional data xfer. If the packet has
509 * no control flags, is in-sequence, the window didn't
510 * change and we're not retransmitting, it's a
511 * candidate. If the length is zero and the ack moved
512 * forward, we're the sender side of the xfer. Just
513 * free the data acked & wake any higher level process
514 * that was blocked waiting for space. If the length
515 * is non-zero and the ack didn't move, we're the
516 * receiver side. If we're getting packets in-order
517 * (the reassembly queue is empty), add the data to
518 * the socket buffer and note that we need a delayed ack.
519 * Make sure that the hidden state-flags are also off.
520 * Since we check for TCPS_ESTABLISHED above, it can only
521 * be TH_NEEDSYN.
522 */
523 if (tp->t_state == TCPS_ESTABLISHED &&
524 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
525 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
526 ((to.to_flag & TOF_TS) == 0 ||
527 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
528 /*
529 * Using the CC option is compulsory if once started:
530 * the segment is OK if no T/TCP was negotiated or
531 * if the segment has a CC option equal to CCrecv
532 */
533 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
534 ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
535 ti->ti_seq == tp->rcv_nxt &&
536 tiwin && tiwin == tp->snd_wnd &&
537 tp->snd_nxt == tp->snd_max) {
538
539 /*
540 * If last ACK falls within this segment's sequence numbers,
541 * record the timestamp.
542 * NOTE that the test is modified according to the latest
543 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
544 */
545 if ((to.to_flag & TOF_TS) != 0 &&
546 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
547 tp->ts_recent_age = tcp_now;
548 tp->ts_recent = to.to_tsval;
549 }
550
551 if (ti->ti_len == 0) {
552 if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
553 SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
554 tp->snd_cwnd >= tp->snd_wnd &&
555 tp->t_dupacks < tcprexmtthresh) {
556 /*
557 * this is a pure ack for outstanding data.
558 */
559 ++tcpstat.tcps_predack;
560 if ((to.to_flag & TOF_TS) != 0)
561 tcp_xmit_timer(tp,
562 tcp_now - to.to_tsecr + 1);
563 else if (tp->t_rtt &&
564 SEQ_GT(ti->ti_ack, tp->t_rtseq))
565 tcp_xmit_timer(tp, tp->t_rtt);
566 acked = ti->ti_ack - tp->snd_una;
567 tcpstat.tcps_rcvackpack++;
568 tcpstat.tcps_rcvackbyte += acked;
569 sbdrop(&so->so_snd, acked);
570 tp->snd_una = ti->ti_ack;
571 m_freem(m);
572
573 /*
574 * If all outstanding data are acked, stop
575 * retransmit timer, otherwise restart timer
576 * using current (possibly backed-off) value.
577 * If process is waiting for space,
578 * wakeup/selwakeup/signal. If data
579 * are ready to send, let tcp_output
580 * decide between more output or persist.
581 */
582 if (tp->snd_una == tp->snd_max)
583 tp->t_timer[TCPT_REXMT] = 0;
584 else if (tp->t_timer[TCPT_PERSIST] == 0)
585 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
586
587 sowwakeup(so);
588 if (so->so_snd.sb_cc)
589 (void) tcp_output(tp);
590 return;
591 }
592 } else if (ti->ti_ack == tp->snd_una &&
593 tp->t_segq == NULL &&
594 ti->ti_len <= sbspace(&so->so_rcv)) {
595 /*
596 * this is a pure, in-sequence data packet
597 * with nothing on the reassembly queue and
598 * we have enough buffer space to take it.
599 */
600 ++tcpstat.tcps_preddat;
601 tp->rcv_nxt += ti->ti_len;
602 tcpstat.tcps_rcvpack++;
603 tcpstat.tcps_rcvbyte += ti->ti_len;
604 /*
605 * Add data to socket buffer.
606 */
607 sbappend(&so->so_rcv, m);
608 sorwakeup(so);
609 if (tcp_delack_enabled) {
610 tp->t_flags |= TF_DELACK;
611 } else {
612 tp->t_flags |= TF_ACKNOW;
613 tcp_output(tp);
614 }
615 return;
616 }
617 }
618
619 /*
620 * Calculate amount of space in receive window,
621 * and then do TCP input processing.
622 * Receive window is amount of space in rcv queue,
623 * but not less than advertised window.
624 */
625 { int win;
626
627 win = sbspace(&so->so_rcv);
628 if (win < 0)
629 win = 0;
630 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
631 }
632
633 switch (tp->t_state) {
634
635 /*
636 * If the state is LISTEN then ignore segment if it contains an RST.
637 * If the segment contains an ACK then it is bad and send a RST.
638 * If it does not contain a SYN then it is not interesting; drop it.
639 * If it is from this socket, drop it, it must be forged.
640 * Don't bother responding if the destination was a broadcast.
641 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
642 * tp->iss, and send a segment:
643 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
644 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
645 * Fill in remote peer address fields if not previously specified.
646 * Enter SYN_RECEIVED state, and process any other fields of this
647 * segment in this state.
648 */
649 case TCPS_LISTEN: {
650 register struct sockaddr_in *sin;
651
652 if (tiflags & TH_RST)
653 goto drop;
654 if (tiflags & TH_ACK)
655 goto dropwithreset;
656 if ((tiflags & TH_SYN) == 0)
657 goto drop;
658 if ((ti->ti_dport == ti->ti_sport) &&
659 (ti->ti_dst.s_addr == ti->ti_src.s_addr))
660 goto drop;
661 /*
662 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
663 * in_broadcast() should never return true on a received
664 * packet with M_BCAST not set.
665 */
666 if (m->m_flags & (M_BCAST|M_MCAST) ||
667 IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
668 goto drop;
669 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
670 M_NOWAIT);
671 if (sin == NULL)
672 goto drop;
673 sin->sin_family = AF_INET;
674 sin->sin_len = sizeof(*sin);
675 sin->sin_addr = ti->ti_src;
676 sin->sin_port = ti->ti_sport;
677 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
678 laddr = inp->inp_laddr;
679 if (inp->inp_laddr.s_addr == INADDR_ANY)
680 inp->inp_laddr = ti->ti_dst;
681 if (in_pcbconnect(inp, (struct sockaddr *)sin, &proc0)) {
682 inp->inp_laddr = laddr;
683 FREE(sin, M_SONAME);
684 goto drop;
685 }
686 FREE(sin, M_SONAME);
687 tp->t_template = tcp_template(tp);
688 if (tp->t_template == 0) {
689 tp = tcp_drop(tp, ENOBUFS);
690 dropsocket = 0; /* socket is already gone */
691 goto drop;
692 }
693 if ((taop = tcp_gettaocache(inp)) == NULL) {
694 taop = &tao_noncached;
695 bzero(taop, sizeof(*taop));
696 }
697 tcp_dooptions(tp, optp, optlen, ti, &to);
698 if (iss)
699 tp->iss = iss;
700 else
701 tp->iss = tcp_iss;
702 tcp_iss += TCP_ISSINCR/4;
703 tp->irs = ti->ti_seq;
704 tcp_sendseqinit(tp);
705 tcp_rcvseqinit(tp);
706 /*
707 * Initialization of the tcpcb for transaction;
708 * set SND.WND = SEG.WND,
709 * initialize CCsend and CCrecv.
710 */
711 tp->snd_wnd = tiwin; /* initial send-window */
712 tp->cc_send = CC_INC(tcp_ccgen);
713 tp->cc_recv = to.to_cc;
714 /*
715 * Perform TAO test on incoming CC (SEG.CC) option, if any.
716 * - compare SEG.CC against cached CC from the same host,
717 * if any.
718 * - if SEG.CC > chached value, SYN must be new and is accepted
719 * immediately: save new CC in the cache, mark the socket
720 * connected, enter ESTABLISHED state, turn on flag to
721 * send a SYN in the next segment.
722 * A virtual advertised window is set in rcv_adv to
723 * initialize SWS prevention. Then enter normal segment
724 * processing: drop SYN, process data and FIN.
725 * - otherwise do a normal 3-way handshake.
726 */
727 if ((to.to_flag & TOF_CC) != 0) {
728 if (((tp->t_flags & TF_NOPUSH) != 0) &&
729 taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
730
731 taop->tao_cc = to.to_cc;
732 tp->t_state = TCPS_ESTABLISHED;
733
734 /*
735 * If there is a FIN, or if there is data and the
736 * connection is local, then delay SYN,ACK(SYN) in
737 * the hope of piggy-backing it on a response
738 * segment. Otherwise must send ACK now in case
739 * the other side is slow starting.
740 */
741 if (tcp_delack_enabled && ((tiflags & TH_FIN) || (ti->ti_len != 0 &&
742 in_localaddr(inp->inp_faddr))))
743 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
744 else
745 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
746
747 /*
748 * Limit the `virtual advertised window' to TCP_MAXWIN
749 * here. Even if we requested window scaling, it will
750 * become effective only later when our SYN is acked.
751 */
752 tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
753 tcpstat.tcps_connects++;
754 soisconnected(so);
755 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
756 dropsocket = 0; /* committed to socket */
757 tcpstat.tcps_accepts++;
758 goto trimthenstep6;
759 }
760 /* else do standard 3-way handshake */
761 } else {
762 /*
763 * No CC option, but maybe CC.NEW:
764 * invalidate cached value.
765 */
766 taop->tao_cc = 0;
767 }
768 /*
769 * TAO test failed or there was no CC option,
770 * do a standard 3-way handshake.
771 */
772 tp->t_flags |= TF_ACKNOW;
773 tp->t_state = TCPS_SYN_RECEIVED;
774 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
775 dropsocket = 0; /* committed to socket */
776 tcpstat.tcps_accepts++;
777 goto trimthenstep6;
778 }
779
780 /*
781 * If the state is SYN_RECEIVED:
782 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
783 */
784 case TCPS_SYN_RECEIVED:
785 if ((tiflags & TH_ACK) &&
786 (SEQ_LEQ(ti->ti_ack, tp->snd_una) ||
787 SEQ_GT(ti->ti_ack, tp->snd_max)))
788 goto dropwithreset;
789 break;
790
791 /*
792 * If the state is SYN_SENT:
793 * if seg contains an ACK, but not for our SYN, drop the input.
794 * if seg contains a RST, then drop the connection.
795 * if seg does not contain SYN, then drop it.
796 * Otherwise this is an acceptable SYN segment
797 * initialize tp->rcv_nxt and tp->irs
798 * if seg contains ack then advance tp->snd_una
799 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
800 * arrange for segment to be acked (eventually)
801 * continue processing rest of data/controls, beginning with URG
802 */
803 case TCPS_SYN_SENT:
804 if ((taop = tcp_gettaocache(inp)) == NULL) {
805 taop = &tao_noncached;
806 bzero(taop, sizeof(*taop));
807 }
808
809 if ((tiflags & TH_ACK) &&
810 (SEQ_LEQ(ti->ti_ack, tp->iss) ||
811 SEQ_GT(ti->ti_ack, tp->snd_max))) {
812 /*
813 * If we have a cached CCsent for the remote host,
814 * hence we haven't just crashed and restarted,
815 * do not send a RST. This may be a retransmission
816 * from the other side after our earlier ACK was lost.
817 * Our new SYN, when it arrives, will serve as the
818 * needed ACK.
819 */
820 if (taop->tao_ccsent != 0)
821 goto drop;
822 else
823 goto dropwithreset;
824 }
825 if (tiflags & TH_RST) {
826 if (tiflags & TH_ACK)
827 tp = tcp_drop(tp, ECONNREFUSED);
828 goto drop;
829 }
830 if ((tiflags & TH_SYN) == 0)
831 goto drop;
832 tp->snd_wnd = ti->ti_win; /* initial send window */
833 tp->cc_recv = to.to_cc; /* foreign CC */
834
835 tp->irs = ti->ti_seq;
836 tcp_rcvseqinit(tp);
837 if (tiflags & TH_ACK) {
838 /*
839 * Our SYN was acked. If segment contains CC.ECHO
840 * option, check it to make sure this segment really
841 * matches our SYN. If not, just drop it as old
842 * duplicate, but send an RST if we're still playing
843 * by the old rules. If no CC.ECHO option, make sure
844 * we don't get fooled into using T/TCP.
845 */
846 if (to.to_flag & TOF_CCECHO) {
847 if (tp->cc_send != to.to_ccecho) {
848 if (taop->tao_ccsent != 0)
849 goto drop;
850 else
851 goto dropwithreset;
852 }
853 } else
854 tp->t_flags &= ~TF_RCVD_CC;
855 tcpstat.tcps_connects++;
856 soisconnected(so);
857 /* Do window scaling on this connection? */
858 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
859 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
860 tp->snd_scale = tp->requested_s_scale;
861 tp->rcv_scale = tp->request_r_scale;
862 }
863 /* Segment is acceptable, update cache if undefined. */
864 if (taop->tao_ccsent == 0)
865 taop->tao_ccsent = to.to_ccecho;
866
867 tp->rcv_adv += tp->rcv_wnd;
868 tp->snd_una++; /* SYN is acked */
869 /*
870 * If there's data, delay ACK; if there's also a FIN
871 * ACKNOW will be turned on later.
872 */
873 if (tcp_delack_enabled && ti->ti_len != 0)
874 tp->t_flags |= TF_DELACK;
875 else
876 tp->t_flags |= TF_ACKNOW;
877 /*
878 * Received <SYN,ACK> in SYN_SENT[*] state.
879 * Transitions:
880 * SYN_SENT --> ESTABLISHED
881 * SYN_SENT* --> FIN_WAIT_1
882 */
883 if (tp->t_flags & TF_NEEDFIN) {
884 tp->t_state = TCPS_FIN_WAIT_1;
885 tp->t_flags &= ~TF_NEEDFIN;
886 tiflags &= ~TH_SYN;
887 } else {
888 tp->t_state = TCPS_ESTABLISHED;
889 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
890 }
891 } else {
892 /*
893 * Received initial SYN in SYN-SENT[*] state => simul-
894 * taneous open. If segment contains CC option and there is
895 * a cached CC, apply TAO test; if it succeeds, connection is
896 * half-synchronized. Otherwise, do 3-way handshake:
897 * SYN-SENT -> SYN-RECEIVED
898 * SYN-SENT* -> SYN-RECEIVED*
899 * If there was no CC option, clear cached CC value.
900 */
901 tp->t_flags |= TF_ACKNOW;
902 tp->t_timer[TCPT_REXMT] = 0;
903 if (to.to_flag & TOF_CC) {
904 if (taop->tao_cc != 0 &&
905 CC_GT(to.to_cc, taop->tao_cc)) {
906 /*
907 * update cache and make transition:
908 * SYN-SENT -> ESTABLISHED*
909 * SYN-SENT* -> FIN-WAIT-1*
910 */
911 taop->tao_cc = to.to_cc;
912 if (tp->t_flags & TF_NEEDFIN) {
913 tp->t_state = TCPS_FIN_WAIT_1;
914 tp->t_flags &= ~TF_NEEDFIN;
915 } else {
916 tp->t_state = TCPS_ESTABLISHED;
917 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
918 }
919 tp->t_flags |= TF_NEEDSYN;
920 } else
921 tp->t_state = TCPS_SYN_RECEIVED;
922 } else {
923 /* CC.NEW or no option => invalidate cache */
924 taop->tao_cc = 0;
925 tp->t_state = TCPS_SYN_RECEIVED;
926 }
927 }
928
929trimthenstep6:
930 /*
931 * Advance ti->ti_seq to correspond to first data byte.
932 * If data, trim to stay within window,
933 * dropping FIN if necessary.
934 */
935 ti->ti_seq++;
936 if (ti->ti_len > tp->rcv_wnd) {
937 todrop = ti->ti_len - tp->rcv_wnd;
938 m_adj(m, -todrop);
939 ti->ti_len = tp->rcv_wnd;
940 tiflags &= ~TH_FIN;
941 tcpstat.tcps_rcvpackafterwin++;
942 tcpstat.tcps_rcvbyteafterwin += todrop;
943 }
944 tp->snd_wl1 = ti->ti_seq - 1;
945 tp->rcv_up = ti->ti_seq;
946 /*
947 * Client side of transaction: already sent SYN and data.
948 * If the remote host used T/TCP to validate the SYN,
949 * our data will be ACK'd; if so, enter normal data segment
950 * processing in the middle of step 5, ack processing.
951 * Otherwise, goto step 6.
952 */
953 if (tiflags & TH_ACK)
954 goto process_ACK;
955 goto step6;
956 /*
957 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
958 * if segment contains a SYN and CC [not CC.NEW] option:
959 * if state == TIME_WAIT and connection duration > MSL,
960 * drop packet and send RST;
961 *
962 * if SEG.CC > CCrecv then is new SYN, and can implicitly
963 * ack the FIN (and data) in retransmission queue.
964 * Complete close and delete TCPCB. Then reprocess
965 * segment, hoping to find new TCPCB in LISTEN state;
966 *
967 * else must be old SYN; drop it.
968 * else do normal processing.
969 */
970 case TCPS_LAST_ACK:
971 case TCPS_CLOSING:
972 case TCPS_TIME_WAIT:
973 if ((tiflags & TH_SYN) &&
974 (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
975 if (tp->t_state == TCPS_TIME_WAIT &&
976 tp->t_duration > TCPTV_MSL)
977 goto dropwithreset;
978 if (CC_GT(to.to_cc, tp->cc_recv)) {
979 tp = tcp_close(tp);
980 goto findpcb;
981 }
982 else
983 goto drop;
984 }
985 break; /* continue normal processing */
986 }
987
988 /*
989 * States other than LISTEN or SYN_SENT.
990 * First check the RST flag and sequence number since reset segments
991 * are exempt from the timestamp and connection count tests. This
992 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
993 * below which allowed reset segments in half the sequence space
994 * to fall though and be processed (which gives forged reset
995 * segments with a random sequence number a 50 percent chance of
996 * killing a connection).
997 * Then check timestamp, if present.
998 * Then check the connection count, if present.
999 * Then check that at least some bytes of segment are within
1000 * receive window. If segment begins before rcv_nxt,
1001 * drop leading data (and SYN); if nothing left, just ack.
1002 *
1003 *
1004 * If the RST bit is set, check the sequence number to see
1005 * if this is a valid reset segment.
1006 * RFC 793 page 37:
1007 * In all states except SYN-SENT, all reset (RST) segments
1008 * are validated by checking their SEQ-fields. A reset is
1009 * valid if its sequence number is in the window.
1010 * Note: this does not take into account delayed ACKs, so
1011 * we should test against last_ack_sent instead of rcv_nxt.
1012 * Also, it does not make sense to allow reset segments with
1013 * sequence numbers greater than last_ack_sent to be processed
1014 * since these sequence numbers are just the acknowledgement
1015 * numbers in our outgoing packets being echoed back at us,
1016 * and these acknowledgement numbers are monotonically
1017 * increasing.
1018 * If we have multiple segments in flight, the intial reset
1019 * segment sequence numbers will be to the left of last_ack_sent,
1020 * but they will eventually catch up.
1021 * In any case, it never made sense to trim reset segments to
1022 * fit the receive window since RFC 1122 says:
1023 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1024 *
1025 * A TCP SHOULD allow a received RST segment to include data.
1026 *
1027 * DISCUSSION
1028 * It has been suggested that a RST segment could contain
1029 * ASCII text that encoded and explained the cause of the
1030 * RST. No standard has yet been established for such
1031 * data.
1032 *
1033 * If the reset segment passes the sequence number test examine
1034 * the state:
1035 * SYN_RECEIVED STATE:
1036 * If passive open, return to LISTEN state.
1037 * If active open, inform user that connection was refused.
1038 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1039 * Inform user that connection was reset, and close tcb.
1040 * CLOSING, LAST_ACK, TIME_WAIT STATES
1041 * Close the tcb.
1042 * TIME_WAIT state:
1043 * Drop the segment - see Stevens, vol. 2, p. 964 and
1044 * RFC 1337.
1045 */
1046 if (tiflags & TH_RST) {
1047 if (tp->last_ack_sent == ti->ti_seq) {
1048 switch (tp->t_state) {
1049
1050 case TCPS_SYN_RECEIVED:
1051 so->so_error = ECONNREFUSED;
1052 goto close;
1053
1054 case TCPS_ESTABLISHED:
1055 case TCPS_FIN_WAIT_1:
1056 case TCPS_FIN_WAIT_2:
1057 case TCPS_CLOSE_WAIT:
1058 so->so_error = ECONNRESET;
1059 close:
1060 tp->t_state = TCPS_CLOSED;
1061 tcpstat.tcps_drops++;
1062 tp = tcp_close(tp);
1063 break;
1064
1065 case TCPS_CLOSING:
1066 case TCPS_LAST_ACK:
1067 tp = tcp_close(tp);
1068 break;
1069
1070 case TCPS_TIME_WAIT:
1071 break;
1072 }
1073 }
1074 goto drop;
1075 }
1076
1077 /*
1078 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1079 * and it's less than ts_recent, drop it.
1080 */
1081 if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1082 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1083
1084 /* Check to see if ts_recent is over 24 days old. */
1085 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1086 /*
1087 * Invalidate ts_recent. If this segment updates
1088 * ts_recent, the age will be reset later and ts_recent
1089 * will get a valid value. If it does not, setting
1090 * ts_recent to zero will at least satisfy the
1091 * requirement that zero be placed in the timestamp
1092 * echo reply when ts_recent isn't valid. The
1093 * age isn't reset until we get a valid ts_recent
1094 * because we don't want out-of-order segments to be
1095 * dropped when ts_recent is old.
1096 */
1097 tp->ts_recent = 0;
1098 } else {
1099 tcpstat.tcps_rcvduppack++;
1100 tcpstat.tcps_rcvdupbyte += ti->ti_len;
1101 tcpstat.tcps_pawsdrop++;
1102 goto dropafterack;
1103 }
1104 }
1105
1106 /*
1107 * T/TCP mechanism
1108 * If T/TCP was negotiated and the segment doesn't have CC,
1109 * or if its CC is wrong then drop the segment.
1110 * RST segments do not have to comply with this.
1111 */
1112 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1113 ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1114 goto dropafterack;
1115
1116 /*
1117 * In the SYN-RECEIVED state, validate that the packet belongs to
1118 * this connection before trimming the data to fit the receive
1119 * window. Check the sequence number versus IRS since we know
1120 * the sequence numbers haven't wrapped. This is a partial fix
1121 * for the "LAND" DoS attack.
1122 */
1123 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(ti->ti_seq, tp->irs))
1124 goto dropwithreset;
1125
1126 todrop = tp->rcv_nxt - ti->ti_seq;
1127 if (todrop > 0) {
1128 if (tiflags & TH_SYN) {
1129 tiflags &= ~TH_SYN;
1130 ti->ti_seq++;
1131 if (ti->ti_urp > 1)
1132 ti->ti_urp--;
1133 else
1134 tiflags &= ~TH_URG;
1135 todrop--;
1136 }
1137 /*
1138 * Following if statement from Stevens, vol. 2, p. 960.
1139 */
1140 if (todrop > ti->ti_len
1141 || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
1142 /*
1143 * Any valid FIN must be to the left of the window.
1144 * At this point the FIN must be a duplicate or out
1145 * of sequence; drop it.
1146 */
1147 tiflags &= ~TH_FIN;
1148
1149 /*
1150 * Send an ACK to resynchronize and drop any data.
1151 * But keep on processing for RST or ACK.
1152 */
1153 tp->t_flags |= TF_ACKNOW;
1154 todrop = ti->ti_len;
1155 tcpstat.tcps_rcvduppack++;
1156 tcpstat.tcps_rcvdupbyte += todrop;
1157 } else {
1158 tcpstat.tcps_rcvpartduppack++;
1159 tcpstat.tcps_rcvpartdupbyte += todrop;
1160 }
1161 m_adj(m, todrop);
1162 ti->ti_seq += todrop;
1163 ti->ti_len -= todrop;
1164 if (ti->ti_urp > todrop)
1165 ti->ti_urp -= todrop;
1166 else {
1167 tiflags &= ~TH_URG;
1168 ti->ti_urp = 0;
1169 }
1170 }
1171
1172 /*
1173 * If new data are received on a connection after the
1174 * user processes are gone, then RST the other end.
1175 */
1176 if ((so->so_state & SS_NOFDREF) &&
1177 tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
1178 tp = tcp_close(tp);
1179 tcpstat.tcps_rcvafterclose++;
1180 goto dropwithreset;
1181 }
1182
1183 /*
1184 * If segment ends after window, drop trailing data
1185 * (and PUSH and FIN); if nothing left, just ACK.
1186 */
1187 todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
1188 if (todrop > 0) {
1189 tcpstat.tcps_rcvpackafterwin++;
1190 if (todrop >= ti->ti_len) {
1191 tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
1192 /*
1193 * If a new connection request is received
1194 * while in TIME_WAIT, drop the old connection
1195 * and start over if the sequence numbers
1196 * are above the previous ones.
1197 */
1198 if (tiflags & TH_SYN &&
1199 tp->t_state == TCPS_TIME_WAIT &&
1200 SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1201 iss = tp->snd_nxt + TCP_ISSINCR;
1202 tp = tcp_close(tp);
1203 goto findpcb;
1204 }
1205 /*
1206 * If window is closed can only take segments at
1207 * window edge, and have to drop data and PUSH from
1208 * incoming segments. Continue processing, but
1209 * remember to ack. Otherwise, drop segment
1210 * and ack.
1211 */
1212 if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1213 tp->t_flags |= TF_ACKNOW;
1214 tcpstat.tcps_rcvwinprobe++;
1215 } else
1216 goto dropafterack;
1217 } else
1218 tcpstat.tcps_rcvbyteafterwin += todrop;
1219 m_adj(m, -todrop);
1220 ti->ti_len -= todrop;
1221 tiflags &= ~(TH_PUSH|TH_FIN);
1222 }
1223
1224 /*
1225 * If last ACK falls within this segment's sequence numbers,
1226 * record its timestamp.
1227 * NOTE that the test is modified according to the latest
1228 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1229 */
1230 if ((to.to_flag & TOF_TS) != 0 &&
1231 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
1232 tp->ts_recent_age = tcp_now;
1233 tp->ts_recent = to.to_tsval;
1234 }
1235
1236 /*
1237 * If a SYN is in the window, then this is an
1238 * error and we send an RST and drop the connection.
1239 */
1240 if (tiflags & TH_SYN) {
1241 tp = tcp_drop(tp, ECONNRESET);
1242 goto dropwithreset;
1243 }
1244
1245 /*
1246 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1247 * flag is on (half-synchronized state), then queue data for
1248 * later processing; else drop segment and return.
1249 */
1250 if ((tiflags & TH_ACK) == 0) {
1251 if (tp->t_state == TCPS_SYN_RECEIVED ||
1252 (tp->t_flags & TF_NEEDSYN))
1253 goto step6;
1254 else
1255 goto drop;
1256 }
1257
1258 /*
1259 * Ack processing.
1260 */
1261 switch (tp->t_state) {
1262
1263 /*
1264 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1265 * ESTABLISHED state and continue processing.
1266 * The ACK was checked above.
1267 */
1268 case TCPS_SYN_RECEIVED:
1269
1270 tcpstat.tcps_connects++;
1271 soisconnected(so);
1272 /* Do window scaling? */
1273 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1274 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1275 tp->snd_scale = tp->requested_s_scale;
1276 tp->rcv_scale = tp->request_r_scale;
1277 }
1278 /*
1279 * Upon successful completion of 3-way handshake,
1280 * update cache.CC if it was undefined, pass any queued
1281 * data to the user, and advance state appropriately.
1282 */
1283 if ((taop = tcp_gettaocache(inp)) != NULL &&
1284 taop->tao_cc == 0)
1285 taop->tao_cc = tp->cc_recv;
1286
1287 /*
1288 * Make transitions:
1289 * SYN-RECEIVED -> ESTABLISHED
1290 * SYN-RECEIVED* -> FIN-WAIT-1
1291 */
1292 if (tp->t_flags & TF_NEEDFIN) {
1293 tp->t_state = TCPS_FIN_WAIT_1;
1294 tp->t_flags &= ~TF_NEEDFIN;
1295 } else {
1296 tp->t_state = TCPS_ESTABLISHED;
1297 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1298 }
1299 /*
1300 * If segment contains data or ACK, will call tcp_reass()
1301 * later; if not, do so now to pass queued data to user.
1302 */
1303 if (ti->ti_len == 0 && (tiflags & TH_FIN) == 0)
1304 (void) tcp_reass(tp, (struct tcpiphdr *)0,
1305 (struct mbuf *)0);
1306 tp->snd_wl1 = ti->ti_seq - 1;
1307 /* fall into ... */
1308
1309 /*
1310 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1311 * ACKs. If the ack is in the range
1312 * tp->snd_una < ti->ti_ack <= tp->snd_max
1313 * then advance tp->snd_una to ti->ti_ack and drop
1314 * data from the retransmission queue. If this ACK reflects
1315 * more up to date window information we update our window information.
1316 */
1317 case TCPS_ESTABLISHED:
1318 case TCPS_FIN_WAIT_1:
1319 case TCPS_FIN_WAIT_2:
1320 case TCPS_CLOSE_WAIT:
1321 case TCPS_CLOSING:
1322 case TCPS_LAST_ACK:
1323 case TCPS_TIME_WAIT:
1324
1325 if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1326 if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1327 tcpstat.tcps_rcvdupack++;
1328 /*
1329 * If we have outstanding data (other than
1330 * a window probe), this is a completely
1331 * duplicate ack (ie, window info didn't
1332 * change), the ack is the biggest we've
1333 * seen and we've seen exactly our rexmt
1334 * threshhold of them, assume a packet
1335 * has been dropped and retransmit it.
1336 * Kludge snd_nxt & the congestion
1337 * window so we send only this one
1338 * packet.
1339 *
1340 * We know we're losing at the current
1341 * window size so do congestion avoidance
1342 * (set ssthresh to half the current window
1343 * and pull our congestion window back to
1344 * the new ssthresh).
1345 *
1346 * Dup acks mean that packets have left the
1347 * network (they're now cached at the receiver)
1348 * so bump cwnd by the amount in the receiver
1349 * to keep a constant cwnd packets in the
1350 * network.
1351 */
1352 if (tp->t_timer[TCPT_REXMT] == 0 ||
1353 ti->ti_ack != tp->snd_una)
1354 tp->t_dupacks = 0;
1355 else if (++tp->t_dupacks == tcprexmtthresh) {
1356 tcp_seq onxt = tp->snd_nxt;
1357 u_int win =
1358 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1359 tp->t_maxseg;
1360
1361 if (win < 2)
1362 win = 2;
1363 tp->snd_ssthresh = win * tp->t_maxseg;
1364 tp->t_timer[TCPT_REXMT] = 0;
1365 tp->t_rtt = 0;
1366 tp->snd_nxt = ti->ti_ack;
1367 tp->snd_cwnd = tp->t_maxseg;
1368 (void) tcp_output(tp);
1369 tp->snd_cwnd = tp->snd_ssthresh +
1370 tp->t_maxseg * tp->t_dupacks;
1371 if (SEQ_GT(onxt, tp->snd_nxt))
1372 tp->snd_nxt = onxt;
1373 goto drop;
1374 } else if (tp->t_dupacks > tcprexmtthresh) {
1375 tp->snd_cwnd += tp->t_maxseg;
1376 (void) tcp_output(tp);
1377 goto drop;
1378 }
1379 } else
1380 tp->t_dupacks = 0;
1381 break;
1382 }
1383 /*
1384 * If the congestion window was inflated to account
1385 * for the other side's cached packets, retract it.
1386 */
1387 if (tp->t_dupacks >= tcprexmtthresh &&
1388 tp->snd_cwnd > tp->snd_ssthresh)
1389 tp->snd_cwnd = tp->snd_ssthresh;
1390 tp->t_dupacks = 0;
1391 if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1392 tcpstat.tcps_rcvacktoomuch++;
1393 goto dropafterack;
1394 }
1395 /*
1396 * If we reach this point, ACK is not a duplicate,
1397 * i.e., it ACKs something we sent.
1398 */
1399 if (tp->t_flags & TF_NEEDSYN) {
1400 /*
1401 * T/TCP: Connection was half-synchronized, and our
1402 * SYN has been ACK'd (so connection is now fully
1403 * synchronized). Go to non-starred state,
1404 * increment snd_una for ACK of SYN, and check if
1405 * we can do window scaling.
1406 */
1407 tp->t_flags &= ~TF_NEEDSYN;
1408 tp->snd_una++;
1409 /* Do window scaling? */
1410 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1411 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1412 tp->snd_scale = tp->requested_s_scale;
1413 tp->rcv_scale = tp->request_r_scale;
1414 }
1415 }
1416
1417process_ACK:
1418 acked = ti->ti_ack - tp->snd_una;
1419 tcpstat.tcps_rcvackpack++;
1420 tcpstat.tcps_rcvackbyte += acked;
1421
1422 /*
1423 * If we have a timestamp reply, update smoothed
1424 * round trip time. If no timestamp is present but
1425 * transmit timer is running and timed sequence
1426 * number was acked, update smoothed round trip time.
1427 * Since we now have an rtt measurement, cancel the
1428 * timer backoff (cf., Phil Karn's retransmit alg.).
1429 * Recompute the initial retransmit timer.
1430 */
1431 if (to.to_flag & TOF_TS)
1432 tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1433 else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1434 tcp_xmit_timer(tp,tp->t_rtt);
1435
1436 /*
1437 * If all outstanding data is acked, stop retransmit
1438 * timer and remember to restart (more output or persist).
1439 * If there is more data to be acked, restart retransmit
1440 * timer, using current (possibly backed-off) value.
1441 */
1442 if (ti->ti_ack == tp->snd_max) {
1443 tp->t_timer[TCPT_REXMT] = 0;
1444 needoutput = 1;
1445 } else if (tp->t_timer[TCPT_PERSIST] == 0)
1446 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1447
1448 /*
1449 * If no data (only SYN) was ACK'd,
1450 * skip rest of ACK processing.
1451 */
1452 if (acked == 0)
1453 goto step6;
1454
1455 /*
1456 * When new data is acked, open the congestion window.
1457 * If the window gives us less than ssthresh packets
1458 * in flight, open exponentially (maxseg per packet).
1459 * Otherwise open linearly: maxseg per window
1460 * (maxseg^2 / cwnd per packet).
1461 */
1462 {
1463 register u_int cw = tp->snd_cwnd;
1464 register u_int incr = tp->t_maxseg;
1465
1466 if (cw > tp->snd_ssthresh)
1467 incr = incr * incr / cw;
1468 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1469 }
1470 if (acked > so->so_snd.sb_cc) {
1471 tp->snd_wnd -= so->so_snd.sb_cc;
1472 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1473 ourfinisacked = 1;
1474 } else {
1475 sbdrop(&so->so_snd, acked);
1476 tp->snd_wnd -= acked;
1477 ourfinisacked = 0;
1478 }
1479 sowwakeup(so);
1480 tp->snd_una = ti->ti_ack;
1481 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1482 tp->snd_nxt = tp->snd_una;
1483
1484 switch (tp->t_state) {
1485
1486 /*
1487 * In FIN_WAIT_1 STATE in addition to the processing
1488 * for the ESTABLISHED state if our FIN is now acknowledged
1489 * then enter FIN_WAIT_2.
1490 */
1491 case TCPS_FIN_WAIT_1:
1492 if (ourfinisacked) {
1493 /*
1494 * If we can't receive any more
1495 * data, then closing user can proceed.
1496 * Starting the timer is contrary to the
1497 * specification, but if we don't get a FIN
1498 * we'll hang forever.
1499 */
1500 if (so->so_state & SS_CANTRCVMORE) {
1501 soisdisconnected(so);
1502 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1503 }
1504 tp->t_state = TCPS_FIN_WAIT_2;
1505 }
1506 break;
1507
1508 /*
1509 * In CLOSING STATE in addition to the processing for
1510 * the ESTABLISHED state if the ACK acknowledges our FIN
1511 * then enter the TIME-WAIT state, otherwise ignore
1512 * the segment.
1513 */
1514 case TCPS_CLOSING:
1515 if (ourfinisacked) {
1516 tp->t_state = TCPS_TIME_WAIT;
1517 tcp_canceltimers(tp);
1518 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1519 if (tp->cc_recv != 0 &&
1520 tp->t_duration < TCPTV_MSL)
1521 tp->t_timer[TCPT_2MSL] =
1522 tp->t_rxtcur * TCPTV_TWTRUNC;
1523 else
1524 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1525 soisdisconnected(so);
1526 }
1527 break;
1528
1529 /*
1530 * In LAST_ACK, we may still be waiting for data to drain
1531 * and/or to be acked, as well as for the ack of our FIN.
1532 * If our FIN is now acknowledged, delete the TCB,
1533 * enter the closed state and return.
1534 */
1535 case TCPS_LAST_ACK:
1536 if (ourfinisacked) {
1537 tp = tcp_close(tp);
1538 goto drop;
1539 }
1540 break;
1541
1542 /*
1543 * In TIME_WAIT state the only thing that should arrive
1544 * is a retransmission of the remote FIN. Acknowledge
1545 * it and restart the finack timer.
1546 */
1547 case TCPS_TIME_WAIT:
1548 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1549 goto dropafterack;
1550 }
1551 }
1552
1553step6:
1554 /*
1555 * Update window information.
1556 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1557 */
1558 if ((tiflags & TH_ACK) &&
1559 (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1560 (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1561 (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1562 /* keep track of pure window updates */
1563 if (ti->ti_len == 0 &&
1564 tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1565 tcpstat.tcps_rcvwinupd++;
1566 tp->snd_wnd = tiwin;
1567 tp->snd_wl1 = ti->ti_seq;
1568 tp->snd_wl2 = ti->ti_ack;
1569 if (tp->snd_wnd > tp->max_sndwnd)
1570 tp->max_sndwnd = tp->snd_wnd;
1571 needoutput = 1;
1572 }
1573
1574 /*
1575 * Process segments with URG.
1576 */
1577 if ((tiflags & TH_URG) && ti->ti_urp &&
1578 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1579 /*
1580 * This is a kludge, but if we receive and accept
1581 * random urgent pointers, we'll crash in
1582 * soreceive. It's hard to imagine someone
1583 * actually wanting to send this much urgent data.
1584 */
1585 if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1586 ti->ti_urp = 0; /* XXX */
1587 tiflags &= ~TH_URG; /* XXX */
1588 goto dodata; /* XXX */
1589 }
1590 /*
1591 * If this segment advances the known urgent pointer,
1592 * then mark the data stream. This should not happen
1593 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1594 * a FIN has been received from the remote side.
1595 * In these states we ignore the URG.
1596 *
1597 * According to RFC961 (Assigned Protocols),
1598 * the urgent pointer points to the last octet
1599 * of urgent data. We continue, however,
1600 * to consider it to indicate the first octet
1601 * of data past the urgent section as the original
1602 * spec states (in one of two places).
1603 */
1604 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1605 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1606 so->so_oobmark = so->so_rcv.sb_cc +
1607 (tp->rcv_up - tp->rcv_nxt) - 1;
1608 if (so->so_oobmark == 0)
1609 so->so_state |= SS_RCVATMARK;
1610 sohasoutofband(so);
1611 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1612 }
1613 /*
1614 * Remove out of band data so doesn't get presented to user.
1615 * This can happen independent of advancing the URG pointer,
1616 * but if two URG's are pending at once, some out-of-band
1617 * data may creep in... ick.
1618 */
1619 if (ti->ti_urp <= (u_long)ti->ti_len
1620#ifdef SO_OOBINLINE
1621 && (so->so_options & SO_OOBINLINE) == 0
1622#endif
1623 )
1624 tcp_pulloutofband(so, ti, m);
1625 } else
1626 /*
1627 * If no out of band data is expected,
1628 * pull receive urgent pointer along
1629 * with the receive window.
1630 */
1631 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1632 tp->rcv_up = tp->rcv_nxt;
1633dodata: /* XXX */
1634
1635 /*
1636 * Process the segment text, merging it into the TCP sequencing queue,
1637 * and arranging for acknowledgment of receipt if necessary.
1638 * This process logically involves adjusting tp->rcv_wnd as data
1639 * is presented to the user (this happens in tcp_usrreq.c,
1640 * case PRU_RCVD). If a FIN has already been received on this
1641 * connection then we just ignore the text.
1642 */
1643 if ((ti->ti_len || (tiflags&TH_FIN)) &&
1644 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1645 TCP_REASS(tp, ti, m, so, tiflags);
1646 /*
1647 * Note the amount of data that peer has sent into
1648 * our window, in order to estimate the sender's
1649 * buffer size.
1650 */
1651 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1652 } else {
1653 m_freem(m);
1654 tiflags &= ~TH_FIN;
1655 }
1656
1657 /*
1658 * If FIN is received ACK the FIN and let the user know
1659 * that the connection is closing.
1660 */
1661 if (tiflags & TH_FIN) {
1662 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1663 socantrcvmore(so);
1664 /*
1665 * If connection is half-synchronized
1666 * (ie NEEDSYN flag on) then delay ACK,
1667 * so it may be piggybacked when SYN is sent.
1668 * Otherwise, since we received a FIN then no
1669 * more input can be expected, send ACK now.
1670 */
1671 if (tcp_delack_enabled && (tp->t_flags & TF_NEEDSYN))
1672 tp->t_flags |= TF_DELACK;
1673 else
1674 tp->t_flags |= TF_ACKNOW;
1675 tp->rcv_nxt++;
1676 }
1677 switch (tp->t_state) {
1678
1679 /*
1680 * In SYN_RECEIVED and ESTABLISHED STATES
1681 * enter the CLOSE_WAIT state.
1682 */
1683 case TCPS_SYN_RECEIVED:
1684 case TCPS_ESTABLISHED:
1685 tp->t_state = TCPS_CLOSE_WAIT;
1686 break;
1687
1688 /*
1689 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1690 * enter the CLOSING state.
1691 */
1692 case TCPS_FIN_WAIT_1:
1693 tp->t_state = TCPS_CLOSING;
1694 break;
1695
1696 /*
1697 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1698 * starting the time-wait timer, turning off the other
1699 * standard timers.
1700 */
1701 case TCPS_FIN_WAIT_2:
1702 tp->t_state = TCPS_TIME_WAIT;
1703 tcp_canceltimers(tp);
1704 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1705 if (tp->cc_recv != 0 &&
1706 tp->t_duration < TCPTV_MSL) {
1707 tp->t_timer[TCPT_2MSL] =
1708 tp->t_rxtcur * TCPTV_TWTRUNC;
1709 /* For transaction client, force ACK now. */
1710 tp->t_flags |= TF_ACKNOW;
1711 }
1712 else
1713 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1714 soisdisconnected(so);
1715 break;
1716
1717 /*
1718 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1719 */
1720 case TCPS_TIME_WAIT:
1721 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1722 break;
1723 }
1724 }
1725#ifdef TCPDEBUG
1726 if (so->so_options & SO_DEBUG)
1727 tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1728#endif
1729
1730 /*
1731 * Return any desired output.
1732 */
1733 if (needoutput || (tp->t_flags & TF_ACKNOW))
1734 (void) tcp_output(tp);
1735 return;
1736
1737dropafterack:
1738 /*
1739 * Generate an ACK dropping incoming segment if it occupies
1740 * sequence space, where the ACK reflects our state.
1741 *
1742 * We can now skip the test for the RST flag since all
1743 * paths to this code happen after packets containing
1744 * RST have been dropped.
1745 *
1746 * In the SYN-RECEIVED state, don't send an ACK unless the
1747 * segment we received passes the SYN-RECEIVED ACK test.
1748 * If it fails send a RST. This breaks the loop in the
1749 * "LAND" DoS attack, and also prevents an ACK storm
1750 * between two listening ports that have been sent forged
1751 * SYN segments, each with the source address of the other.
1752 */
1753 if (tp->t_state == TCPS_SYN_RECEIVED && (tiflags & TH_ACK) &&
1754 (SEQ_GT(tp->snd_una, ti->ti_ack) ||
1755 SEQ_GT(ti->ti_ack, tp->snd_max)) )
1756 goto dropwithreset;
1757#ifdef TCPDEBUG
1758 if (so->so_options & SO_DEBUG)
1759 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1760#endif
1761 m_freem(m);
1762 tp->t_flags |= TF_ACKNOW;
1763 (void) tcp_output(tp);
1764 return;
1765
1766dropwithreset:
1767 /*
1768 * Generate a RST, dropping incoming segment.
1769 * Make ACK acceptable to originator of segment.
1770 * Don't bother to respond if destination was broadcast/multicast.
1771 */
1772 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1773 IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1774 goto drop;
1775#ifdef TCPDEBUG
1776 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1777 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1778#endif
1779 if (tiflags & TH_ACK)
1780 tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1781 else {
1782 if (tiflags & TH_SYN)
1783 ti->ti_len++;
1784 tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1785 TH_RST|TH_ACK);
1786 }
1787 /* destroy temporarily created socket */
1788 if (dropsocket)
1789 (void) soabort(so);
1790 return;
1791
1792drop:
1793 /*
1794 * Drop space held by incoming segment and return.
1795 */
1796#ifdef TCPDEBUG
1797 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1798 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1799#endif
1800 m_freem(m);
1801 /* destroy temporarily created socket */
1802 if (dropsocket)
1803 (void) soabort(so);
1804 return;
1805}
1806
1807static void
1808tcp_dooptions(tp, cp, cnt, ti, to)
1809 struct tcpcb *tp;
1810 u_char *cp;
1811 int cnt;
1812 struct tcpiphdr *ti;
1813 struct tcpopt *to;
1814{
1815 u_short mss = 0;
1816 int opt, optlen;
1817
1818 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1819 opt = cp[0];
1820 if (opt == TCPOPT_EOL)
1821 break;
1822 if (opt == TCPOPT_NOP)
1823 optlen = 1;
1824 else {
1825 optlen = cp[1];
1826 if (optlen <= 0)
1827 break;
1828 }
1829 switch (opt) {
1830
1831 default:
1832 continue;
1833
1834 case TCPOPT_MAXSEG:
1835 if (optlen != TCPOLEN_MAXSEG)
1836 continue;
1837 if (!(ti->ti_flags & TH_SYN))
1838 continue;
1839 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1840 NTOHS(mss);
1841 break;
1842
1843 case TCPOPT_WINDOW:
1844 if (optlen != TCPOLEN_WINDOW)
1845 continue;
1846 if (!(ti->ti_flags & TH_SYN))
1847 continue;
1848 tp->t_flags |= TF_RCVD_SCALE;
1849 tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1850 break;
1851
1852 case TCPOPT_TIMESTAMP:
1853 if (optlen != TCPOLEN_TIMESTAMP)
1854 continue;
1855 to->to_flag |= TOF_TS;
1856 bcopy((char *)cp + 2,
1857 (char *)&to->to_tsval, sizeof(to->to_tsval));
1858 NTOHL(to->to_tsval);
1859 bcopy((char *)cp + 6,
1860 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
1861 NTOHL(to->to_tsecr);
1862
1863 /*
1864 * A timestamp received in a SYN makes
1865 * it ok to send timestamp requests and replies.
1866 */
1867 if (ti->ti_flags & TH_SYN) {
1868 tp->t_flags |= TF_RCVD_TSTMP;
1869 tp->ts_recent = to->to_tsval;
1870 tp->ts_recent_age = tcp_now;
1871 }
1872 break;
1873 case TCPOPT_CC:
1874 if (optlen != TCPOLEN_CC)
1875 continue;
1876 to->to_flag |= TOF_CC;
1877 bcopy((char *)cp + 2,
1878 (char *)&to->to_cc, sizeof(to->to_cc));
1879 NTOHL(to->to_cc);
1880 /*
1881 * A CC or CC.new option received in a SYN makes
1882 * it ok to send CC in subsequent segments.
1883 */
1884 if (ti->ti_flags & TH_SYN)
1885 tp->t_flags |= TF_RCVD_CC;
1886 break;
1887 case TCPOPT_CCNEW:
1888 if (optlen != TCPOLEN_CC)
1889 continue;
1890 if (!(ti->ti_flags & TH_SYN))
1891 continue;
1892 to->to_flag |= TOF_CCNEW;
1893 bcopy((char *)cp + 2,
1894 (char *)&to->to_cc, sizeof(to->to_cc));
1895 NTOHL(to->to_cc);
1896 /*
1897 * A CC or CC.new option received in a SYN makes
1898 * it ok to send CC in subsequent segments.
1899 */
1900 tp->t_flags |= TF_RCVD_CC;
1901 break;
1902 case TCPOPT_CCECHO:
1903 if (optlen != TCPOLEN_CC)
1904 continue;
1905 if (!(ti->ti_flags & TH_SYN))
1906 continue;
1907 to->to_flag |= TOF_CCECHO;
1908 bcopy((char *)cp + 2,
1909 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
1910 NTOHL(to->to_ccecho);
1911 break;
1912 }
1913 }
1914 if (ti->ti_flags & TH_SYN)
1915 tcp_mss(tp, mss); /* sets t_maxseg */
1916}
1917
1918/*
1919 * Pull out of band byte out of a segment so
1920 * it doesn't appear in the user's data queue.
1921 * It is still reflected in the segment length for
1922 * sequencing purposes.
1923 */
1924static void
1925tcp_pulloutofband(so, ti, m)
1926 struct socket *so;
1927 struct tcpiphdr *ti;
1928 register struct mbuf *m;
1929{
1930 int cnt = ti->ti_urp - 1;
1931
1932 while (cnt >= 0) {
1933 if (m->m_len > cnt) {
1934 char *cp = mtod(m, caddr_t) + cnt;
1935 struct tcpcb *tp = sototcpcb(so);
1936
1937 tp->t_iobc = *cp;
1938 tp->t_oobflags |= TCPOOB_HAVEDATA;
1939 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1940 m->m_len--;
1941 return;
1942 }
1943 cnt -= m->m_len;
1944 m = m->m_next;
1945 if (m == 0)
1946 break;
1947 }
1948 panic("tcp_pulloutofband");
1949}
1950
1951/*
1952 * Collect new round-trip time estimate
1953 * and update averages and current timeout.
1954 */
1955static void
1956tcp_xmit_timer(tp, rtt)
1957 register struct tcpcb *tp;
1958 short rtt;
1959{
1960 register int delta;
1961
1962 tcpstat.tcps_rttupdated++;
1963 tp->t_rttupdated++;
1964 if (tp->t_srtt != 0) {
1965 /*
1966 * srtt is stored as fixed point with 5 bits after the
1967 * binary point (i.e., scaled by 8). The following magic
1968 * is equivalent to the smoothing algorithm in rfc793 with
1969 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1970 * point). Adjust rtt to origin 0.
1971 */
1972 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
1973 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
1974
1975 if ((tp->t_srtt += delta) <= 0)
1976 tp->t_srtt = 1;
1977
1978 /*
1979 * We accumulate a smoothed rtt variance (actually, a
1980 * smoothed mean difference), then set the retransmit
1981 * timer to smoothed rtt + 4 times the smoothed variance.
1982 * rttvar is stored as fixed point with 4 bits after the
1983 * binary point (scaled by 16). The following is
1984 * equivalent to rfc793 smoothing with an alpha of .75
1985 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1986 * rfc793's wired-in beta.
1987 */
1988 if (delta < 0)
1989 delta = -delta;
1990 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
1991 if ((tp->t_rttvar += delta) <= 0)
1992 tp->t_rttvar = 1;
1993 } else {
1994 /*
1995 * No rtt measurement yet - use the unsmoothed rtt.
1996 * Set the variance to half the rtt (so our first
1997 * retransmit happens at 3*rtt).
1998 */
1999 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2000 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2001 }
2002 tp->t_rtt = 0;
2003 tp->t_rxtshift = 0;
2004
2005 /*
2006 * the retransmit should happen at rtt + 4 * rttvar.
2007 * Because of the way we do the smoothing, srtt and rttvar
2008 * will each average +1/2 tick of bias. When we compute
2009 * the retransmit timer, we want 1/2 tick of rounding and
2010 * 1 extra tick because of +-1/2 tick uncertainty in the
2011 * firing of the timer. The bias will give us exactly the
2012 * 1.5 tick we need. But, because the bias is
2013 * statistical, we have to test that we don't drop below
2014 * the minimum feasible timer (which is 2 ticks).
2015 */
2016 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2017 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2018
2019 /*
2020 * We received an ack for a packet that wasn't retransmitted;
2021 * it is probably safe to discard any error indications we've
2022 * received recently. This isn't quite right, but close enough
2023 * for now (a route might have failed after we sent a segment,
2024 * and the return path might not be symmetrical).
2025 */
2026 tp->t_softerror = 0;
2027}
2028
2029/*
2030 * Determine a reasonable value for maxseg size.
2031 * If the route is known, check route for mtu.
2032 * If none, use an mss that can be handled on the outgoing
2033 * interface without forcing IP to fragment; if bigger than
2034 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2035 * to utilize large mbufs. If no route is found, route has no mtu,
2036 * or the destination isn't local, use a default, hopefully conservative
2037 * size (usually 512 or the default IP max size, but no more than the mtu
2038 * of the interface), as we can't discover anything about intervening
2039 * gateways or networks. We also initialize the congestion/slow start
2040 * window to be a single segment if the destination isn't local.
2041 * While looking at the routing entry, we also initialize other path-dependent
2042 * parameters from pre-set or cached values in the routing entry.
2043 *
2044 * Also take into account the space needed for options that we
2045 * send regularly. Make maxseg shorter by that amount to assure
2046 * that we can send maxseg amount of data even when the options
2047 * are present. Store the upper limit of the length of options plus
2048 * data in maxopd.
2049 *
2050 * NOTE that this routine is only called when we process an incoming
2051 * segment, for outgoing segments only tcp_mssopt is called.
2052 *
2053 * In case of T/TCP, we call this routine during implicit connection
2054 * setup as well (offer = -1), to initialize maxseg from the cached
2055 * MSS of our peer.
2056 */
2057void
2058tcp_mss(tp, offer)
2059 struct tcpcb *tp;
2060 int offer;
2061{
2062 register struct rtentry *rt;
2063 struct ifnet *ifp;
2064 register int rtt, mss;
2065 u_long bufsize;
2066 struct inpcb *inp;
2067 struct socket *so;
2068 struct rmxp_tao *taop;
2069 int origoffer = offer;
2070
2071 inp = tp->t_inpcb;
2072 if ((rt = tcp_rtlookup(inp)) == NULL) {
2073 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2074 return;
2075 }
2076 ifp = rt->rt_ifp;
2077 so = inp->inp_socket;
2078
2079 taop = rmx_taop(rt->rt_rmx);
2080 /*
2081 * Offer == -1 means that we didn't receive SYN yet,
2082 * use cached value in that case;
2083 */
2084 if (offer == -1)
2085 offer = taop->tao_mssopt;
2086 /*
2087 * Offer == 0 means that there was no MSS on the SYN segment,
2088 * in this case we use tcp_mssdflt.
2089 */
2090 if (offer == 0)
2091 offer = tcp_mssdflt;
2092 else
2093 /*
2094 * Sanity check: make sure that maxopd will be large
2095 * enough to allow some data on segments even is the
2096 * all the option space is used (40bytes). Otherwise
2097 * funny things may happen in tcp_output.
2098 */
2099 offer = max(offer, 64);
2100 taop->tao_mssopt = offer;
2101
2102 /*
2103 * While we're here, check if there's an initial rtt
2104 * or rttvar. Convert from the route-table units
2105 * to scaled multiples of the slow timeout timer.
2106 */
2107 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2108 /*
2109 * XXX the lock bit for RTT indicates that the value
2110 * is also a minimum value; this is subject to time.
2111 */
2112 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2113 tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2114 tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2115 tcpstat.tcps_usedrtt++;
2116 if (rt->rt_rmx.rmx_rttvar) {
2117 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2118 (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2119 tcpstat.tcps_usedrttvar++;
2120 } else {
2121 /* default variation is +- 1 rtt */
2122 tp->t_rttvar =
2123 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2124 }
2125 TCPT_RANGESET(tp->t_rxtcur,
2126 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2127 tp->t_rttmin, TCPTV_REXMTMAX);
2128 }
2129 /*
2130 * if there's an mtu associated with the route, use it
2131 */
2132 if (rt->rt_rmx.rmx_mtu)
2133 mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
2134 else
2135 {
2136 mss = ifp->if_mtu - sizeof(struct tcpiphdr);
2137 if (!in_localaddr(inp->inp_faddr))
2138 mss = min(mss, tcp_mssdflt);
2139 }
2140 mss = min(mss, offer);
2141 /*
2142 * maxopd stores the maximum length of data AND options
2143 * in a segment; maxseg is the amount of data in a normal
2144 * segment. We need to store this value (maxopd) apart
2145 * from maxseg, because now every segment carries options
2146 * and thus we normally have somewhat less data in segments.
2147 */
2148 tp->t_maxopd = mss;
2149
2150 /*
2151 * In case of T/TCP, origoffer==-1 indicates, that no segments
2152 * were received yet. In this case we just guess, otherwise
2153 * we do the same as before T/TCP.
2154 */
2155 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2156 (origoffer == -1 ||
2157 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2158 mss -= TCPOLEN_TSTAMP_APPA;
2159 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2160 (origoffer == -1 ||
2161 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2162 mss -= TCPOLEN_CC_APPA;
2163
2164#if (MCLBYTES & (MCLBYTES - 1)) == 0
2165 if (mss > MCLBYTES)
2166 mss &= ~(MCLBYTES-1);
2167#else
2168 if (mss > MCLBYTES)
2169 mss = mss / MCLBYTES * MCLBYTES;
2170#endif
2171 /*
2172 * If there's a pipesize, change the socket buffer
2173 * to that size. Make the socket buffers an integral
2174 * number of mss units; if the mss is larger than
2175 * the socket buffer, decrease the mss.
2176 */
2177#ifdef RTV_SPIPE
2178 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2179#endif
2180 bufsize = so->so_snd.sb_hiwat;
2181 if (bufsize < mss)
2182 mss = bufsize;
2183 else {
2184 bufsize = roundup(bufsize, mss);
2185 if (bufsize > sb_max)
2186 bufsize = sb_max;
2187 (void)sbreserve(&so->so_snd, bufsize);
2188 }
2189 tp->t_maxseg = mss;
2190
2191#ifdef RTV_RPIPE
2192 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2193#endif
2194 bufsize = so->so_rcv.sb_hiwat;
2195 if (bufsize > mss) {
2196 bufsize = roundup(bufsize, mss);
2197 if (bufsize > sb_max)
2198 bufsize = sb_max;
2199 (void)sbreserve(&so->so_rcv, bufsize);
2200 }
2201 /*
2202 * Don't force slow-start on local network.
2203 */
2204 if (!in_localaddr(inp->inp_faddr))
2205 tp->snd_cwnd = mss;
2206
2207 if (rt->rt_rmx.rmx_ssthresh) {
2208 /*
2209 * There's some sort of gateway or interface
2210 * buffer limit on the path. Use this to set
2211 * the slow start threshhold, but set the
2212 * threshold to no less than 2*mss.
2213 */
2214 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2215 tcpstat.tcps_usedssthresh++;
2216 }
2217}
2218
2219/*
2220 * Determine the MSS option to send on an outgoing SYN.
2221 */
2222int
2223tcp_mssopt(tp)
2224 struct tcpcb *tp;
2225{
2226 struct rtentry *rt;
2227
2228 rt = tcp_rtlookup(tp->t_inpcb);
2229 if (rt == NULL)
2230 return tcp_mssdflt;
2231
2232 return rt->rt_ifp->if_mtu - sizeof(struct tcpiphdr);
2233}
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 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * @(#)tcp_input.c 8.12 (Berkeley) 5/24/95
34 * $Id: tcp_input.c,v 1.85 1999/05/03 23:57:30 billf Exp $
35 */
36
37#include "opt_ipfw.h" /* for ipfw_fwd */
38#include "opt_tcpdebug.h"
39
40#include <sys/param.h>
41#include <sys/systm.h>
42#include <sys/kernel.h>
43#include <sys/sysctl.h>
44#include <sys/malloc.h>
45#include <sys/mbuf.h>
46#include <sys/proc.h> /* for proc0 declaration */
47#include <sys/protosw.h>
48#include <sys/socket.h>
49#include <sys/socketvar.h>
50#include <sys/syslog.h>
51
52#include <machine/cpu.h> /* before tcp_seq.h, for tcp_random18() */
53
54#include <net/if.h>
55#include <net/route.h>
56
57#include <netinet/in.h>
58#include <netinet/in_systm.h>
59#include <netinet/ip.h>
60#include <netinet/ip_icmp.h> /* for ICMP_BANDLIM */
61#include <netinet/in_pcb.h>
62#include <netinet/ip_var.h>
63#include <netinet/icmp_var.h> /* for ICMP_BANDLIM */
64#include <netinet/tcp.h>
65#include <netinet/tcp_fsm.h>
66#include <netinet/tcp_seq.h>
67#include <netinet/tcp_timer.h>
68#include <netinet/tcp_var.h>
69#include <netinet/tcpip.h>
70#ifdef TCPDEBUG
71#include <netinet/tcp_debug.h>
72static struct tcpiphdr tcp_saveti;
73#endif
74
75static int tcprexmtthresh = 3;
76tcp_seq tcp_iss;
77tcp_cc tcp_ccgen;
78
79struct tcpstat tcpstat;
80SYSCTL_STRUCT(_net_inet_tcp, TCPCTL_STATS, stats, CTLFLAG_RD,
81 &tcpstat , tcpstat, "TCP statistics (struct tcpstat, netinet/tcp_var.h)");
82
83static int log_in_vain = 0;
84SYSCTL_INT(_net_inet_tcp, OID_AUTO, log_in_vain, CTLFLAG_RW,
85 &log_in_vain, 0, "Log all incoming TCP connections");
86
87int tcp_delack_enabled = 1;
88SYSCTL_INT(_net_inet_tcp, OID_AUTO, delayed_ack, CTLFLAG_RW,
89 &tcp_delack_enabled, 0,
90 "Delay ACK to try and piggyback it onto a data packet");
91
92u_long tcp_now;
93struct inpcbhead tcb;
94struct inpcbinfo tcbinfo;
95
96static void tcp_dooptions __P((struct tcpcb *,
97 u_char *, int, struct tcpiphdr *, struct tcpopt *));
98static void tcp_pulloutofband __P((struct socket *,
99 struct tcpiphdr *, struct mbuf *));
100static int tcp_reass __P((struct tcpcb *, struct tcpiphdr *, struct mbuf *));
101static void tcp_xmit_timer __P((struct tcpcb *, int));
102
103
104/*
105 * Insert segment ti into reassembly queue of tcp with
106 * control block tp. Return TH_FIN if reassembly now includes
107 * a segment with FIN. The macro form does the common case inline
108 * (segment is the next to be received on an established connection,
109 * and the queue is empty), avoiding linkage into and removal
110 * from the queue and repetition of various conversions.
111 * Set DELACK for segments received in order, but ack immediately
112 * when segments are out of order (so fast retransmit can work).
113 */
114#define TCP_REASS(tp, ti, m, so, flags) { \
115 if ((ti)->ti_seq == (tp)->rcv_nxt && \
116 (tp)->t_segq == NULL && \
117 (tp)->t_state == TCPS_ESTABLISHED) { \
118 if (tcp_delack_enabled) \
119 tp->t_flags |= TF_DELACK; \
120 else \
121 tp->t_flags |= TF_ACKNOW; \
122 (tp)->rcv_nxt += (ti)->ti_len; \
123 flags = (ti)->ti_flags & TH_FIN; \
124 tcpstat.tcps_rcvpack++;\
125 tcpstat.tcps_rcvbyte += (ti)->ti_len;\
126 sbappend(&(so)->so_rcv, (m)); \
127 sorwakeup(so); \
128 } else { \
129 (flags) = tcp_reass((tp), (ti), (m)); \
130 tp->t_flags |= TF_ACKNOW; \
131 } \
132}
133
134static int
135tcp_reass(tp, ti, m)
136 register struct tcpcb *tp;
137 register struct tcpiphdr *ti;
138 struct mbuf *m;
139{
140 struct mbuf *q;
141 struct mbuf *p;
142 struct mbuf *nq;
143 struct socket *so = tp->t_inpcb->inp_socket;
144 int flags;
145
146#define GETTCP(m) ((struct tcpiphdr *)m->m_pkthdr.header)
147
148 /*
149 * Call with ti==0 after become established to
150 * force pre-ESTABLISHED data up to user socket.
151 */
152 if (ti == 0)
153 goto present;
154
155 m->m_pkthdr.header = ti;
156
157 /*
158 * Find a segment which begins after this one does.
159 */
160 for (q = tp->t_segq, p = NULL; q; p = q, q = q->m_nextpkt)
161 if (SEQ_GT(GETTCP(q)->ti_seq, ti->ti_seq))
162 break;
163
164 /*
165 * If there is a preceding segment, it may provide some of
166 * our data already. If so, drop the data from the incoming
167 * segment. If it provides all of our data, drop us.
168 */
169 if (p != NULL) {
170 register int i;
171 /* conversion to int (in i) handles seq wraparound */
172 i = GETTCP(p)->ti_seq + GETTCP(p)->ti_len - ti->ti_seq;
173 if (i > 0) {
174 if (i >= ti->ti_len) {
175 tcpstat.tcps_rcvduppack++;
176 tcpstat.tcps_rcvdupbyte += ti->ti_len;
177 m_freem(m);
178 /*
179 * Try to present any queued data
180 * at the left window edge to the user.
181 * This is needed after the 3-WHS
182 * completes.
183 */
184 goto present; /* ??? */
185 }
186 m_adj(m, i);
187 ti->ti_len -= i;
188 ti->ti_seq += i;
189 }
190 }
191 tcpstat.tcps_rcvoopack++;
192 tcpstat.tcps_rcvoobyte += ti->ti_len;
193
194 /*
195 * While we overlap succeeding segments trim them or,
196 * if they are completely covered, dequeue them.
197 */
198 while (q) {
199 register int i = (ti->ti_seq + ti->ti_len) - GETTCP(q)->ti_seq;
200 if (i <= 0)
201 break;
202 if (i < GETTCP(q)->ti_len) {
203 GETTCP(q)->ti_seq += i;
204 GETTCP(q)->ti_len -= i;
205 m_adj(q, i);
206 break;
207 }
208
209 nq = q->m_nextpkt;
210 if (p)
211 p->m_nextpkt = nq;
212 else
213 tp->t_segq = nq;
214 m_freem(q);
215 q = nq;
216 }
217
218 if (p == NULL) {
219 m->m_nextpkt = tp->t_segq;
220 tp->t_segq = m;
221 } else {
222 m->m_nextpkt = p->m_nextpkt;
223 p->m_nextpkt = m;
224 }
225
226present:
227 /*
228 * Present data to user, advancing rcv_nxt through
229 * completed sequence space.
230 */
231 if (!TCPS_HAVEESTABLISHED(tp->t_state))
232 return (0);
233 q = tp->t_segq;
234 if (!q || GETTCP(q)->ti_seq != tp->rcv_nxt)
235 return (0);
236 do {
237 tp->rcv_nxt += GETTCP(q)->ti_len;
238 flags = GETTCP(q)->ti_flags & TH_FIN;
239 nq = q->m_nextpkt;
240 tp->t_segq = nq;
241 q->m_nextpkt = NULL;
242 if (so->so_state & SS_CANTRCVMORE)
243 m_freem(q);
244 else
245 sbappend(&so->so_rcv, q);
246 q = nq;
247 } while (q && GETTCP(q)->ti_seq == tp->rcv_nxt);
248 sorwakeup(so);
249 return (flags);
250
251#undef GETTCP
252}
253
254/*
255 * TCP input routine, follows pages 65-76 of the
256 * protocol specification dated September, 1981 very closely.
257 */
258void
259tcp_input(m, iphlen)
260 register struct mbuf *m;
261 int iphlen;
262{
263 register struct tcpiphdr *ti;
264 register struct inpcb *inp;
265 u_char *optp = NULL;
266 int optlen = 0;
267 int len, tlen, off;
268 register struct tcpcb *tp = 0;
269 register int tiflags;
270 struct socket *so = 0;
271 int todrop, acked, ourfinisacked, needoutput = 0;
272 struct in_addr laddr;
273 int dropsocket = 0;
274 int iss = 0;
275 u_long tiwin;
276 struct tcpopt to; /* options in this segment */
277 struct rmxp_tao *taop; /* pointer to our TAO cache entry */
278 struct rmxp_tao tao_noncached; /* in case there's no cached entry */
279#ifdef TCPDEBUG
280 short ostate = 0;
281#endif
282
283 bzero((char *)&to, sizeof(to));
284
285 tcpstat.tcps_rcvtotal++;
286 /*
287 * Get IP and TCP header together in first mbuf.
288 * Note: IP leaves IP header in first mbuf.
289 */
290 ti = mtod(m, struct tcpiphdr *);
291 if (iphlen > sizeof (struct ip))
292 ip_stripoptions(m, (struct mbuf *)0);
293 if (m->m_len < sizeof (struct tcpiphdr)) {
294 if ((m = m_pullup(m, sizeof (struct tcpiphdr))) == 0) {
295 tcpstat.tcps_rcvshort++;
296 return;
297 }
298 ti = mtod(m, struct tcpiphdr *);
299 }
300
301 /*
302 * Checksum extended TCP header and data.
303 */
304 tlen = ((struct ip *)ti)->ip_len;
305 len = sizeof (struct ip) + tlen;
306 bzero(ti->ti_x1, sizeof(ti->ti_x1));
307 ti->ti_len = (u_short)tlen;
308 HTONS(ti->ti_len);
309 ti->ti_sum = in_cksum(m, len);
310 if (ti->ti_sum) {
311 tcpstat.tcps_rcvbadsum++;
312 goto drop;
313 }
314
315 /*
316 * Check that TCP offset makes sense,
317 * pull out TCP options and adjust length. XXX
318 */
319 off = ti->ti_off << 2;
320 if (off < sizeof (struct tcphdr) || off > tlen) {
321 tcpstat.tcps_rcvbadoff++;
322 goto drop;
323 }
324 tlen -= off;
325 ti->ti_len = tlen;
326 if (off > sizeof (struct tcphdr)) {
327 if (m->m_len < sizeof(struct ip) + off) {
328 if ((m = m_pullup(m, sizeof (struct ip) + off)) == 0) {
329 tcpstat.tcps_rcvshort++;
330 return;
331 }
332 ti = mtod(m, struct tcpiphdr *);
333 }
334 optlen = off - sizeof (struct tcphdr);
335 optp = mtod(m, u_char *) + sizeof (struct tcpiphdr);
336 }
337 tiflags = ti->ti_flags;
338
339 /*
340 * Convert TCP protocol specific fields to host format.
341 */
342 NTOHL(ti->ti_seq);
343 NTOHL(ti->ti_ack);
344 NTOHS(ti->ti_win);
345 NTOHS(ti->ti_urp);
346
347 /*
348 * Drop TCP, IP headers and TCP options.
349 */
350 m->m_data += sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
351 m->m_len -= sizeof(struct tcpiphdr)+off-sizeof(struct tcphdr);
352
353 /*
354 * Locate pcb for segment.
355 */
356findpcb:
357#ifdef IPFIREWALL_FORWARD
358 if (ip_fw_fwd_addr != NULL) {
359 /*
360 * Diverted. Pretend to be the destination.
361 * already got one like this?
362 */
363 inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
364 ti->ti_dst, ti->ti_dport, 0);
365 if (!inp) {
366 /*
367 * No, then it's new. Try find the ambushing socket
368 */
369 if (!ip_fw_fwd_addr->sin_port) {
370 inp = in_pcblookup_hash(&tcbinfo, ti->ti_src,
371 ti->ti_sport, ip_fw_fwd_addr->sin_addr,
372 ti->ti_dport, 1);
373 } else {
374 inp = in_pcblookup_hash(&tcbinfo,
375 ti->ti_src, ti->ti_sport,
376 ip_fw_fwd_addr->sin_addr,
377 ntohs(ip_fw_fwd_addr->sin_port), 1);
378 }
379 }
380 ip_fw_fwd_addr = NULL;
381 } else
382#endif /* IPFIREWALL_FORWARD */
383
384 inp = in_pcblookup_hash(&tcbinfo, ti->ti_src, ti->ti_sport,
385 ti->ti_dst, ti->ti_dport, 1);
386
387 /*
388 * If the state is CLOSED (i.e., TCB does not exist) then
389 * all data in the incoming segment is discarded.
390 * If the TCB exists but is in CLOSED state, it is embryonic,
391 * but should either do a listen or a connect soon.
392 */
393 if (inp == NULL) {
394 if (log_in_vain && tiflags & TH_SYN) {
395 char buf[4*sizeof "123"];
396
397 strcpy(buf, inet_ntoa(ti->ti_dst));
398 log(LOG_INFO,
399 "Connection attempt to TCP %s:%d from %s:%d\n",
400 buf, ntohs(ti->ti_dport), inet_ntoa(ti->ti_src),
401 ntohs(ti->ti_sport));
402 }
403#ifdef ICMP_BANDLIM
404 if (badport_bandlim(1) < 0)
405 goto drop;
406#endif
407 goto dropwithreset;
408 }
409 tp = intotcpcb(inp);
410 if (tp == 0)
411 goto dropwithreset;
412 if (tp->t_state == TCPS_CLOSED)
413 goto drop;
414
415 /* Unscale the window into a 32-bit value. */
416 if ((tiflags & TH_SYN) == 0)
417 tiwin = ti->ti_win << tp->snd_scale;
418 else
419 tiwin = ti->ti_win;
420
421 so = inp->inp_socket;
422 if (so->so_options & (SO_DEBUG|SO_ACCEPTCONN)) {
423#ifdef TCPDEBUG
424 if (so->so_options & SO_DEBUG) {
425 ostate = tp->t_state;
426 tcp_saveti = *ti;
427 }
428#endif
429 if (so->so_options & SO_ACCEPTCONN) {
430 register struct tcpcb *tp0 = tp;
431 struct socket *so2;
432 if ((tiflags & (TH_RST|TH_ACK|TH_SYN)) != TH_SYN) {
433 /*
434 * Note: dropwithreset makes sure we don't
435 * send a RST in response to a RST.
436 */
437 if (tiflags & TH_ACK) {
438 tcpstat.tcps_badsyn++;
439 goto dropwithreset;
440 }
441 goto drop;
442 }
443 so2 = sonewconn(so, 0);
444 if (so2 == 0) {
445 tcpstat.tcps_listendrop++;
446 so2 = sodropablereq(so);
447 if (so2) {
448 tcp_drop(sototcpcb(so2), ETIMEDOUT);
449 so2 = sonewconn(so, 0);
450 }
451 if (!so2)
452 goto drop;
453 }
454 so = so2;
455 /*
456 * This is ugly, but ....
457 *
458 * Mark socket as temporary until we're
459 * committed to keeping it. The code at
460 * ``drop'' and ``dropwithreset'' check the
461 * flag dropsocket to see if the temporary
462 * socket created here should be discarded.
463 * We mark the socket as discardable until
464 * we're committed to it below in TCPS_LISTEN.
465 */
466 dropsocket++;
467 inp = (struct inpcb *)so->so_pcb;
468 inp->inp_laddr = ti->ti_dst;
469 inp->inp_lport = ti->ti_dport;
470 if (in_pcbinshash(inp) != 0) {
471 /*
472 * Undo the assignments above if we failed to put
473 * the PCB on the hash lists.
474 */
475 inp->inp_laddr.s_addr = INADDR_ANY;
476 inp->inp_lport = 0;
477 goto drop;
478 }
479 inp->inp_options = ip_srcroute();
480 tp = intotcpcb(inp);
481 tp->t_state = TCPS_LISTEN;
482 tp->t_flags |= tp0->t_flags & (TF_NOPUSH|TF_NOOPT);
483
484 /* Compute proper scaling value from buffer space */
485 while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
486 TCP_MAXWIN << tp->request_r_scale < so->so_rcv.sb_hiwat)
487 tp->request_r_scale++;
488 }
489 }
490
491 /*
492 * Segment received on connection.
493 * Reset idle time and keep-alive timer.
494 */
495 tp->t_idle = 0;
496 if (TCPS_HAVEESTABLISHED(tp->t_state))
497 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
498
499 /*
500 * Process options if not in LISTEN state,
501 * else do it below (after getting remote address).
502 */
503 if (tp->t_state != TCPS_LISTEN)
504 tcp_dooptions(tp, optp, optlen, ti, &to);
505
506 /*
507 * Header prediction: check for the two common cases
508 * of a uni-directional data xfer. If the packet has
509 * no control flags, is in-sequence, the window didn't
510 * change and we're not retransmitting, it's a
511 * candidate. If the length is zero and the ack moved
512 * forward, we're the sender side of the xfer. Just
513 * free the data acked & wake any higher level process
514 * that was blocked waiting for space. If the length
515 * is non-zero and the ack didn't move, we're the
516 * receiver side. If we're getting packets in-order
517 * (the reassembly queue is empty), add the data to
518 * the socket buffer and note that we need a delayed ack.
519 * Make sure that the hidden state-flags are also off.
520 * Since we check for TCPS_ESTABLISHED above, it can only
521 * be TH_NEEDSYN.
522 */
523 if (tp->t_state == TCPS_ESTABLISHED &&
524 (tiflags & (TH_SYN|TH_FIN|TH_RST|TH_URG|TH_ACK)) == TH_ACK &&
525 ((tp->t_flags & (TF_NEEDSYN|TF_NEEDFIN)) == 0) &&
526 ((to.to_flag & TOF_TS) == 0 ||
527 TSTMP_GEQ(to.to_tsval, tp->ts_recent)) &&
528 /*
529 * Using the CC option is compulsory if once started:
530 * the segment is OK if no T/TCP was negotiated or
531 * if the segment has a CC option equal to CCrecv
532 */
533 ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) != (TF_REQ_CC|TF_RCVD_CC) ||
534 ((to.to_flag & TOF_CC) != 0 && to.to_cc == tp->cc_recv)) &&
535 ti->ti_seq == tp->rcv_nxt &&
536 tiwin && tiwin == tp->snd_wnd &&
537 tp->snd_nxt == tp->snd_max) {
538
539 /*
540 * If last ACK falls within this segment's sequence numbers,
541 * record the timestamp.
542 * NOTE that the test is modified according to the latest
543 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
544 */
545 if ((to.to_flag & TOF_TS) != 0 &&
546 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
547 tp->ts_recent_age = tcp_now;
548 tp->ts_recent = to.to_tsval;
549 }
550
551 if (ti->ti_len == 0) {
552 if (SEQ_GT(ti->ti_ack, tp->snd_una) &&
553 SEQ_LEQ(ti->ti_ack, tp->snd_max) &&
554 tp->snd_cwnd >= tp->snd_wnd &&
555 tp->t_dupacks < tcprexmtthresh) {
556 /*
557 * this is a pure ack for outstanding data.
558 */
559 ++tcpstat.tcps_predack;
560 if ((to.to_flag & TOF_TS) != 0)
561 tcp_xmit_timer(tp,
562 tcp_now - to.to_tsecr + 1);
563 else if (tp->t_rtt &&
564 SEQ_GT(ti->ti_ack, tp->t_rtseq))
565 tcp_xmit_timer(tp, tp->t_rtt);
566 acked = ti->ti_ack - tp->snd_una;
567 tcpstat.tcps_rcvackpack++;
568 tcpstat.tcps_rcvackbyte += acked;
569 sbdrop(&so->so_snd, acked);
570 tp->snd_una = ti->ti_ack;
571 m_freem(m);
572
573 /*
574 * If all outstanding data are acked, stop
575 * retransmit timer, otherwise restart timer
576 * using current (possibly backed-off) value.
577 * If process is waiting for space,
578 * wakeup/selwakeup/signal. If data
579 * are ready to send, let tcp_output
580 * decide between more output or persist.
581 */
582 if (tp->snd_una == tp->snd_max)
583 tp->t_timer[TCPT_REXMT] = 0;
584 else if (tp->t_timer[TCPT_PERSIST] == 0)
585 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
586
587 sowwakeup(so);
588 if (so->so_snd.sb_cc)
589 (void) tcp_output(tp);
590 return;
591 }
592 } else if (ti->ti_ack == tp->snd_una &&
593 tp->t_segq == NULL &&
594 ti->ti_len <= sbspace(&so->so_rcv)) {
595 /*
596 * this is a pure, in-sequence data packet
597 * with nothing on the reassembly queue and
598 * we have enough buffer space to take it.
599 */
600 ++tcpstat.tcps_preddat;
601 tp->rcv_nxt += ti->ti_len;
602 tcpstat.tcps_rcvpack++;
603 tcpstat.tcps_rcvbyte += ti->ti_len;
604 /*
605 * Add data to socket buffer.
606 */
607 sbappend(&so->so_rcv, m);
608 sorwakeup(so);
609 if (tcp_delack_enabled) {
610 tp->t_flags |= TF_DELACK;
611 } else {
612 tp->t_flags |= TF_ACKNOW;
613 tcp_output(tp);
614 }
615 return;
616 }
617 }
618
619 /*
620 * Calculate amount of space in receive window,
621 * and then do TCP input processing.
622 * Receive window is amount of space in rcv queue,
623 * but not less than advertised window.
624 */
625 { int win;
626
627 win = sbspace(&so->so_rcv);
628 if (win < 0)
629 win = 0;
630 tp->rcv_wnd = imax(win, (int)(tp->rcv_adv - tp->rcv_nxt));
631 }
632
633 switch (tp->t_state) {
634
635 /*
636 * If the state is LISTEN then ignore segment if it contains an RST.
637 * If the segment contains an ACK then it is bad and send a RST.
638 * If it does not contain a SYN then it is not interesting; drop it.
639 * If it is from this socket, drop it, it must be forged.
640 * Don't bother responding if the destination was a broadcast.
641 * Otherwise initialize tp->rcv_nxt, and tp->irs, select an initial
642 * tp->iss, and send a segment:
643 * <SEQ=ISS><ACK=RCV_NXT><CTL=SYN,ACK>
644 * Also initialize tp->snd_nxt to tp->iss+1 and tp->snd_una to tp->iss.
645 * Fill in remote peer address fields if not previously specified.
646 * Enter SYN_RECEIVED state, and process any other fields of this
647 * segment in this state.
648 */
649 case TCPS_LISTEN: {
650 register struct sockaddr_in *sin;
651
652 if (tiflags & TH_RST)
653 goto drop;
654 if (tiflags & TH_ACK)
655 goto dropwithreset;
656 if ((tiflags & TH_SYN) == 0)
657 goto drop;
658 if ((ti->ti_dport == ti->ti_sport) &&
659 (ti->ti_dst.s_addr == ti->ti_src.s_addr))
660 goto drop;
661 /*
662 * RFC1122 4.2.3.10, p. 104: discard bcast/mcast SYN
663 * in_broadcast() should never return true on a received
664 * packet with M_BCAST not set.
665 */
666 if (m->m_flags & (M_BCAST|M_MCAST) ||
667 IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
668 goto drop;
669 MALLOC(sin, struct sockaddr_in *, sizeof *sin, M_SONAME,
670 M_NOWAIT);
671 if (sin == NULL)
672 goto drop;
673 sin->sin_family = AF_INET;
674 sin->sin_len = sizeof(*sin);
675 sin->sin_addr = ti->ti_src;
676 sin->sin_port = ti->ti_sport;
677 bzero((caddr_t)sin->sin_zero, sizeof(sin->sin_zero));
678 laddr = inp->inp_laddr;
679 if (inp->inp_laddr.s_addr == INADDR_ANY)
680 inp->inp_laddr = ti->ti_dst;
681 if (in_pcbconnect(inp, (struct sockaddr *)sin, &proc0)) {
682 inp->inp_laddr = laddr;
683 FREE(sin, M_SONAME);
684 goto drop;
685 }
686 FREE(sin, M_SONAME);
687 tp->t_template = tcp_template(tp);
688 if (tp->t_template == 0) {
689 tp = tcp_drop(tp, ENOBUFS);
690 dropsocket = 0; /* socket is already gone */
691 goto drop;
692 }
693 if ((taop = tcp_gettaocache(inp)) == NULL) {
694 taop = &tao_noncached;
695 bzero(taop, sizeof(*taop));
696 }
697 tcp_dooptions(tp, optp, optlen, ti, &to);
698 if (iss)
699 tp->iss = iss;
700 else
701 tp->iss = tcp_iss;
702 tcp_iss += TCP_ISSINCR/4;
703 tp->irs = ti->ti_seq;
704 tcp_sendseqinit(tp);
705 tcp_rcvseqinit(tp);
706 /*
707 * Initialization of the tcpcb for transaction;
708 * set SND.WND = SEG.WND,
709 * initialize CCsend and CCrecv.
710 */
711 tp->snd_wnd = tiwin; /* initial send-window */
712 tp->cc_send = CC_INC(tcp_ccgen);
713 tp->cc_recv = to.to_cc;
714 /*
715 * Perform TAO test on incoming CC (SEG.CC) option, if any.
716 * - compare SEG.CC against cached CC from the same host,
717 * if any.
718 * - if SEG.CC > chached value, SYN must be new and is accepted
719 * immediately: save new CC in the cache, mark the socket
720 * connected, enter ESTABLISHED state, turn on flag to
721 * send a SYN in the next segment.
722 * A virtual advertised window is set in rcv_adv to
723 * initialize SWS prevention. Then enter normal segment
724 * processing: drop SYN, process data and FIN.
725 * - otherwise do a normal 3-way handshake.
726 */
727 if ((to.to_flag & TOF_CC) != 0) {
728 if (((tp->t_flags & TF_NOPUSH) != 0) &&
729 taop->tao_cc != 0 && CC_GT(to.to_cc, taop->tao_cc)) {
730
731 taop->tao_cc = to.to_cc;
732 tp->t_state = TCPS_ESTABLISHED;
733
734 /*
735 * If there is a FIN, or if there is data and the
736 * connection is local, then delay SYN,ACK(SYN) in
737 * the hope of piggy-backing it on a response
738 * segment. Otherwise must send ACK now in case
739 * the other side is slow starting.
740 */
741 if (tcp_delack_enabled && ((tiflags & TH_FIN) || (ti->ti_len != 0 &&
742 in_localaddr(inp->inp_faddr))))
743 tp->t_flags |= (TF_DELACK | TF_NEEDSYN);
744 else
745 tp->t_flags |= (TF_ACKNOW | TF_NEEDSYN);
746
747 /*
748 * Limit the `virtual advertised window' to TCP_MAXWIN
749 * here. Even if we requested window scaling, it will
750 * become effective only later when our SYN is acked.
751 */
752 tp->rcv_adv += min(tp->rcv_wnd, TCP_MAXWIN);
753 tcpstat.tcps_connects++;
754 soisconnected(so);
755 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
756 dropsocket = 0; /* committed to socket */
757 tcpstat.tcps_accepts++;
758 goto trimthenstep6;
759 }
760 /* else do standard 3-way handshake */
761 } else {
762 /*
763 * No CC option, but maybe CC.NEW:
764 * invalidate cached value.
765 */
766 taop->tao_cc = 0;
767 }
768 /*
769 * TAO test failed or there was no CC option,
770 * do a standard 3-way handshake.
771 */
772 tp->t_flags |= TF_ACKNOW;
773 tp->t_state = TCPS_SYN_RECEIVED;
774 tp->t_timer[TCPT_KEEP] = tcp_keepinit;
775 dropsocket = 0; /* committed to socket */
776 tcpstat.tcps_accepts++;
777 goto trimthenstep6;
778 }
779
780 /*
781 * If the state is SYN_RECEIVED:
782 * if seg contains an ACK, but not for our SYN/ACK, send a RST.
783 */
784 case TCPS_SYN_RECEIVED:
785 if ((tiflags & TH_ACK) &&
786 (SEQ_LEQ(ti->ti_ack, tp->snd_una) ||
787 SEQ_GT(ti->ti_ack, tp->snd_max)))
788 goto dropwithreset;
789 break;
790
791 /*
792 * If the state is SYN_SENT:
793 * if seg contains an ACK, but not for our SYN, drop the input.
794 * if seg contains a RST, then drop the connection.
795 * if seg does not contain SYN, then drop it.
796 * Otherwise this is an acceptable SYN segment
797 * initialize tp->rcv_nxt and tp->irs
798 * if seg contains ack then advance tp->snd_una
799 * if SYN has been acked change to ESTABLISHED else SYN_RCVD state
800 * arrange for segment to be acked (eventually)
801 * continue processing rest of data/controls, beginning with URG
802 */
803 case TCPS_SYN_SENT:
804 if ((taop = tcp_gettaocache(inp)) == NULL) {
805 taop = &tao_noncached;
806 bzero(taop, sizeof(*taop));
807 }
808
809 if ((tiflags & TH_ACK) &&
810 (SEQ_LEQ(ti->ti_ack, tp->iss) ||
811 SEQ_GT(ti->ti_ack, tp->snd_max))) {
812 /*
813 * If we have a cached CCsent for the remote host,
814 * hence we haven't just crashed and restarted,
815 * do not send a RST. This may be a retransmission
816 * from the other side after our earlier ACK was lost.
817 * Our new SYN, when it arrives, will serve as the
818 * needed ACK.
819 */
820 if (taop->tao_ccsent != 0)
821 goto drop;
822 else
823 goto dropwithreset;
824 }
825 if (tiflags & TH_RST) {
826 if (tiflags & TH_ACK)
827 tp = tcp_drop(tp, ECONNREFUSED);
828 goto drop;
829 }
830 if ((tiflags & TH_SYN) == 0)
831 goto drop;
832 tp->snd_wnd = ti->ti_win; /* initial send window */
833 tp->cc_recv = to.to_cc; /* foreign CC */
834
835 tp->irs = ti->ti_seq;
836 tcp_rcvseqinit(tp);
837 if (tiflags & TH_ACK) {
838 /*
839 * Our SYN was acked. If segment contains CC.ECHO
840 * option, check it to make sure this segment really
841 * matches our SYN. If not, just drop it as old
842 * duplicate, but send an RST if we're still playing
843 * by the old rules. If no CC.ECHO option, make sure
844 * we don't get fooled into using T/TCP.
845 */
846 if (to.to_flag & TOF_CCECHO) {
847 if (tp->cc_send != to.to_ccecho) {
848 if (taop->tao_ccsent != 0)
849 goto drop;
850 else
851 goto dropwithreset;
852 }
853 } else
854 tp->t_flags &= ~TF_RCVD_CC;
855 tcpstat.tcps_connects++;
856 soisconnected(so);
857 /* Do window scaling on this connection? */
858 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
859 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
860 tp->snd_scale = tp->requested_s_scale;
861 tp->rcv_scale = tp->request_r_scale;
862 }
863 /* Segment is acceptable, update cache if undefined. */
864 if (taop->tao_ccsent == 0)
865 taop->tao_ccsent = to.to_ccecho;
866
867 tp->rcv_adv += tp->rcv_wnd;
868 tp->snd_una++; /* SYN is acked */
869 /*
870 * If there's data, delay ACK; if there's also a FIN
871 * ACKNOW will be turned on later.
872 */
873 if (tcp_delack_enabled && ti->ti_len != 0)
874 tp->t_flags |= TF_DELACK;
875 else
876 tp->t_flags |= TF_ACKNOW;
877 /*
878 * Received <SYN,ACK> in SYN_SENT[*] state.
879 * Transitions:
880 * SYN_SENT --> ESTABLISHED
881 * SYN_SENT* --> FIN_WAIT_1
882 */
883 if (tp->t_flags & TF_NEEDFIN) {
884 tp->t_state = TCPS_FIN_WAIT_1;
885 tp->t_flags &= ~TF_NEEDFIN;
886 tiflags &= ~TH_SYN;
887 } else {
888 tp->t_state = TCPS_ESTABLISHED;
889 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
890 }
891 } else {
892 /*
893 * Received initial SYN in SYN-SENT[*] state => simul-
894 * taneous open. If segment contains CC option and there is
895 * a cached CC, apply TAO test; if it succeeds, connection is
896 * half-synchronized. Otherwise, do 3-way handshake:
897 * SYN-SENT -> SYN-RECEIVED
898 * SYN-SENT* -> SYN-RECEIVED*
899 * If there was no CC option, clear cached CC value.
900 */
901 tp->t_flags |= TF_ACKNOW;
902 tp->t_timer[TCPT_REXMT] = 0;
903 if (to.to_flag & TOF_CC) {
904 if (taop->tao_cc != 0 &&
905 CC_GT(to.to_cc, taop->tao_cc)) {
906 /*
907 * update cache and make transition:
908 * SYN-SENT -> ESTABLISHED*
909 * SYN-SENT* -> FIN-WAIT-1*
910 */
911 taop->tao_cc = to.to_cc;
912 if (tp->t_flags & TF_NEEDFIN) {
913 tp->t_state = TCPS_FIN_WAIT_1;
914 tp->t_flags &= ~TF_NEEDFIN;
915 } else {
916 tp->t_state = TCPS_ESTABLISHED;
917 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
918 }
919 tp->t_flags |= TF_NEEDSYN;
920 } else
921 tp->t_state = TCPS_SYN_RECEIVED;
922 } else {
923 /* CC.NEW or no option => invalidate cache */
924 taop->tao_cc = 0;
925 tp->t_state = TCPS_SYN_RECEIVED;
926 }
927 }
928
929trimthenstep6:
930 /*
931 * Advance ti->ti_seq to correspond to first data byte.
932 * If data, trim to stay within window,
933 * dropping FIN if necessary.
934 */
935 ti->ti_seq++;
936 if (ti->ti_len > tp->rcv_wnd) {
937 todrop = ti->ti_len - tp->rcv_wnd;
938 m_adj(m, -todrop);
939 ti->ti_len = tp->rcv_wnd;
940 tiflags &= ~TH_FIN;
941 tcpstat.tcps_rcvpackafterwin++;
942 tcpstat.tcps_rcvbyteafterwin += todrop;
943 }
944 tp->snd_wl1 = ti->ti_seq - 1;
945 tp->rcv_up = ti->ti_seq;
946 /*
947 * Client side of transaction: already sent SYN and data.
948 * If the remote host used T/TCP to validate the SYN,
949 * our data will be ACK'd; if so, enter normal data segment
950 * processing in the middle of step 5, ack processing.
951 * Otherwise, goto step 6.
952 */
953 if (tiflags & TH_ACK)
954 goto process_ACK;
955 goto step6;
956 /*
957 * If the state is LAST_ACK or CLOSING or TIME_WAIT:
958 * if segment contains a SYN and CC [not CC.NEW] option:
959 * if state == TIME_WAIT and connection duration > MSL,
960 * drop packet and send RST;
961 *
962 * if SEG.CC > CCrecv then is new SYN, and can implicitly
963 * ack the FIN (and data) in retransmission queue.
964 * Complete close and delete TCPCB. Then reprocess
965 * segment, hoping to find new TCPCB in LISTEN state;
966 *
967 * else must be old SYN; drop it.
968 * else do normal processing.
969 */
970 case TCPS_LAST_ACK:
971 case TCPS_CLOSING:
972 case TCPS_TIME_WAIT:
973 if ((tiflags & TH_SYN) &&
974 (to.to_flag & TOF_CC) && tp->cc_recv != 0) {
975 if (tp->t_state == TCPS_TIME_WAIT &&
976 tp->t_duration > TCPTV_MSL)
977 goto dropwithreset;
978 if (CC_GT(to.to_cc, tp->cc_recv)) {
979 tp = tcp_close(tp);
980 goto findpcb;
981 }
982 else
983 goto drop;
984 }
985 break; /* continue normal processing */
986 }
987
988 /*
989 * States other than LISTEN or SYN_SENT.
990 * First check the RST flag and sequence number since reset segments
991 * are exempt from the timestamp and connection count tests. This
992 * fixes a bug introduced by the Stevens, vol. 2, p. 960 bugfix
993 * below which allowed reset segments in half the sequence space
994 * to fall though and be processed (which gives forged reset
995 * segments with a random sequence number a 50 percent chance of
996 * killing a connection).
997 * Then check timestamp, if present.
998 * Then check the connection count, if present.
999 * Then check that at least some bytes of segment are within
1000 * receive window. If segment begins before rcv_nxt,
1001 * drop leading data (and SYN); if nothing left, just ack.
1002 *
1003 *
1004 * If the RST bit is set, check the sequence number to see
1005 * if this is a valid reset segment.
1006 * RFC 793 page 37:
1007 * In all states except SYN-SENT, all reset (RST) segments
1008 * are validated by checking their SEQ-fields. A reset is
1009 * valid if its sequence number is in the window.
1010 * Note: this does not take into account delayed ACKs, so
1011 * we should test against last_ack_sent instead of rcv_nxt.
1012 * Also, it does not make sense to allow reset segments with
1013 * sequence numbers greater than last_ack_sent to be processed
1014 * since these sequence numbers are just the acknowledgement
1015 * numbers in our outgoing packets being echoed back at us,
1016 * and these acknowledgement numbers are monotonically
1017 * increasing.
1018 * If we have multiple segments in flight, the intial reset
1019 * segment sequence numbers will be to the left of last_ack_sent,
1020 * but they will eventually catch up.
1021 * In any case, it never made sense to trim reset segments to
1022 * fit the receive window since RFC 1122 says:
1023 * 4.2.2.12 RST Segment: RFC-793 Section 3.4
1024 *
1025 * A TCP SHOULD allow a received RST segment to include data.
1026 *
1027 * DISCUSSION
1028 * It has been suggested that a RST segment could contain
1029 * ASCII text that encoded and explained the cause of the
1030 * RST. No standard has yet been established for such
1031 * data.
1032 *
1033 * If the reset segment passes the sequence number test examine
1034 * the state:
1035 * SYN_RECEIVED STATE:
1036 * If passive open, return to LISTEN state.
1037 * If active open, inform user that connection was refused.
1038 * ESTABLISHED, FIN_WAIT_1, FIN_WAIT2, CLOSE_WAIT STATES:
1039 * Inform user that connection was reset, and close tcb.
1040 * CLOSING, LAST_ACK, TIME_WAIT STATES
1041 * Close the tcb.
1042 * TIME_WAIT state:
1043 * Drop the segment - see Stevens, vol. 2, p. 964 and
1044 * RFC 1337.
1045 */
1046 if (tiflags & TH_RST) {
1047 if (tp->last_ack_sent == ti->ti_seq) {
1048 switch (tp->t_state) {
1049
1050 case TCPS_SYN_RECEIVED:
1051 so->so_error = ECONNREFUSED;
1052 goto close;
1053
1054 case TCPS_ESTABLISHED:
1055 case TCPS_FIN_WAIT_1:
1056 case TCPS_FIN_WAIT_2:
1057 case TCPS_CLOSE_WAIT:
1058 so->so_error = ECONNRESET;
1059 close:
1060 tp->t_state = TCPS_CLOSED;
1061 tcpstat.tcps_drops++;
1062 tp = tcp_close(tp);
1063 break;
1064
1065 case TCPS_CLOSING:
1066 case TCPS_LAST_ACK:
1067 tp = tcp_close(tp);
1068 break;
1069
1070 case TCPS_TIME_WAIT:
1071 break;
1072 }
1073 }
1074 goto drop;
1075 }
1076
1077 /*
1078 * RFC 1323 PAWS: If we have a timestamp reply on this segment
1079 * and it's less than ts_recent, drop it.
1080 */
1081 if ((to.to_flag & TOF_TS) != 0 && tp->ts_recent &&
1082 TSTMP_LT(to.to_tsval, tp->ts_recent)) {
1083
1084 /* Check to see if ts_recent is over 24 days old. */
1085 if ((int)(tcp_now - tp->ts_recent_age) > TCP_PAWS_IDLE) {
1086 /*
1087 * Invalidate ts_recent. If this segment updates
1088 * ts_recent, the age will be reset later and ts_recent
1089 * will get a valid value. If it does not, setting
1090 * ts_recent to zero will at least satisfy the
1091 * requirement that zero be placed in the timestamp
1092 * echo reply when ts_recent isn't valid. The
1093 * age isn't reset until we get a valid ts_recent
1094 * because we don't want out-of-order segments to be
1095 * dropped when ts_recent is old.
1096 */
1097 tp->ts_recent = 0;
1098 } else {
1099 tcpstat.tcps_rcvduppack++;
1100 tcpstat.tcps_rcvdupbyte += ti->ti_len;
1101 tcpstat.tcps_pawsdrop++;
1102 goto dropafterack;
1103 }
1104 }
1105
1106 /*
1107 * T/TCP mechanism
1108 * If T/TCP was negotiated and the segment doesn't have CC,
1109 * or if its CC is wrong then drop the segment.
1110 * RST segments do not have to comply with this.
1111 */
1112 if ((tp->t_flags & (TF_REQ_CC|TF_RCVD_CC)) == (TF_REQ_CC|TF_RCVD_CC) &&
1113 ((to.to_flag & TOF_CC) == 0 || tp->cc_recv != to.to_cc))
1114 goto dropafterack;
1115
1116 /*
1117 * In the SYN-RECEIVED state, validate that the packet belongs to
1118 * this connection before trimming the data to fit the receive
1119 * window. Check the sequence number versus IRS since we know
1120 * the sequence numbers haven't wrapped. This is a partial fix
1121 * for the "LAND" DoS attack.
1122 */
1123 if (tp->t_state == TCPS_SYN_RECEIVED && SEQ_LT(ti->ti_seq, tp->irs))
1124 goto dropwithreset;
1125
1126 todrop = tp->rcv_nxt - ti->ti_seq;
1127 if (todrop > 0) {
1128 if (tiflags & TH_SYN) {
1129 tiflags &= ~TH_SYN;
1130 ti->ti_seq++;
1131 if (ti->ti_urp > 1)
1132 ti->ti_urp--;
1133 else
1134 tiflags &= ~TH_URG;
1135 todrop--;
1136 }
1137 /*
1138 * Following if statement from Stevens, vol. 2, p. 960.
1139 */
1140 if (todrop > ti->ti_len
1141 || (todrop == ti->ti_len && (tiflags & TH_FIN) == 0)) {
1142 /*
1143 * Any valid FIN must be to the left of the window.
1144 * At this point the FIN must be a duplicate or out
1145 * of sequence; drop it.
1146 */
1147 tiflags &= ~TH_FIN;
1148
1149 /*
1150 * Send an ACK to resynchronize and drop any data.
1151 * But keep on processing for RST or ACK.
1152 */
1153 tp->t_flags |= TF_ACKNOW;
1154 todrop = ti->ti_len;
1155 tcpstat.tcps_rcvduppack++;
1156 tcpstat.tcps_rcvdupbyte += todrop;
1157 } else {
1158 tcpstat.tcps_rcvpartduppack++;
1159 tcpstat.tcps_rcvpartdupbyte += todrop;
1160 }
1161 m_adj(m, todrop);
1162 ti->ti_seq += todrop;
1163 ti->ti_len -= todrop;
1164 if (ti->ti_urp > todrop)
1165 ti->ti_urp -= todrop;
1166 else {
1167 tiflags &= ~TH_URG;
1168 ti->ti_urp = 0;
1169 }
1170 }
1171
1172 /*
1173 * If new data are received on a connection after the
1174 * user processes are gone, then RST the other end.
1175 */
1176 if ((so->so_state & SS_NOFDREF) &&
1177 tp->t_state > TCPS_CLOSE_WAIT && ti->ti_len) {
1178 tp = tcp_close(tp);
1179 tcpstat.tcps_rcvafterclose++;
1180 goto dropwithreset;
1181 }
1182
1183 /*
1184 * If segment ends after window, drop trailing data
1185 * (and PUSH and FIN); if nothing left, just ACK.
1186 */
1187 todrop = (ti->ti_seq+ti->ti_len) - (tp->rcv_nxt+tp->rcv_wnd);
1188 if (todrop > 0) {
1189 tcpstat.tcps_rcvpackafterwin++;
1190 if (todrop >= ti->ti_len) {
1191 tcpstat.tcps_rcvbyteafterwin += ti->ti_len;
1192 /*
1193 * If a new connection request is received
1194 * while in TIME_WAIT, drop the old connection
1195 * and start over if the sequence numbers
1196 * are above the previous ones.
1197 */
1198 if (tiflags & TH_SYN &&
1199 tp->t_state == TCPS_TIME_WAIT &&
1200 SEQ_GT(ti->ti_seq, tp->rcv_nxt)) {
1201 iss = tp->snd_nxt + TCP_ISSINCR;
1202 tp = tcp_close(tp);
1203 goto findpcb;
1204 }
1205 /*
1206 * If window is closed can only take segments at
1207 * window edge, and have to drop data and PUSH from
1208 * incoming segments. Continue processing, but
1209 * remember to ack. Otherwise, drop segment
1210 * and ack.
1211 */
1212 if (tp->rcv_wnd == 0 && ti->ti_seq == tp->rcv_nxt) {
1213 tp->t_flags |= TF_ACKNOW;
1214 tcpstat.tcps_rcvwinprobe++;
1215 } else
1216 goto dropafterack;
1217 } else
1218 tcpstat.tcps_rcvbyteafterwin += todrop;
1219 m_adj(m, -todrop);
1220 ti->ti_len -= todrop;
1221 tiflags &= ~(TH_PUSH|TH_FIN);
1222 }
1223
1224 /*
1225 * If last ACK falls within this segment's sequence numbers,
1226 * record its timestamp.
1227 * NOTE that the test is modified according to the latest
1228 * proposal of the tcplw@cray.com list (Braden 1993/04/26).
1229 */
1230 if ((to.to_flag & TOF_TS) != 0 &&
1231 SEQ_LEQ(ti->ti_seq, tp->last_ack_sent)) {
1232 tp->ts_recent_age = tcp_now;
1233 tp->ts_recent = to.to_tsval;
1234 }
1235
1236 /*
1237 * If a SYN is in the window, then this is an
1238 * error and we send an RST and drop the connection.
1239 */
1240 if (tiflags & TH_SYN) {
1241 tp = tcp_drop(tp, ECONNRESET);
1242 goto dropwithreset;
1243 }
1244
1245 /*
1246 * If the ACK bit is off: if in SYN-RECEIVED state or SENDSYN
1247 * flag is on (half-synchronized state), then queue data for
1248 * later processing; else drop segment and return.
1249 */
1250 if ((tiflags & TH_ACK) == 0) {
1251 if (tp->t_state == TCPS_SYN_RECEIVED ||
1252 (tp->t_flags & TF_NEEDSYN))
1253 goto step6;
1254 else
1255 goto drop;
1256 }
1257
1258 /*
1259 * Ack processing.
1260 */
1261 switch (tp->t_state) {
1262
1263 /*
1264 * In SYN_RECEIVED state, the ack ACKs our SYN, so enter
1265 * ESTABLISHED state and continue processing.
1266 * The ACK was checked above.
1267 */
1268 case TCPS_SYN_RECEIVED:
1269
1270 tcpstat.tcps_connects++;
1271 soisconnected(so);
1272 /* Do window scaling? */
1273 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1274 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1275 tp->snd_scale = tp->requested_s_scale;
1276 tp->rcv_scale = tp->request_r_scale;
1277 }
1278 /*
1279 * Upon successful completion of 3-way handshake,
1280 * update cache.CC if it was undefined, pass any queued
1281 * data to the user, and advance state appropriately.
1282 */
1283 if ((taop = tcp_gettaocache(inp)) != NULL &&
1284 taop->tao_cc == 0)
1285 taop->tao_cc = tp->cc_recv;
1286
1287 /*
1288 * Make transitions:
1289 * SYN-RECEIVED -> ESTABLISHED
1290 * SYN-RECEIVED* -> FIN-WAIT-1
1291 */
1292 if (tp->t_flags & TF_NEEDFIN) {
1293 tp->t_state = TCPS_FIN_WAIT_1;
1294 tp->t_flags &= ~TF_NEEDFIN;
1295 } else {
1296 tp->t_state = TCPS_ESTABLISHED;
1297 tp->t_timer[TCPT_KEEP] = tcp_keepidle;
1298 }
1299 /*
1300 * If segment contains data or ACK, will call tcp_reass()
1301 * later; if not, do so now to pass queued data to user.
1302 */
1303 if (ti->ti_len == 0 && (tiflags & TH_FIN) == 0)
1304 (void) tcp_reass(tp, (struct tcpiphdr *)0,
1305 (struct mbuf *)0);
1306 tp->snd_wl1 = ti->ti_seq - 1;
1307 /* fall into ... */
1308
1309 /*
1310 * In ESTABLISHED state: drop duplicate ACKs; ACK out of range
1311 * ACKs. If the ack is in the range
1312 * tp->snd_una < ti->ti_ack <= tp->snd_max
1313 * then advance tp->snd_una to ti->ti_ack and drop
1314 * data from the retransmission queue. If this ACK reflects
1315 * more up to date window information we update our window information.
1316 */
1317 case TCPS_ESTABLISHED:
1318 case TCPS_FIN_WAIT_1:
1319 case TCPS_FIN_WAIT_2:
1320 case TCPS_CLOSE_WAIT:
1321 case TCPS_CLOSING:
1322 case TCPS_LAST_ACK:
1323 case TCPS_TIME_WAIT:
1324
1325 if (SEQ_LEQ(ti->ti_ack, tp->snd_una)) {
1326 if (ti->ti_len == 0 && tiwin == tp->snd_wnd) {
1327 tcpstat.tcps_rcvdupack++;
1328 /*
1329 * If we have outstanding data (other than
1330 * a window probe), this is a completely
1331 * duplicate ack (ie, window info didn't
1332 * change), the ack is the biggest we've
1333 * seen and we've seen exactly our rexmt
1334 * threshhold of them, assume a packet
1335 * has been dropped and retransmit it.
1336 * Kludge snd_nxt & the congestion
1337 * window so we send only this one
1338 * packet.
1339 *
1340 * We know we're losing at the current
1341 * window size so do congestion avoidance
1342 * (set ssthresh to half the current window
1343 * and pull our congestion window back to
1344 * the new ssthresh).
1345 *
1346 * Dup acks mean that packets have left the
1347 * network (they're now cached at the receiver)
1348 * so bump cwnd by the amount in the receiver
1349 * to keep a constant cwnd packets in the
1350 * network.
1351 */
1352 if (tp->t_timer[TCPT_REXMT] == 0 ||
1353 ti->ti_ack != tp->snd_una)
1354 tp->t_dupacks = 0;
1355 else if (++tp->t_dupacks == tcprexmtthresh) {
1356 tcp_seq onxt = tp->snd_nxt;
1357 u_int win =
1358 min(tp->snd_wnd, tp->snd_cwnd) / 2 /
1359 tp->t_maxseg;
1360
1361 if (win < 2)
1362 win = 2;
1363 tp->snd_ssthresh = win * tp->t_maxseg;
1364 tp->t_timer[TCPT_REXMT] = 0;
1365 tp->t_rtt = 0;
1366 tp->snd_nxt = ti->ti_ack;
1367 tp->snd_cwnd = tp->t_maxseg;
1368 (void) tcp_output(tp);
1369 tp->snd_cwnd = tp->snd_ssthresh +
1370 tp->t_maxseg * tp->t_dupacks;
1371 if (SEQ_GT(onxt, tp->snd_nxt))
1372 tp->snd_nxt = onxt;
1373 goto drop;
1374 } else if (tp->t_dupacks > tcprexmtthresh) {
1375 tp->snd_cwnd += tp->t_maxseg;
1376 (void) tcp_output(tp);
1377 goto drop;
1378 }
1379 } else
1380 tp->t_dupacks = 0;
1381 break;
1382 }
1383 /*
1384 * If the congestion window was inflated to account
1385 * for the other side's cached packets, retract it.
1386 */
1387 if (tp->t_dupacks >= tcprexmtthresh &&
1388 tp->snd_cwnd > tp->snd_ssthresh)
1389 tp->snd_cwnd = tp->snd_ssthresh;
1390 tp->t_dupacks = 0;
1391 if (SEQ_GT(ti->ti_ack, tp->snd_max)) {
1392 tcpstat.tcps_rcvacktoomuch++;
1393 goto dropafterack;
1394 }
1395 /*
1396 * If we reach this point, ACK is not a duplicate,
1397 * i.e., it ACKs something we sent.
1398 */
1399 if (tp->t_flags & TF_NEEDSYN) {
1400 /*
1401 * T/TCP: Connection was half-synchronized, and our
1402 * SYN has been ACK'd (so connection is now fully
1403 * synchronized). Go to non-starred state,
1404 * increment snd_una for ACK of SYN, and check if
1405 * we can do window scaling.
1406 */
1407 tp->t_flags &= ~TF_NEEDSYN;
1408 tp->snd_una++;
1409 /* Do window scaling? */
1410 if ((tp->t_flags & (TF_RCVD_SCALE|TF_REQ_SCALE)) ==
1411 (TF_RCVD_SCALE|TF_REQ_SCALE)) {
1412 tp->snd_scale = tp->requested_s_scale;
1413 tp->rcv_scale = tp->request_r_scale;
1414 }
1415 }
1416
1417process_ACK:
1418 acked = ti->ti_ack - tp->snd_una;
1419 tcpstat.tcps_rcvackpack++;
1420 tcpstat.tcps_rcvackbyte += acked;
1421
1422 /*
1423 * If we have a timestamp reply, update smoothed
1424 * round trip time. If no timestamp is present but
1425 * transmit timer is running and timed sequence
1426 * number was acked, update smoothed round trip time.
1427 * Since we now have an rtt measurement, cancel the
1428 * timer backoff (cf., Phil Karn's retransmit alg.).
1429 * Recompute the initial retransmit timer.
1430 */
1431 if (to.to_flag & TOF_TS)
1432 tcp_xmit_timer(tp, tcp_now - to.to_tsecr + 1);
1433 else if (tp->t_rtt && SEQ_GT(ti->ti_ack, tp->t_rtseq))
1434 tcp_xmit_timer(tp,tp->t_rtt);
1435
1436 /*
1437 * If all outstanding data is acked, stop retransmit
1438 * timer and remember to restart (more output or persist).
1439 * If there is more data to be acked, restart retransmit
1440 * timer, using current (possibly backed-off) value.
1441 */
1442 if (ti->ti_ack == tp->snd_max) {
1443 tp->t_timer[TCPT_REXMT] = 0;
1444 needoutput = 1;
1445 } else if (tp->t_timer[TCPT_PERSIST] == 0)
1446 tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
1447
1448 /*
1449 * If no data (only SYN) was ACK'd,
1450 * skip rest of ACK processing.
1451 */
1452 if (acked == 0)
1453 goto step6;
1454
1455 /*
1456 * When new data is acked, open the congestion window.
1457 * If the window gives us less than ssthresh packets
1458 * in flight, open exponentially (maxseg per packet).
1459 * Otherwise open linearly: maxseg per window
1460 * (maxseg^2 / cwnd per packet).
1461 */
1462 {
1463 register u_int cw = tp->snd_cwnd;
1464 register u_int incr = tp->t_maxseg;
1465
1466 if (cw > tp->snd_ssthresh)
1467 incr = incr * incr / cw;
1468 tp->snd_cwnd = min(cw + incr, TCP_MAXWIN<<tp->snd_scale);
1469 }
1470 if (acked > so->so_snd.sb_cc) {
1471 tp->snd_wnd -= so->so_snd.sb_cc;
1472 sbdrop(&so->so_snd, (int)so->so_snd.sb_cc);
1473 ourfinisacked = 1;
1474 } else {
1475 sbdrop(&so->so_snd, acked);
1476 tp->snd_wnd -= acked;
1477 ourfinisacked = 0;
1478 }
1479 sowwakeup(so);
1480 tp->snd_una = ti->ti_ack;
1481 if (SEQ_LT(tp->snd_nxt, tp->snd_una))
1482 tp->snd_nxt = tp->snd_una;
1483
1484 switch (tp->t_state) {
1485
1486 /*
1487 * In FIN_WAIT_1 STATE in addition to the processing
1488 * for the ESTABLISHED state if our FIN is now acknowledged
1489 * then enter FIN_WAIT_2.
1490 */
1491 case TCPS_FIN_WAIT_1:
1492 if (ourfinisacked) {
1493 /*
1494 * If we can't receive any more
1495 * data, then closing user can proceed.
1496 * Starting the timer is contrary to the
1497 * specification, but if we don't get a FIN
1498 * we'll hang forever.
1499 */
1500 if (so->so_state & SS_CANTRCVMORE) {
1501 soisdisconnected(so);
1502 tp->t_timer[TCPT_2MSL] = tcp_maxidle;
1503 }
1504 tp->t_state = TCPS_FIN_WAIT_2;
1505 }
1506 break;
1507
1508 /*
1509 * In CLOSING STATE in addition to the processing for
1510 * the ESTABLISHED state if the ACK acknowledges our FIN
1511 * then enter the TIME-WAIT state, otherwise ignore
1512 * the segment.
1513 */
1514 case TCPS_CLOSING:
1515 if (ourfinisacked) {
1516 tp->t_state = TCPS_TIME_WAIT;
1517 tcp_canceltimers(tp);
1518 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1519 if (tp->cc_recv != 0 &&
1520 tp->t_duration < TCPTV_MSL)
1521 tp->t_timer[TCPT_2MSL] =
1522 tp->t_rxtcur * TCPTV_TWTRUNC;
1523 else
1524 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1525 soisdisconnected(so);
1526 }
1527 break;
1528
1529 /*
1530 * In LAST_ACK, we may still be waiting for data to drain
1531 * and/or to be acked, as well as for the ack of our FIN.
1532 * If our FIN is now acknowledged, delete the TCB,
1533 * enter the closed state and return.
1534 */
1535 case TCPS_LAST_ACK:
1536 if (ourfinisacked) {
1537 tp = tcp_close(tp);
1538 goto drop;
1539 }
1540 break;
1541
1542 /*
1543 * In TIME_WAIT state the only thing that should arrive
1544 * is a retransmission of the remote FIN. Acknowledge
1545 * it and restart the finack timer.
1546 */
1547 case TCPS_TIME_WAIT:
1548 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1549 goto dropafterack;
1550 }
1551 }
1552
1553step6:
1554 /*
1555 * Update window information.
1556 * Don't look at window if no ACK: TAC's send garbage on first SYN.
1557 */
1558 if ((tiflags & TH_ACK) &&
1559 (SEQ_LT(tp->snd_wl1, ti->ti_seq) ||
1560 (tp->snd_wl1 == ti->ti_seq && (SEQ_LT(tp->snd_wl2, ti->ti_ack) ||
1561 (tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd))))) {
1562 /* keep track of pure window updates */
1563 if (ti->ti_len == 0 &&
1564 tp->snd_wl2 == ti->ti_ack && tiwin > tp->snd_wnd)
1565 tcpstat.tcps_rcvwinupd++;
1566 tp->snd_wnd = tiwin;
1567 tp->snd_wl1 = ti->ti_seq;
1568 tp->snd_wl2 = ti->ti_ack;
1569 if (tp->snd_wnd > tp->max_sndwnd)
1570 tp->max_sndwnd = tp->snd_wnd;
1571 needoutput = 1;
1572 }
1573
1574 /*
1575 * Process segments with URG.
1576 */
1577 if ((tiflags & TH_URG) && ti->ti_urp &&
1578 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1579 /*
1580 * This is a kludge, but if we receive and accept
1581 * random urgent pointers, we'll crash in
1582 * soreceive. It's hard to imagine someone
1583 * actually wanting to send this much urgent data.
1584 */
1585 if (ti->ti_urp + so->so_rcv.sb_cc > sb_max) {
1586 ti->ti_urp = 0; /* XXX */
1587 tiflags &= ~TH_URG; /* XXX */
1588 goto dodata; /* XXX */
1589 }
1590 /*
1591 * If this segment advances the known urgent pointer,
1592 * then mark the data stream. This should not happen
1593 * in CLOSE_WAIT, CLOSING, LAST_ACK or TIME_WAIT STATES since
1594 * a FIN has been received from the remote side.
1595 * In these states we ignore the URG.
1596 *
1597 * According to RFC961 (Assigned Protocols),
1598 * the urgent pointer points to the last octet
1599 * of urgent data. We continue, however,
1600 * to consider it to indicate the first octet
1601 * of data past the urgent section as the original
1602 * spec states (in one of two places).
1603 */
1604 if (SEQ_GT(ti->ti_seq+ti->ti_urp, tp->rcv_up)) {
1605 tp->rcv_up = ti->ti_seq + ti->ti_urp;
1606 so->so_oobmark = so->so_rcv.sb_cc +
1607 (tp->rcv_up - tp->rcv_nxt) - 1;
1608 if (so->so_oobmark == 0)
1609 so->so_state |= SS_RCVATMARK;
1610 sohasoutofband(so);
1611 tp->t_oobflags &= ~(TCPOOB_HAVEDATA | TCPOOB_HADDATA);
1612 }
1613 /*
1614 * Remove out of band data so doesn't get presented to user.
1615 * This can happen independent of advancing the URG pointer,
1616 * but if two URG's are pending at once, some out-of-band
1617 * data may creep in... ick.
1618 */
1619 if (ti->ti_urp <= (u_long)ti->ti_len
1620#ifdef SO_OOBINLINE
1621 && (so->so_options & SO_OOBINLINE) == 0
1622#endif
1623 )
1624 tcp_pulloutofband(so, ti, m);
1625 } else
1626 /*
1627 * If no out of band data is expected,
1628 * pull receive urgent pointer along
1629 * with the receive window.
1630 */
1631 if (SEQ_GT(tp->rcv_nxt, tp->rcv_up))
1632 tp->rcv_up = tp->rcv_nxt;
1633dodata: /* XXX */
1634
1635 /*
1636 * Process the segment text, merging it into the TCP sequencing queue,
1637 * and arranging for acknowledgment of receipt if necessary.
1638 * This process logically involves adjusting tp->rcv_wnd as data
1639 * is presented to the user (this happens in tcp_usrreq.c,
1640 * case PRU_RCVD). If a FIN has already been received on this
1641 * connection then we just ignore the text.
1642 */
1643 if ((ti->ti_len || (tiflags&TH_FIN)) &&
1644 TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1645 TCP_REASS(tp, ti, m, so, tiflags);
1646 /*
1647 * Note the amount of data that peer has sent into
1648 * our window, in order to estimate the sender's
1649 * buffer size.
1650 */
1651 len = so->so_rcv.sb_hiwat - (tp->rcv_adv - tp->rcv_nxt);
1652 } else {
1653 m_freem(m);
1654 tiflags &= ~TH_FIN;
1655 }
1656
1657 /*
1658 * If FIN is received ACK the FIN and let the user know
1659 * that the connection is closing.
1660 */
1661 if (tiflags & TH_FIN) {
1662 if (TCPS_HAVERCVDFIN(tp->t_state) == 0) {
1663 socantrcvmore(so);
1664 /*
1665 * If connection is half-synchronized
1666 * (ie NEEDSYN flag on) then delay ACK,
1667 * so it may be piggybacked when SYN is sent.
1668 * Otherwise, since we received a FIN then no
1669 * more input can be expected, send ACK now.
1670 */
1671 if (tcp_delack_enabled && (tp->t_flags & TF_NEEDSYN))
1672 tp->t_flags |= TF_DELACK;
1673 else
1674 tp->t_flags |= TF_ACKNOW;
1675 tp->rcv_nxt++;
1676 }
1677 switch (tp->t_state) {
1678
1679 /*
1680 * In SYN_RECEIVED and ESTABLISHED STATES
1681 * enter the CLOSE_WAIT state.
1682 */
1683 case TCPS_SYN_RECEIVED:
1684 case TCPS_ESTABLISHED:
1685 tp->t_state = TCPS_CLOSE_WAIT;
1686 break;
1687
1688 /*
1689 * If still in FIN_WAIT_1 STATE FIN has not been acked so
1690 * enter the CLOSING state.
1691 */
1692 case TCPS_FIN_WAIT_1:
1693 tp->t_state = TCPS_CLOSING;
1694 break;
1695
1696 /*
1697 * In FIN_WAIT_2 state enter the TIME_WAIT state,
1698 * starting the time-wait timer, turning off the other
1699 * standard timers.
1700 */
1701 case TCPS_FIN_WAIT_2:
1702 tp->t_state = TCPS_TIME_WAIT;
1703 tcp_canceltimers(tp);
1704 /* Shorten TIME_WAIT [RFC-1644, p.28] */
1705 if (tp->cc_recv != 0 &&
1706 tp->t_duration < TCPTV_MSL) {
1707 tp->t_timer[TCPT_2MSL] =
1708 tp->t_rxtcur * TCPTV_TWTRUNC;
1709 /* For transaction client, force ACK now. */
1710 tp->t_flags |= TF_ACKNOW;
1711 }
1712 else
1713 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1714 soisdisconnected(so);
1715 break;
1716
1717 /*
1718 * In TIME_WAIT state restart the 2 MSL time_wait timer.
1719 */
1720 case TCPS_TIME_WAIT:
1721 tp->t_timer[TCPT_2MSL] = 2 * TCPTV_MSL;
1722 break;
1723 }
1724 }
1725#ifdef TCPDEBUG
1726 if (so->so_options & SO_DEBUG)
1727 tcp_trace(TA_INPUT, ostate, tp, &tcp_saveti, 0);
1728#endif
1729
1730 /*
1731 * Return any desired output.
1732 */
1733 if (needoutput || (tp->t_flags & TF_ACKNOW))
1734 (void) tcp_output(tp);
1735 return;
1736
1737dropafterack:
1738 /*
1739 * Generate an ACK dropping incoming segment if it occupies
1740 * sequence space, where the ACK reflects our state.
1741 *
1742 * We can now skip the test for the RST flag since all
1743 * paths to this code happen after packets containing
1744 * RST have been dropped.
1745 *
1746 * In the SYN-RECEIVED state, don't send an ACK unless the
1747 * segment we received passes the SYN-RECEIVED ACK test.
1748 * If it fails send a RST. This breaks the loop in the
1749 * "LAND" DoS attack, and also prevents an ACK storm
1750 * between two listening ports that have been sent forged
1751 * SYN segments, each with the source address of the other.
1752 */
1753 if (tp->t_state == TCPS_SYN_RECEIVED && (tiflags & TH_ACK) &&
1754 (SEQ_GT(tp->snd_una, ti->ti_ack) ||
1755 SEQ_GT(ti->ti_ack, tp->snd_max)) )
1756 goto dropwithreset;
1757#ifdef TCPDEBUG
1758 if (so->so_options & SO_DEBUG)
1759 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1760#endif
1761 m_freem(m);
1762 tp->t_flags |= TF_ACKNOW;
1763 (void) tcp_output(tp);
1764 return;
1765
1766dropwithreset:
1767 /*
1768 * Generate a RST, dropping incoming segment.
1769 * Make ACK acceptable to originator of segment.
1770 * Don't bother to respond if destination was broadcast/multicast.
1771 */
1772 if ((tiflags & TH_RST) || m->m_flags & (M_BCAST|M_MCAST) ||
1773 IN_MULTICAST(ntohl(ti->ti_dst.s_addr)))
1774 goto drop;
1775#ifdef TCPDEBUG
1776 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1777 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1778#endif
1779 if (tiflags & TH_ACK)
1780 tcp_respond(tp, ti, m, (tcp_seq)0, ti->ti_ack, TH_RST);
1781 else {
1782 if (tiflags & TH_SYN)
1783 ti->ti_len++;
1784 tcp_respond(tp, ti, m, ti->ti_seq+ti->ti_len, (tcp_seq)0,
1785 TH_RST|TH_ACK);
1786 }
1787 /* destroy temporarily created socket */
1788 if (dropsocket)
1789 (void) soabort(so);
1790 return;
1791
1792drop:
1793 /*
1794 * Drop space held by incoming segment and return.
1795 */
1796#ifdef TCPDEBUG
1797 if (tp == 0 || (tp->t_inpcb->inp_socket->so_options & SO_DEBUG))
1798 tcp_trace(TA_DROP, ostate, tp, &tcp_saveti, 0);
1799#endif
1800 m_freem(m);
1801 /* destroy temporarily created socket */
1802 if (dropsocket)
1803 (void) soabort(so);
1804 return;
1805}
1806
1807static void
1808tcp_dooptions(tp, cp, cnt, ti, to)
1809 struct tcpcb *tp;
1810 u_char *cp;
1811 int cnt;
1812 struct tcpiphdr *ti;
1813 struct tcpopt *to;
1814{
1815 u_short mss = 0;
1816 int opt, optlen;
1817
1818 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1819 opt = cp[0];
1820 if (opt == TCPOPT_EOL)
1821 break;
1822 if (opt == TCPOPT_NOP)
1823 optlen = 1;
1824 else {
1825 optlen = cp[1];
1826 if (optlen <= 0)
1827 break;
1828 }
1829 switch (opt) {
1830
1831 default:
1832 continue;
1833
1834 case TCPOPT_MAXSEG:
1835 if (optlen != TCPOLEN_MAXSEG)
1836 continue;
1837 if (!(ti->ti_flags & TH_SYN))
1838 continue;
1839 bcopy((char *) cp + 2, (char *) &mss, sizeof(mss));
1840 NTOHS(mss);
1841 break;
1842
1843 case TCPOPT_WINDOW:
1844 if (optlen != TCPOLEN_WINDOW)
1845 continue;
1846 if (!(ti->ti_flags & TH_SYN))
1847 continue;
1848 tp->t_flags |= TF_RCVD_SCALE;
1849 tp->requested_s_scale = min(cp[2], TCP_MAX_WINSHIFT);
1850 break;
1851
1852 case TCPOPT_TIMESTAMP:
1853 if (optlen != TCPOLEN_TIMESTAMP)
1854 continue;
1855 to->to_flag |= TOF_TS;
1856 bcopy((char *)cp + 2,
1857 (char *)&to->to_tsval, sizeof(to->to_tsval));
1858 NTOHL(to->to_tsval);
1859 bcopy((char *)cp + 6,
1860 (char *)&to->to_tsecr, sizeof(to->to_tsecr));
1861 NTOHL(to->to_tsecr);
1862
1863 /*
1864 * A timestamp received in a SYN makes
1865 * it ok to send timestamp requests and replies.
1866 */
1867 if (ti->ti_flags & TH_SYN) {
1868 tp->t_flags |= TF_RCVD_TSTMP;
1869 tp->ts_recent = to->to_tsval;
1870 tp->ts_recent_age = tcp_now;
1871 }
1872 break;
1873 case TCPOPT_CC:
1874 if (optlen != TCPOLEN_CC)
1875 continue;
1876 to->to_flag |= TOF_CC;
1877 bcopy((char *)cp + 2,
1878 (char *)&to->to_cc, sizeof(to->to_cc));
1879 NTOHL(to->to_cc);
1880 /*
1881 * A CC or CC.new option received in a SYN makes
1882 * it ok to send CC in subsequent segments.
1883 */
1884 if (ti->ti_flags & TH_SYN)
1885 tp->t_flags |= TF_RCVD_CC;
1886 break;
1887 case TCPOPT_CCNEW:
1888 if (optlen != TCPOLEN_CC)
1889 continue;
1890 if (!(ti->ti_flags & TH_SYN))
1891 continue;
1892 to->to_flag |= TOF_CCNEW;
1893 bcopy((char *)cp + 2,
1894 (char *)&to->to_cc, sizeof(to->to_cc));
1895 NTOHL(to->to_cc);
1896 /*
1897 * A CC or CC.new option received in a SYN makes
1898 * it ok to send CC in subsequent segments.
1899 */
1900 tp->t_flags |= TF_RCVD_CC;
1901 break;
1902 case TCPOPT_CCECHO:
1903 if (optlen != TCPOLEN_CC)
1904 continue;
1905 if (!(ti->ti_flags & TH_SYN))
1906 continue;
1907 to->to_flag |= TOF_CCECHO;
1908 bcopy((char *)cp + 2,
1909 (char *)&to->to_ccecho, sizeof(to->to_ccecho));
1910 NTOHL(to->to_ccecho);
1911 break;
1912 }
1913 }
1914 if (ti->ti_flags & TH_SYN)
1915 tcp_mss(tp, mss); /* sets t_maxseg */
1916}
1917
1918/*
1919 * Pull out of band byte out of a segment so
1920 * it doesn't appear in the user's data queue.
1921 * It is still reflected in the segment length for
1922 * sequencing purposes.
1923 */
1924static void
1925tcp_pulloutofband(so, ti, m)
1926 struct socket *so;
1927 struct tcpiphdr *ti;
1928 register struct mbuf *m;
1929{
1930 int cnt = ti->ti_urp - 1;
1931
1932 while (cnt >= 0) {
1933 if (m->m_len > cnt) {
1934 char *cp = mtod(m, caddr_t) + cnt;
1935 struct tcpcb *tp = sototcpcb(so);
1936
1937 tp->t_iobc = *cp;
1938 tp->t_oobflags |= TCPOOB_HAVEDATA;
1939 bcopy(cp+1, cp, (unsigned)(m->m_len - cnt - 1));
1940 m->m_len--;
1941 return;
1942 }
1943 cnt -= m->m_len;
1944 m = m->m_next;
1945 if (m == 0)
1946 break;
1947 }
1948 panic("tcp_pulloutofband");
1949}
1950
1951/*
1952 * Collect new round-trip time estimate
1953 * and update averages and current timeout.
1954 */
1955static void
1956tcp_xmit_timer(tp, rtt)
1957 register struct tcpcb *tp;
1958 short rtt;
1959{
1960 register int delta;
1961
1962 tcpstat.tcps_rttupdated++;
1963 tp->t_rttupdated++;
1964 if (tp->t_srtt != 0) {
1965 /*
1966 * srtt is stored as fixed point with 5 bits after the
1967 * binary point (i.e., scaled by 8). The following magic
1968 * is equivalent to the smoothing algorithm in rfc793 with
1969 * an alpha of .875 (srtt = rtt/8 + srtt*7/8 in fixed
1970 * point). Adjust rtt to origin 0.
1971 */
1972 delta = ((rtt - 1) << TCP_DELTA_SHIFT)
1973 - (tp->t_srtt >> (TCP_RTT_SHIFT - TCP_DELTA_SHIFT));
1974
1975 if ((tp->t_srtt += delta) <= 0)
1976 tp->t_srtt = 1;
1977
1978 /*
1979 * We accumulate a smoothed rtt variance (actually, a
1980 * smoothed mean difference), then set the retransmit
1981 * timer to smoothed rtt + 4 times the smoothed variance.
1982 * rttvar is stored as fixed point with 4 bits after the
1983 * binary point (scaled by 16). The following is
1984 * equivalent to rfc793 smoothing with an alpha of .75
1985 * (rttvar = rttvar*3/4 + |delta| / 4). This replaces
1986 * rfc793's wired-in beta.
1987 */
1988 if (delta < 0)
1989 delta = -delta;
1990 delta -= tp->t_rttvar >> (TCP_RTTVAR_SHIFT - TCP_DELTA_SHIFT);
1991 if ((tp->t_rttvar += delta) <= 0)
1992 tp->t_rttvar = 1;
1993 } else {
1994 /*
1995 * No rtt measurement yet - use the unsmoothed rtt.
1996 * Set the variance to half the rtt (so our first
1997 * retransmit happens at 3*rtt).
1998 */
1999 tp->t_srtt = rtt << TCP_RTT_SHIFT;
2000 tp->t_rttvar = rtt << (TCP_RTTVAR_SHIFT - 1);
2001 }
2002 tp->t_rtt = 0;
2003 tp->t_rxtshift = 0;
2004
2005 /*
2006 * the retransmit should happen at rtt + 4 * rttvar.
2007 * Because of the way we do the smoothing, srtt and rttvar
2008 * will each average +1/2 tick of bias. When we compute
2009 * the retransmit timer, we want 1/2 tick of rounding and
2010 * 1 extra tick because of +-1/2 tick uncertainty in the
2011 * firing of the timer. The bias will give us exactly the
2012 * 1.5 tick we need. But, because the bias is
2013 * statistical, we have to test that we don't drop below
2014 * the minimum feasible timer (which is 2 ticks).
2015 */
2016 TCPT_RANGESET(tp->t_rxtcur, TCP_REXMTVAL(tp),
2017 max(tp->t_rttmin, rtt + 2), TCPTV_REXMTMAX);
2018
2019 /*
2020 * We received an ack for a packet that wasn't retransmitted;
2021 * it is probably safe to discard any error indications we've
2022 * received recently. This isn't quite right, but close enough
2023 * for now (a route might have failed after we sent a segment,
2024 * and the return path might not be symmetrical).
2025 */
2026 tp->t_softerror = 0;
2027}
2028
2029/*
2030 * Determine a reasonable value for maxseg size.
2031 * If the route is known, check route for mtu.
2032 * If none, use an mss that can be handled on the outgoing
2033 * interface without forcing IP to fragment; if bigger than
2034 * an mbuf cluster (MCLBYTES), round down to nearest multiple of MCLBYTES
2035 * to utilize large mbufs. If no route is found, route has no mtu,
2036 * or the destination isn't local, use a default, hopefully conservative
2037 * size (usually 512 or the default IP max size, but no more than the mtu
2038 * of the interface), as we can't discover anything about intervening
2039 * gateways or networks. We also initialize the congestion/slow start
2040 * window to be a single segment if the destination isn't local.
2041 * While looking at the routing entry, we also initialize other path-dependent
2042 * parameters from pre-set or cached values in the routing entry.
2043 *
2044 * Also take into account the space needed for options that we
2045 * send regularly. Make maxseg shorter by that amount to assure
2046 * that we can send maxseg amount of data even when the options
2047 * are present. Store the upper limit of the length of options plus
2048 * data in maxopd.
2049 *
2050 * NOTE that this routine is only called when we process an incoming
2051 * segment, for outgoing segments only tcp_mssopt is called.
2052 *
2053 * In case of T/TCP, we call this routine during implicit connection
2054 * setup as well (offer = -1), to initialize maxseg from the cached
2055 * MSS of our peer.
2056 */
2057void
2058tcp_mss(tp, offer)
2059 struct tcpcb *tp;
2060 int offer;
2061{
2062 register struct rtentry *rt;
2063 struct ifnet *ifp;
2064 register int rtt, mss;
2065 u_long bufsize;
2066 struct inpcb *inp;
2067 struct socket *so;
2068 struct rmxp_tao *taop;
2069 int origoffer = offer;
2070
2071 inp = tp->t_inpcb;
2072 if ((rt = tcp_rtlookup(inp)) == NULL) {
2073 tp->t_maxopd = tp->t_maxseg = tcp_mssdflt;
2074 return;
2075 }
2076 ifp = rt->rt_ifp;
2077 so = inp->inp_socket;
2078
2079 taop = rmx_taop(rt->rt_rmx);
2080 /*
2081 * Offer == -1 means that we didn't receive SYN yet,
2082 * use cached value in that case;
2083 */
2084 if (offer == -1)
2085 offer = taop->tao_mssopt;
2086 /*
2087 * Offer == 0 means that there was no MSS on the SYN segment,
2088 * in this case we use tcp_mssdflt.
2089 */
2090 if (offer == 0)
2091 offer = tcp_mssdflt;
2092 else
2093 /*
2094 * Sanity check: make sure that maxopd will be large
2095 * enough to allow some data on segments even is the
2096 * all the option space is used (40bytes). Otherwise
2097 * funny things may happen in tcp_output.
2098 */
2099 offer = max(offer, 64);
2100 taop->tao_mssopt = offer;
2101
2102 /*
2103 * While we're here, check if there's an initial rtt
2104 * or rttvar. Convert from the route-table units
2105 * to scaled multiples of the slow timeout timer.
2106 */
2107 if (tp->t_srtt == 0 && (rtt = rt->rt_rmx.rmx_rtt)) {
2108 /*
2109 * XXX the lock bit for RTT indicates that the value
2110 * is also a minimum value; this is subject to time.
2111 */
2112 if (rt->rt_rmx.rmx_locks & RTV_RTT)
2113 tp->t_rttmin = rtt / (RTM_RTTUNIT / PR_SLOWHZ);
2114 tp->t_srtt = rtt / (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTT_SCALE));
2115 tcpstat.tcps_usedrtt++;
2116 if (rt->rt_rmx.rmx_rttvar) {
2117 tp->t_rttvar = rt->rt_rmx.rmx_rttvar /
2118 (RTM_RTTUNIT / (PR_SLOWHZ * TCP_RTTVAR_SCALE));
2119 tcpstat.tcps_usedrttvar++;
2120 } else {
2121 /* default variation is +- 1 rtt */
2122 tp->t_rttvar =
2123 tp->t_srtt * TCP_RTTVAR_SCALE / TCP_RTT_SCALE;
2124 }
2125 TCPT_RANGESET(tp->t_rxtcur,
2126 ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1,
2127 tp->t_rttmin, TCPTV_REXMTMAX);
2128 }
2129 /*
2130 * if there's an mtu associated with the route, use it
2131 */
2132 if (rt->rt_rmx.rmx_mtu)
2133 mss = rt->rt_rmx.rmx_mtu - sizeof(struct tcpiphdr);
2134 else
2135 {
2136 mss = ifp->if_mtu - sizeof(struct tcpiphdr);
2137 if (!in_localaddr(inp->inp_faddr))
2138 mss = min(mss, tcp_mssdflt);
2139 }
2140 mss = min(mss, offer);
2141 /*
2142 * maxopd stores the maximum length of data AND options
2143 * in a segment; maxseg is the amount of data in a normal
2144 * segment. We need to store this value (maxopd) apart
2145 * from maxseg, because now every segment carries options
2146 * and thus we normally have somewhat less data in segments.
2147 */
2148 tp->t_maxopd = mss;
2149
2150 /*
2151 * In case of T/TCP, origoffer==-1 indicates, that no segments
2152 * were received yet. In this case we just guess, otherwise
2153 * we do the same as before T/TCP.
2154 */
2155 if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
2156 (origoffer == -1 ||
2157 (tp->t_flags & TF_RCVD_TSTMP) == TF_RCVD_TSTMP))
2158 mss -= TCPOLEN_TSTAMP_APPA;
2159 if ((tp->t_flags & (TF_REQ_CC|TF_NOOPT)) == TF_REQ_CC &&
2160 (origoffer == -1 ||
2161 (tp->t_flags & TF_RCVD_CC) == TF_RCVD_CC))
2162 mss -= TCPOLEN_CC_APPA;
2163
2164#if (MCLBYTES & (MCLBYTES - 1)) == 0
2165 if (mss > MCLBYTES)
2166 mss &= ~(MCLBYTES-1);
2167#else
2168 if (mss > MCLBYTES)
2169 mss = mss / MCLBYTES * MCLBYTES;
2170#endif
2171 /*
2172 * If there's a pipesize, change the socket buffer
2173 * to that size. Make the socket buffers an integral
2174 * number of mss units; if the mss is larger than
2175 * the socket buffer, decrease the mss.
2176 */
2177#ifdef RTV_SPIPE
2178 if ((bufsize = rt->rt_rmx.rmx_sendpipe) == 0)
2179#endif
2180 bufsize = so->so_snd.sb_hiwat;
2181 if (bufsize < mss)
2182 mss = bufsize;
2183 else {
2184 bufsize = roundup(bufsize, mss);
2185 if (bufsize > sb_max)
2186 bufsize = sb_max;
2187 (void)sbreserve(&so->so_snd, bufsize);
2188 }
2189 tp->t_maxseg = mss;
2190
2191#ifdef RTV_RPIPE
2192 if ((bufsize = rt->rt_rmx.rmx_recvpipe) == 0)
2193#endif
2194 bufsize = so->so_rcv.sb_hiwat;
2195 if (bufsize > mss) {
2196 bufsize = roundup(bufsize, mss);
2197 if (bufsize > sb_max)
2198 bufsize = sb_max;
2199 (void)sbreserve(&so->so_rcv, bufsize);
2200 }
2201 /*
2202 * Don't force slow-start on local network.
2203 */
2204 if (!in_localaddr(inp->inp_faddr))
2205 tp->snd_cwnd = mss;
2206
2207 if (rt->rt_rmx.rmx_ssthresh) {
2208 /*
2209 * There's some sort of gateway or interface
2210 * buffer limit on the path. Use this to set
2211 * the slow start threshhold, but set the
2212 * threshold to no less than 2*mss.
2213 */
2214 tp->snd_ssthresh = max(2 * mss, rt->rt_rmx.rmx_ssthresh);
2215 tcpstat.tcps_usedssthresh++;
2216 }
2217}
2218
2219/*
2220 * Determine the MSS option to send on an outgoing SYN.
2221 */
2222int
2223tcp_mssopt(tp)
2224 struct tcpcb *tp;
2225{
2226 struct rtentry *rt;
2227
2228 rt = tcp_rtlookup(tp->t_inpcb);
2229 if (rt == NULL)
2230 return tcp_mssdflt;
2231
2232 return rt->rt_ifp->if_mtu - sizeof(struct tcpiphdr);
2233}