• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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. 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_subr.c	8.1 (Berkeley) 6/10/93
34  * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp
35  */
36 
37 /*
38  * Changes and additions relating to SLiRP
39  * Copyright (c) 1995 Danny Gasparovski.
40  *
41  * Please read the file COPYRIGHT for the
42  * terms and conditions of the copyright.
43  */
44 
45 #define WANT_SYS_IOCTL_H
46 #include <slirp.h>
47 #include "proxy_common.h"
48 
49 /* patchable/settable parameters for tcp */
50 int 	tcp_mssdflt = TCP_MSS;
51 int 	tcp_rttdflt = TCPTV_SRTTDFLT / PR_SLOWHZ;
52 int	tcp_do_rfc1323 = 0;	/* Don't do rfc1323 performance enhancements */
53 int	tcp_rcvspace;	/* You may want to change this */
54 int	tcp_sndspace;	/* Keep small if you have an error prone link */
55 
56 /*
57  * Tcp initialization
58  */
59 void
tcp_init()60 tcp_init()
61 {
62 	tcp_iss = 1;		/* wrong */
63 	tcb.so_next = tcb.so_prev = &tcb;
64 
65 	/* tcp_rcvspace = our Window we advertise to the remote */
66 	tcp_rcvspace = TCP_RCVSPACE;
67 	tcp_sndspace = TCP_SNDSPACE;
68 
69 	/* Make sure tcp_sndspace is at least 2*MSS */
70 	if (tcp_sndspace < 2*(min(if_mtu, if_mru) - sizeof(struct tcpiphdr)))
71 		tcp_sndspace = 2*(min(if_mtu, if_mru) - sizeof(struct tcpiphdr));
72 }
73 
74 /*
75  * Create template to be used to send tcp packets on a connection.
76  * Call after host entry created, fills
77  * in a skeletal tcp/ip header, minimizing the amount of work
78  * necessary when the connection is used.
79  */
80 /* struct tcpiphdr * */
81 void
tcp_template(tp)82 tcp_template(tp)
83 	struct tcpcb *tp;
84 {
85 	struct socket *so = tp->t_socket;
86 	register struct tcpiphdr *n = &tp->t_template;
87 
88 	n->ti_mbuf = NULL;
89 	n->ti_x1 = 0;
90 	n->ti_pr = IPPROTO_TCP;
91 	n->ti_len = htons(sizeof (struct tcpiphdr) - sizeof (struct ip));
92 	n->ti_src = ip_seth(so->so_faddr_ip);
93 	n->ti_dst = ip_seth(so->so_laddr_ip);
94 	n->ti_sport = port_seth(so->so_faddr_port);
95 	n->ti_dport = port_seth(so->so_laddr_port);
96 
97 	n->ti_seq = 0;
98 	n->ti_ack = 0;
99 	n->ti_x2 = 0;
100 	n->ti_off = 5;
101 	n->ti_flags = 0;
102 	n->ti_win = 0;
103 	n->ti_sum = 0;
104 	n->ti_urp = 0;
105 }
106 
107 /*
108  * Send a single message to the TCP at address specified by
109  * the given TCP/IP header.  If m == 0, then we make a copy
110  * of the tcpiphdr at ti and send directly to the addressed host.
111  * This is used to force keep alive messages out using the TCP
112  * template for a connection tp->t_template.  If flags are given
113  * then we send a message back to the TCP which originated the
114  * segment ti, and discard the mbuf containing it and any other
115  * attached mbufs.
116  *
117  * In any case the ack and sequence number of the transmitted
118  * segment are as specified by the parameters.
119  */
120 void
tcp_respond(tp,ti,m,ack,seq,flags)121 tcp_respond(tp, ti, m, ack, seq, flags)
122 	struct tcpcb *tp;
123 	register struct tcpiphdr *ti;
124 	register MBuf m;
125 	tcp_seq ack, seq;
126 	int flags;
127 {
128 	register int tlen;
129 	int win = 0;
130 
131 	DEBUG_CALL("tcp_respond");
132 	DEBUG_ARG("tp = %lx", (long)tp);
133 	DEBUG_ARG("ti = %lx", (long)ti);
134 	DEBUG_ARG("m = %lx", (long)m);
135 	DEBUG_ARG("ack = %u", ack);
136 	DEBUG_ARG("seq = %u", seq);
137 	DEBUG_ARG("flags = %x", flags);
138 
139 	if (tp)
140 		win = sbuf_space(&tp->t_socket->so_rcv);
141 	if (m == 0) {
142 		if ((m = mbuf_alloc()) == NULL)
143 			return;
144 #ifdef TCP_COMPAT_42
145 		tlen = 1;
146 #else
147 		tlen = 0;
148 #endif
149 		m->m_data += if_maxlinkhdr;
150 		*MBUF_TO(m, struct tcpiphdr *) = *ti;
151 		ti = MBUF_TO(m, struct tcpiphdr *);
152 		flags = TH_ACK;
153 	} else {
154 		/*
155 		 * ti points into m so the next line is just making
156 		 * the mbuf point to ti
157 		 */
158 		m->m_data = (caddr_t)ti;
159 
160 		m->m_len = sizeof (struct tcpiphdr);
161 		tlen = 0;
162 #define xchg(a,b,type) { type t; t=a; a=b; b=t; }
163 		xchg(ti->ti_dst, ti->ti_src, ipaddr_t);
164 		xchg(ti->ti_dport, ti->ti_sport, port_t);
165 #undef xchg
166 	}
167 	ti->ti_len = htons((u_short)(sizeof (struct tcphdr) + tlen));
168 	tlen += sizeof (struct tcpiphdr);
169 	m->m_len = tlen;
170 
171 	ti->ti_mbuf = 0;
172 	ti->ti_x1 = 0;
173 	ti->ti_seq = htonl(seq);
174 	ti->ti_ack = htonl(ack);
175 	ti->ti_x2 = 0;
176 	ti->ti_off = sizeof (struct tcphdr) >> 2;
177 	ti->ti_flags = flags;
178 	if (tp)
179 		ti->ti_win = htons((u_int16_t) (win >> tp->rcv_scale));
180 	else
181 		ti->ti_win = htons((u_int16_t)win);
182 	ti->ti_urp = 0;
183 	ti->ti_sum = 0;
184 	ti->ti_sum = cksum(m, tlen);
185 	((struct ip *)ti)->ip_len = tlen;
186 
187 	if(flags & TH_RST)
188 	  ((struct ip *)ti)->ip_ttl = MAXTTL;
189 	else
190 	  ((struct ip *)ti)->ip_ttl = ip_defttl;
191 
192 	(void) ip_output((struct socket *)0, m);
193 }
194 
195 /*
196  * Create a new TCP control block, making an
197  * empty reassembly queue and hooking it to the argument
198  * protocol control block.
199  */
200 struct tcpcb *
tcp_newtcpcb(so)201 tcp_newtcpcb(so)
202 	struct socket *so;
203 {
204 	register struct tcpcb *tp;
205 
206 	tp = (struct tcpcb *)malloc(sizeof(*tp));
207 	if (tp == NULL)
208 		return ((struct tcpcb *)0);
209 
210 	memset((char *) tp, 0, sizeof(struct tcpcb));
211 	tp->seg_next = tp->seg_prev = (struct tcpiphdr*)tp;
212 	tp->t_maxseg = tcp_mssdflt;
213 
214 	tp->t_flags = tcp_do_rfc1323 ? (TF_REQ_SCALE|TF_REQ_TSTMP) : 0;
215 	tp->t_socket = so;
216 
217 	/*
218 	 * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
219 	 * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
220 	 * reasonable initial retransmit time.
221 	 */
222 	tp->t_srtt = TCPTV_SRTTBASE;
223 	tp->t_rttvar = tcp_rttdflt * PR_SLOWHZ << 2;
224 	tp->t_rttmin = TCPTV_MIN;
225 
226 	TCPT_RANGESET(tp->t_rxtcur,
227 	    ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,
228 	    TCPTV_MIN, TCPTV_REXMTMAX);
229 
230 	tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
231 	tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
232 	tp->t_state = TCPS_CLOSED;
233 
234 	so->so_tcpcb = tp;
235 
236 	return (tp);
237 }
238 
239 /*
240  * Drop a TCP connection, reporting
241  * the specified error.  If connection is synchronized,
242  * then send a RST to peer.
243  */
tcp_drop(struct tcpcb * tp,int err)244 struct tcpcb *tcp_drop(struct tcpcb *tp, int err)
245 {
246 /* tcp_drop(tp, errno)
247 	register struct tcpcb *tp;
248 	int errno;
249 {
250 */
251 
252 	DEBUG_CALL("tcp_drop");
253 	DEBUG_ARG("tp = %lx", (long)tp);
254 	DEBUG_ARG("errno = %d", errno);
255 
256 	if (TCPS_HAVERCVDSYN(tp->t_state)) {
257 		tp->t_state = TCPS_CLOSED;
258 		(void) tcp_output(tp);
259 		tcpstat.tcps_drops++;
260 	} else
261 		tcpstat.tcps_conndrops++;
262 /*	if (errno == ETIMEDOUT && tp->t_softerror)
263  *		errno = tp->t_softerror;
264  */
265 /*	so->so_error = errno; */
266 	return (tcp_close(tp));
267 }
268 
269 /*
270  * Close a TCP control block:
271  *	discard all space held by the tcp
272  *	discard internet protocol block
273  *	wake up any sleepers
274  */
275 struct tcpcb *
tcp_close(tp)276 tcp_close(tp)
277 	register struct tcpcb *tp;
278 {
279 	register struct tcpiphdr *t;
280 	struct socket *so = tp->t_socket;
281 	register MBuf m;
282 
283 	DEBUG_CALL("tcp_close");
284 	DEBUG_ARG("tp = %lx", (long )tp);
285 
286 	/* free the reassembly queue, if any */
287 	t = tcpfrag_list_first(tp);
288 	while (!tcpfrag_list_end(t, tp)) {
289 	    t = tcpiphdr_next(t);
290 	    m = tcpiphdr_prev(t)->ti_mbuf;
291 	    remque(tcpiphdr2qlink(tcpiphdr_prev(t)));
292             mbuf_free(m);
293 	}
294 	/* It's static */
295 /*	if (tp->t_template)
296  *		(void) mbuf_free(MBUF_FROM(tp->t_template));
297  */
298 /*	free(tp, M_PCB);  */
299 	free(tp);
300 	so->so_tcpcb = 0;
301 	soisfdisconnected(so);
302 	/* clobber input socket cache if we're closing the cached connection */
303 	if (so == tcp_last_so)
304 		tcp_last_so = &tcb;
305 	socket_close(so->s);
306 	sbuf_free(&so->so_rcv);
307 	sbuf_free(&so->so_snd);
308 	sofree(so);
309 	tcpstat.tcps_closed++;
310 	return ((struct tcpcb *)0);
311 }
312 
313 void
tcp_drain()314 tcp_drain()
315 {
316 	/* XXX */
317 }
318 
319 /*
320  * When a source quench is received, close congestion window
321  * to one segment.  We will gradually open it again as we proceed.
322  */
323 
324 #ifdef notdef
325 
326 void
tcp_quench(i,errno)327 tcp_quench(i, errno)
328 
329 	int errno;
330 {
331 	struct tcpcb *tp = intotcpcb(inp);
332 
333 	if (tp)
334 		tp->snd_cwnd = tp->t_maxseg;
335 }
336 
337 #endif /* notdef */
338 
339 /*
340  * TCP protocol interface to socket abstraction.
341  */
342 
343 /*
344  * User issued close, and wish to trail through shutdown states:
345  * if never received SYN, just forget it.  If got a SYN from peer,
346  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
347  * If already got a FIN from peer, then almost done; go to LAST_ACK
348  * state.  In all other cases, have already sent FIN to peer (e.g.
349  * after PRU_SHUTDOWN), and just have to play tedious game waiting
350  * for peer to send FIN or not respond to keep-alives, etc.
351  * We can let the user exit from the close as soon as the FIN is acked.
352  */
353 void
tcp_sockclosed(tp)354 tcp_sockclosed(tp)
355 	struct tcpcb *tp;
356 {
357 
358 	DEBUG_CALL("tcp_sockclosed");
359 	DEBUG_ARG("tp = %lx", (long)tp);
360 
361 	switch (tp->t_state) {
362 
363 	case TCPS_CLOSED:
364 	case TCPS_LISTEN:
365 	case TCPS_SYN_SENT:
366 		tp->t_state = TCPS_CLOSED;
367 		tp = tcp_close(tp);
368 		break;
369 
370 	case TCPS_SYN_RECEIVED:
371 	case TCPS_ESTABLISHED:
372 		tp->t_state = TCPS_FIN_WAIT_1;
373 		break;
374 
375 	case TCPS_CLOSE_WAIT:
376 		tp->t_state = TCPS_LAST_ACK;
377 		break;
378 	}
379 /*	soisfdisconnecting(tp->t_socket); */
380 	if (tp && tp->t_state >= TCPS_FIN_WAIT_2)
381 		soisfdisconnected(tp->t_socket);
382 	if (tp)
383 		tcp_output(tp);
384 }
385 
386 static void
tcp_proxy_event(struct socket * so,int s,ProxyEvent event)387 tcp_proxy_event( struct socket*  so,
388                  int             s,
389                  ProxyEvent      event )
390 {
391     so->so_state &= ~SS_PROXIFIED;
392 
393     if (event == PROXY_EVENT_CONNECTED) {
394         so->s         = s;
395         so->so_state &= ~(SS_ISFCONNECTING);
396     }
397     else {
398         so->so_state = SS_NOFDREF;
399     }
400 
401     /* continue the connect */
402     tcp_input(NULL, sizeof(struct ip), so);
403 }
404 
405 /*
406  * Connect to a host on the Internet
407  * Called by tcp_input
408  * Only do a connect, the tcp fields will be set in tcp_input
409  * return 0 if there's a result of the connect,
410  * else return -1 means we're still connecting
411  * The return value is almost always -1 since the socket is
412  * nonblocking.  Connect returns after the SYN is sent, and does
413  * not wait for ACK+SYN.
414  */
tcp_fconnect(so)415 int tcp_fconnect(so)
416      struct socket *so;
417 {
418     int ret=0;
419     int try_proxy = 1;
420     SockAddress    sockaddr;
421     uint32_t       sock_ip;
422     uint16_t       sock_port;
423 
424     DEBUG_CALL("tcp_fconnect");
425     DEBUG_ARG("so = %lx", (long )so);
426 
427     sock_ip   = so->so_faddr_ip;
428     sock_port = so->so_faddr_port;
429 
430     if ((sock_ip & 0xffffff00) == special_addr_ip) {
431       /* It's an alias */
432       int  last_byte = sock_ip & 0xff;
433 
434       if (CTL_IS_DNS(last_byte))
435         sock_ip = dns_addr[last_byte - CTL_DNS];
436       else
437         sock_ip = loopback_addr_ip;
438       try_proxy = 0;
439     }
440 
441     sock_address_init_inet( &sockaddr, sock_ip, sock_port );
442 
443     DEBUG_MISC((dfd, " connect()ing, addr=%s, proxy=%d\n",
444                 sock_address_to_string(&sockaddr), try_proxy));
445 
446     if (try_proxy) {
447         if (!proxy_manager_add(&sockaddr, SOCKET_STREAM, (ProxyEventFunc) tcp_proxy_event, so)) {
448             soisfconnecting(so);
449             so->s         = -1;
450             so->so_state |= SS_PROXIFIED;
451             return 0;
452         }
453     }
454 
455     if ((ret=so->s=socket_create_inet(SOCKET_STREAM)) >= 0)
456     {
457         int  s = so->s;
458 
459         socket_set_nonblock(s);
460         socket_set_xreuseaddr(s);
461         socket_set_oobinline(s);
462 
463         /* We don't care what port we get */
464         socket_connect(s, &sockaddr);
465 
466         /*
467         * If it's not in progress, it failed, so we just return 0,
468         * without clearing SS_NOFDREF
469         */
470         soisfconnecting(so);
471   }
472 
473   return(ret);
474 }
475 
476 /*
477  * Accept the socket and connect to the local-host
478  *
479  * We have a problem. The correct thing to do would be
480  * to first connect to the local-host, and only if the
481  * connection is accepted, then do an accept() here.
482  * But, a) we need to know who's trying to connect
483  * to the socket to be able to SYN the local-host, and
484  * b) we are already connected to the foreign host by
485  * the time it gets to accept(), so... We simply accept
486  * here and SYN the local-host.
487  */
488 void
tcp_connect(inso)489 tcp_connect(inso)
490 	struct socket *inso;
491 {
492 	struct socket *so;
493 	SockAddress   addr;
494 	uint32_t      addr_ip;
495 	struct tcpcb *tp;
496 	int s;
497 
498 	DEBUG_CALL("tcp_connect");
499 	DEBUG_ARG("inso = %lx", (long)inso);
500 
501 	/*
502 	 * If it's an SS_ACCEPTONCE socket, no need to socreate()
503 	 * another socket, just use the accept() socket.
504 	 */
505 	if (inso->so_state & SS_FACCEPTONCE) {
506 		/* FACCEPTONCE already have a tcpcb */
507 		so = inso;
508 	} else {
509 		if ((so = socreate()) == NULL) {
510 			/* If it failed, get rid of the pending connection */
511 			socket_close(socket_accept(inso->s, NULL));
512 			return;
513 		}
514 		if (tcp_attach(so) < 0) {
515 			free(so); /* NOT sofree */
516 			return;
517 		}
518 		so->so_laddr_ip   = inso->so_laddr_ip;
519 		so->so_laddr_port = inso->so_laddr_port;
520 	}
521 
522 	(void) tcp_mss(sototcpcb(so), 0);
523 
524 	if ((s = socket_accept(inso->s, &addr)) < 0) {
525 		tcp_close(sototcpcb(so)); /* This will sofree() as well */
526 		return;
527 	}
528 	socket_set_nonblock(s);
529 	socket_set_xreuseaddr(s);
530 	socket_set_oobinline(s);
531 	socket_set_nodelay(s);
532 
533 	so->so_faddr_port = sock_address_get_port(&addr);
534 
535 	addr_ip = sock_address_get_ip(&addr);
536 
537 	so->so_faddr_ip = addr_ip;
538 	/* Translate connections from localhost to the real hostname */
539 	if (addr_ip == 0 || addr_ip == loopback_addr_ip)
540 	   so->so_faddr_ip = alias_addr_ip;
541 
542 	/* Close the accept() socket, set right state */
543 	if (inso->so_state & SS_FACCEPTONCE) {
544 		socket_close(so->s); /* If we only accept once, close the accept() socket */
545 		so->so_state = SS_NOFDREF; /* Don't select it yet, even though we have an FD */
546 					   /* if it's not FACCEPTONCE, it's already NOFDREF */
547 	}
548 	so->s = s;
549 
550 	so->so_iptos = tcp_tos(so);
551 	tp = sototcpcb(so);
552 
553 	tcp_template(tp);
554 
555 	/* Compute window scaling to request.  */
556 /*	while (tp->request_r_scale < TCP_MAX_WINSHIFT &&
557  *		(TCP_MAXWIN << tp->request_r_scale) < so->so_rcv.sb_hiwat)
558  *		tp->request_r_scale++;
559  */
560 
561 /*	soisconnecting(so); */ /* NOFDREF used instead */
562 	tcpstat.tcps_connattempt++;
563 
564 	tp->t_state = TCPS_SYN_SENT;
565 	tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
566 	tp->iss = tcp_iss;
567 	tcp_iss += TCP_ISSINCR/2;
568 	tcp_sendseqinit(tp);
569 	tcp_output(tp);
570 }
571 
572 /*
573  * Attach a TCPCB to a socket.
574  */
575 int
tcp_attach(so)576 tcp_attach(so)
577 	struct socket *so;
578 {
579 	if ((so->so_tcpcb = tcp_newtcpcb(so)) == NULL)
580 	   return -1;
581 
582 	insque(so, &tcb);
583 
584 	return 0;
585 }
586 
587 /*
588  * Set the socket's type of service field
589  */
590 struct tos_t tcptos[] = {
591 	  {0, 20, IPTOS_THROUGHPUT, 0},	/* ftp data */
592 	  {21, 21, IPTOS_LOWDELAY,  EMU_FTP},	/* ftp control */
593 	  {0, 23, IPTOS_LOWDELAY, 0},	/* telnet */
594 	  {0, 80, IPTOS_THROUGHPUT, 0},	/* WWW */
595 	  {0, 513, IPTOS_LOWDELAY, EMU_RLOGIN|EMU_NOCONNECT},	/* rlogin */
596 	  {0, 514, IPTOS_LOWDELAY, EMU_RSH|EMU_NOCONNECT},	/* shell */
597 	  {0, 544, IPTOS_LOWDELAY, EMU_KSH},		/* kshell */
598 	  {0, 543, IPTOS_LOWDELAY, 0},	/* klogin */
599 	  {0, 6667, IPTOS_THROUGHPUT, EMU_IRC},	/* IRC */
600 	  {0, 6668, IPTOS_THROUGHPUT, EMU_IRC},	/* IRC undernet */
601 	  {0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */
602 	  {0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */
603 	  {0, 0, 0, 0}
604 };
605 
606 
607 /*
608  * Return TOS according to the above table
609  */
610 u_int8_t
tcp_tos(so)611 tcp_tos(so)
612 	struct socket *so;
613 {
614 	int i = 0;
615 
616 	while(tcptos[i].tos) {
617 		if ((tcptos[i].fport && so->so_faddr_port == tcptos[i].fport) ||
618 		    (tcptos[i].lport && so->so_laddr_port == tcptos[i].lport)) {
619 			so->so_emu = tcptos[i].emu;
620 			return tcptos[i].tos;
621 		}
622 		i++;
623 	}
624 
625 	return 0;
626 }
627 
628 int do_echo = -1;
629 
630 /*
631  * Emulate programs that try and connect to us
632  * This includes ftp (the data connection is
633  * initiated by the server) and IRC (DCC CHAT and
634  * DCC SEND) for now
635  *
636  * NOTE: It's possible to crash SLiRP by sending it
637  * unstandard strings to emulate... if this is a problem,
638  * more checks are needed here
639  *
640  * XXX Assumes the whole command came in one packet
641  *
642  * XXX Some ftp clients will have their TOS set to
643  * LOWDELAY and so Nagel will kick in.  Because of this,
644  * we'll get the first letter, followed by the rest, so
645  * we simply scan for ORT instead of PORT...
646  * DCC doesn't have this problem because there's other stuff
647  * in the packet before the DCC command.
648  *
649  * Return 1 if the mbuf m is still valid and should be
650  * sbuf_append()ed
651  *
652  * NOTE: if you return 0 you MUST mbuf_free() the mbuf!
653  */
654 int
tcp_emu(so,m)655 tcp_emu(so, m)
656 	struct socket *so;
657 	MBuf m;
658 {
659 	u_int n1, n2, n3, n4, n5, n6;
660 	char buff[256];
661 	u_int32_t laddr;
662 	u_int lport;
663 	char *bptr;
664 
665 	DEBUG_CALL("tcp_emu");
666 	DEBUG_ARG("so = %lx", (long)so);
667 	DEBUG_ARG("m = %lx", (long)m);
668 
669 	switch(so->so_emu) {
670 		int x, i;
671 
672 	 case EMU_IDENT:
673 		/*
674 		 * Identification protocol as per rfc-1413
675 		 */
676 
677 		{
678 			struct socket *tmpso;
679 			SockAddress    addr;
680 			SBuf  so_rcv = &so->so_rcv;
681 
682 			memcpy(so_rcv->sb_wptr, m->m_data, m->m_len);
683 			so_rcv->sb_wptr += m->m_len;
684 			so_rcv->sb_rptr += m->m_len;
685 			m->m_data[m->m_len] = 0; /* NULL terminate */
686 			if (strchr(m->m_data, '\r') || strchr(m->m_data, '\n')) {
687 				if (sscanf(so_rcv->sb_data, "%d%*[ ,]%d", &n1, &n2) == 2) {
688 					/* n2 is the one on our host */
689 					for (tmpso = tcb.so_next; tmpso != &tcb; tmpso = tmpso->so_next) {
690 						if (tmpso->so_laddr_ip == so->so_laddr_ip &&
691 						    tmpso->so_laddr_port == n2 &&
692 						    tmpso->so_faddr_ip == so->so_faddr_ip &&
693 						    tmpso->so_faddr_port == n1) {
694 							if (socket_get_address(tmpso->s, &addr) == 0)
695 							   n2 = sock_address_get_port(&addr);
696 							break;
697 						}
698 					}
699 				}
700 				so_rcv->sb_cc = sprintf(so_rcv->sb_data, "%d,%d\r\n", n1, n2);
701 				so_rcv->sb_rptr = so_rcv->sb_data;
702 				so_rcv->sb_wptr = so_rcv->sb_data + so_rcv->sb_cc;
703 			}
704 			mbuf_free(m);
705 			return 0;
706 		}
707 
708         case EMU_FTP: /* ftp */
709 		*(m->m_data+m->m_len) = 0; /* NULL terminate for strstr */
710 		if ((bptr = (char *)strstr(m->m_data, "ORT")) != NULL) {
711 			/*
712 			 * Need to emulate the PORT command
713 			 */
714 			x = sscanf(bptr, "ORT %d,%d,%d,%d,%d,%d\r\n%256[^\177]",
715 				   &n1, &n2, &n3, &n4, &n5, &n6, buff);
716 			if (x < 6)
717 			   return 1;
718 
719 			laddr = (n1 << 24) | (n2 << 16) | (n3 << 8) | (n4);
720 			lport = (n5 << 8) | (n6);
721 
722 			if ((so = solisten(0, laddr, lport, SS_FACCEPTONCE)) == NULL)
723 			   return 1;
724 
725 			n6 = so->so_faddr_port;
726 
727 			n5 = (n6 >> 8) & 0xff;
728 			n6 &= 0xff;
729 
730 			laddr = so->so_faddr_ip;
731 
732 			n1 = ((laddr >> 24) & 0xff);
733 			n2 = ((laddr >> 16) & 0xff);
734 			n3 = ((laddr >> 8)  & 0xff);
735 			n4 =  (laddr & 0xff);
736 
737 			m->m_len = bptr - m->m_data; /* Adjust length */
738 			m->m_len += sprintf(bptr,"ORT %d,%d,%d,%d,%d,%d\r\n%s",
739 					    n1, n2, n3, n4, n5, n6, x==7?buff:"");
740 			return 1;
741 		} else if ((bptr = (char *)strstr(m->m_data, "27 Entering")) != NULL) {
742 			/*
743 			 * Need to emulate the PASV response
744 			 */
745 			x = sscanf(bptr, "27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%256[^\177]",
746 				   &n1, &n2, &n3, &n4, &n5, &n6, buff);
747 			if (x < 6)
748 			   return 1;
749 
750 			laddr = (n1 << 24) | (n2 << 16) | (n3 << 8) | (n4);
751 			lport = (n5 << 8) | (n6);
752 
753 			if ((so = solisten(0, laddr, lport, SS_FACCEPTONCE)) == NULL)
754 			   return 1;
755 
756 			n6 = so->so_faddr_port;
757 
758 			n5 = (n6 >> 8) & 0xff;
759 			n6 &= 0xff;
760 
761 			laddr = so->so_faddr_ip;
762 
763 			n1 = ((laddr >> 24) & 0xff);
764 			n2 = ((laddr >> 16) & 0xff);
765 			n3 = ((laddr >> 8)  & 0xff);
766 			n4 =  (laddr & 0xff);
767 
768 			m->m_len = bptr - m->m_data; /* Adjust length */
769 			m->m_len += sprintf(bptr,"27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%s",
770 					    n1, n2, n3, n4, n5, n6, x==7?buff:"");
771 
772 			return 1;
773 		}
774 
775 		return 1;
776 
777 	 case EMU_KSH:
778 		/*
779 		 * The kshell (Kerberos rsh) and shell services both pass
780 		 * a local port port number to carry signals to the server
781 		 * and stderr to the client.  It is passed at the beginning
782 		 * of the connection as a NUL-terminated decimal ASCII string.
783 		 */
784 		so->so_emu = 0;
785 		for (lport = 0, i = 0; i < m->m_len-1; ++i) {
786 			if (m->m_data[i] < '0' || m->m_data[i] > '9')
787 				return 1;       /* invalid number */
788 			lport *= 10;
789 			lport += m->m_data[i] - '0';
790 		}
791 		if (m->m_data[m->m_len-1] == '\0' && lport != 0 &&
792 		    (so = solisten(0, so->so_laddr_ip, lport, SS_FACCEPTONCE)) != NULL)
793 			m->m_len = sprintf(m->m_data, "%d", so->so_faddr_port)+1;
794 		return 1;
795 
796 	 case EMU_IRC:
797 		/*
798 		 * Need to emulate DCC CHAT, DCC SEND and DCC MOVE
799 		 */
800 		*(m->m_data+m->m_len) = 0; /* NULL terminate the string for strstr */
801 		if ((bptr = (char *)strstr(m->m_data, "DCC")) == NULL)
802 			 return 1;
803 
804 		/* The %256s is for the broken mIRC */
805 		if (sscanf(bptr, "DCC CHAT %256s %u %u", buff, &laddr, &lport) == 3) {
806 			if ((so = solisten(0, laddr, lport, SS_FACCEPTONCE)) == NULL)
807 				return 1;
808 
809 			m->m_len = bptr - m->m_data; /* Adjust length */
810 			m->m_len += sprintf(bptr, "DCC CHAT chat %lu %u%c\n",
811 			     (unsigned long) so->so_faddr_ip,
812 			     so->so_faddr_port, 1);
813 		} else if (sscanf(bptr, "DCC SEND %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) {
814 			if ((so = solisten(0, laddr, lport, SS_FACCEPTONCE)) == NULL)
815 				return 1;
816 
817 			m->m_len = bptr - m->m_data; /* Adjust length */
818 			m->m_len += sprintf(bptr, "DCC SEND %s %lu %u %u%c\n",
819 			      buff, (unsigned long)so->so_faddr_ip,
820 			      so->so_faddr_port, n1, 1);
821 		} else if (sscanf(bptr, "DCC MOVE %256s %u %u %u", buff, &laddr, &lport, &n1) == 4) {
822 			if ((so = solisten(0, laddr, lport, SS_FACCEPTONCE)) == NULL)
823 				return 1;
824 
825 			m->m_len = bptr - m->m_data; /* Adjust length */
826 			m->m_len += sprintf(bptr, "DCC MOVE %s %lu %u %u%c\n",
827 			      buff, (unsigned long)so->so_faddr_ip,
828 			      so->so_faddr_port, n1, 1);
829 		}
830 		return 1;
831 
832 	 case EMU_REALAUDIO:
833                 /*
834 		 * RealAudio emulation - JP. We must try to parse the incoming
835 		 * data and try to find the two characters that contain the
836 		 * port number. Then we redirect an udp port and replace the
837 		 * number with the real port we got.
838 		 *
839 		 * The 1.0 beta versions of the player are not supported
840 		 * any more.
841 		 *
842 		 * A typical packet for player version 1.0 (release version):
843 		 *
844 		 * 0000:50 4E 41 00 05
845 		 * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 .....�..g�l�c..P
846 		 * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH
847 		 * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v
848 		 * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB
849 		 *
850 		 * Now the port number 0x1BD7 is found at offset 0x04 of the
851 		 * Now the port number 0x1BD7 is found at offset 0x04 of the
852 		 * second packet. This time we received five bytes first and
853 		 * then the rest. You never know how many bytes you get.
854 		 *
855 		 * A typical packet for player version 2.0 (beta):
856 		 *
857 		 * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA...........�.
858 		 * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux�c..Win2.0.0
859 		 * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/
860 		 * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas
861 		 * 0040:65 2E 72 61 79 53 00 00 06 36 42                e.rayS...6B
862 		 *
863 		 * Port number 0x1BC1 is found at offset 0x0d.
864 		 *
865 		 * This is just a horrible switch statement. Variable ra tells
866 		 * us where we're going.
867 		 */
868 
869 		bptr = m->m_data;
870 		while (bptr < m->m_data + m->m_len) {
871 			u_short p;
872 			static int ra = 0;
873 			char ra_tbl[4];
874 
875 			ra_tbl[0] = 0x50;
876 			ra_tbl[1] = 0x4e;
877 			ra_tbl[2] = 0x41;
878 			ra_tbl[3] = 0;
879 
880 			switch (ra) {
881 			 case 0:
882 			 case 2:
883 			 case 3:
884 				if (*bptr++ != ra_tbl[ra]) {
885 					ra = 0;
886 					continue;
887 				}
888 				break;
889 
890 			 case 1:
891 				/*
892 				 * We may get 0x50 several times, ignore them
893 				 */
894 				if (*bptr == 0x50) {
895 					ra = 1;
896 					bptr++;
897 					continue;
898 				} else if (*bptr++ != ra_tbl[ra]) {
899 					ra = 0;
900 					continue;
901 				}
902 				break;
903 
904 			 case 4:
905 				/*
906 				 * skip version number
907 				 */
908 				bptr++;
909 				break;
910 
911 			 case 5:
912 				/*
913 				 * The difference between versions 1.0 and
914 				 * 2.0 is here. For future versions of
915 				 * the player this may need to be modified.
916 				 */
917 				if (*(bptr + 1) == 0x02)
918 				   bptr += 8;
919 				else
920 				   bptr += 4;
921 				break;
922 
923 			 case 6:
924 				/* This is the field containing the port
925 				 * number that RA-player is listening to.
926 				 */
927 				lport = (((u_char*)bptr)[0] << 8)
928 				+ ((u_char *)bptr)[1];
929 				if (lport < 6970)
930 				   lport += 256;   /* don't know why */
931 				if (lport < 6970 || lport > 7170)
932 				   return 1;       /* failed */
933 
934 				/* try to get udp port between 6970 - 7170 */
935 				for (p = 6970; p < 7071; p++) {
936 					if (udp_listen( p,
937 						        so->so_laddr_ip,
938 						        lport,
939 						        SS_FACCEPTONCE)) {
940 						break;
941 					}
942 				}
943 				if (p == 7071)
944 				   p = 0;
945 				*(u_char *)bptr++ = (p >> 8) & 0xff;
946 				*(u_char *)bptr++ = p & 0xff;
947 				ra = 0;
948 				return 1;   /* port redirected, we're done */
949 				break;
950 
951 			 default:
952 				ra = 0;
953 			}
954 			ra++;
955 		}
956 		return 1;
957 
958 	 default:
959 		/* Ooops, not emulated, won't call tcp_emu again */
960 		so->so_emu = 0;
961 		return 1;
962 	}
963 }
964 
965 /*
966  * Do misc. config of SLiRP while its running.
967  * Return 0 if this connections is to be closed, 1 otherwise,
968  * return 2 if this is a command-line connection
969  */
970 int
tcp_ctl(so)971 tcp_ctl(so)
972 	struct socket *so;
973 {
974 	SBuf  sb = &so->so_snd;
975 	int command;
976 #if 0
977  	struct ex_list *ex_ptr;
978 	int do_pty;
979 #endif
980         //	struct socket *tmpso;
981 
982 	DEBUG_CALL("tcp_ctl");
983 	DEBUG_ARG("so = %lx", (long )so);
984 
985 #if 0
986 	/*
987 	 * Check if they're authorised
988 	 */
989 	if (ctl_addr_ip && (ctl_addr_ip == -1 || (so->so_laddr_ip != ctl_addr_ip))) {
990 		sb->sb_cc = sprintf(sb->sb_wptr,"Error: Permission denied.\r\n");
991 		sb->sb_wptr += sb->sb_cc;
992 		return 0;
993 	}
994 #endif
995 	command = (so->so_faddr_ip & 0xff);
996 
997 	switch(command) {
998 	default:
999 		/*
1000 		 * Nothing bound..
1001 		 */
1002 		/* tcp_fconnect(so); */
1003 
1004 	case CTL_ALIAS:
1005 	  sb->sb_cc = sprintf(sb->sb_wptr,
1006 			      "Error: No application configured.\r\n");
1007 	  sb->sb_wptr += sb->sb_cc;
1008 	  return(0);
1009 	}
1010 }
1011