1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
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. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)tcp_output.c	8.3 (Berkeley) 12/30/93
30 * tcp_output.c,v 1.3 1994/09/15 10:36:55 davidg Exp
31 */
32
33/*
34 * Changes and additions relating to SLiRP
35 * Copyright (c) 1995 Danny Gasparovski.
36 *
37 * Please read the file COPYRIGHT for the
38 * terms and conditions of the copyright.
39 */
40
41#include <slirp.h>
42
43/*
44 * Since this is only used in "stats socket", we give meaning
45 * names instead of the REAL names
46 */
47const char * const tcpstates[] = {
48/*	"CLOSED",       "LISTEN",       "SYN_SENT",     "SYN_RCVD", */
49	"REDIRECT",	"LISTEN",	"SYN_SENT",     "SYN_RCVD",
50	"ESTABLISHED",  "CLOSE_WAIT",   "FIN_WAIT_1",   "CLOSING",
51	"LAST_ACK",     "FIN_WAIT_2",   "TIME_WAIT",
52};
53
54static const u_char  tcp_outflags[TCP_NSTATES] = {
55	TH_RST|TH_ACK, 0,      TH_SYN,        TH_SYN|TH_ACK,
56	TH_ACK,        TH_ACK, TH_FIN|TH_ACK, TH_FIN|TH_ACK,
57	TH_FIN|TH_ACK, TH_ACK, TH_ACK,
58};
59
60
61#define MAX_TCPOPTLEN	32	/* max # bytes that go in options */
62
63/*
64 * Tcp output routine: figure out what should be sent and send it.
65 */
66int
67tcp_output(struct tcpcb *tp)
68{
69	register struct socket *so = tp->t_socket;
70	register long len, win;
71	int off, flags, error;
72	register struct mbuf *m;
73	register struct tcpiphdr *ti;
74	u_char opt[MAX_TCPOPTLEN];
75	unsigned optlen, hdrlen;
76	int idle, sendalot;
77
78	DEBUG_CALL("tcp_output");
79	DEBUG_ARG("tp = %lx", (long )tp);
80
81	/*
82	 * Determine length of data that should be transmitted,
83	 * and flags that will be used.
84	 * If there is some data or critical controls (SYN, RST)
85	 * to send, then transmit; otherwise, investigate further.
86	 */
87	idle = (tp->snd_max == tp->snd_una);
88	if (idle && tp->t_idle >= tp->t_rxtcur)
89		/*
90		 * We have been idle for "a while" and no acks are
91		 * expected to clock out any data we send --
92		 * slow start to get ack "clock" running again.
93		 */
94		tp->snd_cwnd = tp->t_maxseg;
95again:
96	sendalot = 0;
97	off = tp->snd_nxt - tp->snd_una;
98	win = min(tp->snd_wnd, tp->snd_cwnd);
99
100	flags = tcp_outflags[tp->t_state];
101
102	DEBUG_MISC((dfd, " --- tcp_output flags = 0x%x\n",flags));
103
104	/*
105	 * If in persist timeout with window of 0, send 1 byte.
106	 * Otherwise, if window is small but nonzero
107	 * and timer expired, we will send what we can
108	 * and go to transmit state.
109	 */
110	if (tp->t_force) {
111		if (win == 0) {
112			/*
113			 * If we still have some data to send, then
114			 * clear the FIN bit.  Usually this would
115			 * happen below when it realizes that we
116			 * aren't sending all the data.  However,
117			 * if we have exactly 1 byte of unset data,
118			 * then it won't clear the FIN bit below,
119			 * and if we are in persist state, we wind
120			 * up sending the packet without recording
121			 * that we sent the FIN bit.
122			 *
123			 * We can't just blindly clear the FIN bit,
124			 * because if we don't have any more data
125			 * to send then the probe will be the FIN
126			 * itself.
127			 */
128			if (off < so->so_snd.sb_cc)
129				flags &= ~TH_FIN;
130			win = 1;
131		} else {
132			tp->t_timer[TCPT_PERSIST] = 0;
133			tp->t_rxtshift = 0;
134		}
135	}
136
137	len = min(so->so_snd.sb_cc, win) - off;
138
139	if (len < 0) {
140		/*
141		 * If FIN has been sent but not acked,
142		 * but we haven't been called to retransmit,
143		 * len will be -1.  Otherwise, window shrank
144		 * after we sent into it.  If window shrank to 0,
145		 * cancel pending retransmit and pull snd_nxt
146		 * back to (closed) window.  We will enter persist
147		 * state below.  If the window didn't close completely,
148		 * just wait for an ACK.
149		 */
150		len = 0;
151		if (win == 0) {
152			tp->t_timer[TCPT_REXMT] = 0;
153			tp->snd_nxt = tp->snd_una;
154		}
155	}
156
157	if (len > tp->t_maxseg) {
158		len = tp->t_maxseg;
159		sendalot = 1;
160	}
161	if (SEQ_LT(tp->snd_nxt + len, tp->snd_una + so->so_snd.sb_cc))
162		flags &= ~TH_FIN;
163
164	win = sbspace(&so->so_rcv);
165
166	/*
167	 * Sender silly window avoidance.  If connection is idle
168	 * and can send all data, a maximum segment,
169	 * at least a maximum default-size segment do it,
170	 * or are forced, do it; otherwise don't bother.
171	 * If peer's buffer is tiny, then send
172	 * when window is at least half open.
173	 * If retransmitting (possibly after persist timer forced us
174	 * to send into a small window), then must resend.
175	 */
176	if (len) {
177		if (len == tp->t_maxseg)
178			goto send;
179		if ((1 || idle || tp->t_flags & TF_NODELAY) &&
180		    len + off >= so->so_snd.sb_cc)
181			goto send;
182		if (tp->t_force)
183			goto send;
184		if (len >= tp->max_sndwnd / 2 && tp->max_sndwnd > 0)
185			goto send;
186		if (SEQ_LT(tp->snd_nxt, tp->snd_max))
187			goto send;
188	}
189
190	/*
191	 * Compare available window to amount of window
192	 * known to peer (as advertised window less
193	 * next expected input).  If the difference is at least two
194	 * max size segments, or at least 50% of the maximum possible
195	 * window, then want to send a window update to peer.
196	 */
197	if (win > 0) {
198		/*
199		 * "adv" is the amount we can increase the window,
200		 * taking into account that we are limited by
201		 * TCP_MAXWIN << tp->rcv_scale.
202		 */
203		long adv = min(win, (long)TCP_MAXWIN << tp->rcv_scale) -
204			(tp->rcv_adv - tp->rcv_nxt);
205
206		if (adv >= (long) (2 * tp->t_maxseg))
207			goto send;
208		if (2 * adv >= (long) so->so_rcv.sb_datalen)
209			goto send;
210	}
211
212	/*
213	 * Send if we owe peer an ACK.
214	 */
215	if (tp->t_flags & TF_ACKNOW)
216		goto send;
217	if (flags & (TH_SYN|TH_RST))
218		goto send;
219	if (SEQ_GT(tp->snd_up, tp->snd_una))
220		goto send;
221	/*
222	 * If our state indicates that FIN should be sent
223	 * and we have not yet done so, or we're retransmitting the FIN,
224	 * then we need to send.
225	 */
226	if (flags & TH_FIN &&
227	    ((tp->t_flags & TF_SENTFIN) == 0 || tp->snd_nxt == tp->snd_una))
228		goto send;
229
230	/*
231	 * TCP window updates are not reliable, rather a polling protocol
232	 * using ``persist'' packets is used to insure receipt of window
233	 * updates.  The three ``states'' for the output side are:
234	 *	idle			not doing retransmits or persists
235	 *	persisting		to move a small or zero window
236	 *	(re)transmitting	and thereby not persisting
237	 *
238	 * tp->t_timer[TCPT_PERSIST]
239	 *	is set when we are in persist state.
240	 * tp->t_force
241	 *	is set when we are called to send a persist packet.
242	 * tp->t_timer[TCPT_REXMT]
243	 *	is set when we are retransmitting
244	 * The output side is idle when both timers are zero.
245	 *
246	 * If send window is too small, there is data to transmit, and no
247	 * retransmit or persist is pending, then go to persist state.
248	 * If nothing happens soon, send when timer expires:
249	 * if window is nonzero, transmit what we can,
250	 * otherwise force out a byte.
251	 */
252	if (so->so_snd.sb_cc && tp->t_timer[TCPT_REXMT] == 0 &&
253	    tp->t_timer[TCPT_PERSIST] == 0) {
254		tp->t_rxtshift = 0;
255		tcp_setpersist(tp);
256	}
257
258	/*
259	 * No reason to send a segment, just return.
260	 */
261	STAT(tcpstat.tcps_didnuttin++);
262
263	return (0);
264
265send:
266	/*
267	 * Before ESTABLISHED, force sending of initial options
268	 * unless TCP set not to do any options.
269	 * NOTE: we assume that the IP/TCP header plus TCP options
270	 * always fit in a single mbuf, leaving room for a maximum
271	 * link header, i.e.
272	 *	max_linkhdr + sizeof (struct tcpiphdr) + optlen <= MHLEN
273	 */
274	optlen = 0;
275	hdrlen = sizeof (struct tcpiphdr);
276	if (flags & TH_SYN) {
277		tp->snd_nxt = tp->iss;
278		if ((tp->t_flags & TF_NOOPT) == 0) {
279			u_int16_t mss;
280
281			opt[0] = TCPOPT_MAXSEG;
282			opt[1] = 4;
283			mss = htons((u_int16_t) tcp_mss(tp, 0));
284			memcpy((caddr_t)(opt + 2), (caddr_t)&mss, sizeof(mss));
285			optlen = 4;
286
287/*			if ((tp->t_flags & TF_REQ_SCALE) &&
288 *			    ((flags & TH_ACK) == 0 ||
289 *			    (tp->t_flags & TF_RCVD_SCALE))) {
290 *				*((u_int32_t *) (opt + optlen)) = htonl(
291 *					TCPOPT_NOP << 24 |
292 *					TCPOPT_WINDOW << 16 |
293 *					TCPOLEN_WINDOW << 8 |
294 *					tp->request_r_scale);
295 *				optlen += 4;
296 *			}
297 */
298		}
299 	}
300
301 	/*
302	 * Send a timestamp and echo-reply if this is a SYN and our side
303	 * wants to use timestamps (TF_REQ_TSTMP is set) or both our side
304	 * and our peer have sent timestamps in our SYN's.
305 	 */
306/* 	if ((tp->t_flags & (TF_REQ_TSTMP|TF_NOOPT)) == TF_REQ_TSTMP &&
307 *	     (flags & TH_RST) == 0 &&
308 *	    ((flags & (TH_SYN|TH_ACK)) == TH_SYN ||
309 *	     (tp->t_flags & TF_RCVD_TSTMP))) {
310 *		u_int32_t *lp = (u_int32_t *)(opt + optlen);
311 *
312 *		/ * Form timestamp option as shown in appendix A of RFC 1323. *  /
313 *		*lp++ = htonl(TCPOPT_TSTAMP_HDR);
314 *		*lp++ = htonl(tcp_now);
315 *		*lp   = htonl(tp->ts_recent);
316 *		optlen += TCPOLEN_TSTAMP_APPA;
317 *	}
318 */
319 	hdrlen += optlen;
320
321	/*
322	 * Adjust data length if insertion of options will
323	 * bump the packet length beyond the t_maxseg length.
324	 */
325	 if (len > tp->t_maxseg - optlen) {
326		len = tp->t_maxseg - optlen;
327		sendalot = 1;
328	 }
329
330	/*
331	 * Grab a header mbuf, attaching a copy of data to
332	 * be transmitted, and initialize the header from
333	 * the template for sends on this connection.
334	 */
335	if (len) {
336		if (tp->t_force && len == 1)
337			STAT(tcpstat.tcps_sndprobe++);
338		else if (SEQ_LT(tp->snd_nxt, tp->snd_max)) {
339			STAT(tcpstat.tcps_sndrexmitpack++);
340			STAT(tcpstat.tcps_sndrexmitbyte += len);
341		} else {
342			STAT(tcpstat.tcps_sndpack++);
343			STAT(tcpstat.tcps_sndbyte += len);
344		}
345
346		m = m_get();
347		if (m == NULL) {
348/*			error = ENOBUFS; */
349			error = 1;
350			goto out;
351		}
352		m->m_data += IF_MAXLINKHDR;
353		m->m_len = hdrlen;
354
355		/*
356		 * This will always succeed, since we make sure our mbufs
357		 * are big enough to hold one MSS packet + header + ... etc.
358		 */
359/*		if (len <= MHLEN - hdrlen - max_linkhdr) { */
360
361			sbcopy(&so->so_snd, off, (int) len, mtod(m, caddr_t) + hdrlen);
362			m->m_len += len;
363
364/*		} else {
365 *			m->m_next = m_copy(so->so_snd.sb_mb, off, (int) len);
366 *			if (m->m_next == 0)
367 *				len = 0;
368 *		}
369 */
370		/*
371		 * If we're sending everything we've got, set PUSH.
372		 * (This will keep happy those implementations which only
373		 * give data to the user when a buffer fills or
374		 * a PUSH comes in.)
375		 */
376		if (off + len == so->so_snd.sb_cc)
377			flags |= TH_PUSH;
378	} else {
379		if (tp->t_flags & TF_ACKNOW)
380			STAT(tcpstat.tcps_sndacks++);
381		else if (flags & (TH_SYN|TH_FIN|TH_RST))
382			STAT(tcpstat.tcps_sndctrl++);
383		else if (SEQ_GT(tp->snd_up, tp->snd_una))
384			STAT(tcpstat.tcps_sndurg++);
385		else
386			STAT(tcpstat.tcps_sndwinup++);
387
388		m = m_get();
389		if (m == NULL) {
390/*			error = ENOBUFS; */
391			error = 1;
392			goto out;
393		}
394		m->m_data += IF_MAXLINKHDR;
395		m->m_len = hdrlen;
396	}
397
398	ti = mtod(m, struct tcpiphdr *);
399
400	memcpy((caddr_t)ti, &tp->t_template, sizeof (struct tcpiphdr));
401
402	/*
403	 * Fill in fields, remembering maximum advertised
404	 * window for use in delaying messages about window sizes.
405	 * If resending a FIN, be sure not to use a new sequence number.
406	 */
407	if (flags & TH_FIN && tp->t_flags & TF_SENTFIN &&
408	    tp->snd_nxt == tp->snd_max)
409		tp->snd_nxt--;
410	/*
411	 * If we are doing retransmissions, then snd_nxt will
412	 * not reflect the first unsent octet.  For ACK only
413	 * packets, we do not want the sequence number of the
414	 * retransmitted packet, we want the sequence number
415	 * of the next unsent octet.  So, if there is no data
416	 * (and no SYN or FIN), use snd_max instead of snd_nxt
417	 * when filling in ti_seq.  But if we are in persist
418	 * state, snd_max might reflect one byte beyond the
419	 * right edge of the window, so use snd_nxt in that
420	 * case, since we know we aren't doing a retransmission.
421	 * (retransmit and persist are mutually exclusive...)
422	 */
423	if (len || (flags & (TH_SYN|TH_FIN)) || tp->t_timer[TCPT_PERSIST])
424		ti->ti_seq = htonl(tp->snd_nxt);
425	else
426		ti->ti_seq = htonl(tp->snd_max);
427	ti->ti_ack = htonl(tp->rcv_nxt);
428	if (optlen) {
429		memcpy((caddr_t)(ti + 1), (caddr_t)opt, optlen);
430		ti->ti_off = (sizeof (struct tcphdr) + optlen) >> 2;
431	}
432	ti->ti_flags = flags;
433	/*
434	 * Calculate receive window.  Don't shrink window,
435	 * but avoid silly window syndrome.
436	 */
437	if (win < (long)(so->so_rcv.sb_datalen / 4) && win < (long)tp->t_maxseg)
438		win = 0;
439	if (win > (long)TCP_MAXWIN << tp->rcv_scale)
440		win = (long)TCP_MAXWIN << tp->rcv_scale;
441	if (win < (long)(tp->rcv_adv - tp->rcv_nxt))
442		win = (long)(tp->rcv_adv - tp->rcv_nxt);
443	ti->ti_win = htons((u_int16_t) (win>>tp->rcv_scale));
444
445	if (SEQ_GT(tp->snd_up, tp->snd_una)) {
446		ti->ti_urp = htons((u_int16_t)(tp->snd_up - ntohl(ti->ti_seq)));
447#ifdef notdef
448	if (SEQ_GT(tp->snd_up, tp->snd_nxt)) {
449		ti->ti_urp = htons((u_int16_t)(tp->snd_up - tp->snd_nxt));
450#endif
451		ti->ti_flags |= TH_URG;
452	} else
453		/*
454		 * If no urgent pointer to send, then we pull
455		 * the urgent pointer to the left edge of the send window
456		 * so that it doesn't drift into the send window on sequence
457		 * number wraparound.
458		 */
459		tp->snd_up = tp->snd_una;		/* drag it along */
460
461	/*
462	 * Put TCP length in extended header, and then
463	 * checksum extended header and data.
464	 */
465	if (len + optlen)
466		ti->ti_len = htons((u_int16_t)(sizeof (struct tcphdr) +
467		    optlen + len));
468	ti->ti_sum = cksum(m, (int)(hdrlen + len));
469
470	/*
471	 * In transmit state, time the transmission and arrange for
472	 * the retransmit.  In persist state, just set snd_max.
473	 */
474	if (tp->t_force == 0 || tp->t_timer[TCPT_PERSIST] == 0) {
475		tcp_seq startseq = tp->snd_nxt;
476
477		/*
478		 * Advance snd_nxt over sequence space of this segment.
479		 */
480		if (flags & (TH_SYN|TH_FIN)) {
481			if (flags & TH_SYN)
482				tp->snd_nxt++;
483			if (flags & TH_FIN) {
484				tp->snd_nxt++;
485				tp->t_flags |= TF_SENTFIN;
486			}
487		}
488		tp->snd_nxt += len;
489		if (SEQ_GT(tp->snd_nxt, tp->snd_max)) {
490			tp->snd_max = tp->snd_nxt;
491			/*
492			 * Time this transmission if not a retransmission and
493			 * not currently timing anything.
494			 */
495			if (tp->t_rtt == 0) {
496				tp->t_rtt = 1;
497				tp->t_rtseq = startseq;
498				STAT(tcpstat.tcps_segstimed++);
499			}
500		}
501
502		/*
503		 * Set retransmit timer if not currently set,
504		 * and not doing an ack or a keep-alive probe.
505		 * Initial value for retransmit timer is smoothed
506		 * round-trip time + 2 * round-trip time variance.
507		 * Initialize shift counter which is used for backoff
508		 * of retransmit time.
509		 */
510		if (tp->t_timer[TCPT_REXMT] == 0 &&
511		    tp->snd_nxt != tp->snd_una) {
512			tp->t_timer[TCPT_REXMT] = tp->t_rxtcur;
513			if (tp->t_timer[TCPT_PERSIST]) {
514				tp->t_timer[TCPT_PERSIST] = 0;
515				tp->t_rxtshift = 0;
516			}
517		}
518	} else
519		if (SEQ_GT(tp->snd_nxt + len, tp->snd_max))
520			tp->snd_max = tp->snd_nxt + len;
521
522	/*
523	 * Fill in IP length and desired time to live and
524	 * send to IP level.  There should be a better way
525	 * to handle ttl and tos; we could keep them in
526	 * the template, but need a way to checksum without them.
527	 */
528	m->m_len = hdrlen + len; /* XXX Needed? m_len should be correct */
529
530    {
531
532	((struct ip *)ti)->ip_len = m->m_len;
533
534	((struct ip *)ti)->ip_ttl = IPDEFTTL;
535	((struct ip *)ti)->ip_tos = so->so_iptos;
536
537/* #if BSD >= 43 */
538	/* Don't do IP options... */
539/*	error = ip_output(m, tp->t_inpcb->inp_options, &tp->t_inpcb->inp_route,
540 *	    so->so_options & SO_DONTROUTE, 0);
541 */
542	error = ip_output(so, m);
543
544/* #else
545 *	error = ip_output(m, (struct mbuf *)0, &tp->t_inpcb->inp_route,
546 *	    so->so_options & SO_DONTROUTE);
547 * #endif
548 */
549    }
550	if (error) {
551out:
552/*		if (error == ENOBUFS) {
553 *			tcp_quench(tp->t_inpcb, 0);
554 *			return (0);
555 *		}
556 */
557/*		if ((error == EHOSTUNREACH || error == ENETDOWN)
558 *		    && TCPS_HAVERCVDSYN(tp->t_state)) {
559 *			tp->t_softerror = error;
560 *			return (0);
561 *		}
562 */
563		return (error);
564	}
565	STAT(tcpstat.tcps_sndtotal++);
566
567	/*
568	 * Data sent (as far as we can tell).
569	 * If this advertises a larger window than any other segment,
570	 * then remember the size of the advertised window.
571	 * Any pending ACK has now been sent.
572	 */
573	if (win > 0 && SEQ_GT(tp->rcv_nxt+win, tp->rcv_adv))
574		tp->rcv_adv = tp->rcv_nxt + win;
575	tp->last_ack_sent = tp->rcv_nxt;
576	tp->t_flags &= ~(TF_ACKNOW|TF_DELACK);
577	if (sendalot)
578		goto again;
579
580	return (0);
581}
582
583void
584tcp_setpersist(struct tcpcb *tp)
585{
586    int t = ((tp->t_srtt >> 2) + tp->t_rttvar) >> 1;
587
588/*	if (tp->t_timer[TCPT_REXMT])
589 *		panic("tcp_output REXMT");
590 */
591	/*
592	 * Start/restart persistence timer.
593	 */
594	TCPT_RANGESET(tp->t_timer[TCPT_PERSIST],
595	    t * tcp_backoff[tp->t_rxtshift],
596	    TCPTV_PERSMIN, TCPTV_PERSMAX);
597	if (tp->t_rxtshift < TCP_MAXRXTSHIFT)
598		tp->t_rxtshift++;
599}
600