tests: test-announce-self: fix memory leak
[qemu/ar7.git] / slirp / src / slirp.c
blob18af670a0afecdaeacf0f5f724bb445d6a9301b2
1 /*
2 * libslirp glue
4 * Copyright (c) 2004-2008 Fabrice Bellard
6 * Permission is hereby granted, free of charge, to any person obtaining a copy
7 * of this software and associated documentation files (the "Software"), to deal
8 * in the Software without restriction, including without limitation the rights
9 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 * copies of the Software, and to permit persons to whom the Software is
11 * furnished to do so, subject to the following conditions:
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 * THE SOFTWARE.
24 #include "slirp.h"
27 #ifndef _WIN32
28 #include <net/if.h>
29 #endif
31 int slirp_debug;
33 /* Define to 1 if you want KEEPALIVE timers */
34 bool slirp_do_keepalive;
36 /* host loopback address */
37 struct in_addr loopback_addr;
38 /* host loopback network mask */
39 unsigned long loopback_mask;
41 /* emulated hosts use the MAC addr 52:55:IP:IP:IP:IP */
42 static const uint8_t special_ethaddr[ETH_ALEN] = {
43 0x52, 0x55, 0x00, 0x00, 0x00, 0x00
46 unsigned curtime;
48 static struct in_addr dns_addr;
49 #ifndef _WIN32
50 static struct in6_addr dns6_addr;
51 #endif
52 static unsigned dns_addr_time;
53 #ifndef _WIN32
54 static unsigned dns6_addr_time;
55 #endif
57 #define TIMEOUT_FAST 2 /* milliseconds */
58 #define TIMEOUT_SLOW 499 /* milliseconds */
59 /* for the aging of certain requests like DNS */
60 #define TIMEOUT_DEFAULT 1000 /* milliseconds */
62 #ifdef _WIN32
64 int get_dns_addr(struct in_addr *pdns_addr)
66 FIXED_INFO *FixedInfo=NULL;
67 ULONG BufLen;
68 DWORD ret;
69 IP_ADDR_STRING *pIPAddr;
70 struct in_addr tmp_addr;
72 if (dns_addr.s_addr != 0 && (curtime - dns_addr_time) < TIMEOUT_DEFAULT) {
73 *pdns_addr = dns_addr;
74 return 0;
77 FixedInfo = (FIXED_INFO *)GlobalAlloc(GPTR, sizeof(FIXED_INFO));
78 BufLen = sizeof(FIXED_INFO);
80 if (ERROR_BUFFER_OVERFLOW == GetNetworkParams(FixedInfo, &BufLen)) {
81 if (FixedInfo) {
82 GlobalFree(FixedInfo);
83 FixedInfo = NULL;
85 FixedInfo = GlobalAlloc(GPTR, BufLen);
88 if ((ret = GetNetworkParams(FixedInfo, &BufLen)) != ERROR_SUCCESS) {
89 printf("GetNetworkParams failed. ret = %08x\n", (unsigned)ret );
90 if (FixedInfo) {
91 GlobalFree(FixedInfo);
92 FixedInfo = NULL;
94 return -1;
97 pIPAddr = &(FixedInfo->DnsServerList);
98 inet_aton(pIPAddr->IpAddress.String, &tmp_addr);
99 *pdns_addr = tmp_addr;
100 dns_addr = tmp_addr;
101 dns_addr_time = curtime;
102 if (FixedInfo) {
103 GlobalFree(FixedInfo);
104 FixedInfo = NULL;
106 return 0;
109 int get_dns6_addr(struct in6_addr *pdns6_addr, uint32_t *scope_id)
111 return -1;
114 static void winsock_cleanup(void)
116 WSACleanup();
119 #else
121 static int get_dns_addr_cached(void *pdns_addr, void *cached_addr,
122 socklen_t addrlen,
123 struct stat *cached_stat, unsigned *cached_time)
125 struct stat old_stat;
126 if (curtime - *cached_time < TIMEOUT_DEFAULT) {
127 memcpy(pdns_addr, cached_addr, addrlen);
128 return 0;
130 old_stat = *cached_stat;
131 if (stat("/etc/resolv.conf", cached_stat) != 0) {
132 return -1;
134 if (cached_stat->st_dev == old_stat.st_dev
135 && cached_stat->st_ino == old_stat.st_ino
136 && cached_stat->st_size == old_stat.st_size
137 && cached_stat->st_mtime == old_stat.st_mtime) {
138 memcpy(pdns_addr, cached_addr, addrlen);
139 return 0;
141 return 1;
144 static int get_dns_addr_resolv_conf(int af, void *pdns_addr, void *cached_addr,
145 socklen_t addrlen, uint32_t *scope_id,
146 unsigned *cached_time)
148 char buff[512];
149 char buff2[257];
150 FILE *f;
151 int found = 0;
152 void *tmp_addr = alloca(addrlen);
153 unsigned if_index;
155 f = fopen("/etc/resolv.conf", "r");
156 if (!f)
157 return -1;
159 DEBUG_MISC("IP address of your DNS(s):");
160 while (fgets(buff, 512, f) != NULL) {
161 if (sscanf(buff, "nameserver%*[ \t]%256s", buff2) == 1) {
162 char *c = strchr(buff2, '%');
163 if (c) {
164 if_index = if_nametoindex(c + 1);
165 *c = '\0';
166 } else {
167 if_index = 0;
170 if (!inet_pton(af, buff2, tmp_addr)) {
171 continue;
173 /* If it's the first one, set it to dns_addr */
174 if (!found) {
175 memcpy(pdns_addr, tmp_addr, addrlen);
176 memcpy(cached_addr, tmp_addr, addrlen);
177 if (scope_id) {
178 *scope_id = if_index;
180 *cached_time = curtime;
183 if (++found > 3) {
184 DEBUG_MISC(" (more)");
185 break;
186 } else if (slirp_debug & DBG_MISC) {
187 char s[INET6_ADDRSTRLEN];
188 const char *res = inet_ntop(af, tmp_addr, s, sizeof(s));
189 if (!res) {
190 res = " (string conversion error)";
192 DEBUG_MISC(" %s", res);
196 fclose(f);
197 if (!found)
198 return -1;
199 return 0;
202 int get_dns_addr(struct in_addr *pdns_addr)
204 static struct stat dns_addr_stat;
206 if (dns_addr.s_addr != 0) {
207 int ret;
208 ret = get_dns_addr_cached(pdns_addr, &dns_addr, sizeof(dns_addr),
209 &dns_addr_stat, &dns_addr_time);
210 if (ret <= 0) {
211 return ret;
214 return get_dns_addr_resolv_conf(AF_INET, pdns_addr, &dns_addr,
215 sizeof(dns_addr), NULL, &dns_addr_time);
218 int get_dns6_addr(struct in6_addr *pdns6_addr, uint32_t *scope_id)
220 static struct stat dns6_addr_stat;
222 if (!in6_zero(&dns6_addr)) {
223 int ret;
224 ret = get_dns_addr_cached(pdns6_addr, &dns6_addr, sizeof(dns6_addr),
225 &dns6_addr_stat, &dns6_addr_time);
226 if (ret <= 0) {
227 return ret;
230 return get_dns_addr_resolv_conf(AF_INET6, pdns6_addr, &dns6_addr,
231 sizeof(dns6_addr),
232 scope_id, &dns6_addr_time);
235 #endif
237 static void slirp_init_once(void)
239 static int initialized;
240 const char *debug;
241 #ifdef _WIN32
242 WSADATA Data;
243 #endif
245 if (initialized) {
246 return;
248 initialized = 1;
250 #ifdef _WIN32
251 WSAStartup(MAKEWORD(2,0), &Data);
252 atexit(winsock_cleanup);
253 #endif
255 loopback_addr.s_addr = htonl(INADDR_LOOPBACK);
256 loopback_mask = htonl(IN_CLASSA_NET);
258 debug = g_getenv("SLIRP_DEBUG");
259 if (debug) {
260 const GDebugKey keys[] = {
261 { "call", DBG_CALL },
262 { "misc", DBG_MISC },
263 { "error", DBG_ERROR },
264 { "tftp", DBG_TFTP },
266 slirp_debug = g_parse_debug_string(debug, keys, G_N_ELEMENTS(keys));
272 Slirp *slirp_init(int restricted, bool in_enabled, struct in_addr vnetwork,
273 struct in_addr vnetmask, struct in_addr vhost,
274 bool in6_enabled,
275 struct in6_addr vprefix_addr6, uint8_t vprefix_len,
276 struct in6_addr vhost6, const char *vhostname,
277 const char *tftp_server_name,
278 const char *tftp_path, const char *bootfile,
279 struct in_addr vdhcp_start, struct in_addr vnameserver,
280 struct in6_addr vnameserver6, const char **vdnssearch,
281 const char *vdomainname,
282 const SlirpCb *callbacks,
283 void *opaque)
285 Slirp *slirp = g_malloc0(sizeof(Slirp));
287 slirp_init_once();
289 slirp->opaque = opaque;
290 slirp->cb = callbacks;
291 slirp->grand = g_rand_new();
292 slirp->restricted = restricted;
294 slirp->in_enabled = in_enabled;
295 slirp->in6_enabled = in6_enabled;
297 if_init(slirp);
298 ip_init(slirp);
299 ip6_init(slirp);
301 /* Initialise mbufs *after* setting the MTU */
302 m_init(slirp);
304 slirp->vnetwork_addr = vnetwork;
305 slirp->vnetwork_mask = vnetmask;
306 slirp->vhost_addr = vhost;
307 slirp->vprefix_addr6 = vprefix_addr6;
308 slirp->vprefix_len = vprefix_len;
309 slirp->vhost_addr6 = vhost6;
310 if (vhostname) {
311 slirp_pstrcpy(slirp->client_hostname, sizeof(slirp->client_hostname),
312 vhostname);
314 slirp->tftp_prefix = g_strdup(tftp_path);
315 slirp->bootp_filename = g_strdup(bootfile);
316 slirp->vdomainname = g_strdup(vdomainname);
317 slirp->vdhcp_startaddr = vdhcp_start;
318 slirp->vnameserver_addr = vnameserver;
319 slirp->vnameserver_addr6 = vnameserver6;
320 slirp->tftp_server_name = g_strdup(tftp_server_name);
322 if (vdnssearch) {
323 translate_dnssearch(slirp, vdnssearch);
326 return slirp;
329 void slirp_cleanup(Slirp *slirp)
331 struct gfwd_list *e, *next;
333 for (e = slirp->guestfwd_list; e; e = next) {
334 next = e->ex_next;
335 g_free(e->ex_exec);
336 g_free(e);
339 ip_cleanup(slirp);
340 ip6_cleanup(slirp);
341 m_cleanup(slirp);
343 g_rand_free(slirp->grand);
345 g_free(slirp->vdnssearch);
346 g_free(slirp->tftp_prefix);
347 g_free(slirp->bootp_filename);
348 g_free(slirp->vdomainname);
349 g_free(slirp);
352 #define CONN_CANFSEND(so) (((so)->so_state & (SS_FCANTSENDMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
353 #define CONN_CANFRCV(so) (((so)->so_state & (SS_FCANTRCVMORE|SS_ISFCONNECTED)) == SS_ISFCONNECTED)
355 static void slirp_update_timeout(Slirp *slirp, uint32_t *timeout)
357 uint32_t t;
359 if (*timeout <= TIMEOUT_FAST) {
360 return;
363 t = MIN(1000, *timeout);
365 /* If we have tcp timeout with slirp, then we will fill @timeout with
366 * more precise value.
368 if (slirp->time_fasttimo) {
369 *timeout = TIMEOUT_FAST;
370 return;
372 if (slirp->do_slowtimo) {
373 t = MIN(TIMEOUT_SLOW, t);
375 *timeout = t;
378 void slirp_pollfds_fill(Slirp *slirp, uint32_t *timeout,
379 SlirpAddPollCb add_poll, void *opaque)
381 struct socket *so, *so_next;
384 * First, TCP sockets
388 * *_slowtimo needs calling if there are IP fragments
389 * in the fragment queue, or there are TCP connections active
391 slirp->do_slowtimo = ((slirp->tcb.so_next != &slirp->tcb) ||
392 (&slirp->ipq.ip_link != slirp->ipq.ip_link.next));
394 for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so_next) {
395 int events = 0;
397 so_next = so->so_next;
399 so->pollfds_idx = -1;
402 * See if we need a tcp_fasttimo
404 if (slirp->time_fasttimo == 0 &&
405 so->so_tcpcb->t_flags & TF_DELACK) {
406 slirp->time_fasttimo = curtime; /* Flag when want a fasttimo */
410 * NOFDREF can include still connecting to local-host,
411 * newly socreated() sockets etc. Don't want to select these.
413 if (so->so_state & SS_NOFDREF || so->s == -1) {
414 continue;
418 * Set for reading sockets which are accepting
420 if (so->so_state & SS_FACCEPTCONN) {
421 so->pollfds_idx = add_poll(so->s,
422 SLIRP_POLL_IN | SLIRP_POLL_HUP | SLIRP_POLL_ERR, opaque);
423 continue;
427 * Set for writing sockets which are connecting
429 if (so->so_state & SS_ISFCONNECTING) {
430 so->pollfds_idx = add_poll(so->s,
431 SLIRP_POLL_OUT | SLIRP_POLL_ERR, opaque);
432 continue;
436 * Set for writing if we are connected, can send more, and
437 * we have something to send
439 if (CONN_CANFSEND(so) && so->so_rcv.sb_cc) {
440 events |= SLIRP_POLL_OUT | SLIRP_POLL_ERR;
444 * Set for reading (and urgent data) if we are connected, can
445 * receive more, and we have room for it XXX /2 ?
447 if (CONN_CANFRCV(so) &&
448 (so->so_snd.sb_cc < (so->so_snd.sb_datalen/2))) {
449 events |= SLIRP_POLL_IN | SLIRP_POLL_HUP |
450 SLIRP_POLL_ERR | SLIRP_POLL_PRI;
453 if (events) {
454 so->pollfds_idx = add_poll(so->s, events, opaque);
459 * UDP sockets
461 for (so = slirp->udb.so_next; so != &slirp->udb; so = so_next) {
462 so_next = so->so_next;
464 so->pollfds_idx = -1;
467 * See if it's timed out
469 if (so->so_expire) {
470 if (so->so_expire <= curtime) {
471 udp_detach(so);
472 continue;
473 } else {
474 slirp->do_slowtimo = true; /* Let socket expire */
479 * When UDP packets are received from over the
480 * link, they're sendto()'d straight away, so
481 * no need for setting for writing
482 * Limit the number of packets queued by this session
483 * to 4. Note that even though we try and limit this
484 * to 4 packets, the session could have more queued
485 * if the packets needed to be fragmented
486 * (XXX <= 4 ?)
488 if ((so->so_state & SS_ISFCONNECTED) && so->so_queued <= 4) {
489 so->pollfds_idx = add_poll(so->s,
490 SLIRP_POLL_IN | SLIRP_POLL_HUP | SLIRP_POLL_ERR, opaque);
495 * ICMP sockets
497 for (so = slirp->icmp.so_next; so != &slirp->icmp; so = so_next) {
498 so_next = so->so_next;
500 so->pollfds_idx = -1;
503 * See if it's timed out
505 if (so->so_expire) {
506 if (so->so_expire <= curtime) {
507 icmp_detach(so);
508 continue;
509 } else {
510 slirp->do_slowtimo = true; /* Let socket expire */
514 if (so->so_state & SS_ISFCONNECTED) {
515 so->pollfds_idx = add_poll(so->s,
516 SLIRP_POLL_IN | SLIRP_POLL_HUP | SLIRP_POLL_ERR, opaque);
520 slirp_update_timeout(slirp, timeout);
523 void slirp_pollfds_poll(Slirp *slirp, int select_error,
524 SlirpGetREventsCb get_revents, void *opaque)
526 struct socket *so, *so_next;
527 int ret;
529 curtime = slirp->cb->clock_get_ns(slirp->opaque) / SCALE_MS;
532 * See if anything has timed out
534 if (slirp->time_fasttimo &&
535 ((curtime - slirp->time_fasttimo) >= TIMEOUT_FAST)) {
536 tcp_fasttimo(slirp);
537 slirp->time_fasttimo = 0;
539 if (slirp->do_slowtimo &&
540 ((curtime - slirp->last_slowtimo) >= TIMEOUT_SLOW)) {
541 ip_slowtimo(slirp);
542 tcp_slowtimo(slirp);
543 slirp->last_slowtimo = curtime;
547 * Check sockets
549 if (!select_error) {
551 * Check TCP sockets
553 for (so = slirp->tcb.so_next; so != &slirp->tcb;
554 so = so_next) {
555 int revents;
557 so_next = so->so_next;
559 revents = 0;
560 if (so->pollfds_idx != -1) {
561 revents = get_revents(so->pollfds_idx, opaque);
564 if (so->so_state & SS_NOFDREF || so->s == -1) {
565 continue;
569 * Check for URG data
570 * This will soread as well, so no need to
571 * test for SLIRP_POLL_IN below if this succeeds
573 if (revents & SLIRP_POLL_PRI) {
574 ret = sorecvoob(so);
575 if (ret < 0) {
576 /* Socket error might have resulted in the socket being
577 * removed, do not try to do anything more with it. */
578 continue;
582 * Check sockets for reading
584 else if (revents &
585 (SLIRP_POLL_IN | SLIRP_POLL_HUP | SLIRP_POLL_ERR)) {
587 * Check for incoming connections
589 if (so->so_state & SS_FACCEPTCONN) {
590 tcp_connect(so);
591 continue;
592 } /* else */
593 ret = soread(so);
595 /* Output it if we read something */
596 if (ret > 0) {
597 tcp_output(sototcpcb(so));
599 if (ret < 0) {
600 /* Socket error might have resulted in the socket being
601 * removed, do not try to do anything more with it. */
602 continue;
607 * Check sockets for writing
609 if (!(so->so_state & SS_NOFDREF) &&
610 (revents & (SLIRP_POLL_OUT | SLIRP_POLL_ERR))) {
612 * Check for non-blocking, still-connecting sockets
614 if (so->so_state & SS_ISFCONNECTING) {
615 /* Connected */
616 so->so_state &= ~SS_ISFCONNECTING;
618 ret = send(so->s, (const void *) &ret, 0, 0);
619 if (ret < 0) {
620 /* XXXXX Must fix, zero bytes is a NOP */
621 if (errno == EAGAIN || errno == EWOULDBLOCK ||
622 errno == EINPROGRESS || errno == ENOTCONN) {
623 continue;
626 /* else failed */
627 so->so_state &= SS_PERSISTENT_MASK;
628 so->so_state |= SS_NOFDREF;
630 /* else so->so_state &= ~SS_ISFCONNECTING; */
633 * Continue tcp_input
635 tcp_input((struct mbuf *)NULL, sizeof(struct ip), so,
636 so->so_ffamily);
637 /* continue; */
638 } else {
639 ret = sowrite(so);
640 if (ret > 0) {
641 /* Call tcp_output in case we need to send a window
642 * update to the guest, otherwise it will be stuck
643 * until it sends a window probe. */
644 tcp_output(sototcpcb(so));
651 * Now UDP sockets.
652 * Incoming packets are sent straight away, they're not buffered.
653 * Incoming UDP data isn't buffered either.
655 for (so = slirp->udb.so_next; so != &slirp->udb;
656 so = so_next) {
657 int revents;
659 so_next = so->so_next;
661 revents = 0;
662 if (so->pollfds_idx != -1) {
663 revents = get_revents(so->pollfds_idx, opaque);
666 if (so->s != -1 &&
667 (revents & (SLIRP_POLL_IN | SLIRP_POLL_HUP | SLIRP_POLL_ERR))) {
668 sorecvfrom(so);
673 * Check incoming ICMP relies.
675 for (so = slirp->icmp.so_next; so != &slirp->icmp;
676 so = so_next) {
677 int revents;
679 so_next = so->so_next;
681 revents = 0;
682 if (so->pollfds_idx != -1) {
683 revents = get_revents(so->pollfds_idx, opaque);
686 if (so->s != -1 &&
687 (revents & (SLIRP_POLL_IN | SLIRP_POLL_HUP | SLIRP_POLL_ERR))) {
688 icmp_receive(so);
693 if_start(slirp);
696 static void arp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)
698 struct slirp_arphdr *ah = (struct slirp_arphdr *)(pkt + ETH_HLEN);
699 uint8_t arp_reply[MAX(ETH_HLEN + sizeof(struct slirp_arphdr), 64)];
700 struct ethhdr *reh = (struct ethhdr *)arp_reply;
701 struct slirp_arphdr *rah = (struct slirp_arphdr *)(arp_reply + ETH_HLEN);
702 int ar_op;
703 struct gfwd_list *ex_ptr;
705 if (!slirp->in_enabled) {
706 return;
709 ar_op = ntohs(ah->ar_op);
710 switch(ar_op) {
711 case ARPOP_REQUEST:
712 if (ah->ar_tip == ah->ar_sip) {
713 /* Gratuitous ARP */
714 arp_table_add(slirp, ah->ar_sip, ah->ar_sha);
715 return;
718 if ((ah->ar_tip & slirp->vnetwork_mask.s_addr) ==
719 slirp->vnetwork_addr.s_addr) {
720 if (ah->ar_tip == slirp->vnameserver_addr.s_addr ||
721 ah->ar_tip == slirp->vhost_addr.s_addr)
722 goto arp_ok;
723 /* TODO: IPv6 */
724 for (ex_ptr = slirp->guestfwd_list; ex_ptr; ex_ptr = ex_ptr->ex_next) {
725 if (ex_ptr->ex_addr.s_addr == ah->ar_tip)
726 goto arp_ok;
728 return;
729 arp_ok:
730 memset(arp_reply, 0, sizeof(arp_reply));
732 arp_table_add(slirp, ah->ar_sip, ah->ar_sha);
734 /* ARP request for alias/dns mac address */
735 memcpy(reh->h_dest, pkt + ETH_ALEN, ETH_ALEN);
736 memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);
737 memcpy(&reh->h_source[2], &ah->ar_tip, 4);
738 reh->h_proto = htons(ETH_P_ARP);
740 rah->ar_hrd = htons(1);
741 rah->ar_pro = htons(ETH_P_IP);
742 rah->ar_hln = ETH_ALEN;
743 rah->ar_pln = 4;
744 rah->ar_op = htons(ARPOP_REPLY);
745 memcpy(rah->ar_sha, reh->h_source, ETH_ALEN);
746 rah->ar_sip = ah->ar_tip;
747 memcpy(rah->ar_tha, ah->ar_sha, ETH_ALEN);
748 rah->ar_tip = ah->ar_sip;
749 slirp_send_packet_all(slirp, arp_reply, sizeof(arp_reply));
751 break;
752 case ARPOP_REPLY:
753 arp_table_add(slirp, ah->ar_sip, ah->ar_sha);
754 break;
755 default:
756 break;
760 void slirp_input(Slirp *slirp, const uint8_t *pkt, int pkt_len)
762 struct mbuf *m;
763 int proto;
765 if (pkt_len < ETH_HLEN)
766 return;
768 proto = (((uint16_t) pkt[12]) << 8) + pkt[13];
769 switch(proto) {
770 case ETH_P_ARP:
771 arp_input(slirp, pkt, pkt_len);
772 break;
773 case ETH_P_IP:
774 case ETH_P_IPV6:
775 m = m_get(slirp);
776 if (!m)
777 return;
778 /* Note: we add 2 to align the IP header on 4 bytes,
779 * and add the margin for the tcpiphdr overhead */
780 if (M_FREEROOM(m) < pkt_len + TCPIPHDR_DELTA + 2) {
781 m_inc(m, pkt_len + TCPIPHDR_DELTA + 2);
783 m->m_len = pkt_len + TCPIPHDR_DELTA + 2;
784 memcpy(m->m_data + TCPIPHDR_DELTA + 2, pkt, pkt_len);
786 m->m_data += TCPIPHDR_DELTA + 2 + ETH_HLEN;
787 m->m_len -= TCPIPHDR_DELTA + 2 + ETH_HLEN;
789 if (proto == ETH_P_IP) {
790 ip_input(m);
791 } else if (proto == ETH_P_IPV6) {
792 ip6_input(m);
794 break;
796 case ETH_P_NCSI:
797 ncsi_input(slirp, pkt, pkt_len);
798 break;
800 default:
801 break;
805 /* Prepare the IPv4 packet to be sent to the ethernet device. Returns 1 if no
806 * packet should be sent, 0 if the packet must be re-queued, 2 if the packet
807 * is ready to go.
809 static int if_encap4(Slirp *slirp, struct mbuf *ifm, struct ethhdr *eh,
810 uint8_t ethaddr[ETH_ALEN])
812 const struct ip *iph = (const struct ip *)ifm->m_data;
814 if (iph->ip_dst.s_addr == 0) {
815 /* 0.0.0.0 can not be a destination address, something went wrong,
816 * avoid making it worse */
817 return 1;
819 if (!arp_table_search(slirp, iph->ip_dst.s_addr, ethaddr)) {
820 uint8_t arp_req[ETH_HLEN + sizeof(struct slirp_arphdr)];
821 struct ethhdr *reh = (struct ethhdr *)arp_req;
822 struct slirp_arphdr *rah = (struct slirp_arphdr *)(arp_req + ETH_HLEN);
824 if (!ifm->resolution_requested) {
825 /* If the client addr is not known, send an ARP request */
826 memset(reh->h_dest, 0xff, ETH_ALEN);
827 memcpy(reh->h_source, special_ethaddr, ETH_ALEN - 4);
828 memcpy(&reh->h_source[2], &slirp->vhost_addr, 4);
829 reh->h_proto = htons(ETH_P_ARP);
830 rah->ar_hrd = htons(1);
831 rah->ar_pro = htons(ETH_P_IP);
832 rah->ar_hln = ETH_ALEN;
833 rah->ar_pln = 4;
834 rah->ar_op = htons(ARPOP_REQUEST);
836 /* source hw addr */
837 memcpy(rah->ar_sha, special_ethaddr, ETH_ALEN - 4);
838 memcpy(&rah->ar_sha[2], &slirp->vhost_addr, 4);
840 /* source IP */
841 rah->ar_sip = slirp->vhost_addr.s_addr;
843 /* target hw addr (none) */
844 memset(rah->ar_tha, 0, ETH_ALEN);
846 /* target IP */
847 rah->ar_tip = iph->ip_dst.s_addr;
848 slirp->client_ipaddr = iph->ip_dst;
849 slirp_send_packet_all(slirp, arp_req, sizeof(arp_req));
850 ifm->resolution_requested = true;
852 /* Expire request and drop outgoing packet after 1 second */
853 ifm->expiration_date =
854 slirp->cb->clock_get_ns(slirp->opaque) + 1000000000ULL;
856 return 0;
857 } else {
858 memcpy(eh->h_source, special_ethaddr, ETH_ALEN - 4);
859 /* XXX: not correct */
860 memcpy(&eh->h_source[2], &slirp->vhost_addr, 4);
861 eh->h_proto = htons(ETH_P_IP);
863 /* Send this */
864 return 2;
868 /* Prepare the IPv6 packet to be sent to the ethernet device. Returns 1 if no
869 * packet should be sent, 0 if the packet must be re-queued, 2 if the packet
870 * is ready to go.
872 static int if_encap6(Slirp *slirp, struct mbuf *ifm, struct ethhdr *eh,
873 uint8_t ethaddr[ETH_ALEN])
875 const struct ip6 *ip6h = mtod(ifm, const struct ip6 *);
876 if (!ndp_table_search(slirp, ip6h->ip_dst, ethaddr)) {
877 if (!ifm->resolution_requested) {
878 ndp_send_ns(slirp, ip6h->ip_dst);
879 ifm->resolution_requested = true;
880 ifm->expiration_date = slirp->cb->clock_get_ns(slirp->opaque) + 1000000000ULL;
882 return 0;
883 } else {
884 eh->h_proto = htons(ETH_P_IPV6);
885 in6_compute_ethaddr(ip6h->ip_src, eh->h_source);
887 /* Send this */
888 return 2;
892 /* Output the IP packet to the ethernet device. Returns 0 if the packet must be
893 * re-queued.
895 int if_encap(Slirp *slirp, struct mbuf *ifm)
897 uint8_t buf[1600];
898 struct ethhdr *eh = (struct ethhdr *)buf;
899 uint8_t ethaddr[ETH_ALEN];
900 const struct ip *iph = (const struct ip *)ifm->m_data;
901 int ret;
903 if (ifm->m_len + ETH_HLEN > sizeof(buf)) {
904 return 1;
907 switch (iph->ip_v) {
908 case IPVERSION:
909 ret = if_encap4(slirp, ifm, eh, ethaddr);
910 if (ret < 2) {
911 return ret;
913 break;
915 case IP6VERSION:
916 ret = if_encap6(slirp, ifm, eh, ethaddr);
917 if (ret < 2) {
918 return ret;
920 break;
922 default:
923 g_assert_not_reached();
924 break;
927 memcpy(eh->h_dest, ethaddr, ETH_ALEN);
928 DEBUG_ARG("src = %02x:%02x:%02x:%02x:%02x:%02x",
929 eh->h_source[0], eh->h_source[1], eh->h_source[2],
930 eh->h_source[3], eh->h_source[4], eh->h_source[5]);
931 DEBUG_ARG("dst = %02x:%02x:%02x:%02x:%02x:%02x",
932 eh->h_dest[0], eh->h_dest[1], eh->h_dest[2],
933 eh->h_dest[3], eh->h_dest[4], eh->h_dest[5]);
934 memcpy(buf + sizeof(struct ethhdr), ifm->m_data, ifm->m_len);
935 slirp_send_packet_all(slirp, buf, ifm->m_len + ETH_HLEN);
936 return 1;
939 /* Drop host forwarding rule, return 0 if found. */
940 /* TODO: IPv6 */
941 int slirp_remove_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,
942 int host_port)
944 struct socket *so;
945 struct socket *head = (is_udp ? &slirp->udb : &slirp->tcb);
946 struct sockaddr_in addr;
947 int port = htons(host_port);
948 socklen_t addr_len;
950 for (so = head->so_next; so != head; so = so->so_next) {
951 addr_len = sizeof(addr);
952 if ((so->so_state & SS_HOSTFWD) &&
953 getsockname(so->s, (struct sockaddr *)&addr, &addr_len) == 0 &&
954 addr.sin_addr.s_addr == host_addr.s_addr &&
955 addr.sin_port == port) {
956 so->slirp->cb->unregister_poll_fd(so->s, so->slirp->opaque);
957 closesocket(so->s);
958 sofree(so);
959 return 0;
963 return -1;
966 /* TODO: IPv6 */
967 int slirp_add_hostfwd(Slirp *slirp, int is_udp, struct in_addr host_addr,
968 int host_port, struct in_addr guest_addr, int guest_port)
970 if (!guest_addr.s_addr) {
971 guest_addr = slirp->vdhcp_startaddr;
973 if (is_udp) {
974 if (!udp_listen(slirp, host_addr.s_addr, htons(host_port),
975 guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))
976 return -1;
977 } else {
978 if (!tcp_listen(slirp, host_addr.s_addr, htons(host_port),
979 guest_addr.s_addr, htons(guest_port), SS_HOSTFWD))
980 return -1;
982 return 0;
985 /* TODO: IPv6 */
986 static bool
987 check_guestfwd(Slirp *slirp, struct in_addr *guest_addr, int guest_port)
989 struct gfwd_list *tmp_ptr;
991 if (!guest_addr->s_addr) {
992 guest_addr->s_addr = slirp->vnetwork_addr.s_addr |
993 (htonl(0x0204) & ~slirp->vnetwork_mask.s_addr);
995 if ((guest_addr->s_addr & slirp->vnetwork_mask.s_addr) !=
996 slirp->vnetwork_addr.s_addr ||
997 guest_addr->s_addr == slirp->vhost_addr.s_addr ||
998 guest_addr->s_addr == slirp->vnameserver_addr.s_addr) {
999 return false;
1002 /* check if the port is "bound" */
1003 for (tmp_ptr = slirp->guestfwd_list; tmp_ptr; tmp_ptr = tmp_ptr->ex_next) {
1004 if (guest_port == tmp_ptr->ex_fport &&
1005 guest_addr->s_addr == tmp_ptr->ex_addr.s_addr)
1006 return false;
1009 return true;
1012 int slirp_add_exec(Slirp *slirp, const char *cmdline,
1013 struct in_addr *guest_addr, int guest_port)
1015 if (!check_guestfwd(slirp, guest_addr, guest_port)) {
1016 return -1;
1019 add_exec(&slirp->guestfwd_list, cmdline, *guest_addr, htons(guest_port));
1020 return 0;
1023 int slirp_add_guestfwd(Slirp *slirp, SlirpWriteCb write_cb, void *opaque,
1024 struct in_addr *guest_addr, int guest_port)
1026 if (!check_guestfwd(slirp, guest_addr, guest_port)) {
1027 return -1;
1030 add_guestfwd(&slirp->guestfwd_list, write_cb, opaque,
1031 *guest_addr, htons(guest_port));
1032 return 0;
1035 ssize_t slirp_send(struct socket *so, const void *buf, size_t len, int flags)
1037 if (so->s == -1 && so->guestfwd) {
1038 /* XXX this blocks entire thread. Rewrite to use
1039 * qemu_chr_fe_write and background I/O callbacks */
1040 so->guestfwd->write_cb(buf, len, so->guestfwd->opaque);
1041 return len;
1044 if (so->s == -1) {
1046 * This should in theory not happen but it is hard to be
1047 * sure because some code paths will end up with so->s == -1
1048 * on a failure but don't dispose of the struct socket.
1049 * Check specifically, so we don't pass -1 to send().
1051 errno = EBADF;
1052 return -1;
1055 return send(so->s, buf, len, flags);
1058 struct socket *
1059 slirp_find_ctl_socket(Slirp *slirp, struct in_addr guest_addr, int guest_port)
1061 struct socket *so;
1063 /* TODO: IPv6 */
1064 for (so = slirp->tcb.so_next; so != &slirp->tcb; so = so->so_next) {
1065 if (so->so_faddr.s_addr == guest_addr.s_addr &&
1066 htons(so->so_fport) == guest_port) {
1067 return so;
1070 return NULL;
1073 size_t slirp_socket_can_recv(Slirp *slirp, struct in_addr guest_addr,
1074 int guest_port)
1076 struct iovec iov[2];
1077 struct socket *so;
1079 so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);
1081 if (!so || so->so_state & SS_NOFDREF) {
1082 return 0;
1085 if (!CONN_CANFRCV(so) || so->so_snd.sb_cc >= (so->so_snd.sb_datalen/2)) {
1086 return 0;
1089 return sopreprbuf(so, iov, NULL);
1092 void slirp_socket_recv(Slirp *slirp, struct in_addr guest_addr, int guest_port,
1093 const uint8_t *buf, int size)
1095 int ret;
1096 struct socket *so = slirp_find_ctl_socket(slirp, guest_addr, guest_port);
1098 if (!so)
1099 return;
1101 ret = soreadbuf(so, (const char *)buf, size);
1103 if (ret > 0)
1104 tcp_output(sototcpcb(so));
1107 void slirp_send_packet_all(Slirp *slirp, const void *buf, size_t len)
1109 ssize_t ret = slirp->cb->send_packet(buf, len, slirp->opaque);
1111 if (ret < 0) {
1112 g_critical("Failed to send packet, ret: %ld", (long) ret);
1113 } else if (ret < len) {
1114 DEBUG_ERROR("send_packet() didn't send all data: %ld < %lu",
1115 (long) ret, (unsigned long) len);