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