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