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