1 /* SPDX-License-Identifier: BSD-3-Clause */
2 /*
3  * Copyright (c) 1982, 1986, 1988, 1990, 1993
4  *	The Regents of the University of California.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Neither the name of the University nor the names of its contributors
15  *    may be used to endorse or promote products derived from this software
16  *    without specific prior written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *	@(#)tcp_subr.c	8.1 (Berkeley) 6/10/93
31  * tcp_subr.c,v 1.5 1994/10/08 22:39:58 phk Exp
32  */
33 
34 /*
35  * Changes and additions relating to SLiRP
36  * Copyright (c) 1995 Danny Gasparovski.
37  */
38 
39 #include "slirp.h"
40 
41 /* patchable/settable parameters for tcp */
42 /* Don't do rfc1323 performance enhancements */
43 #define TCP_DO_RFC1323 0
44 
45 /*
46  * Tcp initialization
47  */
tcp_init(Slirp * slirp)48 void tcp_init(Slirp *slirp)
49 {
50     slirp->tcp_iss = 1; /* wrong */
51     slirp->tcb.so_next = slirp->tcb.so_prev = &slirp->tcb;
52     slirp->tcp_last_so = &slirp->tcb;
53 }
54 
tcp_cleanup(Slirp * slirp)55 void tcp_cleanup(Slirp *slirp)
56 {
57     while (slirp->tcb.so_next != &slirp->tcb) {
58         tcp_close(sototcpcb(slirp->tcb.so_next));
59     }
60 }
61 
62 /*
63  * Create template to be used to send tcp packets on a connection.
64  * Call after host entry created, fills
65  * in a skeletal tcp/ip header, minimizing the amount of work
66  * necessary when the connection is used.
67  */
tcp_template(struct tcpcb * tp)68 void tcp_template(struct tcpcb *tp)
69 {
70     struct socket *so = tp->t_socket;
71     register struct tcpiphdr *n = &tp->t_template;
72 
73     n->ti_mbuf = NULL;
74     memset(&n->ti, 0, sizeof(n->ti));
75     n->ti_x0 = 0;
76     switch (so->so_ffamily) {
77     case AF_INET:
78         n->ti_pr = IPPROTO_TCP;
79         n->ti_len = htons(sizeof(struct tcphdr));
80         n->ti_src = so->so_faddr;
81         n->ti_dst = so->so_laddr;
82         n->ti_sport = so->so_fport;
83         n->ti_dport = so->so_lport;
84         break;
85 
86     case AF_INET6:
87         n->ti_nh6 = IPPROTO_TCP;
88         n->ti_len = htons(sizeof(struct tcphdr));
89         n->ti_src6 = so->so_faddr6;
90         n->ti_dst6 = so->so_laddr6;
91         n->ti_sport = so->so_fport6;
92         n->ti_dport = so->so_lport6;
93         break;
94 
95     default:
96         g_assert_not_reached();
97     }
98 
99     n->ti_seq = 0;
100     n->ti_ack = 0;
101     n->ti_x2 = 0;
102     n->ti_off = 5;
103     n->ti_flags = 0;
104     n->ti_win = 0;
105     n->ti_sum = 0;
106     n->ti_urp = 0;
107 }
108 
109 /*
110  * Send a single message to the TCP at address specified by
111  * the given TCP/IP header.  If m == 0, then we make a copy
112  * of the tcpiphdr at ti and send directly to the addressed host.
113  * This is used to force keep alive messages out using the TCP
114  * template for a connection tp->t_template.  If flags are given
115  * then we send a message back to the TCP which originated the
116  * segment ti, and discard the mbuf containing it and any other
117  * attached mbufs.
118  *
119  * In any case the ack and sequence number of the transmitted
120  * segment are as specified by the parameters.
121  */
tcp_respond(struct tcpcb * tp,struct tcpiphdr * ti,struct mbuf * m,tcp_seq ack,tcp_seq seq,int flags,unsigned short af)122 void tcp_respond(struct tcpcb *tp, struct tcpiphdr *ti, struct mbuf *m,
123                  tcp_seq ack, tcp_seq seq, int flags, unsigned short af)
124 {
125     register int tlen;
126     int win = 0;
127 
128     DEBUG_CALL("tcp_respond");
129     DEBUG_ARG("tp = %p", tp);
130     DEBUG_ARG("ti = %p", ti);
131     DEBUG_ARG("m = %p", m);
132     DEBUG_ARG("ack = %u", ack);
133     DEBUG_ARG("seq = %u", seq);
134     DEBUG_ARG("flags = %x", flags);
135 
136     if (tp)
137         win = sbspace(&tp->t_socket->so_rcv);
138     if (m == NULL) {
139         if (!tp || (m = m_get(tp->t_socket->slirp)) == NULL)
140             return;
141         tlen = 0;
142         m->m_data += IF_MAXLINKHDR;
143         *mtod(m, struct tcpiphdr *) = *ti;
144         ti = mtod(m, struct tcpiphdr *);
145         switch (af) {
146         case AF_INET:
147             ti->ti.ti_i4.ih_x1 = 0;
148             break;
149         case AF_INET6:
150             ti->ti.ti_i6.ih_x1 = 0;
151             break;
152         default:
153             g_assert_not_reached();
154         }
155         flags = TH_ACK;
156     } else {
157         /*
158          * ti points into m so the next line is just making
159          * the mbuf point to ti
160          */
161         m->m_data = (char *)ti;
162 
163         m->m_len = sizeof(struct tcpiphdr);
164         tlen = 0;
165 #define xchg(a, b, type) \
166     {                    \
167         type t;          \
168         t = a;           \
169         a = b;           \
170         b = t;           \
171     }
172         switch (af) {
173         case AF_INET:
174             xchg(ti->ti_dst.s_addr, ti->ti_src.s_addr, uint32_t);
175             xchg(ti->ti_dport, ti->ti_sport, uint16_t);
176             break;
177         case AF_INET6:
178             xchg(ti->ti_dst6, ti->ti_src6, struct in6_addr);
179             xchg(ti->ti_dport, ti->ti_sport, uint16_t);
180             break;
181         default:
182             g_assert_not_reached();
183         }
184 #undef xchg
185     }
186     ti->ti_len = htons((uint16_t)(sizeof(struct tcphdr) + tlen));
187     tlen += sizeof(struct tcpiphdr);
188     m->m_len = tlen;
189 
190     ti->ti_mbuf = NULL;
191     ti->ti_x0 = 0;
192     ti->ti_seq = htonl(seq);
193     ti->ti_ack = htonl(ack);
194     ti->ti_x2 = 0;
195     ti->ti_off = sizeof(struct tcphdr) >> 2;
196     ti->ti_flags = flags;
197     if (tp)
198         ti->ti_win = htons((uint16_t)(win >> tp->rcv_scale));
199     else
200         ti->ti_win = htons((uint16_t)win);
201     ti->ti_urp = 0;
202     ti->ti_sum = 0;
203     ti->ti_sum = cksum(m, tlen);
204 
205     struct tcpiphdr tcpiph_save = *(mtod(m, struct tcpiphdr *));
206     struct ip *ip;
207     struct ip6 *ip6;
208 
209     switch (af) {
210     case AF_INET:
211         m->m_data +=
212             sizeof(struct tcpiphdr) - sizeof(struct tcphdr) - sizeof(struct ip);
213         m->m_len -=
214             sizeof(struct tcpiphdr) - sizeof(struct tcphdr) - sizeof(struct ip);
215         ip = mtod(m, struct ip *);
216         ip->ip_len = m->m_len;
217         ip->ip_dst = tcpiph_save.ti_dst;
218         ip->ip_src = tcpiph_save.ti_src;
219         ip->ip_p = tcpiph_save.ti_pr;
220 
221         if (flags & TH_RST) {
222             ip->ip_ttl = MAXTTL;
223         } else {
224             ip->ip_ttl = IPDEFTTL;
225         }
226 
227         ip_output(NULL, m);
228         break;
229 
230     case AF_INET6:
231         m->m_data += sizeof(struct tcpiphdr) - sizeof(struct tcphdr) -
232                      sizeof(struct ip6);
233         m->m_len -= sizeof(struct tcpiphdr) - sizeof(struct tcphdr) -
234                     sizeof(struct ip6);
235         ip6 = mtod(m, struct ip6 *);
236         ip6->ip_pl = tcpiph_save.ti_len;
237         ip6->ip_dst = tcpiph_save.ti_dst6;
238         ip6->ip_src = tcpiph_save.ti_src6;
239         ip6->ip_nh = tcpiph_save.ti_nh6;
240 
241         ip6_output(NULL, m, 0);
242         break;
243 
244     default:
245         g_assert_not_reached();
246     }
247 }
248 
249 /*
250  * Create a new TCP control block, making an
251  * empty reassembly queue and hooking it to the argument
252  * protocol control block.
253  */
tcp_newtcpcb(struct socket * so)254 struct tcpcb *tcp_newtcpcb(struct socket *so)
255 {
256     register struct tcpcb *tp;
257 
258     tp = g_new0(struct tcpcb, 1);
259     tp->seg_next = tp->seg_prev = (struct tcpiphdr *)tp;
260     /*
261      * 40: length of IPv4 header (20) + TCP header (20)
262      * 60: length of IPv6 header (40) + TCP header (20)
263      */
264     tp->t_maxseg =
265         MIN(so->slirp->if_mtu - ((so->so_ffamily == AF_INET) ? 40 : 60),
266             TCP_MAXSEG_MAX);
267 
268     tp->t_flags = TCP_DO_RFC1323 ? (TF_REQ_SCALE | TF_REQ_TSTMP) : 0;
269     tp->t_socket = so;
270 
271     /*
272      * Init srtt to TCPTV_SRTTBASE (0), so we can tell that we have no
273      * rtt estimate.  Set rttvar so that srtt + 2 * rttvar gives
274      * reasonable initial retransmit time.
275      */
276     tp->t_srtt = TCPTV_SRTTBASE;
277     tp->t_rttvar = TCPTV_SRTTDFLT << 2;
278     tp->t_rttmin = TCPTV_MIN;
279 
280     TCPT_RANGESET(tp->t_rxtcur,
281                   ((TCPTV_SRTTBASE >> 2) + (TCPTV_SRTTDFLT << 2)) >> 1,
282                   TCPTV_MIN, TCPTV_REXMTMAX);
283 
284     tp->snd_cwnd = TCP_MAXWIN << TCP_MAX_WINSHIFT;
285     tp->snd_ssthresh = TCP_MAXWIN << TCP_MAX_WINSHIFT;
286     tp->t_state = TCPS_CLOSED;
287 
288     so->so_tcpcb = tp;
289 
290     return (tp);
291 }
292 
293 /*
294  * Drop a TCP connection, reporting
295  * the specified error.  If connection is synchronized,
296  * then send a RST to peer.
297  */
tcp_drop(struct tcpcb * tp,int err)298 struct tcpcb *tcp_drop(struct tcpcb *tp, int err)
299 {
300     DEBUG_CALL("tcp_drop");
301     DEBUG_ARG("tp = %p", tp);
302     DEBUG_ARG("errno = %d", errno);
303 
304     if (TCPS_HAVERCVDSYN(tp->t_state)) {
305         tp->t_state = TCPS_CLOSED;
306         tcp_output(tp);
307     }
308     return (tcp_close(tp));
309 }
310 
311 /*
312  * Close a TCP control block:
313  *	discard all space held by the tcp
314  *	discard internet protocol block
315  *	wake up any sleepers
316  */
tcp_close(struct tcpcb * tp)317 struct tcpcb *tcp_close(struct tcpcb *tp)
318 {
319     register struct tcpiphdr *t;
320     struct socket *so = tp->t_socket;
321     Slirp *slirp = so->slirp;
322     register struct mbuf *m;
323 
324     DEBUG_CALL("tcp_close");
325     DEBUG_ARG("tp = %p", tp);
326 
327     /* free the reassembly queue, if any */
328     t = tcpfrag_list_first(tp);
329     while (!tcpfrag_list_end(t, tp)) {
330         t = tcpiphdr_next(t);
331         m = tcpiphdr_prev(t)->ti_mbuf;
332         remque(tcpiphdr2qlink(tcpiphdr_prev(t)));
333         m_free(m);
334     }
335     g_free(tp);
336     so->so_tcpcb = NULL;
337     /* clobber input socket cache if we're closing the cached connection */
338     if (so == slirp->tcp_last_so)
339         slirp->tcp_last_so = &slirp->tcb;
340     so->slirp->cb->unregister_poll_fd(so->s, so->slirp->opaque);
341     closesocket(so->s);
342     sbfree(&so->so_rcv);
343     sbfree(&so->so_snd);
344     sofree(so);
345     return ((struct tcpcb *)0);
346 }
347 
348 /*
349  * TCP protocol interface to socket abstraction.
350  */
351 
352 /*
353  * User issued close, and wish to trail through shutdown states:
354  * if never received SYN, just forget it.  If got a SYN from peer,
355  * but haven't sent FIN, then go to FIN_WAIT_1 state to send peer a FIN.
356  * If already got a FIN from peer, then almost done; go to LAST_ACK
357  * state.  In all other cases, have already sent FIN to peer (e.g.
358  * after PRU_SHUTDOWN), and just have to play tedious game waiting
359  * for peer to send FIN or not respond to keep-alives, etc.
360  * We can let the user exit from the close as soon as the FIN is acked.
361  */
tcp_sockclosed(struct tcpcb * tp)362 void tcp_sockclosed(struct tcpcb *tp)
363 {
364     DEBUG_CALL("tcp_sockclosed");
365     DEBUG_ARG("tp = %p", tp);
366 
367     if (!tp) {
368         return;
369     }
370 
371     switch (tp->t_state) {
372     case TCPS_CLOSED:
373     case TCPS_LISTEN:
374     case TCPS_SYN_SENT:
375         tp->t_state = TCPS_CLOSED;
376         tcp_close(tp);
377         return;
378 
379     case TCPS_SYN_RECEIVED:
380     case TCPS_ESTABLISHED:
381         tp->t_state = TCPS_FIN_WAIT_1;
382         break;
383 
384     case TCPS_CLOSE_WAIT:
385         tp->t_state = TCPS_LAST_ACK;
386         break;
387     }
388     tcp_output(tp);
389 }
390 
391 /*
392  * Connect to a host on the Internet
393  * Called by tcp_input
394  * Only do a connect, the tcp fields will be set in tcp_input
395  * return 0 if there's a result of the connect,
396  * else return -1 means we're still connecting
397  * The return value is almost always -1 since the socket is
398  * nonblocking.  Connect returns after the SYN is sent, and does
399  * not wait for ACK+SYN.
400  */
tcp_fconnect(struct socket * so,unsigned short af)401 int tcp_fconnect(struct socket *so, unsigned short af)
402 {
403     int ret = 0;
404 
405     DEBUG_CALL("tcp_fconnect");
406     DEBUG_ARG("so = %p", so);
407 
408     ret = so->s = slirp_socket(af, SOCK_STREAM, 0);
409     if (ret >= 0) {
410         ret = slirp_bind_outbound(so, af);
411         if (ret < 0) {
412             // bind failed - close socket
413             closesocket(so->s);
414             so->s = -1;
415             return (ret);
416         }
417     }
418 
419     if (ret >= 0) {
420         int opt, s = so->s;
421         struct sockaddr_storage addr;
422 
423         slirp_set_nonblock(s);
424         so->slirp->cb->register_poll_fd(s, so->slirp->opaque);
425         slirp_socket_set_fast_reuse(s);
426         opt = 1;
427         setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(opt));
428         opt = 1;
429         setsockopt(s, IPPROTO_TCP, TCP_NODELAY, &opt, sizeof(opt));
430 
431         addr = so->fhost.ss;
432         DEBUG_CALL(" connect()ing");
433         if (sotranslate_out(so, &addr) < 0) {
434             return -1;
435         }
436 
437         /* We don't care what port we get */
438         ret = connect(s, (struct sockaddr *)&addr, sockaddr_size(&addr));
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  */
tcp_connect(struct socket * inso)462 void tcp_connect(struct socket *inso)
463 {
464     Slirp *slirp = inso->slirp;
465     struct socket *so;
466     struct sockaddr_storage addr;
467     socklen_t addrlen = sizeof(struct sockaddr_storage);
468     struct tcpcb *tp;
469     int s, opt, ret;
470     /* AF_INET6 addresses are bigger than AF_INET, so this is big enough. */
471     char addrstr[INET6_ADDRSTRLEN];
472     char portstr[6];
473 
474     DEBUG_CALL("tcp_connect");
475     DEBUG_ARG("inso = %p", inso);
476     ret = getnameinfo((const struct sockaddr *) &inso->lhost.ss, sizeof(inso->lhost.ss), addrstr, sizeof(addrstr), portstr, sizeof(portstr), NI_NUMERICHOST|NI_NUMERICSERV);
477     g_assert(ret == 0);
478     DEBUG_ARG("ip = [%s]:%s", addrstr, portstr);
479     DEBUG_ARG("so_state = 0x%x", inso->so_state);
480 
481     /* Perform lazy guest IP address resolution if needed. */
482     if (inso->so_state & SS_HOSTFWD) {
483         /*
484          * We can only reject the connection request by accepting it and
485          * then immediately closing it. Note that SS_FACCEPTONCE sockets can't
486          * get here.
487          */
488         if (soassign_guest_addr_if_needed(inso) < 0) {
489             /*
490              * Guest address isn't available yet. We could either try to defer
491              * completing this connection request until the guest address is
492              * available, or punt. It's easier to punt. Otherwise we need to
493              * complicate the mechanism by which we're called to defer calling
494              * us again until the guest address is available.
495              */
496             DEBUG_MISC(" guest address not available yet");
497             s = accept(inso->s, (struct sockaddr *)&addr, &addrlen);
498             if (s >= 0) {
499                 close(s);
500             }
501             return;
502         }
503     }
504 
505     /*
506      * If it's an SS_ACCEPTONCE socket, no need to socreate()
507      * another socket, just use the accept() socket.
508      */
509     if (inso->so_state & SS_FACCEPTONCE) {
510         /* FACCEPTONCE already have a tcpcb */
511         so = inso;
512     } else {
513         so = socreate(slirp);
514         tcp_attach(so);
515         so->lhost = inso->lhost;
516         so->so_ffamily = inso->so_ffamily;
517     }
518 
519     tcp_mss(sototcpcb(so), 0);
520 
521     s = accept(inso->s, (struct sockaddr *)&addr, &addrlen);
522     if (s < 0) {
523         tcp_close(sototcpcb(so)); /* This will sofree() as well */
524         return;
525     }
526     slirp_set_nonblock(s);
527     so->slirp->cb->register_poll_fd(s, so->slirp->opaque);
528     slirp_socket_set_fast_reuse(s);
529     opt = 1;
530     setsockopt(s, SOL_SOCKET, SO_OOBINLINE, &opt, sizeof(int));
531     slirp_socket_set_nodelay(s);
532 
533     so->fhost.ss = addr;
534     sotranslate_accept(so);
535 
536     /* Close the accept() socket, set right state */
537     if (inso->so_state & SS_FACCEPTONCE) {
538         /* If we only accept once, close the accept() socket */
539         so->slirp->cb->unregister_poll_fd(so->s, so->slirp->opaque);
540         closesocket(so->s);
541 
542         /* Don't select it yet, even though we have an FD */
543         /* if it's not FACCEPTONCE, it's already NOFDREF */
544         so->so_state = SS_NOFDREF;
545     }
546     so->s = s;
547     so->so_state |= SS_INCOMING;
548 
549     so->so_iptos = tcp_tos(so);
550     tp = sototcpcb(so);
551 
552     tcp_template(tp);
553 
554     tp->t_state = TCPS_SYN_SENT;
555     tp->t_timer[TCPT_KEEP] = TCPTV_KEEP_INIT;
556     tp->iss = slirp->tcp_iss;
557     slirp->tcp_iss += TCP_ISSINCR / 2;
558     tcp_sendseqinit(tp);
559     tcp_output(tp);
560 }
561 
562 /*
563  * Attach a TCPCB to a socket.
564  */
tcp_attach(struct socket * so)565 void tcp_attach(struct socket *so)
566 {
567     so->so_tcpcb = tcp_newtcpcb(so);
568     insque(so, &so->slirp->tcb);
569 }
570 
571 /*
572  * Set the socket's type of service field
573  */
574 static const struct tos_t tcptos[] = {
575     { 0, 20, IPTOS_THROUGHPUT, 0 }, /* ftp data */
576     { 21, 21, IPTOS_LOWDELAY, EMU_FTP }, /* ftp control */
577     { 0, 23, IPTOS_LOWDELAY, 0 }, /* telnet */
578     { 0, 80, IPTOS_THROUGHPUT, 0 }, /* WWW */
579     { 0, 513, IPTOS_LOWDELAY, EMU_RLOGIN | EMU_NOCONNECT }, /* rlogin */
580     { 0, 544, IPTOS_LOWDELAY, EMU_KSH }, /* kshell */
581     { 0, 543, IPTOS_LOWDELAY, 0 }, /* klogin */
582     { 0, 6667, IPTOS_THROUGHPUT, EMU_IRC }, /* IRC */
583     { 0, 6668, IPTOS_THROUGHPUT, EMU_IRC }, /* IRC undernet */
584     { 0, 7070, IPTOS_LOWDELAY, EMU_REALAUDIO }, /* RealAudio control */
585     { 0, 113, IPTOS_LOWDELAY, EMU_IDENT }, /* identd protocol */
586     { 0, 0, 0, 0 }
587 };
588 
589 /*
590  * Return TOS according to the above table
591  */
tcp_tos(struct socket * so)592 uint8_t tcp_tos(struct socket *so)
593 {
594     int i = 0;
595 
596     while (tcptos[i].tos) {
597         if ((tcptos[i].fport && (ntohs(so->so_fport) == tcptos[i].fport)) ||
598             (tcptos[i].lport && (ntohs(so->so_lport) == tcptos[i].lport))) {
599             if (so->slirp->enable_emu)
600                 so->so_emu = tcptos[i].emu;
601             return tcptos[i].tos;
602         }
603         i++;
604     }
605     return 0;
606 }
607 
608 /*
609  * Emulate programs that try and connect to us
610  * This includes ftp (the data connection is
611  * initiated by the server) and IRC (DCC CHAT and
612  * DCC SEND) for now
613  *
614  * NOTE: It's possible to crash SLiRP by sending it
615  * unstandard strings to emulate... if this is a problem,
616  * more checks are needed here
617  *
618  * XXX Assumes the whole command came in one packet
619  * XXX If there is more than one command in the packet, the others may
620  * be truncated.
621  * XXX If the command is too long, it may be truncated.
622  *
623  * XXX Some ftp clients will have their TOS set to
624  * LOWDELAY and so Nagel will kick in.  Because of this,
625  * we'll get the first letter, followed by the rest, so
626  * we simply scan for ORT instead of PORT...
627  * DCC doesn't have this problem because there's other stuff
628  * in the packet before the DCC command.
629  *
630  * Return 1 if the mbuf m is still valid and should be
631  * sbappend()ed
632  *
633  * NOTE: if you return 0 you MUST m_free() the mbuf!
634  */
tcp_emu(struct socket * so,struct mbuf * m)635 int tcp_emu(struct socket *so, struct mbuf *m)
636 {
637     Slirp *slirp = so->slirp;
638     unsigned n1, n2, n3, n4, n5, n6;
639     char buff[257];
640     uint32_t laddr;
641     unsigned lport;
642     char *bptr;
643 
644     DEBUG_CALL("tcp_emu");
645     DEBUG_ARG("so = %p", so);
646     DEBUG_ARG("m = %p", m);
647 
648     switch (so->so_emu) {
649         int x, i;
650 
651         /* TODO: IPv6 */
652     case EMU_IDENT:
653         /*
654          * Identification protocol as per rfc-1413
655          */
656 
657         {
658             struct socket *tmpso;
659             struct sockaddr_in addr;
660             socklen_t addrlen = sizeof(struct sockaddr_in);
661             char *eol = g_strstr_len(m->m_data, m->m_len, "\r\n");
662 
663             if (!eol) {
664                 return 1;
665             }
666 
667             *eol = '\0';
668             if (sscanf(m->m_data, "%u%*[ ,]%u", &n1, &n2) == 2) {
669                 HTONS(n1);
670                 HTONS(n2);
671                 /* n2 is the one on our host */
672                 for (tmpso = slirp->tcb.so_next; tmpso != &slirp->tcb;
673                      tmpso = tmpso->so_next) {
674                     if (tmpso->so_laddr.s_addr == so->so_laddr.s_addr &&
675                         tmpso->so_lport == n2 &&
676                         tmpso->so_faddr.s_addr == so->so_faddr.s_addr &&
677                         tmpso->so_fport == n1) {
678                         if (getsockname(tmpso->s, (struct sockaddr *)&addr,
679                                         &addrlen) == 0)
680                             n2 = addr.sin_port;
681                         break;
682                     }
683                 }
684                 NTOHS(n1);
685                 NTOHS(n2);
686                 m_inc(m, g_snprintf(NULL, 0, "%d,%d\r\n", n1, n2) + 1);
687                 m->m_len = slirp_fmt(m->m_data, M_ROOM(m), "%d,%d\r\n", n1, n2);
688             } else {
689                 *eol = '\r';
690             }
691 
692             return 1;
693         }
694 
695     case EMU_FTP: /* ftp */
696         m_inc(m, m->m_len + 1);
697         *(m->m_data + m->m_len) = 0; /* NUL terminate for strstr */
698         if ((bptr = (char *)strstr(m->m_data, "ORT")) != NULL) {
699             /*
700              * Need to emulate the PORT command
701              */
702             x = sscanf(bptr, "ORT %u,%u,%u,%u,%u,%u\r\n%256[^\177]", &n1, &n2,
703                        &n3, &n4, &n5, &n6, buff);
704             if (x < 6)
705                 return 1;
706 
707             laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));
708             lport = htons((n5 << 8) | (n6));
709 
710             if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport,
711                                  SS_FACCEPTONCE)) == NULL) {
712                 return 1;
713             }
714             n6 = ntohs(so->so_fport);
715 
716             n5 = (n6 >> 8) & 0xff;
717             n6 &= 0xff;
718 
719             laddr = ntohl(so->so_faddr.s_addr);
720 
721             n1 = ((laddr >> 24) & 0xff);
722             n2 = ((laddr >> 16) & 0xff);
723             n3 = ((laddr >> 8) & 0xff);
724             n4 = (laddr & 0xff);
725 
726             m->m_len = bptr - m->m_data; /* Adjust length */
727             m->m_len += slirp_fmt(bptr, M_FREEROOM(m),
728                                   "ORT %d,%d,%d,%d,%d,%d\r\n%s",
729                                   n1, n2, n3, n4, n5, n6, x == 7 ? buff : "");
730             return 1;
731         } else if ((bptr = (char *)strstr(m->m_data, "27 Entering")) != NULL) {
732             /*
733              * Need to emulate the PASV response
734              */
735             x = sscanf(
736                 bptr,
737                 "27 Entering Passive Mode (%u,%u,%u,%u,%u,%u)\r\n%256[^\177]",
738                 &n1, &n2, &n3, &n4, &n5, &n6, buff);
739             if (x < 6)
740                 return 1;
741 
742             laddr = htonl((n1 << 24) | (n2 << 16) | (n3 << 8) | (n4));
743             lport = htons((n5 << 8) | (n6));
744 
745             if ((so = tcp_listen(slirp, INADDR_ANY, 0, laddr, lport,
746                                  SS_FACCEPTONCE)) == NULL) {
747                 return 1;
748             }
749             n6 = ntohs(so->so_fport);
750 
751             n5 = (n6 >> 8) & 0xff;
752             n6 &= 0xff;
753 
754             laddr = ntohl(so->so_faddr.s_addr);
755 
756             n1 = ((laddr >> 24) & 0xff);
757             n2 = ((laddr >> 16) & 0xff);
758             n3 = ((laddr >> 8) & 0xff);
759             n4 = (laddr & 0xff);
760 
761             m->m_len = bptr - m->m_data; /* Adjust length */
762             m->m_len += slirp_fmt(bptr, M_FREEROOM(m),
763                                   "27 Entering Passive Mode (%d,%d,%d,%d,%d,%d)\r\n%s",
764                                   n1, n2, n3, n4, n5, n6, x == 7 ? buff : "");
765             return 1;
766         }
767 
768         return 1;
769 
770     case EMU_KSH:
771         /*
772          * The kshell (Kerberos rsh) and shell services both pass
773          * a local port port number to carry signals to the server
774          * and stderr to the client.  It is passed at the beginning
775          * of the connection as a NUL-terminated decimal ASCII string.
776          */
777         so->so_emu = 0;
778         for (lport = 0, i = 0; i < m->m_len - 1; ++i) {
779             if (m->m_data[i] < '0' || m->m_data[i] > '9')
780                 return 1; /* invalid number */
781             lport *= 10;
782             lport += m->m_data[i] - '0';
783         }
784         if (m->m_data[m->m_len - 1] == '\0' && lport != 0 &&
785             (so = tcp_listen(slirp, INADDR_ANY, 0, so->so_laddr.s_addr,
786                              htons(lport), SS_FACCEPTONCE)) != NULL)
787             m->m_len = slirp_fmt0(m->m_data, M_ROOM(m),
788                                   "%d", ntohs(so->so_fport));
789         return 1;
790 
791     case EMU_IRC:
792         /*
793          * Need to emulate DCC CHAT, DCC SEND and DCC MOVE
794          */
795         m_inc(m, m->m_len + 1);
796         *(m->m_data + m->m_len) = 0; /* NULL terminate the string for strstr */
797         if ((bptr = (char *)strstr(m->m_data, "DCC")) == NULL)
798             return 1;
799 
800         /* The %256s is for the broken mIRC */
801         if (sscanf(bptr, "DCC CHAT %256s %u %u", buff, &laddr, &lport) == 3) {
802             if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr),
803                                  htons(lport), SS_FACCEPTONCE)) == NULL) {
804                 return 1;
805             }
806             m->m_len = bptr - m->m_data; /* Adjust length */
807             m->m_len += slirp_fmt(bptr, M_FREEROOM(m),
808                                   "DCC CHAT chat %lu %u%c\n",
809                                   (unsigned long)ntohl(so->so_faddr.s_addr),
810                                   ntohs(so->so_fport), 1);
811         } else if (sscanf(bptr, "DCC SEND %256s %u %u %u", buff, &laddr, &lport,
812                           &n1) == 4) {
813             if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr),
814                                  htons(lport), SS_FACCEPTONCE)) == NULL) {
815                 return 1;
816             }
817             m->m_len = bptr - m->m_data; /* Adjust length */
818             m->m_len += slirp_fmt(bptr, M_FREEROOM(m),
819                                   "DCC SEND %s %lu %u %u%c\n", buff,
820                                   (unsigned long)ntohl(so->so_faddr.s_addr),
821                                   ntohs(so->so_fport), n1, 1);
822         } else if (sscanf(bptr, "DCC MOVE %256s %u %u %u", buff, &laddr, &lport,
823                           &n1) == 4) {
824             if ((so = tcp_listen(slirp, INADDR_ANY, 0, htonl(laddr),
825                                  htons(lport), SS_FACCEPTONCE)) == NULL) {
826                 return 1;
827             }
828             m->m_len = bptr - m->m_data; /* Adjust length */
829             m->m_len += slirp_fmt(bptr, M_FREEROOM(m),
830                                   "DCC MOVE %s %lu %u %u%c\n", buff,
831                                   (unsigned long)ntohl(so->so_faddr.s_addr),
832                                   ntohs(so->so_fport), n1, 1);
833         }
834         return 1;
835 
836     case EMU_REALAUDIO:
837         /*
838          * RealAudio emulation - JP. We must try to parse the incoming
839          * data and try to find the two characters that contain the
840          * port number. Then we redirect an udp port and replace the
841          * number with the real port we got.
842          *
843          * The 1.0 beta versions of the player are not supported
844          * any more.
845          *
846          * A typical packet for player version 1.0 (release version):
847          *
848          * 0000:50 4E 41 00 05
849          * 0000:00 01 00 02 1B D7 00 00 67 E6 6C DC 63 00 12 50 ........g.l.c..P
850          * 0010:4E 43 4C 49 45 4E 54 20 31 30 31 20 41 4C 50 48 NCLIENT 101 ALPH
851          * 0020:41 6C 00 00 52 00 17 72 61 66 69 6C 65 73 2F 76 Al..R..rafiles/v
852          * 0030:6F 61 2F 65 6E 67 6C 69 73 68 5F 2E 72 61 79 42 oa/english_.rayB
853          *
854          * Now the port number 0x1BD7 is found at offset 0x04 of the
855          * Now the port number 0x1BD7 is found at offset 0x04 of the
856          * second packet. This time we received five bytes first and
857          * then the rest. You never know how many bytes you get.
858          *
859          * A typical packet for player version 2.0 (beta):
860          *
861          * 0000:50 4E 41 00 06 00 02 00 00 00 01 00 02 1B C1 00 PNA.............
862          * 0010:00 67 75 78 F5 63 00 0A 57 69 6E 32 2E 30 2E 30 .gux.c..Win2.0.0
863          * 0020:2E 35 6C 00 00 52 00 1C 72 61 66 69 6C 65 73 2F .5l..R..rafiles/
864          * 0030:77 65 62 73 69 74 65 2F 32 30 72 65 6C 65 61 73 website/20releas
865          * 0040:65 2E 72 61 79 53 00 00 06 36 42                e.rayS...6B
866          *
867          * Port number 0x1BC1 is found at offset 0x0d.
868          *
869          * This is just a horrible switch statement. Variable ra tells
870          * us where we're going.
871          */
872 
873         bptr = m->m_data;
874         while (bptr < m->m_data + m->m_len) {
875             uint16_t p;
876             static int ra = 0;
877             char ra_tbl[4];
878 
879             ra_tbl[0] = 0x50;
880             ra_tbl[1] = 0x4e;
881             ra_tbl[2] = 0x41;
882             ra_tbl[3] = 0;
883 
884             switch (ra) {
885             case 0:
886             case 2:
887             case 3:
888                 if (*bptr++ != ra_tbl[ra]) {
889                     ra = 0;
890                     continue;
891                 }
892                 break;
893 
894             case 1:
895                 /*
896                  * We may get 0x50 several times, ignore them
897                  */
898                 if (*bptr == 0x50) {
899                     ra = 1;
900                     bptr++;
901                     continue;
902                 } else if (*bptr++ != ra_tbl[ra]) {
903                     ra = 0;
904                     continue;
905                 }
906                 break;
907 
908             case 4:
909                 /*
910                  * skip version number
911                  */
912                 bptr++;
913                 break;
914 
915             case 5:
916                 if (bptr == m->m_data + m->m_len - 1)
917                         return 1; /* We need two bytes */
918 
919                 /*
920                  * The difference between versions 1.0 and
921                  * 2.0 is here. For future versions of
922                  * the player this may need to be modified.
923                  */
924                 if (*(bptr + 1) == 0x02)
925                     bptr += 8;
926                 else
927                     bptr += 4;
928                 break;
929 
930             case 6:
931                 /* This is the field containing the port
932                  * number that RA-player is listening to.
933                  */
934 
935                 if (bptr == m->m_data + m->m_len - 1)
936                         return 1; /* We need two bytes */
937 
938                 lport = (((uint8_t *)bptr)[0] << 8) + ((uint8_t *)bptr)[1];
939                 if (lport < 6970)
940                     lport += 256; /* don't know why */
941                 if (lport < 6970 || lport > 7170)
942                     return 1; /* failed */
943 
944                 /* try to get udp port between 6970 - 7170 */
945                 for (p = 6970; p < 7071; p++) {
946                     if (udp_listen(slirp, INADDR_ANY, htons(p),
947                                    so->so_laddr.s_addr, htons(lport),
948                                    SS_FACCEPTONCE)) {
949                         break;
950                     }
951                 }
952                 if (p == 7071)
953                     p = 0;
954                 *(uint8_t *)bptr++ = (p >> 8) & 0xff;
955                 *(uint8_t *)bptr = p & 0xff;
956                 ra = 0;
957                 return 1; /* port redirected, we're done */
958                 break;
959 
960             default:
961                 ra = 0;
962             }
963             ra++;
964         }
965         return 1;
966 
967     default:
968         /* Ooops, not emulated, won't call tcp_emu again */
969         so->so_emu = 0;
970         return 1;
971     }
972 }
973 
974 /*
975  * Do misc. config of SLiRP while its running.
976  * Return 0 if this connections is to be closed, 1 otherwise,
977  * return 2 if this is a command-line connection
978  */
tcp_ctl(struct socket * so)979 int tcp_ctl(struct socket *so)
980 {
981     Slirp *slirp = so->slirp;
982     struct sbuf *sb = &so->so_snd;
983     struct gfwd_list *ex_ptr;
984 
985     DEBUG_CALL("tcp_ctl");
986     DEBUG_ARG("so = %p", so);
987 
988     /* TODO: IPv6 */
989     if (so->so_faddr.s_addr != slirp->vhost_addr.s_addr) {
990         /* Check if it's pty_exec */
991         for (ex_ptr = slirp->guestfwd_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
992             if (ex_ptr->ex_fport == so->so_fport &&
993                 so->so_faddr.s_addr == ex_ptr->ex_addr.s_addr) {
994                 if (ex_ptr->write_cb) {
995                     so->s = -1;
996                     so->guestfwd = ex_ptr;
997                     return 1;
998                 }
999                 DEBUG_MISC(" executing %s", ex_ptr->ex_exec);
1000                 if (ex_ptr->ex_unix)
1001                     return open_unix(so, ex_ptr->ex_unix);
1002                 else
1003                     return fork_exec(so, ex_ptr->ex_exec);
1004             }
1005         }
1006     }
1007     sb->sb_cc = slirp_fmt(sb->sb_wptr, sb->sb_datalen - (sb->sb_wptr - sb->sb_data),
1008                           "Error: No application configured.\r\n");
1009     sb->sb_wptr += sb->sb_cc;
1010     return 0;
1011 }
1012